add logger

This commit is contained in:
Julian Freeman
2026-03-14 20:55:46 -04:00
parent db20a31643
commit cdeb52c316
8 changed files with 348 additions and 54 deletions

3
src-tauri/Cargo.lock generated
View File

@@ -451,8 +451,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0"
dependencies = [ dependencies = [
"iana-time-zone", "iana-time-zone",
"js-sys",
"num-traits", "num-traits",
"serde", "serde",
"wasm-bindgen",
"windows-link 0.2.1", "windows-link 0.2.1",
] ]
@@ -4620,6 +4622,7 @@ dependencies = [
name = "win-softmgr" name = "win-softmgr"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"chrono",
"serde", "serde",
"serde_json", "serde_json",
"tauri", "tauri",

View File

@@ -23,4 +23,5 @@ tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
tokio = { version = "1.50.0", features = ["full"] } tokio = { version = "1.50.0", features = ["full"] }
chrono = "0.4.44"

View File

@@ -12,6 +12,24 @@ struct AppState {
install_tx: mpsc::Sender<String>, install_tx: mpsc::Sender<String>,
} }
#[derive(Clone, Serialize)]
pub struct LogPayload {
pub timestamp: String,
pub command: String,
pub output: String,
pub status: String, // "info", "success", "error"
}
pub fn emit_log(handle: &AppHandle, command: &str, output: &str, status: &str) {
let now = chrono::Local::now().format("%H:%M:%S").to_string();
let _ = handle.emit("log-event", LogPayload {
timestamp: now,
command: command.to_string(),
output: output.to_string(),
status: status.to_string(),
});
}
#[tauri::command] #[tauri::command]
fn get_essentials(app: AppHandle) -> Vec<Software> { fn get_essentials(app: AppHandle) -> Vec<Software> {
let app_data_dir = app.path().app_data_dir().unwrap_or_default(); let app_data_dir = app.path().app_data_dir().unwrap_or_default();
@@ -28,12 +46,12 @@ fn get_essentials(app: AppHandle) -> Vec<Software> {
description: Some("Microsoft PowerToys 是一组实用程序,供高级用户调整和简化其 Windows 10 和 11 体验。".to_string()), description: Some("Microsoft PowerToys 是一组实用程序,供高级用户调整和简化其 Windows 10 和 11 体验。".to_string()),
version: None, version: None,
available_version: None, available_version: None,
icon_url: Some("https://raw.githubusercontent.com/microsoft/PowerToys/main/doc/images/icons/PowerToys icon/PNG/PowerToysAppList.targetsize-48.png".to_string()), icon_url: Some("https://raw.githubusercontent.com/microsoft/PowerToys/master/doc/images/logo.png".to_string()),
status: "idle".to_string(), status: "idle".to_string(),
progress: 0.0, progress: 0.0,
}, },
Software { Software {
id: "Google.Chrome.EXE".to_string(), id: "Google.Chrome".to_string(),
name: "Google Chrome".to_string(), name: "Google Chrome".to_string(),
description: Some("Google Chrome 是一款快速、安全且免费的浏览器。".to_string()), description: Some("Google Chrome 是一款快速、安全且免费的浏览器。".to_string()),
version: None, version: None,
@@ -52,13 +70,13 @@ fn get_essentials(app: AppHandle) -> Vec<Software> {
} }
#[tauri::command] #[tauri::command]
async fn get_all_software() -> Vec<Software> { async fn get_all_software(app: AppHandle) -> Vec<Software> {
tokio::task::spawn_blocking(move || list_all_software()).await.unwrap_or_default() tokio::task::spawn_blocking(move || list_all_software(&app)).await.unwrap_or_default()
} }
#[tauri::command] #[tauri::command]
async fn get_updates() -> Vec<Software> { async fn get_updates(app: AppHandle) -> Vec<Software> {
tokio::task::spawn_blocking(move || list_updates()).await.unwrap_or_default() tokio::task::spawn_blocking(move || list_updates(&app)).await.unwrap_or_default()
} }
#[tauri::command] #[tauri::command]
@@ -66,6 +84,12 @@ async fn install_software(id: String, state: State<'_, AppState>) -> Result<(),
state.install_tx.send(id).await.map_err(|e| e.to_string()) state.install_tx.send(id).await.map_err(|e| e.to_string())
} }
#[tauri::command]
fn get_logs_history() -> Vec<LogPayload> {
// 暂时返回空,后续可以考虑存储
vec![]
}
#[derive(Clone, Serialize)] #[derive(Clone, Serialize)]
struct InstallProgress { struct InstallProgress {
id: String, id: String,
@@ -78,21 +102,18 @@ pub fn run() {
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.setup(move |app| { .setup(move |app| {
let handle = app.handle().clone(); let handle = app.handle().clone();
let (tx, mut rx) = mpsc::channel::<String>(100);
app.manage(AppState { install_tx: tx });
// 确保依赖项已安装 (这是一个耗时的过程,建议在异步任务中运行) // 环境初始化逻辑
let init_handle = handle.clone();
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
let _ = tokio::task::spawn_blocking(|| { let _ = tokio::task::spawn_blocking(move || {
let _ = ensure_winget_dependencies(); let _ = ensure_winget_dependencies(&init_handle);
}).await; }).await;
}); });
// 在 setup 闭包中初始化,此时运行时已就绪 // 安装队列
let (tx, mut rx) = mpsc::channel::<String>(100);
// 托管状态
app.manage(AppState { install_tx: tx });
// 后台安装队列
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
while let Some(id) = rx.recv().await { while let Some(id) = rx.recv().await {
let _ = handle.emit("install-status", InstallProgress { let _ = handle.emit("install-status", InstallProgress {
@@ -101,7 +122,10 @@ pub fn run() {
progress: 0.5, progress: 0.5,
}); });
emit_log(&handle, &format!("winget install --id {}", id), "Starting installation...", "info");
let id_for_cmd = id.clone(); let id_for_cmd = id.clone();
let h = handle.clone();
let status_result = tokio::task::spawn_blocking(move || { let status_result = tokio::task::spawn_blocking(move || {
let output = Command::new("winget") let output = Command::new("winget")
.args([ .args([
@@ -113,8 +137,16 @@ pub fn run() {
.output(); .output();
match output { match output {
Ok(out) if out.status.success() => "success", Ok(out) => {
_ => "error", let msg = String::from_utf8_lossy(&out.stdout).to_string();
let err = String::from_utf8_lossy(&out.stderr).to_string();
emit_log(&h, &format!("Install result for {}", id_for_cmd), &format!("OUT: {}\nERR: {}", msg, err), if out.status.success() { "success" } else { "error" });
if out.status.success() { "success" } else { "error" }
},
Err(e) => {
emit_log(&h, &format!("Install error for {}", id_for_cmd), &e.to_string(), "error");
"error"
},
} }
}).await.unwrap_or("error"); }).await.unwrap_or("error");
@@ -132,7 +164,8 @@ pub fn run() {
get_essentials, get_essentials,
get_all_software, get_all_software,
get_updates, get_updates,
install_software install_software,
get_logs_history
]) ])
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while running tauri application");

View File

@@ -1,6 +1,8 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::process::Command; use std::process::Command;
use std::os::windows::process::CommandExt; use std::os::windows::process::CommandExt;
use tauri::AppHandle;
use crate::emit_log;
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Software { pub struct Software {
@@ -23,30 +25,60 @@ struct WingetPackage {
pub available_versions: Option<Vec<String>>, pub available_versions: Option<Vec<String>>,
} }
pub fn ensure_winget_dependencies() -> Result<(), String> { pub fn ensure_winget_dependencies(handle: &AppHandle) -> Result<(), String> {
// 确保执行权限和模块存在 emit_log(handle, "Check Environment", "Checking Winget and Microsoft.WinGet.Client...", "info");
let setup_script = r#" let setup_script = r#"
$ErrorActionPreference = 'SilentlyContinue' $ErrorActionPreference = 'Stop'
Write-Output "Step 1: Enabling TLS 1.2"
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
Write-Output "Step 2: Installing NuGet provider"
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Confirm:$false
Write-Output "Step 3: Trusting PSGallery"
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
Write-Output "Step 4: Setting Execution Policy"
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
if (-not (Get-Module -ListAvailable Microsoft.WinGet.Client)) { if (-not (Get-Module -ListAvailable Microsoft.WinGet.Client)) {
Install-Module -Name Microsoft.WinGet.Client -Force -AllowClobber -Scope CurrentUser Write-Output "Step 5: Installing Microsoft.WinGet.Client module"
Install-Module -Name Microsoft.WinGet.Client -Force -AllowClobber -Scope CurrentUser -Confirm:$false
} else {
Write-Output "Step 5: Module already installed"
} }
"#; "#;
let _ = Command::new("powershell") let output = Command::new("powershell")
.args(["-NoProfile", "-Command", setup_script]) .args(["-NoProfile", "-Command", setup_script])
.creation_flags(0x08000000) .creation_flags(0x08000000)
.status(); .output();
match output {
Ok(out) => {
let msg = String::from_utf8_lossy(&out.stdout).to_string();
let err = String::from_utf8_lossy(&out.stderr).to_string();
if out.status.success() {
emit_log(handle, "Environment Setup", &format!("Success: {}", msg), "success");
Ok(()) Ok(())
} else {
emit_log(handle, "Environment Setup Error", &format!("OUT: {}\nERR: {}", msg, err), "error");
Err(format!("Setup failed: {}", err))
}
},
Err(e) => {
emit_log(handle, "Environment Setup Fatal", &e.to_string(), "error");
Err(e.to_string())
}
}
} }
pub fn list_all_software() -> Vec<Software> { pub fn list_all_software(handle: &AppHandle) -> Vec<Software> {
// 使用更健壮的脚本获取 JSON
let script = r#" let script = r#"
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = 'SilentlyContinue' $ErrorActionPreference = 'SilentlyContinue'
Import-Module Microsoft.WinGet.Client -ErrorAction SilentlyContinue Import-Module Microsoft.WinGet.Client
$pkgs = Get-WinGetPackage $pkgs = Get-WinGetPackage
if ($pkgs) { if ($pkgs) {
$pkgs | ForEach-Object { $pkgs | ForEach-Object {
@@ -62,14 +94,14 @@ pub fn list_all_software() -> Vec<Software> {
} }
"#; "#;
execute_powershell(script) execute_powershell(handle, "Get All Software", script)
} }
pub fn list_updates() -> Vec<Software> { pub fn list_updates(handle: &AppHandle) -> Vec<Software> {
let script = r#" let script = r#"
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = 'SilentlyContinue' $ErrorActionPreference = 'SilentlyContinue'
Import-Module Microsoft.WinGet.Client -ErrorAction SilentlyContinue Import-Module Microsoft.WinGet.Client
$pkgs = Get-WinGetPackage | Where-Object { $_.IsUpdateAvailable } $pkgs = Get-WinGetPackage | Where-Object { $_.IsUpdateAvailable }
if ($pkgs) { if ($pkgs) {
$pkgs | ForEach-Object { $pkgs | ForEach-Object {
@@ -85,10 +117,12 @@ pub fn list_updates() -> Vec<Software> {
} }
"#; "#;
execute_powershell(script) execute_powershell(handle, "Get Updates", script)
} }
fn execute_powershell(script: &str) -> Vec<Software> { fn execute_powershell(handle: &AppHandle, cmd_name: &str, script: &str) -> Vec<Software> {
emit_log(handle, cmd_name, "Executing PowerShell script...", "info");
let output = Command::new("powershell") let output = Command::new("powershell")
.args(["-NoProfile", "-Command", script]) .args(["-NoProfile", "-Command", script])
.creation_flags(0x08000000) .creation_flags(0x08000000)
@@ -97,29 +131,37 @@ fn execute_powershell(script: &str) -> Vec<Software> {
match output { match output {
Ok(out) => { Ok(out) => {
let stdout = String::from_utf8_lossy(&out.stdout); let stdout = String::from_utf8_lossy(&out.stdout);
// 移除可能存在的 UTF-8 BOM let stderr = String::from_utf8_lossy(&out.stderr);
let clean_json = stdout.trim_start_matches('\u{feff}').trim(); let clean_json = stdout.trim_start_matches('\u{feff}').trim();
parse_json_output(clean_json.to_string())
},
Err(_) => vec![],
}
}
fn parse_json_output(json_str: String) -> Vec<Software> { if !out.status.success() || !stderr.is_empty() {
if json_str.is_empty() || json_str == "[]" { emit_log(handle, &format!("{} stderr", cmd_name), &stderr, "error");
}
if clean_json.is_empty() || clean_json == "[]" {
emit_log(handle, cmd_name, "No software found (Empty JSON)", "info");
return vec![]; return vec![];
} }
// 尝试解析数组 let result = parse_json_output(clean_json.to_string());
emit_log(handle, cmd_name, &format!("Success: found {} items", result.len()), "success");
result
},
Err(e) => {
emit_log(handle, cmd_name, &format!("Execution error: {}", e), "error");
vec![]
},
}
}
// 修正Rust 并没有 .length(),应使用 .len()
fn parse_json_output(json_str: String) -> Vec<Software> {
if let Ok(packages) = serde_json::from_str::<Vec<WingetPackage>>(&json_str) { if let Ok(packages) = serde_json::from_str::<Vec<WingetPackage>>(&json_str) {
return packages.into_iter().map(map_package).collect(); return packages.into_iter().map(map_package).collect();
} }
// 尝试解析单个对象
if let Ok(package) = serde_json::from_str::<WingetPackage>(&json_str) { if let Ok(package) = serde_json::from_str::<WingetPackage>(&json_str) {
return vec![map_package(package)]; return vec![map_package(package)];
} }
vec![] vec![]
} }

View File

@@ -33,6 +33,20 @@
</span> </span>
全部软件 全部软件
</router-link> </router-link>
<!-- 底部日志选项 -->
<router-link to="/logs" class="nav-item nav-logs">
<span class="nav-icon">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
</span>
运行日志
</router-link>
</nav> </nav>
</div> </div>
</template> </template>
@@ -59,6 +73,7 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 8px; gap: 8px;
flex: 1; /* 撑满空间 */
} }
.nav-item { .nav-item {
@@ -90,4 +105,9 @@
align-items: center; align-items: center;
justify-content: center; justify-content: center;
} }
.nav-logs {
margin-top: auto; /* 将日志推到底部 */
margin-bottom: 20px;
}
</style> </style>

View File

@@ -18,6 +18,10 @@ const router = createRouter({
{ {
path: '/all', path: '/all',
component: () => import('../views/AllSoftware.vue') component: () => import('../views/AllSoftware.vue')
},
{
path: '/logs',
component: () => import('../views/Logs.vue')
} }
] ]
}) })

View File

@@ -4,6 +4,13 @@ import { listen } from '@tauri-apps/api/event'
const sortByName = (a: any, b: any) => a.name.localeCompare(b.name, 'zh-CN', { sensitivity: 'accent' }); const sortByName = (a: any, b: any) => a.name.localeCompare(b.name, 'zh-CN', { sensitivity: 'accent' });
export interface LogEntry {
timestamp: string;
command: string;
output: string;
status: 'info' | 'success' | 'error';
}
export const useSoftwareStore = defineStore('software', { export const useSoftwareStore = defineStore('software', {
state: () => ({ state: () => ({
essentials: [] as any[], essentials: [] as any[],
@@ -11,6 +18,7 @@ export const useSoftwareStore = defineStore('software', {
allSoftware: [] as any[], allSoftware: [] as any[],
selectedEssentialIds: [] as string[], selectedEssentialIds: [] as string[],
selectedUpdateIds: [] as string[], selectedUpdateIds: [] as string[],
logs: [] as LogEntry[],
loading: false, loading: false,
lastFetched: 0 lastFetched: 0
}), }),
@@ -39,15 +47,11 @@ export const useSoftwareStore = defineStore('software', {
sortedAllSoftware: (state) => [...state.allSoftware].sort(sortByName) sortedAllSoftware: (state) => [...state.allSoftware].sort(sortByName)
}, },
actions: { actions: {
// 通用的勾选切换逻辑
toggleSelection(id: string, type: 'essential' | 'update') { toggleSelection(id: string, type: 'essential' | 'update') {
const list = type === 'essential' ? this.selectedEssentialIds : this.selectedUpdateIds; const list = type === 'essential' ? this.selectedEssentialIds : this.selectedUpdateIds;
const index = list.indexOf(id); const index = list.indexOf(id);
if (index === -1) { if (index === -1) list.push(id);
list.push(id); else list.splice(index, 1);
} else {
list.splice(index, 1);
}
}, },
selectAll(type: 'essential' | 'update') { selectAll(type: 'essential' | 'update') {
if (type === 'essential') { if (type === 'essential') {
@@ -79,7 +83,6 @@ export const useSoftwareStore = defineStore('software', {
try { try {
const res = await invoke('get_updates') const res = await invoke('get_updates')
this.updates = res as any[] this.updates = res as any[]
// 刷新数据后,如果没选过,默认全选
if (this.selectedUpdateIds.length === 0) this.selectAll('update'); if (this.selectedUpdateIds.length === 0) this.selectAll('update');
} finally { } finally {
this.loading = false this.loading = false
@@ -115,7 +118,6 @@ export const useSoftwareStore = defineStore('software', {
this.allSoftware = all as any[]; this.allSoftware = all as any[];
this.updates = updates as any[]; this.updates = updates as any[];
this.lastFetched = Date.now(); this.lastFetched = Date.now();
// 如果没选过,默认全选
if (this.selectedEssentialIds.length === 0) this.selectAll('essential'); if (this.selectedEssentialIds.length === 0) this.selectAll('essential');
} finally { } finally {
this.loading = false; this.loading = false;
@@ -144,11 +146,17 @@ export const useSoftwareStore = defineStore('software', {
} }
if (status === 'success') { if (status === 'success') {
this.lastFetched = 0; this.lastFetched = 0;
// 安装成功后从选择列表中移除
this.selectedEssentialIds = this.selectedEssentialIds.filter(i => i !== id); this.selectedEssentialIds = this.selectedEssentialIds.filter(i => i !== id);
this.selectedUpdateIds = this.selectedUpdateIds.filter(i => i !== id); this.selectedUpdateIds = this.selectedUpdateIds.filter(i => i !== id);
} }
}) })
// 监听日志事件
listen('log-event', (event: any) => {
this.logs.unshift(event.payload as LogEntry);
// 限制日志条数,防止内存溢出
if (this.logs.length > 200) this.logs.pop();
})
} }
} }
}) })

183
src/views/Logs.vue Normal file
View File

@@ -0,0 +1,183 @@
<template>
<main class="content">
<header class="content-header">
<div class="header-left">
<h1>运行日志</h1>
<p class="count">记录应用最近执行的命令和结果</p>
</div>
<div class="header-actions">
<button @click="store.logs = []" class="secondary-btn action-btn">
清空日志
</button>
</div>
</header>
<div v-if="store.logs.length === 0" class="empty-state">
<span class="empty-icon">📝</span>
<p>暂无操作记录</p>
</div>
<div v-else class="log-list">
<div v-for="(log, index) in store.logs" :key="index" class="log-item" :class="log.status">
<div class="log-header">
<span class="timestamp">[{{ log.timestamp }}]</span>
<span class="command">{{ log.command }}</span>
<span class="status-badge">{{ log.status.toUpperCase() }}</span>
</div>
<pre class="log-output">{{ log.output }}</pre>
</div>
</div>
</main>
</template>
<script setup lang="ts">
import { useSoftwareStore } from '../store/software';
import { onMounted } from 'vue';
const store = useSoftwareStore();
onMounted(() => {
store.initListener();
});
</script>
<style scoped>
.content {
flex: 1;
padding: 40px 60px;
overflow-y: auto;
background-color: var(--bg-light);
}
.content-header {
display: flex;
justify-content: space-between;
align-items: flex-end;
margin-bottom: 30px;
}
.header-left h1 {
font-size: 32px;
font-weight: 700;
color: var(--text-main);
}
.header-left .count {
font-size: 14px;
color: var(--text-sec);
margin-top: 4px;
}
.header-actions {
display: flex;
gap: 12px;
}
.action-btn {
padding: 8px 16px;
border-radius: 10px;
font-weight: 600;
font-size: 13px;
cursor: pointer;
transition: all 0.2s ease;
border: 1px solid var(--border-color);
background-color: white;
color: var(--text-main);
}
.action-btn:hover {
background-color: #FFF5F5;
border-color: #FF3B30;
color: #FF3B30;
}
.log-list {
display: flex;
flex-direction: column;
gap: 16px;
padding-bottom: 40px;
}
.log-item {
background: white;
border-radius: 16px;
padding: 16px;
box-shadow: var(--card-shadow);
border: 1px solid transparent;
transition: all 0.2s ease;
}
.log-item.error {
border-left: 4px solid #FF3B30;
background-color: #FFF9F9;
}
.log-item.success {
border-left: 4px solid #34C759;
}
.log-item.info {
border-left: 4px solid var(--primary-color);
}
.log-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 12px;
}
.timestamp {
font-family: monospace;
color: var(--text-sec);
font-size: 13px;
}
.command {
font-weight: 700;
color: var(--text-main);
font-size: 14px;
flex: 1;
}
.status-badge {
font-size: 10px;
font-weight: 800;
padding: 2px 8px;
border-radius: 6px;
background: var(--bg-light);
}
.error .status-badge { color: #FF3B30; background: #FFE5E5; }
.success .status-badge { color: #34C759; background: #E5F9E5; }
.info .status-badge { color: var(--primary-color); background: #E5F0FF; }
.log-output {
margin: 0;
padding: 12px;
background: #1D1D1F;
color: #F5F5F7;
border-radius: 8px;
font-family: 'Cascadia Code', 'Fira Code', monospace;
font-size: 12px;
line-height: 1.5;
overflow-x: auto;
white-space: pre-wrap;
max-height: 200px;
overflow-y: auto;
}
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 300px;
color: var(--text-sec);
}
.empty-icon {
font-size: 48px;
margin-bottom: 16px;
}
</style>