diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index f2db091..0d7b4c5 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -6,7 +6,7 @@ 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}; +use winget::{Software, list_all_software, list_updates, ensure_winget_dependencies}; struct AppState { install_tx: mpsc::Sender, @@ -79,6 +79,13 @@ pub fn run() { .setup(move |app| { let handle = app.handle().clone(); + // 确保依赖项已安装 (这是一个耗时的过程,建议在异步任务中运行) + tauri::async_runtime::spawn(async move { + let _ = tokio::task::spawn_blocking(|| { + let _ = ensure_winget_dependencies(); + }).await; + }); + // 在 setup 闭包中初始化,此时运行时已就绪 let (tx, mut rx) = mpsc::channel::(100); diff --git a/src-tauri/src/winget.rs b/src-tauri/src/winget.rs index 1982ea1..3d46a94 100644 --- a/src-tauri/src/winget.rs +++ b/src-tauri/src/winget.rs @@ -14,78 +14,102 @@ pub struct Software { pub progress: f32, } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "PascalCase")] +struct WingetPackage { + pub id: String, + pub name: String, + pub installed_version: Option, + pub available_versions: Option>, +} + +pub fn ensure_winget_dependencies() -> Result<(), String> { + // 1. 检查 winget + let winget_check = Command::new("winget") + .arg("--version") + .creation_flags(0x08000000) + .status(); + + if winget_check.is_err() || !winget_check.unwrap().success() { + // 如果没有 winget,尝试安装 (这里简化处理,实际可能需要更复杂的脚本) + println!("Winget not found, attempting to install..."); + let _ = Command::new("powershell") + .args(["-Command", "Invoke-WebRequest -Uri https://github.com/microsoft/winget-cli/releases/latest/download/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle -OutFile ./winget.msixbundle; Add-AppxPackage ./winget.msixbundle; Remove-Item ./winget.msixbundle"]) + .creation_flags(0x08000000) + .status(); + } + + // 2. 检查 Microsoft.WinGet.Client 模块 + let module_check = Command::new("powershell") + .args(["-Command", "Get-Module -ListAvailable Microsoft.WinGet.Client"]) + .creation_flags(0x08000000) + .output(); + + if let Ok(out) = module_check { + if out.stdout.is_empty() { + println!("Microsoft.WinGet.Client module not found, installing..."); + let install_res = Command::new("powershell") + .args(["-Command", "Install-Module -Name Microsoft.WinGet.Client -Force -AllowClobber -Scope CurrentUser -ErrorAction SilentlyContinue"]) + .creation_flags(0x08000000) + .status(); + + if install_res.is_err() || !install_res.unwrap().success() { + return Err("Failed to install Microsoft.WinGet.Client module".to_string()); + } + } + } + + Ok(()) +} + pub fn list_all_software() -> Vec { - // winget list - let output = Command::new("winget") - .args(["list", "--accept-source-agreements"]) - .creation_flags(0x08000000) // CREATE_NO_WINDOW + // 使用 PowerShell 获取结构化 JSON + let output = Command::new("powershell") + .args(["-Command", "Get-WinGetPackage | Select-Object Name, Id, InstalledVersion, IsUpdateAvailable, AvailableVersions | ConvertTo-Json"]) + .creation_flags(0x08000000) .output(); match output { - Ok(out) => parse_winget_output(String::from_utf8_lossy(&out.stdout).to_string()), + Ok(out) => parse_json_output(String::from_utf8_lossy(&out.stdout).to_string()), Err(_) => vec![], } } pub fn list_updates() -> Vec { - // winget upgrade - let output = Command::new("winget") - .args(["upgrade", "--accept-source-agreements"]) + // 过滤出有更新的软件 + let output = Command::new("powershell") + .args(["-Command", "Get-WinGetPackage | Where-Object { $_.IsUpdateAvailable } | Select-Object Name, Id, InstalledVersion, IsUpdateAvailable, AvailableVersions | ConvertTo-Json"]) .creation_flags(0x08000000) .output(); match output { - Ok(out) => parse_winget_output(String::from_utf8_lossy(&out.stdout).to_string()), + Ok(out) => parse_json_output(String::from_utf8_lossy(&out.stdout).to_string()), Err(_) => vec![], } } -fn parse_winget_output(output: String) -> Vec { - let mut softwares = Vec::new(); - let lines: Vec<&str> = output.lines().collect(); - - if lines.len() < 3 { - return softwares; +fn parse_json_output(json_str: String) -> Vec { + if json_str.trim().is_empty() { + return vec![]; } - // 查找表头行以确定列偏移量 - // 通常格式: 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()); + // 处理单个对象或数组的情况 + let packages: Vec = if json_str.trim().starts_with('[') { + serde_json::from_str(&json_str).unwrap_or_default() + } else { + serde_json::from_str::(&json_str) + .map(|p| vec![p]) + .unwrap_or_default() + }; - 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 + packages.into_iter().map(|p| Software { + id: p.id, + name: p.name, + description: None, + version: p.installed_version, + available_version: p.available_versions.and_then(|v| v.first().cloned()), + icon_url: None, + status: "idle".to_string(), + progress: 0.0, + }).collect() } diff --git a/src/components/SoftwareCard.vue b/src/components/SoftwareCard.vue index 54f413e..ed26c8d 100644 --- a/src/components/SoftwareCard.vue +++ b/src/components/SoftwareCard.vue @@ -1,6 +1,6 @@