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
11pub struct Fs<R: Runtime>(pub(crate) AppHandle<R>);
12
13fn path_or_err<P: Into<FilePath>>(p: P) -> std::io::Result<PathBuf> {
14    match p.into() {
15        FilePath::Path(p) => Ok(p),
16        FilePath::Url(u) if u.scheme() == "file" => u
17            .to_file_path()
18            .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid file URL")),
19        FilePath::Url(_) => Err(std::io::Error::new(
20            std::io::ErrorKind::InvalidInput,
21            "cannot use a URL to load files on desktop and iOS",
22        )),
23    }
24}
25
26impl<R: Runtime> Fs<R> {
27    /// Open a file.
28    ///
29    /// # Platform-specific
30    ///
31    /// - **iOS**: This method will automatically start accessing a security-scoped resource if the path is a file URL.
32    ///   You must call `stop_accessing_security_scoped_resource` when you're done accessing the file.
33    pub fn open<P: Into<FilePath>>(
34        &self,
35        path: P,
36        opts: OpenOptions,
37    ) -> std::io::Result<std::fs::File> {
38        let path = path_or_err(path)?;
39        std::fs::OpenOptions::from(opts).open(path)
40    }
41}