Skip to main content

macroquad_ply/
file.rs

1//! Cross platform file management functions.
2
3use crate::{exec, Error};
4
5/// Load file from the path and block until its loaded
6/// Will use filesystem on PC and do http request on web
7pub async fn load_file(path: &str) -> Result<Vec<u8>, Error> {
8    fn load_file_inner(path: &str) -> exec::FileLoadingFuture {
9        use std::sync::{Arc, Mutex};
10
11        let contents = Arc::new(Mutex::new(None));
12        let path = path.to_owned();
13
14        {
15            let contents = contents.clone();
16            let err_path = path.clone();
17
18            miniquad::fs::load_file(&path, move |bytes| {
19                *contents.lock().unwrap() = Some(bytes.map_err(|kind| Error::FileError {
20                    kind,
21                    path: err_path.clone(),
22                }));
23            });
24        }
25
26        exec::FileLoadingFuture { contents }
27    }
28
29    #[cfg(target_os = "ios")]
30    let _ = std::env::set_current_dir(std::env::current_exe().unwrap().parent().unwrap());
31
32    #[cfg(not(target_os = "android"))]
33    let path = if let Some(ref pc_assets) = crate::get_context().pc_assets_folder {
34        format!("{pc_assets}/{path}")
35    } else {
36        path.to_string()
37    };
38
39    load_file_inner(&path).await
40}
41
42/// Load string from the path and block until its loaded.
43/// Right now this will use load_file and `from_utf8_lossy` internally, but
44/// implementation details may change in the future
45pub async fn load_string(path: &str) -> Result<String, Error> {
46    let data = load_file(path).await?;
47
48    Ok(String::from_utf8_lossy(&data).to_string())
49}
50
51/// There are super common project layout like this:
52/// ```skip
53///    .
54///    ├── assets
55///    ├── └── nice_texture.png
56///    ├── src
57///    ├── └── main.rs
58///    └── Cargo.toml
59/// ```
60/// when such a project being run on desktop assets should be referenced as
61/// "assets/nice_texture.png".
62/// While on web or android it usually is just "nice_texture.png".
63/// The reason: on PC assets are being referenced relative to current active directory/executable path. In most IDEs its the root of the project.
64/// While on, say, android it is:
65/// ```skip
66/// [package.metadata.android]
67/// assets = "assets"
68/// ```
69/// And therefore on android assets are referenced from the root of "assets" folder.
70///
71/// In the future there going to be some sort of meta-data file for PC as well.
72/// But right now to resolve this situation and keep pathes consistent across platforms
73/// `set_pc_assets_folder("assets");`call before first `load_file`/`load_texture` will allow using same pathes on PC and Android.
74pub fn set_pc_assets_folder(path: &str) {
75    crate::get_context().pc_assets_folder = Some(path.to_string());
76}