Skip to content

Commit

Permalink
Add native volume data saving support
Browse files Browse the repository at this point in the history
  • Loading branch information
Xevion committed Apr 24, 2024
1 parent a1884c0 commit 6f445b1
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 18 deletions.
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ fn main() {
)
.unwrap();

let storage = store::Store {};
let mut storage = store::Store::new();

let mut volume = storage.volume().map_or_else(
|| {
Expand Down
73 changes: 56 additions & 17 deletions src/store.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,48 @@
use std::{io::Seek, path::PathBuf};

#[cfg(not(target_os = "emscripten"))]
pub struct Store {
file: std::fs::File,
}

#[cfg(target_os = "emscripten")]
pub struct Store;

#[cfg(not(target_os = "emscripten"))]
impl Store {
pub fn volume(&self) -> Option<u32> {
None
pub fn new () -> Self {
let path = Store::get_path();
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
Store { file }
}

pub fn set_volume(&self, volume: u32) {
// Do nothing
fn get_path() -> PathBuf {
use std::env;
let mut path = env::current_exe().unwrap();
path.pop();
path.push("volume.txt");
path
}

pub fn volume(&mut self) -> Option<u32> {
use std::io::Read;

let mut buffer = String::new();
self.file.read_to_string(&mut buffer).unwrap();
buffer.trim().parse::<u32>().ok()
}

pub fn set_volume(&mut self, volume: u32) {
use std::io::Write;

self.file.set_len(0).unwrap();
self.file.seek(std::io::SeekFrom::Start(0)).unwrap();
write!(self.file, "{}", volume).unwrap();
}
}

Expand All @@ -19,6 +54,23 @@ extern "C" {

#[cfg(target_os = "emscripten")]
impl Store {
pub fn new () -> Self {
Store
}

pub fn volume(&self) -> Option<u32> {
// Use local storage to try and read volume
let script = "localStorage.getItem('volume')";
let response = Store::run_script_string(&script);
response.parse::<u32>().ok()
}

pub fn set_volume(&self, volume: u32) {
// Use local storage to set volume
let script = format!("localStorage.setItem('volume', '{}')", volume);
Store::run_script_string(&script);
}

fn run_script(script: &str) {
use std::ffi::CString;

Expand All @@ -38,17 +90,4 @@ impl Store {
String::from(c_str.to_str().unwrap())
}
}

pub fn volume(&self) -> Option<u32> {
// Use local storage to try and read volume
let script = "localStorage.getItem('volume')";
let response = Store::run_script_string(&script);
response.parse::<u32>().ok()
}

pub fn set_volume(&self, volume: u32) {
// Use local storage to set volume
let script = format!("localStorage.setItem('volume', '{}')", volume);
Store::run_script_string(&script);
}
}

0 comments on commit 6f445b1

Please sign in to comment.