Skip to main content

tauri_plugin_fs/
desktop.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5use std::path::PathBuf;
6
7use tauri::{AppHandle, Runtime};
8
9use crate::{FilePath, OpenOptions};
10
11/// Access to the file system APIs on desktop.
12///
13/// Retrieved with [`crate::FsExt::fs`].
14pub struct Fs<R: Runtime>(pub(crate) AppHandle<R>);
15
16fn path_or_err<P: Into<FilePath>>(p: P) -> std::io::Result<PathBuf> {
17    match p.into() {
18        FilePath::Path(p) => Ok(p),
19        FilePath::Url(u) if u.scheme() == "file" => u
20            .to_file_path()
21            .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid file URL")),
22        FilePath::Url(_) => Err(std::io::Error::new(
23            std::io::ErrorKind::InvalidInput,
24            "cannot use a URL to load files on desktop and iOS",
25        )),
26    }
27}
28
29impl<R: Runtime> Fs<R> {
30    /// Open a file.
31    ///
32    /// # Platform-specific
33    ///
34    /// - **iOS**: This method will automatically start accessing a security-scoped resource if the path is a file URL.
35    ///   You must call `stop_accessing_security_scoped_resource` when you're done accessing the file.
36    pub fn open<P: Into<FilePath>>(
37        &self,
38        path: P,
39        opts: OpenOptions,
40    ) -> std::io::Result<std::fs::File> {
41        let path = path_or_err(path)?;
42        std::fs::OpenOptions::from(opts).open(path)
43    }
44}