chore: update rust fmt rules (#235)

This commit is contained in:
RainbowBird
2025-06-28 00:26:07 +08:00
committed by GitHub
parent 9b85fe4f6b
commit 0bc7abc396
9 changed files with 136 additions and 49 deletions
@@ -50,6 +50,9 @@ pub fn get_mouse_location() -> Point {
unsafe { unsafe {
// Get cursor position in screen coordinates (macOS coordinates - origin at bottom left) // Get cursor position in screen coordinates (macOS coordinates - origin at bottom left)
let mouse_location: NSPoint = msg_send![class!(NSEvent), mouseLocation]; let mouse_location: NSPoint = msg_send![class!(NSEvent), mouseLocation];
Point { x: mouse_location.x, y: mouse_location.y } Point {
x: mouse_location.x,
y: mouse_location.y,
}
} }
} }
@@ -13,7 +13,10 @@ pub fn get_window_frame(window: &tauri::Window) -> WindowFrame {
if GetWindowRect(hwnd, &mut rect).is_ok() { if GetWindowRect(hwnd, &mut rect).is_ok() {
// Return the coordinates as (left, top, right, bottom) // Return the coordinates as (left, top, right, bottom)
return WindowFrame { return WindowFrame {
origin: Point { x: rect.left.into(), y: rect.top.into() }, origin: Point {
x: rect.left.into(),
y: rect.top.into(),
},
size: Size { size: Size {
width: (rect.right - rect.left).into(), width: (rect.right - rect.left).into(),
height: (rect.bottom - rect.top).into(), height: (rect.bottom - rect.top).into(),
@@ -24,7 +27,10 @@ pub fn get_window_frame(window: &tauri::Window) -> WindowFrame {
WindowFrame { WindowFrame {
origin: Point { x: 0.0, y: 0.0 }, origin: Point { x: 0.0, y: 0.0 },
size: Size { width: 0.0, height: 0.0 }, size: Size {
width: 0.0,
height: 0.0,
},
} // Default if unable to get window frame } // Default if unable to get window frame
} }
@@ -37,7 +43,10 @@ pub fn get_mouse_location() -> Point {
// Get cursor position in screen coordinates // Get cursor position in screen coordinates
if GetCursorPos(&mut cursor_pos).is_ok() { if GetCursorPos(&mut cursor_pos).is_ok() {
return Point { x: cursor_pos.x.into(), y: cursor_pos.y.into() }; return Point {
x: cursor_pos.x.into(),
y: cursor_pos.y.into(),
};
} }
} }
@@ -1,6 +1,6 @@
use std::sync::{ use std::sync::{
atomic::{AtomicBool, Ordering},
Arc, Arc,
atomic::{AtomicBool, Ordering},
}; };
use tauri::{Emitter, Manager}; use tauri::{Emitter, Manager};
@@ -11,12 +11,17 @@ pub struct WindowClickThroughState {
pub enabled: Arc<AtomicBool>, pub enabled: Arc<AtomicBool>,
} }
pub fn set_click_through_enabled(window: &tauri::Window, enabled: bool) -> Result<(), String> { pub fn set_click_through_enabled(
window: &tauri::Window,
enabled: bool,
) -> Result<(), String> {
let state = window.state::<WindowClickThroughState>(); let state = window.state::<WindowClickThroughState>();
state.enabled.store(enabled, Ordering::Relaxed); state.enabled.store(enabled, Ordering::Relaxed);
window.set_ignore_cursor_events(enabled).map_err(|e| format!("Failed to set click-through state: {e}"))?; window
.set_ignore_cursor_events(enabled)
.map_err(|e| format!("Failed to set click-through state: {e}"))?;
let _ = window.emit("tauri-app:window-click-through:enabled", enabled); let _ = window.emit("tauri-app:window-click-through:enabled", enabled);
@@ -5,12 +5,16 @@ use tauri::TitleBarStyle;
use tauri::{WebviewUrl, WebviewWindowBuilder}; use tauri::{WebviewUrl, WebviewWindowBuilder};
pub fn new_chat_window(app: &tauri::AppHandle) -> Result<(), tauri::Error> { pub fn new_chat_window(app: &tauri::AppHandle) -> Result<(), tauri::Error> {
let mut builder = WebviewWindowBuilder::new(app, "chat", WebviewUrl::App(Path::new("#/chat").to_path_buf())) let mut builder = WebviewWindowBuilder::new(
.title("Chat") app,
.inner_size(600.0, 800.0) "chat",
.shadow(true) WebviewUrl::App(Path::new("#/chat").to_path_buf()),
.transparent(false) )
.accept_first_mouse(true); .title("Chat")
.inner_size(600.0, 800.0)
.shadow(true)
.transparent(false)
.accept_first_mouse(true);
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
@@ -5,12 +5,16 @@ use tauri::TitleBarStyle;
use tauri::{WebviewUrl, WebviewWindowBuilder}; use tauri::{WebviewUrl, WebviewWindowBuilder};
pub fn new_settings_window(app: &tauri::AppHandle) -> Result<(), tauri::Error> { pub fn new_settings_window(app: &tauri::AppHandle) -> Result<(), tauri::Error> {
let mut builder = WebviewWindowBuilder::new(app, "settings", WebviewUrl::App(Path::new("#/settings").to_path_buf())) let mut builder = WebviewWindowBuilder::new(
.title("Settings") app,
.inner_size(450.0, 800.0) "settings",
.shadow(true) WebviewUrl::App(Path::new("#/settings").to_path_buf()),
.transparent(false) )
.accept_first_mouse(true); .title("Settings")
.inner_size(450.0, 800.0)
.shadow(true)
.transparent(false)
.accept_first_mouse(true);
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
+31 -8
View File
@@ -34,7 +34,9 @@ async fn start_monitor(window: tauri::Window) -> Result<(), String> {
} }
// Set to true // Set to true
state.monitoring_enabled.store(true, Ordering::Relaxed); state
.monitoring_enabled
.store(true, Ordering::Relaxed);
// Then start interval timer for monitoring // Then start interval timer for monitoring
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
@@ -48,12 +50,18 @@ async fn start_monitor(window: tauri::Window) -> Result<(), String> {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
let _ = window.emit("tauri-app:window-click-through:position-cursor-and-window-frame", (get_mouse_location(), get_window_frame(&window))); let _ = window.emit(
"tauri-app:window-click-through:position-cursor-and-window-frame",
(get_mouse_location(), get_window_frame(&window)),
);
} }
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
{ {
let _ = window.emit("tauri-app:window-click-through:position-cursor-and-window-frame", (get_mouse_location(), get_window_frame(&window))); let _ = window.emit(
"tauri-app:window-click-through:position-cursor-and-window-frame",
(get_mouse_location(), get_window_frame(&window)),
);
} }
} }
}); });
@@ -68,7 +76,9 @@ async fn stop_monitor(window: tauri::Window) -> Result<(), String> {
// Set to false // Set to false
// Termination will be triggered in the next interval check (tick) // Termination will be triggered in the next interval check (tick)
state.monitoring_enabled.store(false, Ordering::Relaxed); state
.monitoring_enabled
.store(false, Ordering::Relaxed);
Ok(()) Ok(())
} }
@@ -88,7 +98,9 @@ async fn stop_click_through(window: tauri::Window) -> Result<(), String> {
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
#[allow(clippy::missing_panics_doc)] #[allow(clippy::missing_panics_doc)]
pub fn run() { pub fn run() {
let prevent_default_plugin = tauri_plugin_prevent_default::Builder::new().with_flags(Flags::RELOAD).build(); let prevent_default_plugin = tauri_plugin_prevent_default::Builder::new()
.with_flags(Flags::RELOAD)
.build();
#[allow(clippy::missing_panics_doc)] #[allow(clippy::missing_panics_doc)]
tauri::Builder::default() tauri::Builder::default()
@@ -100,7 +112,13 @@ pub fn run() {
.setup(|app| { .setup(|app| {
let mut builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::default()); let mut builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::default());
builder = builder.title("AIRI").decorations(false).inner_size(450.0, 600.0).shadow(false).transparent(true).always_on_top(true); builder = builder
.title("AIRI")
.decorations(false)
.inner_size(450.0, 600.0)
.shadow(false)
.transparent(true)
.always_on_top(true);
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
@@ -115,7 +133,11 @@ pub fn run() {
} }
if cfg!(debug_assertions) { if cfg!(debug_assertions) {
app.handle().plugin(tauri_plugin_log::Builder::default().level(log::LevelFilter::Info).build())?; app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
} }
// TODO: i18n // TODO: i18n
@@ -126,7 +148,8 @@ pub fn run() {
let menu = Menu::with_items(app, &[&settings_item, &hide_item, &show_item, &quit_item])?; let menu = Menu::with_items(app, &[&settings_item, &hide_item, &show_item, &quit_item])?;
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
{ {
let show_devtools_item = MenuItem::with_id(app, "show-devtools", "Show Devtools", true, None::<&str>)?; let show_devtools_item =
MenuItem::with_id(app, "show-devtools", "Show Devtools", true, None::<&str>)?;
menu.append_items(&[&show_devtools_item])?; menu.append_items(&[&show_devtools_item])?;
} }
+6 -1
View File
@@ -1,4 +1,9 @@
const COMMANDS: &[&str] = &["connect_server", "disconnect_server", "list_tools", "call_tool"]; const COMMANDS: &[&str] = &[
"connect_server",
"disconnect_server",
"list_tools",
"call_tool",
];
fn main() { fn main() {
tauri_plugin::Builder::new(COMMANDS).build(); tauri_plugin::Builder::new(COMMANDS).build();
+50 -18
View File
@@ -25,34 +25,46 @@ pub struct McpState {
pub fn destroy<R: Runtime>(app_handle: &AppHandle<R>) { pub fn destroy<R: Runtime>(app_handle: &AppHandle<R>) {
println!("Destroying MCP plugin"); println!("Destroying MCP plugin");
tokio::runtime::Runtime::new().unwrap().block_on(async { tokio::runtime::Runtime::new()
let state = app_handle.state::<Mutex<McpState>>(); .unwrap()
.block_on(async {
let state = app_handle.state::<Mutex<McpState>>();
let mut state = state.lock().await; let mut state = state.lock().await;
if state.client.is_none() { if state.client.is_none() {
println!("MCP plugin not connected, no need to disconnect"); println!("MCP plugin not connected, no need to disconnect");
return; return;
} }
let client = state.client.take().unwrap(); let client = state.client.take().unwrap();
drop(state); drop(state);
client.cancel().await.unwrap(); client.cancel().await.unwrap();
// client.waiting().await.unwrap(); // client.waiting().await.unwrap();
}); });
println!("MCP plugin destroyed"); println!("MCP plugin destroyed");
} }
#[tauri::command] #[tauri::command]
async fn connect_server(state: State<'_, Mutex<McpState>>, command: String, args: Vec<String>) -> Result<(), String> { async fn connect_server(
state: State<'_, Mutex<McpState>>,
command: String,
args: Vec<String>,
) -> Result<(), String> {
let mut state = state.lock().await; let mut state = state.lock().await;
if state.client.is_some() { if state.client.is_some() {
return Err("Client already connected".to_string()); return Err("Client already connected".to_string());
} }
let child_process = TokioChildProcess::new(Command::new(command).args(args).stderr(Stdio::inherit()).stdout(Stdio::inherit())).unwrap(); let child_process = TokioChildProcess::new(
Command::new(command)
.args(args)
.stderr(Stdio::inherit())
.stdout(Stdio::inherit()),
)
.unwrap();
let service: RunningService<RoleClient, ()> = ().serve(child_process).await.unwrap(); let service: RunningService<RoleClient, ()> = ().serve(child_process).await.unwrap();
@@ -87,7 +99,11 @@ async fn list_tools(state: State<'_, Mutex<McpState>>) -> Result<Vec<Tool>, Stri
return Err("Client not connected".to_string()); return Err("Client not connected".to_string());
} }
let list_tools_result = client.unwrap().list_tools(Option::default()).await.unwrap(); // TODO: handle error let list_tools_result = client
.unwrap()
.list_tools(Option::default())
.await
.unwrap(); // TODO: handle error
let tools = list_tools_result.tools; let tools = list_tools_result.tools;
drop(state); drop(state);
@@ -95,7 +111,11 @@ async fn list_tools(state: State<'_, Mutex<McpState>>) -> Result<Vec<Tool>, Stri
} }
#[tauri::command] #[tauri::command]
async fn call_tool(state: State<'_, Mutex<McpState>>, name: String, args: Option<Map<String, Value>>) -> Result<CallToolResult, String> { async fn call_tool(
state: State<'_, Mutex<McpState>>,
name: String,
args: Option<Map<String, Value>>,
) -> Result<CallToolResult, String> {
println!("Calling tool: {name:?}"); println!("Calling tool: {name:?}");
println!("Arguments: {args:?}"); println!("Arguments: {args:?}");
@@ -105,7 +125,14 @@ async fn call_tool(state: State<'_, Mutex<McpState>>, name: String, args: Option
return Err("Client not connected".to_string()); return Err("Client not connected".to_string());
} }
let call_tool_result = client.unwrap().call_tool(CallToolRequestParam { name: name.into(), arguments: args }).await.unwrap(); let call_tool_result = client
.unwrap()
.call_tool(CallToolRequestParam {
name: name.into(),
arguments: args,
})
.await
.unwrap();
drop(state); drop(state);
println!("Tool result: {call_tool_result:?}"); println!("Tool result: {call_tool_result:?}");
@@ -122,7 +149,12 @@ impl Builder {
println!("Building MCP plugin"); println!("Building MCP plugin");
plugin::Builder::new("mcp") plugin::Builder::new("mcp")
.invoke_handler(tauri::generate_handler![connect_server, disconnect_server, list_tools, call_tool]) .invoke_handler(tauri::generate_handler![
connect_server,
disconnect_server,
list_tools,
call_tool
])
.setup(|app_handle, _| { .setup(|app_handle, _| {
app_handle.manage(Mutex::new(McpState { client: None })); app_handle.manage(Mutex::new(McpState { client: None }));
Ok(()) Ok(())
+5 -3
View File
@@ -2,7 +2,6 @@
edition = "2024" edition = "2024"
tab_spaces = 2 tab_spaces = 2
newline_style = "Unix"
imports_indent = "Block" # nightly imports_indent = "Block" # nightly
match_arm_leading_pipes = "Preserve" match_arm_leading_pipes = "Preserve"
# empty_item_single_line = true # nightly # empty_item_single_line = true # nightly
@@ -16,9 +15,12 @@ match_block_trailing_comma = true
# overflow_delimited_expr = true # nightly # overflow_delimited_expr = true # nightly
# reorder_impl_items = true # nightly # reorder_impl_items = true # nightly
# spaces_around_ranges = true # nightly # spaces_around_ranges = true # nightly
# unstable_features = true # nightly unstable_features = true # nightly
use_field_init_shorthand = true use_field_init_shorthand = true
use_try_shorthand = true use_try_shorthand = true
struct_field_align_threshold = 999 struct_field_align_threshold = 999
enum_discrim_align_threshold = 999 enum_discrim_align_threshold = 999
max_width = 256 # max_width = 512
chain_width = 50
fn_params_layout = "Vertical"
single_line_if_else_max_width = 25