use std::{
future::Future,
path::{Path, PathBuf},
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll, Waker},
};
use crate::app::WindowHandle;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DroppedFile {
name: Arc<str>,
size: Option<u64>,
path: Option<PathBuf>,
bytes: Option<FileBytes>,
}
#[derive(Clone, PartialEq, Eq)]
struct FileBytes(Arc<[u8]>);
impl std::fmt::Debug for FileBytes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} bytes", self.0.len())
}
}
impl DroppedFile {
pub fn from_path(path: impl Into<PathBuf>) -> Self {
let path = path.into();
#[cfg(target_arch = "wasm32")]
if let Some(bytes) = dropped_on_the_page(&path) {
let name = path
.file_name()
.map_or_else(String::new, |name| name.to_string_lossy().into_owned());
return Self::new(&name, None).with_bytes(bytes);
}
let size = std::fs::metadata(&path)
.ok()
.filter(|metadata| metadata.is_file())
.map(|metadata| metadata.len());
let name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| path.to_string_lossy().into_owned());
Self {
name: Arc::from(name),
size,
path: Some(path),
bytes: None,
}
}
pub fn new(name: &str, size: Option<u64>) -> Self {
Self {
name: Arc::from(name),
size,
path: None,
bytes: None,
}
}
pub fn with_bytes(mut self, bytes: impl Into<Arc<[u8]>>) -> Self {
let bytes = bytes.into();
self.size = Some(bytes.len() as u64);
self.bytes = Some(FileBytes(bytes));
self
}
pub fn read(&self) -> std::io::Result<Arc<[u8]>> {
if let Some(FileBytes(bytes)) = &self.bytes {
return Ok(bytes.clone());
}
match &self.path {
Some(path) => std::fs::read(path).map(Arc::from),
None => Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
"the file has no path and came with no bytes",
)),
}
}
pub fn with_size(mut self, size: Option<u64>) -> Self {
self.size = size;
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn size(&self) -> Option<u64> {
self.size
}
pub fn path(&self) -> Option<&Path> {
self.path.as_deref()
}
pub fn extension(&self) -> Option<String> {
let (stem, extension) = self.name.rsplit_once('.')?;
(!stem.is_empty() && !extension.is_empty()).then(|| extension.to_ascii_lowercase())
}
pub fn kind(&self) -> FileKind {
self
.extension()
.map(|extension| FileKind::of_extension(&extension))
.unwrap_or(FileKind::Other)
}
pub fn is_accepted(&self, accepted: &[impl AsRef<str>]) -> bool {
if accepted.is_empty() {
return true;
}
let extension = self.extension();
let kind = self.kind();
accepted.iter().any(|entry| {
let entry = entry.as_ref().trim().to_ascii_lowercase();
match entry.strip_suffix("/*") {
Some(kind_name) => kind.name() == kind_name,
None => extension.as_deref() == Some(entry.trim_start_matches('.')),
}
})
}
}
impl crate::app::component::DevtoolsInspectable for DroppedFile {
fn inspect(&self, formatter: &mut crate::app::component::DevtoolsFormatter<'_>) {
formatter.value_display(&self.name);
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FileKind {
Image,
Video,
Audio,
Text,
Archive,
#[default]
Other,
}
impl FileKind {
pub fn of_extension(extension: &str) -> Self {
[Self::Image, Self::Video, Self::Audio, Self::Text, Self::Archive]
.into_iter()
.find(|kind| kind.extensions().contains(&extension))
.unwrap_or(Self::Other)
}
pub fn extensions(self) -> &'static [&'static str] {
match self {
Self::Image => &[
"png", "jpg", "jpeg", "gif", "webp", "bmp", "svg", "tif", "tiff", "ico", "heic", "avif",
],
Self::Video => &["mp4", "mov", "webm", "mkv", "avi", "m4v"],
Self::Audio => &["mp3", "wav", "ogg", "flac", "m4a", "aac", "opus"],
Self::Text => &[
"txt", "md", "json", "csv", "tsv", "xml", "yaml", "yml", "toml", "pdf", "doc", "docx", "rtf", "odt", "xls",
"xlsx", "ods", "html", "htm", "log", "rs", "js", "ts", "py", "css",
],
Self::Archive => &["zip", "tar", "gz", "tgz", "7z", "rar", "xz", "bz2"],
Self::Other => &[],
}
}
pub fn named(name: &str) -> Option<Self> {
[Self::Image, Self::Video, Self::Audio, Self::Text, Self::Archive]
.into_iter()
.find(|kind| kind.name() == name)
}
pub fn name(self) -> &'static str {
match self {
Self::Image => "image",
Self::Video => "video",
Self::Audio => "audio",
Self::Text => "text",
Self::Archive => "archive",
Self::Other => "other",
}
}
}
pub fn format_size(bytes: u64) -> String {
crate::ui::current_locale().fields.size(bytes)
}
#[derive(Clone, Debug, Default)]
pub struct FileDialog {
title: String,
filters: Vec<(String, Vec<String>)>,
multiple: bool,
folder: Option<PathBuf>,
file_name: Option<String>,
asks: Asks,
parent: Option<crate::app::window::parent::ParentWindow>,
sources: Vec<FileSource>,
#[cfg_attr(not(target_os = "ios"), allow(dead_code))]
words: Option<SourceWords>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FileSource {
Files,
PhotoLibrary,
#[cfg(any(target_os = "ios", target_os = "android"))]
Camera,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SourceWords {
pub(crate) photo_library: Arc<str>,
pub(crate) take_photo: Arc<str>,
pub(crate) choose_file: Arc<str>,
pub(crate) cancel: Arc<str>,
pub(crate) switch_camera: Arc<str>,
pub(crate) done: Arc<str>,
pub(crate) remove: Arc<str>,
pub(crate) close: Arc<str>,
pub(crate) place_of: Arc<str>,
pub(crate) flash: Arc<str>,
pub(crate) flash_auto: Arc<str>,
pub(crate) flash_on: Arc<str>,
pub(crate) flash_off: Arc<str>,
pub(crate) zoom: Arc<str>,
}
impl SourceWords {
fn of(locale: &crate::core::Locale) -> Self {
Self {
photo_library: locale.fields.photo_library.clone(),
take_photo: locale.fields.take_photo.clone(),
choose_file: locale.fields.choose_file.clone(),
cancel: locale.common.cancel.clone(),
switch_camera: locale.fields.switch_camera.clone(),
done: locale.common.done.clone(),
remove: locale.common.remove.clone(),
close: locale.common.close.clone(),
place_of: locale.common.place_of.clone(),
flash: locale.fields.flash.clone(),
flash_auto: locale.fields.flash_auto.clone(),
flash_on: locale.fields.flash_on.clone(),
flash_off: locale.fields.flash_off.clone(),
zoom: locale.fields.zoom.clone(),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum Asks {
#[default]
Files,
Folder,
Save,
}
impl FileDialog {
pub fn new() -> Self {
Self {
words: Some(SourceWords::of(&crate::ui::current_locale())),
..Self::default()
}
}
pub fn sources(mut self, sources: impl IntoIterator<Item = FileSource>) -> Self {
self.sources = sources.into_iter().collect();
self
}
#[cfg_attr(not(any(target_os = "ios", target_os = "macos", windows)), allow(dead_code))]
pub(crate) fn offered(&self, has: &[FileSource]) -> Vec<FileSource> {
let wanted = if self.sources.is_empty() {
let extensions: Vec<&str> = self
.filters
.iter()
.flat_map(|(_, extensions)| extensions.iter())
.map(String::as_str)
.collect();
let takes = |kind: FileKind| {
extensions.is_empty()
|| extensions
.iter()
.any(|extension| FileKind::of_extension(extension) == kind)
};
let mut wanted = Vec::new();
if takes(FileKind::Image) || takes(FileKind::Video) {
wanted.push(FileSource::PhotoLibrary);
}
#[cfg(any(target_os = "ios", target_os = "android"))]
if takes(FileKind::Image) {
wanted.push(FileSource::Camera);
}
wanted.push(FileSource::Files);
wanted
} else {
self.sources.clone()
};
let mut offered: Vec<FileSource> = Vec::new();
for source in wanted {
if has.contains(&source) && !offered.contains(&source) {
offered.push(source);
}
}
if offered.is_empty() {
offered.push(FileSource::Files);
}
offered
}
#[cfg_attr(
not(any(target_os = "ios", all(target_os = "macos", feature = "file_dialog"))),
allow(dead_code)
)]
pub(crate) fn takes_media(&self) -> (bool, bool) {
let extensions: Vec<&str> = self
.filters
.iter()
.flat_map(|(_, extensions)| extensions.iter())
.map(String::as_str)
.collect();
let takes = |kind: FileKind| {
extensions.is_empty()
|| extensions
.iter()
.any(|extension| FileKind::of_extension(extension) == kind)
};
(takes(FileKind::Image), takes(FileKind::Video))
}
pub fn title(mut self, title: &str) -> Self {
self.title = title.to_owned();
self
}
pub fn filter(mut self, name: &str, extensions: &[&str]) -> Self {
self.filters.push((
name.to_owned(),
extensions
.iter()
.map(|extension| extension.trim_start_matches('.').to_owned())
.collect(),
));
self
}
pub fn multiple(mut self, multiple: bool) -> Self {
self.multiple = multiple;
self
}
pub fn folder(mut self, folder: impl Into<PathBuf>) -> Self {
self.folder = Some(folder.into());
self
}
pub(crate) fn folder_unless_given(mut self, folder: impl Into<PathBuf>) -> Self {
if self.folder.is_none() {
self.folder = Some(folder.into());
}
self
}
pub fn file_name(mut self, name: &str) -> Self {
self.file_name = Some(name.to_owned());
self
}
pub fn pick(mut self, window: &WindowHandle) -> impl Future<Output = Vec<DroppedFile>> + Send + 'static + use<> {
self.asks = Asks::Files;
self.ask(window)
}
pub fn pick_folder(
mut self,
window: &WindowHandle,
) -> impl Future<Output = Option<PathBuf>> + Send + 'static + use<> {
self.asks = Asks::Folder;
let asked = self.ask(window);
async move { path_of(asked.await) }
}
pub fn pick_save(mut self, window: &WindowHandle) -> impl Future<Output = Option<PathBuf>> + Send + 'static + use<> {
self.asks = Asks::Save;
let asked = self.ask(window);
async move { path_of(asked.await) }
}
pub fn save(self, window: &WindowHandle, bytes: Arc<[u8]>) -> impl Future<Output = bool> + Send + 'static + use<> {
#[cfg(target_arch = "wasm32")]
{
let _ = window;
let name = self.file_name.clone().unwrap_or_else(|| "download".to_owned());
let handed = download(&name, &bytes);
return std::future::ready(handed);
}
#[cfg(not(target_arch = "wasm32"))]
{
let chosen = self.pick_save(window);
async move {
match chosen.await {
Some(path) => std::fs::write(path, &bytes).is_ok(),
None => false,
}
}
}
}
fn ask(self, window: &WindowHandle) -> Picked {
let this = self.over(window);
#[cfg(feature = "mcp")]
if let Some(broker) = window.file_dialog_broker() {
use crate::mcp::{FileDialogOperation, FileDialogRequest};
let mut request = FileDialogRequest::new(match this.asks {
Asks::Files if this.multiple => FileDialogOperation::OpenFiles,
Asks::Files => FileDialogOperation::OpenFile,
Asks::Folder => FileDialogOperation::OpenFolder,
Asks::Save => FileDialogOperation::SaveFile,
});
request.title = this.title.clone();
request.filters = this.filters.clone();
request.suggested_name = this.file_name.clone().filter(|_| this.asks == Asks::Save);
match broker.request(window, request) {
Ok(Some(pending)) => {
return Picked::Broker(Box::pin(async move {
match pending.await {
Ok(selection) => selection.paths.into_iter().map(DroppedFile::from_path).collect(),
Err(_) => Vec::new(),
}
}));
}
Err(_) => return Picked::Ready(Some(Vec::new())),
Ok(None) => {}
}
}
Picked::Native(native::pick(this))
}
pub(crate) fn over(mut self, window: &WindowHandle) -> Self {
self.parent = if cfg!(windows) { window.parent() } else { None };
self
}
#[cfg(test)]
pub(crate) fn parent(&self) -> Option<crate::app::window::parent::ParentWindow> {
self.parent
}
pub fn pick_result(
self,
window: &WindowHandle,
) -> impl Future<Output = Result<Vec<DroppedFile>, ()>> + Send + 'static + use<> {
let picked = self.pick(window);
async move { Ok(picked.await) }
}
}
#[cfg(target_arch = "wasm32")]
thread_local! {
static DROPPED: std::cell::RefCell<Vec<(PathBuf, Arc<[u8]>)>> = const { std::cell::RefCell::new(Vec::new()) };
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn hold_dropped(files: Vec<(PathBuf, Arc<[u8]>)>) {
DROPPED.with(|dropped| *dropped.borrow_mut() = files);
}
#[cfg(target_arch = "wasm32")]
fn dropped_on_the_page(path: &Path) -> Option<Arc<[u8]>> {
DROPPED.with(|dropped| {
dropped
.borrow()
.iter()
.find(|(held, _)| held == path)
.map(|(_, bytes)| bytes.clone())
})
}
#[cfg(target_arch = "wasm32")]
fn download(name: &str, bytes: &[u8]) -> bool {
use wasm_bindgen::JsCast;
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
let Ok(blob) = web_sys::Blob::new_with_u8_array_sequence(&parts) else {
return false;
};
let Ok(address) = web_sys::Url::create_object_url_with_blob(&blob) else {
return false;
};
let handed = web_sys::window()
.and_then(|window| window.document())
.and_then(|document| document.create_element("a").ok())
.and_then(|link| link.dyn_into::<web_sys::HtmlAnchorElement>().ok())
.map(|link| {
link.set_href(&address);
link.set_download(name);
link.click();
})
.is_some();
let later = wasm_bindgen::closure::Closure::once_into_js(move || {
let _ = web_sys::Url::revoke_object_url(&address);
});
if let Some(window) = web_sys::window() {
let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(later.unchecked_ref(), 10_000);
}
handed
}
fn path_of(chosen: Vec<DroppedFile>) -> Option<PathBuf> {
chosen.into_iter().next().and_then(|file| file.path)
}
enum Picked {
#[cfg(feature = "mcp")]
Ready(Option<Vec<DroppedFile>>),
#[cfg(feature = "mcp")]
Broker(Pin<Box<dyn Future<Output = Vec<DroppedFile>> + Send>>),
Native(Answer),
}
impl Future for Picked {
type Output = Vec<DroppedFile>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.get_mut() {
#[cfg(feature = "mcp")]
Self::Ready(files) => Poll::Ready(files.take().unwrap_or_default()),
#[cfg(feature = "mcp")]
Self::Broker(future) => future.as_mut().poll(cx),
Self::Native(answer) => Pin::new(answer).poll(cx),
}
}
}
struct Answer(Arc<Mutex<AnswerSlot>>);
#[derive(Default)]
struct AnswerSlot {
files: Option<Vec<DroppedFile>>,
waker: Option<Waker>,
}
impl Answer {
fn new() -> (Self, Answering) {
let slot = Arc::new(Mutex::new(AnswerSlot::default()));
(Self(slot.clone()), Answering(slot))
}
#[cfg_attr(
any(target_os = "ios", all(feature = "file_dialog", not(target_arch = "wasm32"))),
allow(dead_code)
)]
fn ready(files: Vec<DroppedFile>) -> Self {
let (answer, answering) = Self::new();
answering.give(files);
answer
}
}
impl Future for Answer {
type Output = Vec<DroppedFile>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut slot = self.0.lock().unwrap();
match slot.files.take() {
Some(files) => Poll::Ready(files),
None => {
slot.waker = Some(cx.waker().clone());
Poll::Pending
}
}
}
}
struct Answering(Arc<Mutex<AnswerSlot>>);
impl Answering {
fn give(self, files: Vec<DroppedFile>) {
let waker = {
let mut slot = self.0.lock().unwrap();
slot.files = Some(files);
slot.waker.take()
};
if let Some(waker) = waker {
waker.wake();
}
}
}
#[cfg(all(feature = "file_dialog", not(target_os = "ios"), not(target_arch = "wasm32")))]
mod native {
use super::{Answer, Asks, DroppedFile, FileDialog};
pub(super) fn pick(dialog: FileDialog) -> Answer {
#[cfg(target_os = "macos")]
if dialog.asks == Asks::Files
&& dialog.offered(&[super::FileSource::PhotoLibrary, super::FileSource::Files])
== [super::FileSource::PhotoLibrary]
{
return super::photos::pick(dialog);
}
let (answer, answering) = Answer::new();
std::thread::spawn(move || {
let files = block_on(dialog_of(&dialog, dialog.multiple));
answering.give(files);
});
answer
}
async fn dialog_of(dialog: &FileDialog, multiple: bool) -> Vec<DroppedFile> {
let mut native = rfd::AsyncFileDialog::new();
if !dialog.title.is_empty() {
native = native.set_title(&dialog.title);
}
for (name, extensions) in &dialog.filters {
native = native.add_filter(name, extensions);
}
if let Some(folder) = &dialog.folder {
native = native.set_directory(folder);
} else if let Some(pictures) = pictures_for(dialog) {
native = native.set_directory(pictures);
}
if let Some(parent) = &dialog.parent {
native = native.set_parent(parent);
}
let handles = match dialog.asks {
Asks::Files if multiple => native.pick_files().await.unwrap_or_default(),
Asks::Files => native.pick_file().await.into_iter().collect(),
Asks::Folder => native.pick_folder().await.into_iter().collect(),
Asks::Save => {
if let Some(name) = &dialog.file_name {
native = native.set_file_name(name);
}
native.save_file().await.into_iter().collect()
}
};
handles
.into_iter()
.map(|handle| DroppedFile::from_path(handle.path()))
.collect()
}
fn pictures_for(dialog: &FileDialog) -> Option<std::path::PathBuf> {
if !cfg!(windows) || dialog.asks != Asks::Files {
return None;
}
let offered = dialog.offered(&[super::FileSource::PhotoLibrary, super::FileSource::Files]);
if !offered.contains(&super::FileSource::PhotoLibrary) {
return None;
}
let folder = std::path::PathBuf::from(std::env::var_os("USERPROFILE")?).join("Pictures");
folder.is_dir().then_some(folder)
}
fn block_on<F: std::future::Future>(future: F) -> F::Output {
use std::{
pin::pin,
sync::Arc,
task::{Context, Poll, Wake, Waker},
thread::Thread,
};
struct Unpark(Thread);
impl Wake for Unpark {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
let waker = Waker::from(Arc::new(Unpark(std::thread::current())));
let mut cx = Context::from_waker(&waker);
let mut future = pin!(future);
loop {
if let Poll::Ready(output) = future.as_mut().poll(&mut cx) {
return output;
}
std::thread::park();
}
}
}
#[cfg(all(feature = "file_dialog", target_arch = "wasm32"))]
mod native {
use super::{Answer, Asks, DroppedFile, FileDialog};
pub(super) fn pick(dialog: FileDialog) -> Answer {
if dialog.asks != Asks::Files {
return Answer::ready(Vec::new());
}
let (answer, answering) = Answer::new();
wasm_bindgen_futures::spawn_local(async move {
let mut native = rfd::AsyncFileDialog::new();
if !dialog.title.is_empty() {
native = native.set_title(&dialog.title);
}
for (name, extensions) in &dialog.filters {
native = native.add_filter(name, extensions);
}
let handles = if dialog.multiple {
native.pick_files().await.unwrap_or_default()
} else {
native.pick_file().await.into_iter().collect()
};
let mut files = Vec::with_capacity(handles.len());
for handle in handles {
let name = handle.file_name();
files.push(DroppedFile::new(&name, None).with_bytes(handle.read().await));
}
answering.give(files);
});
answer
}
}
#[cfg(target_os = "ios")]
#[path = "files_ios.rs"]
mod native;
#[cfg(target_os = "ios")]
#[path = "files_camera_ios.rs"]
mod camera;
#[cfg(any(target_os = "ios", all(target_os = "macos", feature = "file_dialog")))]
#[path = "files_photos.rs"]
mod photos;
#[cfg(any(target_os = "ios", all(target_os = "macos", feature = "file_dialog")))]
fn on_main(work: impl FnOnce(objc2::MainThreadMarker) + Send + 'static) {
use std::ffi::c_void;
unsafe extern "C" {
static _dispatch_main_q: c_void;
fn dispatch_async_f(queue: *const c_void, context: *mut c_void, work: extern "C" fn(*mut c_void));
}
type Work = Box<dyn FnOnce(objc2::MainThreadMarker) + Send>;
extern "C" fn run(context: *mut c_void) {
let work = unsafe { Box::from_raw(context.cast::<Work>()) };
if let Some(main) = objc2::MainThreadMarker::new() {
work(main);
}
}
let context = Box::into_raw(Box::new(Box::new(work) as Work)).cast::<c_void>();
unsafe { dispatch_async_f(&raw const _dispatch_main_q, context, run) };
}
#[cfg(all(not(feature = "file_dialog"), not(target_os = "ios")))]
mod native {
use super::{Answer, FileDialog};
pub(super) fn pick(_dialog: FileDialog) -> Answer {
static SAID: std::sync::Once = std::sync::Once::new();
SAID.call_once(|| {
tracing::warn!("lurq: FileDialog::pick needs the feature `file_dialog`; it gives nothing without it");
});
Answer::ready(Vec::new())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_sources_offered_are_what_the_filters_take_or_what_the_app_said_of_what_the_system_has() {
use FileSource::{Files, PhotoLibrary};
let has = [PhotoLibrary, Files];
let images = FileDialog::new().filter("Images", &["png", "heic"]);
assert_eq!(
images.offered(&has),
[PhotoLibrary, Files],
"pictures: the photo library too"
);
assert_eq!(
FileDialog::new().offered(&has),
[PhotoLibrary, Files],
"anything: the photo library too"
);
let documents = FileDialog::new().filter("PDF", &["pdf"]);
assert_eq!(documents.offered(&has), [Files], "no picture nor video: Files alone");
assert_eq!(
images.clone().sources([PhotoLibrary]).offered(&has),
[PhotoLibrary],
"the app's"
);
assert_eq!(
images.sources([PhotoLibrary]).offered(&[Files]),
[Files],
"what the system has not: Files"
);
let videos = FileDialog::new().filter("Videos", &["mov"]);
assert_eq!(videos.takes_media(), (false, true));
}
#[test]
fn a_drop_zones_dialog_shows_the_extensions_of_the_kinds_it_takes() {
let dialog = crate::ui::DropZone::new()
.accept(["image/*", ".PDF"])
.takes()
.dialog("Choose");
let [(name, extensions)] = dialog.filters.as_slice() else {
panic!("one filter: {:?}", dialog.filters);
};
assert_eq!(name, "image/*, .PDF");
assert!(
extensions.iter().any(|extension| extension == "heic"),
"the kind's extensions"
);
assert!(
extensions.iter().any(|extension| extension == "pdf"),
"an extension, in lower case without its dot"
);
assert!(!extensions.iter().any(|extension| extension == "mp4"));
let every = crate::ui::DropZone::new().accept(["model/*"]).takes().dialog("Choose");
assert!(every.filters.is_empty());
assert_eq!(FileKind::of_extension("heic"), FileKind::Image);
assert_eq!(FileKind::named("audio"), Some(FileKind::Audio));
}
#[test]
fn a_file_is_accepted_by_its_extension_or_its_kind_in_any_case() {
let photo = DroppedFile::new("Holiday.PNG", Some(2048));
assert_eq!(photo.extension().as_deref(), Some("png"));
assert_eq!(photo.kind(), FileKind::Image);
assert!(photo.is_accepted(&["png"]));
assert!(photo.is_accepted(&[".PNG"]));
assert!(photo.is_accepted(&["image/*"]));
assert!(!photo.is_accepted(&["text/*", "pdf"]));
assert!(photo.is_accepted(&[] as &[&str]), "nothing accepted takes every file");
let dotfile = DroppedFile::new(".gitignore", None);
assert_eq!(
dotfile.extension(),
None,
"a name that starts with its dot has no extension"
);
assert_eq!(dotfile.kind(), FileKind::Other);
}
#[test]
fn a_folder_or_a_place_to_save_is_the_path_of_the_one_thing_chosen() {
assert_eq!(path_of(Vec::new()), None, "cancelled");
assert_eq!(
path_of(vec![DroppedFile::new("notes.md", None)]),
None,
"a browser's file has no path"
);
let chosen = path_of(vec![DroppedFile::from_path("/projects/lurq")]);
assert_eq!(chosen.as_deref(), Some(Path::new("/projects/lurq")));
}
#[cfg(not(feature = "file_dialog"))]
#[test]
fn without_the_feature_a_folder_and_a_place_to_save_are_not_chosen() {
use std::{pin::pin, task::Waker};
let tree = crate::app::Tree::new();
let window = tree.window().handle();
let mut cx = Context::from_waker(Waker::noop());
let folder = pin!(FileDialog::new().title("Project folder").pick_folder(&window));
assert_eq!(folder.poll(&mut cx), Poll::Ready(None));
let save = pin!(FileDialog::new().file_name("notes.md").pick_save(&window));
assert_eq!(save.poll(&mut cx), Poll::Ready(None));
}
#[cfg(windows)]
#[test]
fn on_windows_the_dialog_is_given_its_window_as_its_parent() {
use raw_window_handle::{RawDisplayHandle, RawWindowHandle, Win32WindowHandle, WindowsDisplayHandle};
use crate::app::{Tree, window::parent::ParentWindow};
let tree = Tree::new();
let window = tree.window().handle();
assert_eq!(
FileDialog::new().over(&window).parent(),
None,
"a window the shell did not make has none"
);
let hwnd = Win32WindowHandle::new(std::num::NonZeroIsize::new(0x1234).unwrap());
let parent = ParentWindow::new(
RawWindowHandle::Win32(hwnd),
RawDisplayHandle::Windows(WindowsDisplayHandle::new()),
);
tree.window().set_parent(Some(parent));
let dialog = FileDialog::new().title("Add files").over(&window);
assert_eq!(
dialog.parent().map(|parent| parent.raw().0),
Some(RawWindowHandle::Win32(hwnd))
);
tree.window().set_parent(None);
assert_eq!(
FileDialog::new().over(&window).parent(),
None,
"the window gone, the dialog has none"
);
}
#[test]
fn a_size_is_said_in_the_unit_a_person_reads() {
assert_eq!(format_size(512), "512 B");
assert_eq!(format_size(4 * 1024), "4 KB");
assert_eq!(format_size(40 * 1024), "40 KB");
assert_eq!(format_size(1_258_291), "1.2 MB");
assert_eq!(format_size(3 * 1024 * 1024 * 1024), "3 GB");
}
#[test]
fn a_file_from_a_path_has_its_name_and_the_size_on_disk() {
let dir = std::env::temp_dir().join(format!("lurq-files-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("notes.txt");
std::fs::write(&path, b"twelve bytes").unwrap();
let file = DroppedFile::from_path(&path);
assert_eq!(file.name(), "notes.txt");
assert_eq!(file.size(), Some(12));
assert_eq!(file.path(), Some(path.as_path()));
assert_eq!(DroppedFile::from_path(dir.join("gone.txt")).size(), None);
assert_eq!(DroppedFile::from_path(&dir).size(), None, "a folder has no size");
std::fs::remove_dir_all(&dir).unwrap();
}
}