Skip to main content

Module picked_file

Module picked_file 

Source
Expand description

Reading and writing what the user chose in a file dialog, the same way on every platform.

FileDialogResult::files turns a choice into PickedFiles. What one holds depends on where the application runs, and the application does not have to know:

  • On a desktop or a phone it is a path. PickedFile::read, PickedFile::write, PickedFile::entries and PickedFile::child run on a Host worker with std::fs, so the UI thread never waits for the disk. A write goes to a temporary file beside the target and is renamed over it, so a reader never sees half of it.
  • In a browser there is no path. The Renderer keeps the browser’s handle for the file and the Host keeps its number. The dialog’s answer carries one reference per file in Chosen.paths, written webfile:<handle>/<name>, and files() turns each into a PickedFile. Every operation then crosses to the Renderer as one FileCall record and comes back as one event: an IoAnswer with the bytes or the reason, or a FileHandles with the files a folder holds. When the last PickedFile for a handle is dropped, the Host tells the Renderer to let go of it with ReleaseFileHandle.
ⓘ
FileDialog::open_file().filter("Text", &["txt", "md"]).show(move |result| {
    if let Some(file) = result.files().into_iter().next() {
        scope.launch(async move {
            if let Ok(bytes) = file.read().await {
                document.set(String::from_utf8_lossy(&bytes).into_owned());
            }
        });
    }
});

How a file reached the application is PickedFile::delivery. Only a Delivery::Handle can be written again in place: a browser without the File System Access API hands over a copy to read (Delivery::Upload) or turns a save into a download (Delivery::Download), and an application treats its next save as “save as” when PickedFile::can_write_again is false.

The operations are futures to await on the UI thread, from an effect, a coroutine scope or a handler. They are not Send on the web, where the answer comes back on the UI thread inside a Host call.

Structs§

PickedFile
One file or folder the user chose, to read and write.

Enums§

Delivery
How a file reached the application.
FileError
Why an operation on a PickedFile did not happen.