Skip to main content

nsh_core/
picker.rs

1//! The system's pickers (`nsh/picker`'s `Picker.pickImages` and
2//! `Picker.pickFiles`): the user picks photos or files of any type, which
3//! reach the app as `File`s whose bytes stay native.
4//!
5//! A pick is a [`Command::PickImages`](crate::Command::PickImages) on the
6//! root with a [`PickRequest`]; the platform shows its picker (iOS
7//! `PHPickerViewController`, Android's Photo Picker, an open panel on the
8//! desktops, `<input type=file>` on the web), prepares the picked images as
9//! the request says ([`PickRequest::needs_encoding`]: HEIC and other formats
10//! browsers do not show become JPEG, images larger than
11//! [`PickRequest::max_dimension`] are scaled down) and answers with the
12//! root's [`EventKind::Pick`](crate::EventKind::Pick), whose
13//! [`EventPayload::Picked`](crate::EventPayload::Picked) carries the files'
14//! bytes ([`PickedFile`]). A cancelled picker answers with no files.
15//!
16//! A pick of files is a [`Command::PickFiles`](crate::Command::PickFiles) with
17//! a [`FilePickRequest`]; the platform shows its picker for documents (iOS
18//! `UIDocumentPickerViewController`, Android's `ACTION_OPEN_DOCUMENT`, the
19//! open dialog on the desktops, `<input type=file>` on the web) and answers
20//! with the same event, each file's bytes as they are and its name kept. A
21//! file larger than the request reads ([`FilePickRequest::size_limit`]: the
22//! app's [`FilePickRequest::max_size`], at most [`MAX_PICKED_FILE_BYTES`])
23//! is not read into memory: it answers with its name and size only
24//! ([`PickedStatus::TooLarge`]), so the app can tell the user.
25//!
26//! An embedding app can show a picker of its own instead: a
27//! [`PickerBackend`] given to the core
28//! ([`Core::set_picker`](crate::Core::set_picker), `EngineConfig::picker`)
29//! answers every pick, and the platform's picker is never shown. Tests
30//! answer picks the same way.
31//!
32//! Modules that bring images of their own to JS (a camera in an nshm)
33//! return them as a [`PickedImage`], the shape `pickImages` resolves with.
34
35use std::{future::Future, pin::Pin, time::SystemTime};
36
37use crate::{
38    ImageData,
39    element::{JsHost, JsIn, JsOwned, JsValue, PropError, TsTypes},
40    file_dialog::{FileFilter, OpenDialog},
41    geometry::{DevicePixels, Percentage, Size},
42};
43
44/// At most this many files answer one pick, whatever the request or the
45/// platform says.
46pub const MAX_PICKED: u32 = 100;
47
48/// A file picked with [`FilePickRequest`] larger than this many bytes is not
49/// read, whatever the request says ([`PickedStatus::TooLarge`]): its bytes
50/// would all have to fit in memory.
51pub const MAX_PICKED_FILE_BYTES: u64 = 512 * 1024 * 1024;
52
53/// The JPEG quality NSH encodes with when the app gives none.
54pub const DEFAULT_QUALITY: Percentage = Percentage(0.9);
55
56/// What the app asked a pick for, checked: what the platform's picker
57/// shows and what it does with the picked images.
58#[derive(Debug, Clone, Copy, PartialEq)]
59#[non_exhaustive]
60pub struct PickRequest {
61    /// At most this many images (1 for a single pick), never more than
62    /// [`MAX_PICKED`].
63    pub limit: u32,
64    /// Images whose longer side is longer than this are scaled down to it
65    /// (and encoded again); `None` keeps their size.
66    pub max_dimension: Option<DevicePixels>,
67    /// The quality of the JPEGs NSH encodes, from 0 (smallest) to 1 (best);
68    /// `None`: [`DEFAULT_QUALITY`], and JPEGs that need no other change
69    /// stay as they are.
70    pub quality: Option<Percentage>,
71    /// Which formats the images come in.
72    pub format: PickFormat,
73}
74
75impl Default for PickRequest {
76    fn default() -> Self {
77        Self {
78            limit: 1,
79            max_dimension: None,
80            quality: None,
81            format: PickFormat::Compatible,
82        }
83    }
84}
85
86/// Which formats picked images come in.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
88pub enum PickFormat {
89    /// Formats every browser and server takes: JPEG, PNG, GIF and WebP
90    /// stay as they are, anything else (HEIC, HEIF, TIFF, RAW) becomes a
91    /// JPEG.
92    #[default]
93    Compatible,
94    /// The format the image is stored in (HEIC stays HEIC), unless it has
95    /// to be encoded again (scaled down, or a quality given).
96    Current,
97}
98
99/// What a platform does with one picked image.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum Encoding {
102    /// Its bytes as they are.
103    Keep,
104    /// Decoded (with its orientation applied), scaled to fit
105    /// [`PickRequest::max_dimension`] and encoded as a PNG: an image that
106    /// was a PNG.
107    Png,
108    /// Decoded (with its orientation applied), scaled to fit
109    /// [`PickRequest::max_dimension`] and encoded as a JPEG of the
110    /// request's quality.
111    Jpeg,
112}
113
114impl PickRequest {
115    /// A request for one image (`multiple: false`) or up to `limit` of them
116    /// (0: as many as [`MAX_PICKED`]).
117    pub fn new(multiple: bool, limit: u32) -> Self {
118        let limit = match (multiple, limit) {
119            (false, _) => 1,
120            (true, 0) => MAX_PICKED,
121            (true, n) => n.min(MAX_PICKED),
122        };
123        Self {
124            limit,
125            ..Self::default()
126        }
127    }
128
129    /// Whether the user may pick several.
130    pub fn multiple(&self) -> bool {
131        self.limit > 1
132    }
133
134    /// The quality NSH encodes JPEGs with.
135    pub fn jpeg_quality(&self) -> Percentage {
136        Percentage(self.quality.unwrap_or(DEFAULT_QUALITY).0.clamp(0.0, 1.0))
137    }
138
139    /// What to do with an image of type `mime` whose pixels are `size`
140    /// (with its orientation applied): keep it, or decode and encode it
141    /// again.
142    pub fn needs_encoding(&self, mime: &str, size: Size<DevicePixels>) -> Encoding {
143        let mime = mime.to_ascii_lowercase();
144        let png = mime == "image/png";
145        let longer = size.width.0.max(size.height.0);
146        let scale = self.max_dimension.is_some_and(|max| longer > max.0.max(1));
147        let foreign = !matches!(
148            mime.as_str(),
149            "image/jpeg" | "image/png" | "image/gif" | "image/webp"
150        );
151        let convert = self.format == PickFormat::Compatible && foreign;
152        let requality = self.quality.is_some() && mime == "image/jpeg";
153        match () {
154            _ if png && scale => Encoding::Png,
155            _ if scale || convert || requality => Encoding::Jpeg,
156            _ => Encoding::Keep,
157        }
158    }
159
160    /// The size an image of `size` pixels is scaled to: fitting
161    /// [`Self::max_dimension`], its aspect ratio kept.
162    pub fn scaled_size(&self, size: Size<DevicePixels>) -> Size<DevicePixels> {
163        let Some(max) = self.max_dimension else {
164            return size;
165        };
166        let (w, h) = (size.width.0.max(1), size.height.0.max(1));
167        let longer = w.max(h);
168        let max = max.0.max(1);
169        if longer <= max {
170            return size;
171        }
172        let fit = |side: i32| ((side as f64 * max as f64 / longer as f64).round() as i32).max(1);
173        Size::new(DevicePixels(fit(w)), DevicePixels(fit(h)))
174    }
175}
176
177/// What the app asked a pick of files for, checked: what the platform's
178/// picker shows.
179#[derive(Debug, Clone, PartialEq, Eq)]
180#[non_exhaustive]
181pub struct FilePickRequest {
182    /// At most this many files (1 for a single pick), never more than
183    /// [`MAX_PICKED`].
184    pub limit: u32,
185    /// The file types offered, the first chosen; none: any file. iOS,
186    /// Android and the web take one list of all their extensions. A filter
187    /// is what the picker offers, not a promise: a system's picker may let
188    /// other files through.
189    pub filters: Vec<FileFilter>,
190    /// The largest file read, in bytes: a larger one answers with its name
191    /// and size only ([`PickedStatus::TooLarge`]). `None`:
192    /// [`MAX_PICKED_FILE_BYTES`], which also caps a larger one.
193    pub max_size: Option<u64>,
194}
195
196impl Default for FilePickRequest {
197    fn default() -> Self {
198        Self::new(false, 0)
199    }
200}
201
202impl FilePickRequest {
203    /// A request for one file (`multiple: false`) or up to `limit` of them
204    /// (0: as many as [`MAX_PICKED`]), of any type.
205    pub fn new(multiple: bool, limit: u32) -> Self {
206        Self {
207            limit: PickRequest::new(multiple, limit).limit,
208            filters: Vec::new(),
209            max_size: None,
210        }
211    }
212
213    /// Reads files of at most `bytes` bytes; a larger one answers with its
214    /// name and size only ([`PickedStatus::TooLarge`]).
215    pub fn max_size(mut self, bytes: u64) -> Self {
216        self.max_size = Some(bytes);
217        self
218    }
219
220    /// The largest file read, in bytes: [`Self::max_size`], at most
221    /// [`MAX_PICKED_FILE_BYTES`].
222    pub fn size_limit(&self) -> u64 {
223        self.max_size
224            .map_or(MAX_PICKED_FILE_BYTES, |max| max.min(MAX_PICKED_FILE_BYTES))
225    }
226
227    /// Offers the file types of `filter`, after those given before.
228    pub fn filter(mut self, filter: FileFilter) -> Self {
229        self.filters.push(filter);
230        self
231    }
232
233    /// Whether the user may pick several.
234    pub fn multiple(&self) -> bool {
235        self.limit > 1
236    }
237
238    /// The open dialog that shows this request on a desktop.
239    pub fn dialog(&self) -> OpenDialog {
240        self.filters
241            .iter()
242            .cloned()
243            .fold(OpenDialog::files().multiple(self.multiple()), |d, f| {
244                d.filter(f)
245            })
246    }
247}
248
249/// A pick the app asked for.
250#[derive(Debug, Clone, PartialEq)]
251pub enum Pick {
252    /// Images ([`Command::PickImages`](crate::Command::PickImages)).
253    Images(PickRequest),
254    /// Files of any type ([`Command::PickFiles`](crate::Command::PickFiles)).
255    Files(FilePickRequest),
256}
257
258impl Pick {
259    /// `files` in the form the app gets ([`finish`], [`finish_files`]).
260    pub fn finish(&self, files: Vec<PickedFile>) -> Vec<PickedFile> {
261        match self {
262            Pick::Images(request) => finish(request, files),
263            Pick::Files(request) => finish_files(request, files),
264        }
265    }
266}
267
268/// A file the user picked: what the app gets as a `File`.
269#[derive(Clone, PartialEq, Default)]
270#[non_exhaustive]
271pub struct PickedFile {
272    /// Its name, with an extension that matches [`Self::mime`]
273    /// (`IMG_0042.jpg`).
274    pub name: String,
275    /// Its media type (`image/jpeg`).
276    pub mime: String,
277    /// Its bytes, shared with the `File` and with an `Image` showing it.
278    pub data: ImageData,
279    /// Its size in pixels, with its orientation applied (as it shows);
280    /// zero when the platform does not say, then read from the bytes.
281    pub size: Size<DevicePixels>,
282    /// When it was last changed (`File.lastModified`); `None`: when the
283    /// app gets it.
284    pub last_modified: Option<SystemTime>,
285    /// Its size in bytes: its bytes' length, or for a file not read, the
286    /// size its system gave (a pick of files fills it in,
287    /// [`finish_files`]).
288    pub len: u64,
289    /// Whether its bytes were read.
290    pub status: PickedStatus,
291}
292
293/// Whether a picked file's bytes were read ([`PickedFile::status`]).
294#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
295#[non_exhaustive]
296pub enum PickedStatus {
297    /// Its bytes are [`PickedFile::data`].
298    #[default]
299    Read,
300    /// It is larger than the pick reads
301    /// ([`FilePickRequest::size_limit`]): its bytes were not read, and only
302    /// its name, type and size ([`PickedFile::len`]) answer.
303    TooLarge,
304}
305
306impl std::fmt::Debug for PickedFile {
307    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
308        f.debug_struct("PickedFile")
309            .field("name", &self.name)
310            .field("mime", &self.mime)
311            .field("bytes", &self.data.len())
312            .field("size", &self.size)
313            .field("len", &self.len)
314            .field("status", &self.status)
315            .finish()
316    }
317}
318
319impl PickedFile {
320    /// The file `name` of type `mime` holding `data` (its size read from
321    /// the bytes).
322    pub fn new(name: impl Into<String>, mime: impl Into<String>, data: ImageData) -> Self {
323        let mut file = Self {
324            name: name.into(),
325            mime: mime.into(),
326            data,
327            ..Self::default()
328        };
329        file.fill_in();
330        file
331    }
332
333    /// The file `name` of `len` bytes, too large to read
334    /// ([`PickedStatus::TooLarge`]): no bytes, its type what its name says
335    /// when `mime` is empty ([`finish_files`]).
336    pub fn too_large(name: impl Into<String>, mime: impl Into<String>, len: u64) -> Self {
337        Self {
338            name: name.into(),
339            mime: mime.into(),
340            len,
341            status: PickedStatus::TooLarge,
342            ..Self::default()
343        }
344    }
345
346    /// Completes what the platform left out: the size from the bytes, the
347    /// type from them or the name, and an extension matching the type.
348    pub fn fill_in(&mut self) {
349        if self.mime.is_empty() {
350            self.mime = sniff(&self.data)
351                .or_else(|| mime_for_name(&self.name))
352                .unwrap_or("application/octet-stream")
353                .into();
354        }
355        if self.size.width.0 <= 0 || self.size.height.0 <= 0 {
356            self.size = image_size(&self.data).unwrap_or_default();
357        }
358        self.name = file_name(&self.name, &self.mime);
359    }
360}
361
362/// The size in pixels the header of an image's bytes says (before any
363/// orientation), `None` when they are no image it knows.
364pub fn image_size(bytes: &[u8]) -> Option<Size<DevicePixels>> {
365    let size = imagesize::blob_size(bytes).ok()?;
366    Some(Size::new(
367        DevicePixels(size.width as i32),
368        DevicePixels(size.height as i32),
369    ))
370}
371
372/// The media type an image's bytes start with, if they are a format it
373/// knows.
374pub fn sniff(bytes: &[u8]) -> Option<&'static str> {
375    use imagesize::ImageType;
376    Some(match imagesize::image_type(bytes).ok()? {
377        ImageType::Jpeg => "image/jpeg",
378        ImageType::Png => "image/png",
379        ImageType::Gif => "image/gif",
380        ImageType::Webp => "image/webp",
381        ImageType::Heif(imagesize::Compression::Av1) => "image/avif",
382        ImageType::Heif(_) => "image/heic",
383        ImageType::Tiff => "image/tiff",
384        ImageType::Bmp => "image/bmp",
385        _ => return None,
386    })
387}
388
389/// The media type a file's name says (its extension), if it is an image's.
390pub fn mime_for_name(name: &str) -> Option<&'static str> {
391    let ext = name.rsplit_once('.')?.1.to_ascii_lowercase();
392    Some(match ext.as_str() {
393        "jpg" | "jpeg" | "jpe" => "image/jpeg",
394        "png" => "image/png",
395        "gif" => "image/gif",
396        "webp" => "image/webp",
397        "heic" => "image/heic",
398        "heif" => "image/heif",
399        "avif" => "image/avif",
400        "tif" | "tiff" => "image/tiff",
401        "bmp" => "image/bmp",
402        _ => return None,
403    })
404}
405
406/// The extension a file of type `mime` has (`jpg`), if it is an image's.
407pub fn extension(mime: &str) -> Option<&'static str> {
408    Some(match mime.to_ascii_lowercase().as_str() {
409        "image/jpeg" => "jpg",
410        "image/png" => "png",
411        "image/gif" => "gif",
412        "image/webp" => "webp",
413        "image/heic" => "heic",
414        "image/heif" => "heif",
415        "image/avif" => "avif",
416        "image/tiff" => "tiff",
417        "image/bmp" => "bmp",
418        _ => return None,
419    })
420}
421
422/// `name` with the extension of `mime` (`IMG_0042.HEIC` as a JPEG is
423/// `IMG_0042.jpg`); a name without a stem becomes `image`.
424pub fn file_name(name: &str, mime: &str) -> String {
425    let name = name.rsplit(['/', '\\']).next().unwrap_or_default();
426    let Some(ext) = extension(mime) else {
427        return if name.is_empty() {
428            "file".into()
429        } else {
430            name.into()
431        };
432    };
433    let stem = match name.rsplit_once('.') {
434        Some((stem, old)) if mime_for_name(name).is_some() || old.len() <= 4 => stem,
435        _ => name,
436    };
437    let stem = if stem.is_empty() { "image" } else { stem };
438    if mime_for_name(name) == Some(mime) {
439        return name.into();
440    }
441    format!("{stem}.{ext}")
442}
443
444/// An image for the app: its `File` and its size in pixels, as JS gets
445/// each of `Picker.pickImages`' images. A module returning images of its
446/// own (a photo taken) returns this, so apps handle them the same way.
447#[derive(Clone, Debug, Default, PartialEq)]
448#[non_exhaustive]
449pub struct PickedImage {
450    /// The image's file and its size ([`finish`] completes both).
451    pub file: PickedFile,
452}
453
454impl PickedImage {
455    /// `file` as an image for the app.
456    pub fn new(file: PickedFile) -> Self {
457        Self { file }
458    }
459}
460
461impl JsValue for PickedImage {
462    fn ts_type(types: &mut TsTypes) -> String {
463        let size = Size::<DevicePixels>::ts_type(types);
464        types.declare("PickedImage", |_| {
465            format!(
466                "/** An image the user picked (`Picker.pickImages`) or took. */\n\
467                 export interface PickedImage {{\n\
468                 \x20 /** The image's file: its name, type (`image/jpeg`), size in bytes and bytes. */\n\
469                 \x20 file: File;\n\
470                 \x20 /** Its size in pixels, as it shows (its orientation applied). */\n\
471                 \x20 size: {size};\n\
472                 }}"
473            )
474        })
475    }
476
477    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
478        Err(value.expected("no value: a picked image is only returned"))
479    }
480
481    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
482        let file = &self.file;
483        let owned = JsOwned::new(host, host.new_object()?);
484        let object = owned.get().raw();
485        let js_file = host.new_file(&file.data, &file.mime, &file.name, file.last_modified)?;
486        host.set_field(object, "file", js_file)?;
487        host.set_field(object, "size", file.size.to_js(host)?.into_raw())?;
488        Ok(owned)
489    }
490}
491
492/// The files a pick resolves with, as the core hands them to the app.
493pub type PickFuture = Pin<Box<dyn Future<Output = Vec<PickedFile>> + Send>>;
494
495/// Answers the app's picks in place of the platform's picker: an embedding
496/// app's own picker, or a test's files.
497pub trait PickerBackend: Send + Sync {
498    /// The files the user picked for `request` (none when cancelled). The
499    /// future may finish on any thread; the core truncates what goes past
500    /// the request's limit and fills in sizes and types the files lack
501    /// ([`PickedFile::fill_in`]).
502    fn pick_images(&self, request: PickRequest) -> PickFuture;
503
504    /// The files the user picked for `request` (none when cancelled); the
505    /// core truncates what goes past the request's limit. A backend that
506    /// picks no files cancels: the platform's picker is still not shown.
507    fn pick_files(&self, request: FilePickRequest) -> PickFuture {
508        let _ = request;
509        Box::pin(std::future::ready(Vec::new()))
510    }
511}
512
513/// One picked image as a platform's codec reads it, for [`prepare_image`]:
514/// the platform decodes and encodes, the core decides what to do with it.
515/// Made by the backends that encode (Android, iOS, macOS), no API of apps':
516/// hidden from the docs, so it stays out of what NSH keeps compatible.
517#[doc(hidden)]
518pub trait PickedSource: Sized {
519    /// Its media type (`image/heic`).
520    fn mime(&self) -> &str;
521
522    /// Its pixel size with its orientation applied, of the image the
523    /// platform shows of it; empty when the platform cannot tell.
524    fn size(&self) -> Size<DevicePixels>;
525
526    /// Its bytes as they are.
527    fn into_bytes(self) -> Option<ImageData>;
528
529    /// The image decoded with its orientation applied, scaled to `target`
530    /// and encoded as a PNG (`png`) or a JPEG of `quality`: the encoded
531    /// bytes and their pixel size. `None` when it cannot be.
532    fn encode(
533        self,
534        png: bool,
535        target: Size<DevicePixels>,
536        quality: Percentage,
537    ) -> Option<(Vec<u8>, Size<DevicePixels>)>;
538}
539
540/// `source`, an image named `name`, prepared as `request` says
541/// ([`PickRequest::needs_encoding`]): its bytes as they are, or decoded,
542/// scaled to [`PickRequest::scaled_size`] and encoded again as a PNG or a
543/// JPEG of [`PickRequest::jpeg_quality`]. One whose size the platform
544/// cannot tell stays as it is. `None` when it cannot be encoded. The flow
545/// every backend that encodes shares (Android, iOS, macOS), no API of
546/// apps': hidden from the docs, so it stays out of what NSH keeps
547/// compatible.
548#[doc(hidden)]
549pub fn prepare_image(
550    source: impl PickedSource,
551    name: &str,
552    request: &PickRequest,
553) -> Option<PickedFile> {
554    let size = source.size();
555    let encoding = if size.width.0 <= 0 || size.height.0 <= 0 {
556        Encoding::Keep
557    } else {
558        request.needs_encoding(source.mime(), size)
559    };
560    let (mime, data, size) = match encoding {
561        Encoding::Keep => {
562            let mime = source.mime().to_owned();
563            (mime, source.into_bytes()?, size)
564        }
565        Encoding::Png | Encoding::Jpeg => {
566            let png = encoding == Encoding::Png;
567            let target = request.scaled_size(size);
568            let (bytes, size) = source.encode(png, target, request.jpeg_quality())?;
569            let mime = if png { "image/png" } else { "image/jpeg" };
570            (mime.to_owned(), ImageData::new(bytes), size)
571        }
572    };
573    let mut file = PickedFile::new(name, mime, data);
574    if size.width.0 > 0 && size.height.0 > 0 {
575        file.size = size;
576    }
577    Some(file)
578}
579
580/// Puts `files` in the form the app gets: at most `request.limit`, each
581/// completed ([`PickedFile::fill_in`]).
582pub fn finish(request: &PickRequest, mut files: Vec<PickedFile>) -> Vec<PickedFile> {
583    files.truncate(request.limit.max(1) as usize);
584    for file in &mut files {
585        file.fill_in();
586    }
587    files
588}
589
590/// Puts `files` of a pick of files in the form the app gets: at most
591/// `request.limit`, their names without folders and as the user knows them,
592/// each with a type ([`mime_for_file`]) and its size; one read whose bytes
593/// are more than the request reads ([`FilePickRequest::size_limit`]: a
594/// platform that could not tell its size before) keeps only its name and
595/// size ([`PickedStatus::TooLarge`]).
596pub fn finish_files(request: &FilePickRequest, mut files: Vec<PickedFile>) -> Vec<PickedFile> {
597    files.truncate(request.limit.max(1) as usize);
598    let limit = request.size_limit();
599    for file in &mut files {
600        if file.status == PickedStatus::Read {
601            file.len = file.data.len() as u64;
602            if file.len > limit {
603                log::warn!(
604                    "the picked {} is not read: larger than {limit} bytes",
605                    file.name
606                );
607                file.status = PickedStatus::TooLarge;
608                file.data = ImageData::default();
609            }
610        }
611        if let Some(name) = file.name.rsplit(['/', '\\']).next() {
612            file.name = name.to_owned();
613        }
614        if file.name.is_empty() {
615            file.name = "file".into();
616        }
617        if file.mime.is_empty() {
618            file.mime = mime_for_file(&file.name, &file.data).into();
619        }
620    }
621    files
622}
623
624/// The media type of a file of any type: what its bytes say when they are
625/// an image, else what its name says, else `application/octet-stream`.
626pub fn mime_for_file(name: &str, bytes: &[u8]) -> &'static str {
627    sniff(bytes)
628        .or_else(|| mime_for_name(name))
629        .or_else(|| {
630            let ext = name.rsplit_once('.')?.1.to_ascii_lowercase();
631            Some(match ext.as_str() {
632                "pdf" => "application/pdf",
633                "txt" | "log" => "text/plain",
634                "md" | "markdown" => "text/markdown",
635                "csv" => "text/csv",
636                "html" | "htm" => "text/html",
637                "css" => "text/css",
638                "js" | "mjs" => "text/javascript",
639                "json" => "application/json",
640                "xml" => "application/xml",
641                "svg" => "image/svg+xml",
642                "zip" => "application/zip",
643                "gz" => "application/gzip",
644                "tar" => "application/x-tar",
645                "7z" => "application/x-7z-compressed",
646                "doc" => "application/msword",
647                "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
648                "xls" => "application/vnd.ms-excel",
649                "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
650                "ppt" => "application/vnd.ms-powerpoint",
651                "pptx" => {
652                    "application/vnd.openxmlformats-officedocument.presentationml.presentation"
653                }
654                "mp3" => "audio/mpeg",
655                "m4a" => "audio/mp4",
656                "wav" => "audio/wav",
657                "ogg" => "audio/ogg",
658                "flac" => "audio/flac",
659                "mp4" | "m4v" => "video/mp4",
660                "mov" => "video/quicktime",
661                "webm" => "video/webm",
662                _ => return None,
663            })
664        })
665        .unwrap_or("application/octet-stream")
666}
667
668/// The extensions a desktop open dialog offers for `request` whose
669/// backend reads files as they are ([`read_files`]): with
670/// [`PickFormat::Compatible`], only the formats browsers show.
671pub fn dialog_extensions(request: &PickRequest) -> &'static [&'static str] {
672    match request.format {
673        PickFormat::Compatible => &["jpg", "jpeg", "jpe", "png", "gif", "webp"],
674        PickFormat::Current => &[
675            "jpg", "jpeg", "jpe", "png", "gif", "webp", "heic", "heif", "avif", "tif", "tiff",
676            "bmp",
677        ],
678    }
679}
680
681/// The files at `paths`, read as they are (the backends without an image
682/// encoder: Windows, Linux, GPUI), at most the request's limit; those that
683/// cannot be read are left out.
684#[cfg(not(target_arch = "wasm32"))]
685pub fn read_files(paths: &[std::path::PathBuf], request: &PickRequest) -> Vec<PickedFile> {
686    paths
687        .iter()
688        .take(request.limit.max(1) as usize)
689        .filter_map(|path| {
690            let bytes = std::fs::read(path).ok()?;
691            let name = path.file_name()?.to_string_lossy().into_owned();
692            let mime = sniff(&bytes)
693                .or_else(|| mime_for_name(&name))
694                .unwrap_or_default();
695            let mut file = PickedFile::new(name, mime, ImageData::new(bytes));
696            file.last_modified = std::fs::metadata(path).and_then(|m| m.modified()).ok();
697            Some(file)
698        })
699        .collect()
700}
701
702/// The files at `paths` for a pick of files, read as they are, at most the
703/// request's limit; those that cannot be read are left out and logged, and
704/// those larger than the request reads ([`FilePickRequest::size_limit`])
705/// are not read: they answer with their names and sizes
706/// ([`PickedStatus::TooLarge`]).
707#[cfg(not(target_arch = "wasm32"))]
708pub fn read_picked_files(
709    paths: &[std::path::PathBuf],
710    request: &FilePickRequest,
711) -> Vec<PickedFile> {
712    read_paths(paths, request, request.size_limit())
713}
714
715#[cfg(not(target_arch = "wasm32"))]
716fn read_paths(
717    paths: &[std::path::PathBuf],
718    request: &FilePickRequest,
719    max_bytes: u64,
720) -> Vec<PickedFile> {
721    let files = paths
722        .iter()
723        .take(request.limit.max(1) as usize)
724        .filter_map(|path| {
725            let metadata = std::fs::metadata(path)
726                .inspect_err(|e| log::warn!("cannot read the picked {}: {e}", path.display()))
727                .ok()?;
728            let name = path.file_name()?.to_string_lossy().into_owned();
729            if metadata.len() > max_bytes {
730                log::warn!(
731                    "the picked {} is not read: larger than {max_bytes} bytes",
732                    path.display()
733                );
734                let mut file = PickedFile::too_large(name, "", metadata.len());
735                file.last_modified = metadata.modified().ok();
736                return Some(file);
737            }
738            let bytes = std::fs::read(path)
739                .inspect_err(|e| log::warn!("cannot read the picked {}: {e}", path.display()))
740                .ok()?;
741            Some(PickedFile {
742                name,
743                data: ImageData::new(bytes),
744                last_modified: metadata.modified().ok(),
745                ..PickedFile::default()
746            })
747        })
748        .collect();
749    finish_files(request, files)
750}
751
752#[cfg(test)]
753mod tests {
754    use super::*;
755
756    fn px(w: i32, h: i32) -> Size<DevicePixels> {
757        Size::new(DevicePixels(w), DevicePixels(h))
758    }
759
760    #[test]
761    fn limits() {
762        assert_eq!(PickRequest::new(false, 5).limit, 1);
763        assert_eq!(PickRequest::new(true, 0).limit, MAX_PICKED);
764        assert_eq!(PickRequest::new(true, 3).limit, 3);
765        assert_eq!(PickRequest::new(true, 1000).limit, MAX_PICKED);
766        assert!(!PickRequest::new(true, 1).multiple());
767    }
768
769    #[test]
770    fn encodings() {
771        let mut r = PickRequest::default();
772        assert_eq!(
773            r.needs_encoding("image/jpeg", px(4000, 3000)),
774            Encoding::Keep
775        );
776        assert_eq!(r.needs_encoding("image/heic", px(400, 300)), Encoding::Jpeg);
777        assert_eq!(r.needs_encoding("image/gif", px(400, 300)), Encoding::Keep);
778        r.format = PickFormat::Current;
779        assert_eq!(r.needs_encoding("image/heic", px(400, 300)), Encoding::Keep);
780        r.max_dimension = Some(DevicePixels(1000));
781        assert_eq!(
782            r.needs_encoding("image/heic", px(4000, 3000)),
783            Encoding::Jpeg
784        );
785        assert_eq!(r.needs_encoding("image/png", px(4000, 3000)), Encoding::Png);
786        assert_eq!(r.needs_encoding("image/png", px(400, 300)), Encoding::Keep);
787        r.quality = Some(Percentage(0.5));
788        assert_eq!(r.needs_encoding("image/jpeg", px(400, 300)), Encoding::Jpeg);
789        assert_eq!(r.scaled_size(px(4000, 3000)), px(1000, 750));
790        assert_eq!(r.scaled_size(px(300, 4000)), px(75, 1000));
791        assert_eq!(r.scaled_size(px(400, 300)), px(400, 300));
792    }
793
794    /// What [`Fake`] was asked to encode: PNG or not, the size, the quality.
795    type Asked = Option<(bool, Size<DevicePixels>, f32)>;
796
797    /// A codec that encodes nothing: it says what it was asked.
798    struct Fake {
799        mime: &'static str,
800        size: Size<DevicePixels>,
801        asked: std::rc::Rc<std::cell::Cell<Asked>>,
802    }
803
804    impl PickedSource for Fake {
805        fn mime(&self) -> &str {
806            self.mime
807        }
808
809        fn size(&self) -> Size<DevicePixels> {
810            self.size
811        }
812
813        fn into_bytes(self) -> Option<ImageData> {
814            Some(ImageData::new(b"original".to_vec()))
815        }
816
817        fn encode(
818            self,
819            png: bool,
820            target: Size<DevicePixels>,
821            quality: Percentage,
822        ) -> Option<(Vec<u8>, Size<DevicePixels>)> {
823            self.asked.set(Some((png, target, quality.0)));
824            Some((b"encoded".to_vec(), target))
825        }
826    }
827
828    fn prepared(
829        mime: &'static str,
830        size: Size<DevicePixels>,
831        request: &PickRequest,
832    ) -> (PickedFile, Asked) {
833        let asked = std::rc::Rc::default();
834        let source = Fake {
835            mime,
836            size,
837            asked: std::rc::Rc::clone(&asked),
838        };
839        let file = prepare_image(source, "IMG_1.HEIC", request).expect("prepared");
840        (file, asked.get())
841    }
842
843    #[test]
844    fn prepared_images_keep_or_encode_as_the_request_says() {
845        let mut r = PickRequest::default();
846        // Compatible: a HEIC becomes a JPEG of its size and the default
847        // quality.
848        let (file, asked) = prepared("image/heic", px(400, 300), &r);
849        assert_eq!(asked, Some((false, px(400, 300), DEFAULT_QUALITY.0)));
850        assert_eq!(
851            (file.name.as_str(), file.mime.as_str()),
852            ("IMG_1.jpg", "image/jpeg")
853        );
854        assert_eq!(&file.data[..], b"encoded");
855        assert_eq!(file.size, px(400, 300));
856        // Its own format at its size: as it is, its size the codec's.
857        r.format = PickFormat::Current;
858        let (file, asked) = prepared("image/heic", px(400, 300), &r);
859        assert_eq!(asked, None);
860        assert_eq!(
861            (file.name.as_str(), file.mime.as_str()),
862            ("IMG_1.HEIC", "image/heic")
863        );
864        assert_eq!(&file.data[..], b"original");
865        assert_eq!(file.size, px(400, 300));
866        // A large PNG is scaled and stays a PNG.
867        r.max_dimension = Some(DevicePixels(100));
868        r.quality = Some(Percentage(0.5));
869        let (file, asked) = prepared("image/png", px(400, 300), &r);
870        assert_eq!(asked, Some((true, px(100, 75), 0.5)));
871        assert_eq!(file.mime, "image/png");
872        assert_eq!(file.size, px(100, 75));
873        // One whose size the platform cannot tell stays as it is.
874        r.format = PickFormat::Compatible;
875        let (file, asked) = prepared("image/heic", px(0, 0), &r);
876        assert_eq!(asked, None);
877        assert_eq!(&file.data[..], b"original");
878    }
879
880    #[test]
881    fn names() {
882        assert_eq!(file_name("IMG_0042.HEIC", "image/jpeg"), "IMG_0042.jpg");
883        assert_eq!(file_name("IMG_0042", "image/jpeg"), "IMG_0042.jpg");
884        assert_eq!(file_name("a.jpeg", "image/jpeg"), "a.jpeg");
885        assert_eq!(file_name("/tmp/x/shot.png", "image/png"), "shot.png");
886        assert_eq!(file_name("", "image/png"), "image.png");
887        assert_eq!(file_name("v1.2 draft", "image/png"), "v1.2 draft.png");
888    }
889
890    #[test]
891    fn fill_in_reads_the_bytes() {
892        // A 1×1 PNG.
893        let png = vec![
894            0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, b'I', b'H', b'D', b'R', 0,
895            0, 0, 3, 0, 0, 0, 2, 8, 6, 0, 0, 0,
896        ];
897        let file = PickedFile::new("pic", "", ImageData::new(png));
898        assert_eq!(file.mime, "image/png");
899        assert_eq!(file.name, "pic.png");
900        assert_eq!(file.size, px(3, 2));
901    }
902
903    #[test]
904    fn a_backend_without_file_picks_cancels_them() {
905        struct Images;
906        impl PickerBackend for Images {
907            fn pick_images(&self, _: PickRequest) -> PickFuture {
908                unreachable!()
909            }
910        }
911        let picked = Images.pick_files(FilePickRequest::default());
912        let mut picked = std::pin::pin!(picked);
913        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
914        assert_eq!(
915            picked.as_mut().poll(&mut cx),
916            std::task::Poll::Ready(Vec::new())
917        );
918    }
919
920    #[test]
921    fn file_requests() {
922        assert_eq!(FilePickRequest::default().limit, 1);
923        assert_eq!(FilePickRequest::new(true, 0).limit, MAX_PICKED);
924        let request = FilePickRequest::new(true, 2).filter(FileFilter::new("Docs", ["pdf", ".MD"]));
925        assert!(request.multiple());
926        let dialog = request.dialog();
927        assert!(dialog.multiple && dialog.picks_files() && !dialog.picks_folders());
928        assert_eq!(dialog.filters[0].extensions, ["pdf", "md"]);
929        assert!(FilePickRequest::new(false, 0).dialog().filters.is_empty());
930    }
931
932    #[test]
933    fn types_of_files() {
934        assert_eq!(mime_for_file("a.PDF", b"%PDF"), "application/pdf");
935        assert_eq!(
936            mime_for_file("a", b"\xff\xd8\xff\xe0\0\0\0\0\0\0\0\0"),
937            "image/jpeg"
938        );
939        assert_eq!(mime_for_file("a.bin", b"x"), "application/octet-stream");
940    }
941
942    #[test]
943    fn picked_files_keep_their_names_and_bytes() {
944        let dir = std::env::temp_dir().join(format!("nsh-picked-{}", std::process::id()));
945        std::fs::create_dir_all(&dir).unwrap();
946        // A PNG's bytes under another name, a type no image has and a file
947        // past the limit.
948        let png = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13];
949        let paths: Vec<_> = [
950            ("shot.dat", &png[..]),
951            ("report.pdf", b"%PDF-1.7"),
952            ("big.bin", &[0; 32]),
953        ]
954        .into_iter()
955        .map(|(name, bytes)| {
956            let path = dir.join(name);
957            std::fs::write(&path, bytes).unwrap();
958            path
959        })
960        .collect();
961        let missing = dir.join("missing.txt");
962        let request = FilePickRequest::new(true, 0);
963        let files = read_paths(&[&paths[..], &[missing]].concat(), &request, 16);
964        let one = read_paths(&paths, &FilePickRequest::default(), 16);
965        std::fs::remove_dir_all(&dir).unwrap();
966        let got: Vec<_> = files
967            .iter()
968            .map(|f| {
969                (
970                    f.name.as_str(),
971                    f.mime.as_str(),
972                    f.data.len(),
973                    f.len,
974                    f.status,
975                )
976            })
977            .collect();
978        // The file past the limit answers with its name and size, unread.
979        assert_eq!(
980            got,
981            [
982                ("shot.dat", "image/png", 12, 12, PickedStatus::Read),
983                ("report.pdf", "application/pdf", 8, 8, PickedStatus::Read),
984                (
985                    "big.bin",
986                    "application/octet-stream",
987                    0,
988                    32,
989                    PickedStatus::TooLarge
990                ),
991            ]
992        );
993        assert!(files[0].last_modified.is_some());
994        assert!(files[2].last_modified.is_some());
995        assert_eq!(one.len(), 1);
996    }
997
998    /// A directory of its own for test `name`, removed when dropped.
999    struct TempDir(std::path::PathBuf);
1000
1001    impl TempDir {
1002        fn new(name: &str) -> Self {
1003            let dir = std::env::temp_dir().join(format!("nsh-{name}-{}", std::process::id()));
1004            std::fs::create_dir_all(&dir).unwrap();
1005            Self(dir)
1006        }
1007    }
1008
1009    impl Drop for TempDir {
1010        fn drop(&mut self) {
1011            let _ = std::fs::remove_dir_all(&self.0);
1012        }
1013    }
1014
1015    #[test]
1016    fn files_past_the_apps_limit_answer_with_their_name_and_size_only() {
1017        let dir = TempDir::new("picked-limit");
1018        let small = dir.0.join("notes.txt");
1019        let video = dir.0.join("clip.mp4");
1020        std::fs::write(&small, b"hello").unwrap();
1021        std::fs::write(&video, [0; 64]).unwrap();
1022        let request = FilePickRequest::new(true, 0).max_size(16);
1023        assert_eq!(request.size_limit(), 16);
1024        let files = read_picked_files(&[small, video], &request);
1025        assert_eq!(files.len(), 2);
1026        assert_eq!(files[0].status, PickedStatus::Read);
1027        assert_eq!((files[0].data.len(), files[0].len), (5, 5));
1028        let video = &files[1];
1029        assert_eq!(video.status, PickedStatus::TooLarge);
1030        assert_eq!(video.name, "clip.mp4");
1031        assert_eq!(video.mime, "video/mp4", "the type its name says");
1032        assert_eq!((video.data.len(), video.len), (0, 64));
1033        // A limit past NSH's own is NSH's.
1034        let request = FilePickRequest::default().max_size(u64::MAX);
1035        assert_eq!(request.size_limit(), MAX_PICKED_FILE_BYTES);
1036    }
1037
1038    #[test]
1039    fn files_past_nshs_limit_answer_with_their_name_and_size_only() {
1040        let dir = TempDir::new("picked-huge");
1041        // A sparse file: its size without its bytes on disk.
1042        let path = dir.0.join("huge.bin");
1043        let file = std::fs::File::create(&path).unwrap();
1044        file.set_len(MAX_PICKED_FILE_BYTES + 1).unwrap();
1045        drop(file);
1046        let request = FilePickRequest::default();
1047        assert_eq!(request.size_limit(), MAX_PICKED_FILE_BYTES);
1048        let files = read_picked_files(&[path], &request);
1049        assert_eq!(files.len(), 1);
1050        assert_eq!(files[0].status, PickedStatus::TooLarge);
1051        assert_eq!(files[0].name, "huge.bin");
1052        assert_eq!(files[0].len, MAX_PICKED_FILE_BYTES + 1);
1053        assert!(files[0].data.is_empty());
1054    }
1055
1056    #[test]
1057    fn files_read_past_the_limit_keep_only_their_name_and_size() {
1058        // What a platform that could not tell the size first read, or a
1059        // picker backend gave.
1060        let request = FilePickRequest::new(true, 0).max_size(4);
1061        let file = |name: &str, bytes: &[u8]| PickedFile {
1062            name: name.into(),
1063            data: ImageData::new(bytes.to_vec()),
1064            ..PickedFile::default()
1065        };
1066        let unread = PickedFile::too_large("film.mov", "", 1 << 40);
1067        let files = finish_files(
1068            &request,
1069            vec![file("a.txt", b"abcd"), file("b.txt", b"abcde"), unread],
1070        );
1071        let got: Vec<_> = files
1072            .iter()
1073            .map(|f| {
1074                (
1075                    f.name.as_str(),
1076                    f.mime.as_str(),
1077                    f.data.len(),
1078                    f.len,
1079                    f.status,
1080                )
1081            })
1082            .collect();
1083        assert_eq!(
1084            got,
1085            [
1086                ("a.txt", "text/plain", 4, 4, PickedStatus::Read),
1087                ("b.txt", "text/plain", 0, 5, PickedStatus::TooLarge),
1088                (
1089                    "film.mov",
1090                    "video/quicktime",
1091                    0,
1092                    1 << 40,
1093                    PickedStatus::TooLarge
1094                ),
1095            ]
1096        );
1097    }
1098
1099    #[test]
1100    fn finished_files_drop_folders_from_names() {
1101        let request = FilePickRequest::new(false, 0);
1102        let file = PickedFile {
1103            name: "/tmp/x/notes".into(),
1104            data: ImageData::new(b"hello".to_vec()),
1105            ..PickedFile::default()
1106        };
1107        let files = finish_files(&request, vec![file.clone(), file]);
1108        assert_eq!(files.len(), 1);
1109        assert_eq!(files[0].name, "notes");
1110        assert_eq!(files[0].mime, "application/octet-stream");
1111    }
1112}