1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
use std; use std::collections::HashMap; use uni_app; struct AsyncFile(String, uni_app::fs::File, Option<Vec<u8>>); pub struct FileLoader { files_to_load: HashMap<usize, AsyncFile>, seq: usize, } impl FileLoader { pub fn new() -> Self { Self { files_to_load: HashMap::new(), seq: 0, } } pub fn load_file(&mut self, path: &str) -> Result<usize, String> { uni_app::App::print(format!("loading file {}\n", path)); match open_file(path) { Ok(mut f) => { if f.is_ready() { match f.read_binary() { Ok(buf) => { self.files_to_load .insert(self.seq, AsyncFile(path.to_owned(), f, Some(buf))); self.seq += 1; return Ok(self.seq - 1); } Err(e) => { return Err(format!("Could not read file {} : {}\n", path, e)); } } } else { uni_app::App::print(format!("loading async file {}\n", path)); self.files_to_load .insert(self.seq, AsyncFile(path.to_owned(), f, None)); self.seq += 1; return Ok(self.seq - 1); } } Err(e) => { return Err(format!("Could not open file {} : {}\n", path, e)); } } } fn load_file_async(&mut self) -> bool { for (_, f) in self.files_to_load.iter_mut() { if f.1.is_ready() && f.2.is_none() { match f.1.read_binary() { Ok(buf) => { f.2 = Some(buf); } Err(e) => panic!("could not load async file {} : {}", f.0, e), } } } return true; } pub fn is_file_ready(&mut self, id: usize) -> bool { self.load_file_async(); if let Some(f) = self.files_to_load.get(&id) { return f.2.is_some(); } false } pub fn get_file_content(&mut self, id: usize) -> Vec<u8> { let mut f = self.files_to_load.remove(&id).unwrap(); f.2.take().unwrap() } } fn open_file(filename: &str) -> Result<uni_app::fs::File, std::io::Error> { let ffilename = if cfg!(not(target_arch = "wasm32")) && &filename[0..1] != "/" && &filename[1..2] != ":" { "static/".to_owned() + filename } else { filename.to_owned() }; uni_app::fs::FileSystem::open(&ffilename) }