Files
md-preview/src/config.rs

236 lines
6.4 KiB
Rust

//! User data paths, persisted window/zoom/theme state, and the blocking dialogs.
use std::fs;
use std::path::PathBuf;
use tao::event_loop::EventLoop;
use tao::window::{Theme, Window};
// Window defaults, in logical pixels.
pub const DEFAULT_W: f64 = 900.0;
pub const DEFAULT_H: f64 = 700.0;
use crate::app::UserEvent;
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum ThemeChoice {
#[default]
System,
Light,
Dark,
}
impl ThemeChoice {
pub fn as_str(self) -> &'static str {
match self {
ThemeChoice::System => "system",
ThemeChoice::Light => "light",
ThemeChoice::Dark => "dark",
}
}
pub fn from_str(value: &str) -> Self {
match value.trim().to_ascii_lowercase().as_str() {
"light" => ThemeChoice::Light,
"dark" => ThemeChoice::Dark,
_ => ThemeChoice::System,
}
}
pub fn tao_theme(self) -> Option<Theme> {
match self {
ThemeChoice::System => None,
ThemeChoice::Light => Some(Theme::Light),
ThemeChoice::Dark => Some(Theme::Dark),
}
}
}
pub fn config_dir() -> PathBuf {
if let Some(path) = std::env::var_os("MD_PREVIEW_CONFIG_DIR") {
return PathBuf::from(path);
}
std::env::var_os("LOCALAPPDATA")
.or_else(|| std::env::var_os("APPDATA"))
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."))
.join("md-preview")
}
#[derive(Copy, Clone)]
pub struct WindowGeom {
pub x: f64,
pub y: f64,
pub w: f64,
pub h: f64,
}
pub fn geom_path() -> PathBuf {
config_dir().join("window.geom")
}
pub fn theme_path() -> PathBuf {
config_dir().join("theme.txt")
}
pub fn load_theme_choice() -> ThemeChoice {
fs::read_to_string(theme_path())
.map(|raw| ThemeChoice::from_str(&raw))
.unwrap_or_default()
}
pub fn save_theme_choice(choice: ThemeChoice) {
let dir = config_dir();
let _ = fs::create_dir_all(&dir);
let _ = fs::write(dir.join("theme.txt"), choice.as_str());
}
const ZOOM_MIN: u32 = 50;
const ZOOM_MAX: u32 = 300;
pub fn zoom_path() -> PathBuf {
config_dir().join("zoom.txt")
}
pub fn clamp_zoom(percent: u32) -> u32 {
percent.clamp(ZOOM_MIN, ZOOM_MAX)
}
pub fn load_zoom() -> u32 {
fs::read_to_string(zoom_path())
.ok()
.and_then(|raw| raw.trim().parse::<u32>().ok())
.map(clamp_zoom)
.unwrap_or(100)
}
pub fn save_zoom(percent: u32) {
let dir = config_dir();
let _ = fs::create_dir_all(&dir);
let _ = fs::write(zoom_path(), clamp_zoom(percent).to_string());
}
pub fn show_warning_dialog(title: &str, description: &str) {
let _ = rfd::MessageDialog::new()
.set_level(rfd::MessageLevel::Warning)
.set_title(title)
.set_description(description)
.show();
}
pub fn confirm_discard_unsaved(error: &str) -> bool {
matches!(
rfd::MessageDialog::new()
.set_level(rfd::MessageLevel::Warning)
.set_title("Could Not Save")
.set_description(format!(
"{error}\n\nThe file may be read-only or locked by another program. Close the window and discard the unsaved changes?"
))
.set_buttons(rfd::MessageButtons::OkCancel)
.show(),
rfd::MessageDialogResult::Ok
)
}
pub fn load_window_geom() -> Option<WindowGeom> {
let txt = fs::read_to_string(geom_path()).ok()?;
let parts: Vec<&str> = txt.trim().split(',').collect();
if parts.len() != 4 {
return None;
}
Some(WindowGeom {
x: parts[0].parse().ok()?,
y: parts[1].parse().ok()?,
w: parts[2].parse().ok()?,
h: parts[3].parse().ok()?,
})
}
pub fn save_window_geom(window: &Window) {
let Ok(pos) = window.outer_position() else {
return;
};
let scale = window.scale_factor();
let size = window.inner_size();
let geom = WindowGeom {
x: pos.x as f64 / scale,
y: pos.y as f64 / scale,
w: size.width as f64 / scale,
h: size.height as f64 / scale,
};
if geom.w < 200.0 || geom.h < 150.0 {
return;
}
let dir = config_dir();
let _ = fs::create_dir_all(&dir);
let _ = fs::write(
dir.join("window.geom"),
format!("{},{},{},{}", geom.x, geom.y, geom.w, geom.h),
);
}
/// Return the saved geometry only when its center still falls inside
/// some connected monitor — prevents the window from landing off-screen
/// after a display swap.
pub fn geom_visible(geom: &WindowGeom, event_loop: &EventLoop<UserEvent>) -> bool {
let cx = geom.x + geom.w / 2.0;
let cy = geom.y + geom.h / 2.0;
event_loop.available_monitors().any(|mon| {
let scale = mon.scale_factor();
let mp = mon.position();
let ms = mon.size();
let mx = mp.x as f64 / scale;
let my = mp.y as f64 / scale;
let mw = ms.width as f64 / scale;
let mh = ms.height as f64 / scale;
cx >= mx && cx <= mx + mw && cy >= my && cy <= my + mh
})
}
pub fn centered_geom(event_loop: &EventLoop<UserEvent>) -> WindowGeom {
if let Some(mon) = event_loop.primary_monitor() {
let scale = mon.scale_factor();
let mp = mon.position();
let ms = mon.size();
let mx = mp.x as f64 / scale;
let my = mp.y as f64 / scale;
let mw = ms.width as f64 / scale;
let mh = ms.height as f64 / scale;
WindowGeom {
x: mx + (mw - DEFAULT_W) / 2.0,
y: my + (mh - DEFAULT_H) / 2.0,
w: DEFAULT_W,
h: DEFAULT_H,
}
} else {
WindowGeom {
x: 100.0,
y: 100.0,
w: DEFAULT_W,
h: DEFAULT_H,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn zoom_percent_is_clamped_to_supported_range() {
assert_eq!(clamp_zoom(10), 50);
assert_eq!(clamp_zoom(50), 50);
assert_eq!(clamp_zoom(105), 105);
assert_eq!(clamp_zoom(300), 300);
assert_eq!(clamp_zoom(999), 300);
}
#[test]
fn theme_choice_parses_menu_values() {
assert_eq!(ThemeChoice::from_str("system"), ThemeChoice::System);
assert_eq!(ThemeChoice::from_str("light"), ThemeChoice::Light);
assert_eq!(ThemeChoice::from_str("dark"), ThemeChoice::Dark);
assert_eq!(ThemeChoice::from_str("unexpected"), ThemeChoice::System);
assert_eq!(ThemeChoice::Dark.as_str(), "dark");
}
}