-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathmain.rs
More file actions
235 lines (214 loc) · 8.96 KB
/
main.rs
File metadata and controls
235 lines (214 loc) · 8.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use tauri::{
api::process::{Command, CommandEvent},
CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
};
use std::fs;
use std::path::PathBuf;
use std::sync::Mutex;
use tauri::api::{dialog, path};
#[derive(serde::Deserialize, Clone)]
struct Settings {
text_generation_webui_path: String,
}
// the payload type must implement `Serialize` and `Clone`.
#[derive(Clone, serde::Serialize)]
struct Payload {
message: String,
}
struct AppState {
child_process: Mutex<Option<tauri::api::process::Child>>,
}
fn show_error_and_exit(handle: &tauri::AppHandle, title: &str, message: &str) {
dialog::message(handle.get_window("main").as_ref(), title, message);
std::process::exit(1);
}
#[tauri::command]
async fn close_splashscreen(window: tauri::Window) {
// Close splashscreen
if let Some(splashscreen) = window.get_window("splashscreen") {
splashscreen.close().unwrap();
}
// Show main window
window.get_window("main").unwrap().show().unwrap();
}
#[derive(serde::Deserialize)]
struct ProxyRequestPayload {
path: String,
body: serde_json::Value,
}
#[tauri::command]
async fn proxy_request(payload: ProxyRequestPayload) -> Result<serde_json::Value, String> {
let client = reqwest::Client::new();
// This port should be configurable in the future.
let url = format!("http://127.0.0.1:5000/{}", payload.path);
let res = client
.post(&url)
.json(&payload.body)
.send()
.await
.map_err(|e| e.to_string())?;
if res.status().is_success() {
res.json::<serde_json::Value>()
.await
.map_err(|e| e.to_string())
} else {
let status = res.status();
let text = res.text().await.map_err(|e| e.to_string())?;
Err(format!(
"API request to {} failed with status {}: {}",
url, status, text
))
}
}
fn main() {
let app_state = AppState {
child_process: Mutex::new(None),
};
tauri::Builder::default()
.manage(app_state)
.setup(|app| {
let handle = app.handle().clone();
let app_state = handle.state::<AppState>();
// Load settings
let config_dir = match path::app_config_dir(&handle.config()) {
Some(dir) => dir,
None => {
show_error_and_exit(&handle, "Fatal Error", "Could not determine the application config directory.");
return Ok(()); // Unreachable but needed for type check
}
};
let settings_path_in_config = config_dir.join("settings.json");
let settings_str = if settings_path_in_config.exists() {
match fs::read_to_string(&settings_path_in_config) {
Ok(s) => s,
Err(e) => {
let msg = format!("Failed to read settings.json from config directory ({}): {}", settings_path_in_config.display(), e);
show_error_and_exit(&handle, "Configuration Error", &msg);
return Ok(());
}
}
} else {
let resource_path = match handle.path_resolver().resolve_resource("resources/settings.json") {
Some(path) => path,
None => {
show_error_and_exit(&handle, "Fatal Error", "Could not resolve bundled settings.json path.");
return Ok(());
}
};
match fs::read_to_string(resource_path) {
Ok(s) => s,
Err(e) => {
let msg = format!("Failed to read bundled settings.json: {}", e);
show_error_and_exit(&handle, "Fatal Error", &msg);
return Ok(());
}
}
};
let settings: Settings = match serde_json::from_str(&settings_str) {
Ok(s) => s,
Err(e) => {
let msg = format!("Failed to parse settings.json: {}. Please check for syntax errors.", e);
show_error_and_exit(&handle, "Configuration Error", &msg);
return Ok(());
}
};
// Validate path
let executable_path = PathBuf::from(&settings.text_generation_webui_path);
if settings.text_generation_webui_path.is_empty() || !executable_path.is_file() {
let msg = format!("The path specified in settings.json is either empty or does not point to a valid file: '{}'", settings.text_generation_webui_path);
show_error_and_exit(&handle, "Configuration Error", &msg);
return Ok(());
}
// Launch the external process
tauri::async_runtime::spawn(async move {
let (mut rx, child) = match Command::new(&settings.text_generation_webui_path).spawn() {
Ok(c) => c,
Err(e) => {
let msg = format!("Failed to spawn the external process at '{}': {}", settings.text_generation_webui_path, e);
show_error_and_exit(&handle, "Process Error", &msg);
// This exit is in a spawned thread, so it won't kill the main app directly
// The main app will continue, but the child process won't be running.
// The dialog is the most important part.
return;
}
};
*app_state.child_process.lock().unwrap() = Some(child);
while let Some(event) = rx.recv().await {
if let CommandEvent::Stdout(line) = event {
// Here you can log the output from the sidecar
// Or send it to the frontend
handle
.emit_all("sidecar-output", Payload { message: line.into() })
.unwrap();
}
}
});
Ok(())
})
.system_tray(
SystemTray::new().with_menu(
SystemTrayMenu::new()
.add_item(CustomMenuItem::new("checkforupdates".to_string(), "Check for updates"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("help".to_string(), "Help"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("quit".to_string(), "Quit")),
),
)
.on_system_tray_event(|app, event| match event {
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"quit" => {
let app_handle = app.app_handle();
let app_state = app_handle.state::<AppState>();
if let Some(child) = app_state.child_process.lock().unwrap().take() {
child.kill().expect("Failed to kill sidecar");
}
app_handle.exit(0);
}
"checkforupdates" => {
tauri::api::shell::open(
&app.shell_scope(),
"https://github.com/semperai/amica/releases/latest",
None,
)
.expect("failed to open url");
}
"help" => {
tauri::api::shell::open(
&app.shell_scope(),
"https://docs.heyamica.com",
None,
)
.expect("failed to open url");
}
_ => {}
},
_ => {}
})
.on_window_event(|event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event.event() {
let app_handle = event.window().app_handle();
let app_state = app_handle.state::<AppState>();
if let Some(child) = app_state.child_process.lock().unwrap().take() {
child.kill().expect("Failed to kill sidecar");
}
app_handle.exit(0);
}
})
.invoke_handler(tauri::generate_handler![
close_splashscreen,
proxy_request
])
.build(tauri::generate_context!())
.expect("error while building tauri application")
.run(|app_handle, event| {
if let tauri::RunEvent::ExitRequested { .. } = event {
let app_state = app_handle.state::<AppState>();
if let Some(child) = app_state.child_process.lock().unwrap().take() {
child.kill().expect("Failed to kill sidecar");
}
}
});
}