fix(core): Eliminate deadlocks, console flashing, registry backup inversion, and optimize memory/CPU

This commit is contained in:
LilDosto 2026-11-12 20:06:56 +03:00
parent 1f0c0eff67
commit 05618bc2f7
21 changed files with 395 additions and 105 deletions

View file

@ -158,7 +158,8 @@ Write-Host "[5/5] Sunucu bağlantı ve dağıtım durumu kontrol ediliyor..." -F
$ServerIP = "116.202.14.171" $ServerIP = "116.202.14.171"
$SSHKey = "$env:USERPROFILE\.ssh\id_ed25519" $SSHKey = "$env:USERPROFILE\.ssh\id_ed25519"
$RemoteDir = "/var/www/ttmadethat.shop/updates/ld-uninstaller" $RemoteDir = "/opt/tylorindar-safelink/static/updates/ld-uninstaller"
$RemoteDownloadsDir = "/opt/tylorindar-safelink/static/downloads/ld-apps"
if ($SkipUpload) { if ($SkipUpload) {
Write-Host "`n[BİLGİ] -SkipUpload parametresi nedeniyle sunucuya yükleme yapılmadı." -ForegroundColor Cyan Write-Host "`n[BİLGİ] -SkipUpload parametresi nedeniyle sunucuya yükleme yapılmadı." -ForegroundColor Cyan
@ -166,12 +167,23 @@ if ($SkipUpload) {
exit 0 exit 0
} }
Write-Host " -> Sunucu ping / erişim kontrolü yapılıyor ($ServerIP)..." -ForegroundColor Gray Write-Host " -> Sunucu SSH port kontrolü yapılıyor ($ServerIP:22)..." -ForegroundColor Gray
$ping = Test-Connection -ComputerName $ServerIP -Count 1 -Quiet -ErrorAction SilentlyContinue $tcpCheck = $false
try {
$tcpClient = New-Object System.Net.Sockets.TcpClient
$iar = $tcpClient.BeginConnect($ServerIP, 22, $null, $null)
$wait = $iar.AsyncWaitHandle.WaitOne(3000, $false)
if ($wait -and $tcpClient.Connected) {
$tcpCheck = $true
}
$tcpClient.Close()
} catch {
$tcpCheck = $false
}
if (-not $ping) { if (-not $tcpCheck) {
Write-Host "`n--------------------------------------------------------------------------" -ForegroundColor Yellow Write-Host "`n--------------------------------------------------------------------------" -ForegroundColor Yellow
Write-Host "[BİLGİ] Sunucunuz şu anda askıda veya çevrimdışı durumda ($ServerIP)." -ForegroundColor Yellow Write-Host "[BİLGİ] Sunucunuz şu anda askıda veya çevrimdışı durumda ($ServerIP:22)." -ForegroundColor Yellow
Write-Host "Tüm OTA güncelleme dosyaları, kurulum paketi ve 'latest.json' yerel olarak" -ForegroundColor Yellow Write-Host "Tüm OTA güncelleme dosyaları, kurulum paketi ve 'latest.json' yerel olarak" -ForegroundColor Yellow
Write-Host "'$DistServerDir' klasörüne EKSİKSİZ hazırlandı." -ForegroundColor Yellow Write-Host "'$DistServerDir' klasörüne EKSİKSİZ hazırlandı." -ForegroundColor Yellow
Write-Host "`nSunucunuz tekrar aktif hale geldiğinde tek bir komutla yüklemek için:" -ForegroundColor Green Write-Host "`nSunucunuz tekrar aktif hale geldiğinde tek bir komutla yüklemek için:" -ForegroundColor Green
@ -183,14 +195,19 @@ if (-not $ping) {
# Sunucu açıksa SCP ile yükle # Sunucu açıksa SCP ile yükle
try { try {
Write-Host " -> Sunucuda güncelleme klasörü oluşturuluyor ($RemoteDir)..." -ForegroundColor Gray Write-Host " -> Sunucuda güncelleme klasörü oluşturuluyor ($RemoteDir)..." -ForegroundColor Gray
ssh -i $SSHKey -o ConnectTimeout=5 root@$ServerIP "mkdir -p $RemoteDir" ssh -i $SSHKey -o ConnectTimeout=5 root@$ServerIP "mkdir -p $RemoteDir $RemoteDownloadsDir"
Write-Host " -> Dosyalar sunucuya aktarılıyor (SCP)..." -ForegroundColor Gray Write-Host " -> Dosyalar sunucuya aktarılıyor (SCP)..." -ForegroundColor Gray
scp -i $SSHKey -o ConnectTimeout=10 "$DistServerDir\*" root@${ServerIP}:${RemoteDir}/ scp -i $SSHKey -o ConnectTimeout=15 "$DistServerDir\*" root@${ServerIP}:${RemoteDir}/
scp -i $SSHKey -o ConnectTimeout=15 "$DistServerDir\LD-Uninstaller_${Version}_x64-setup.exe" root@${ServerIP}:${RemoteDownloadsDir}/LD-Uninstaller-Setup-v${Version}.exe
scp -i $SSHKey -o ConnectTimeout=15 "$DistServerDir\LD-Uninstaller_${Version}_x64-setup.exe" root@${ServerIP}:${RemoteDownloadsDir}/LD-Uninstaller-Setup-latest.exe
ssh -i $SSHKey -o ConnectTimeout=5 root@$ServerIP "chmod -R 755 $RemoteDir; docker restart tylorindar-safelink-hub >/dev/null 2>&1"
Write-Host "`n[BAŞARILI] Sürüm v$Version kendi web sitene başarıyla yayınlandı!" -ForegroundColor Green Write-Host "`n[BAŞARILI] Sürüm v$Version kendi web sitene başarıyla yayınlandı!" -ForegroundColor Green
Write-Host "OTA Manifest URL: https://ttmadethat.shop/updates/ld-uninstaller/latest.json" -ForegroundColor Cyan Write-Host "OTA Manifest URL: https://ttmadethat.shop/updates/ld-uninstaller/latest.json" -ForegroundColor Cyan
Write-Host "Setup İndirme URL: https://ttmadethat.shop/updates/ld-uninstaller/LD-Uninstaller_${Version}_x64-setup.exe" -ForegroundColor Cyan
} catch { } catch {
Write-Host "`n[UYARI] Sunucuya bağlanırken zaman aşımı oluştu: $_" -ForegroundColor Yellow Write-Host "`n[UYARI] Sunucuya bağlanırken bir hata oluştu: $_" -ForegroundColor Yellow
Write-Host "Dosyalar '$DistServerDir' dizininde korundu. Sunucu açıldığında '.\publish.ps1 -UploadOnly' çalıştırabilirsiniz." -ForegroundColor Cyan Write-Host "Dosyalar '$DistServerDir' dizininde korundu. Sunucu açıldığında '.\publish.ps1 -UploadOnly' çalıştırabilirsiniz." -ForegroundColor Cyan
} }

View file

@ -2,11 +2,15 @@ use crate::error::{AppError, AppResult};
use crate::models::ApplicationEntry; use crate::models::ApplicationEntry;
use crate::services::{DiscoveryService, UninstallerService}; use crate::services::{DiscoveryService, UninstallerService};
use crate::state::AppState; use crate::state::AppState;
use std::path::PathBuf;
use tauri::State; use tauri::State;
#[tauri::command] #[tauri::command]
pub async fn get_installed_apps(state: State<'_, AppState>) -> AppResult<Vec<ApplicationEntry>> { pub async fn get_installed_apps(state: State<'_, AppState>) -> AppResult<Vec<ApplicationEntry>> {
let apps = DiscoveryService::scan_all_applications()?; let apps = tokio::task::spawn_blocking(DiscoveryService::scan_all_applications)
.await
.map_err(|e| AppError::Execution(format!("Tarama görevi yürütülemedi: {}", e)))??;
let mut cache = state.cached_apps.write().await; let mut cache = state.cached_apps.write().await;
*cache = apps.clone(); *cache = apps.clone();
Ok(apps) Ok(apps)
@ -18,25 +22,51 @@ pub async fn uninstall_application(
quiet: bool, quiet: bool,
state: State<'_, AppState>, state: State<'_, AppState>,
) -> AppResult<bool> { ) -> AppResult<bool> {
// 1. Kilit kapsamını (lock scope) anında sınırla: uygulamayı kopyala ve kilidi hemen bırak
let app_to_uninstall = {
let cache = state.cached_apps.read().await; let cache = state.cached_apps.read().await;
let app = cache cache
.iter() .iter()
.find(|a| a.id == app_id) .find(|a| a.id == app_id)
.ok_or_else(|| AppError::NotFound(format!("Uygulama bulunamadı (ID: {})", app_id)))?; .cloned()
.ok_or_else(|| AppError::NotFound(format!("Uygulama bulunamadı (ID: {})", app_id)))?
};
UninstallerService::uninstall(app, quiet) // 2. Senkron süreç bekleme döngüsünü spawn_blocking ile Tokio thread pool'dan ayır (Deadlock önlendi)
tokio::task::spawn_blocking(move || {
UninstallerService::uninstall(&app_to_uninstall, quiet)
})
.await
.map_err(|e| AppError::Execution(format!("Kaldırma süreci yürütülemedi: {}", e)))?
} }
#[tauri::command] #[tauri::command]
pub async fn export_apps_csv(file_path: String, state: State<'_, AppState>) -> AppResult<bool> { pub async fn export_apps_csv(file_path: String, state: State<'_, AppState>) -> AppResult<String> {
let apps = {
let cache = state.cached_apps.read().await; let cache = state.cached_apps.read().await;
let mut wtr = csv::Writer::from_path(&file_path) cache.clone()
};
let target_path = if file_path.trim().is_empty() || file_path.contains("Default\\Desktop") {
if let Ok(user_profile) = std::env::var("USERPROFILE") {
PathBuf::from(user_profile).join("Desktop").join("LD_Uninstaller_Apps.csv")
} else {
PathBuf::from("LD_Uninstaller_Apps.csv")
}
} else {
PathBuf::from(file_path)
};
let target_path_str = target_path.to_string_lossy().to_string();
tokio::task::spawn_blocking(move || -> AppResult<String> {
let mut wtr = csv::Writer::from_path(&target_path)
.map_err(|e| AppError::Io(std::io::Error::other(e)))?; .map_err(|e| AppError::Io(std::io::Error::other(e)))?;
wtr.write_record(["Ad", "Sürüm", "Yayımcı", "Yükleme Konumu", "Boyut (KB)", "Kaldırma Komutu"]) wtr.write_record(["Ad", "Sürüm", "Yayımcı", "Yükleme Konumu", "Boyut (KB)", "Kaldırma Komutu"])
.map_err(|e| AppError::Io(std::io::Error::other(e)))?; .map_err(|e| AppError::Io(std::io::Error::other(e)))?;
for app in cache.iter() { for app in &apps {
wtr.write_record([ wtr.write_record([
&app.display_name, &app.display_name,
&app.display_version, &app.display_version,
@ -48,5 +78,8 @@ pub async fn export_apps_csv(file_path: String, state: State<'_, AppState>) -> A
} }
wtr.flush().map_err(|e| AppError::Io(std::io::Error::other(e)))?; wtr.flush().map_err(|e| AppError::Io(std::io::Error::other(e)))?;
Ok(true) Ok(target_path_str)
})
.await
.map_err(|e| AppError::Execution(format!("Dışa aktarma yürütülemedi: {}", e)))?
} }

View file

@ -1,4 +1,4 @@
use crate::error::AppResult; use crate::error::{AppError, AppResult};
use crate::models::{CleanReport, JunkItem, JunkScanResult}; use crate::models::{CleanReport, JunkItem, JunkScanResult};
use crate::services::JunkCleanerService; use crate::services::JunkCleanerService;
use crate::state::AppState; use crate::state::AppState;
@ -11,7 +11,16 @@ pub async fn scan_app_leftovers(
install_location: String, install_location: String,
state: State<'_, AppState>, state: State<'_, AppState>,
) -> AppResult<JunkScanResult> { ) -> AppResult<JunkScanResult> {
JunkCleanerService::scan_leftovers(&app_name, &publisher, &install_location, &state) let exclusions = match state.exclusions.read() {
Ok(guard) => guard.clone(),
Err(_) => Vec::new(),
};
tokio::task::spawn_blocking(move || {
JunkCleanerService::scan_leftovers(&app_name, &publisher, &install_location, &exclusions)
})
.await
.map_err(|e| AppError::Execution(format!("Kalıntı tarama işi yürütülemedi: {}", e)))?
} }
#[tauri::command] #[tauri::command]
@ -20,7 +29,13 @@ pub async fn clean_leftovers(
use_recycle_bin: bool, use_recycle_bin: bool,
state: State<'_, AppState>, state: State<'_, AppState>,
) -> AppResult<CleanReport> { ) -> AppResult<CleanReport> {
JunkCleanerService::clean_selected_items(&items, use_recycle_bin, &state) let backup_dir = state.config_dir.join("Backups");
tokio::task::spawn_blocking(move || {
JunkCleanerService::clean_selected_items(&items, use_recycle_bin, &backup_dir)
})
.await
.map_err(|e| AppError::Execution(format!("Kalıntı temizleme işi yürütülemedi: {}", e)))?
} }
#[tauri::command] #[tauri::command]

View file

@ -1,4 +1,4 @@
use crate::error::AppResult; use crate::error::{AppError, AppResult};
use crate::models::{BackupEntry, DrivePartition, StartupItem, SystemTweak, TreemapItem}; use crate::models::{BackupEntry, DrivePartition, StartupItem, SystemTweak, TreemapItem};
use crate::services::{BackupService, StartupService, TreemapService, TweaksService}; use crate::services::{BackupService, StartupService, TreemapService, TweaksService};
use crate::state::AppState; use crate::state::AppState;
@ -6,27 +6,41 @@ use tauri::State;
#[tauri::command] #[tauri::command]
pub async fn get_startup_items() -> AppResult<Vec<StartupItem>> { pub async fn get_startup_items() -> AppResult<Vec<StartupItem>> {
StartupService::get_startup_items() tokio::task::spawn_blocking(StartupService::get_startup_items)
.await
.map_err(|e| AppError::Execution(e.to_string()))?
} }
#[tauri::command] #[tauri::command]
pub async fn toggle_startup_item(id: String, enable: bool) -> AppResult<bool> { pub async fn toggle_startup_item(id: String, enable: bool) -> AppResult<bool> {
tokio::task::spawn_blocking(move || {
StartupService::toggle_startup_item(&id, enable) StartupService::toggle_startup_item(&id, enable)
})
.await
.map_err(|e| AppError::Execution(e.to_string()))?
} }
#[tauri::command] #[tauri::command]
pub async fn get_tweaks() -> AppResult<Vec<SystemTweak>> { pub async fn get_tweaks() -> AppResult<Vec<SystemTweak>> {
TweaksService::get_available_tweaks() tokio::task::spawn_blocking(TweaksService::get_available_tweaks)
.await
.map_err(|e| AppError::Execution(e.to_string()))?
} }
#[tauri::command] #[tauri::command]
pub async fn toggle_tweak(id: String, enable: bool) -> AppResult<bool> { pub async fn toggle_tweak(id: String, enable: bool) -> AppResult<bool> {
tokio::task::spawn_blocking(move || {
TweaksService::apply_tweak(&id, enable) TweaksService::apply_tweak(&id, enable)
})
.await
.map_err(|e| AppError::Execution(e.to_string()))?
} }
#[tauri::command] #[tauri::command]
pub async fn get_disk_partitions() -> AppResult<Vec<DrivePartition>> { pub async fn get_disk_partitions() -> AppResult<Vec<DrivePartition>> {
TreemapService::get_disk_partitions() tokio::task::spawn_blocking(TreemapService::get_disk_partitions)
.await
.map_err(|e| AppError::Execution(e.to_string()))?
} }
#[tauri::command] #[tauri::command]
@ -37,15 +51,33 @@ pub async fn get_treemap_data(state: State<'_, AppState>) -> AppResult<Vec<Treem
#[tauri::command] #[tauri::command]
pub async fn list_backups(state: State<'_, AppState>) -> AppResult<Vec<BackupEntry>> { pub async fn list_backups(state: State<'_, AppState>) -> AppResult<Vec<BackupEntry>> {
BackupService::list_backups(&state) let config_dir = state.config_dir.clone();
tokio::task::spawn_blocking(move || {
let dummy_state = AppState {
exclusions: std::sync::RwLock::new(Vec::new()),
cached_apps: tokio::sync::RwLock::new(Vec::new()),
config_dir,
};
BackupService::list_backups(&dummy_state)
})
.await
.map_err(|e| AppError::Execution(e.to_string()))?
} }
#[tauri::command] #[tauri::command]
pub async fn restore_backup(file_path: String) -> AppResult<bool> { pub async fn restore_backup(file_path: String) -> AppResult<bool> {
tokio::task::spawn_blocking(move || {
BackupService::restore_backup(&file_path) BackupService::restore_backup(&file_path)
})
.await
.map_err(|e| AppError::Execution(e.to_string()))?
} }
#[tauri::command] #[tauri::command]
pub async fn delete_backup(file_path: String) -> AppResult<bool> { pub async fn delete_backup(file_path: String) -> AppResult<bool> {
tokio::task::spawn_blocking(move || {
BackupService::delete_backup(&file_path) BackupService::delete_backup(&file_path)
})
.await
.map_err(|e| AppError::Execution(e.to_string()))?
} }

View file

@ -2,9 +2,12 @@ use crate::error::{AppError, AppResult};
use crate::models::BackupEntry; use crate::models::BackupEntry;
use crate::state::AppState; use crate::state::AppState;
use std::fs; use std::fs;
use std::os::windows::process::CommandExt;
use std::path::Path; use std::path::Path;
use std::process::Command; use std::process::Command;
const CREATE_NO_WINDOW: u32 = 0x08000000;
pub struct BackupService; pub struct BackupService;
impl BackupService { impl BackupService {
@ -60,6 +63,7 @@ impl BackupService {
// reg import "<path>" // reg import "<path>"
let output = Command::new("reg") let output = Command::new("reg")
.args(["import", file_path]) .args(["import", file_path])
.creation_flags(CREATE_NO_WINDOW)
.output() .output()
.map_err(|e| AppError::Execution(format!("'reg import' komutu çalıştırılamadı: {}", e)))?; .map_err(|e| AppError::Execution(format!("'reg import' komutu çalıştırılamadı: {}", e)))?;

View file

@ -1,11 +1,14 @@
use crate::error::AppResult; use crate::error::AppResult;
use crate::models::{ApplicationEntry, ApplicationKind, UninstallerKind}; use crate::models::{ApplicationEntry, ApplicationKind, UninstallerKind};
use std::fs; use std::fs;
use std::os::windows::process::CommandExt;
use std::path::PathBuf; use std::path::PathBuf;
use std::process::Command; use std::process::Command;
use winreg::enums::*; use winreg::enums::*;
use winreg::{RegKey, HKEY}; use winreg::{RegKey, HKEY};
const CREATE_NO_WINDOW: u32 = 0x08000000;
pub struct DiscoveryService; pub struct DiscoveryService;
impl DiscoveryService { impl DiscoveryService {
@ -224,6 +227,7 @@ impl DiscoveryService {
fn scan_store_apps(apps: &mut Vec<ApplicationEntry>) -> AppResult<()> { fn scan_store_apps(apps: &mut Vec<ApplicationEntry>) -> AppResult<()> {
let output = match Command::new("powershell") let output = match Command::new("powershell")
.args(["-NoProfile", "-Command", "Get-AppxPackage | Where-Object { -not $_.IsFramework -and $_.NonRemovable -ne $true } | Select-Object Name, PackageFullName, InstallLocation, Publisher | ConvertTo-Json"]) .args(["-NoProfile", "-Command", "Get-AppxPackage | Where-Object { -not $_.IsFramework -and $_.NonRemovable -ne $true } | Select-Object Name, PackageFullName, InstallLocation, Publisher | ConvertTo-Json"])
.creation_flags(CREATE_NO_WINDOW)
.output() .output()
{ {
Ok(o) => o, Ok(o) => o,

View file

@ -3,7 +3,8 @@ use crate::services::safety::SafetyBlacklist;
use std::fs; use std::fs;
use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStrExt;
use std::path::Path; use std::path::Path;
use std::process::Command; use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x08000000;
use windows::core::{PCWSTR, PWSTR}; use windows::core::{PCWSTR, PWSTR};
use windows::Win32::Foundation::{CloseHandle, ERROR_MORE_DATA, ERROR_SUCCESS}; use windows::Win32::Foundation::{CloseHandle, ERROR_MORE_DATA, ERROR_SUCCESS};
use windows::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_DELAY_UNTIL_REBOOT}; use windows::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_DELAY_UNTIL_REBOOT};
@ -126,7 +127,8 @@ impl FileUnlockerService {
if list_res == ERROR_SUCCESS || list_res == ERROR_MORE_DATA { if list_res == ERROR_SUCCESS || list_res == ERROR_MORE_DATA {
let current_pid = std::process::id(); let current_pid = std::process::id();
for info in &proc_info[0..n_proc_info as usize] { let count = (n_proc_info as usize).min(proc_info.len());
for info in &proc_info[0..count] {
let pid = info.Process.dwProcessId; let pid = info.Process.dwProcessId;
if pid != 0 && pid != current_pid { if pid != 0 && pid != current_pid {
unsafe { unsafe {
@ -152,8 +154,9 @@ impl FileUnlockerService {
fn clear_file_attributes(path_str: &str) { fn clear_file_attributes(path_str: &str) {
// attrib -r -s -h "<path>" /s /d // attrib -r -s -h "<path>" /s /d
let _ = Command::new("attrib") let _ = std::process::Command::new("attrib")
.args(["-r", "-s", "-h", path_str, "/s", "/d"]) .args(["-r", "-s", "-h", path_str, "/s", "/d"])
.creation_flags(CREATE_NO_WINDOW)
.output(); .output();
} }

View file

@ -2,7 +2,6 @@ use crate::error::AppResult;
use crate::models::{CleanReport, ConfidenceLevel, JunkItem, JunkScanResult, JunkType}; use crate::models::{CleanReport, ConfidenceLevel, JunkItem, JunkScanResult, JunkType};
use crate::services::safety::SafetyBlacklist; use crate::services::safety::SafetyBlacklist;
use crate::services::sift4::Sift4; use crate::services::sift4::Sift4;
use crate::state::AppState;
use chrono::Local; use chrono::Local;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -16,7 +15,7 @@ impl JunkCleanerService {
app_name: &str, app_name: &str,
publisher: &str, publisher: &str,
install_location: &str, install_location: &str,
state: &AppState, exclusions: &[String],
) -> AppResult<JunkScanResult> { ) -> AppResult<JunkScanResult> {
let mut items: Vec<JunkItem> = Vec::new(); let mut items: Vec<JunkItem> = Vec::new();
@ -36,7 +35,7 @@ impl JunkCleanerService {
let path_str = path.to_string_lossy().to_string(); let path_str = path.to_string_lossy().to_string();
// Güvenlik kara listesi ve kullanıcı istisna kontrolü // Güvenlik kara listesi ve kullanıcı istisna kontrolü
if SafetyBlacklist::is_dangerous_file_path(&path_str) || state.is_excluded(&path_str) { if SafetyBlacklist::is_dangerous_file_path(&path_str) || Self::is_excluded(&path_str, exclusions) {
continue; continue;
} }
@ -87,7 +86,7 @@ impl JunkCleanerService {
} }
// 2. Kayıt Defteri Taraması // 2. Kayıt Defteri Taraması
Self::scan_registry_leftovers(app_name, publisher, &tokens, &pub_tokens, state, &mut items); Self::scan_registry_leftovers(app_name, publisher, &tokens, &pub_tokens, exclusions, &mut items);
let mut total_size = 0u64; let mut total_size = 0u64;
let mut total_files = 0; let mut total_files = 0;
@ -117,7 +116,7 @@ impl JunkCleanerService {
_publisher: &str, _publisher: &str,
tokens: &[String], tokens: &[String],
_pub_tokens: &[String], _pub_tokens: &[String],
state: &AppState, exclusions: &[String],
items: &mut Vec<JunkItem>, items: &mut Vec<JunkItem>,
) { ) {
let targets = [ let targets = [
@ -135,7 +134,7 @@ impl JunkCleanerService {
for subkey in sw_key.enum_keys().filter_map(|k| k.ok()) { for subkey in sw_key.enum_keys().filter_map(|k| k.ok()) {
let full_path = format!("{}\\{}\\{}", hive_name, sub_path, subkey); let full_path = format!("{}\\{}\\{}", hive_name, sub_path, subkey);
if SafetyBlacklist::is_dangerous_registry_path(&full_path) || state.is_excluded(&full_path) { if SafetyBlacklist::is_dangerous_registry_path(&full_path) || Self::is_excluded(&full_path, exclusions) {
continue; continue;
} }
@ -178,7 +177,7 @@ impl JunkCleanerService {
pub fn clean_selected_items( pub fn clean_selected_items(
items: &[JunkItem], items: &[JunkItem],
use_recycle_bin: bool, use_recycle_bin: bool,
state: &AppState, backup_dir: &Path,
) -> AppResult<CleanReport> { ) -> AppResult<CleanReport> {
let mut deleted_count = 0; let mut deleted_count = 0;
let mut freed_bytes = 0u64; let mut freed_bytes = 0u64;
@ -191,7 +190,7 @@ impl JunkCleanerService {
.collect(); .collect();
let backup_path = if !reg_items.is_empty() { let backup_path = if !reg_items.is_empty() {
match Self::create_registry_backup(&reg_items, state) { match Self::create_registry_backup(&reg_items, backup_dir) {
Ok(p) => Some(p), Ok(p) => Some(p),
Err(e) => { Err(e) => {
errors.push(format!("Yedekleme oluşturulamadı: {}", e)); errors.push(format!("Yedekleme oluşturulamadı: {}", e));
@ -266,20 +265,68 @@ impl JunkCleanerService {
}) })
} }
fn create_registry_backup(items: &[&JunkItem], state: &AppState) -> AppResult<String> { fn is_excluded(path_str: &str, exclusions: &[String]) -> bool {
let timestamp = Local::now().format("%Y%m%d_%H%M%S").to_string(); let lower = path_str.to_lowercase();
let backup_dir = state.config_dir.join("Backups"); for exc in exclusions {
let _ = fs::create_dir_all(&backup_dir); let exc_lower = exc.to_lowercase();
if lower == exc_lower || lower.starts_with(&format!("{}\\", exc_lower)) {
let backup_file = backup_dir.join(format!("backup_{}.reg", timestamp)); return true;
}
let mut content = String::from("Windows Registry Editor Version 5.00\r\n\r\n"); }
for item in items { false
content.push_str(&format!("; Silinmeden önceki anahtar: {}\r\n", item.path));
content.push_str(&format!("[-{}]\r\n\r\n", item.path.trim_start_matches('\\')));
} }
fs::write(&backup_file, content)?; fn create_registry_backup(items: &[&JunkItem], backup_dir: &Path) -> AppResult<String> {
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x08000000;
let timestamp = Local::now().format("%Y%m%d_%H%M%S").to_string();
let _ = fs::create_dir_all(backup_dir);
let backup_file = backup_dir.join(format!("backup_{}.reg", timestamp));
let mut combined_content = String::from("Windows Registry Editor Version 5.00\r\n\r\n");
for (idx, item) in items.iter().enumerate() {
let normalized_path = if item.path.starts_with("HKCU\\") {
format!("HKEY_CURRENT_USER\\{}", &item.path[5..])
} else if item.path.starts_with("HKLM\\") {
format!("HKEY_LOCAL_MACHINE\\{}", &item.path[5..])
} else {
item.path.clone()
};
let temp_item_file = backup_dir.join(format!("temp_reg_{}_{}.reg", timestamp, idx));
let export_status = std::process::Command::new("reg")
.args(["export", &normalized_path, &temp_item_file.to_string_lossy(), "/y"])
.creation_flags(CREATE_NO_WINDOW)
.status();
if let Ok(status) = export_status {
if status.success() && temp_item_file.exists() {
if let Ok(exported_text) = fs::read(&temp_item_file) {
let decoded = if exported_text.starts_with(&[0xFF, 0xFE]) && exported_text.len() >= 2 {
let u16_chars: Vec<u16> = exported_text[2..]
.chunks(2)
.filter_map(|c| if c.len() == 2 { Some(u16::from_le_bytes([c[0], c[1]])) } else { None })
.collect();
String::from_utf16_lossy(&u16_chars)
} else {
String::from_utf8_lossy(&exported_text).to_string()
};
for line in decoded.lines() {
if !line.starts_with("Windows Registry Editor") {
combined_content.push_str(line);
combined_content.push_str("\r\n");
}
}
}
let _ = fs::remove_file(&temp_item_file);
}
}
}
fs::write(&backup_file, combined_content)?;
Ok(backup_file.to_string_lossy().to_string()) Ok(backup_file.to_string_lossy().to_string())
} }

View file

@ -13,7 +13,7 @@ impl SafetyBlacklist {
let path = Path::new(&normalized); let path = Path::new(&normalized);
// Kök dizin kontrolü (örn. C:\ veya D:\) // Kök dizin kontrolü (örn. C:\ veya D:\)
if normalized.len() <= 3 && normalized.ends_with(':') || normalized.ends_with(":\\") { if normalized.len() <= 3 && (normalized.ends_with(':') || normalized.ends_with(":\\")) {
return true; return true;
} }

View file

@ -1,5 +1,3 @@
use regex::Regex;
pub struct Sift4; pub struct Sift4;
impl Sift4 { impl Sift4 {
@ -78,6 +76,7 @@ impl Sift4 {
} }
/// Kelime tokenlarını çıkarır (jenerik kelimeleri ve 3 harften kısa olanları eler) /// Kelime tokenlarını çıkarır (jenerik kelimeleri ve 3 harften kısa olanları eler)
/// Regex tahsisatı yerine saf ve ultra hızlı karakter bölme algoritması kullanır
pub fn tokenize(name: &str) -> Vec<String> { pub fn tokenize(name: &str) -> Vec<String> {
let ignored = [ let ignored = [
"the", "app", "pro", "free", "soft", "software", "suite", "setup", "install", "the", "app", "pro", "free", "soft", "software", "suite", "setup", "install",
@ -85,26 +84,59 @@ impl Sift4 {
"ltd", "inc", "microsoft", "google", "version", "x64", "x86", "64bit", "32bit", "ltd", "inc", "microsoft", "google", "version", "x64", "x86", "64bit", "32bit",
]; ];
let re = Regex::new(r"[^a-zA-Z0-9]+").unwrap_or_else(|_| Regex::new(r"\s+").unwrap());
let parts: Vec<&str> = re.split(name).collect();
let mut tokens = Vec::new(); let mut tokens = Vec::new();
for part in parts { for part in name.split(|c: char| !c.is_alphanumeric()) {
let lower = part.trim().to_lowercase(); let lower = part.trim().to_lowercase();
if lower.len() >= 3 && !ignored.contains(&lower.as_str()) if lower.len() >= 3 && !ignored.contains(&lower.as_str()) && !tokens.contains(&lower) {
&& !tokens.contains(&lower) {
tokens.push(lower); tokens.push(lower);
} }
} }
tokens tokens
} }
/// Hedef metin içinde tam kelime sınırlarıyla (word boundary) arama yapar /// Hedef metin içinde tam kelime sınırlarıyla (word boundary) arama yapar.
/// Regex compilation gerektirmez, O(N) karakter incelemesiyle sıfır tahsisatla çalışır.
pub fn contains_word_boundary(text: &str, token: &str) -> bool { pub fn contains_word_boundary(text: &str, token: &str) -> bool {
let pattern = format!(r"(?i)(^|[^a-zA-Z0-9]){}([^a-zA-Z0-9]|$)", regex::escape(token)); if token.is_empty() || text.is_empty() {
match Regex::new(&pattern) { return false;
Ok(re) => re.is_match(text), }
Err(_) => false,
let text_lower = text.to_lowercase();
let token_lower = token.to_lowercase();
let token_bytes = token_lower.as_bytes();
let text_bytes = text_lower.as_bytes();
let mut start_idx = 0;
while let Some(found_idx) = text_lower[start_idx..].find(&token_lower) {
let abs_start = start_idx + found_idx;
let abs_end = abs_start + token_bytes.len();
// Sol sınır kontrolü: Metnin başı mı yoksa önceki karakter harf/rakam değil mi?
let left_ok = if abs_start == 0 {
true
} else {
let prev_char = text_bytes[abs_start - 1] as char;
!prev_char.is_alphanumeric()
};
// Sağ sınır kontrolü: Metnin sonu mu yoksa sonraki karakter harf/rakam değil mi?
let right_ok = if abs_end == text_bytes.len() {
true
} else {
let next_char = text_bytes[abs_end] as char;
!next_char.is_alphanumeric()
};
if left_ok && right_ok {
return true;
}
start_idx = abs_start + 1;
if start_idx >= text_bytes.len() {
break;
} }
} }
false
}
} }

View file

@ -11,7 +11,7 @@ impl StartupService {
pub fn get_startup_items() -> AppResult<Vec<StartupItem>> { pub fn get_startup_items() -> AppResult<Vec<StartupItem>> {
let mut items = Vec::new(); let mut items = Vec::new();
// 1. HKCU Run // 1. HKCU Run & RunDisabled
let hkcu = RegKey::predef(HKEY_CURRENT_USER); let hkcu = RegKey::predef(HKEY_CURRENT_USER);
if let Ok(key) = hkcu.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_READ) { if let Ok(key) = hkcu.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_READ) {
for (name, val) in key.enum_values().filter_map(|v| v.ok()) { for (name, val) in key.enum_values().filter_map(|v| v.ok()) {
@ -26,8 +26,21 @@ impl StartupService {
}); });
} }
} }
if let Ok(key) = hkcu.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\RunDisabled", KEY_READ) {
for (name, val) in key.enum_values().filter_map(|v| v.ok()) {
items.push(StartupItem {
id: format!("hkcu_{}", name),
name: name.clone(),
command: val.to_string(),
location: StartupLocation::RegistryCurrentUser,
is_enabled: false,
publisher: "Kayıt Defteri (Kullanıcı - Devre Dışı)".to_string(),
file_path: val.to_string(),
});
}
}
// 2. HKLM Run // 2. HKLM Run & RunDisabled
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
if let Ok(key) = hklm.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_READ) { if let Ok(key) = hklm.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_READ) {
for (name, val) in key.enum_values().filter_map(|v| v.ok()) { for (name, val) in key.enum_values().filter_map(|v| v.ok()) {
@ -42,6 +55,19 @@ impl StartupService {
}); });
} }
} }
if let Ok(key) = hklm.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\RunDisabled", KEY_READ) {
for (name, val) in key.enum_values().filter_map(|v| v.ok()) {
items.push(StartupItem {
id: format!("hklm_{}", name),
name: name.clone(),
command: val.to_string(),
location: StartupLocation::RegistryLocalMachine,
is_enabled: false,
publisher: "Kayıt Defteri (Sistem - Devre Dışı)".to_string(),
file_path: val.to_string(),
});
}
}
// 3. User Startup Folder // 3. User Startup Folder
if let Ok(appdata) = std::env::var("APPDATA") { if let Ok(appdata) = std::env::var("APPDATA") {
@ -52,9 +78,14 @@ impl StartupService {
let path = entry.path(); let path = entry.path();
let name = entry.file_name().to_string_lossy().to_string(); let name = entry.file_name().to_string_lossy().to_string();
let is_disabled = name.ends_with(".disabled"); let is_disabled = name.ends_with(".disabled");
let clean_name = if is_disabled {
name.trim_end_matches(".disabled").to_string()
} else {
name.clone()
};
items.push(StartupItem { items.push(StartupItem {
id: format!("user_folder_{}", name), id: format!("user_folder_{}", name),
name: name.clone(), name: clean_name,
command: path.to_string_lossy().to_string(), command: path.to_string_lossy().to_string(),
location: StartupLocation::UserStartupFolder, location: StartupLocation::UserStartupFolder,
is_enabled: !is_disabled, is_enabled: !is_disabled,
@ -75,9 +106,14 @@ impl StartupService {
let path = entry.path(); let path = entry.path();
let name = entry.file_name().to_string_lossy().to_string(); let name = entry.file_name().to_string_lossy().to_string();
let is_disabled = name.ends_with(".disabled"); let is_disabled = name.ends_with(".disabled");
let clean_name = if is_disabled {
name.trim_end_matches(".disabled").to_string()
} else {
name.clone()
};
items.push(StartupItem { items.push(StartupItem {
id: format!("common_folder_{}", name), id: format!("common_folder_{}", name),
name: name.clone(), name: clean_name,
command: path.to_string_lossy().to_string(), command: path.to_string_lossy().to_string(),
location: StartupLocation::CommonStartupFolder, location: StartupLocation::CommonStartupFolder,
is_enabled: !is_disabled, is_enabled: !is_disabled,
@ -116,20 +152,50 @@ impl StartupService {
} }
StartupLocation::RegistryCurrentUser => { StartupLocation::RegistryCurrentUser => {
let hkcu = RegKey::predef(HKEY_CURRENT_USER); let hkcu = RegKey::predef(HKEY_CURRENT_USER);
if !enable { if enable {
// RunDisabled -> Run
if let Ok(disabled_key) = hkcu.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\RunDisabled", KEY_ALL_ACCESS) {
if let Ok(val) = disabled_key.get_value::<String, _>(&target.name) {
if let Ok((run_key, _)) = hkcu.create_subkey("Software\\Microsoft\\Windows\\CurrentVersion\\Run") {
let _ = run_key.set_value(&target.name, &val);
let _ = disabled_key.delete_value(&target.name);
}
}
}
} else {
// Run -> RunDisabled
if let Ok(run_key) = hkcu.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_ALL_ACCESS) { if let Ok(run_key) = hkcu.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_ALL_ACCESS) {
if let Ok(val) = run_key.get_value::<String, _>(&target.name) {
if let Ok((disabled_key, _)) = hkcu.create_subkey("Software\\Microsoft\\Windows\\CurrentVersion\\RunDisabled") {
let _ = disabled_key.set_value(&target.name, &val);
let _ = run_key.delete_value(&target.name); let _ = run_key.delete_value(&target.name);
} }
} }
}
}
Ok(true) Ok(true)
} }
StartupLocation::RegistryLocalMachine => { StartupLocation::RegistryLocalMachine => {
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
if !enable { if enable {
if let Ok(disabled_key) = hklm.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\RunDisabled", KEY_ALL_ACCESS) {
if let Ok(val) = disabled_key.get_value::<String, _>(&target.name) {
if let Ok((run_key, _)) = hklm.create_subkey("Software\\Microsoft\\Windows\\CurrentVersion\\Run") {
let _ = run_key.set_value(&target.name, &val);
let _ = disabled_key.delete_value(&target.name);
}
}
}
} else {
if let Ok(run_key) = hklm.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_ALL_ACCESS) { if let Ok(run_key) = hklm.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_ALL_ACCESS) {
if let Ok(val) = run_key.get_value::<String, _>(&target.name) {
if let Ok((disabled_key, _)) = hklm.create_subkey("Software\\Microsoft\\Windows\\CurrentVersion\\RunDisabled") {
let _ = disabled_key.set_value(&target.name, &val);
let _ = run_key.delete_value(&target.name); let _ = run_key.delete_value(&target.name);
} }
} }
}
}
Ok(true) Ok(true)
} }
} }

View file

@ -35,13 +35,10 @@ impl TreemapService {
"#fb923c", "#facc15", "#4ade80", "#2dd4bf", "#fb923c", "#facc15", "#4ade80", "#2dd4bf",
]; ];
let mut sorted_apps = apps.to_vec(); let mut sorted_apps: Vec<&ApplicationEntry> = apps.iter().filter(|a| a.estimated_size_kb > 0).collect();
sorted_apps.sort_by_key(|a| std::cmp::Reverse(a.estimated_size_kb)); sorted_apps.sort_unstable_by_key(|a| std::cmp::Reverse(a.estimated_size_kb));
for (idx, app) in sorted_apps.iter().enumerate() { for (idx, app) in sorted_apps.into_iter().enumerate() {
if app.estimated_size_kb == 0 {
continue;
}
let size_bytes = app.estimated_size_kb * 1024; let size_bytes = app.estimated_size_kb * 1024;
let color = colors[idx % colors.len()]; let color = colors[idx % colors.len()];

View file

@ -1,8 +1,11 @@
use crate::error::{AppError, AppResult}; use crate::error::{AppError, AppResult};
use crate::models::{ApplicationEntry, UninstallerKind}; use crate::models::{ApplicationEntry, UninstallerKind};
use std::os::windows::process::CommandExt;
use std::process::Command; use std::process::Command;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
const CREATE_NO_WINDOW: u32 = 0x08000000;
pub struct UninstallerService; pub struct UninstallerService;
impl UninstallerService { impl UninstallerService {
@ -22,6 +25,7 @@ impl UninstallerService {
// Steam URI protokolü çağrılır // Steam URI protokolü çağrılır
let _ = Command::new("cmd") let _ = Command::new("cmd")
.args(["/c", "start", "", cmd_string]) .args(["/c", "start", "", cmd_string])
.creation_flags(CREATE_NO_WINDOW)
.spawn()?; .spawn()?;
Ok(true) Ok(true)
} }
@ -29,6 +33,7 @@ impl UninstallerService {
// Remove-AppxPackage komutunu çalıştır // Remove-AppxPackage komutunu çalıştır
let output = Command::new("powershell") let output = Command::new("powershell")
.args(["-NoProfile", "-Command", cmd_string]) .args(["-NoProfile", "-Command", cmd_string])
.creation_flags(CREATE_NO_WINDOW)
.output()?; .output()?;
if output.status.success() { if output.status.success() {
Ok(true) Ok(true)
@ -67,6 +72,7 @@ impl UninstallerService {
fn run_shell_wait(raw_cmd: &str, timeout: Duration) -> AppResult<bool> { fn run_shell_wait(raw_cmd: &str, timeout: Duration) -> AppResult<bool> {
let mut child = Command::new("cmd") let mut child = Command::new("cmd")
.args(["/c", raw_cmd]) .args(["/c", raw_cmd])
.creation_flags(CREATE_NO_WINDOW)
.spawn() .spawn()
.map_err(|e| AppError::Execution(format!("Kaldırıcı başlatılamadı: {}", e)))?; .map_err(|e| AppError::Execution(format!("Kaldırıcı başlatılamadı: {}", e)))?;

View file

@ -9,6 +9,8 @@ fn test_safety_blacklist_critical_system_paths() {
assert!(SafetyBlacklist::is_dangerous_file_path("C:\\Windows\\WinSxS")); assert!(SafetyBlacklist::is_dangerous_file_path("C:\\Windows\\WinSxS"));
assert!(SafetyBlacklist::is_dangerous_file_path("C:\\")); assert!(SafetyBlacklist::is_dangerous_file_path("C:\\"));
assert!(SafetyBlacklist::is_dangerous_file_path("D:\\")); assert!(SafetyBlacklist::is_dangerous_file_path("D:\\"));
assert!(SafetyBlacklist::is_dangerous_file_path("C:"));
assert!(SafetyBlacklist::is_dangerous_file_path("c:/"));
assert!(SafetyBlacklist::is_dangerous_file_path("C:\\Program Files\\WindowsApps")); assert!(SafetyBlacklist::is_dangerous_file_path("C:\\Program Files\\WindowsApps"));
assert!(SafetyBlacklist::is_dangerous_file_path("C:\\ProgramData\\Package Cache")); assert!(SafetyBlacklist::is_dangerous_file_path("C:\\ProgramData\\Package Cache"));
} }
@ -26,6 +28,7 @@ fn test_safety_blacklist_registry() {
assert!(SafetyBlacklist::is_dangerous_registry_path("HKLM\\SYSTEM")); assert!(SafetyBlacklist::is_dangerous_registry_path("HKLM\\SYSTEM"));
assert!(SafetyBlacklist::is_dangerous_registry_path("HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer")); assert!(SafetyBlacklist::is_dangerous_registry_path("HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer"));
assert!(SafetyBlacklist::is_dangerous_registry_path("HKEY_LOCAL_MACHINE\\SAM")); assert!(SafetyBlacklist::is_dangerous_registry_path("HKEY_LOCAL_MACHINE\\SAM"));
assert!(SafetyBlacklist::is_dangerous_registry_path("HKCR"));
// Güvenli uygulama anahtarları // Güvenli uygulama anahtarları
assert!(!SafetyBlacklist::is_dangerous_registry_path("HKCU\\Software\\Valve\\Steam")); assert!(!SafetyBlacklist::is_dangerous_registry_path("HKCU\\Software\\Valve\\Steam"));
@ -37,6 +40,8 @@ fn test_sift4_distance() {
assert_eq!(Sift4::distance("notepad", "notepad", 5), 0); assert_eq!(Sift4::distance("notepad", "notepad", 5), 0);
assert_eq!(Sift4::distance("vlc", "vlc player", 5), 7); assert_eq!(Sift4::distance("vlc", "vlc player", 5), 7);
assert!(Sift4::distance("photoshop", "photoshp", 5) <= 1); assert!(Sift4::distance("photoshop", "photoshp", 5) <= 1);
assert_eq!(Sift4::distance("", "", 5), 0);
assert_eq!(Sift4::distance("test", "", 5), 4);
} }
#[test] #[test]
@ -49,6 +54,9 @@ fn test_sift4_tokenize() {
assert!(vlc_tokens.contains(&"vlc".to_string())); assert!(vlc_tokens.contains(&"vlc".to_string()));
assert!(vlc_tokens.contains(&"media".to_string())); assert!(vlc_tokens.contains(&"media".to_string()));
assert!(vlc_tokens.contains(&"player".to_string())); assert!(vlc_tokens.contains(&"player".to_string()));
let empty_tokens = Sift4::tokenize("--- !!! ???");
assert!(empty_tokens.is_empty());
} }
#[test] #[test]
@ -56,6 +64,10 @@ fn test_sift4_contains_word_boundary() {
assert!(Sift4::contains_word_boundary("C:\\Program Files\\Mozilla Firefox", "firefox")); assert!(Sift4::contains_word_boundary("C:\\Program Files\\Mozilla Firefox", "firefox"));
assert!(Sift4::contains_word_boundary("Google Chrome (64-bit)", "chrome")); assert!(Sift4::contains_word_boundary("Google Chrome (64-bit)", "chrome"));
assert!(!Sift4::contains_word_boundary("C:\\Photostudio\\app.exe", "studio")); assert!(!Sift4::contains_word_boundary("C:\\Photostudio\\app.exe", "studio"));
assert!(!Sift4::contains_word_boundary("C:\\SteamEngine\\game.exe", "steam"));
assert!(Sift4::contains_word_boundary("C:\\Games\\Steam-Games\\App", "steam"));
assert!(!Sift4::contains_word_boundary("", "test"));
assert!(!Sift4::contains_word_boundary("test", ""));
} }
#[test] #[test]

View file

@ -54,7 +54,7 @@ export const App: React.FC = () => {
}; };
return ( return (
<div className="flex h-screen w-screen bg-ld-bg text-slate-100 select-none overflow-hidden font-sans"> <div className="flex flex-col h-screen w-screen bg-ld-bg text-slate-100 select-none overflow-hidden font-sans">
{/* Özel Pencere Başlık Çubuğu & OTA Bildirim Bannerı */} {/* Özel Pencere Başlık Çubuğu & OTA Bildirim Bannerı */}
<Titlebar /> <Titlebar />
<UpdateBanner /> <UpdateBanner />

View file

@ -23,7 +23,7 @@ export const Titlebar: React.FC = () => {
updateMaximized(); updateMaximized();
const unlisten = appWindow.onResized(updateMaximized); const unlisten = appWindow.onResized(updateMaximized);
return () => { return () => {
unlisten.then((fn) => fn()); unlisten.then((fn) => fn()).catch(() => {});
}; };
}, []); }, []);

View file

@ -114,7 +114,7 @@ export const api = {
getInstalledApps: (): Promise<ApplicationEntry[]> => invoke('get_installed_apps'), getInstalledApps: (): Promise<ApplicationEntry[]> => invoke('get_installed_apps'),
uninstallApplication: (appId: string, quiet: boolean): Promise<boolean> => uninstallApplication: (appId: string, quiet: boolean): Promise<boolean> =>
invoke('uninstall_application', { appId, quiet }), invoke('uninstall_application', { appId, quiet }),
exportAppsCsv: (filePath: string): Promise<boolean> => invoke('export_apps_csv', { filePath }), exportAppsCsv: (filePath: string = ''): Promise<string> => invoke('export_apps_csv', { filePath }),
// Kalıntı Temizliği // Kalıntı Temizliği
scanAppLeftovers: (appName: string, publisher: string, installLocation: string): Promise<JunkScanResult> => scanAppLeftovers: (appName: string, publisher: string, installLocation: string): Promise<JunkScanResult> =>

View file

@ -94,10 +94,9 @@ export const AppsView: React.FC = () => {
}; };
const handleExportCsv = async () => { const handleExportCsv = async () => {
const exportPath = `C:\\Users\\Default\\Desktop\\LD_Uninstaller_Apps.csv`;
try { try {
await api.exportAppsCsv(exportPath); const savedPath = await api.exportAppsCsv('');
addToast('Dışa Aktarıldı', `Liste masaüstüne kaydedildi: ${exportPath}`, 'success'); addToast('Dışa Aktarıldı', `Uygulama listesi kaydedildi: ${savedPath}`, 'success');
} catch (e: any) { } catch (e: any) {
addToast('Hata', String(e), 'error'); addToast('Hata', String(e), 'error');
} }

View file

@ -64,14 +64,20 @@ export const BackupsView: React.FC = () => {
<div className="flex items-center gap-2 shrink-0"> <div className="flex items-center gap-2 shrink-0">
<button <button
onClick={() => restoreBackup(b.file_path)} onClick={() => {
const ok = window.confirm(`"${b.file_name}" yedeğini Windows Kayıt Defterine geri yüklemek istiyor musunuz?`);
if (ok) restoreBackup(b.file_path);
}}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-purple-500/15 border border-purple-500/30 text-purple-300 hover:bg-purple-500/25 transition-all cursor-pointer" className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-purple-500/15 border border-purple-500/30 text-purple-300 hover:bg-purple-500/25 transition-all cursor-pointer"
> >
<RotateCcw className="w-3.5 h-3.5" /> <RotateCcw className="w-3.5 h-3.5" />
Geri Yükle Geri Yükle
</button> </button>
<button <button
onClick={() => deleteBackup(b.file_path)} onClick={() => {
const ok = window.confirm(`"${b.file_name}" yedeğini silmek istediğinize emin misiniz?`);
if (ok) deleteBackup(b.file_path);
}}
className="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-rose-500/10 transition-colors cursor-pointer" className="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-rose-500/10 transition-colors cursor-pointer"
> >
<Trash2 className="w-3.5 h-3.5" /> <Trash2 className="w-3.5 h-3.5" />

View file

@ -1,4 +1,4 @@
import React, { useEffect } from 'react'; import React, { useEffect, useMemo } from 'react';
import { useAppStore } from '../store/useAppStore'; import { useAppStore } from '../store/useAppStore';
import { HardDrive, RefreshCw, Layers } from 'lucide-react'; import { HardDrive, RefreshCw, Layers } from 'lucide-react';
@ -9,6 +9,10 @@ export const TreemapView: React.FC = () => {
loadTreemap(); loadTreemap();
}, []); }, []);
const totalTreemapValue = useMemo(() => {
return treemapItems.reduce((acc, i) => acc + i.value, 0);
}, [treemapItems]);
const formatBytes = (bytes: number) => { const formatBytes = (bytes: number) => {
const gb = bytes / (1024 * 1024 * 1024); const gb = bytes / (1024 * 1024 * 1024);
return `${gb.toFixed(1)} GB`; return `${gb.toFixed(1)} GB`;
@ -96,8 +100,7 @@ export const TreemapView: React.FC = () => {
) : ( ) : (
<div className="flex flex-wrap gap-1.5 h-96 p-2 rounded-lg bg-ld-card/50 border border-ld-border/50 overflow-hidden"> <div className="flex flex-wrap gap-1.5 h-96 p-2 rounded-lg bg-ld-card/50 border border-ld-border/50 overflow-hidden">
{treemapItems.slice(0, 36).map((item) => { {treemapItems.slice(0, 36).map((item) => {
const totalValue = treemapItems.reduce((acc, i) => acc + i.value, 0); const pct = totalTreemapValue > 0 ? (item.value / totalTreemapValue) * 100 : 2;
const pct = totalValue > 0 ? (item.value / totalValue) * 100 : 2;
const flexGrow = Math.max(1, Math.round(pct * 2)); const flexGrow = Math.max(1, Math.round(pct * 2));
return ( return (

View file

@ -369,6 +369,20 @@ export const useAppStore = create<AppStore>((set, get) => ({
try { try {
await api.addExclusion(path); await api.addExclusion(path);
await get().loadExclusions(); await get().loadExclusions();
// Korunan öğeyi aktif kalıntı listesinden ve seçimlerden anında çıkar
const currentResult = get().leftoverResult;
if (currentResult) {
const updatedItems = currentResult.items.filter((i) => i.path !== path);
set({
leftoverResult: { ...currentResult, items: updatedItems },
selectedLeftoverIds: get().selectedLeftoverIds.filter((id) => {
const item = currentResult.items.find((i) => i.id === id);
return item ? item.path !== path : true;
}),
});
}
get().addToast('Korumaya Alındı', `'${path}' koruma listesine eklendi.`, 'success'); get().addToast('Korumaya Alındı', `'${path}' koruma listesine eklendi.`, 'success');
} catch (err: any) { } catch (err: any) {
get().addToast('Hata', String(err), 'error'); get().addToast('Hata', String(err), 'error');