diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 42014a6..0307115 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -98,13 +98,12 @@ jobs: } $bytes = [System.IO.File]::ReadAllBytes((Resolve-Path $exe)) $text = [System.Text.Encoding]::UTF8.GetString($bytes) - if ($text -notmatch 'requestedExecutionLevel level="asInvoker"') { Write-Error 'asInvoker manifest missing'; exit 1 } - if ($text -match 'requireAdministrator') { Write-Error 'the executable requests elevation'; exit 1 } + if ($text -notmatch 'requestedExecutionLevel level="requireAdministrator"') { Write-Error 'requireAdministrator manifest missing'; exit 1 } if ($text -match 'VCRUNTIME140') { Write-Error 'the C runtime is not linked statically'; exit 1 } if ($text.Contains($env:USERPROFILE) -or $text.Contains($env:GITHUB_WORKSPACE)) { Write-Error 'build machine paths are embedded'; exit 1 } $pe = [BitConverter]::ToInt32($bytes, 0x3C) if ([BitConverter]::ToUInt32($bytes, $pe + 24 + 64) -eq 0) { Write-Error 'the PE checksum is not set'; exit 1 } - Write-Output "OK: $($info.ProductName) $($info.ProductVersion) by $($info.CompanyName), runs as invoker" + Write-Output "OK: $($info.ProductName) $($info.ProductVersion) by $($info.CompanyName), requests elevation on launch" - name: Save cargo registry & build if: github.event_name == 'push' && steps.cargo-cache.outputs.cache-hit != 'true' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0ade379..c48f971 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -155,6 +155,20 @@ jobs: BULLET_REQUIRE_LTK: "1" run: cargo xtask package + - name: Verify private LTK module linked into dist/bullet.exe + shell: pwsh + run: | + foreach ($f in @("dist/bullet.exe", "dist/tools/bullet_launcher.exe", "dist/tools/bullet_bridge.dll")) { + if (-not (Test-Path $f)) { throw "Missing required packaged artifact: $f" } + } + $text = [System.Text.Encoding]::ASCII.GetString([System.IO.File]::ReadAllBytes("dist/bullet.exe")) + foreach ($marker in @("bullet_launcher.exe", "ltk-manager.exe")) { + if (-not $text.Contains($marker)) { + throw "dist/bullet.exe is missing private LTK marker '$marker' (public stub was compiled)" + } + } + Write-Host "Verified dist/bullet.exe contains private LTK bridge module and tools" + - name: Build installer around that binary (cargo xtask installer --prebuilt) run: cargo xtask installer --prebuilt diff --git a/Cargo.lock b/Cargo.lock index f837b2a..74cd2fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -925,9 +925,9 @@ dependencies = [ [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] @@ -1559,9 +1559,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -5512,9 +5512,9 @@ checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/README.md b/README.md index 38703fb..1da2ee9 100644 --- a/README.md +++ b/README.md @@ -51,12 +51,6 @@ Download [`Bullet-Setup-x64.exe`](https://github.com/Isllanrx/Bullet/releases/la irm https://raw.githubusercontent.com/Isllanrx/Bullet/main/install.ps1 | iex ``` -Or install with Cargo: - -```powershell -cargo install --git https://github.com/Isllanrx/Bullet.git bullet-app --locked -``` - ### macOS (Intel `x86_64` & Apple Silicon) Run in **Terminal**: @@ -89,7 +83,7 @@ Inside our Discord server: **[discord.gg/e2dH2nUjd9](https://discord.gg/e2dH2nUj No. Overlays are built separately and loaded in memory at match start. Your game files stay untouched. **Does it require Administrator privileges or Pengu Loader?** -No. On Windows it runs as a standard user (`asInvoker`) and does not use Pengu Loader. +On Windows, Bullet asks for Administrator permission once on launch so switching between Window and Native In-Client modes never interrupts you with repeated UAC prompts. It does not use Pengu Loader. **Can other players see my skin?** Only locally, unless you and your friends enable **Party Mode** inside Bullet. diff --git a/crates/bullet-app/build.rs b/crates/bullet-app/build.rs index 7b967b0..f34c710 100644 --- a/crates/bullet-app/build.rs +++ b/crates/bullet-app/build.rs @@ -51,7 +51,7 @@ fn main() { - + diff --git a/crates/bullet-app/src/boot/startup/injector.rs b/crates/bullet-app/src/boot/startup/injector.rs index 5af0807..563bb1a 100644 --- a/crates/bullet-app/src/boot/startup/injector.rs +++ b/crates/bullet-app/src/boot/startup/injector.rs @@ -90,7 +90,21 @@ fn warn_if_manager_outdated(text: &bullet_platform::i18n::Text) { bullet_platform::shell::message_box_warning(text.manager_outdated_title, &body); } ManagerInstallState::Missing => { - warn!("Mod Manager is not installed on this PC"); + let desktop_roaming = bullet_platform::user_profile::local_app_data() + .ok() + .and_then(|p| p.parent().map(|a| a.join("Roaming"))); + let appdata_exists = desktop_roaming + .into_iter() + .chain(std::env::var("APPDATA").ok().map(std::path::PathBuf::from)) + .any(|dir| dir.join("dev.leaguetoolkit.manager").is_dir()); + let env_override = std::env::var("BULLET_LTK_MANAGER") + .or_else(|_| std::env::var("LTK_MANAGER_EXE")) + .ok(); + warn!( + appdata_profile_exists = appdata_exists, + env_override_set = env_override.is_some(), + "Mod Manager (ltk-manager.exe) was not found on this PC" + ); bullet_platform::shell::message_box_warning( text.manager_missing_title, text.manager_missing_body, diff --git a/crates/bullet-app/src/boot/tray/mod.rs b/crates/bullet-app/src/boot/tray/mod.rs index 83c49da..0b18c0d 100644 --- a/crates/bullet-app/src/boot/tray/mod.rs +++ b/crates/bullet-app/src/boot/tray/mod.rs @@ -1,2 +1,3 @@ pub mod panel; +pub mod repair; pub mod tasks; diff --git a/crates/bullet-app/src/boot/tray/panel.rs b/crates/bullet-app/src/boot/tray/panel.rs index f5122b8..fb35f36 100644 --- a/crates/bullet-app/src/boot/tray/panel.rs +++ b/crates/bullet-app/src/boot/tray/panel.rs @@ -49,6 +49,7 @@ pub fn tray_status( pub struct ReleaseNotices { pub bullet: bullet_app::update_check::UpdateNotice, pub custom_mods: bullet_app::mod_repair::CustomModsNotice, + pub repair: bullet_app::control_panel::RepairState, } pub fn panel_links_for( @@ -110,6 +111,7 @@ pub fn panel_links_for( .ok() .map(|dir| bullet_app::stats::load_summary(&dir)) .unwrap_or_default(), + repair: notices.repair.snapshot(), }; let snapshot = bullet_app::control_panel::snapshot(&facts, bullet_platform::i18n::text()); let failing: Vec = snapshot @@ -149,6 +151,8 @@ pub struct TrayActions { pub links: bullet_platform::panel::PanelLinks, pub mark_state: bullet_core::state::StateReceiver, pub mark_live: bullet_app::live_game::LiveGame, + pub custom_mods: bullet_app::mod_repair::CustomModsNotice, + pub repair: bullet_app::control_panel::RepairState, } impl TrayActions { @@ -310,25 +314,20 @@ impl TrayActions { } } bullet_platform::tray::TrayEvent::RepairSkins => { - let mods = self.mods_dir.clone(); - let state = self.state_dir.clone(); - let game = bullet_platform::paths::discover_game_dir().unwrap_or_default(); - drop(tokio::task::spawn_blocking(move || { - let report = - bullet_app::control_panel::repair_skins_and_mods(&mods, &state, &game); - info!( - repaired = report.repaired.len(), - incompatible = report.incompatible.len(), - "Manual skin and mod repair completed" - ); - })); + super::repair::spawn_repair_skins( + self.repair.clone(), + self.custom_mods.clone(), + self.mod_roots.clone(), + self.state_dir.clone(), + self.notifier.clone(), + ); } bullet_platform::tray::TrayEvent::RepairClient => { - let state = self.state_dir.clone(); - drop(tokio::task::spawn_blocking(move || { - bullet_app::control_panel::repair_client(&state); - info!("Manual client and Bullet cache repair completed"); - })); + super::repair::spawn_repair_client( + self.repair.clone(), + self.state_dir.clone(), + self.notifier.clone(), + ); } bullet_platform::tray::TrayEvent::OpenRelease => { let page = bullet_app::update_check::release_page(); diff --git a/crates/bullet-app/src/boot/tray/repair.rs b/crates/bullet-app/src/boot/tray/repair.rs new file mode 100644 index 0000000..dbfd653 --- /dev/null +++ b/crates/bullet-app/src/boot/tray/repair.rs @@ -0,0 +1,65 @@ +use std::path::PathBuf; + +use tracing::info; + +pub fn spawn_repair_skins( + repair_state: bullet_app::control_panel::RepairState, + custom_mods: bullet_app::mod_repair::CustomModsNotice, + mod_roots: Vec, + state_dir: PathBuf, + notifier: bullet_platform::tray::TrayController, +) { + let text = bullet_platform::i18n::text(); + if !repair_state.begin_skins(text.panel_repair_skins_running) { + return; + } + bullet_platform::panel::refresh_open_panel(); + let game = bullet_platform::paths::discover_game_dir().unwrap_or_default(); + drop(tokio::task::spawn_blocking(move || { + let report = + bullet_app::control_panel::repair_skins_and_mods(&mod_roots, &state_dir, &game); + if let Some(totals) = report.totals { + custom_mods.set(totals); + } + info!( + cleared = report.cleared_generated, + checked = report.checked, + repaired = report.repaired, + incompatible = report.incompatible, + game_found = report.game_found, + "Manual skin and mod repair completed" + ); + let t = bullet_platform::i18n::text(); + let (ok, message) = bullet_app::control_panel::format_skins_feedback(&report, t); + repair_state.finish_skins(ok, message.clone()); + bullet_platform::panel::refresh_open_panel(); + notifier.notify(t.panel_repair_skins, &message); + })); +} + +pub fn spawn_repair_client( + repair_state: bullet_app::control_panel::RepairState, + state_dir: PathBuf, + notifier: bullet_platform::tray::TrayController, +) { + let text = bullet_platform::i18n::text(); + if !repair_state.begin_client(text.panel_repair_client_running) { + return; + } + bullet_platform::panel::refresh_open_panel(); + drop(tokio::task::spawn_blocking(move || { + let report = bullet_app::control_panel::repair_client(&state_dir); + info!( + cleared_caches = report.cleared_caches, + stopped_processes = report.stopped_processes, + reset_bridge = report.reset_bridge, + warnings = report.warnings.len(), + "Manual client and Bullet cache repair completed" + ); + let t = bullet_platform::i18n::text(); + let (ok, message) = bullet_app::control_panel::format_client_feedback(&report, t); + repair_state.finish_client(ok, message.clone()); + bullet_platform::panel::refresh_open_panel(); + notifier.notify(t.panel_repair_client, &message); + })); +} diff --git a/crates/bullet-app/src/diagnostics/control_panel/mod.rs b/crates/bullet-app/src/diagnostics/control_panel/mod.rs index 5cdac4a..da9f871 100644 --- a/crates/bullet-app/src/diagnostics/control_panel/mod.rs +++ b/crates/bullet-app/src/diagnostics/control_panel/mod.rs @@ -6,8 +6,14 @@ use bullet_platform::panel::{PanelCheck, PanelSnapshot}; mod export; mod redact; +mod repair; pub use export::export_diagnostics; +pub use repair::{ + REPAIR_STATE_BUSY, REPAIR_STATE_ERROR, REPAIR_STATE_IDLE, REPAIR_STATE_OK, RepairClientReport, + RepairSkinsReport, RepairState, format_client_feedback, format_skins_feedback, repair_client, + repair_skins_and_mods, +}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum ManagerStatus { @@ -35,6 +41,7 @@ pub struct Facts { pub update: Option, pub custom_mods: Option, pub stats: bullet_platform::panel::PanelStats, + pub repair: bullet_platform::panel::PanelRepair, } #[must_use] @@ -96,6 +103,7 @@ pub fn snapshot(facts: &Facts, text: &Text) -> PanelSnapshot { ) }), stats: facts.stats.clone(), + repair: facts.repair.clone(), checks: vec![ check( text.check_injector, @@ -173,56 +181,5 @@ pub fn tools_present(files: &[PathBuf]) -> bool { files.iter().all(|file| file.is_file()) } -pub fn repair_skins_and_mods( - mods_dir: &std::path::Path, - state_dir: &std::path::Path, - game_dir: &std::path::Path, -) -> crate::mod_repair::RepairReport { - let _ = std::fs::remove_file(state_dir.join("mod_repair.json")); // ignore-ok: force fresh repair scan - if let Ok(data_dir) = bullet_platform::paths::data_dir() { - let generated_dir = data_dir.join("mods"); - if let Ok(entries) = std::fs::read_dir(&generated_dir) { - for entry in entries.flatten() { - let name = entry.file_name(); - if let Some(s) = name.to_str() { - if s.starts_with("std_") || s == "bullet_loading_name" { - let _ = std::fs::remove_dir_all(entry.path()); // ignore-ok: clear cached generated skin mod - } - } - } - } - } - let resolved_game = bullet_platform::paths::normalize_game_dir(game_dir) - .or_else(bullet_platform::paths::discover_game_dir) - .unwrap_or_else(|| game_dir.to_path_buf()); - crate::mod_repair::repair_custom_mods( - &[mods_dir.to_path_buf()], - &resolved_game, - state_dir, - &|| false, - ) -} - -pub fn repair_client(state_dir: &std::path::Path) { - if let Ok(data_dir) = bullet_platform::paths::data_dir() { - for sub in ["staging", "overlay"] { - let _ = std::fs::remove_dir_all(data_dir.join(sub)); // ignore-ok: clear transient overlay/staging cache - } - } - let _ = std::fs::remove_file(state_dir.join("ltf_journal.json")); // ignore-ok: clear stale journal - #[cfg(windows)] - if let Ok(Some(pid)) = bullet_platform::process::ProcessFinder::find_any_process(&[ - "ltk-manager.exe", - "LTK Manager.exe", - ]) { - let _ = bullet_platform::process::terminate_process(pid); // ignore-ok: restart stalled mod manager - } - if let Ok(local_app) = std::env::var("LOCALAPPDATA") { - let bridge_dir = std::path::PathBuf::from(local_app).join("BulletBridge"); - let _ = std::fs::remove_file(bridge_dir.join("port.txt")); // ignore-ok: reset bridge discovery - let _ = std::fs::remove_file(bridge_dir.join("token.txt")); // ignore-ok: reset bridge token - } -} - #[cfg(test)] mod tests; diff --git a/crates/bullet-app/src/diagnostics/control_panel/repair.rs b/crates/bullet-app/src/diagnostics/control_panel/repair.rs new file mode 100644 index 0000000..085030e --- /dev/null +++ b/crates/bullet-app/src/diagnostics/control_panel/repair.rs @@ -0,0 +1,299 @@ +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use bullet_platform::i18n::{Text, fill}; +use bullet_platform::panel::PanelRepair; + +pub const REPAIR_STATE_IDLE: u8 = 0; +pub const REPAIR_STATE_BUSY: u8 = 1; +pub const REPAIR_STATE_OK: u8 = 2; +pub const REPAIR_STATE_ERROR: u8 = 3; + +#[derive(Debug, Clone, Default)] +pub struct RepairState(Arc>); + +impl RepairState { + #[must_use] + pub fn snapshot(&self) -> PanelRepair { + self.0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + pub fn begin_skins(&self, message: &str) -> bool { + let mut guard = self + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if guard.skins_busy { + return false; + } + guard.skins_busy = true; + guard.state = REPAIR_STATE_BUSY; + guard.message = message.to_owned(); + true + } + + pub fn finish_skins(&self, ok: bool, message: String) { + let mut guard = self + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + guard.skins_busy = false; + if !guard.client_busy { + guard.state = if ok { + REPAIR_STATE_OK + } else { + REPAIR_STATE_ERROR + }; + guard.message = message; + } + } + + pub fn begin_client(&self, message: &str) -> bool { + let mut guard = self + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if guard.client_busy { + return false; + } + guard.client_busy = true; + guard.state = REPAIR_STATE_BUSY; + guard.message = message.to_owned(); + true + } + + pub fn finish_client(&self, ok: bool, message: String) { + let mut guard = self + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + guard.client_busy = false; + if !guard.skins_busy { + guard.state = if ok { + REPAIR_STATE_OK + } else { + REPAIR_STATE_ERROR + }; + guard.message = message; + } + } +} + +#[derive(Debug, Default)] +pub struct RepairSkinsReport { + pub cleared_generated: usize, + pub checked: usize, + pub repaired: usize, + pub incompatible: usize, + pub game_found: bool, + pub totals: Option, +} + +#[derive(Debug, Default)] +pub struct RepairClientReport { + pub cleared_caches: usize, + pub stopped_processes: usize, + pub reset_bridge: bool, + pub warnings: Vec, +} + +pub fn repair_skins_and_mods( + mod_roots: &[PathBuf], + state_dir: &Path, + game_dir: &Path, +) -> RepairSkinsReport { + let mut cleared_generated = 0usize; + let repair_index = state_dir.join("mod_repair.json"); + if repair_index.exists() && std::fs::remove_file(&repair_index).is_ok() { + cleared_generated += 1; + } + if let Ok(data_dir) = bullet_platform::paths::data_dir() { + cleared_generated += clear_generated_skin_dirs(&data_dir.join("mods")); + } + let resolved_game = bullet_platform::paths::normalize_game_dir(game_dir) + .or_else(bullet_platform::paths::discover_game_dir); + let Some(resolved_game) = resolved_game else { + return RepairSkinsReport { + cleared_generated, + game_found: false, + ..RepairSkinsReport::default() + }; + }; + let report = + crate::mod_repair::repair_custom_mods(mod_roots, &resolved_game, state_dir, &|| false); + RepairSkinsReport { + cleared_generated, + checked: report.checked, + repaired: report.repaired.len(), + incompatible: report.incompatible.len(), + game_found: true, + totals: report.totals, + } +} + +pub(crate) fn clear_generated_skin_dirs(generated_dir: &Path) -> usize { + let mut cleared = 0usize; + if let Ok(entries) = std::fs::read_dir(generated_dir) { + for entry in entries.flatten() { + let name = entry.file_name(); + if let Some(s) = name.to_str() + && (s.starts_with("std_") || s == "bullet_loading_name") + && std::fs::remove_dir_all(entry.path()).is_ok() + { + cleared += 1; + } + } + } + cleared +} + +fn remove_path_tracked(path: &Path, report: &mut RepairClientReport) { + if !path.exists() { + return; + } + let res = if path.is_dir() { + std::fs::remove_dir_all(path) + } else { + std::fs::remove_file(path) + }; + match res { + Ok(()) => report.cleared_caches += 1, + Err(e) => report.warnings.push(format!("{}: {e}", path.display())), + } +} + +pub fn repair_client(state_dir: &Path) -> RepairClientReport { + let mut report = RepairClientReport::default(); + + #[cfg(windows)] + { + for _ in 0..8 { + let Some(pid) = bullet_platform::process::ProcessFinder::find_any_process(&[ + "ltk-manager.exe", + "LTK Manager.exe", + "ltk_manager.exe", + "LeagueToolkit Manager.exe", + "bullet_launcher.exe", + ]) + .ok() + .flatten() else { + break; + }; + if bullet_platform::process::terminate_process(pid) { + report.stopped_processes += 1; + } else { + break; + } + } + if report.stopped_processes > 0 { + std::thread::sleep(std::time::Duration::from_millis(250)); + } + } + + if let Ok(data_dir) = bullet_platform::paths::data_dir() { + for sub in ["staging", "overlay"] { + remove_path_tracked(&data_dir.join(sub), &mut report); + } + } + remove_path_tracked(&state_dir.join("ltf_journal.json"), &mut report); + + let mut local_roots = Vec::new(); + if let Ok(desktop_local) = bullet_platform::user_profile::local_app_data() { + local_roots.push(desktop_local); + } + if let Ok(env_local) = std::env::var("LOCALAPPDATA") { + let p = PathBuf::from(env_local); + if !local_roots.contains(&p) { + local_roots.push(p); + } + } + for local_root in &local_roots { + let bridge_dir = local_root.join("BulletBridge"); + for file in ["port.txt", "token.txt"] { + let path = bridge_dir.join(file); + if path.exists() { + remove_path_tracked(&path, &mut report); + report.reset_bridge = true; + } + } + } + + let mut roaming_roots = Vec::new(); + for local_root in &local_roots { + if let Some(roaming) = local_root.parent().map(|p| p.join("Roaming")) + && !roaming_roots.contains(&roaming) + { + roaming_roots.push(roaming); + } + } + if let Ok(roaming) = std::env::var("APPDATA") { + let p = PathBuf::from(roaming); + if !roaming_roots.contains(&p) { + roaming_roots.push(p); + } + } + for roaming in roaming_roots { + let profile = roaming + .join("dev.leaguetoolkit.manager") + .join("profiles") + .join("default"); + for item in ["overlay", "overlay.json", "override_meta.bin"] { + remove_path_tracked(&profile.join(item), &mut report); + } + } + + report +} + +#[must_use] +pub fn format_skins_feedback(report: &RepairSkinsReport, text: &Text) -> (bool, String) { + let cleared = report.cleared_generated.to_string(); + if !report.game_found { + return ( + false, + fill(text.panel_repair_skins_no_game, "cleared", &cleared), + ); + } + let checked = report.checked.to_string(); + let repaired = report.repaired.to_string(); + let incompatible = report.incompatible.to_string(); + if report.incompatible > 0 { + let msg = fill( + &fill( + &fill(text.panel_repair_skins_done_warn, "cleared", &cleared), + "repaired", + &repaired, + ), + "incompatible", + &incompatible, + ); + return (false, msg); + } + let msg = fill( + &fill( + &fill(text.panel_repair_skins_done, "cleared", &cleared), + "checked", + &checked, + ), + "repaired", + &repaired, + ); + (true, msg) +} + +#[must_use] +pub fn format_client_feedback(report: &RepairClientReport, text: &Text) -> (bool, String) { + let caches = report.cleared_caches.to_string(); + if let Some(first) = report.warnings.first() { + let msg = fill( + &fill(text.panel_repair_client_partial, "caches", &caches), + "error", + first, + ); + return (false, msg); + } + (true, fill(text.panel_repair_client_done, "caches", &caches)) +} diff --git a/crates/bullet-app/src/diagnostics/control_panel/tests.rs b/crates/bullet-app/src/diagnostics/control_panel/tests.rs index 917392b..01b1dfd 100644 --- a/crates/bullet-app/src/diagnostics/control_panel/tests.rs +++ b/crates/bullet-app/src/diagnostics/control_panel/tests.rs @@ -22,6 +22,7 @@ fn facts() -> Facts { update: None, custom_mods: None, stats: bullet_platform::panel::PanelStats::default(), + repair: bullet_platform::panel::PanelRepair::default(), } } @@ -226,3 +227,96 @@ fn test_missing_pieces_are_reported() { assert!(!row.ok); assert!(row.detail.contains("1.29.0") && row.detail.contains("1.33.0")); } + +#[test] +fn test_repair_state_prevents_concurrent_runs_and_transitions_cleanly() { + let state = RepairState::default(); + assert!(state.begin_skins("running skins")); + assert!(!state.begin_skins("duplicate skins")); + let busy = state.snapshot(); + assert!(busy.skins_busy); + assert_eq!(busy.state, REPAIR_STATE_BUSY); + assert_eq!(busy.message, "running skins"); + + state.finish_skins(true, "skins fixed".into()); + let done = state.snapshot(); + assert!(!done.skins_busy); + assert_eq!(done.state, REPAIR_STATE_OK); + assert_eq!(done.message, "skins fixed"); + + assert!(state.begin_client("running client")); + assert!(!state.begin_client("duplicate client")); + state.finish_client(false, "file locked".into()); + let failed = state.snapshot(); + assert!(!failed.client_busy); + assert_eq!(failed.state, REPAIR_STATE_ERROR); + assert_eq!(failed.message, "file locked"); +} + +#[test] +fn test_repair_feedback_formatting_covers_all_languages_and_outcomes() { + for lang in [Language::Portuguese, Language::Spanish, Language::English] { + let text = lang.text(); + let (ok, msg) = format_skins_feedback( + &RepairSkinsReport { + cleared_generated: 3, + checked: 5, + repaired: 2, + incompatible: 0, + game_found: true, + totals: None, + }, + text, + ); + assert!(ok); + assert!(msg.contains('3') && msg.contains('5') && msg.contains('2') && !msg.contains('{')); + + let (warn_ok, warn_msg) = format_skins_feedback( + &RepairSkinsReport { + cleared_generated: 1, + checked: 2, + repaired: 1, + incompatible: 1, + game_found: true, + totals: None, + }, + text, + ); + assert!(!warn_ok); + assert!(!warn_msg.contains('{')); + + let (no_game_ok, no_game_msg) = format_skins_feedback( + &RepairSkinsReport { + cleared_generated: 2, + game_found: false, + ..RepairSkinsReport::default() + }, + text, + ); + assert!(!no_game_ok); + assert!(no_game_msg.contains('2') && !no_game_msg.contains('{')); + + let (client_ok, client_msg) = format_client_feedback( + &RepairClientReport { + cleared_caches: 4, + stopped_processes: 1, + reset_bridge: true, + warnings: Vec::new(), + }, + text, + ); + assert!(client_ok); + assert!(client_msg.contains('4') && !client_msg.contains('{')); + + let (partial_ok, partial_msg) = format_client_feedback( + &RepairClientReport { + cleared_caches: 2, + warnings: vec!["overlay: busy".into()], + ..RepairClientReport::default() + }, + text, + ); + assert!(!partial_ok); + assert!(partial_msg.contains("overlay: busy") && !partial_msg.contains('{')); + } +} diff --git a/crates/bullet-app/src/main.rs b/crates/bullet-app/src/main.rs index f1f9fd1..a5537dd 100644 --- a/crates/bullet-app/src/main.rs +++ b/crates/bullet-app/src/main.rs @@ -227,6 +227,7 @@ async fn run() -> Result<()> { } })); } + let repair_state = bullet_app::control_panel::RepairState::default(); let links = boot::panel::panel_links_for( &tray_controller, state_rx.clone(), @@ -236,6 +237,7 @@ async fn run() -> Result<()> { boot::panel::ReleaseNotices { bullet: update_notice.clone(), custom_mods: custom_mods_notice.clone(), + repair: repair_state.clone(), }, ); boot::tasks::spawn_custom_mods_notice( @@ -259,6 +261,8 @@ async fn run() -> Result<()> { links: links.clone(), mark_state, mark_live, + custom_mods: custom_mods_notice.clone(), + repair: repair_state, }; supervisor.spawn_essential("tray-events", move |child_token| async move { diff --git a/crates/bullet-platform/src/os/system/identity/mod.rs b/crates/bullet-platform/src/os/system/identity/mod.rs index d3072f3..09e60bb 100644 --- a/crates/bullet-platform/src/os/system/identity/mod.rs +++ b/crates/bullet-platform/src/os/system/identity/mod.rs @@ -1,2 +1,4 @@ +mod registry; +mod search; pub mod user_profile; pub mod version; diff --git a/crates/bullet-platform/src/os/system/identity/registry.rs b/crates/bullet-platform/src/os/system/identity/registry.rs new file mode 100644 index 0000000..e936022 --- /dev/null +++ b/crates/bullet-platform/src/os/system/identity/registry.rs @@ -0,0 +1,343 @@ +#[cfg(windows)] +use std::path::PathBuf; + +#[cfg(windows)] +use super::version::{extract_history_exe_path, parse_registry_path_value, resolve_exe_from_path}; + +#[cfg(windows)] +#[must_use] +pub(crate) fn discover_from_registry(keywords: &[&str], exe_names: &[&str]) -> Option { + use windows::Win32::System::Registry::{ + HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY, KEY_WOW64_64KEY, + }; + + let views = [KEY_READ | KEY_WOW64_64KEY, KEY_READ | KEY_WOW64_32KEY]; + let hives = [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE]; + + for hive in hives { + for view in views { + if let Some(found) = scan_uninstall_root( + hive, + r"Software\Microsoft\Windows\CurrentVersion\Uninstall", + view, + keywords, + exe_names, + ) { + return Some(found); + } + } + } + + for hive in hives { + if let Some(found) = scan_shell_and_app_paths(hive, exe_names) { + return Some(found); + } + for view in views { + for subkey in [r"Software\LTK Manager", r"Software\LeagueToolkit\Manager"] { + if let Some(found) = read_vendor_key(hive, subkey, view, exe_names) { + return Some(found); + } + } + } + } + + for history_key in [ + r"Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\MuiCache", + r"Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Compatibility Assistant\Store", + r"Software\Microsoft\Windows\CurrentVersion\Explorer\FeatureUsage\AppSwitched", + ] { + if let Some(found) = scan_value_names_for_exe(HKEY_CURRENT_USER, history_key, exe_names) { + return Some(found); + } + } + + None +} + +#[cfg(windows)] +unsafe fn read_reg_str(hkey: windows::Win32::System::Registry::HKEY, name: &str) -> Option { + use windows::Win32::System::Registry::{RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ, RegGetValueW}; + use windows::core::PCWSTR; + + let wide_name: Vec = name.encode_utf16().chain(std::iter::once(0)).collect(); + let mut buf = vec![0u16; 512]; + let mut bytes = (buf.len() * 2) as u32; + let status = unsafe { + RegGetValueW( + hkey, + PCWSTR::null(), + PCWSTR(wide_name.as_ptr()), + RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ, + None, + Some(buf.as_mut_ptr().cast()), + Some(&mut bytes), + ) + }; + if status.is_err() { + return None; + } + let chars = (bytes as usize / 2).min(buf.len()); + let slice = &buf[..chars]; + let end = slice.iter().position(|&c| c == 0).unwrap_or(slice.len()); + Some(String::from_utf16_lossy(&slice[..end])) +} + +#[cfg(windows)] +fn scan_uninstall_root( + hive: windows::Win32::System::Registry::HKEY, + subkey_path: &str, + access: windows::Win32::System::Registry::REG_SAM_FLAGS, + keywords: &[&str], + exe_names: &[&str], +) -> Option { + use windows::Win32::Foundation::ERROR_NO_MORE_ITEMS; + use windows::Win32::System::Registry::{HKEY, RegCloseKey, RegEnumKeyExW, RegOpenKeyExW}; + use windows::core::PCWSTR; + + let subkey_wide: Vec = subkey_path + .encode_utf16() + .chain(std::iter::once(0)) + .collect(); + let mut root_key = HKEY::default(); + if unsafe { + RegOpenKeyExW( + hive, + PCWSTR(subkey_wide.as_ptr()), + Some(0), + access, + &mut root_key, + ) + } + .is_err() + { + return None; + } + + let mut found = None; + let mut index = 0u32; + let mut name_buf = [0u16; 256]; + loop { + let mut name_len = name_buf.len() as u32; + let status = unsafe { + RegEnumKeyExW( + root_key, + index, + Some(windows::core::PWSTR(name_buf.as_mut_ptr())), + &mut name_len, + None, + None, + None, + None, + ) + }; + if status == ERROR_NO_MORE_ITEMS || status.is_err() { + break; + } + index += 1; + + let child_name = String::from_utf16_lossy(&name_buf[..name_len as usize]); + let child_wide: Vec = child_name + .encode_utf16() + .chain(std::iter::once(0)) + .collect(); + let mut app_key = HKEY::default(); + if unsafe { + RegOpenKeyExW( + root_key, + PCWSTR(child_wide.as_ptr()), + Some(0), + access, + &mut app_key, + ) + } + .is_err() + { + continue; + } + + let display_name = unsafe { read_reg_str(app_key, "DisplayName") } + .unwrap_or_default() + .to_ascii_lowercase(); + let publisher = unsafe { read_reg_str(app_key, "Publisher") } + .unwrap_or_default() + .to_ascii_lowercase(); + let key_lower = child_name.to_ascii_lowercase(); + let matched = keywords.iter().any(|kw| { + display_name.contains(kw) || publisher.contains(kw) || key_lower.contains(kw) + }); + if matched { + for field in [ + "DisplayIcon", + "InstallLocation", + "UninstallString", + "QuietUninstallString", + ] { + if let Some(raw) = unsafe { read_reg_str(app_key, field) } + && let Some(parsed) = parse_registry_path_value(&raw) + && let Some(candidate) = resolve_exe_from_path(&parsed, exe_names) + { + found = Some(candidate); + break; + } + } + } + let _ = unsafe { RegCloseKey(app_key) }; // ignore-ok: close app uninstall key + if found.is_some() { + break; + } + } + let _ = unsafe { RegCloseKey(root_key) }; // ignore-ok: close uninstall root key + found +} + +#[cfg(windows)] +fn scan_shell_and_app_paths( + hive: windows::Win32::System::Registry::HKEY, + exe_names: &[&str], +) -> Option { + use windows::Win32::System::Registry::{KEY_READ, KEY_WOW64_64KEY}; + + let mut keys = vec![ + ( + r"Software\Classes\LTKManager.Fantome\shell\open\command".to_owned(), + "", + ), + ( + r"Software\Classes\LTKManager.Modpkg\shell\open\command".to_owned(), + "", + ), + ]; + for exe in exe_names { + keys.push(( + format!(r"Software\Classes\Applications\{exe}\shell\open\command"), + "", + )); + keys.push(( + format!(r"Software\Microsoft\Windows\CurrentVersion\App Paths\{exe}"), + "", + )); + keys.push(( + format!(r"Software\Microsoft\Windows\CurrentVersion\App Paths\{exe}"), + "Path", + )); + } + + for (subkey, field) in keys { + if let Some(found) = + read_vendor_field(hive, &subkey, field, KEY_READ | KEY_WOW64_64KEY, exe_names) + { + return Some(found); + } + } + None +} + +#[cfg(windows)] +fn read_vendor_key( + hive: windows::Win32::System::Registry::HKEY, + subkey: &str, + access: windows::Win32::System::Registry::REG_SAM_FLAGS, + exe_names: &[&str], +) -> Option { + for field in ["", "InstallDir", "InstallLocation", "Path"] { + if let Some(found) = read_vendor_field(hive, subkey, field, access, exe_names) { + return Some(found); + } + } + None +} + +#[cfg(windows)] +fn read_vendor_field( + hive: windows::Win32::System::Registry::HKEY, + subkey: &str, + field: &str, + access: windows::Win32::System::Registry::REG_SAM_FLAGS, + exe_names: &[&str], +) -> Option { + use windows::Win32::System::Registry::{HKEY, RegCloseKey, RegOpenKeyExW}; + use windows::core::PCWSTR; + + let subkey_wide: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); + let mut key = HKEY::default(); + if unsafe { + RegOpenKeyExW( + hive, + PCWSTR(subkey_wide.as_ptr()), + Some(0), + access, + &mut key, + ) + } + .is_err() + { + return None; + } + let found = unsafe { read_reg_str(key, field) } + .and_then(|raw| parse_registry_path_value(&raw)) + .and_then(|parsed| resolve_exe_from_path(&parsed, exe_names)); + let _ = unsafe { RegCloseKey(key) }; // ignore-ok: close registry key + found +} + +#[cfg(windows)] +fn scan_value_names_for_exe( + hive: windows::Win32::System::Registry::HKEY, + subkey: &str, + exe_names: &[&str], +) -> Option { + use windows::Win32::Foundation::ERROR_NO_MORE_ITEMS; + use windows::Win32::System::Registry::{ + HKEY, KEY_READ, KEY_WOW64_64KEY, RegCloseKey, RegEnumValueW, RegOpenKeyExW, + }; + use windows::core::{PCWSTR, PWSTR}; + + let subkey_wide: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); + let mut key = HKEY::default(); + if unsafe { + RegOpenKeyExW( + hive, + PCWSTR(subkey_wide.as_ptr()), + Some(0), + KEY_READ | KEY_WOW64_64KEY, + &mut key, + ) + } + .is_err() + { + return None; + } + + let mut found = None; + let mut index = 0u32; + let mut name_buf = [0u16; 512]; + loop { + let mut name_len = name_buf.len() as u32; + let status = unsafe { + RegEnumValueW( + key, + index, + Some(PWSTR(name_buf.as_mut_ptr())), + &mut name_len, + None, + None, + None, + None, + ) + }; + if status == ERROR_NO_MORE_ITEMS || status.is_err() { + break; + } + index += 1; + + let value_name = String::from_utf16_lossy(&name_buf[..name_len as usize]); + if let Some(candidate) = extract_history_exe_path(&value_name, exe_names) + && candidate.is_file() + { + found = Some(candidate); + break; + } + } + let _ = unsafe { RegCloseKey(key) }; // ignore-ok: close history registry key + found +} diff --git a/crates/bullet-platform/src/os/system/identity/search.rs b/crates/bullet-platform/src/os/system/identity/search.rs new file mode 100644 index 0000000..67d2f9f --- /dev/null +++ b/crates/bullet-platform/src/os/system/identity/search.rs @@ -0,0 +1,397 @@ +#[cfg(any(windows, test))] +use std::path::Path; +use std::path::PathBuf; + +#[cfg(any(windows, test))] +use super::version::matches_exe_name; + +#[cfg(windows)] +#[must_use] +pub fn discover_installed_exe(keywords: &[&str], exe_names: &[&str]) -> Option { + if let Some(found) = super::registry::discover_from_registry(keywords, exe_names) { + return Some(found); + } + if let Some(found) = discover_from_shortcuts(keywords, exe_names) { + return Some(found); + } + if let Some(found) = discover_from_path_env(exe_names) { + return Some(found); + } + discover_from_fixed_drives(keywords, exe_names) +} + +#[cfg(not(windows))] +#[must_use] +pub fn discover_installed_exe(_keywords: &[&str], _exe_names: &[&str]) -> Option { + None +} + +#[cfg(any(windows, test))] +#[must_use] +pub(crate) fn extract_lnk_exe_targets(bytes: &[u8], exe_names: &[&str]) -> Vec { + let mut found = Vec::new(); + collect_ascii_drive_paths(bytes, exe_names, &mut found); + collect_utf16le_drive_paths(bytes, exe_names, &mut found); + found +} + +#[cfg(any(windows, test))] +fn collect_ascii_drive_paths(bytes: &[u8], exe_names: &[&str], out: &mut Vec) { + let mut i = 0usize; + while i + 6 < bytes.len() { + if bytes[i].is_ascii_alphabetic() && bytes[i + 1] == b':' && bytes[i + 2] == b'\\' { + let start = i; + let mut end = i + 3; + while end < bytes.len() && end - start < 260 { + let b = bytes[end]; + if b < 0x20 || b == 0x7F || matches!(b, b'"' | b'<' | b'>' | b'|' | b'*' | b'?') { + break; + } + end += 1; + } + if let Ok(text) = std::str::from_utf8(&bytes[start..end]) { + push_matching_exe_candidate(text, exe_names, out); + } + i = end; + } else { + i += 1; + } + } +} + +#[cfg(any(windows, test))] +fn collect_utf16le_drive_paths(bytes: &[u8], exe_names: &[&str], out: &mut Vec) { + let mut i = 0usize; + while i + 12 < bytes.len() { + if bytes[i].is_ascii_alphabetic() + && bytes[i + 1] == 0 + && bytes[i + 2] == b':' + && bytes[i + 3] == 0 + && bytes[i + 4] == b'\\' + && bytes[i + 5] == 0 + { + let mut units = Vec::new(); + let mut j = i; + while j + 1 < bytes.len() && units.len() < 260 { + let u = u16::from_le_bytes([bytes[j], bytes[j + 1]]); + if u < 0x20 || matches!(u, 0x0022 | 0x003C | 0x003E | 0x007C | 0x002A | 0x003F) { + break; + } + units.push(u); + j += 2; + } + let text = String::from_utf16_lossy(&units); + push_matching_exe_candidate(&text, exe_names, out); + i = j.max(i + 2); + } else { + i += 1; + } + } +} + +#[cfg(any(windows, test))] +fn push_matching_exe_candidate(text: &str, exe_names: &[&str], out: &mut Vec) { + let lower = text.to_ascii_lowercase(); + for exe in exe_names { + let exe_lower = exe.to_ascii_lowercase(); + if let Some(pos) = lower.find(&exe_lower) { + let end = pos + exe_lower.len(); + if let Some(slice) = text.get(..end) { + let cand = PathBuf::from(slice.trim()); + if matches_exe_name(&cand, exe_names) && !out.contains(&cand) { + out.push(cand); + } + } + } + } +} + +#[cfg(windows)] +fn desktop_user_profile_dirs() -> (Option, Option, Option) { + let Ok(local) = crate::user_profile::local_app_data() else { + return (None, None, None); + }; + let appdata = local.parent(); + let roaming = appdata.map(|a| a.join("Roaming")); + let home = appdata.and_then(|a| a.parent()).map(Path::to_path_buf); + (Some(local), roaming, home) +} + +#[cfg(windows)] +fn discover_from_shortcuts(keywords: &[&str], exe_names: &[&str]) -> Option { + let mut roots = Vec::new(); + let (_, desktop_roaming, desktop_home) = desktop_user_profile_dirs(); + for base in [ + std::env::var("PROGRAMDATA").ok().map(PathBuf::from), + desktop_roaming, + std::env::var("APPDATA").ok().map(PathBuf::from), + ] + .into_iter() + .flatten() + { + roots.push( + base.join("Microsoft") + .join("Windows") + .join("Start Menu") + .join("Programs"), + ); + } + for base in [ + desktop_home, + std::env::var("USERPROFILE").ok().map(PathBuf::from), + std::env::var("PUBLIC").ok().map(PathBuf::from), + ] + .into_iter() + .flatten() + { + roots.push(base.join("Desktop")); + } + + for root in roots { + if let Some(found) = scan_shortcuts_dir(&root, 2, keywords, exe_names) { + return Some(found); + } + } + None +} + +#[cfg(windows)] +fn scan_shortcuts_dir( + dir: &Path, + depth: u8, + keywords: &[&str], + exe_names: &[&str], +) -> Option { + let entries = std::fs::read_dir(dir).ok()?; + for entry in entries.flatten() { + let path = entry.path(); + let Ok(ft) = entry.file_type() else { + continue; + }; + if ft.is_dir() && depth > 0 { + if let Some(found) = scan_shortcuts_dir(&path, depth - 1, keywords, exe_names) { + return Some(found); + } + continue; + } + if !ft.is_file() { + continue; + } + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { + continue; + }; + let lower = name.to_ascii_lowercase(); + if !lower.ends_with(".lnk") { + continue; + } + if !keywords.iter().any(|kw| lower.contains(kw)) && !lower.contains("ltk") { + continue; + } + if let Ok(bytes) = std::fs::read(&path) { + for candidate in extract_lnk_exe_targets(&bytes, exe_names) { + if candidate.is_file() { + return Some(candidate); + } + } + } + } + None +} + +#[cfg(windows)] +fn discover_from_path_env(exe_names: &[&str]) -> Option { + let path_var = std::env::var_os("PATH")?; + for dir in std::env::split_paths(&path_var) { + if let Some(found) = check_dir_for_exes(&dir, exe_names) { + return Some(found); + } + } + None +} + +#[cfg(windows)] +fn fixed_drive_roots() -> Vec { + use windows::Win32::Storage::FileSystem::{GetDriveTypeW, GetLogicalDrives}; + use windows::core::PCWSTR; + + const DRIVE_FIXED: u32 = 3; + let mask = unsafe { GetLogicalDrives() }; + let mut roots = Vec::new(); + for idx in 0..26u32 { + if (mask & (1 << idx)) == 0 { + continue; + } + let letter = (b'A' + idx as u8) as char; + let root_str = format!("{letter}:\\"); + let wide: Vec = root_str.encode_utf16().chain(std::iter::once(0)).collect(); + if unsafe { GetDriveTypeW(PCWSTR(wide.as_ptr())) } == DRIVE_FIXED { + roots.push(PathBuf::from(root_str)); + } + } + roots +} + +#[cfg(windows)] +fn discover_from_fixed_drives(keywords: &[&str], exe_names: &[&str]) -> Option { + let mut scan_roots = Vec::new(); + for env_var in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Ok(base) = std::env::var(env_var) { + scan_roots.push(PathBuf::from(base)); + } + } + let (desktop_local, desktop_roaming, desktop_home) = desktop_user_profile_dirs(); + if let Some(local) = desktop_local { + scan_roots.push(local.join("Programs")); + scan_roots.push(local); + } + if let Some(roaming) = desktop_roaming { + scan_roots.push(roaming); + } + if let Some(home) = desktop_home { + scan_roots.push(home.join("Desktop")); + scan_roots.push(home.join("Downloads")); + } + if let Ok(la) = std::env::var("LOCALAPPDATA") { + let base = PathBuf::from(la); + scan_roots.push(base.join("Programs")); + scan_roots.push(base); + } + if let Ok(home) = std::env::var("USERPROFILE") { + let base = PathBuf::from(home); + scan_roots.push(base.join("Desktop")); + scan_roots.push(base.join("Downloads")); + } + + let common_subdirs = [ + "LTK Manager", + "LeagueToolkit", + "Program Files", + "Program Files (x86)", + "Programs", + "Apps", + "Games", + "Jogos", + "Riot Games", + ]; + for drive in fixed_drive_roots() { + if let Some(found) = check_dir_for_exes(&drive, exe_names) { + return Some(found); + } + for sub in common_subdirs { + let dir = drive.join(sub); + if let Some(found) = check_dir_for_exes(&dir, exe_names) { + return Some(found); + } + if dir.is_dir() { + scan_roots.push(dir); + } + } + scan_roots.push(drive); + } + + let mut seen = std::collections::HashSet::new(); + for root in scan_roots { + let norm = root.to_string_lossy().to_ascii_lowercase(); + if !seen.insert(norm) { + continue; + } + if let Some(found) = scan_matching_folders(&root, 2, keywords, exe_names) { + return Some(found); + } + } + None +} + +#[cfg(any(windows, test))] +fn check_dir_for_exes(dir: &Path, exe_names: &[&str]) -> Option { + for exe in exe_names { + let candidate = dir.join(exe); + if candidate.is_file() { + return Some(candidate); + } + } + None +} + +#[cfg(any(windows, test))] +pub(crate) fn scan_matching_folders( + root: &Path, + depth: u8, + keywords: &[&str], + exe_names: &[&str], +) -> Option { + if let Some(found) = check_dir_for_exes(root, exe_names) { + return Some(found); + } + if depth == 0 { + return None; + } + let entries = std::fs::read_dir(root).ok()?; + for entry in entries.flatten() { + let Ok(ft) = entry.file_type() else { + continue; + }; + if !ft.is_dir() { + continue; + } + let path = entry.path(); + if let Some(found) = check_dir_for_exes(&path, exe_names) { + return Some(found); + } + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { + continue; + }; + let lower = name.to_ascii_lowercase(); + let interesting = keywords.iter().any(|kw| lower.contains(kw)) + || lower.contains("ltk") + || lower.contains("toolkit") + || lower.contains("mod"); + if interesting + && let Some(found) = scan_matching_folders(&path, depth - 1, keywords, exe_names) + { + return Some(found); + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extracts_ascii_and_utf16le_paths_from_lnk_payload() { + let exes = ["ltk-manager.exe", "LTK Manager.exe"]; + let mut blob = vec![0u8; 16]; + blob.extend_from_slice(br"D:\Games\LTK Manager\ltk-manager.exe"); + blob.push(0); + let wide = r"E:\Custom Folder\LTK\LTK Manager.exe"; + for u in wide.encode_utf16() { + blob.extend_from_slice(&u.to_le_bytes()); + } + blob.extend_from_slice(&[0, 0]); + + let targets = extract_lnk_exe_targets(&blob, &exes); + assert!(targets.contains(&PathBuf::from(r"D:\Games\LTK Manager\ltk-manager.exe"))); + assert!(targets.contains(&PathBuf::from(r"E:\Custom Folder\LTK\LTK Manager.exe"))); + } + + #[test] + fn shallow_folder_scan_finds_custom_install_directory() { + let root = std::env::temp_dir().join(format!("bullet_scan_ltk_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); // ignore-ok: cleanup before test + let nested = root.join("My LTK Custom").join("bin"); + std::fs::create_dir_all(&nested).expect("nested dir"); + let exe = nested.join("ltk-manager.exe"); + std::fs::write(&exe, b"mz").expect("write exe"); + + let found = scan_matching_folders( + &root, + 2, + &["ltk manager", "leaguetoolkit"], + &["ltk-manager.exe"], + ); + assert_eq!(found, Some(exe)); + let _ = std::fs::remove_dir_all(&root); // ignore-ok: cleanup after test + } +} diff --git a/crates/bullet-platform/src/os/system/identity/version.rs b/crates/bullet-platform/src/os/system/identity/version.rs index 1ec589b..40978e5 100644 --- a/crates/bullet-platform/src/os/system/identity/version.rs +++ b/crates/bullet-platform/src/os/system/identity/version.rs @@ -1,5 +1,7 @@ use std::path::{Path, PathBuf}; +pub use super::search::discover_installed_exe; + #[must_use] pub fn display_version() -> &'static str { const RAW: &str = env!("CARGO_PKG_VERSION"); @@ -137,7 +139,7 @@ pub fn parse_registry_path_value(raw: &str) -> Option { let without_quotes = if let Some(rest) = trimmed.strip_prefix('"') { rest.split('"').next().unwrap_or(rest) } else { - trimmed + strip_unquoted_cli_args(trimmed) }; let clean = match without_quotes.rfind(',') { Some(idx) @@ -155,175 +157,61 @@ pub fn parse_registry_path_value(raw: &str) -> Option { (!clean.is_empty()).then(|| PathBuf::from(clean)) } -#[cfg(windows)] -#[must_use] -pub fn discover_installed_exe(keywords: &[&str], exe_names: &[&str]) -> Option { - use windows::Win32::Foundation::ERROR_NO_MORE_ITEMS; - use windows::Win32::System::Registry::{ - HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ, - RegCloseKey, RegEnumKeyExW, RegGetValueW, RegOpenKeyExW, - }; - use windows::core::PCWSTR; - - unsafe fn read_reg_str(hkey: HKEY, name: &str) -> Option { - let wide_name: Vec = name.encode_utf16().chain(std::iter::once(0)).collect(); - let mut buf = vec![0u16; 512]; - let mut bytes = (buf.len() * 2) as u32; - let status = unsafe { - RegGetValueW( - hkey, - PCWSTR::null(), - PCWSTR(wide_name.as_ptr()), - RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ, - None, - Some(buf.as_mut_ptr().cast()), - Some(&mut bytes), - ) - }; - if status.is_err() { - return None; - } - let chars = (bytes as usize / 2).min(buf.len()); - let slice = &buf[..chars]; - let end = slice.iter().position(|&c| c == 0).unwrap_or(slice.len()); - Some(String::from_utf16_lossy(&slice[..end])) - } - - let roots = [ - ( - HKEY_CURRENT_USER, - r"Software\Microsoft\Windows\CurrentVersion\Uninstall", - ), - ( - HKEY_LOCAL_MACHINE, - r"Software\Microsoft\Windows\CurrentVersion\Uninstall", - ), - ( - HKEY_LOCAL_MACHINE, - r"Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall", - ), - ]; - - for (hive, subkey_path) in roots { - let subkey_wide: Vec = subkey_path - .encode_utf16() - .chain(std::iter::once(0)) - .collect(); - let mut root_key = HKEY::default(); - if unsafe { - RegOpenKeyExW( - hive, - PCWSTR(subkey_wide.as_ptr()), - Some(0), - KEY_READ, - &mut root_key, - ) - } - .is_err() +fn strip_unquoted_cli_args(input: &str) -> &str { + let lower = input.to_ascii_lowercase(); + if let Some(idx) = lower.find(".exe") { + let end = idx + 4; + if let Some(after) = input.get(end..) + && (after.is_empty() + || after.starts_with(char::is_whitespace) + || after.starts_with(',')) + && let Some(head) = input.get(..end) { - continue; + return head; } + } + input +} - let mut index = 0u32; - let mut name_buf = [0u16; 256]; - loop { - let mut name_len = name_buf.len() as u32; - let status = unsafe { - RegEnumKeyExW( - root_key, - index, - Some(windows::core::PWSTR(name_buf.as_mut_ptr())), - &mut name_len, - None, - None, - None, - None, - ) - }; - if status == ERROR_NO_MORE_ITEMS || status.is_err() { - break; - } - index += 1; - - let child_name = String::from_utf16_lossy(&name_buf[..name_len as usize]); - let child_wide: Vec = child_name - .encode_utf16() - .chain(std::iter::once(0)) - .collect(); - let mut app_key = HKEY::default(); - if unsafe { - RegOpenKeyExW( - root_key, - PCWSTR(child_wide.as_ptr()), - Some(0), - KEY_READ, - &mut app_key, - ) - } - .is_err() - { - continue; - } +#[cfg(any(windows, test))] +#[must_use] +pub(crate) fn extract_history_exe_path(value_name: &str, exe_names: &[&str]) -> Option { + let trimmed = value_name.trim().trim_matches('"'); + let stripped = trimmed + .strip_suffix(".FriendlyAppName") + .or_else(|| trimmed.strip_suffix(".ApplicationCompany")) + .unwrap_or(trimmed); + let path = PathBuf::from(stripped); + matches_exe_name(&path, exe_names).then_some(path) +} - let display_name = unsafe { read_reg_str(app_key, "DisplayName") } - .unwrap_or_default() - .to_ascii_lowercase(); - let key_lower = child_name.to_ascii_lowercase(); - let matched = keywords - .iter() - .any(|kw| display_name.contains(kw) || key_lower.contains(kw)); - if matched { - if let Some(icon) = unsafe { read_reg_str(app_key, "DisplayIcon") } - .and_then(|v| parse_registry_path_value(&v)) - && icon.is_file() - && exe_names.iter().any(|e| { - icon.file_name() - .and_then(|n| n.to_str()) - .is_some_and(|n| n.eq_ignore_ascii_case(e)) - }) - { - let _ = unsafe { RegCloseKey(app_key) }; // ignore-ok: close app uninstall key - let _ = unsafe { RegCloseKey(root_key) }; // ignore-ok: close uninstall root key - return Some(icon); - } +#[cfg(any(windows, test))] +pub(crate) fn matches_exe_name(path: &Path, exe_names: &[&str]) -> bool { + path.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|name| exe_names.iter().any(|e| name.eq_ignore_ascii_case(e))) +} - for field in ["InstallLocation", "UninstallString"] { - let Some(raw) = (unsafe { read_reg_str(app_key, field) }) else { - continue; - }; - let Some(parsed) = parse_registry_path_value(&raw) else { - continue; - }; - let dir = if field == "UninstallString" { - parsed.parent().map(Path::to_path_buf) - } else { - Some(parsed) - }; - if let Some(dir) = dir { - for exe in exe_names { - let candidate = dir.join(exe); - if candidate.is_file() { - let _ = unsafe { RegCloseKey(app_key) }; // ignore-ok: close app uninstall key - let _ = unsafe { RegCloseKey(root_key) }; // ignore-ok: close uninstall root key - return Some(candidate); - } - } - } - } - } - let _ = unsafe { RegCloseKey(app_key) }; // ignore-ok: close app uninstall key +#[cfg(windows)] +pub(crate) fn resolve_exe_from_path(parsed: &Path, exe_names: &[&str]) -> Option { + if parsed.is_file() && matches_exe_name(parsed, exe_names) { + return Some(parsed.to_path_buf()); + } + let dir = if parsed.is_dir() { + Some(parsed) + } else { + parsed.parent() + }; + let dir = dir?; + for exe in exe_names { + let candidate = dir.join(exe); + if candidate.is_file() { + return Some(candidate); } - let _ = unsafe { RegCloseKey(root_key) }; // ignore-ok: close uninstall root key } None } -#[cfg(not(windows))] -#[must_use] -pub fn discover_installed_exe(_keywords: &[&str], _exe_names: &[&str]) -> Option { - None -} - #[cfg(test)] mod tests { use super::*; @@ -369,8 +257,25 @@ mod tests { r"C:\Program Files\LTK Manager\ltk-manager.exe" )) ); + assert_eq!( + parse_registry_path_value(r#""E:\Custom\LTK Manager\ltk-manager.exe" "%1""#), + Some(PathBuf::from(r"E:\Custom\LTK Manager\ltk-manager.exe")) + ); + assert_eq!( + parse_registry_path_value(r"F:\Jogos\LTK Manager\uninstall.exe /S"), + Some(PathBuf::from(r"F:\Jogos\LTK Manager\uninstall.exe")) + ); assert_eq!(parse_registry_path_value(" "), None); let plist = "CFBundleShortVersionString1.34.2"; assert_eq!(parse_plist_short_version(plist), Some((1, 34, 2))); + let exes = ["ltk-manager.exe", "LTK Manager.exe"]; + assert_eq!( + extract_history_exe_path(r"G:\Custom Path\LTK\ltk-manager.exe.FriendlyAppName", &exes), + Some(PathBuf::from(r"G:\Custom Path\LTK\ltk-manager.exe")) + ); + assert_eq!( + extract_history_exe_path(r"H:\Portable\LTK Manager.exe", &exes), + Some(PathBuf::from(r"H:\Portable\LTK Manager.exe")) + ); } } diff --git a/crates/bullet-platform/src/ui/desktop/shell.rs b/crates/bullet-platform/src/ui/desktop/shell.rs index 42dc989..9dcece0 100644 --- a/crates/bullet-platform/src/ui/desktop/shell.rs +++ b/crates/bullet-platform/src/ui/desktop/shell.rs @@ -133,10 +133,15 @@ pub fn run_elevated_wait(exe: &Path, args: &str) -> Result let file_h = HSTRING::from(exe.as_os_str()); let params_h = HSTRING::from(args); + let verb = if crate::elevation::is_elevated() { + w!("open") + } else { + w!("runas") + }; let mut info = SHELLEXECUTEINFOW { cbSize: std::mem::size_of::() as u32, fMask: SEE_MASK_NOCLOSEPROCESS, - lpVerb: w!("runas"), + lpVerb: verb, lpFile: PCWSTR(file_h.as_ptr()), lpParameters: PCWSTR(params_h.as_ptr()), nShow: SW_HIDE.0, diff --git a/crates/bullet-platform/src/ui/locale/i18n/en.rs b/crates/bullet-platform/src/ui/locale/i18n/en.rs index 35ab500..018815c 100644 --- a/crates/bullet-platform/src/ui/locale/i18n/en.rs +++ b/crates/bullet-platform/src/ui/locale/i18n/en.rs @@ -232,12 +232,20 @@ No: keep this version; you can update later from the download page.", star_gate_unconfigured: "This Bullet build has no GitHub Client ID configured. Download the official release.", manager_missing_title: "Mod Manager missing", - manager_missing_body: "Mod Manager was not found on this PC. Install the latest version (1.33.0 or newer) so Bullet can work properly.", + manager_missing_body: "LTK Manager (ltk-manager.exe) was not found on this PC. Install LTK Manager (1.33.0 or newer) or check if antivirus removed the executable. If installed in a custom folder, launch LTK Manager once or set BULLET_LTK_MANAGER.", manager_outdated_title: "Mod Manager outdated", manager_outdated_body: "The installed Mod Manager version ({found}) is outdated for this Bullet version ({bullet}). Please update Mod Manager on your PC to version {required}+ so everything works properly.", panel_repair_skins: "Repair skins and mods", panel_repair_client: "Repair client", + panel_repair_running: "Repairing…", + panel_repair_skins_running: "Clearing skin caches and checking custom mods…", + panel_repair_skins_done: "Skins and mods repaired ({cleared} caches cleared, {checked} mods checked, {repaired} adjusted).", + panel_repair_skins_done_warn: "Repair finished ({cleared} caches cleared, {repaired} adjusted), but {incompatible} mod(s) remain incompatible.", + panel_repair_skins_no_game: "Caches cleared ({cleared}), but the League of Legends folder was not found to check custom mods.", + panel_repair_client_running: "Clearing client caches, overlay state, and resetting bridge…", + panel_repair_client_done: "Client repaired: {caches} caches cleared and bridge ready for the next match.", + panel_repair_client_partial: "Client partially repaired ({caches} caches cleared), but some files were in use: {error}", panel_stats_title: "Skin performance", panel_stats_empty: "Play a match to track wins, losses, and win rate per skin.", panel_stats_games: "games", diff --git a/crates/bullet-platform/src/ui/locale/i18n/es.rs b/crates/bullet-platform/src/ui/locale/i18n/es.rs index fd5f8e4..2116d94 100644 --- a/crates/bullet-platform/src/ui/locale/i18n/es.rs +++ b/crates/bullet-platform/src/ui/locale/i18n/es.rs @@ -233,12 +233,20 @@ No: sigues con esta versión; puedes actualizar después desde la página de des star_gate_unconfigured: "Esta compilación de Bullet no tiene el Client ID de GitHub configurado. Descarga la versión oficial.", manager_missing_title: "Falta Mod Manager", - manager_missing_body: "No se encontró Mod Manager en este PC. Instala la última versión (1.33.0 o superior) para que Bullet funcione correctamente.", + manager_missing_body: "No se encontró LTK Manager (ltk-manager.exe) en este PC. Instala LTK Manager (1.33.0 o superior) o revisa si el antivirus eliminó el ejecutable. Si lo instalaste en otra carpeta, abre LTK Manager una vez o define BULLET_LTK_MANAGER.", manager_outdated_title: "Mod Manager desactualizado", manager_outdated_body: "La versión instalada de Mod Manager ({found}) está desactualizada para esta versión de Bullet ({bullet}). Actualiza Mod Manager en tu PC a la versión {required}+ para que todo funcione correctamente.", panel_repair_skins: "Reparar skins y mods", panel_repair_client: "Reparar cliente", + panel_repair_running: "Reparando…", + panel_repair_skins_running: "Limpiando cachés de aspectos y revisando mods personalizados…", + panel_repair_skins_done: "Skins y mods corregidos ({cleared} cachés limpiadas, {checked} mods revisados, {repaired} ajustados).", + panel_repair_skins_done_warn: "Reparación terminada ({cleared} cachés limpiadas, {repaired} ajustados), pero {incompatible} mod(s) siguen incompatibles.", + panel_repair_skins_no_game: "Cachés limpiadas ({cleared}), pero no se encontró la carpeta de League of Legends para revisar los mods.", + panel_repair_client_running: "Limpiando cachés del cliente, overlay y reiniciando el puente…", + panel_repair_client_done: "Cliente corregido: {caches} cachés limpiadas y puente listo para la próxima partida.", + panel_repair_client_partial: "Cliente reparado parcialmente ({caches} cachés limpiadas), pero algunos archivos estaban en uso: {error}", panel_stats_title: "Rendimiento con skins", panel_stats_empty: "Juega una partida para registrar victorias, derrotas y tasa de victoria por skin.", panel_stats_games: "partidas", diff --git a/crates/bullet-platform/src/ui/locale/i18n/mod.rs b/crates/bullet-platform/src/ui/locale/i18n/mod.rs index cef98ff..368303d 100644 --- a/crates/bullet-platform/src/ui/locale/i18n/mod.rs +++ b/crates/bullet-platform/src/ui/locale/i18n/mod.rs @@ -329,6 +329,14 @@ pub struct Text { pub panel_repair_skins: &'static str, pub panel_repair_client: &'static str, + pub panel_repair_running: &'static str, + pub panel_repair_skins_running: &'static str, + pub panel_repair_skins_done: &'static str, + pub panel_repair_skins_done_warn: &'static str, + pub panel_repair_skins_no_game: &'static str, + pub panel_repair_client_running: &'static str, + pub panel_repair_client_done: &'static str, + pub panel_repair_client_partial: &'static str, pub panel_stats_title: &'static str, pub panel_stats_empty: &'static str, pub panel_stats_games: &'static str, diff --git a/crates/bullet-platform/src/ui/locale/i18n/pt.rs b/crates/bullet-platform/src/ui/locale/i18n/pt.rs index 7ca1e3f..2bfbd82 100644 --- a/crates/bullet-platform/src/ui/locale/i18n/pt.rs +++ b/crates/bullet-platform/src/ui/locale/i18n/pt.rs @@ -233,12 +233,20 @@ Não: continua nesta versão; dá para atualizar depois pela página de download star_gate_unconfigured: "Este build do Bullet não tem o Client ID do GitHub configurado. Baixe a versão oficial.", manager_missing_title: "Mod Manager ausente", - manager_missing_body: "O Mod Manager não foi encontrado neste PC. Instale a versão mais recente (1.33.0 ou superior) para que o Bullet funcione corretamente.", + manager_missing_body: "O LTK Manager (ltk-manager.exe) não foi encontrado neste PC. Instale o LTK Manager (1.33.0 ou superior) ou verifique se o antivírus removeu o executável. Se instalou em uma pasta personalizada, abra o LTK Manager uma vez ou defina BULLET_LTK_MANAGER.", manager_outdated_title: "Mod Manager desatualizado", manager_outdated_body: "A versão instalada do Mod Manager ({found}) está desatualizada para esta versão do Bullet ({bullet}). Atualize o Mod Manager no seu PC para a versão {required}+ para que tudo funcione corretamente.", panel_repair_skins: "Reparar skins e mods", panel_repair_client: "Reparar cliente", + panel_repair_running: "Reparando…", + panel_repair_skins_running: "Limpando caches de skins e verificando mods personalizados…", + panel_repair_skins_done: "Skins e mods corrigidos ({cleared} caches limpos, {checked} mods verificados, {repaired} ajustados).", + panel_repair_skins_done_warn: "Reparo concluído ({cleared} caches limpos, {repaired} ajustados), mas {incompatible} mod(s) seguem incompatíveis.", + panel_repair_skins_no_game: "Caches limpos ({cleared}), mas a pasta do League of Legends não foi encontrada para verificar mods.", + panel_repair_client_running: "Limpando caches do cliente, overlay e reiniciando o bridge…", + panel_repair_client_done: "Cliente corrigido: {caches} caches limpos e bridge pronto para a próxima partida.", + panel_repair_client_partial: "Cliente reparado parcialmente ({caches} caches limpos), mas alguns arquivos estavam em uso: {error}", panel_stats_title: "Desempenho com skins", panel_stats_empty: "Jogue uma partida para registrar vitórias, derrotas e taxa de vitória por skin.", panel_stats_games: "jogos", diff --git a/crates/bullet-platform/src/ui/pages/panel/mod.rs b/crates/bullet-platform/src/ui/pages/panel/mod.rs index 838ad54..f695b6b 100644 --- a/crates/bullet-platform/src/ui/pages/panel/mod.rs +++ b/crates/bullet-platform/src/ui/pages/panel/mod.rs @@ -35,6 +35,14 @@ pub struct PanelStats { pub top: Vec, } +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PanelRepair { + pub skins_busy: bool, + pub client_busy: bool, + pub state: u8, + pub message: String, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct PanelSnapshot { pub status: String, @@ -49,6 +57,7 @@ pub struct PanelSnapshot { pub update_line: Option, pub checks: Vec, pub stats: PanelStats, + pub repair: PanelRepair, } pub type SnapshotSource = Arc PanelSnapshot + Send + Sync>; @@ -61,6 +70,7 @@ pub struct PanelLinks { struct OpenPanel { window: ControlPanel, + refresh_now: std::rc::Rc, _refresh: slint::Timer, } @@ -138,6 +148,7 @@ pub(crate) fn labels(text: &crate::i18n::Text) -> PanelLabels { export_diagnostics: text.panel_export_diagnostics.into(), repair_skins: text.panel_repair_skins.into(), repair_client: text.panel_repair_client.into(), + repair_running: text.panel_repair_running.into(), stats_title: text.panel_stats_title.into(), stats_empty: text.panel_stats_empty.into(), stats_games: text.panel_stats_games.into(), @@ -198,6 +209,20 @@ pub(crate) fn render(window: &ControlPanel, state: &PanelSnapshot) { }) .collect(); window.set_stats_rows(ModelRc::new(VecModel::from(rows))); + window.set_repair_skins_busy(state.repair.skins_busy); + window.set_repair_client_busy(state.repair.client_busy); + window.set_repair_state(i32::from(state.repair.state)); + window.set_repair_message(state.repair.message.as_str().into()); +} + +pub fn refresh_open_panel() { + // ignore-ok: panel may not be running in headless or shutting down state + let _ = runtime::run_on_ui(|| { + let refresh = OPEN_PANEL.with_borrow(|open| open.as_ref().map(|p| p.refresh_now.clone())); + if let Some(refresh) = refresh { + refresh(); + } + }); } pub fn show_panel(links: PanelLinks) { @@ -232,7 +257,7 @@ fn open(links: PanelLinks) { let last = std::rc::Rc::new(RefCell::new(None::)); let language = std::rc::Rc::new(std::cell::Cell::new(None::)); - let refresh = { + let refresh: std::rc::Rc = std::rc::Rc::new({ let weak = window.as_weak(); let snapshot = links.snapshot.clone(); let last = last.clone(); @@ -245,7 +270,7 @@ fn open(links: PanelLinks) { *last.borrow_mut() = Some(state); } } - }; + }); refresh(); let events = links.events.clone(); @@ -279,15 +304,19 @@ fn open(links: PanelLinks) { }); let timer = slint::Timer::default(); - timer.start(slint::TimerMode::Repeated, REFRESH, refresh); + let timer_refresh = refresh.clone(); + timer.start(slint::TimerMode::Repeated, REFRESH, move || timer_refresh()); OPEN_PANEL.with_borrow_mut(|open| { *open = Some(OpenPanel { window, + refresh_now: refresh, _refresh: timer, }); }); debug!("Control panel opened"); } +#[cfg(test)] +mod repair_tests; #[cfg(test)] mod tests; diff --git a/crates/bullet-platform/src/ui/pages/panel/repair_tests.rs b/crates/bullet-platform/src/ui/pages/panel/repair_tests.rs new file mode 100644 index 0000000..a804d7d --- /dev/null +++ b/crates/bullet-platform/src/ui/pages/panel/repair_tests.rs @@ -0,0 +1,80 @@ +use super::*; +use crate::i18n::Language; +use i_slint_backend_testing::ElementHandle; + +fn empty_snapshot(repair: PanelRepair) -> PanelSnapshot { + PanelSnapshot { + status: "Ready".into(), + party_line: String::new(), + in_room: false, + auto_accept: false, + injection: true, + random_skin: false, + light_loading: false, + in_client_ui: false, + autostart: false, + update_line: None, + checks: Vec::new(), + stats: PanelStats::default(), + repair, + } +} + +#[test] +fn repair_buttons_show_loading_state_disable_clicks_and_render_result_banner() { + i_slint_backend_testing::init_no_event_loop(); + let window = ControlPanel::new().expect("panel"); + window + .window() + .set_size(slint::LogicalSize::new(460.0, 1600.0)); + let text = Language::Portuguese.text(); + window.set_labels(labels(text)); + window.set_tab(3); + + let fired = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let sink = fired.clone(); + window.on_action(move |action| sink.borrow_mut().push(action)); + + render( + &window, + &empty_snapshot(PanelRepair { + skins_busy: true, + client_busy: false, + state: 1, + message: text.panel_repair_skins_running.into(), + }), + ); + assert!(window.get_repair_skins_busy()); + assert!(!window.get_repair_client_busy()); + assert_eq!(window.get_repair_state(), 1); + assert_eq!( + window.get_repair_message().as_str(), + text.panel_repair_skins_running + ); + let busy_btn = ElementHandle::find_by_accessible_label(&window, text.panel_repair_running) + .next() + .expect("busy repair button"); + busy_btn.invoke_accessible_default_action(); + assert!( + fired.borrow().is_empty(), + "disabled repair button must ignore duplicate clicks" + ); + + render( + &window, + &empty_snapshot(PanelRepair { + skins_busy: false, + client_busy: false, + state: 2, + message: "Cliente corrigido".into(), + }), + ); + assert!(!window.get_repair_skins_busy()); + assert_eq!(window.get_repair_state(), 2); + assert_eq!(window.get_repair_message(), "Cliente corrigido"); + ElementHandle::find_by_accessible_label(&window, text.panel_repair_client) + .next() + .expect("client repair button re-enabled") + .invoke_accessible_default_action(); + assert_eq!(*fired.borrow(), vec![PanelAction::RepairClient]); +} diff --git a/crates/bullet-platform/src/ui/pages/panel/tests.rs b/crates/bullet-platform/src/ui/pages/panel/tests.rs index 83a041f..263464e 100644 --- a/crates/bullet-platform/src/ui/pages/panel/tests.rs +++ b/crates/bullet-platform/src/ui/pages/panel/tests.rs @@ -61,6 +61,7 @@ fn snapshot() -> PanelSnapshot { }, ], stats: PanelStats::default(), + repair: PanelRepair::default(), } } @@ -109,6 +110,9 @@ fn every_language_fills_every_label() { ("quit", &labels.quit), ("mark", &labels.mark_problem), ("export", &labels.export_diagnostics), + ("repair skins", &labels.repair_skins), + ("repair client", &labels.repair_client), + ("repair running", &labels.repair_running), ] { assert!(!value.is_empty(), "{language:?} {name}"); } @@ -225,6 +229,8 @@ fn every_button_and_toggle_of_the_panel_sends_its_own_action() { (3, text.folder_tools, PanelAction::OpenTools), (3, text.folder_logs, PanelAction::OpenLogs), (3, text.folder_restore_mods, PanelAction::RestoreMods), + (3, text.panel_repair_skins, PanelAction::RepairSkins), + (3, text.panel_repair_client, PanelAction::RepairClient), (3, text.panel_mark_problem, PanelAction::MarkProblem), ( 3, diff --git a/crates/bullet-platform/ui/panel/panel.slint b/crates/bullet-platform/ui/panel/panel.slint index 9e25e6e..b5488ff 100644 --- a/crates/bullet-platform/ui/panel/panel.slint +++ b/crates/bullet-platform/ui/panel/panel.slint @@ -2,7 +2,7 @@ import { Theme, ExposeLayer, GoldButton, Wordmark, StatusDot, Halo } from "../th import { ScrollView } from "std-widgets.slint"; import { PanelLabels, PanelCheckRow, PanelSkinStatRow, PanelAction } from "panel_types.slint"; import { Section, PanelTab, CheckRow, Toggle, Notice, PowerCard, AllClearBanner } from "panel_parts.slint"; -import { ModeCard } from "panel_mode.slint"; +import { ModeCard, RepairBanner } from "panel_mode.slint"; import { StatsCard } from "panel_stats.slint"; export component ControlPanel inherits Window { @@ -24,6 +24,10 @@ export component ControlPanel inherits Window { in property stats-losses; in property stats-winrate; in property <[PanelSkinStatRow]> stats-rows; + in property repair-skins-busy; + in property repair-client-busy; + in property repair-state; + in property repair-message; in-out property tab; callback action(PanelAction); title: "Bullet"; @@ -278,14 +282,20 @@ export component ControlPanel inherits Window { HorizontalLayout { spacing: 8px; GoldButton { - text: root.labels.repair-skins; + text: root.repair-skins-busy ? root.labels.repair-running : root.labels.repair-skins; + enabled: !root.repair-skins-busy; clicked => { root.action(PanelAction.repair-skins); } } GoldButton { - text: root.labels.repair-client; + text: root.repair-client-busy ? root.labels.repair-running : root.labels.repair-client; + enabled: !root.repair-client-busy; clicked => { root.action(PanelAction.repair-client); } } } + if root.repair-message != "": RepairBanner { + state: root.repair-state; + text: root.repair-message; + } HorizontalLayout { spacing: 8px; GoldButton { diff --git a/crates/bullet-platform/ui/panel/panel_mode.slint b/crates/bullet-platform/ui/panel/panel_mode.slint index 35f3b6b..5c6de6b 100644 --- a/crates/bullet-platform/ui/panel/panel_mode.slint +++ b/crates/bullet-platform/ui/panel/panel_mode.slint @@ -1,4 +1,4 @@ -import { Theme, Surface } from "../theme.slint"; +import { Theme, Surface, CheckGlyph } from "../theme.slint"; component ModeOption inherits Rectangle { in property label; @@ -107,3 +107,68 @@ export component ModeCard inherits Surface { } } } + +export component RepairBanner inherits Rectangle { + in property state; + in property text; + property phase: mod(animation-tick() / 1100ms, 1.0); + border-radius: 10px; + border-width: 1px; + border-color: root.state == 3 ? #7c3037 : root.state == 2 ? #1b5a55 : Theme.gold-dim; + background: root.state == 3 ? #241419 : root.state == 2 ? #0d2126 : #1a1811; + VerticalLayout { + padding-top: 10px; + padding-bottom: 10px; + padding-left: 12px; + padding-right: 12px; + spacing: 8px; + HorizontalLayout { + spacing: 10px; + alignment: start; + if root.state == 2: VerticalLayout { + alignment: center; + Rectangle { + width: 18px; + height: 18px; + border-radius: 9px; + background: Theme.cyan.with-alpha(0.2); + CheckGlyph { + x: 4px; + y: 4px; + stroke: Theme.cyan; + } + } + } + if root.state != 2: VerticalLayout { + alignment: center; + Rectangle { + width: 8px; + height: 8px; + border-radius: 4px; + background: root.state == 3 ? Theme.danger : Theme.gold; + } + } + Text { + text: root.text; + color: root.state == 3 ? Theme.danger-text : root.state == 2 ? Theme.text : Theme.gold-bright; + font-size: Theme.text-sm; + font-weight: 500; + wrap: word-wrap; + horizontal-stretch: 1; + } + } + if root.state == 1: Rectangle { + height: 4px; + border-radius: 2px; + background: #243043; + clip: true; + Rectangle { + width: parent.width * 0.36; + height: parent.height; + border-radius: 2px; + x: (parent.width + self.width) * root.phase - self.width; + background: @linear-gradient(90deg, #8a6a30 0%, #e0c48a 50%, #18d4c4 100%); + } + } + } +} diff --git a/crates/bullet-platform/ui/panel/panel_types.slint b/crates/bullet-platform/ui/panel/panel_types.slint index 7bda5a1..de3f937 100644 --- a/crates/bullet-platform/ui/panel/panel_types.slint +++ b/crates/bullet-platform/ui/panel/panel_types.slint @@ -40,6 +40,7 @@ export struct PanelLabels { export-diagnostics: string, repair-skins: string, repair-client: string, + repair-running: string, stats-title: string, stats-empty: string, stats-games: string, diff --git a/install.ps1 b/install.ps1 index ac7d9c4..d4918a9 100644 --- a/install.ps1 +++ b/install.ps1 @@ -91,20 +91,35 @@ function Install-Bullet { Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue } - $uninstallKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{D387A5B1-8C56-4D2A-94B8-975DE11C6B45}_is1' - $installDir = (Get-ItemProperty -Path $uninstallKey -ErrorAction SilentlyContinue).InstallLocation - if (-not $installDir) { $installDir = Join-Path $env:ProgramFiles 'Bullet' } + $installDir = $null + try { + $baseKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey( + [Microsoft.Win32.RegistryHive]::LocalMachine, + [Microsoft.Win32.RegistryView]::Registry64 + ) + $subKey = $baseKey.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{D387A5B1-8C56-4D2A-94B8-975DE11C6B45}_is1') + if ($subKey) { + $installDir = $subKey.GetValue('InstallLocation') + $subKey.Close() + } + $baseKey.Close() + } catch {} + if (-not $installDir) { + $pf = if ($env:ProgramW6432) { $env:ProgramW6432 } else { $env:ProgramFiles } + $installDir = Join-Path $pf 'Bullet' + } $exe = Join-Path $installDir 'bullet.exe' + $launcher = Join-Path $installDir 'tools\bullet_launcher.exe' + $bridge = Join-Path $installDir 'tools\bullet_bridge.dll' if (-not (Test-Path -LiteralPath $exe)) { throw "Bullet was not found at $exe after the install." } + if (-not (Test-Path -LiteralPath $launcher) -or -not (Test-Path -LiteralPath $bridge)) { + throw "Bullet bridge tools were not found under $installDir\tools after the install." + } Write-Host "Bullet $($release.tag_name) installed in $installDir" if ($NoLaunch) { return } - if ($elevated) { - Write-Host 'This terminal runs as administrator, so Bullet is not started from it. Open Bullet from the Start menu.' - return - } Start-Process -FilePath $exe - Write-Host 'Bullet started in the system tray. On first start it offers to download and verify the injector.' + Write-Host 'Bullet started in the system tray. Make sure LTK Manager 1.33.0+ is installed.' } Install-Bullet -Version $Version -PreRelease:$PreRelease -NoLaunch:$NoLaunch diff --git a/installer/bullet.iss b/installer/bullet.iss index 1eaa37c..cef2320 100644 --- a/installer/bullet.iss +++ b/installer/bullet.iss @@ -93,8 +93,8 @@ Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: none; ValueName: "Bullet"; Flags: uninsdeletevalue [Run] -Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent runasoriginaluser -Filename: "{app}\{#MyAppExeName}"; Flags: nowait runasoriginaluser; Check: ShouldRelaunch +Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent +Filename: "{app}\{#MyAppExeName}"; Flags: nowait; Check: ShouldRelaunch [UninstallDelete] Type: filesandordirs; Name: "{localappdata}\Bullet\logs"