refactor: app conf

This commit is contained in:
lencx
2023-01-27 00:23:05 +08:00
parent f0ff062b21
commit f9f173407e
14 changed files with 388 additions and 396 deletions

View File

@@ -1,10 +1,7 @@
use crate::{
conf::ChatConfJson,
utils::{self, chat_root, create_file},
};
use crate::utils;
use log::info;
use std::{fs, path::PathBuf};
use tauri::{api, command, AppHandle, Manager, Theme};
use tauri::{api, command, AppHandle, Manager};
#[command]
pub fn drag_window(app: AppHandle) {
@@ -23,16 +20,16 @@ pub fn fullscreen(app: AppHandle) {
#[command]
pub fn download(_app: AppHandle, name: String, blob: Vec<u8>) {
let path = chat_root().join(PathBuf::from(name));
create_file(&path).unwrap();
let path = utils::app_root().join(PathBuf::from(name));
utils::create_file(&path).unwrap();
fs::write(&path, blob).unwrap();
utils::open_file(path);
}
#[command]
pub fn save_file(_app: AppHandle, name: String, content: String) {
let path = chat_root().join(PathBuf::from(name));
create_file(&path).unwrap();
let path = utils::app_root().join(PathBuf::from(name));
utils::create_file(&path).unwrap();
fs::write(&path, content).unwrap();
utils::open_file(path);
}
@@ -42,52 +39,11 @@ pub fn open_link(app: AppHandle, url: String) {
api::shell::open(&app.shell_scope(), url, None).unwrap();
}
#[command]
pub fn get_chat_conf() -> ChatConfJson {
ChatConfJson::get_chat_conf()
}
#[command]
pub fn reset_chat_conf() -> ChatConfJson {
ChatConfJson::reset_chat_conf()
}
#[command]
pub fn get_theme() -> String {
ChatConfJson::theme().unwrap_or(Theme::Light).to_string()
}
#[command]
pub fn run_check_update(app: AppHandle, silent: bool, has_msg: Option<bool>) {
utils::run_check_update(app, silent, has_msg);
}
#[command]
pub fn form_confirm(_app: AppHandle, data: serde_json::Value) {
ChatConfJson::amend(&serde_json::json!(data), None).unwrap();
}
#[command]
pub fn form_cancel(app: AppHandle, label: &str, title: &str, msg: &str) {
let win = app.app_handle().get_window(label).unwrap();
tauri::api::dialog::ask(
app.app_handle().get_window(label).as_ref(),
title,
msg,
move |is_cancel| {
if is_cancel {
win.close().unwrap();
}
},
);
}
#[command]
pub fn form_msg(app: AppHandle, label: &str, title: &str, msg: &str) {
let win = app.app_handle().get_window(label);
tauri::api::dialog::message(win.as_ref(), title, msg);
}
#[command]
pub fn open_file(path: PathBuf) {
utils::open_file(path);

View File

@@ -1,7 +1,7 @@
use crate::{
app::{fs_extra, window},
conf::GITHUB_PROMPTS_CSV_URL,
utils::{self, chat_root},
utils,
};
use log::info;
use regex::Regex;
@@ -11,7 +11,7 @@ use walkdir::WalkDir;
#[command]
pub fn get_chat_model_cmd() -> serde_json::Value {
let path = utils::chat_root().join("chat.model.cmd.json");
let path = utils::app_root().join("chat.model.cmd.json");
let content = fs::read_to_string(path).unwrap_or_else(|_| r#"{"data":[]}"#.to_string());
serde_json::from_str(&content).unwrap()
}
@@ -55,7 +55,7 @@ pub struct ModelRecord {
#[command]
pub fn cmd_list() -> Vec<ModelRecord> {
let mut list = vec![];
for entry in WalkDir::new(utils::chat_root().join("cache_model"))
for entry in WalkDir::new(utils::app_root().join("cache_model"))
.into_iter()
.filter_map(|e| e.ok())
{
@@ -82,7 +82,7 @@ pub struct FileMetadata {
#[tauri::command]
pub fn get_download_list(pathname: &str) -> (Vec<serde_json::Value>, PathBuf) {
info!("get_download_list: {}", pathname);
let download_path = chat_root().join(PathBuf::from(pathname));
let download_path = utils::app_root().join(PathBuf::from(pathname));
let content = fs::read_to_string(&download_path).unwrap_or_else(|err| {
info!("download_list_error: {}", err);
fs::write(&download_path, "[]").unwrap();
@@ -104,7 +104,7 @@ pub fn download_list(pathname: &str, dir: &str, filename: Option<String>, id: Op
let mut idmap = HashMap::new();
utils::vec_to_hashmap(data.0.into_iter(), "id", &mut idmap);
for entry in WalkDir::new(utils::chat_root().join(dir))
for entry in WalkDir::new(utils::app_root().join(dir))
.into_iter()
.filter_entry(|e| !utils::is_hidden(e))
.filter_map(|e| e.ok())
@@ -182,9 +182,9 @@ pub async fn sync_prompts(app: AppHandle, time: u64) -> Option<Vec<ModelRecord>>
let data2 = data.clone();
let model = utils::chat_root().join("chat.model.json");
let model_cmd = utils::chat_root().join("chat.model.cmd.json");
let chatgpt_prompts = utils::chat_root()
let model = utils::app_root().join("chat.model.json");
let model_cmd = utils::app_root().join("chat.model.cmd.json");
let chatgpt_prompts = utils::app_root()
.join("cache_model")
.join("chatgpt_prompts.json");
@@ -238,8 +238,8 @@ pub async fn sync_prompts(app: AppHandle, time: u64) -> Option<Vec<ModelRecord>>
"Sync Prompts",
"ChatGPT Prompts data has been synchronized!",
);
window::window_reload(app.clone(), "core");
window::window_reload(app, "tray");
window::cmd::window_reload(app.clone(), "core");
window::cmd::window_reload(app, "tray");
return Some(data2);
}

View File

@@ -1,6 +1,6 @@
use crate::{
app::window,
conf::{self, ChatConfJson},
conf::{self, AppConf},
utils,
};
use tauri::{
@@ -14,7 +14,7 @@ use tauri::AboutMetadata;
// --- Menu
pub fn init() -> Menu {
let chat_conf = ChatConfJson::get_chat_conf();
let app_conf = AppConf::read();
let name = "ChatGPT";
let app_menu = Submenu::new(
name,
@@ -35,7 +35,7 @@ pub fn init() -> Menu {
let stay_on_top =
CustomMenuItem::new("stay_on_top".to_string(), "Stay On Top").accelerator("CmdOrCtrl+T");
let stay_on_top_menu = if chat_conf.stay_on_top {
let stay_on_top_menu = if app_conf.stay_on_top {
stay_on_top.selected()
} else {
stay_on_top
@@ -44,15 +44,15 @@ pub fn init() -> Menu {
let theme_light = CustomMenuItem::new("theme_light".to_string(), "Light");
let theme_dark = CustomMenuItem::new("theme_dark".to_string(), "Dark");
let theme_system = CustomMenuItem::new("theme_system".to_string(), "System");
let is_dark = chat_conf.theme == "Dark";
let is_system = chat_conf.theme == "System";
let is_dark = app_conf.clone().theme_check("dark");
let is_system = app_conf.clone().theme_check("system");
let update_prompt = CustomMenuItem::new("update_prompt".to_string(), "Prompt");
let update_silent = CustomMenuItem::new("update_silent".to_string(), "Silent");
let _update_disable = CustomMenuItem::new("update_disable".to_string(), "Disable");
let popup_search = CustomMenuItem::new("popup_search".to_string(), "Pop-up Search");
let popup_search_menu = if chat_conf.popup_search {
let popup_search_menu = if app_conf.popup_search {
popup_search.selected()
} else {
popup_search
@@ -61,14 +61,14 @@ pub fn init() -> Menu {
#[cfg(target_os = "macos")]
let titlebar = CustomMenuItem::new("titlebar".to_string(), "Titlebar").accelerator("CmdOrCtrl+B");
#[cfg(target_os = "macos")]
let titlebar_menu = if chat_conf.titlebar {
let titlebar_menu = if app_conf.titlebar {
titlebar.selected()
} else {
titlebar
};
let system_tray = CustomMenuItem::new("system_tray".to_string(), "System Tray");
let system_tray_menu = if chat_conf.tray {
let system_tray_menu = if app_conf.tray {
system_tray.selected()
} else {
system_tray
@@ -114,16 +114,16 @@ pub fn init() -> Menu {
Submenu::new(
"Auto Update",
Menu::new()
.add_item(if chat_conf.auto_update == "Prompt" {
.add_item(if app_conf.auto_update == "Prompt" {
update_prompt.selected()
} else {
update_prompt
})
.add_item(if chat_conf.auto_update == "Silent" {
.add_item(if app_conf.auto_update == "Silent" {
update_silent.selected()
} else {
update_silent
}), // .add_item(if chat_conf.auto_update == "Disable" {
}), // .add_item(if app_conf.auto_update == "Disable" {
// update_disable.selected()
// } else {
// update_disable
@@ -241,23 +241,25 @@ pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
utils::run_check_update(app, false, None);
}
// Preferences
"control_center" => window::control_window(app),
"control_center" => window::cmd::control_window(app),
"restart" => tauri::api::process::restart(&app.env()),
"inject_script" => open(&app, script_path),
"go_conf" => utils::open_file(utils::chat_root()),
"go_conf" => utils::open_file(utils::app_root()),
"clear_conf" => utils::clear_conf(&app),
"awesome" => open(&app, conf::AWESOME_URL.to_string()),
"buy_coffee" => open(&app, conf::BUY_COFFEE.to_string()),
"popup_search" => {
let chat_conf = conf::ChatConfJson::get_chat_conf();
let popup_search = !chat_conf.popup_search;
let app_conf = AppConf::read();
let popup_search = !app_conf.popup_search;
menu_handle
.get_item(menu_id)
.set_selected(popup_search)
.unwrap();
ChatConfJson::amend(&serde_json::json!({ "popup_search": popup_search }), None).unwrap();
window::window_reload(app.clone(), "core");
window::window_reload(app, "tray");
app_conf
.amend(serde_json::json!({ "popup_search": popup_search }))
.write();
window::cmd::window_reload(app.clone(), "core");
window::cmd::window_reload(app, "tray");
}
"sync_prompts" => {
tauri::api::dialog::ask(
@@ -276,29 +278,37 @@ pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
);
}
"hide_dock_icon" => {
ChatConfJson::amend(&serde_json::json!({ "hide_dock_icon": true }), Some(app)).unwrap()
AppConf::read()
.amend(serde_json::json!({ "hide_dock_icon": true }))
.write()
.restart(app);
}
"titlebar" => {
let chat_conf = conf::ChatConfJson::get_chat_conf();
ChatConfJson::amend(
&serde_json::json!({ "titlebar": !chat_conf.titlebar }),
None,
)
.unwrap();
tauri::api::process::restart(&app.env());
let app_conf = AppConf::read();
app_conf
.clone()
.amend(serde_json::json!({ "titlebar": !app_conf.titlebar }))
.write()
.restart(app);
}
"system_tray" => {
let chat_conf = conf::ChatConfJson::get_chat_conf();
ChatConfJson::amend(&serde_json::json!({ "tray": !chat_conf.tray }), None).unwrap();
tauri::api::process::restart(&app.env());
let app_conf = AppConf::read();
app_conf
.clone()
.amend(serde_json::json!({ "tray": !app_conf.tray }))
.write()
.restart(app);
}
"theme_light" | "theme_dark" | "theme_system" => {
let theme = match menu_id {
"theme_dark" => "Dark",
"theme_system" => "System",
_ => "Light",
"theme_dark" => "dark",
"theme_system" => "system",
_ => "light",
};
ChatConfJson::amend(&serde_json::json!({ "theme": theme }), Some(app)).unwrap();
AppConf::read()
.amend(serde_json::json!({ "theme": theme }))
.write()
.restart(app);
}
"update_prompt" | "update_silent" | "update_disable" => {
// for id in ["update_prompt", "update_silent", "update_disable"] {
@@ -328,17 +338,21 @@ pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
"Prompt"
}
};
ChatConfJson::amend(&serde_json::json!({ "auto_update": auto_update }), None).unwrap();
AppConf::read()
.amend(serde_json::json!({ "auto_update": auto_update }))
.write();
}
"stay_on_top" => {
let chat_conf = conf::ChatConfJson::get_chat_conf();
let stay_on_top = !chat_conf.stay_on_top;
let app_conf = AppConf::read();
let stay_on_top = !app_conf.stay_on_top;
menu_handle
.get_item(menu_id)
.set_selected(stay_on_top)
.unwrap();
win.set_always_on_top(stay_on_top).unwrap();
ChatConfJson::amend(&serde_json::json!({ "stay_on_top": stay_on_top }), None).unwrap();
app_conf
.amend(serde_json::json!({ "stay_on_top": stay_on_top }))
.write();
}
// Window
"dalle2" => window::dalle2_window(&app, None, None, Some(false)),
@@ -367,7 +381,7 @@ pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
)
.unwrap(),
// Help
"chatgpt_log" => utils::open_file(utils::chat_root().join("chatgpt.log")),
"chatgpt_log" => utils::open_file(utils::app_root().join("chatgpt.log")),
"update_log" => open(&app, conf::UPDATE_LOG_URL.to_string()),
"report_bug" => open(&app, conf::ISSUES_URL.to_string()),
"dev_tools" => {
@@ -422,9 +436,9 @@ pub fn tray_handler(handle: &AppHandle, event: SystemTrayEvent) {
match event {
SystemTrayEvent::LeftClick { .. } => {
let chat_conf = conf::ChatConfJson::get_chat_conf();
let app_conf = AppConf::read();
if !chat_conf.hide_dock_icon {
if !app_conf.hide_dock_icon {
let core_win = handle.get_window("core").unwrap();
core_win.minimize().unwrap();
}
@@ -439,15 +453,21 @@ pub fn tray_handler(handle: &AppHandle, event: SystemTrayEvent) {
}
}
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"control_center" => window::control_window(app),
"control_center" => window::cmd::control_window(app),
"restart" => tauri::api::process::restart(&handle.env()),
"show_dock_icon" => {
ChatConfJson::amend(&serde_json::json!({ "hide_dock_icon": false }), Some(app)).unwrap();
AppConf::read()
.amend(serde_json::json!({ "hide_dock_icon": false }))
.write()
.restart(app);
}
"hide_dock_icon" => {
let chat_conf = conf::ChatConfJson::get_chat_conf();
if !chat_conf.hide_dock_icon {
ChatConfJson::amend(&serde_json::json!({ "hide_dock_icon": true }), Some(app)).unwrap();
let app_conf = AppConf::read();
if !app_conf.hide_dock_icon {
app_conf
.amend(serde_json::json!({ "hide_dock_icon": true }))
.write()
.restart(app);
}
}
"show_core" => {

View File

@@ -1,20 +1,20 @@
use crate::{app::window, conf::ChatConfJson, utils};
use crate::{app::window, conf::AppConf, utils};
use log::info;
use tauri::{utils::config::WindowUrl, window::WindowBuilder, App, GlobalShortcutManager, Manager};
use wry::application::accelerator::Accelerator;
pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>> {
info!("stepup");
let chat_conf = ChatConfJson::get_chat_conf();
let url = chat_conf.main_origin.to_string();
let theme = ChatConfJson::theme();
let app_conf = AppConf::read();
let url = app_conf.main_origin.to_string();
let theme = AppConf::theme_mode();
let handle = app.app_handle();
tauri::async_runtime::spawn(async move {
window::tray_window(&handle);
});
if let Some(v) = chat_conf.global_shortcut {
if let Some(v) = app_conf.clone().global_shortcut {
info!("global_shortcut: `{}`", v);
match v.parse::<Accelerator>() {
Ok(_) => {
@@ -44,13 +44,14 @@ pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>
info!("global_shortcut_unregister");
};
if chat_conf.hide_dock_icon {
let app_conf2 = app_conf.clone();
if app_conf.hide_dock_icon {
#[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
} else {
let app = app.handle();
tauri::async_runtime::spawn(async move {
let link = if chat_conf.main_dashboard {
let link = if app_conf2.main_dashboard {
"index.html"
} else {
&url
@@ -60,20 +61,20 @@ pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>
.resizable(true)
.fullscreen(false)
.inner_size(800.0, 600.0)
.theme(theme)
.always_on_top(chat_conf.stay_on_top)
.theme(Some(theme))
.always_on_top(app_conf2.stay_on_top)
.initialization_script(&utils::user_script())
.initialization_script(include_str!("../scripts/core.js"))
.user_agent(&chat_conf.ua_window);
.user_agent(&app_conf2.ua_window);
#[cfg(target_os = "macos")]
{
main_win = main_win
.title_bar_style(ChatConfJson::titlebar())
.title_bar_style(app_conf2.clone().titlebar())
.hidden_title(true);
}
if url == "https://chat.openai.com" && !chat_conf.main_dashboard {
if url == "https://chat.openai.com" && !app_conf2.main_dashboard {
main_win = main_win
.initialization_script(include_str!("../vendors/floating-ui-core.js"))
.initialization_script(include_str!("../vendors/floating-ui-dom.js"))
@@ -92,10 +93,10 @@ pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>
}
// auto_update
if chat_conf.auto_update != "Disable" {
if app_conf.auto_update != "Disable" {
info!("stepup::run_check_update");
let app = app.handle();
utils::run_check_update(app, chat_conf.auto_update == "Silent", None);
utils::run_check_update(app, app_conf.auto_update == "Silent", None);
}
Ok(())

View File

@@ -1,18 +1,18 @@
use crate::{conf, utils};
use crate::{conf::AppConf, utils};
use log::info;
use std::time::SystemTime;
use tauri::{utils::config::WindowUrl, window::WindowBuilder, Manager};
pub fn tray_window(handle: &tauri::AppHandle) {
let chat_conf = conf::ChatConfJson::get_chat_conf();
let theme = conf::ChatConfJson::theme();
let app_conf = AppConf::read();
let theme = AppConf::theme_mode();
let app = handle.clone();
tauri::async_runtime::spawn(async move {
let link = if chat_conf.tray_dashboard {
let link = if app_conf.tray_dashboard {
"index.html"
} else {
&chat_conf.tray_origin
&app_conf.tray_origin
};
let mut tray_win = WindowBuilder::new(&app, "tray", WindowUrl::App(link.into()))
.title("ChatGPT")
@@ -21,12 +21,12 @@ pub fn tray_window(handle: &tauri::AppHandle) {
.inner_size(360.0, 540.0)
.decorations(false)
.always_on_top(true)
.theme(theme)
.theme(Some(theme))
.initialization_script(&utils::user_script())
.initialization_script(include_str!("../scripts/core.js"))
.user_agent(&chat_conf.ua_tray);
.user_agent(&app_conf.ua_tray);
if chat_conf.tray_origin == "https://chat.openai.com" && !chat_conf.tray_dashboard {
if app_conf.tray_origin == "https://chat.openai.com" && !app_conf.tray_dashboard {
tray_win = tray_win
.initialization_script(include_str!("../vendors/floating-ui-core.js"))
.initialization_script(include_str!("../vendors/floating-ui-dom.js"))
@@ -45,7 +45,7 @@ pub fn dalle2_window(
is_new: Option<bool>,
) {
info!("dalle2_query: {:?}", query);
let theme = conf::ChatConfJson::theme();
let theme = AppConf::theme_mode();
let app = handle.clone();
let query = if query.is_some() {
@@ -76,7 +76,7 @@ pub fn dalle2_window(
.fullscreen(false)
.inner_size(800.0, 600.0)
.always_on_top(false)
.theme(theme)
.theme(Some(theme))
.initialization_script(include_str!("../scripts/core.js"))
.initialization_script(&query)
.initialization_script(include_str!("../scripts/dalle2.js"))
@@ -90,78 +90,84 @@ pub fn dalle2_window(
}
}
#[tauri::command]
pub fn dalle2_search_window(app: tauri::AppHandle, query: String) {
dalle2_window(
&app.app_handle(),
Some(query),
Some("ChatGPT & DALL·E 2".to_string()),
None,
);
}
pub mod cmd {
use super::*;
use log::info;
use tauri::{command, utils::config::WindowUrl, window::WindowBuilder, Manager};
#[tauri::command]
pub fn control_window(handle: tauri::AppHandle) {
tauri::async_runtime::spawn(async move {
if handle.get_window("main").is_none() {
WindowBuilder::new(
&handle,
"main",
WindowUrl::App("index.html?type=control".into()),
)
.title("Control Center")
.resizable(true)
.fullscreen(false)
.inner_size(1200.0, 700.0)
.min_inner_size(1000.0, 600.0)
.build()
.unwrap();
} else {
let main_win = handle.get_window("main").unwrap();
main_win.show().unwrap();
main_win.set_focus().unwrap();
}
});
}
#[tauri::command]
pub fn dalle2_search_window(app: tauri::AppHandle, query: String) {
dalle2_window(
&app.app_handle(),
Some(query),
Some("ChatGPT & DALL·E 2".to_string()),
None,
);
}
#[tauri::command]
pub async fn wa_window(
app: tauri::AppHandle,
label: String,
title: String,
url: String,
script: Option<String>,
) {
info!("wa_window: {} :=> {}", title, url);
let win = app.get_window(&label);
if win.is_none() {
#[tauri::command]
pub fn control_window(handle: tauri::AppHandle) {
tauri::async_runtime::spawn(async move {
tauri::WindowBuilder::new(&app, label, tauri::WindowUrl::App(url.parse().unwrap()))
.initialization_script(&script.unwrap_or_default())
.initialization_script(include_str!("../scripts/core.js"))
.title(title)
if handle.get_window("main").is_none() {
WindowBuilder::new(
&handle,
"main",
WindowUrl::App("index.html?type=control".into()),
)
.title("Control Center")
.resizable(true)
.fullscreen(false)
.inner_size(1200.0, 700.0)
.min_inner_size(1000.0, 600.0)
.build()
.unwrap();
} else {
let main_win = handle.get_window("main").unwrap();
main_win.show().unwrap();
main_win.set_focus().unwrap();
}
});
} else {
if !win.clone().unwrap().is_visible().unwrap() {
win.clone().unwrap().show().unwrap();
}
#[command]
pub async fn wa_window(
app: tauri::AppHandle,
label: String,
title: String,
url: String,
script: Option<String>,
) {
info!("wa_window: {} :=> {}", title, url);
let win = app.get_window(&label);
if win.is_none() {
tauri::async_runtime::spawn(async move {
tauri::WindowBuilder::new(&app, label, tauri::WindowUrl::App(url.parse().unwrap()))
.initialization_script(&script.unwrap_or_default())
.initialization_script(include_str!("../scripts/core.js"))
.title(title)
.build()
.unwrap();
});
} else {
if !win.clone().unwrap().is_visible().unwrap() {
win.clone().unwrap().show().unwrap();
}
win
.clone()
.unwrap()
.eval("window.location.reload()")
.unwrap();
win.unwrap().set_focus().unwrap();
}
win
.clone()
}
#[command]
pub fn window_reload(app: tauri::AppHandle, label: &str) {
app
.app_handle()
.get_window(label)
.unwrap()
.eval("window.location.reload()")
.unwrap();
win.unwrap().set_focus().unwrap();
}
}
#[tauri::command]
pub fn window_reload(app: tauri::AppHandle, label: &str) {
app
.app_handle()
.get_window(label)
.unwrap()
.eval("window.location.reload()")
.unwrap();
}