Skip to content

Commit

Permalink
feat: 设置热重载
Browse files Browse the repository at this point in the history
  • Loading branch information
Pylogmon committed Mar 19, 2023
1 parent 922b267 commit a2b52cd
Show file tree
Hide file tree
Showing 7 changed files with 225 additions and 124 deletions.
66 changes: 59 additions & 7 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ edition = "2021"
tauri-build = { version = "1.2", features = [] }

[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.2", features = ["clipboard-all", "fs-write-file", "global-shortcut-all", "http-all", "notification", "notification-all", "shell-open", "system-tray", "window-all"] }
tauri-plugin-single-instance = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "dev" }
once_cell = "1.17.1"
reqwest = "0.11.14"
toml = "0.7.3"

[target.'cfg(windows)'.dependencies]
window-shadows = "0.2"
Expand Down
158 changes: 90 additions & 68 deletions src-tauri/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,87 +1,109 @@
use once_cell::sync::OnceCell;
use serde::{Deserialize, Serialize};
use std::{fs, io::Read, io::Write};
use tauri::api::path::config_dir;
// 全局配置
pub static CONFIG_STR: OnceCell<String> = OnceCell::new();
pub static CONFIG: OnceCell<Config> = OnceCell::new();
static APPID: &str = "cn.pylogmon.pot";
use crate::shortcut::register_shortcut;
use crate::APP;
use std::sync::Mutex;
use std::{fs, fs::OpenOptions, io::Read, io::Write, path::PathBuf};
use tauri::{api::path::config_dir, Manager};
use toml::{Table, Value};

// 配置文件结构体
#[derive(Deserialize, Debug, Serialize)]
#[allow(dead_code)]
pub struct Config {
pub shortcut_translate: String,
pub shortcut_persistent: String,
pub target_language: String,
pub interface: String,
pub static APPID: &str = "cn.pylogmon.pot";

fn get_app_config_dir() -> PathBuf {
let mut app_config_dir_path = config_dir().expect("Get Config Dir Failed");
app_config_dir_path.push(APPID);
app_config_dir_path
}

// 检查配置文件是否存在
fn check_config() -> Result<(fs::File, bool), String> {
fn get_app_config_file() -> PathBuf {
let mut app_config_file_path = get_app_config_dir();
app_config_file_path.push("config.toml");
app_config_file_path
}

fn check_config() -> bool {
// 配置目录路径
let app_config_dir_path = get_app_config_dir();
// 配置文件路径
let mut app_config_dir_path = match config_dir() {
Some(v) => v,
None => todo!(),
};
app_config_dir_path.push(APPID);
let mut app_config_file_path = app_config_dir_path.clone();
app_config_file_path.push("config.json");
// 检查文件
let app_config_file_path = get_app_config_file();

if !app_config_file_path.exists() {
// 检查目录
if !app_config_dir_path.exists() {
fs::create_dir_all(app_config_dir_path).unwrap();
// 创建目录
fs::create_dir_all(app_config_dir_path).expect("Create Config Dir Failed");
}
// 创建文件
let mut config_file = fs::File::create(&app_config_file_path).unwrap();
// 写入默认配置
let default_config = Config {
shortcut_translate: "CommandOrControl+D".to_owned(),
shortcut_persistent: "CommandOrControl+Shift+D".to_owned(),
target_language: "zh-cn".to_owned(),
interface: "youdao_free".to_owned(),
};
config_file
.write_all(serde_json::to_string(&default_config).unwrap().as_bytes())
.unwrap();
let config_file = fs::File::open(&app_config_file_path).unwrap();
return Ok((config_file, false));
fs::File::create(app_config_file_path).expect("Create Config File Failed");
return false;
}

let config_file = fs::File::open(&app_config_file_path).unwrap();
Ok((config_file, true))
return true;
}

// 从文件读取配置
fn read_config(mut file: fs::File) {
// 从文件读取配置
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
CONFIG_STR.get_or_init(|| contents.clone());
// 对配置反序列化
let config: Config = serde_json::from_str(contents.as_str()).unwrap();
// 写入全局变量
CONFIG.get_or_init(|| config);
pub struct ConfigWrapper(pub Mutex<Config>);
// 配置文件结构体
pub struct Config {
pub config_toml: Table,
}

// 初始化配置
pub fn init_config() -> bool {
// 获取配置文件
let (file, flag) = match check_config() {
Ok(v) => v,
Err(_) => {
panic!("panic")
impl Config {
pub fn init_config() -> bool {
// 配置文件路径
let app_config_file_path = get_app_config_file();
// 检查配置文件
let flag = check_config();
// 读取配置文件
let mut config_file =
fs::File::open(&app_config_file_path).expect("Open Config File Failed");
let mut contents = String::new();
config_file
.read_to_string(&mut contents)
.expect("Read Config File Failed");
// 构造配置结构体
let config = ConfigWrapper(Mutex::new(Config {
config_toml: contents.parse::<Table>().expect("Parse Config File Failed"),
}));
// 写入状态
APP.get().unwrap().manage(config);
return flag;
}
pub fn get(&self, key: &str, default: Value) -> Value {
match self.config_toml.get(key) {
Some(v) => v.to_owned(),
None => default,
}
}
pub fn set(&mut self, key: &str, value: Value) {
self.config_toml.insert(key.to_string(), value);
}
pub fn write(&self) -> Result<(), String> {
let app_config_file_path = get_app_config_file();
let mut config_file = OpenOptions::new()
.write(true)
.open(&app_config_file_path)
.expect("Open Config File Failed");
let contents = self.config_toml.to_string();
match config_file.write_all(contents.as_bytes()) {
Ok(_) => return Ok(()),
Err(e) => return Err(e.to_string()),
}
};
// 读取配置文件
read_config(file);
}
}

!flag
pub fn get_config(key: &str, default: Value, state: tauri::State<ConfigWrapper>) -> Value {
state.0.lock().unwrap().get(key, default)
}

#[tauri::command]
pub fn set_config(key: &str, value: Value, state: tauri::State<ConfigWrapper>) {
state.0.lock().unwrap().set(key, value);
}

#[tauri::command]
pub fn write_config(state: tauri::State<ConfigWrapper>) -> Result<(), String> {
register_shortcut().unwrap();
state.0.lock().unwrap().write()
}

// 前端获取配置
#[tauri::command]
pub fn get_config() -> Result<String, String> {
Ok(CONFIG_STR.get().unwrap().to_string())
pub fn get_config_str(state: tauri::State<ConfigWrapper>) -> Table {
println!("{:?}", state.0.lock().unwrap().config_toml);
return state.0.lock().unwrap().config_toml.clone();
}
21 changes: 18 additions & 3 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,32 @@ fn main() {
APP.get_or_init(|| app.handle());
let handle = APP.get().unwrap();
// 初始化设置
let is_first = init_config();
let is_first = !Config::init_config();
// 首次启动打开设置页面
if is_first {
on_config_click(handle);
}
// 注册全局快捷键
register_shortcut();
match register_shortcut() {
Ok(_) => {}
Err(e) => {
Notification::new(&app.config().tauri.bundle.identifier)
.title("快捷键注册失败")
.body(e.to_string())
.icon("pot")
.show()
.unwrap();
}
}
Ok(())
})
// 注册Tauri Command
.invoke_handler(tauri::generate_handler![get_selection_text, get_config])
.invoke_handler(tauri::generate_handler![
get_selection_text,
get_config_str,
set_config,
write_config
])
//加载托盘图标
.system_tray(build_system_tray())
//绑定托盘事件
Expand Down

0 comments on commit a2b52cd

Please sign in to comment.