first
This commit is contained in:
132
src-tauri/src/lib.rs
Normal file
132
src-tauri/src/lib.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
pub mod winget;
|
||||
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
use std::os::windows::process::CommandExt;
|
||||
use tokio::sync::mpsc;
|
||||
use tauri::{AppHandle, Manager, State, Emitter};
|
||||
use serde::Serialize;
|
||||
use winget::{Software, list_all_software, list_updates};
|
||||
|
||||
struct AppState {
|
||||
install_tx: mpsc::Sender<String>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn get_essentials(app: AppHandle) -> Vec<Software> {
|
||||
let app_data_dir = app.path().app_data_dir().unwrap_or_default();
|
||||
if !app_data_dir.exists() {
|
||||
let _ = fs::create_dir_all(&app_data_dir);
|
||||
}
|
||||
|
||||
let file_path = app_data_dir.join("setup-essentials.json");
|
||||
if !file_path.exists() {
|
||||
let default_essentials = vec![
|
||||
Software {
|
||||
id: "Microsoft.PowerToys".to_string(),
|
||||
name: "PowerToys".to_string(),
|
||||
description: Some("Microsoft PowerToys 是一组实用程序,供高级用户调整和简化其 Windows 10 和 11 体验。".to_string()),
|
||||
version: None,
|
||||
available_version: None,
|
||||
icon_url: Some("https://raw.githubusercontent.com/microsoft/PowerToys/master/doc/images/logo.png".to_string()),
|
||||
status: "idle".to_string(),
|
||||
progress: 0.0,
|
||||
},
|
||||
Software {
|
||||
id: "Google.Chrome".to_string(),
|
||||
name: "Google Chrome".to_string(),
|
||||
description: Some("Google Chrome 是一款快速、安全且免费的浏览器。".to_string()),
|
||||
version: None,
|
||||
available_version: None,
|
||||
icon_url: Some("https://www.google.com/chrome/static/images/chrome-logo.svg".to_string()),
|
||||
status: "idle".to_string(),
|
||||
progress: 0.0,
|
||||
}
|
||||
];
|
||||
let _ = fs::write(&file_path, serde_json::to_string_pretty(&default_essentials).unwrap());
|
||||
return default_essentials;
|
||||
}
|
||||
|
||||
let content = fs::read_to_string(file_path).unwrap_or_else(|_| "[]".to_string());
|
||||
serde_json::from_str(&content).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn get_all_software() -> Vec<Software> {
|
||||
tokio::task::spawn_blocking(move || list_all_software()).await.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn get_updates() -> Vec<Software> {
|
||||
tokio::task::spawn_blocking(move || list_updates()).await.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn install_software(id: String, state: State<'_, AppState>) -> Result<(), String> {
|
||||
state.install_tx.send(id).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
struct InstallProgress {
|
||||
id: String,
|
||||
status: String,
|
||||
progress: f32,
|
||||
}
|
||||
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.setup(move |app| {
|
||||
let handle = app.handle().clone();
|
||||
|
||||
// 在 setup 闭包中初始化,此时运行时已就绪
|
||||
let (tx, mut rx) = mpsc::channel::<String>(100);
|
||||
|
||||
// 托管状态
|
||||
app.manage(AppState { install_tx: tx });
|
||||
|
||||
// 后台安装队列
|
||||
tauri::async_runtime::spawn(async move {
|
||||
while let Some(id) = rx.recv().await {
|
||||
let _ = handle.emit("install-status", InstallProgress {
|
||||
id: id.clone(),
|
||||
status: "installing".to_string(),
|
||||
progress: 0.5,
|
||||
});
|
||||
|
||||
let id_for_cmd = id.clone();
|
||||
let status_result = tokio::task::spawn_blocking(move || {
|
||||
let output = Command::new("winget")
|
||||
.args([
|
||||
"install", "--id", &id_for_cmd, "-e", "--silent",
|
||||
"--accept-package-agreements", "--accept-source-agreements",
|
||||
"--disable-interactivity"
|
||||
])
|
||||
.creation_flags(0x08000000)
|
||||
.output();
|
||||
|
||||
match output {
|
||||
Ok(out) if out.status.success() => "success",
|
||||
_ => "error",
|
||||
}
|
||||
}).await.unwrap_or("error");
|
||||
|
||||
let _ = handle.emit("install-status", InstallProgress {
|
||||
id: id.clone(),
|
||||
status: status_result.to_string(),
|
||||
progress: 1.0,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
get_essentials,
|
||||
get_all_software,
|
||||
get_updates,
|
||||
install_software
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
6
src-tauri/src/main.rs
Normal file
6
src-tauri/src/main.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
win_softmgr_lib::run();
|
||||
}
|
||||
91
src-tauri/src/winget.rs
Normal file
91
src-tauri/src/winget.rs
Normal file
@@ -0,0 +1,91 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::process::Command;
|
||||
use std::os::windows::process::CommandExt;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Software {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub version: Option<String>,
|
||||
pub available_version: Option<String>,
|
||||
pub icon_url: Option<String>,
|
||||
pub status: String, // "idle", "pending", "installing", "success", "error"
|
||||
pub progress: f32,
|
||||
}
|
||||
|
||||
pub fn list_all_software() -> Vec<Software> {
|
||||
// winget list
|
||||
let output = Command::new("winget")
|
||||
.args(["list", "--accept-source-agreements"])
|
||||
.creation_flags(0x08000000) // CREATE_NO_WINDOW
|
||||
.output();
|
||||
|
||||
match output {
|
||||
Ok(out) => parse_winget_output(String::from_utf8_lossy(&out.stdout).to_string()),
|
||||
Err(_) => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_updates() -> Vec<Software> {
|
||||
// winget upgrade
|
||||
let output = Command::new("winget")
|
||||
.args(["upgrade", "--accept-source-agreements"])
|
||||
.creation_flags(0x08000000)
|
||||
.output();
|
||||
|
||||
match output {
|
||||
Ok(out) => parse_winget_output(String::from_utf8_lossy(&out.stdout).to_string()),
|
||||
Err(_) => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_winget_output(output: String) -> Vec<Software> {
|
||||
let mut softwares = Vec::new();
|
||||
let lines: Vec<&str> = output.lines().collect();
|
||||
|
||||
if lines.len() < 3 {
|
||||
return softwares;
|
||||
}
|
||||
|
||||
// 查找表头行以确定列偏移量
|
||||
// 通常格式: Name Id Version Available Source
|
||||
let header_idx = lines.iter().position(|l| l.contains("Id") && l.contains("Name")).unwrap_or(0);
|
||||
let header = lines[header_idx];
|
||||
|
||||
let id_pos = header.find("Id").unwrap_or(0);
|
||||
let version_pos = header.find("Version").unwrap_or(0);
|
||||
let available_pos = header.find("Available").unwrap_or(header.len());
|
||||
let source_pos = header.find("Source").unwrap_or(header.len());
|
||||
|
||||
for line in &lines[header_idx + 2..] {
|
||||
if line.trim().is_empty() || line.starts_with('-') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if line.len() < version_pos { continue; }
|
||||
|
||||
let name = line[..id_pos].trim().to_string();
|
||||
let id = line[id_pos..version_pos].trim().to_string();
|
||||
let version = line[version_pos..available_pos.min(line.len())].trim().to_string();
|
||||
|
||||
let available_version = if available_pos < line.len() {
|
||||
Some(line[available_pos..source_pos.min(line.len())].trim().to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
softwares.push(Software {
|
||||
id,
|
||||
name,
|
||||
description: None,
|
||||
version: Some(version),
|
||||
available_version,
|
||||
icon_url: None,
|
||||
status: "idle".to_string(),
|
||||
progress: 0.0,
|
||||
});
|
||||
}
|
||||
|
||||
softwares
|
||||
}
|
||||
Reference in New Issue
Block a user