first version
This commit is contained in:
71
sam-tool-tauri/src-tauri/src/settings.rs
Normal file
71
sam-tool-tauri/src-tauri/src/settings.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone)]
|
||||
pub struct Settings {
|
||||
#[serde(default = "default_sam_url")]
|
||||
pub sam_url: String,
|
||||
#[serde(default)]
|
||||
pub sam_enabled: bool,
|
||||
/// Model id chosen from the backend's /models list (e.g.
|
||||
/// "sam2.1_hiera_small"). `None` lets the backend pick its default.
|
||||
#[serde(default)]
|
||||
pub sam_model: Option<String>,
|
||||
#[serde(default = "default_cache_capacity")]
|
||||
pub cache_capacity: usize,
|
||||
}
|
||||
|
||||
fn default_sam_url() -> String {
|
||||
"http://localhost:9090".into()
|
||||
}
|
||||
|
||||
fn default_cache_capacity() -> usize {
|
||||
500
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
sam_url: default_sam_url(),
|
||||
sam_enabled: false,
|
||||
sam_model: None,
|
||||
cache_capacity: default_cache_capacity(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_path(app: &AppHandle) -> Result<PathBuf, String> {
|
||||
let dir = app
|
||||
.path()
|
||||
.app_local_data_dir()
|
||||
.map_err(|e| format!("app data dir: {e}"))?;
|
||||
fs::create_dir_all(&dir).map_err(|e| format!("mkdir {}: {e}", dir.display()))?;
|
||||
Ok(dir.join("settings.json"))
|
||||
}
|
||||
|
||||
pub fn load(app: &AppHandle) -> Result<Settings, String> {
|
||||
let path = settings_path(app)?;
|
||||
if !path.exists() {
|
||||
return Ok(Settings::default());
|
||||
}
|
||||
let text = fs::read_to_string(&path).map_err(|e| format!("read {}: {e}", path.display()))?;
|
||||
serde_json::from_str(&text).map_err(|e| format!("parse settings: {e}"))
|
||||
}
|
||||
|
||||
pub fn save(app: &AppHandle, s: &Settings) -> Result<(), String> {
|
||||
let path = settings_path(app)?;
|
||||
let text = serde_json::to_string_pretty(s).map_err(|e| format!("serialize: {e}"))?;
|
||||
fs::write(&path, text).map_err(|e| format!("write {}: {e}", path.display()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_settings(app: AppHandle) -> Result<Settings, String> {
|
||||
load(&app)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn save_settings(app: AppHandle, settings: Settings) -> Result<(), String> {
|
||||
save(&app, &settings)
|
||||
}
|
||||
Reference in New Issue
Block a user