commit 3867a440a099c72f9e5e0e11b3ed34883693c95f Author: LilDosto Date: Wed Oct 28 06:10:44 2026 +0300 Release v2.3.1: Ultra akici performans yamasi, coklu disk analizi ve otomatik kalinti temizleyici diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b9d4a3d --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +## Visual Studio / .NET +[Bb]in/ +[Oo]bj/ +*.user +*.suo +*.userosscache +*.sln.docstates +.vs/ +.idea/ + +## Logs and traces +*.log +trace.log +crash_*.log +test_*.json + +## Release packages & archives +*.zip +LD Uninstaller v*/ +dist/ +publish/ diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..8cc6f1e --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,10 @@ + + + 2.3.1 + 2.3.1.0 + 2.3.1.0 + LD Uninstaller + LD Software + LD Software + + diff --git a/LDUninstaller.sln b/LDUninstaller.sln new file mode 100644 index 0000000..8dfe64f --- /dev/null +++ b/LDUninstaller.sln @@ -0,0 +1,55 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{AE9859BA-F5B7-476C-9ACF-870E6CB944B0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDUninstaller.Core", "src\LDUninstaller.Core\LDUninstaller.Core.csproj", "{CD3DDC8C-4415-46B1-9E3D-C71152DE0902}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDUninstaller.Automatizer", "src\LDUninstaller.Automatizer\LDUninstaller.Automatizer.csproj", "{7A617868-4F8D-4206-A0EF-D818F0963703}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDUninstaller.CLI", "src\LDUninstaller.CLI\LDUninstaller.CLI.csproj", "{715A77F8-93E4-4D03-BAD1-6F749A803288}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDUninstaller.UI", "src\LDUninstaller.UI\LDUninstaller.UI.csproj", "{894C87C4-22A2-4935-9238-ED19CB1AD23C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDUninstaller.Launcher", "src\LDUninstaller.Launcher\LDUninstaller.Launcher.csproj", "{8B9A7CB4-F72E-42F3-ADC9-A253FBE447E3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CD3DDC8C-4415-46B1-9E3D-C71152DE0902}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CD3DDC8C-4415-46B1-9E3D-C71152DE0902}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CD3DDC8C-4415-46B1-9E3D-C71152DE0902}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CD3DDC8C-4415-46B1-9E3D-C71152DE0902}.Release|Any CPU.Build.0 = Release|Any CPU + {7A617868-4F8D-4206-A0EF-D818F0963703}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7A617868-4F8D-4206-A0EF-D818F0963703}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7A617868-4F8D-4206-A0EF-D818F0963703}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7A617868-4F8D-4206-A0EF-D818F0963703}.Release|Any CPU.Build.0 = Release|Any CPU + {715A77F8-93E4-4D03-BAD1-6F749A803288}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {715A77F8-93E4-4D03-BAD1-6F749A803288}.Debug|Any CPU.Build.0 = Debug|Any CPU + {715A77F8-93E4-4D03-BAD1-6F749A803288}.Release|Any CPU.ActiveCfg = Release|Any CPU + {715A77F8-93E4-4D03-BAD1-6F749A803288}.Release|Any CPU.Build.0 = Release|Any CPU + {894C87C4-22A2-4935-9238-ED19CB1AD23C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {894C87C4-22A2-4935-9238-ED19CB1AD23C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {894C87C4-22A2-4935-9238-ED19CB1AD23C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {894C87C4-22A2-4935-9238-ED19CB1AD23C}.Release|Any CPU.Build.0 = Release|Any CPU + {8B9A7CB4-F72E-42F3-ADC9-A253FBE447E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8B9A7CB4-F72E-42F3-ADC9-A253FBE447E3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8B9A7CB4-F72E-42F3-ADC9-A253FBE447E3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8B9A7CB4-F72E-42F3-ADC9-A253FBE447E3}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {CD3DDC8C-4415-46B1-9E3D-C71152DE0902} = {AE9859BA-F5B7-476C-9ACF-870E6CB944B0} + {7A617868-4F8D-4206-A0EF-D818F0963703} = {AE9859BA-F5B7-476C-9ACF-870E6CB944B0} + {715A77F8-93E4-4D03-BAD1-6F749A803288} = {AE9859BA-F5B7-476C-9ACF-870E6CB944B0} + {894C87C4-22A2-4935-9238-ED19CB1AD23C} = {AE9859BA-F5B7-476C-9ACF-870E6CB944B0} + {8B9A7CB4-F72E-42F3-ADC9-A253FBE447E3} = {AE9859BA-F5B7-476C-9ACF-870E6CB944B0} + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md new file mode 100644 index 0000000..cf130ea --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +# LD Uninstaller (Modern v2.3.1 Pro Edition) + +**LD Uninstaller**, Bulk Crap Uninstaller (BCU) endüstri standardı mimarisini temel alan; donanım hızlandırmalı modern **Windows 11 Fluent Dark** arayüzü, çoklu disk analizi ve akıllı otomasyon ajanıyla güçlendirilmiş açık kaynaklı, endüstri standardı sistem yönetimi ve yazılım kaldırma çözümüdür. + +--- + +## ✨ Öne Çıkan Özellikler + +### 1. ⚡ Ultra Akıcı Performans & Sıfır Takılma (Fluidity & Optimization) +- **Gecikmesiz Arama (Debounced Search):** Arama çubuğuna yazarken UI thread'i dondurmayan 160ms debounce filtreleme. +- **Piksel Düzeyinde Pürüzsüz Kaydırma:** DataGrid sanallaştırması `VirtualizingPanel.ScrollUnit="Pixel"` ve `Recycling` modlarıyla 120 FPS akıcılık sağlar. +- **Donanım Hızlandırmalı Squarified Treemap:** Vektörel çizim elemanları, dondurulmuş (frozen) Direct3D fırçaları ve statik tipografiler ile anında disk görselleştirmesi. +- **Asenkron Başlatma:** Başlangıç yöneticisi ve debloat ayarları arka plan görevlerinde yüklenerek uygulamanın anında açılmasını sağlar. + +### 2. 💾 Çoklu Disk Analizi & Üst Sekmeler (Multi-Drive Tab System) +- Bilgisayara takılı tüm aktif diskleri (`C:`, `D:`, harici sürücüler vb.) otomatik tespit eder ve analiz eder. +- Birden fazla disk bağlıysa üst kısımda modern sekmeler belirir: + - **`🌐 Tüm Diskler`**: Sistemdeki tüm sürücüleri ve tüm yazılımları bir arada sunar. + - **`💾 C: (Yerel Disk)`**: C sürücüsündeki yazılımları, kullanılan alanı ve boş kapasiteyi filtreler. + - **`💾 D: (Depolama / Oyunlar)`**: İkincil diskteki yazılımları ve Steam/Epic/Games kütüphanelerini listeler. +- Disk sekmeleri değiştikçe hem **Yazılım Tablosu** hem de **Disk Haritası (TreeMap)** sadece seçilen diski görselleştirecek şekilde dinamik olarak güncellenir. + +### 3. 🧹 Otomatik Kalıntı ve Artık Temizleme Motoru (Leftover Cleaner) +- Kaldırma işlemi (tekli veya çoklu) tamamlandığı anda **Kalıntı Temizleme Ekranı** otomatik olarak açılır. +- **Derin Tarama Kapsamı:** + - Ana kurulum klasörleri + - `%AppData%`, `%LocalAppData%`, `%LocalAppData%\LocalLow`, `%ProgramData%` + - Belgeler ve Kayıtlı Oyunlar (Saved Games) + - 64-bit & 32-bit (`WOW6432Node`) Kayıt Defteri Software dalları + - Uninstaller kayıt girdileri + - Windows Prefetch, WER Crash Dumps ve Güvenlik Duvarı kuralları +- **Seçim Kolaylığı:** "Tümünü Seç / Seçimi Kaldır" özelliği ve her satır için bağımsız onay kutuları ile silme öncesinde otomatik `.reg` yedeği alınır. + +### 4. 🚀 Tek Tıkla Kaldırma & Akıllı Kuyruk Matrisi +- Karmaşık butonlar yerine sadece **`🗑️ Kaldır`** butonu. 1 yazılım seçildiğinde tekli, birden fazla seçildiğinde toplu kuyruk yönetimini otomatik üstlenir. +- **Çakışma Önleyici Kuyruk (Collision Matrix):** Windows Installer (`_MSIExecute` mutex) kilitlerini, aynı yayıncı ve aynı dizin bağımlılıklarını otomatik olarak sıraya dizer. +- **Uninstaller Automatizer Daemon:** UI Automation (FlaUI) arka plan servisi ile kaldırıcı pencerelerindeki "İleri", "Kaldır", "Bitir" adımlarını sessizce otomatik tıklar. + +### 5. ⚡ Başlangıç Yöneticisi & Windows Debloat +- **StartupApproved Standardı:** Kayıt defteri ve başlangıç klasörlerindeki programları silmeden güvenle açıp kapatma. +- **Debloat Optimizasyonları:** Windows telemetri servislerini (DiagTrack), Cortana/Bing web aramalarını ve sponsorlu arka plan mağaza uygulamalarını tek tıkla kapatma. + +--- + +## 📦 Dağıtım ve Yayınlama (Release Management) + +Projeyi derlemek ve belirlenen kurallara göre tek klasörde paketlemek için PowerShell otomasyonu: + +```powershell +# Ufak hata düzeltmesi / bugfix (0.0.1 artırır: v2.3.1 -> v2.3.2) +.\release.ps1 -Type patch + +# Orta / yeni özellik güncellemesi (0.1 artırır: v2.3.1 -> v2.4.0) +.\release.ps1 -Type minor + +# Büyük mimari güncelleme (1 artırır: v2.3.1 -> v3.0.0) +.\release.ps1 -Type major +``` + +Script, kök dizindeki eski sürümleri temizler ve yalnızca en güncel sürüm klasörünü (`LD Uninstaller vX.Y.Z`) oluşturur. + +--- + +## 💻 Başlatma ve Kullanım + +```powershell +# Yönetici yetkili başlatıcı: +.\LD Uninstaller v2.3.1\LDUninstaller.Launcher.exe + +# veya doğrudan arayüz: +.\LD Uninstaller v2.3.1\LDUninstaller.UI.exe + +# SysAdmin ve Otomasyon için CLI aracı: +.\LD Uninstaller v2.3.1\LDUninstaller.CLI.exe list /F=table +.\LD Uninstaller v2.3.1\LDUninstaller.CLI.exe export software_inventory.json /F=json +.\LD Uninstaller v2.3.1\LDUninstaller.CLI.exe debloat --list +``` diff --git a/release.ps1 b/release.ps1 new file mode 100644 index 0000000..2a7d1f3 --- /dev/null +++ b/release.ps1 @@ -0,0 +1,139 @@ +param( + [ValidateSet("major", "minor", "patch", "current")] + [string]$Type = "current" +) + +$ErrorActionPreference = "Stop" +$root = $PSScriptRoot +if (-not $root) { $root = (Get-Location).Path } + +$versionFile = Join-Path $root "version.json" +$propsFile = Join-Path $root "Directory.Build.props" + +if (-not (Test-Path $versionFile)) { + @{ major = 2; minor = 1; patch = 1; version = "2.1.1" } | ConvertTo-Json | Set-Content $versionFile +} + +$vData = Get-Content $versionFile -Raw | ConvertFrom-Json +$major = [int]$vData.major +$minor = [int]$vData.minor +$patch = [int]$vData.patch + +switch ($Type.ToLowerInvariant()) { + "major" { + $major += 1 + $minor = 0 + $patch = 0 + } + "minor" { + $minor += 1 + $patch = 0 + } + "patch" { + $patch += 1 + } + "current" { + # Keep existing version for initial packaging + } +} + +$newVersion = "$major.$minor.$patch" +$vData.major = $major +$vData.minor = $minor +$vData.patch = $patch +$vData.version = $newVersion + +$vData | ConvertTo-Json | Set-Content $versionFile -Encoding UTF8 + +# Update Directory.Build.props +$propsContent = @" + + + $newVersion + $newVersion.0 + $newVersion.0 + LD Uninstaller + LD Software + LD Software + + +"@ +Set-Content -Path $propsFile -Value $propsContent -Encoding UTF8 + +Write-Host "==========================================" -ForegroundColor Cyan +Write-Host " LD UNINSTALLER SÜRÜM YAYINLAMA: v$newVersion" -ForegroundColor Yellow +Write-Host "==========================================" -ForegroundColor Cyan + +# 1. Ana klasörde eski sürümleri temizle (Sadece tek ve son sürüm kalacak şekilde) +$oldFolders = Get-ChildItem -Path $root -Directory -Filter "LD Uninstaller v*" +foreach ($old in $oldFolders) { + Write-Host "Eski sürüm klasörü temizleniyor: $($old.Name)..." -ForegroundColor Gray + try { + Remove-Item -Path $old.FullName -Recurse -Force -ErrorAction SilentlyContinue + } catch { } +} + +$targetFolderName = "LD Uninstaller v$newVersion" +$targetDir = Join-Path $root $targetFolderName + +Write-Host "Yeni sürüm klasörü oluşturuluyor: $targetFolderName..." -ForegroundColor Green +New-Item -ItemType Directory -Path $targetDir -Force | Out-Null + +# 2. Projeleri Release modunda derle ve tek klasöre aktar +Write-Host "Projeler derleniyor ve yayınlanıyor..." -ForegroundColor Cyan + +$projects = @( + "src/LDUninstaller.UI/LDUninstaller.UI.csproj", + "src/LDUninstaller.CLI/LDUninstaller.CLI.csproj", + "src/LDUninstaller.Automatizer/LDUninstaller.Automatizer.csproj", + "src/LDUninstaller.Launcher/LDUninstaller.Launcher.csproj" +) + +foreach ($proj in $projects) { + $projPath = Join-Path $root $proj + Write-Host " -> Yayınlanıyor: $proj" -ForegroundColor Gray + dotnet publish $projPath -c Release -o $targetDir --nologo -v q +} + +# 3. Gereksiz pdb ve log dosyalarını temizle +Get-ChildItem -Path $targetDir -Filter "*.pdb" | Remove-Item -Force -ErrorAction SilentlyContinue + +# 4. Eski publish ve dist klasörlerini de temizle +try { Remove-Item -Path (Join-Path $root "publish") -Recurse -Force -ErrorAction SilentlyContinue } catch { } +try { Remove-Item -Path (Join-Path $root "dist") -Recurse -Force -ErrorAction SilentlyContinue } catch { } + +# 5. Sürüm ZIP Arşivini Oluştur (GitHub Releases için) +$zipName = "LD-Uninstaller-v$newVersion.zip" +$zipPath = Join-Path $root $zipName +Write-Host "Sürüm arşivi oluşturuluyor: $zipName..." -ForegroundColor Cyan +if (Test-Path $zipPath) { Remove-Item $zipPath -Force } +Compress-Archive -Path "$targetDir\*" -DestinationPath $zipPath -Force + +# 6. Git Değişiklikleri, Etiket (Tag) ve GitHub Senkronizasyonu +if (Test-Path (Join-Path $root ".git")) { + Write-Host "`nGit değişiklikleri işleniyor ve GitHub'a aktarılıyor..." -ForegroundColor Cyan + try { + git add . + git commit -m "Release v${newVersion}: Ultra akici performans yamasi, coklu disk analizi ve otomatik kalinti temizleyici" + git tag -a "v$newVersion" -m "LD Uninstaller v$newVersion" -f + + $remote = git remote get-url origin 2>$null + if ($remote) { + Write-Host "GitHub'a gönderiliyor (origin master --tags)..." -ForegroundColor Yellow + git push origin master --tags -u + } + } catch { + Write-Host "Git işlemi uyarısı: $_" -ForegroundColor Yellow + } +} + +Write-Host "`n✅ Başarıyla Tamamlandı!" -ForegroundColor Green +Write-Host "Ana dizinde oluşturulan son güncel sürüm klasörü:" -ForegroundColor Yellow +Write-Host " -> $targetFolderName" -ForegroundColor White +Write-Host "GitHub Release için hazır paket:" -ForegroundColor White +Write-Host " -> $zipName" -ForegroundColor Cyan +Write-Host "Kullanıma hazır yürütülebilir dosyalar:" -ForegroundColor Gray +Write-Host " - LDUninstaller.Launcher.exe (Yönetici yetkili başlatıcı)" +Write-Host " - LDUninstaller.UI.exe (Modern Fluent Arayüz)" +Write-Host " - LDUninstaller.CLI.exe (Konsol aracı)" +Write-Host " - LDUninstaller.Automatizer.exe (Otomasyon ajanı)`n" diff --git a/src/LDUninstaller.Automatizer/LDUninstaller.Automatizer.csproj b/src/LDUninstaller.Automatizer/LDUninstaller.Automatizer.csproj new file mode 100644 index 0000000..e7317e1 --- /dev/null +++ b/src/LDUninstaller.Automatizer/LDUninstaller.Automatizer.csproj @@ -0,0 +1,18 @@ + + + + WinExe + net8.0-windows + enable + enable + true + LDUninstaller.Automatizer + LDUninstaller.Automatizer + + + + + + + + diff --git a/src/LDUninstaller.Automatizer/Program.cs b/src/LDUninstaller.Automatizer/Program.cs new file mode 100644 index 0000000..7e56fc7 --- /dev/null +++ b/src/LDUninstaller.Automatizer/Program.cs @@ -0,0 +1,241 @@ +using System; +using System.Collections.Concurrent; +using System.Diagnostics; +using System.IO; +using System.IO.Pipes; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using FlaUI.Core.AutomationElements; +using FlaUI.Core.Definitions; +using FlaUI.UIA3; +using LDUninstaller.Core.Native; + +namespace LDUninstaller.Automatizer +{ + internal class Program + { + private static readonly ConcurrentDictionary MonitoredProcesses = new(); + private static readonly string[] GoodButtonTexts = new[] + { + "next", "uninstall", "continue", "finish", "close", "i agree", "ok", "yes", + "ileri", "kaldır", "devam", "bitir", "kapat", "kabul ediyorum", "tamam", "evet", + "suivant", "weiter", "fertigstellen", "schließen", "désinstaller" + }; + + private static readonly string[] BadButtonTexts = new[] + { + "install bloatware", "change homepage", "reboot now", "ankete katıl", + "survey", "reboot computer now", "şimdi yeniden başlat" + }; + + private static readonly string[] BadCheckboxTexts = new[] + { + "reboot now", "şimdi yeniden başlat", "install", "toolbar", "browser", "search engine", + "anket", "survey", "homepage", "launch", "çalıştır" + }; + + [STAThread] + static void Main(string[] args) + { + bool isDaemon = args.Contains("/d") || args.Contains("--daemon") || args.Length == 0; + Console.WriteLine("=== LD Uninstaller Automation Daemon ==="); + + if (args.Length > 0 && int.TryParse(args[0], out int singlePid)) + { + // Direct PID mode + MonitorProcess(singlePid, stealth: false); + return; + } + + // Start Named Pipe listener loop in background + var cts = new CancellationTokenSource(); + _ = Task.Run(() => StartPipeServer(cts.Token)); + + // Start Automation Monitoring Loop + using var automation = new UIA3Automation(); + Console.WriteLine("Daemon aktif. Named Pipe '\\\\.\\pipe\\LDUninstallerDaemon' dinleniyor..."); + + while (true) + { + try + { + foreach (var kvp in MonitoredProcesses.ToArray()) + { + int pid = kvp.Key; + DateTime startTime = kvp.Value; + + // Check watchdog timeout (5 minutes) + if ((DateTime.Now - startTime).TotalMinutes > 5) + { + Console.WriteLine($"[Watchdog] PID {pid} zaman aşımına uğradı, sonlandırılıyor."); + try + { + var p = Process.GetProcessById(pid); + p.Kill(); + } + catch { } + MonitoredProcesses.TryRemove(pid, out _); + continue; + } + + // Check if process still exists + try + { + var proc = Process.GetProcessById(pid); + if (proc.HasExited) + { + MonitoredProcesses.TryRemove(pid, out _); + continue; + } + + // Automate UI windows for this PID + AutomateProcessWindows(automation, proc); + } + catch (ArgumentException) + { + MonitoredProcesses.TryRemove(pid, out _); + } + catch (Exception ex) + { + Console.WriteLine($"[Hata PID {pid}] {ex.Message}"); + } + } + } + catch { } + + Thread.Sleep(800); + } + } + + private static void StartPipeServer(CancellationToken token) + { + while (!token.IsCancellationRequested) + { + try + { + using var server = new NamedPipeServerStream("LDUninstallerDaemon", PipeDirection.In); + server.WaitForConnection(); + using var reader = new StreamReader(server); + string? line = reader.ReadLine(); + + if (!string.IsNullOrWhiteSpace(line) && line.StartsWith("ATTACH:", StringComparison.OrdinalIgnoreCase)) + { + string pidStr = line["ATTACH:".Length..].Trim(); + if (int.TryParse(pidStr, out int pid)) + { + Console.WriteLine($"[IPC] Takip edilecek PID alındı: {pid}"); + MonitoredProcesses.TryAdd(pid, DateTime.Now); + } + } + } + catch { } + } + } + + private static void MonitorProcess(int pid, bool stealth) + { + using var automation = new UIA3Automation(); + Console.WriteLine($"PID {pid} izleniyor..."); + + try + { + var proc = Process.GetProcessById(pid); + while (!proc.HasExited) + { + AutomateProcessWindows(automation, proc, stealth); + Thread.Sleep(800); + } + } + catch (Exception ex) + { + Console.WriteLine($"İzleme tamamlandı: {ex.Message}"); + } + } + + private static void AutomateProcessWindows(UIA3Automation automation, Process proc, bool stealth = false) + { + var desktop = automation.GetDesktop(); + var windows = desktop.FindAllChildren(cf => cf.ByProcessId(proc.Id)); + + foreach (var win in windows) + { + try + { + IntPtr hwnd = win.Properties.NativeWindowHandle.ValueOrDefault; + if (stealth && hwnd != IntPtr.Zero) + { + Win32.SetWindowPos(hwnd, IntPtr.Zero, -32000, -32000, 0, 0, Win32.SWP_NOSIZE | Win32.SWP_NOZORDER); + } + + // Check radio buttons: NSIS 1204 (Reboot Later) vs 1203 (Reboot Now) + var radioButtons = win.FindAllDescendants(cf => cf.ByControlType(ControlType.RadioButton)); + foreach (var rb in radioButtons) + { + string autoId = rb.AutomationId ?? ""; + string name = rb.Name?.ToLowerInvariant() ?? ""; + + if (autoId == "1204" || name.Contains("later") || name.Contains("sonra")) + { + var r = rb.AsRadioButton(); + if (r != null) r.IsChecked = true; + Console.WriteLine($"[AutoUI] 'Daha sonra yeniden başlat' seçildi (ID {autoId})"); + } + } + + // Check checkboxes for bloatware / surveys / reboot + var checkBoxes = win.FindAllDescendants(cf => cf.ByControlType(ControlType.CheckBox)); + foreach (var cb in checkBoxes) + { + string cbName = cb.Name?.ToLowerInvariant() ?? ""; + foreach (var bad in BadCheckboxTexts) + { + if (cbName.Contains(bad)) + { + var checkBox = cb.AsCheckBox(); + if (checkBox != null && checkBox.IsChecked == true) + { + checkBox.IsChecked = false; + Console.WriteLine($"[AutoUI] İstenmeyen onay kutusu temizlendi: {cb.Name}"); + } + } + } + } + + // Check standard buttons + var buttons = win.FindAllDescendants(cf => cf.ByControlType(ControlType.Button)); + foreach (var btn in buttons) + { + string btnId = btn.AutomationId ?? ""; + string btnText = btn.Name?.Trim().ToLowerInvariant() ?? ""; + + // Prioritize NSIS standard Next button ID 1 or Close/Finish + if (btnId == "1" || IsGoodButton(btnText)) + { + if (!IsBadButton(btnText) && btn.IsEnabled) + { + Console.WriteLine($"[AutoUI] Buton tıklandı: '{btn.Name}' (ID: {btnId})"); + btn.AsButton()?.Invoke(); + Thread.Sleep(300); + break; + } + } + } + } + catch { } + } + } + + private static bool IsGoodButton(string text) + { + if (string.IsNullOrWhiteSpace(text)) return false; + return GoodButtonTexts.Any(g => text.Equals(g, StringComparison.OrdinalIgnoreCase) || text.Contains(g, StringComparison.OrdinalIgnoreCase)); + } + + private static bool IsBadButton(string text) + { + if (string.IsNullOrWhiteSpace(text)) return false; + return BadButtonTexts.Any(b => text.Contains(b, StringComparison.OrdinalIgnoreCase)); + } + } +} diff --git a/src/LDUninstaller.CLI/LDUninstaller.CLI.csproj b/src/LDUninstaller.CLI/LDUninstaller.CLI.csproj new file mode 100644 index 0000000..0dc3ba2 --- /dev/null +++ b/src/LDUninstaller.CLI/LDUninstaller.CLI.csproj @@ -0,0 +1,16 @@ + + + + Exe + net8.0-windows + enable + enable + LDUninstaller.CLI + LDUninstaller.CLI + + + + + + + diff --git a/src/LDUninstaller.CLI/Program.cs b/src/LDUninstaller.CLI/Program.cs new file mode 100644 index 0000000..2c34a4e --- /dev/null +++ b/src/LDUninstaller.CLI/Program.cs @@ -0,0 +1,341 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; +using System.Xml.Serialization; +using LDUninstaller.Core.Bulk; +using LDUninstaller.Core.Discovery; +using LDUninstaller.Core.InfoAdders; +using LDUninstaller.Core.Junk; +using LDUninstaller.Core.Models; +using LDUninstaller.Core.Tweaks; + +namespace LDUninstaller.CLI +{ + internal class Program + { + static async Task Main(string[] args) + { + Console.OutputEncoding = System.Text.Encoding.UTF8; + + if (args.Length == 0 || args[0] is "-h" or "--help" or "/?") + { + PrintHelp(); + return 0; + } + + string command = args[0].ToLowerInvariant(); + + try + { + switch (command) + { + case "list": + return await HandleListAsync(args.Skip(1).ToArray()); + + case "export": + return await HandleExportAsync(args.Skip(1).ToArray()); + + case "uninstall": + return await HandleUninstallAsync(args.Skip(1).ToArray()); + + case "debloat": + return HandleDebloat(args.Skip(1).ToArray()); + + default: + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"Bilinmeyen komut: {command}"); + Console.ResetColor(); + PrintHelp(); + return 1; + } + } + catch (Exception ex) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"Kritik Hata: {ex.Message}"); + Console.ResetColor(); + return 1; + } + } + + private static void PrintHelp() + { + Console.WriteLine(@" +LD Uninstaller CLI - Gelişmiş Komut Satırı Yönetim Aracı +Kullanım: + LDUninstaller.CLI.exe list [/F=table|json|xml] + LDUninstaller.CLI.exe export [/F=json|xml|csv] + LDUninstaller.CLI.exe uninstall [/Q] [/U] [/J=VeryGood|Good] [/N] + LDUninstaller.CLI.exe debloat [--list | --apply ] + +Parametreler: + /Q Mümkünse sessiz (Quiet) kaldırıcıları tercih et + /U Unattended (Kullanıcıdan onay istemeden yürüt) + /J= Kaldırma sonrası otomatik artık temizleme düzeyi (VeryGood, Good, Questionable) + /N, --dry-run Simülasyon modu. Değişiklik yapmadan yapılacakları listeler + /F= Çıktı formatı: table, json, xml, csv +"); + } + + private static async Task> ScanAndEnrichAsync() + { + var sw = System.Diagnostics.Stopwatch.StartNew(); + Console.WriteLine("[1/3] Sistem taranıyor (Kayıt Defteri, Store, Steam)..."); + var pipeline = new DiscoveryPipeline(); + pipeline.OnProgress += (msg, pct) => Console.WriteLine($" -> {msg} (%{pct})"); + var list = await pipeline.DiscoverAllAsync(); + Console.WriteLine($"[1/3] Keşif tamamlandı ({list.Count} girdi, {sw.ElapsedMilliseconds} ms)"); + + sw.Restart(); + Console.WriteLine("[2/3] Eksik bilgiler ve sertifikalar tamamlanıyor..."); + var adder = new InfoAdderManager(); + adder.ProcessAll(list); + Console.WriteLine($"[2/3] Zenginleştirme tamamlandı ({sw.ElapsedMilliseconds} ms)"); + + return list; + } + + private static async Task HandleListAsync(string[] args) + { + string format = GetArgValue(args, "/F", "table").ToLowerInvariant(); + var list = await ScanAndEnrichAsync(); + + if (format == "json") + { + Console.WriteLine(JsonSerializer.Serialize(list, new JsonSerializerOptions { WriteIndented = true })); + } + else if (format == "xml") + { + var serializer = new XmlSerializer(typeof(List)); + using var sw = new StringWriter(); + serializer.Serialize(sw, list); + Console.WriteLine(sw.ToString()); + } + else + { + Console.WriteLine($"\nToplam Tespit Edilen Uygulama: {list.Count}\n"); + Console.WriteLine($"{"Uygulama Adı",-40} | {"Yayıncı",-25} | {"Boyut",-10} | {"Tür",-12}"); + Console.WriteLine(new string('-', 95)); + + foreach (var app in list.Take(100)) + { + string name = Truncate(app.DisplayName, 38); + string pub = Truncate(app.Publisher, 23); + string sz = app.EstimatedSize.ToString(); + string kind = app.UninstallerKind.ToString(); + Console.WriteLine($"{name,-40} | {pub,-25} | {sz,-10} | {kind,-12}"); + } + + if (list.Count > 100) + { + Console.WriteLine($"... ve {list.Count - 100} uygulama daha."); + } + } + + return 0; + } + + private static async Task HandleExportAsync(string[] args) + { + if (args.Length == 0) + { + Console.WriteLine("Hata: Dışa aktarılacak dosya yolu belirtilmedi. Örnek: export \"C:\\apps.json\""); + return 1; + } + + string filePath = args[0]; + string format = GetArgValue(args, "/F", Path.GetExtension(filePath).TrimStart('.')).ToLowerInvariant(); + if (string.IsNullOrWhiteSpace(format)) format = "json"; + + var list = await ScanAndEnrichAsync(); + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(filePath)) ?? "."); + + if (format == "json") + { + string json = JsonSerializer.Serialize(list, new JsonSerializerOptions { WriteIndented = true }); + File.WriteAllText(filePath, json); + } + else if (format == "csv") + { + using var writer = new StreamWriter(filePath); + writer.WriteLine("DisplayName,Publisher,DisplayVersion,EstimatedSizeBytes,UninstallerKind,InstallLocation"); + foreach (var a in list) + { + writer.WriteLine($"\"{EscapeCsv(a.DisplayName)}\",\"{EscapeCsv(a.Publisher)}\",\"{EscapeCsv(a.DisplayVersion)}\",{a.EstimatedSize.Bytes},\"{a.UninstallerKind}\",\"{EscapeCsv(a.InstallLocation)}\""); + } + } + else if (format == "xml") + { + var serializer = new XmlSerializer(typeof(List)); + using var writer = new StreamWriter(filePath); + serializer.Serialize(writer, list); + } + + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"Başarıyla aktarıldı: {filePath} ({list.Count} kayıt)"); + Console.ResetColor(); + return 0; + } + + private static async Task HandleUninstallAsync(string[] args) + { + if (args.Length == 0) + { + Console.WriteLine("Hata: Kaldırılacak uygulama adı, GUID veya .bcul liste dosyası belirtilmedi."); + return 1; + } + + string target = args[0]; + bool quiet = args.Contains("/Q", StringComparer.OrdinalIgnoreCase); + bool unattended = args.Contains("/U", StringComparer.OrdinalIgnoreCase); + bool dryRun = args.Contains("/N", StringComparer.OrdinalIgnoreCase) || args.Contains("--dry-run", StringComparer.OrdinalIgnoreCase); + string junkLevelStr = GetArgValue(args, "/J", ""); + + var appsToUninstall = new List(); + var allApps = await ScanAndEnrichAsync(); + + if (File.Exists(target)) + { + // File-based target (bcul, json, txt) + string ext = Path.GetExtension(target).ToLowerInvariant(); + var lines = File.ReadAllLines(target); + foreach (var line in lines) + { + string trimmed = line.Trim(); + if (string.IsNullOrWhiteSpace(trimmed) || trimmed.StartsWith("#")) continue; + + var matched = allApps.FirstOrDefault(a => + a.DisplayName.Equals(trimmed, StringComparison.OrdinalIgnoreCase) || + a.RegistryKeyName.Equals(trimmed, StringComparison.OrdinalIgnoreCase)); + + if (matched != null) appsToUninstall.Add(matched); + } + } + else + { + // Name or pattern match + var matched = allApps.Where(a => + a.DisplayName.Contains(target, StringComparison.OrdinalIgnoreCase) || + a.RegistryKeyName.Equals(target, StringComparison.OrdinalIgnoreCase)).ToList(); + + appsToUninstall.AddRange(matched); + } + + if (appsToUninstall.Count == 0) + { + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine($"Kaldırılacak eşleşen uygulama bulunamadı: '{target}'"); + Console.ResetColor(); + return 1; + } + + Console.WriteLine($"\nKaldırılacak Uygulamalar ({appsToUninstall.Count}):"); + foreach (var a in appsToUninstall) + { + Console.WriteLine($" - {a.DisplayName} [{a.UninstallerKind}]"); + } + + if (dryRun) + { + Console.ForegroundColor = ConsoleColor.Cyan; + Console.WriteLine("\n[SIMULATION / DRY-RUN] Gerçek kaldırma yapılmadı."); + Console.ResetColor(); + return 0; + } + + if (!unattended) + { + Console.Write("\nDevam etmek istiyor musunuz? [E/H]: "); + var key = Console.ReadKey(); + Console.WriteLine(); + if (key.Key != ConsoleKey.E && key.Key != ConsoleKey.Y) + { + Console.WriteLine("İşlem iptal edildi."); + return 0; + } + } + + var bulkTask = new BulkUninstallTask(appsToUninstall, quiet); + bulkTask.OnLog += msg => Console.WriteLine($"[Toplu Görev] {msg}"); + await bulkTask.ExecuteAsync(); + + // Automatic Junk Clean + if (!string.IsNullOrWhiteSpace(junkLevelStr) && Enum.TryParse(junkLevelStr, true, out var minConfidence)) + { + Console.WriteLine($"\nArtık temizleme motoru çalıştırılıyor (Asgari Güven: {minConfidence})..."); + var junkManager = new JunkManager(); + foreach (var a in appsToUninstall) + { + var junks = junkManager.ScanJunk(a); + var cleanable = junks.Where(j => j.Confidence >= minConfidence).ToList(); + int cleaned = JunkManager.CleanJunk(cleanable, JunkManager.BackupDirectory); + Console.WriteLine($" -> {a.DisplayName}: {cleaned} artık öğe temizlendi."); + } + } + + return 0; + } + + private static int HandleDebloat(string[] args) + { + var tweaks = WindowsTweaks.GetDefaultTweaks(); + + if (args.Contains("--list") || args.Length == 0) + { + Console.WriteLine("\nKullanılabilir Windows Debloat İnce Ayarları:\n"); + foreach (var t in tweaks) + { + string status = t.IsApplied ? "[Uygulandı]" : "[Uygulanmadı]"; + Console.WriteLine($"{status,-14} ID: {t.Id,-15} | {t.Title}"); + Console.WriteLine($" {t.Description}\n"); + } + return 0; + } + + int applyIdx = Array.IndexOf(args, "--apply"); + if (applyIdx >= 0 && applyIdx + 1 < args.Length) + { + string target = args[applyIdx + 1].ToLowerInvariant(); + foreach (var t in tweaks) + { + if (target == "all" || t.Id.Equals(target, StringComparison.OrdinalIgnoreCase)) + { + Console.Write($"Uygulanıyor: {t.Title}... "); + bool ok = t.Apply(); + Console.WriteLine(ok ? "BAŞARILI" : "HATA"); + } + } + return 0; + } + + return 0; + } + + private static string GetArgValue(string[] args, string prefix, string fallback) + { + foreach (var a in args) + { + if (a.StartsWith(prefix + "=", StringComparison.OrdinalIgnoreCase)) + return a[(prefix.Length + 1)..].Trim('\"'); + if (a.StartsWith(prefix + ":", StringComparison.OrdinalIgnoreCase)) + return a[(prefix.Length + 1)..].Trim('\"'); + } + return fallback; + } + + private static string Truncate(string val, int maxLen) + { + if (string.IsNullOrEmpty(val)) return ""; + return val.Length <= maxLen ? val : val[..(maxLen - 3)] + "..."; + } + + private static string EscapeCsv(string val) + { + if (string.IsNullOrEmpty(val)) return ""; + return val.Replace("\"", "\"\""); + } + } +} diff --git a/src/LDUninstaller.Core/Algorithms/Sift4.cs b/src/LDUninstaller.Core/Algorithms/Sift4.cs new file mode 100644 index 0000000..105ef53 --- /dev/null +++ b/src/LDUninstaller.Core/Algorithms/Sift4.cs @@ -0,0 +1,98 @@ +using System; +using System.Text.RegularExpressions; + +namespace LDUninstaller.Core.Algorithms +{ + public static class Sift4 + { + // maxOffset: Arama penceresi boyutu (Genellikle 1-5 arası) + public static int SimplestDistance(string? s1, string? s2, int maxOffset = 5) + { + if (string.IsNullOrEmpty(s1)) return string.IsNullOrEmpty(s2) ? 0 : s2.Length; + if (string.IsNullOrEmpty(s2)) return s1.Length; + + int l1 = s1.Length; + int l2 = s2.Length; + int c1 = 0, c2 = 0; + int local_cs = 0; + int trans = 0; // yer değiştirme sayısı + + while ((c1 < l1) && (c2 < l2)) + { + if (s1[c1] == s2[c2]) + { + local_cs++; + c1++; + c2++; + } + else + { + trans += local_cs; + local_cs = 0; + bool matched = false; + for (int i = 0; i < maxOffset; i++) + { + if ((c1 + i < l1) && (s1[c1 + i] == s2[c2])) + { + c1 += i; + local_cs++; + c1++; + c2++; + matched = true; + break; + } + if ((c2 + i < l2) && (s1[c1] == s2[c2 + i])) + { + c2 += i; + local_cs++; + c1++; + c2++; + matched = true; + break; + } + } + + if (!matched) + { + c1++; + c2++; + } + } + } + trans += local_cs; + return Math.Max(l1, l2) - trans; + } + + public static double GetSimilarity(string? s1, string? s2, int maxOffset = 5) + { + if (string.IsNullOrEmpty(s1) && string.IsNullOrEmpty(s2)) return 1.0; + if (string.IsNullOrEmpty(s1) || string.IsNullOrEmpty(s2)) return 0.0; + + string clean1 = NormalizeName(s1); + string clean2 = NormalizeName(s2); + + if (clean1.Equals(clean2, StringComparison.OrdinalIgnoreCase)) + return 1.0; + + int maxLen = Math.Max(clean1.Length, clean2.Length); + if (maxLen == 0) return 1.0; + + int dist = SimplestDistance(clean1.ToLowerInvariant(), clean2.ToLowerInvariant(), maxOffset); + double similarity = 1.0 - ((double)dist / maxLen); + return Math.Clamp(similarity, 0.0, 1.0); + } + + private static readonly Regex CompanySuffixesRegex = new( + @"\b(corp|corporation|inc|incorporated|ltd|limited|llc|gmbh|co|software|technologies|systems)\b", + RegexOptions.IgnoreCase | RegexOptions.Compiled); + + public static string NormalizeName(string input) + { + if (string.IsNullOrWhiteSpace(input)) return string.Empty; + string s = CompanySuffixesRegex.Replace(input, ""); + s = Regex.Replace(s, @"[^\w\s]", " "); + s = Regex.Replace(s, @"\s+", " ").Trim(); + return s; + } + } +} diff --git a/src/LDUninstaller.Core/Algorithms/SquarifiedTreeMap.cs b/src/LDUninstaller.Core/Algorithms/SquarifiedTreeMap.cs new file mode 100644 index 0000000..5775498 --- /dev/null +++ b/src/LDUninstaller.Core/Algorithms/SquarifiedTreeMap.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; + +namespace LDUninstaller.Core.Algorithms +{ + public class TreeMapItem + { + public T Value { get; set; } + public double Weight { get; set; } + public RectangleF Bounds { get; set; } + + public TreeMapItem(T value, double weight) + { + Value = value; + Weight = weight; + } + } + + public static class SquarifiedTreeMap + { + public static List> CalculateLayout(IEnumerable> items, RectangleF bounds) + { + var itemList = items.Where(x => x.Weight > 0).OrderByDescending(x => x.Weight).ToList(); + if (itemList.Count == 0 || bounds.Width <= 0 || bounds.Height <= 0) + return itemList; + + double totalWeight = itemList.Sum(x => x.Weight); + if (totalWeight <= 0) + return itemList; + + double totalArea = bounds.Width * bounds.Height; + var normalized = itemList.Select(i => new Element(i, (i.Weight / totalWeight) * totalArea)).ToList(); + + LayoutSub(normalized, bounds); + return itemList; + } + + private class Element + { + public TreeMapItem Item { get; } + public double Area { get; set; } + + public Element(TreeMapItem item, double area) + { + Item = item; + Area = area; + } + } + + private static void LayoutSub(List> elements, RectangleF bounds) + { + if (elements.Count == 0 || bounds.Width <= 0 || bounds.Height <= 0) + return; + + if (elements.Count == 1) + { + elements[0].Item.Bounds = bounds; + return; + } + + var row = new List>(); + var remaining = new List>(elements); + + double side = Math.Min(bounds.Width, bounds.Height); + if (side <= 0) return; + + while (remaining.Count > 0) + { + var candidate = remaining[0]; + var testRow = new List>(row) { candidate }; + + if (row.Count == 0 || Worst(row, side) >= Worst(testRow, side)) + { + row.Add(candidate); + remaining.RemoveAt(0); + } + else + { + break; + } + } + + // Layout row + double rowArea = row.Sum(x => x.Area); + RectangleF remainingBounds; + + if (bounds.Width >= bounds.Height) + { + // Vertical strip + float rowWidth = (float)(rowArea / bounds.Height); + float currentY = bounds.Y; + + foreach (var el in row) + { + float h = (float)(el.Area / rowWidth); + el.Item.Bounds = new RectangleF(bounds.X, currentY, rowWidth, h); + currentY += h; + } + + remainingBounds = new RectangleF(bounds.X + rowWidth, bounds.Y, Math.Max(0, bounds.Width - rowWidth), bounds.Height); + } + else + { + // Horizontal strip + float rowHeight = (float)(rowArea / bounds.Width); + float currentX = bounds.X; + + foreach (var el in row) + { + float w = (float)(el.Area / rowHeight); + el.Item.Bounds = new RectangleF(currentX, bounds.Y, w, rowHeight); + currentX += w; + } + + remainingBounds = new RectangleF(bounds.X, bounds.Y + rowHeight, bounds.Width, Math.Max(0, bounds.Height - rowHeight)); + } + + if (remaining.Count > 0) + { + LayoutSub(remaining, remainingBounds); + } + } + + private static double Worst(List> row, double side) + { + if (row.Count == 0) return double.MaxValue; + double s2 = side * side; + double sum = row.Sum(x => x.Area); + if (sum == 0 || s2 == 0) return double.MaxValue; + + double max = row.Max(x => x.Area); + double min = row.Min(x => x.Area); + + return Math.Max((s2 * max) / (sum * sum), (sum * sum) / (s2 * min)); + } + } +} diff --git a/src/LDUninstaller.Core/Bulk/BulkUninstallTask.cs b/src/LDUninstaller.Core/Bulk/BulkUninstallTask.cs new file mode 100644 index 0000000..a605346 --- /dev/null +++ b/src/LDUninstaller.Core/Bulk/BulkUninstallTask.cs @@ -0,0 +1,391 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.IO.Pipes; +using System.Linq; +using System.ServiceProcess; +using System.Threading; +using System.Threading.Tasks; +using LDUninstaller.Core.Algorithms; +using LDUninstaller.Core.Models; +using LDUninstaller.Core.Native; + +namespace LDUninstaller.Core.Bulk +{ + public enum BulkStatus + { + Queued, + Running, + Succeeded, + Failed, + Skipped, + Cancelled + } + + public class BulkUninstallEntry + { + public ApplicationUninstallerEntry Entry { get; } + public BulkStatus Status { get; set; } = BulkStatus.Queued; + public string StatusMessage { get; set; } = "Kuyrukta"; + public bool PreferQuiet { get; set; } = true; + public int ExitCode { get; set; } = -1; + + public BulkUninstallEntry(ApplicationUninstallerEntry entry, bool preferQuiet = true) + { + Entry = entry; + PreferQuiet = preferQuiet; + } + } + + public class BulkUninstallTask + { + public List Items { get; } + public int MaxConcurrentQuiet { get; set; } = 2; + public bool CreateRestorePoint { get; set; } = true; + public bool EnableAutomatizer { get; set; } = true; + + public event Action? OnItemStarted; + public event Action? OnItemCompleted; + public event Action? OnLog; + + private readonly SemaphoreSlim _msiLock = new(1, 1); + private readonly SemaphoreSlim _loudLimitLock = new(1, 1); + private readonly object _stateLock = new(); + private readonly HashSet _activePublishers = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _activeDirectories = new(StringComparer.OrdinalIgnoreCase); + + public BulkUninstallTask(IEnumerable entries, bool preferQuiet = true) + { + Items = entries.Select(e => new BulkUninstallEntry(e, preferQuiet)).ToList(); + } + + public async Task ExecuteAsync(CancellationToken cancellationToken = default) + { + if (CreateRestorePoint) + { + OnLog?.Invoke("Sistem Geri Yükleme Noktası oluşturuluyor..."); + await Task.Run(() => Win32.CreateRestorePoint("LD Uninstaller Bulk Pre-Restore Point", out _)); + } + + var throttler = new SemaphoreSlim(MaxConcurrentQuiet, MaxConcurrentQuiet); + var runningTasks = new List(); + + foreach (var item in Items) + { + if (cancellationToken.IsCancellationRequested) + { + item.Status = BulkStatus.Cancelled; + item.StatusMessage = "İptal edildi"; + continue; + } + + // Check serialized types + bool isSerialized = IsSerializedType(item.Entry.UninstallerKind); + + if (isSerialized) + { + // Wait for all currently running background tasks to finish + await Task.WhenAll(runningTasks); + runningTasks.Clear(); + + await RunSingleItemAsync(item, cancellationToken); + } + else + { + await throttler.WaitAsync(cancellationToken); + + var t = Task.Run(async () => + { + try + { + await RunSingleItemAsync(item, cancellationToken); + } + finally + { + throttler.Release(); + } + }, cancellationToken); + + runningTasks.Add(t); + } + } + + await Task.WhenAll(runningTasks); + OnLog?.Invoke("Tüm toplu kaldırma işlemleri tamamlandı."); + } + + private async Task RunSingleItemAsync(BulkUninstallEntry item, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + item.Status = BulkStatus.Cancelled; + item.StatusMessage = "İptal edildi"; + return; + } + + // Concurrency Collision Prevention: + // 1. Publisher Lock + string pub = Sift4.NormalizeName(item.Entry.Publisher); + bool pubAcquired = false; + + // 2. Directory Hierarchy Lock + string dir = !string.IsNullOrWhiteSpace(item.Entry.InstallLocation) + ? Path.GetFullPath(item.Entry.InstallLocation).TrimEnd('\\') + : string.Empty; + + while (!pubAcquired && !cancellationToken.IsCancellationRequested) + { + lock (_stateLock) + { + bool pubConflict = !string.IsNullOrWhiteSpace(pub) && _activePublishers.Contains(pub); + bool dirConflict = !string.IsNullOrWhiteSpace(dir) && _activeDirectories.Any(d => + d.Equals(dir, StringComparison.OrdinalIgnoreCase) || + dir.StartsWith(d + "\\", StringComparison.OrdinalIgnoreCase) || + d.StartsWith(dir + "\\", StringComparison.OrdinalIgnoreCase)); + + if (!pubConflict && !dirConflict) + { + if (!string.IsNullOrWhiteSpace(pub)) _activePublishers.Add(pub); + if (!string.IsNullOrWhiteSpace(dir)) _activeDirectories.Add(dir); + pubAcquired = true; + } + } + + if (!pubAcquired) + { + await Task.Delay(500, cancellationToken); + } + } + + // 3. MSI Lock + bool msiLocked = false; + if (item.Entry.UninstallerKind == UninstallerType.Msiexec) + { + await _msiLock.WaitAsync(cancellationToken); + msiLocked = true; + await WaitForActiveMsiProcesses(cancellationToken); + } + + // 4. One Loud Limit (if uninstaller requires GUI) + bool isQuiet = item.PreferQuiet && !string.IsNullOrWhiteSpace(item.Entry.QuietUninstallString); + bool loudLocked = false; + if (!isQuiet) + { + await _loudLimitLock.WaitAsync(cancellationToken); + loudLocked = true; + } + + try + { + item.Status = BulkStatus.Running; + item.StatusMessage = "Çalıştırılıyor..."; + OnItemStarted?.Invoke(item); + OnLog?.Invoke($"Kaldırma başladı: {item.Entry.DisplayName}"); + + // Pre-kill locking processes in install folder + PreKillLockingProcesses(item.Entry); + + // Stop services in install folder + PreStopServices(item.Entry); + + // Execute Uninstaller Process + int exitCode = await ExecuteUninstallerProcessAsync(item, cancellationToken); + item.ExitCode = exitCode; + + if (exitCode == 0 || exitCode == 3010) // 3010 is ERROR_SUCCESS_REBOOT_REQUIRED + { + item.Status = BulkStatus.Succeeded; + item.StatusMessage = exitCode == 3010 ? "Başarılı (Yeniden başlatma gerekli)" : "Başarıyla kaldırıldı"; + } + else + { + item.Status = BulkStatus.Failed; + item.StatusMessage = $"Hata (Çıkış kodu: {exitCode})"; + } + } + catch (Exception ex) + { + item.Status = BulkStatus.Failed; + item.StatusMessage = $"Hata: {ex.Message}"; + } + finally + { + lock (_stateLock) + { + if (!string.IsNullOrWhiteSpace(pub)) _activePublishers.Remove(pub); + if (!string.IsNullOrWhiteSpace(dir)) _activeDirectories.Remove(dir); + } + + if (msiLocked) _msiLock.Release(); + if (loudLocked) _loudLimitLock.Release(); + + OnItemCompleted?.Invoke(item); + OnLog?.Invoke($"Tamamlandı [{item.Status}]: {item.Entry.DisplayName}"); + } + } + + private async Task ExecuteUninstallerProcessAsync(BulkUninstallEntry item, CancellationToken token) + { + string command = item.PreferQuiet && !string.IsNullOrWhiteSpace(item.Entry.QuietUninstallString) + ? item.Entry.QuietUninstallString + : item.Entry.UninstallString; + + if (string.IsNullOrWhiteSpace(command)) + { + // Simple delete fallback for orphaned software + if (item.Entry.IsOrphaned && Directory.Exists(item.Entry.InstallLocation)) + { + Directory.Delete(item.Entry.InstallLocation, true); + return 0; + } + return -1; + } + + var (fileName, args) = SplitCommand(command); + + var psi = new ProcessStartInfo + { + FileName = fileName, + Arguments = args, + UseShellExecute = true, + CreateNoWindow = item.PreferQuiet + }; + + if (!string.IsNullOrWhiteSpace(item.Entry.InstallLocation) && Directory.Exists(item.Entry.InstallLocation)) + { + psi.WorkingDirectory = item.Entry.InstallLocation; + } + + using var process = Process.Start(psi); + if (process == null) return -1; + + if (EnableAutomatizer) + { + NotifyAutomatizerDaemon(process.Id); + } + + await process.WaitForExitAsync(token); + return process.ExitCode; + } + + private static void NotifyAutomatizerDaemon(int pid) + { + _ = Task.Run(() => + { + try + { + using var client = new NamedPipeClientStream(".", "LDUninstallerDaemon", PipeDirection.Out); + client.Connect(1000); + using var writer = new StreamWriter(client); + writer.WriteLine($"ATTACH:{pid}"); + writer.Flush(); + } + catch { } + }); + } + + private static void PreKillLockingProcesses(ApplicationUninstallerEntry entry) + { + if (string.IsNullOrWhiteSpace(entry.InstallLocation) || !Directory.Exists(entry.InstallLocation)) + return; + + try + { + string norm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\'); + var procs = Process.GetProcesses(); + foreach (var p in procs) + { + try + { + if (p.Id == Process.GetCurrentProcess().Id) continue; + string? mainModule = p.MainModule?.FileName; + if (!string.IsNullOrWhiteSpace(mainModule)) + { + if (Path.GetFullPath(mainModule).StartsWith(norm, StringComparison.OrdinalIgnoreCase)) + { + Win32.GentleKillProcess(p, 2000); + } + } + } + catch { } + } + } + catch { } + } + + private static void PreStopServices(ApplicationUninstallerEntry entry) + { + if (string.IsNullOrWhiteSpace(entry.InstallLocation) || !Directory.Exists(entry.InstallLocation)) + return; + + try + { + string norm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\'); + var services = ServiceController.GetServices(); + foreach (var sc in services) + { + try + { + using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{sc.ServiceName}"); + string? path = key?.GetValue("ImagePath")?.ToString(); + if (!string.IsNullOrWhiteSpace(path) && path.StartsWith(norm, StringComparison.OrdinalIgnoreCase)) + { + if (sc.Status == ServiceControllerStatus.Running) + { + sc.Stop(); + sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3)); + } + } + } + catch { } + } + } + catch { } + } + + private static async Task WaitForActiveMsiProcesses(CancellationToken token) + { + while (!token.IsCancellationRequested) + { + var msiProcs = Process.GetProcessesByName("msiexec"); + if (msiProcs.Length <= 1) + break; + await Task.Delay(1000, token); + } + } + + private static bool IsSerializedType(UninstallerType type) + { + return type is UninstallerType.WindowsFeature + or UninstallerType.WindowsUpdate + or UninstallerType.InstallShield + or UninstallerType.SdbInst + or UninstallerType.PowerShell; + } + + private static (string fileName, string arguments) SplitCommand(string command) + { + string trimmed = command.Trim(); + if (trimmed.StartsWith("\"")) + { + int endQuote = trimmed.IndexOf('\"', 1); + if (endQuote > 0) + { + string file = trimmed.Substring(1, endQuote - 1); + string args = endQuote + 1 < trimmed.Length ? trimmed[(endQuote + 1)..].Trim() : ""; + return (file, args); + } + } + + int space = trimmed.IndexOf(' '); + if (space > 0) + { + return (trimmed[..space], trimmed[(space + 1)..].Trim()); + } + + return (trimmed, ""); + } + } +} diff --git a/src/LDUninstaller.Core/Discovery/DirectoryFactory.cs b/src/LDUninstaller.Core/Discovery/DirectoryFactory.cs new file mode 100644 index 0000000..c4d6ed1 --- /dev/null +++ b/src/LDUninstaller.Core/Discovery/DirectoryFactory.cs @@ -0,0 +1,201 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using LDUninstaller.Core.Models; + +namespace LDUninstaller.Core.Discovery +{ + public class DirectoryFactory : IUninstallerFactory + { + public string SourceName => "Directory Orphan Scanner"; + + private readonly HashSet _knownInstallLocations; + + public DirectoryFactory(IEnumerable knownInstallLocations) + { + _knownInstallLocations = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var loc in knownInstallLocations) + { + if (string.IsNullOrWhiteSpace(loc)) continue; + try + { + _knownInstallLocations.Add(Path.GetFullPath(loc).TrimEnd('\\')); + } + catch { } + } + } + + public IEnumerable GetUninstallerEntries() + { + var results = new List(); + + var searchRoots = new List(); + + string pf = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); + if (!string.IsNullOrEmpty(pf) && Directory.Exists(pf)) searchRoots.Add(pf); + + string pf86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); + if (!string.IsNullOrEmpty(pf86) && Directory.Exists(pf86) && !pf86.Equals(pf, StringComparison.OrdinalIgnoreCase)) + searchRoots.Add(pf86); + + string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + if (!string.IsNullOrEmpty(localAppData)) + { + string localProg = Path.Combine(localAppData, "Programs"); + if (Directory.Exists(localProg)) searchRoots.Add(localProg); + } + + // Scan all connected drives (e.g. D:\Games, E:\Apps, etc.) + try + { + var drives = DriveInfo.GetDrives(); + string[] candidates = { + "Games", "Oyunlar", "Program Files", "Program Files (x86)", + "Programs", "Programlar", "Apps", "Yazılımlar", + "Epic Games", "Riot Games", "GOG Games", "Ubisoft Games" + }; + + foreach (var d in drives) + { + if (!d.IsReady) continue; + string rootPath = d.RootDirectory.FullName; + + foreach (var c in candidates) + { + string candidatePath = Path.Combine(rootPath, c); + if (Directory.Exists(candidatePath) && !searchRoots.Contains(candidatePath, StringComparer.OrdinalIgnoreCase)) + { + searchRoots.Add(candidatePath); + } + } + } + } + catch { } + + var systemBlacklist = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "Common Files", "Windows Defender", "Windows Defender Advanced Threat Protection", + "Windows Mail", "Windows Media Player", "Windows NT", "Windows Photo Viewer", + "Windows Portable Devices", "WindowsPowerShell", "Microsoft", "PackageManagement", + "Temp", "Packages", "Microsoft Help" + }; + + foreach (var root in searchRoots) + { + try + { + var dirs = Directory.GetDirectories(root); + foreach (var dir in dirs) + { + string dirName = Path.GetFileName(dir); + if (systemBlacklist.Contains(dirName)) continue; + + // Check if this path or a subfolder is known + if (IsAlreadyRegistered(dir)) continue; + + // 1. If this directory itself has executables, it is the app! + var selfEntry = AnalyzeFolder(dir, dirName); + if (selfEntry != null) + { + results.Add(selfEntry); + continue; + } + + // 2. Otherwise, check subdirectories (e.g. Program Files/Vendor/App) + var subBlacklist = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "vc", "redist", "_redist", "support", "directx", "installer", + "prerequisites", "engine", "crashreports", "docs", "logs" + }; + + try + { + var subDirs = Directory.GetDirectories(dir); + foreach (var sub in subDirs) + { + string subName = Path.GetFileName(sub); + if (subBlacklist.Contains(subName)) continue; + if (IsAlreadyRegistered(sub)) continue; + + var subEntry = AnalyzeFolder(sub, $"{dirName} - {subName}"); + if (subEntry != null) + { + results.Add(subEntry); + } + } + } + catch { } + } + } + catch + { + // Access error on root + } + } + + return results; + } + + private bool IsAlreadyRegistered(string path) + { + try + { + string normalized = Path.GetFullPath(path).TrimEnd('\\'); + if (_knownInstallLocations.Contains(normalized)) return true; + foreach (var known in _knownInstallLocations) + { + if (normalized.StartsWith(known + "\\", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + } + catch { } + return false; + } + + private static ApplicationUninstallerEntry? AnalyzeFolder(string dir, string defaultName) + { + try + { + var files = Directory.GetFiles(dir, "*.exe", SearchOption.TopDirectoryOnly); + if (files.Length == 0) return null; + + // Look for dedicated uninstaller + string? uninstaller = files.FirstOrDefault(f => + { + string name = Path.GetFileName(f).ToLowerInvariant(); + return name.Contains("unins") || name.Contains("uninstall") || name.Contains("setup"); + }); + + string mainExe = uninstaller ?? files[0]; + var fileInfo = new FileInfo(mainExe); + + var kind = UninstallerType.SimpleDelete; + string uninsLower = Path.GetFileName(mainExe).ToLowerInvariant(); + if (uninsLower.StartsWith("unins000")) kind = UninstallerType.InnoSetup; + else if (uninsLower.Equals("uninstall.exe")) kind = UninstallerType.Nsis; + + return new ApplicationUninstallerEntry + { + DisplayName = defaultName + " [Yetim/Orphaned]", + RawDisplayName = defaultName, + InstallLocation = dir, + UninstallerLocation = Path.GetDirectoryName(mainExe) ?? dir, + UninstallerFullFilename = mainExe, + UninstallString = uninstaller != null ? $"\"{uninstaller}\"" : string.Empty, + DisplayIcon = mainExe, + IsOrphaned = true, + IsRegistered = false, + UninstallerKind = kind, + InstallDate = fileInfo.CreationTime + }; + } + catch + { + return null; + } + } + } +} diff --git a/src/LDUninstaller.Core/Discovery/DiscoveryPipeline.cs b/src/LDUninstaller.Core/Discovery/DiscoveryPipeline.cs new file mode 100644 index 0000000..139bdc9 --- /dev/null +++ b/src/LDUninstaller.Core/Discovery/DiscoveryPipeline.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using LDUninstaller.Core.Algorithms; +using LDUninstaller.Core.Models; + +namespace LDUninstaller.Core.Discovery +{ + public class DiscoveryPipeline + { + public event Action? OnProgress; + + public async Task> DiscoverAllAsync(bool includeStoreApps = true, bool includeOrphaned = true, bool includeSteam = true) + { + var registryFactory = new RegistryFactory(); + OnProgress?.Invoke("Kayıt defteri taranıyor...", 10); + var regEntries = await Task.Run(() => registryFactory.GetUninstallerEntries().ToList()); + + var knownLocations = regEntries + .Select(x => x.InstallLocation) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .ToList(); + + var allEntries = new List(regEntries); + + var tasks = new List>>(); + + if (includeStoreApps) + { + tasks.Add(Task.Run(() => new StoreAppFactory().GetUninstallerEntries())); + } + + if (includeSteam) + { + tasks.Add(Task.Run(() => new SteamFactory().GetUninstallerEntries())); + } + + tasks.Add(Task.Run(() => new ChocolateyFactory().GetUninstallerEntries())); + tasks.Add(Task.Run(() => new ScoopFactory().GetUninstallerEntries())); + + if (includeOrphaned) + { + tasks.Add(Task.Run(() => new DirectoryFactory(knownLocations).GetUninstallerEntries())); + } + + OnProgress?.Invoke("Diğer kaynaklar ve paketler taranıyor...", 40); + + var additionalResults = await Task.WhenAll(tasks); + foreach (var set in additionalResults) + { + allEntries.AddRange(set); + } + + OnProgress?.Invoke("Sonuçlar birleştiriliyor ve tekilleştiriliyor...", 80); + var merged = MergeResults(allEntries); + + OnProgress?.Invoke("Tarama tamamlandı.", 100); + return merged; + } + + public static List MergeResults(IEnumerable entries) + { + var merged = new List(); + var guidMap = new Dictionary(); + var pathMap = new Dictionary(StringComparer.OrdinalIgnoreCase); + var nameMap = new Dictionary(StringComparer.OrdinalIgnoreCase); + + foreach (var candidate in entries) + { + if (string.IsNullOrWhiteSpace(candidate.DisplayName)) + continue; + + // 1. Fast GUID match + if (candidate.BundleProviderKey != Guid.Empty && guidMap.TryGetValue(candidate.BundleProviderKey, out var matchGuid)) + { + Enrich(matchGuid, candidate); + continue; + } + + // 2. Fast InstallLocation match + if (!string.IsNullOrWhiteSpace(candidate.InstallLocation)) + { + string normPath = Path.GetFullPath(candidate.InstallLocation).TrimEnd('\\'); + if (pathMap.TryGetValue(normPath, out var matchPath)) + { + Enrich(matchPath, candidate); + continue; + } + } + + // 3. Fast Exact Name match + string cleanName = Sift4.NormalizeName(candidate.DisplayName); + if (nameMap.TryGetValue(cleanName, out var matchName)) + { + Enrich(matchName, candidate); + continue; + } + + // 4. Sift4 fuzzy match on candidates sharing the same starting word + string firstWord = cleanName.Split(' ')[0]; + ApplicationUninstallerEntry? existingFuzzy = null; + + if (firstWord.Length >= 3) + { + for (int i = 0; i < merged.Count; i++) + { + var x = merged[i]; + string xClean = Sift4.NormalizeName(x.DisplayName); + if (!xClean.StartsWith(firstWord, StringComparison.OrdinalIgnoreCase)) + continue; + + double simName = Sift4.GetSimilarity(xClean, cleanName); + if (simName > 0.88) + { + if (string.IsNullOrWhiteSpace(x.Publisher) || string.IsNullOrWhiteSpace(candidate.Publisher)) + { + existingFuzzy = x; + break; + } + double simPub = Sift4.GetSimilarity(x.Publisher, candidate.Publisher); + if (simPub > 0.70) + { + existingFuzzy = x; + break; + } + } + } + } + + if (existingFuzzy != null) + { + Enrich(existingFuzzy, candidate); + continue; + } + + merged.Add(candidate); + + if (candidate.BundleProviderKey != Guid.Empty) + guidMap[candidate.BundleProviderKey] = candidate; + + if (!string.IsNullOrWhiteSpace(candidate.InstallLocation)) + { + try { pathMap[Path.GetFullPath(candidate.InstallLocation).TrimEnd('\\')] = candidate; } catch { } + } + + if (!string.IsNullOrWhiteSpace(cleanName)) + nameMap[cleanName] = candidate; + } + + return merged.OrderBy(x => x.DisplayName).ToList(); + } + + private static void Enrich(ApplicationUninstallerEntry primary, ApplicationUninstallerEntry secondary) + { + if (string.IsNullOrWhiteSpace(primary.InstallLocation) && !string.IsNullOrWhiteSpace(secondary.InstallLocation)) + primary.InstallLocation = secondary.InstallLocation; + + if (string.IsNullOrWhiteSpace(primary.UninstallString) && !string.IsNullOrWhiteSpace(secondary.UninstallString)) + primary.UninstallString = secondary.UninstallString; + + if (string.IsNullOrWhiteSpace(primary.QuietUninstallString) && !string.IsNullOrWhiteSpace(secondary.QuietUninstallString)) + primary.QuietUninstallString = secondary.QuietUninstallString; + + if (primary.EstimatedSize.Bytes == 0 && secondary.EstimatedSize.Bytes > 0) + primary.EstimatedSize = secondary.EstimatedSize; + + if (string.IsNullOrWhiteSpace(primary.DisplayIcon) && !string.IsNullOrWhiteSpace(secondary.DisplayIcon)) + primary.DisplayIcon = secondary.DisplayIcon; + + if (primary.InstallDate == DateTime.MinValue && secondary.InstallDate != DateTime.MinValue) + primary.InstallDate = secondary.InstallDate; + + if (primary.UninstallerKind == UninstallerType.Unknown && secondary.UninstallerKind != UninstallerType.Unknown) + primary.UninstallerKind = secondary.UninstallerKind; + } + } +} diff --git a/src/LDUninstaller.Core/Discovery/DriveAnalyzer.cs b/src/LDUninstaller.Core/Discovery/DriveAnalyzer.cs new file mode 100644 index 0000000..c652c1e --- /dev/null +++ b/src/LDUninstaller.Core/Discovery/DriveAnalyzer.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using LDUninstaller.Core.Models; + +namespace LDUninstaller.Core.Discovery +{ + public static class DriveAnalyzer + { + public static List AnalyzeDrives(IEnumerable apps) + { + var results = new List(); + var appList = apps?.ToList() ?? new List(); + + try + { + var drives = DriveInfo.GetDrives(); + foreach (var d in drives) + { + if (!d.IsReady) continue; + + string name = d.Name; // e.g. "C:\" + string letter = name.TrimEnd('\\'); + string label = string.Empty; + try { label = d.VolumeLabel; } catch { } + if (string.IsNullOrWhiteSpace(label)) + { + label = d.DriveType == DriveType.Fixed ? "Yerel Sürücü" : d.DriveType.ToString(); + } + + var part = new DrivePartitionInfo + { + Name = name, + DriveLetter = letter, + VolumeLabel = label, + TotalBytes = d.TotalSize, + FreeBytes = d.AvailableFreeSpace, + DriveType = d.DriveType == DriveType.Fixed ? "Sabit Disk" : "Çıkarılabilir" + }; + + // Correlate apps + foreach (var app in appList) + { + if (string.IsNullOrWhiteSpace(app.InstallLocation)) continue; + try + { + string? root = Path.GetPathRoot(app.InstallLocation); + if (!string.IsNullOrEmpty(root) && root.Equals(name, StringComparison.OrdinalIgnoreCase)) + { + part.AppCount++; + part.AppsTotalBytes += app.EstimatedSize.Bytes; + } + } + catch { } + } + + results.Add(part); + } + } + catch { } + + return results; + } + } +} diff --git a/src/LDUninstaller.Core/Discovery/PackageManagersFactory.cs b/src/LDUninstaller.Core/Discovery/PackageManagersFactory.cs new file mode 100644 index 0000000..75a7eb0 --- /dev/null +++ b/src/LDUninstaller.Core/Discovery/PackageManagersFactory.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using LDUninstaller.Core.Models; + +namespace LDUninstaller.Core.Discovery +{ + public class ChocolateyFactory : IUninstallerFactory + { + public string SourceName => "Chocolatey"; + + public IEnumerable GetUninstallerEntries() + { + var results = new List(); + try + { + var psi = new ProcessStartInfo("choco.exe", "list -l --limit-output") + { + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + + using var process = Process.Start(psi); + if (process == null) return results; + + string output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(3000); + + using var reader = new StringReader(output); + string? line; + while ((line = reader.ReadLine()) != null) + { + var parts = line.Split('|'); + if (parts.Length >= 2 && !string.IsNullOrWhiteSpace(parts[0])) + { + string id = parts[0].Trim(); + string version = parts[1].Trim(); + results.Add(new ApplicationUninstallerEntry + { + DisplayName = $"{id} (Chocolatey)", + RawDisplayName = id, + DisplayVersion = version, + Publisher = "Chocolatey Package", + UninstallString = $"choco uninstall {id} -y", + QuietUninstallString = $"choco uninstall {id} -y", + UninstallerKind = UninstallerType.Chocolatey, + IsRegistered = true + }); + } + } + } + catch + { + // choco not in path + } + return results; + } + } + + public class ScoopFactory : IUninstallerFactory + { + public string SourceName => "Scoop"; + + public IEnumerable GetUninstallerEntries() + { + var results = new List(); + try + { + string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + string scoopApps = Path.Combine(userProfile, "scoop", "apps"); + if (Directory.Exists(scoopApps)) + { + foreach (var appDir in Directory.GetDirectories(scoopApps)) + { + string appName = Path.GetFileName(appDir); + if (appName.Equals("scoop", StringComparison.OrdinalIgnoreCase)) continue; + + string currentSymlink = Path.Combine(appDir, "current"); + string version = Directory.Exists(currentSymlink) ? "latest" : ""; + + results.Add(new ApplicationUninstallerEntry + { + DisplayName = $"{appName} (Scoop)", + RawDisplayName = appName, + DisplayVersion = version, + Publisher = "Scoop App", + InstallLocation = appDir, + UninstallString = $"scoop uninstall {appName}", + QuietUninstallString = $"scoop uninstall {appName}", + UninstallerKind = UninstallerType.Scoop, + IsRegistered = true + }); + } + } + } + catch + { + // Scoop directory not found + } + return results; + } + } + + public class WindowsFeatureFactory : IUninstallerFactory + { + public string SourceName => "Windows Features"; + + public IEnumerable GetUninstallerEntries() + { + var results = new List(); + try + { + var psi = new ProcessStartInfo("dism.exe", "/Online /Get-Features /Format:Table") + { + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + + using var process = Process.Start(psi); + if (process == null) return results; + + string output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(5000); + + using var reader = new StringReader(output); + string? line; + while ((line = reader.ReadLine()) != null) + { + if (line.Contains("Enabled", StringComparison.OrdinalIgnoreCase)) + { + var parts = line.Split('|'); + if (parts.Length >= 2) + { + string featureName = parts[0].Trim(); + if (!string.IsNullOrWhiteSpace(featureName) && !featureName.StartsWith("-")) + { + results.Add(new ApplicationUninstallerEntry + { + DisplayName = featureName, + RawDisplayName = featureName, + Publisher = "Microsoft Corporation", + UninstallString = $"dism.exe /Online /Disable-Feature /FeatureName:{featureName} /NoRestart", + QuietUninstallString = $"dism.exe /Online /Disable-Feature /FeatureName:{featureName} /NoRestart", + UninstallerKind = UninstallerType.WindowsFeature, + SystemComponent = true, + IsRegistered = true + }); + } + } + } + } + } + catch + { + // DISM access limitation + } + return results; + } + } +} diff --git a/src/LDUninstaller.Core/Discovery/RegistryFactory.cs b/src/LDUninstaller.Core/Discovery/RegistryFactory.cs new file mode 100644 index 0000000..4773edb --- /dev/null +++ b/src/LDUninstaller.Core/Discovery/RegistryFactory.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using LDUninstaller.Core.Models; +using Microsoft.Win32; + +namespace LDUninstaller.Core.Discovery +{ + public interface IUninstallerFactory + { + string SourceName { get; } + IEnumerable GetUninstallerEntries(); + } + + public class RegistryFactory : IUninstallerFactory + { + public string SourceName => "Windows Registry"; + + private const string UninstallPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"; + + public IEnumerable GetUninstallerEntries() + { + var results = new List(); + + // 1. HKLM 64-bit + ScanHive(RegistryHive.LocalMachine, RegistryView.Registry64, UninstallPath, results, MachineType.X64); + + // 2. HKLM 32-bit (Wow6432Node) + if (Environment.Is64BitOperatingSystem) + { + ScanHive(RegistryHive.LocalMachine, RegistryView.Registry32, UninstallPath, results, MachineType.X86); + } + + // 3. HKCU (Current User) + ScanHive(RegistryHive.CurrentUser, RegistryView.Default, UninstallPath, results, MachineType.Unknown); + + return results; + } + + private void ScanHive(RegistryHive hive, RegistryView view, string subKeyPath, List results, MachineType machineType) + { + try + { + using var baseKey = RegistryKey.OpenBaseKey(hive, view); + using var key = baseKey.OpenSubKey(subKeyPath); + if (key == null) return; + + foreach (string subKeyName in key.GetSubKeyNames()) + { + try + { + using var sub = key.OpenSubKey(subKeyName); + if (sub == null) continue; + + string? displayName = sub.GetValue("DisplayName") as string; + string? uninstallString = sub.GetValue("UninstallString") as string; + string? quietUninstallString = sub.GetValue("QuietUninstallString") as string; + + // Need at least DisplayName or UninstallString + if (string.IsNullOrWhiteSpace(displayName) && string.IsNullOrWhiteSpace(uninstallString)) + continue; + + // Check SystemComponent + object? sysCompVal = sub.GetValue("SystemComponent"); + bool isSystemComponent = sysCompVal is int i && i == 1; + + // ParentKeyName (sub-components) + string? parentKeyName = sub.GetValue("ParentKeyName") as string; + bool isUpdate = !string.IsNullOrWhiteSpace(parentKeyName); + + string? publisher = sub.GetValue("Publisher") as string ?? string.Empty; + string? displayVersion = sub.GetValue("DisplayVersion") as string ?? string.Empty; + string? installLocation = sub.GetValue("InstallLocation") as string ?? string.Empty; + string? displayIcon = sub.GetValue("DisplayIcon") as string ?? string.Empty; + string? modifyPath = sub.GetValue("ModifyPath") as string ?? string.Empty; + string? aboutUrl = sub.GetValue("URLInfoAbout") as string ?? sub.GetValue("HelpLink") as string ?? string.Empty; + + // Size + long estimatedSize = 0; + if (sub.GetValue("EstimatedSize") is int sizeInKb) + estimatedSize = (long)sizeInKb * 1024; + else if (sub.GetValue("EstimatedSize") is long sizeLong) + estimatedSize = sizeLong * 1024; + + // InstallDate + DateTime installDate = DateTime.MinValue; + if (sub.GetValue("InstallDate") is string dateStr && !string.IsNullOrWhiteSpace(dateStr)) + { + if (DateTime.TryParseExact(dateStr, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt)) + installDate = dt; + else if (DateTime.TryParse(dateStr, out var dt2)) + installDate = dt2; + } + + // WindowsInstaller flag / MSI Product code + object? winInstallerVal = sub.GetValue("WindowsInstaller"); + bool isMsi = winInstallerVal is int wi && wi == 1; + Guid bundleGuid = Guid.Empty; + if (Guid.TryParse(subKeyName, out var guid)) + { + bundleGuid = guid; + isMsi = true; + } + + var entry = new ApplicationUninstallerEntry + { + DisplayName = displayName ?? subKeyName, + RawDisplayName = displayName ?? subKeyName, + DisplayVersion = displayVersion, + Publisher = publisher, + InstallLocation = installLocation.Trim('\"'), + UninstallString = uninstallString ?? string.Empty, + QuietUninstallString = quietUninstallString ?? string.Empty, + ModifyPath = modifyPath, + DisplayIcon = displayIcon.Trim('\"'), + AboutUrl = aboutUrl, + RegistryKeyName = subKeyName, + RegistryPath = $"{hive}\\{subKeyPath}\\{subKeyName}", + BundleProviderKey = bundleGuid, + EstimatedSize = FileSize.FromBytes(estimatedSize), + InstallDate = installDate, + Is64Bit = machineType, + SystemComponent = isSystemComponent, + IsUpdate = isUpdate, + IsRegistered = true, + IsOrphaned = false, + UninstallerKind = isMsi ? UninstallerType.Msiexec : UninstallerType.Unknown + }; + + results.Add(entry); + } + catch + { + // Skip unreadable entry + } + } + } + catch + { + // Access error or registry view not supported + } + } + } +} diff --git a/src/LDUninstaller.Core/Discovery/ScriptFactory.cs b/src/LDUninstaller.Core/Discovery/ScriptFactory.cs new file mode 100644 index 0000000..b5243e6 --- /dev/null +++ b/src/LDUninstaller.Core/Discovery/ScriptFactory.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using LDUninstaller.Core.Models; +using LDUninstaller.Core.Tweaks; + +namespace LDUninstaller.Core.Discovery +{ + public class ScriptFactory : IUninstallerFactory + { + public string SourceName => "Windows Debloat & Tweaks"; + + public IEnumerable GetUninstallerEntries() + { + var results = new List(); + var tweaks = WindowsTweaks.GetDefaultTweaks(); + + foreach (var tweak in tweaks) + { + results.Add(new ApplicationUninstallerEntry + { + DisplayName = $"[Tweak] {tweak.Title}", + RawDisplayName = tweak.Title, + Publisher = "System Debloat", + DisplayVersion = tweak.Category, + AboutUrl = tweak.Description, + UninstallString = $"lduninstaller://tweak/apply/{tweak.Id}", + QuietUninstallString = $"lduninstaller://tweak/apply/{tweak.Id}", + UninstallerKind = UninstallerType.PowerShell, + SystemComponent = true, + IsRegistered = false + }); + } + + return results; + } + } +} diff --git a/src/LDUninstaller.Core/Discovery/SteamFactory.cs b/src/LDUninstaller.Core/Discovery/SteamFactory.cs new file mode 100644 index 0000000..873234a --- /dev/null +++ b/src/LDUninstaller.Core/Discovery/SteamFactory.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using LDUninstaller.Core.Models; +using Microsoft.Win32; + +namespace LDUninstaller.Core.Discovery +{ + public class SteamFactory : IUninstallerFactory + { + public string SourceName => "Steam Games"; + + public IEnumerable GetUninstallerEntries() + { + var results = new List(); + + try + { + string? steamPath = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Valve\Steam", "SteamPath", null) as string; + if (string.IsNullOrWhiteSpace(steamPath) || !Directory.Exists(steamPath)) + { + steamPath = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Valve\Steam", "InstallPath", null) as string; + } + + if (string.IsNullOrWhiteSpace(steamPath) || !Directory.Exists(steamPath)) + return results; + + var libraryFolders = new List { steamPath }; + + // Parse libraryfolders.vdf + string vdfPath = Path.Combine(steamPath, "steamapps", "libraryfolders.vdf"); + if (File.Exists(vdfPath)) + { + string content = File.ReadAllText(vdfPath); + var matches = Regex.Matches(content, @"""path""\s+""([^""]+)"""); + foreach (Match m in matches) + { + string p = m.Groups[1].Value.Replace(@"\\", @"\"); + if (Directory.Exists(p) && !libraryFolders.Contains(p)) + libraryFolders.Add(p); + } + } + + // Check all connected drives for SteamLibrary + try + { + foreach (var d in DriveInfo.GetDrives()) + { + if (!d.IsReady) continue; + string extraLib = Path.Combine(d.RootDirectory.FullName, "SteamLibrary"); + if (Directory.Exists(extraLib) && !libraryFolders.Contains(extraLib, StringComparer.OrdinalIgnoreCase)) + { + libraryFolders.Add(extraLib); + } + } + } + catch { } + + foreach (var lib in libraryFolders) + { + string steamApps = Path.Combine(lib, "steamapps"); + if (!Directory.Exists(steamApps)) continue; + + var manifests = Directory.GetFiles(steamApps, "appmanifest_*.acf"); + foreach (var manifest in manifests) + { + try + { + string text = File.ReadAllText(manifest); + string? appId = Regex.Match(text, @"""appid""\s+""(\d+)""").Groups[1].Value; + string? name = Regex.Match(text, @"""name""\s+""([^""]+)""").Groups[1].Value; + string? installDir = Regex.Match(text, @"""installdir""\s+""([^""]+)""").Groups[1].Value; + string? sizeOnDiskStr = Regex.Match(text, @"""SizeOnDisk""\s+""(\d+)""").Groups[1].Value; + + if (string.IsNullOrWhiteSpace(appId) || string.IsNullOrWhiteSpace(name)) + continue; + + // Skip common steam redistributables + if (appId == "228980" || name.Contains("Steamworks Shared")) + continue; + + long sizeOnDisk = 0; + if (long.TryParse(sizeOnDiskStr, out var sz)) + sizeOnDisk = sz; + + string gamePath = Path.Combine(steamApps, "common", installDir ?? name); + + var entry = new ApplicationUninstallerEntry + { + DisplayName = name, + RawDisplayName = name, + Publisher = "Steam", + RegistryKeyName = $"Steam App {appId}", + InstallLocation = Directory.Exists(gamePath) ? gamePath : string.Empty, + UninstallString = $"steam://uninstall/{appId}", + QuietUninstallString = $"steam://uninstall/{appId}", + UninstallerKind = UninstallerType.Steam, + EstimatedSize = FileSize.FromBytes(sizeOnDisk), + IsRegistered = true + }; + + results.Add(entry); + } + catch + { + // Skip corrupted manifest + } + } + } + } + catch + { + // Steam not installed or inaccessible + } + + return results; + } + } +} diff --git a/src/LDUninstaller.Core/Discovery/StoreAppFactory.cs b/src/LDUninstaller.Core/Discovery/StoreAppFactory.cs new file mode 100644 index 0000000..a0b7631 --- /dev/null +++ b/src/LDUninstaller.Core/Discovery/StoreAppFactory.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using LDUninstaller.Core.Models; + +namespace LDUninstaller.Core.Discovery +{ + public class StoreAppFactory : IUninstallerFactory + { + public string SourceName => "Windows Store (UWP/AppX)"; + + public IEnumerable GetUninstallerEntries() + { + var results = new List(); + + try + { + // Run PowerShell to fetch NonDevelopment AppX packages + var psi = new ProcessStartInfo + { + FileName = "powershell.exe", + Arguments = "-NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"Get-AppxPackage | Where-Object { -not $_.IsFramework -and -not $_.NonRemovable } | Select-Object Name, PackageFullName, Publisher, InstallLocation, Version | ConvertTo-Csv -NoTypeInformation\"", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + + using var process = Process.Start(psi); + if (process == null) return results; + + string output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(7000); + + using var reader = new StringReader(output); + string? line; + bool isHeader = true; + + while ((line = reader.ReadLine()) != null) + { + if (string.IsNullOrWhiteSpace(line)) continue; + if (isHeader) + { + isHeader = false; + continue; + } + + // CSV simple split + var parts = SplitCsvLine(line); + if (parts.Count < 5) continue; + + string name = parts[0]; + string packageFullName = parts[1]; + string publisher = parts[2]; + string installLocation = parts[3]; + string version = parts[4]; + + if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(packageFullName)) + continue; + + // Clean publisher string CN=... + if (publisher.StartsWith("CN=", StringComparison.OrdinalIgnoreCase)) + { + int comma = publisher.IndexOf(','); + publisher = comma > 3 ? publisher[3..comma] : publisher[3..]; + } + + var entry = new ApplicationUninstallerEntry + { + DisplayName = name, + RawDisplayName = name, + DisplayVersion = version, + Publisher = publisher, + InstallLocation = installLocation, + RegistryKeyName = packageFullName, + UninstallString = $"powershell.exe -NoProfile -Command \"Remove-AppxPackage -Package '{packageFullName}'\"", + QuietUninstallString = $"powershell.exe -NoProfile -Command \"Remove-AppxPackage -Package '{packageFullName}'\"", + UninstallerKind = UninstallerType.StoreApp, + IsRegistered = true, + IsOrphaned = false, + SystemComponent = false + }; + + results.Add(entry); + } + } + catch + { + // PowerShell unavailable or permissions restricted + } + + return results; + } + + private static List SplitCsvLine(string line) + { + var result = new List(); + bool inQuotes = false; + var current = new System.Text.StringBuilder(); + + for (int i = 0; i < line.Length; i++) + { + char c = line[i]; + if (c == '\"') + { + inQuotes = !inQuotes; + } + else if (c == ',' && !inQuotes) + { + result.Add(current.ToString()); + current.Clear(); + } + else + { + current.Append(c); + } + } + result.Add(current.ToString()); + return result; + } + } +} diff --git a/src/LDUninstaller.Core/InfoAdders/InfoAdders.cs b/src/LDUninstaller.Core/InfoAdders/InfoAdders.cs new file mode 100644 index 0000000..a4dd76b --- /dev/null +++ b/src/LDUninstaller.Core/InfoAdders/InfoAdders.cs @@ -0,0 +1,316 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Security.Cryptography.X509Certificates; +using System.Text.RegularExpressions; +using LDUninstaller.Core.Models; +using LDUninstaller.Core.Native; + +namespace LDUninstaller.Core.InfoAdders +{ + public interface IMissingInfoAdder + { + void AddInfo(ApplicationUninstallerEntry entry); + } + + public class InstallLocationGenerator : IMissingInfoAdder + { + public void AddInfo(ApplicationUninstallerEntry entry) + { + if (!string.IsNullOrWhiteSpace(entry.InstallLocation) && Directory.Exists(entry.InstallLocation)) + return; + + if (!string.IsNullOrWhiteSpace(entry.UninstallString)) + { + string path = ExtractExePath(entry.UninstallString); + if (File.Exists(path)) + { + entry.InstallLocation = Path.GetDirectoryName(path) ?? string.Empty; + entry.UninstallerFullFilename = path; + } + } + } + + private static string ExtractExePath(string raw) + { + if (string.IsNullOrWhiteSpace(raw)) return string.Empty; + string trimmed = raw.Trim(); + if (trimmed.StartsWith("\"")) + { + int end = trimmed.IndexOf('\"', 1); + if (end > 0) return trimmed.Substring(1, end - 1); + } + int exeIdx = trimmed.IndexOf(".exe", StringComparison.OrdinalIgnoreCase); + if (exeIdx > 0) return trimmed.Substring(0, exeIdx + 4); + return trimmed; + } + } + + public class UninstallerTypeRecognizer : IMissingInfoAdder + { + public void AddInfo(ApplicationUninstallerEntry entry) + { + if (entry.UninstallerKind != UninstallerType.Unknown) + return; + + string unins = entry.UninstallString; + string uninsLower = unins.ToLowerInvariant(); + + if (uninsLower.Contains("msiexec.exe") || entry.BundleProviderKey != Guid.Empty) + { + entry.UninstallerKind = UninstallerType.Msiexec; + } + else if (uninsLower.Contains("unins000.exe") || uninsLower.Contains("inno setup")) + { + entry.UninstallerKind = UninstallerType.InnoSetup; + } + else if (uninsLower.Contains("uninstall.exe") || uninsLower.Contains("nsis")) + { + entry.UninstallerKind = UninstallerType.Nsis; + } + else if (uninsLower.Contains("installshield") || uninsLower.Contains("_isuninst")) + { + entry.UninstallerKind = UninstallerType.InstallShield; + } + else if (uninsLower.Contains("advanced installer") || uninsLower.Contains("ai_")) + { + entry.UninstallerKind = UninstallerType.AdvancedInstaller; + } + else if (uninsLower.Contains("update.exe --uninstall") || uninsLower.Contains("squirrel")) + { + entry.UninstallerKind = UninstallerType.Squirrel; + } + else if (uninsLower.Contains("dfshim.dll") || uninsLower.Contains("rundll32 dfshim")) + { + entry.UninstallerKind = UninstallerType.ClickOnce; + } + else if (uninsLower.StartsWith("steam://")) + { + entry.UninstallerKind = UninstallerType.Steam; + } + else if (uninsLower.Contains("remove-appxpackage")) + { + entry.UninstallerKind = UninstallerType.StoreApp; + } + else if (uninsLower.Contains("choco uninstall")) + { + entry.UninstallerKind = UninstallerType.Chocolatey; + } + else if (entry.IsOrphaned) + { + entry.UninstallerKind = UninstallerType.SimpleDelete; + } + } + } + + public class QuietUninstallStringGenerator : IMissingInfoAdder + { + public void AddInfo(ApplicationUninstallerEntry entry) + { + if (!string.IsNullOrWhiteSpace(entry.QuietUninstallString)) + return; + + if (string.IsNullOrWhiteSpace(entry.UninstallString)) + return; + + string u = entry.UninstallString.Trim(); + + switch (entry.UninstallerKind) + { + case UninstallerType.InnoSetup: + entry.QuietUninstallString = $"{u} /VERYSILENT /SUPPRESSMSGBOXES /NORESTART"; + break; + + case UninstallerType.Nsis: + entry.QuietUninstallString = $"{u} /S"; + break; + + case UninstallerType.Msiexec: + if (u.Contains("/I", StringComparison.OrdinalIgnoreCase)) + { + entry.QuietUninstallString = Regex.Replace(u, @"(?i)/i", "/X") + " /qn /norestart"; + } + else if (!u.Contains("/qn", StringComparison.OrdinalIgnoreCase)) + { + entry.QuietUninstallString = $"{u} /qn /norestart"; + } + else + { + entry.QuietUninstallString = u; + } + break; + + case UninstallerType.InstallShield: + entry.QuietUninstallString = $"{u} /s /v\"/qn /norestart\""; + break; + + case UninstallerType.AdvancedInstaller: + entry.QuietUninstallString = $"{u} /quiet /norestart"; + break; + + case UninstallerType.Chocolatey: + case UninstallerType.StoreApp: + case UninstallerType.Steam: + entry.QuietUninstallString = u; + break; + } + } + } + + public class CertificateGetter : IMissingInfoAdder + { + public void AddInfo(ApplicationUninstallerEntry entry) + { + string targetPath = entry.UninstallerFullFilename; + if (string.IsNullOrWhiteSpace(targetPath) || !File.Exists(targetPath)) + { + if (!string.IsNullOrWhiteSpace(entry.InstallLocation) && Directory.Exists(entry.InstallLocation)) + { + try + { + var files = Directory.GetFiles(entry.InstallLocation, "*.exe", SearchOption.TopDirectoryOnly); + if (files.Length > 0) targetPath = files[0]; + } + catch { } + } + } + + if (string.IsNullOrWhiteSpace(targetPath) || !File.Exists(targetPath)) + return; + + try + { + bool isValid = Win32.VerifyEmbeddedSignature(targetPath); + entry.IsCertificateValid = isValid; + + if (isValid) + { + var cert = X509Certificate.CreateFromSignedFile(targetPath); + entry.Certificate = new X509Certificate2(cert); + } + } + catch + { + entry.IsCertificateValid = false; + } + } + } + + public class FastSizeGenerator : IMissingInfoAdder + { + public void AddInfo(ApplicationUninstallerEntry entry) + { + if (entry.EstimatedSize.Bytes > 0) + return; + + if (string.IsNullOrWhiteSpace(entry.InstallLocation) || !Directory.Exists(entry.InstallLocation)) + return; + + // Never scan root or system directories + if (Junk.SafetyBlacklist.IsDangerousDirectory(entry.InstallLocation)) + return; + + try + { + long totalBytes = CalculateDirSize(new DirectoryInfo(entry.InstallLocation), 0, 3); + if (totalBytes > 0) + { + entry.EstimatedSize = FileSize.FromBytes(totalBytes); + } + } + catch { } + } + + private static long CalculateDirSize(DirectoryInfo dir, int currentDepth, int maxDepth) + { + if (currentDepth > maxDepth) return 0; + // Prevent junction / symlink loops + if ((dir.Attributes & FileAttributes.ReparsePoint) != 0) return 0; + + long size = 0; + try + { + foreach (var file in dir.EnumerateFiles()) + { + size += file.Length; + } + + if (currentDepth < maxDepth) + { + foreach (var sub in dir.EnumerateDirectories()) + { + size += CalculateDirSize(sub, currentDepth + 1, maxDepth); + } + } + } + catch { } + + return size; + } + } + + public class Is64BitGetter : IMissingInfoAdder + { + public void AddInfo(ApplicationUninstallerEntry entry) + { + if (entry.Is64Bit != MachineType.Unknown) + return; + + string targetFile = entry.UninstallerFullFilename; + if (string.IsNullOrWhiteSpace(targetFile) || !File.Exists(targetFile)) + { + if (!string.IsNullOrWhiteSpace(entry.InstallLocation) && Directory.Exists(entry.InstallLocation)) + { + try + { + var files = Directory.GetFiles(entry.InstallLocation, "*.exe"); + if (files.Length > 0) targetFile = files[0]; + } + catch { } + } + } + + if (string.IsNullOrWhiteSpace(targetFile) || !File.Exists(targetFile)) + return; + + ushort arch = Win32.GetPeArchitecture(targetFile); + entry.Is64Bit = arch switch + { + 0x014c => MachineType.X86, + 0x8664 => MachineType.X64, + 0xAA64 => MachineType.Arm64, + _ => MachineType.Unknown + }; + } + } + + public class InfoAdderManager + { + private readonly IMissingInfoAdder[] _adders = new IMissingInfoAdder[] + { + new InstallLocationGenerator(), + new UninstallerTypeRecognizer(), + new QuietUninstallStringGenerator(), + new CertificateGetter(), + new FastSizeGenerator(), + new Is64BitGetter() + }; + + public void Process(ApplicationUninstallerEntry entry) + { + foreach (var adder in _adders) + { + try + { + adder.AddInfo(entry); + } + catch { } + } + } + + public void ProcessAll(System.Collections.Generic.IEnumerable entries) + { + System.Threading.Tasks.Parallel.ForEach(entries, new System.Threading.Tasks.ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, Process); + } + } +} diff --git a/src/LDUninstaller.Core/Junk/JunkManager.cs b/src/LDUninstaller.Core/Junk/JunkManager.cs new file mode 100644 index 0000000..d1d2de4 --- /dev/null +++ b/src/LDUninstaller.Core/Junk/JunkManager.cs @@ -0,0 +1,547 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using LDUninstaller.Core.Algorithms; +using LDUninstaller.Core.Models; +using Microsoft.Win32; + +namespace LDUninstaller.Core.Junk +{ + public class JunkManager + { + public static string BackupDirectory => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "LDUninstaller", "Backups"); + + public List ScanJunk(ApplicationUninstallerEntry entry) + { + var results = new List(); + + // 1. Install Location leftover scanner + ScanInstallLocation(entry, results); + + // 2. Common drive junk scanner (AppData, LocalAppData, ProgramData, Documents, Saved Games) + ScanCommonDriveJunk(entry, results); + + // 3. Software Registry Keys (HKLM & HKCU) + ScanSoftwareRegistryKeys(entry, results); + + // 4. Windows Prefetch scanner + ScanPrefetch(entry, results); + + // 5. Windows Error Reporting / CrashDumps + ScanWerDumps(entry, results); + + // 6. Firewall Rules + ScanFirewallRules(entry, results); + + // 7. UserAssist ROT13 scanner + ScanUserAssist(entry, results); + + // 8. Shortcuts (Desktop, Start Menu, Quick Launch) + ScanShortcuts(entry, results); + + // 9. Registry Uninstaller Entry Check (if uninstall key still exists) + ScanRegistryUninstallKey(entry, results); + + // Apply Safety Blacklist filter and adjust Confidence + foreach (var item in results) + { + if (item.Type == JunkType.Directory && SafetyBlacklist.IsDangerousDirectory(item.Path)) + { + if (item is FileSystemJunkResult fs) + { + fs.Confidence = ConfidenceLevel.Bad; + fs.Selected = false; + } + } + else if (item.Type == JunkType.RegistryKey && SafetyBlacklist.IsDangerousRegistryPath(item.Path)) + { + if (item is RegistryJunkResult rj) + { + rj.Confidence = ConfidenceLevel.Bad; + rj.Selected = false; + } + } + } + + return results; + } + + public List ScanMultiple(IEnumerable entries) + { + var all = new List(); + var seenPaths = new HashSet(StringComparer.OrdinalIgnoreCase); + + foreach (var entry in entries) + { + var list = ScanJunk(entry); + foreach (var j in list) + { + if (!seenPaths.Contains(j.Path)) + { + seenPaths.Add(j.Path); + all.Add(j); + } + } + } + + return all; + } + + private static (string cleanName, string cleanPublisher, List tokens) GetMatchTokens(ApplicationUninstallerEntry entry) + { + string rawName = entry.DisplayName; + string stripped = Regex.Replace(rawName, @"(\bv?\d+(\.\d+)+|\(x86\)|\(x64\)|\(amd64\)|sürümü|version)", " ", RegexOptions.IgnoreCase); + string cleanName = Sift4.NormalizeName(stripped).ToLowerInvariant(); + string cleanPub = Sift4.NormalizeName(entry.Publisher).ToLowerInvariant(); + + var tokens = new List(); + if (cleanName.Length >= 2) tokens.Add(cleanName); + if (cleanPub.Length >= 3) tokens.Add(cleanPub); + + foreach (var word in cleanName.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + if (word.Length >= 3 && !tokens.Contains(word)) + tokens.Add(word); + } + + if (!string.IsNullOrWhiteSpace(entry.UninstallerFullFilename)) + { + string exeName = Path.GetFileNameWithoutExtension(entry.UninstallerFullFilename).ToLowerInvariant(); + if (exeName.Length >= 3 && !exeName.Contains("unins") && !exeName.Contains("setup") && !tokens.Contains(exeName)) + tokens.Add(exeName); + } + + return (cleanName, cleanPub, tokens); + } + + private void ScanInstallLocation(ApplicationUninstallerEntry entry, List results) + { + if (string.IsNullOrWhiteSpace(entry.InstallLocation) || !Directory.Exists(entry.InstallLocation)) + return; + + if (SafetyBlacklist.IsDangerousDirectory(entry.InstallLocation)) + return; + + results.Add(new FileSystemJunkResult + { + EntryName = Path.GetFileName(entry.InstallLocation), + Path = entry.InstallLocation, + IsDirectory = true, + Confidence = ConfidenceLevel.VeryGood, + Reason = "Kaldırma sonrası diskte kalan ana kurulum klasörü", + Selected = true + }); + } + + private void ScanCommonDriveJunk(ApplicationUninstallerEntry entry, List results) + { + var (cleanName, cleanPub, tokens) = GetMatchTokens(entry); + if (tokens.Count == 0) return; + + var targetRoots = new List + { + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "AppData", "LocalLow"), + Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Documents"), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Saved Games") + }; + + foreach (var root in targetRoots) + { + if (!Directory.Exists(root)) continue; + + try + { + foreach (var dir in Directory.GetDirectories(root)) + { + string dirName = Path.GetFileName(dir).ToLowerInvariant(); + if (SafetyBlacklist.IsDangerousDirectory(dir)) continue; + + bool matched = false; + ConfidenceLevel conf = ConfidenceLevel.Good; + + if (dirName.Equals(cleanName, StringComparison.OrdinalIgnoreCase)) + { + matched = true; + conf = ConfidenceLevel.VeryGood; + } + else if (!string.IsNullOrEmpty(cleanPub) && dirName.Equals(cleanPub, StringComparison.OrdinalIgnoreCase)) + { + // Publisher folder: search subdirectories! + try + { + foreach (var sub in Directory.GetDirectories(dir)) + { + string subName = Path.GetFileName(sub).ToLowerInvariant(); + if (tokens.Any(t => subName.Contains(t) || Sift4.GetSimilarity(subName, t) >= 0.75)) + { + results.Add(new FileSystemJunkResult + { + EntryName = $"{dirName}\\{subName}", + Path = sub, + IsDirectory = true, + Confidence = ConfidenceLevel.VeryGood, + Reason = "Yayıncı klasörü altındaki uygulama veri kalıntısı", + Selected = true + }); + } + } + } + catch { } + continue; + } + else if (tokens.Any(t => dirName.Contains(t) || Sift4.GetSimilarity(dirName, t) >= 0.80)) + { + matched = true; + conf = ConfidenceLevel.Good; + } + + if (matched) + { + results.Add(new FileSystemJunkResult + { + EntryName = Path.GetFileName(dir), + Path = dir, + IsDirectory = true, + Confidence = conf, + Reason = "Kullanıcı verisi ve yapılandırma klasörü kalıntısı", + Selected = true + }); + } + } + } + catch { } + } + } + + private void ScanSoftwareRegistryKeys(ApplicationUninstallerEntry entry, List results) + { + var (cleanName, cleanPub, tokens) = GetMatchTokens(entry); + if (tokens.Count == 0) return; + + var hives = new[] + { + (Name: "HKCU", Key: Registry.CurrentUser.OpenSubKey("Software")), + (Name: "HKLM", Key: Registry.LocalMachine.OpenSubKey("SOFTWARE")), + (Name: "HKLM_32", Key: Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node")) + }; + + foreach (var (hiveName, rootKey) in hives) + { + if (rootKey == null) continue; + using (rootKey) + { + foreach (var subName in rootKey.GetSubKeyNames()) + { + if (SafetyBlacklist.IsDangerousRegistryPath($"{hiveName}\\Software\\{subName}")) + continue; + + string subLower = subName.ToLowerInvariant(); + + if (subLower.Equals(cleanName, StringComparison.OrdinalIgnoreCase) || tokens.Any(t => subLower.Equals(t, StringComparison.OrdinalIgnoreCase))) + { + results.Add(new RegistryJunkResult + { + EntryName = subName, + Path = $@"{hiveName}\Software\{subName}", + Confidence = ConfidenceLevel.VeryGood, + Reason = "Kayıt defteri yazılım anahtarı kalıntısı", + Selected = true + }); + } + else if (!string.IsNullOrEmpty(cleanPub) && (subLower.Equals(cleanPub, StringComparison.OrdinalIgnoreCase) || Sift4.GetSimilarity(subLower, cleanPub) >= 0.80)) + { + // Publisher registry key -> scan app subkeys + try + { + using var pubKey = rootKey.OpenSubKey(subName); + if (pubKey != null) + { + foreach (var appSub in pubKey.GetSubKeyNames()) + { + string appSubLower = appSub.ToLowerInvariant(); + if (tokens.Any(t => appSubLower.Contains(t) || Sift4.GetSimilarity(appSubLower, t) >= 0.75)) + { + results.Add(new RegistryJunkResult + { + EntryName = $"{subName}\\{appSub}", + Path = $@"{hiveName}\Software\{subName}\{appSub}", + Confidence = ConfidenceLevel.VeryGood, + Reason = "Yayıncı altındaki uygulama kayıt defteri anahtarı kalıntısı", + Selected = true + }); + } + } + } + } + catch { } + } + else if (tokens.Any(t => Sift4.GetSimilarity(subLower, t) >= 0.85)) + { + results.Add(new RegistryJunkResult + { + EntryName = subName, + Path = $@"{hiveName}\Software\{subName}", + Confidence = ConfidenceLevel.Good, + Reason = "Eşleşen kayıt defteri yazılım anahtarı", + Selected = true + }); + } + } + } + } + } + + private void ScanPrefetch(ApplicationUninstallerEntry entry, List results) + { + try + { + string prefetchDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Prefetch"); + if (!Directory.Exists(prefetchDir)) return; + + var (cleanName, _, tokens) = GetMatchTokens(entry); + + foreach (var token in tokens.Take(2)) + { + if (token.Length < 3) continue; + var pfFiles = Directory.GetFiles(prefetchDir, $"{token.ToUpperInvariant()}*.pf"); + foreach (var pf in pfFiles) + { + results.Add(new FileSystemJunkResult + { + EntryName = Path.GetFileName(pf), + Path = pf, + IsDirectory = false, + Confidence = ConfidenceLevel.VeryGood, + Reason = "Windows Prefetch çalıştırma önbellek dosyası", + Selected = true + }); + } + } + } + catch { } + } + + private void ScanWerDumps(ApplicationUninstallerEntry entry, List results) + { + try + { + string crashDumps = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CrashDumps"); + if (!Directory.Exists(crashDumps)) return; + + var (_, _, tokens) = GetMatchTokens(entry); + + foreach (var file in Directory.GetFiles(crashDumps, "*.dmp")) + { + string fname = Path.GetFileName(file).ToLowerInvariant(); + if (tokens.Any(t => fname.Contains(t))) + { + results.Add(new FileSystemJunkResult + { + EntryName = Path.GetFileName(file), + Path = file, + IsDirectory = false, + Confidence = ConfidenceLevel.Good, + Reason = "Windows Hata Raporlama çökme döküm dosyası (Crash Dump)", + Selected = true + }); + } + } + } + catch { } + } + + private void ScanFirewallRules(ApplicationUninstallerEntry entry, List results) + { + if (string.IsNullOrWhiteSpace(entry.InstallLocation)) return; + try + { + using var key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules", true); + if (key == null) return; + + string installNorm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\').ToLowerInvariant(); + + foreach (var valName in key.GetValueNames()) + { + string? val = key.GetValue(valName)?.ToString(); + if (!string.IsNullOrWhiteSpace(val) && val.ToLowerInvariant().Contains(installNorm)) + { + results.Add(new RegistryJunkResult + { + EntryName = valName, + Path = @"HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules", + ValueName = valName, + Confidence = ConfidenceLevel.VeryGood, + Reason = "Uygulamaya ait geçersiz Windows Güvenlik Duvarı kuralı", + Selected = true + }); + } + } + } + catch { } + } + + private void ScanUserAssist(ApplicationUninstallerEntry entry, List results) + { + try + { + using var uaKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist"); + if (uaKey == null) return; + + var (cleanName, _, tokens) = GetMatchTokens(entry); + + foreach (var sub in uaKey.GetSubKeyNames()) + { + using var countKey = uaKey.OpenSubKey($"{sub}\\Count", true); + if (countKey == null) continue; + + foreach (var valName in countKey.GetValueNames()) + { + string decoded = Rot13(valName).ToLowerInvariant(); + if (tokens.Any(t => decoded.Contains(t))) + { + results.Add(new RegistryJunkResult + { + EntryName = Rot13(valName), + Path = $@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{sub}\Count", + ValueName = valName, + Confidence = ConfidenceLevel.VeryGood, + Reason = "UserAssist uygulama çalıştırma geçmişi girdisi", + Selected = true + }); + } + } + } + } + catch { } + } + + private void ScanShortcuts(ApplicationUninstallerEntry entry, List results) + { + var shortcutDirs = new List + { + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory), + Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), + Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu), + Environment.GetFolderPath(Environment.SpecialFolder.Programs), + Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms) + }; + + var (_, _, tokens) = GetMatchTokens(entry); + + foreach (var dir in shortcutDirs) + { + if (!Directory.Exists(dir)) continue; + try + { + foreach (var file in Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)) + { + string ext = Path.GetExtension(file).ToLowerInvariant(); + if (ext != ".lnk" && ext != ".url") continue; + + string fname = Path.GetFileNameWithoutExtension(file).ToLowerInvariant(); + if (tokens.Any(t => fname.Contains(t) || Sift4.GetSimilarity(fname, t) >= 0.85)) + { + results.Add(new FileSystemJunkResult + { + EntryName = Path.GetFileName(file), + Path = file, + IsDirectory = false, + Confidence = ConfidenceLevel.VeryGood, + Reason = "Masaüstü veya Başlat menüsü kısayol kalıntısı", + Selected = true + }); + } + } + } + catch { } + } + } + + public static int CleanJunk(IEnumerable items, string backupDir) + { + int cleanedCount = 0; + Directory.CreateDirectory(backupDir); + + foreach (var item in items.Where(x => x.Selected && x.Confidence > ConfidenceLevel.Bad)) + { + try + { + if (item.Delete(backupDir)) + { + cleanedCount++; + } + } + catch { } + } + return cleanedCount; + } + + private void ScanRegistryUninstallKey(ApplicationUninstallerEntry entry, List results) + { + if (string.IsNullOrWhiteSpace(entry.RegistryPath)) return; + + try + { + RegistryKey? root = null; + string subPath = entry.RegistryPath; + + if (subPath.StartsWith("HKEY_LOCAL_MACHINE\\", StringComparison.OrdinalIgnoreCase)) + { + root = Registry.LocalMachine; + subPath = subPath.Substring("HKEY_LOCAL_MACHINE\\".Length); + } + else if (subPath.StartsWith("HKEY_CURRENT_USER\\", StringComparison.OrdinalIgnoreCase)) + { + root = Registry.CurrentUser; + subPath = subPath.Substring("HKEY_CURRENT_USER\\".Length); + } + + if (root != null) + { + using var key = root.OpenSubKey(subPath); + if (key != null) + { + results.Add(new RegistryJunkResult + { + EntryName = Path.GetFileName(entry.RegistryPath), + Path = entry.RegistryPath, + Confidence = ConfidenceLevel.VeryGood, + Reason = "Kaldırma sonrası sistemde kalan uninstaller kayıt defteri girdisi", + Selected = true + }); + } + } + } + catch { } + } + + public static string Rot13(string input) + { + char[] array = input.ToCharArray(); + for (int i = 0; i < array.Length; i++) + { + int number = (int)array[i]; + if (number >= 'a' && number <= 'z') + { + if (number > 'm') number -= 13; + else number += 13; + } + else if (number >= 'A' && number <= 'Z') + { + if (number > 'M') number -= 13; + else number += 13; + } + array[i] = (char)number; + } + return new string(array); + } + } +} diff --git a/src/LDUninstaller.Core/Junk/SafetyBlacklist.cs b/src/LDUninstaller.Core/Junk/SafetyBlacklist.cs new file mode 100644 index 0000000..039d206 --- /dev/null +++ b/src/LDUninstaller.Core/Junk/SafetyBlacklist.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace LDUninstaller.Core.Junk +{ + public static class SafetyBlacklist + { + private static readonly HashSet BlacklistedDirs = new(StringComparer.OrdinalIgnoreCase); + private static readonly HashSet BlacklistedRegPaths = new(StringComparer.OrdinalIgnoreCase); + + static SafetyBlacklist() + { + // Windows & System + AddDir(Environment.GetFolderPath(Environment.SpecialFolder.Windows)); + AddDir(Environment.GetFolderPath(Environment.SpecialFolder.System)); + AddDir(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86)); + AddDir(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)); + AddDir(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)); + AddDir(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); + AddDir(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); + AddDir(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); + AddDir(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)); + + // Drives roots + foreach (var drive in DriveInfo.GetDrives()) + { + AddDir(drive.RootDirectory.FullName); + } + + // Registry Blacklists + BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion"); + BlacklistedRegPaths.Add(@"HKLM\SYSTEM\CurrentControlSet"); + BlacklistedRegPaths.Add(@"HKLM\SYSTEM"); + BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft"); + BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Classes"); + BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft"); + BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows"); + BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion"); + } + + private static void AddDir(string? path) + { + if (!string.IsNullOrWhiteSpace(path)) + { + try + { + BlacklistedDirs.Add(Path.GetFullPath(path).TrimEnd('\\')); + } + catch { } + } + } + + public static bool IsDangerousDirectory(string path) + { + if (string.IsNullOrWhiteSpace(path)) return true; + try + { + string norm = Path.GetFullPath(path).TrimEnd('\\'); + if (BlacklistedDirs.Contains(norm)) + return true; + + // Parent must not be directly root or users root without specific subfolder + var di = new DirectoryInfo(norm); + if (di.Parent == null) return true; // C:\ + if (di.Parent.FullName.Equals(@"C:\Users", StringComparison.OrdinalIgnoreCase)) return true; + + return false; + } + catch + { + return true; + } + } + + public static bool IsDangerousRegistryPath(string regPath) + { + if (string.IsNullOrWhiteSpace(regPath)) return true; + string norm = regPath.Replace("/", "\\").TrimEnd('\\'); + foreach (var bl in BlacklistedRegPaths) + { + if (norm.Equals(bl, StringComparison.OrdinalIgnoreCase)) + return true; + } + // Root hives + if (!norm.Contains('\\')) return true; + return false; + } + } +} diff --git a/src/LDUninstaller.Core/LDUninstaller.Core.csproj b/src/LDUninstaller.Core/LDUninstaller.Core.csproj new file mode 100644 index 0000000..3b048a6 --- /dev/null +++ b/src/LDUninstaller.Core/LDUninstaller.Core.csproj @@ -0,0 +1,18 @@ + + + + net8.0-windows + enable + enable + true + true + LDUninstaller.Core + LDUninstaller.Core + + + + + + + + diff --git a/src/LDUninstaller.Core/Models/ApplicationUninstallerEntry.cs b/src/LDUninstaller.Core/Models/ApplicationUninstallerEntry.cs new file mode 100644 index 0000000..aede15f --- /dev/null +++ b/src/LDUninstaller.Core/Models/ApplicationUninstallerEntry.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Security.Cryptography.X509Certificates; + +namespace LDUninstaller.Core.Models +{ + public class ApplicationUninstallerEntry + { + // Tanımlayıcılar ve Temel Bilgiler + public string DisplayName { get; set; } = string.Empty; + public string RawDisplayName { get; set; } = string.Empty; + public string DisplayVersion { get; set; } = string.Empty; + public string Publisher { get; set; } = string.Empty; + public string RatingId { get; set; } = string.Empty; + public string RegistryKeyName { get; set; } = string.Empty; + public string RegistryPath { get; set; } = string.Empty; + public Guid BundleProviderKey { get; set; } = Guid.Empty; + + // Konumlar ve Yollar + public string InstallLocation { get; set; } = string.Empty; + public string UninstallerLocation { get; set; } = string.Empty; + public string UninstallerFullFilename { get; set; } = string.Empty; + public string DisplayIcon { get; set; } = string.Empty; + public string AboutUrl { get; set; } = string.Empty; + + // Kaldırma Komutları + public string UninstallString { get; set; } = string.Empty; + public string QuietUninstallString { get; set; } = string.Empty; + public string ModifyPath { get; set; } = string.Empty; + public UninstallerType UninstallerKind { get; set; } = UninstallerType.Unknown; + + // Durum ve Nitelik Bayrakları + public FileSize EstimatedSize { get; set; } = FileSize.Zero; + public DateTime InstallDate { get; set; } = DateTime.MinValue; + public MachineType Is64Bit { get; set; } = MachineType.Unknown; + public bool IsProtected { get; set; } + public bool IsRegistered { get; set; } = true; + public bool IsOrphaned { get; set; } + public bool IsUpdate { get; set; } + public bool SystemComponent { get; set; } + public bool IsValid { get; set; } = true; + public bool IsSelected { get; set; } + public bool IsCertificateValid { get; set; } + + // Görsel / Simge + [System.Text.Json.Serialization.JsonIgnore] + [System.Xml.Serialization.XmlIgnore] + public Icon? Icon { get; set; } + + [System.Text.Json.Serialization.JsonIgnore] + [System.Xml.Serialization.XmlIgnore] + public X509Certificate2? Certificate { get; set; } + + // İlişkili Varlıklar + [System.Text.Json.Serialization.JsonIgnore] + [System.Xml.Serialization.XmlIgnore] + public List StartupEntries { get; set; } = new(); + + [System.Text.Json.Serialization.JsonIgnore] + [System.Xml.Serialization.XmlIgnore] + public List AdditionalJunk { get; } = new(); + + public override string ToString() => + $"{DisplayName} ({Publisher}) - {DisplayVersion} [{UninstallerKind}]"; + } +} diff --git a/src/LDUninstaller.Core/Models/BasicTypes.cs b/src/LDUninstaller.Core/Models/BasicTypes.cs new file mode 100644 index 0000000..2be816c --- /dev/null +++ b/src/LDUninstaller.Core/Models/BasicTypes.cs @@ -0,0 +1,81 @@ +using System; + +namespace LDUninstaller.Core.Models +{ + public enum UninstallerType + { + Unknown = 0, + Msiexec = 1, + InnoSetup = 2, + Steam = 3, + Nsis = 4, + InstallShield = 5, + SdbInst = 6, + WindowsFeature = 7, + WindowsUpdate = 8, + StoreApp = 9, + SimpleDelete = 10, + Chocolatey = 11, + Oculus = 12, + PowerShell = 13, + AdvancedInstaller = 14, + Wise = 15, + Squirrel = 16, + ClickOnce = 17, + Scoop = 18 + } + + public enum ConfidenceLevel + { + Bad = 0, // Dangerous / critical system location + Questionable = 1, // Weak name match or shared temp + Good = 2, // Strong match in standard app folders + VeryGood = 3 // Exact name/publisher match; safe to clean + } + + public enum MachineType + { + Unknown = 0, + X86 = 1, + X64 = 2, + Arm64 = 3 + } + + public readonly struct FileSize : IComparable, IEquatable + { + public long Bytes { get; } + + public FileSize(long bytes) + { + Bytes = bytes < 0 ? 0 : bytes; + } + + public static FileSize FromBytes(long bytes) => new(bytes); + public static FileSize FromKilobytes(double kb) => new((long)(kb * 1024)); + public static FileSize FromMegabytes(double mb) => new((long)(mb * 1024 * 1024)); + public static FileSize Zero => new(0); + + public override string ToString() + { + if (Bytes >= 1024L * 1024 * 1024) + return $"{(double)Bytes / (1024 * 1024 * 1024):F2} GB"; + if (Bytes >= 1024L * 1024) + return $"{(double)Bytes / (1024 * 1024):F1} MB"; + if (Bytes >= 1024L) + return $"{(double)Bytes / 1024:F0} KB"; + if (Bytes > 0) + return $"{Bytes} B"; + return "0 B"; + } + + public int CompareTo(FileSize other) => Bytes.CompareTo(other.Bytes); + public bool Equals(FileSize other) => Bytes == other.Bytes; + public override bool Equals(object? obj) => obj is FileSize other && Equals(other); + public override int GetHashCode() => Bytes.GetHashCode(); + + public static bool operator ==(FileSize left, FileSize right) => left.Equals(right); + public static bool operator !=(FileSize left, FileSize right) => !left.Equals(right); + public static bool operator <(FileSize left, FileSize right) => left.Bytes < right.Bytes; + public static bool operator >(FileSize left, FileSize right) => left.Bytes > right.Bytes; + } +} diff --git a/src/LDUninstaller.Core/Models/DrivePartitionInfo.cs b/src/LDUninstaller.Core/Models/DrivePartitionInfo.cs new file mode 100644 index 0000000..38b807a --- /dev/null +++ b/src/LDUninstaller.Core/Models/DrivePartitionInfo.cs @@ -0,0 +1,33 @@ +using System; +using System.IO; + +namespace LDUninstaller.Core.Models +{ + public class DrivePartitionInfo + { + public string Name { get; set; } = string.Empty; // "C:\" + public string DriveLetter { get; set; } = string.Empty; // "C:" + public string VolumeLabel { get; set; } = string.Empty; // "Yerel Disk" + public string DriveType { get; set; } = string.Empty; // "Sabit Disk" + public long TotalBytes { get; set; } + public long FreeBytes { get; set; } + public long UsedBytes => Math.Max(0, TotalBytes - FreeBytes); + public double PercentUsed => TotalBytes > 0 ? (double)UsedBytes / TotalBytes * 100.0 : 0; + + public int AppCount { get; set; } + public long AppsTotalBytes { get; set; } + + public string DisplayTitle + { + get + { + if (string.IsNullOrWhiteSpace(VolumeLabel)) + return $"💾 {DriveLetter}"; + return $"💾 {DriveLetter} ({VolumeLabel})"; + } + } + + public string DisplayStats => $"{FileSize.FromBytes(UsedBytes)} / {FileSize.FromBytes(TotalBytes)} ({PercentUsed:F0}% Dolu)"; + public string DisplayBadge => $"{AppCount} Yazılım | {FileSize.FromBytes(AppsTotalBytes)}"; + } +} diff --git a/src/LDUninstaller.Core/Models/JunkResults.cs b/src/LDUninstaller.Core/Models/JunkResults.cs new file mode 100644 index 0000000..0a35d67 --- /dev/null +++ b/src/LDUninstaller.Core/Models/JunkResults.cs @@ -0,0 +1,172 @@ +using System; +using System.IO; +using Microsoft.Win32; + +namespace LDUninstaller.Core.Models +{ + public enum JunkType + { + RegistryKey, + RegistryValue, + Directory, + File, + Service, + FirewallRule, + UserAssist, + Shortcut + } + + public interface IJunkResult + { + string EntryName { get; } + string Path { get; } + JunkType Type { get; } + ConfidenceLevel Confidence { get; } + string Reason { get; } + bool Selected { get; set; } + bool Delete(string backupDir); + } + + public class RegistryJunkResult : IJunkResult + { + public string EntryName { get; set; } = string.Empty; + public string Path { get; set; } = string.Empty; // e.g. HKLM\SOFTWARE\Vendor\AppName + public string? ValueName { get; set; } // if null, entire key is deleted + public JunkType Type => ValueName == null ? JunkType.RegistryKey : JunkType.RegistryValue; + public ConfidenceLevel Confidence { get; set; } = ConfidenceLevel.Good; + public string Reason { get; set; } = string.Empty; + public bool Selected { get; set; } = true; + + public bool Delete(string backupDir) + { + try + { + BackupToReg(backupDir); + var (hive, subKey) = ParseRegistryPath(Path); + using var baseKey = RegistryKey.OpenBaseKey(hive, RegistryView.Default); + if (ValueName == null) + { + baseKey.DeleteSubKeyTree(subKey, false); + } + else + { + using var opened = baseKey.OpenSubKey(subKey, true); + opened?.DeleteValue(ValueName, false); + } + return true; + } + catch + { + return false; + } + } + + private void BackupToReg(string backupDir) + { + try + { + Directory.CreateDirectory(backupDir); + string sanitized = System.Text.RegularExpressions.Regex.Replace(Path, @"[\\/:\*\?""<>\|]", "_"); + string file = System.IO.Path.Combine(backupDir, $"reg_backup_{DateTime.Now:yyyyMMdd_HHmmss}_{sanitized}.reg"); + var psi = new System.Diagnostics.ProcessStartInfo("reg.exe", $"export \"{Path}\" \"{file}\" /y") + { + CreateNoWindow = true, + UseShellExecute = false + }; + using var p = System.Diagnostics.Process.Start(psi); + p?.WaitForExit(3000); + } + catch + { + // Non-fatal if backup tool fails + } + } + + private static (RegistryHive hive, string subKey) ParseRegistryPath(string fullPath) + { + int firstSlash = fullPath.IndexOf('\\'); + string hiveStr = firstSlash > 0 ? fullPath[..firstSlash] : fullPath; + string sub = firstSlash > 0 ? fullPath[(firstSlash + 1)..] : ""; + + RegistryHive hive = hiveStr.ToUpperInvariant() switch + { + "HKLM" or "HKEY_LOCAL_MACHINE" => RegistryHive.LocalMachine, + "HKCU" or "HKEY_CURRENT_USER" => RegistryHive.CurrentUser, + "HKCR" or "HKEY_CLASSES_ROOT" => RegistryHive.ClassesRoot, + "HKU" or "HKEY_USERS" => RegistryHive.Users, + _ => RegistryHive.LocalMachine + }; + return (hive, sub); + } + } + + public class FileSystemJunkResult : IJunkResult + { + public string EntryName { get; set; } = string.Empty; + public string Path { get; set; } = string.Empty; + public bool IsDirectory { get; set; } + public JunkType Type => IsDirectory ? JunkType.Directory : JunkType.File; + public ConfidenceLevel Confidence { get; set; } = ConfidenceLevel.Good; + public string Reason { get; set; } = string.Empty; + public bool Selected { get; set; } = true; + + public bool Delete(string backupDir) + { + try + { + if (IsDirectory) + { + if (Directory.Exists(Path)) + { + Directory.Delete(Path, true); + return true; + } + } + else + { + if (File.Exists(Path)) + { + try + { + File.Delete(Path); + return true; + } + catch + { + // If file is locked, queue delete on reboot + return Native.Win32.ScheduleDeleteOnReboot(Path); + } + } + } + return true; + } + catch + { + return false; + } + } + } + + public class GenericJunkResult : IJunkResult + { + public string EntryName { get; set; } = string.Empty; + public string Path { get; set; } = string.Empty; + public JunkType Type { get; set; } + public ConfidenceLevel Confidence { get; set; } = ConfidenceLevel.Good; + public string Reason { get; set; } = string.Empty; + public bool Selected { get; set; } = true; + public Func? CustomAction { get; set; } + + public bool Delete(string backupDir) + { + try + { + return CustomAction?.Invoke() ?? true; + } + catch + { + return false; + } + } + } +} diff --git a/src/LDUninstaller.Core/Models/StartupAndTweaks.cs b/src/LDUninstaller.Core/Models/StartupAndTweaks.cs new file mode 100644 index 0000000..8e0bebc --- /dev/null +++ b/src/LDUninstaller.Core/Models/StartupAndTweaks.cs @@ -0,0 +1,66 @@ +using System; + +namespace LDUninstaller.Core.Models +{ + public enum StartupType + { + RegistryRun, + RegistryRunOnce, + StartupFolder, + TaskScheduler, + Service + } + + public class StartupEntry + { + public string Name { get; set; } = string.Empty; + public string Command { get; set; } = string.Empty; + public string Publisher { get; set; } = string.Empty; + public StartupType Type { get; set; } + public string Location { get; set; } = string.Empty; + public bool IsEnabled { get; set; } = true; + public byte[]? StartupApprovedBinary { get; set; } + + public override string ToString() => $"{Name} ({Type}) - {(IsEnabled ? "Enabled" : "Disabled")}"; + } + + public class DebloatTweak + { + public string Id { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public string Category { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public bool IsApplied { get; set; } + + public Action? ApplyAction { get; set; } + public Action? RevertAction { get; set; } + + public bool Apply() + { + try + { + ApplyAction?.Invoke(); + IsApplied = true; + return true; + } + catch + { + return false; + } + } + + public bool Revert() + { + try + { + RevertAction?.Invoke(); + IsApplied = false; + return true; + } + catch + { + return false; + } + } + } +} diff --git a/src/LDUninstaller.Core/Native/Win32.cs b/src/LDUninstaller.Core/Native/Win32.cs new file mode 100644 index 0000000..200830e --- /dev/null +++ b/src/LDUninstaller.Core/Native/Win32.cs @@ -0,0 +1,237 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; + +namespace LDUninstaller.Core.Native +{ + public static class Win32 + { + // --- MSI API --- + [DllImport("msi.dll", CharSet = CharSet.Unicode)] + public static extern int MsiEnumProducts(int iProductIndex, StringBuilder lpProductBuf); + + [DllImport("msi.dll", CharSet = CharSet.Unicode)] + public static extern int MsiGetProductInfo(string szProduct, string szProperty, StringBuilder lpValueBuf, ref int pcchValueBuf); + + // --- Authenticode & WinTrust --- + [DllImport("wintrust.dll", ExactSpelling = true, SetLastError = true)] + public static extern uint WinVerifyTrust(IntPtr hwnd, [MarshalAs(UnmanagedType.LPStruct)] Guid pgActionID, WinTrustData pWVTData); + + private static readonly Guid WINTRUST_ACTION_GENERIC_VERIFY_V2 = new("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); + + public static bool VerifyEmbeddedSignature(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath)) + return false; + + try + { + using var wtd = new WinTrustFileInfo(filePath); + var data = new WinTrustData(wtd.Handle); + uint result = WinVerifyTrust(new IntPtr(-1), WINTRUST_ACTION_GENERIC_VERIFY_V2, data); + return result == 0; // 0 == ERROR_SUCCESS + } + catch + { + return false; + } + } + + // --- System Restore API (srclient.dll) --- + [DllImport("srclient.dll", CharSet = CharSet.Unicode)] + public static extern bool SRSetRestorePointW(ref RESTOREPOINTINFO pRestorePointInit, ref STATEMGRSTATUS pSMgrStatus); + + public static bool CreateRestorePoint(string description, out long sequenceNumber) + { + sequenceNumber = 0; + try + { + var info = new RESTOREPOINTINFO + { + dwEventType = 100, // BEGIN_SYSTEM_CHANGE + dwRestorePtType = 0, // APPLICATION_INSTALL / UNINSTALL + llSequenceNumber = 0, + szDescription = description + }; + var status = new STATEMGRSTATUS(); + bool ok = SRSetRestorePointW(ref info, ref status); + if (ok && status.nStatus == 0) + { + sequenceNumber = status.llSequenceNumber; + return true; + } + } + catch + { + // Fallback / SR disabled on machine + } + return false; + } + + // --- MoveFileEx (Reboot cleanup) --- + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + public static extern bool MoveFileEx(string lpExistingFileName, string? lpNewFileName, int dwFlags); + public const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004; + + public static bool ScheduleDeleteOnReboot(string path) + { + try + { + return MoveFileEx(path, null, MOVEFILE_DELAY_UNTIL_REBOOT); + } + catch + { + return false; + } + } + + // --- Shell Icons --- + [DllImport("shell32.dll", CharSet = CharSet.Auto)] + public static extern uint ExtractIconEx(string szFileName, int nIconIndex, IntPtr[]? phiconLarge, IntPtr[]? phiconSmall, uint nIcons); + + [DllImport("user32.dll", SetLastError = true)] + public static extern bool DestroyIcon(IntPtr hIcon); + + // --- Window & Process Control --- + [DllImport("user32.dll", SetLastError = true)] + public static extern IntPtr FindWindow(string? lpClassName, string? lpWindowName); + + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam, uint fuFlags, uint uTimeout, out IntPtr lpdwResult); + + [DllImport("user32.dll")] + public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); + + [DllImport("user32.dll")] + public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + + public const uint WM_CLOSE = 0x0010; + public const uint SMTO_ABORTIFHUNG = 0x0002; + public const int SW_HIDE = 0; + public const uint SWP_NOSIZE = 0x0001; + public const uint SWP_NOZORDER = 0x0004; + + public static void GentleKillProcess(Process process, int waitMs = 3000) + { + try + { + if (process.HasExited) return; + + if (process.MainWindowHandle != IntPtr.Zero) + { + SendMessageTimeout(process.MainWindowHandle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero, SMTO_ABORTIFHUNG, (uint)waitMs, out _); + if (process.WaitForExit(waitMs)) + return; + } + + process.CloseMainWindow(); + if (process.WaitForExit(waitMs)) + return; + + process.Kill(true); + } + catch + { + // Process already terminated or access denied + } + } + + // --- PE COFF Architecture Reader --- + public static ushort GetPeArchitecture(string filePath) + { + if (!File.Exists(filePath)) return 0; + try + { + using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using var br = new BinaryReader(fs); + if (fs.Length < 64) return 0; + if (br.ReadUInt16() != 0x5A4D) return 0; // MZ header + fs.Seek(0x3C, SeekOrigin.Begin); + int peOffset = br.ReadInt32(); + if (peOffset + 6 > fs.Length) return 0; + fs.Seek(peOffset, SeekOrigin.Begin); + if (br.ReadUInt32() != 0x00004550) return 0; // PE\0\0 + return br.ReadUInt16(); // Machine + } + catch + { + return 0; + } + } + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct RESTOREPOINTINFO + { + public int dwEventType; + public int dwRestorePtType; + public long llSequenceNumber; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] + public string szDescription; + } + + [StructLayout(LayoutKind.Sequential)] + public struct STATEMGRSTATUS + { + public int nStatus; + public long llSequenceNumber; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public class WinTrustData : IDisposable + { + private uint cbStruct = (uint)Marshal.SizeOf(typeof(WinTrustData)); + private IntPtr pPolicyCallbackData = IntPtr.Zero; + private IntPtr pSIPClientData = IntPtr.Zero; + private uint dwUIChoice = 2; // WTD_UI_NONE + private uint fdwRevocationChecks = 0; // WTD_REVOKE_NONE + private uint dwUnionChoice = 1; // WTD_CHOICE_FILE + private IntPtr pFile; + private uint dwStateAction = 0; + private IntPtr hWVTStateData = IntPtr.Zero; + private IntPtr pwszURLReference = IntPtr.Zero; + private uint dwProvFlags = 0x00000040 | 0x00000010 | 0x00001000; // WTD_SAFER_FLAG | WTD_REVOCATION_CHECK_NONE | WTD_CACHE_ONLY_URL_RETRIEVAL + private uint dwUIContext = 0; + + public WinTrustData(IntPtr fileInfoPtr) + { + pFile = fileInfoPtr; + } + + public void Dispose() + { + // No unmanaged allocations inside this class directly + } + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public class WinTrustFileInfo : IDisposable + { + private uint cbStruct = (uint)Marshal.SizeOf(typeof(WinTrustFileInfo)); + [MarshalAs(UnmanagedType.LPWStr)] + private string pcwszFilePath; + private IntPtr hFile = IntPtr.Zero; + private IntPtr pgKnownSubject = IntPtr.Zero; + private IntPtr _nativeMemory = IntPtr.Zero; + + public IntPtr Handle => _nativeMemory; + + public WinTrustFileInfo(string filePath) + { + pcwszFilePath = filePath; + _nativeMemory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WinTrustFileInfo))); + Marshal.StructureToPtr(this, _nativeMemory, false); + } + + public void Dispose() + { + if (_nativeMemory != IntPtr.Zero) + { + Marshal.FreeHGlobal(_nativeMemory); + _nativeMemory = IntPtr.Zero; + } + } + } +} diff --git a/src/LDUninstaller.Core/Startup/StartupManager.cs b/src/LDUninstaller.Core/Startup/StartupManager.cs new file mode 100644 index 0000000..c7a180c --- /dev/null +++ b/src/LDUninstaller.Core/Startup/StartupManager.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.ServiceProcess; +using LDUninstaller.Core.Models; +using Microsoft.Win32; + +namespace LDUninstaller.Core.Startup +{ + public class StartupManager + { + public static List GetAllStartupEntries() + { + var list = new List(); + + // 1. Registry HKCU Run + ScanRegistryRun(Registry.CurrentUser, @"Software\Microsoft\Windows\CurrentVersion\Run", StartupType.RegistryRun, list); + // 2. Registry HKLM Run + ScanRegistryRun(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", StartupType.RegistryRun, list); + // 3. Registry HKLM 32-bit (Wow6432Node) + if (Environment.Is64BitOperatingSystem) + { + using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); + using var key = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); + if (key != null) + { + foreach (var name in key.GetValueNames()) + { + var val = key.GetValue(name)?.ToString() ?? string.Empty; + list.Add(new StartupEntry + { + Name = name, + Command = val, + Type = StartupType.RegistryRun, + Location = @"HKLM\Software\Wow6432Node\...\Run", + IsEnabled = CheckStartupApproved(name) + }); + } + } + } + + // 4. Startup Folders + ScanFolder(Environment.GetFolderPath(Environment.SpecialFolder.Startup), "User Startup Folder", list); + ScanFolder(Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup), "All Users Startup Folder", list); + + // 5. Services (3rd party automatic) + ScanServices(list); + + return list; + } + + private static void ScanRegistryRun(RegistryKey root, string subKey, StartupType type, List list) + { + try + { + using var key = root.OpenSubKey(subKey); + if (key == null) return; + + foreach (var name in key.GetValueNames()) + { + string cmd = key.GetValue(name)?.ToString() ?? string.Empty; + list.Add(new StartupEntry + { + Name = name, + Command = cmd, + Type = type, + Location = $"{root.Name}\\{subKey}", + IsEnabled = CheckStartupApproved(name) + }); + } + } + catch { } + } + + private static void ScanFolder(string path, string locationDesc, List list) + { + if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path)) return; + try + { + foreach (var file in Directory.GetFiles(path)) + { + string name = Path.GetFileNameWithoutExtension(file); + list.Add(new StartupEntry + { + Name = name, + Command = file, + Type = StartupType.StartupFolder, + Location = locationDesc, + IsEnabled = true + }); + } + } + catch { } + } + + private static void ScanServices(List list) + { + try + { + var services = ServiceController.GetServices(); + foreach (var sc in services) + { + try + { + using var key = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{sc.ServiceName}"); + if (key != null) + { + int startType = (int)(key.GetValue("Start") ?? 3); + // 2 = Automatic + if (startType == 2) + { + string imgPath = key.GetValue("ImagePath")?.ToString() ?? ""; + if (!imgPath.ToLowerInvariant().Contains(@"windows\system32")) + { + list.Add(new StartupEntry + { + Name = sc.DisplayName, + Command = imgPath, + Type = StartupType.Service, + Location = "Windows Service", + IsEnabled = sc.Status == ServiceControllerStatus.Running + }); + } + } + } + } + catch { } + } + } + catch { } + } + + public static bool CheckStartupApproved(string entryName) + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"); + if (key?.GetValue(entryName) is byte[] data && data.Length > 0) + { + // 0x02 is enabled, 0x03 or other is disabled + return data[0] == 0x02; + } + } + catch { } + return true; + } + + public static bool ToggleStartupEntry(StartupEntry entry, bool enable) + { + try + { + if (entry.Type == StartupType.RegistryRun) + { + using var key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"); + if (key != null) + { + byte[] data = enable + ? new byte[] { 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } + : new byte[] { 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + key.SetValue(entry.Name, data, RegistryValueKind.Binary); + entry.IsEnabled = enable; + return true; + } + } + else if (entry.Type == StartupType.Service) + { + using var sc = new ServiceController(entry.Name); + if (enable && sc.Status != ServiceControllerStatus.Running) + { + sc.Start(); + entry.IsEnabled = true; + } + else if (!enable && sc.Status == ServiceControllerStatus.Running) + { + sc.Stop(); + entry.IsEnabled = false; + } + return true; + } + } + catch { } + return false; + } + } +} diff --git a/src/LDUninstaller.Core/Tweaks/WindowsTweaks.cs b/src/LDUninstaller.Core/Tweaks/WindowsTweaks.cs new file mode 100644 index 0000000..40913a5 --- /dev/null +++ b/src/LDUninstaller.Core/Tweaks/WindowsTweaks.cs @@ -0,0 +1,169 @@ +using System; +using System.Collections.Generic; +using System.ServiceProcess; +using LDUninstaller.Core.Models; +using Microsoft.Win32; + +namespace LDUninstaller.Core.Tweaks +{ + public static class WindowsTweaks + { + public static List GetDefaultTweaks() + { + return new List + { + new DebloatTweak + { + Id = "telemetry", + Title = "Windows Telemetri ve Veri Toplamayı Kapat", + Category = "Gizlilik & Güvenlik", + Description = "DiagTrack ve dmwappushservice servislerini durdurur ve kayıt defteri telemetri bayraklarını 0 yapar.", + IsApplied = CheckTelemetryDisabled(), + ApplyAction = () => + { + StopAndDisableService("DiagTrack"); + StopAndDisableService("dmwappushservice"); + + using var key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows\DataCollection"); + key?.SetValue("AllowTelemetry", 0, RegistryValueKind.DWord); + + using var userKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack"); + userKey?.SetValue("ShowedToastAtLevel", 0, RegistryValueKind.DWord); + }, + RevertAction = () => + { + using var key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows\DataCollection"); + key?.SetValue("AllowTelemetry", 1, RegistryValueKind.DWord); + } + }, + new DebloatTweak + { + Id = "cortana_bing", + Title = "Cortana ve Web Aramalarını Kapat", + Category = "Sistem & Başlat", + Description = "Başlat menüsünde Bing web aramalarını ve Cortana asistanını devre dışı bırakır.", + IsApplied = CheckCortanaDisabled(), + ApplyAction = () => + { + using var searchKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Search"); + searchKey?.SetValue("DisableWebSearch", 1, RegistryValueKind.DWord); + searchKey?.SetValue("ConnectedSearchUseWeb", 0, RegistryValueKind.DWord); + searchKey?.SetValue("BingSearchEnabled", 0, RegistryValueKind.DWord); + + using var policyKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows\Windows Search"); + policyKey?.SetValue("AllowCortana", 0, RegistryValueKind.DWord); + policyKey?.SetValue("DisableWebSearch", 1, RegistryValueKind.DWord); + policyKey?.SetValue("ConnectedSearchUseWeb", 0, RegistryValueKind.DWord); + }, + RevertAction = () => + { + using var searchKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Search"); + searchKey?.SetValue("DisableWebSearch", 0, RegistryValueKind.DWord); + searchKey?.SetValue("ConnectedSearchUseWeb", 1, RegistryValueKind.DWord); + searchKey?.SetValue("BingSearchEnabled", 1, RegistryValueKind.DWord); + } + }, + new DebloatTweak + { + Id = "silent_apps", + Title = "Önerilen ve Sponsorlu Uygulamaların Otomatik Yüklenmesini Engelle", + Category = "Windows Mağaza", + Description = "Candy Crush ve benzeri sponsorlu 3. parti uygulamaların arka planda yüklenmesini engeller.", + IsApplied = CheckSilentAppsDisabled(), + ApplyAction = () => + { + using var cdmKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager"); + cdmKey?.SetValue("SilentInstalledAppsEnabled", 0, RegistryValueKind.DWord); + cdmKey?.SetValue("SubscribedContent-338388Enabled", 0, RegistryValueKind.DWord); + cdmKey?.SetValue("SubscribedContent-338389Enabled", 0, RegistryValueKind.DWord); + cdmKey?.SetValue("SystemPaneSuggestionsEnabled", 0, RegistryValueKind.DWord); + }, + RevertAction = () => + { + using var cdmKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager"); + cdmKey?.SetValue("SilentInstalledAppsEnabled", 1, RegistryValueKind.DWord); + } + }, + new DebloatTweak + { + Id = "sticky_keys", + Title = "Yapışkan Tuşlar (Sticky Keys) Açılır Penceresini Engelle", + Category = "Erişilebilirlik", + Description = "5 kez Shift tuşuna basıldığında açılan yapışkan tuşlar uyarı penceresini sessizleştirir.", + IsApplied = CheckStickyKeysDisabled(), + ApplyAction = () => + { + using var key = Registry.CurrentUser.CreateSubKey(@"Control Panel\Accessibility\StickyKeys"); + key?.SetValue("Flags", "506", RegistryValueKind.String); + }, + RevertAction = () => + { + using var key = Registry.CurrentUser.CreateSubKey(@"Control Panel\Accessibility\StickyKeys"); + key?.SetValue("Flags", "510", RegistryValueKind.String); + } + } + }; + } + + private static bool CheckTelemetryDisabled() + { + try + { + using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Policies\Microsoft\Windows\DataCollection"); + int val = (int)(key?.GetValue("AllowTelemetry") ?? 1); + return val == 0; + } + catch { return false; } + } + + private static bool CheckCortanaDisabled() + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Search"); + int val = (int)(key?.GetValue("DisableWebSearch") ?? 0); + return val == 1; + } + catch { return false; } + } + + private static bool CheckSilentAppsDisabled() + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager"); + int val = (int)(key?.GetValue("SilentInstalledAppsEnabled") ?? 1); + return val == 0; + } + catch { return false; } + } + + private static bool CheckStickyKeysDisabled() + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Accessibility\StickyKeys"); + string val = key?.GetValue("Flags")?.ToString() ?? ""; + return val == "506"; + } + catch { return false; } + } + + private static void StopAndDisableService(string serviceName) + { + try + { + using var sc = new ServiceController(serviceName); + if (sc.Status == ServiceControllerStatus.Running) + { + sc.Stop(); + sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3)); + } + + using var key = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{serviceName}", true); + key?.SetValue("Start", 4, RegistryValueKind.DWord); // 4 = Disabled + } + catch { } + } + } +} diff --git a/src/LDUninstaller.Launcher/LDUninstaller.Launcher.csproj b/src/LDUninstaller.Launcher/LDUninstaller.Launcher.csproj new file mode 100644 index 0000000..7c327cb --- /dev/null +++ b/src/LDUninstaller.Launcher/LDUninstaller.Launcher.csproj @@ -0,0 +1,17 @@ + + + + WinExe + net8.0-windows + enable + enable + true + LDUninstaller.Launcher + LDUninstaller.Launcher + + + + + + + diff --git a/src/LDUninstaller.Launcher/Program.cs b/src/LDUninstaller.Launcher/Program.cs new file mode 100644 index 0000000..dae229c --- /dev/null +++ b/src/LDUninstaller.Launcher/Program.cs @@ -0,0 +1,89 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Windows.Forms; + +namespace LDUninstaller.Launcher +{ + internal static class Program + { + [STAThread] + static void Main(string[] args) + { + ApplicationConfiguration.Initialize(); + + // 1. Architecture check + var arch = RuntimeInformation.OSArchitecture; + + // 2. Administrator check + if (!IsAdministrator()) + { + try + { + string exePath = Process.GetCurrentProcess().MainModule?.FileName ?? Application.ExecutablePath; + var psi = new ProcessStartInfo + { + FileName = exePath, + Arguments = string.Join(" ", args), + UseShellExecute = true, + Verb = "runas" + }; + Process.Start(psi); + return; + } + catch (Exception) + { + MessageBox.Show( + "Bu uygulamanın tüm yazılımları eksiksiz tespit edebilmesi ve kalıntıları temizleyebilmesi için Yönetici (Administrator) yetkilerine ihtiyacı vardır.", + "Yönetici İzni Gerekli - LD Uninstaller", + MessageBoxButtons.OK, + MessageBoxIcon.Warning); + return; + } + } + + // 3. Locate LDUninstaller.UI.exe + string baseDir = AppDomain.CurrentDomain.BaseDirectory; + string uiPath = Path.Combine(baseDir, "LDUninstaller.UI.exe"); + + if (!File.Exists(uiPath)) + { + // In Debug / Development environment check + string siblingUi = Path.GetFullPath(Path.Combine(baseDir, "..", "LDUninstaller.UI", "LDUninstaller.UI.exe")); + if (File.Exists(siblingUi)) + { + uiPath = siblingUi; + } + } + + if (File.Exists(uiPath)) + { + var psi = new ProcessStartInfo + { + FileName = uiPath, + Arguments = string.Join(" ", args), + UseShellExecute = false, + WorkingDirectory = Path.GetDirectoryName(uiPath) + }; + Process.Start(psi); + } + else + { + MessageBox.Show( + $"Ana arayüz yürütülebilir dosyası bulunamadı:\n{uiPath}", + "Başlatma Hatası", + MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private static bool IsAdministrator() + { + using var identity = WindowsIdentity.GetCurrent(); + var principal = new WindowsPrincipal(identity); + return principal.IsInRole(WindowsBuiltInRole.Administrator); + } + } +} diff --git a/src/LDUninstaller.UI/App.xaml b/src/LDUninstaller.UI/App.xaml new file mode 100644 index 0000000..9550a79 --- /dev/null +++ b/src/LDUninstaller.UI/App.xaml @@ -0,0 +1,174 @@ + + + + #0B0F19 + #111827 + #1F2937 + #283548 + #374151 + #4B5563 + #F9FAFB + #9CA3AF + #6B7280 + + #3B82F6 + #2563EB + #10B981 + #EF4444 + #8B5CF6 + #F59E0B + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/LDUninstaller.UI/App.xaml.cs b/src/LDUninstaller.UI/App.xaml.cs new file mode 100644 index 0000000..db2d430 --- /dev/null +++ b/src/LDUninstaller.UI/App.xaml.cs @@ -0,0 +1,36 @@ +using System; +using System.IO; +using System.Windows; + +namespace LDUninstaller.UI +{ + public partial class App : Application + { + protected override void OnStartup(StartupEventArgs e) + { + base.OnStartup(e); + + string logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "trace.log"); + AppDomain.CurrentDomain.ProcessExit += (s, args) => + { + try { File.AppendAllText(logPath, $"PROCESS EXIT TRIGGERED! Environment.StackTrace:\n{Environment.StackTrace}\n"); } catch { } + }; + + AppDomain.CurrentDomain.UnhandledException += (s, args) => + { + try { File.AppendAllText(logPath, $"UNHANDLED: {args.ExceptionObject}\n"); } catch { } + }; + + DispatcherUnhandledException += (s, args) => + { + try { File.WriteAllText(logPath, args.Exception.ToString()); } catch { } + MessageBox.Show( + $"Arayüz Hatası:\n{args.Exception.Message}\n\n{args.Exception}", + "Hata - LD Uninstaller", + MessageBoxButton.OK, + MessageBoxImage.Error); + args.Handled = true; + }; + } + } +} diff --git a/src/LDUninstaller.UI/Controls/WpfSquarifiedTreeMap.cs b/src/LDUninstaller.UI/Controls/WpfSquarifiedTreeMap.cs new file mode 100644 index 0000000..179277a --- /dev/null +++ b/src/LDUninstaller.UI/Controls/WpfSquarifiedTreeMap.cs @@ -0,0 +1,208 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; +using LDUninstaller.Core.Algorithms; +using LDUninstaller.Core.Models; + +namespace LDUninstaller.UI.Controls +{ + public class WpfSquarifiedTreeMap : FrameworkElement + { + private List> _items = new(); + private TreeMapItem? _hoveredItem; + public event Action? OnItemSelected; + + private static readonly Brush[] Palette; + private static readonly Pen BorderPen; + private static readonly Pen HoverPen; + private static readonly Brush BackdropBrush; + private static readonly Brush EmptyTextBrush; + private static readonly Brush SubTextBrush; + private static readonly Typeface TitleTypeface; + private static readonly Typeface SubTypeface; + + static WpfSquarifiedTreeMap() + { + Palette = new Brush[] + { + new SolidColorBrush(Color.FromRgb(37, 99, 235)), // Modern Blue + new SolidColorBrush(Color.FromRgb(16, 185, 129)), // Emerald + new SolidColorBrush(Color.FromRgb(139, 92, 246)), // Violet + new SolidColorBrush(Color.FromRgb(245, 158, 11)), // Amber + new SolidColorBrush(Color.FromRgb(14, 165, 233)), // Sky + new SolidColorBrush(Color.FromRgb(239, 68, 68)), // Rose + new SolidColorBrush(Color.FromRgb(99, 102, 241)), // Indigo + new SolidColorBrush(Color.FromRgb(20, 184, 166)) // Teal + }; + + foreach (var b in Palette) b.Freeze(); + + BorderPen = new Pen(new SolidColorBrush(Color.FromArgb(120, 15, 23, 42)), 1.5); + BorderPen.Freeze(); + + HoverPen = new Pen(Brushes.White, 2.0); + HoverPen.Freeze(); + + BackdropBrush = new SolidColorBrush(Color.FromRgb(15, 23, 42)); + BackdropBrush.Freeze(); + + EmptyTextBrush = new SolidColorBrush(Color.FromRgb(148, 163, 184)); + EmptyTextBrush.Freeze(); + + SubTextBrush = new SolidColorBrush(Color.FromArgb(200, 240, 240, 240)); + SubTextBrush.Freeze(); + + TitleTypeface = new Typeface(new FontFamily("Segoe UI"), FontStyles.Normal, FontWeights.SemiBold, FontStretches.Normal); + SubTypeface = new Typeface(new FontFamily("Segoe UI"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); + } + + public WpfSquarifiedTreeMap() + { + ClipToBounds = true; + MouseMove += WpfSquarifiedTreeMap_MouseMove; + MouseLeave += (s, e) => { _hoveredItem = null; InvalidateVisual(); }; + MouseLeftButtonDown += WpfSquarifiedTreeMap_MouseLeftButtonDown; + } + + public void SetData(IEnumerable entries) + { + var valid = entries + .Where(e => e.EstimatedSize.Bytes > 1024 * 1024) // > 1 MB + .Select(e => new TreeMapItem(e, e.EstimatedSize.Bytes)) + .ToList(); + + _items = valid; + Recalculate(); + InvalidateVisual(); + } + + protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) + { + base.OnRenderSizeChanged(sizeInfo); + Recalculate(); + InvalidateVisual(); + } + + private void Recalculate() + { + if (ActualWidth <= 10 || ActualHeight <= 10 || _items.Count == 0) return; + var bounds = new System.Drawing.RectangleF(2, 2, (float)ActualWidth - 4, (float)ActualHeight - 4); + _items = SquarifiedTreeMap.CalculateLayout(_items, bounds); + } + + private void WpfSquarifiedTreeMap_MouseMove(object sender, MouseEventArgs e) + { + var p = e.GetPosition(this); + var hit = _items.FirstOrDefault(i => + p.X >= i.Bounds.X && p.X <= i.Bounds.Right && + p.Y >= i.Bounds.Y && p.Y <= i.Bounds.Bottom); + + if (hit != _hoveredItem) + { + _hoveredItem = hit; + ToolTip = _hoveredItem != null + ? $"{_hoveredItem.Value.DisplayName}\nBoyut: {_hoveredItem.Value.EstimatedSize}\nYayıncı: {_hoveredItem.Value.Publisher}" + : null; + InvalidateVisual(); + } + } + + private void WpfSquarifiedTreeMap_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + if (_hoveredItem != null) + { + OnItemSelected?.Invoke(_hoveredItem.Value); + } + } + + protected override void OnRender(DrawingContext dc) + { + base.OnRender(dc); + + // Draw dark backdrop with frozen brush + dc.DrawRectangle(BackdropBrush, null, new Rect(0, 0, ActualWidth, ActualHeight)); + + if (_items.Count == 0) + { + var ftEmpty = new FormattedText( + "Görselleştirilecek disk verisi yok veya boyutlar hesaplanıyor...", + CultureInfo.CurrentCulture, + FlowDirection.LeftToRight, + TitleTypeface, + 13, + EmptyTextBrush, + 1.0); + dc.DrawText(ftEmpty, new Point((ActualWidth - ftEmpty.Width) / 2, (ActualHeight - ftEmpty.Height) / 2)); + return; + } + + int index = 0; + double dpi = VisualTreeHelper.GetDpi(this).PixelsPerDip; + + foreach (var item in _items) + { + var b = item.Bounds; + if (b.Width < 2 || b.Height < 2) continue; + + var rect = new Rect(b.X, b.Y, b.Width, b.Height); + var brush = Palette[index % Palette.Length]; + index++; + + bool isHovered = item == _hoveredItem; + + dc.DrawRoundedRectangle(brush, isHovered ? HoverPen : BorderPen, rect, 4, 4); + + // Text labels + if (b.Width > 55 && b.Height > 28) + { + string title = item.Value?.DisplayName ?? "Uygulama"; + string sub = item.Value?.EstimatedSize.ToString() ?? ""; + double maxW = Math.Max(10, b.Width - 12); + + try + { + var ft = new FormattedText( + title, + CultureInfo.CurrentCulture, + FlowDirection.LeftToRight, + TitleTypeface, + 11, + Brushes.White, + dpi) + { + MaxTextWidth = maxW, + MaxTextHeight = 16, + Trimming = TextTrimming.CharacterEllipsis + }; + + dc.DrawText(ft, new Point(b.X + 6, b.Y + 5)); + + if (b.Height > 44) + { + var ftSub = new FormattedText( + sub, + CultureInfo.CurrentCulture, + FlowDirection.LeftToRight, + SubTypeface, + 9.5, + SubTextBrush, + dpi) + { + MaxTextWidth = maxW, + MaxTextHeight = 14, + Trimming = TextTrimming.CharacterEllipsis + }; + dc.DrawText(ftSub, new Point(b.X + 6, b.Y + 22)); + } + } + catch { } + } + } + } + } +} diff --git a/src/LDUninstaller.UI/Dialogs/BulkWizardWindow.xaml b/src/LDUninstaller.UI/Dialogs/BulkWizardWindow.xaml new file mode 100644 index 0000000..27b5208 --- /dev/null +++ b/src/LDUninstaller.UI/Dialogs/BulkWizardWindow.xaml @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + +