diff --git a/Directory.Build.props b/Directory.Build.props index acb4c07..67164b0 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,8 +1,8 @@  - 2.7.1 - 2.7.1.0 - 2.7.1.0 + 2.8.0 + 2.8.0.0 + 2.8.0.0 LD Uninstaller LD Software LD Software diff --git a/LD-Uninstaller-Setup-v2.7.1.exe b/LD-Uninstaller-Setup-v2.8.0.exe similarity index 83% rename from LD-Uninstaller-Setup-v2.7.1.exe rename to LD-Uninstaller-Setup-v2.8.0.exe index a17aba4..f955031 100644 Binary files a/LD-Uninstaller-Setup-v2.7.1.exe and b/LD-Uninstaller-Setup-v2.8.0.exe differ diff --git a/LDUninstaller.sln b/LDUninstaller.sln index 8dfe64f..cbc8cbb 100644 --- a/LDUninstaller.sln +++ b/LDUninstaller.sln @@ -15,6 +15,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDUninstaller.UI", "src\LDU EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDUninstaller.Launcher", "src\LDUninstaller.Launcher\LDUninstaller.Launcher.csproj", "{8B9A7CB4-F72E-42F3-ADC9-A253FBE447E3}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{8EE5BA1E-6ECC-43C0-95C4-5FF1CE4FF319}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDUninstaller.Tests", "tests\LDUninstaller.Tests\LDUninstaller.Tests.csproj", "{AB7C8AF3-BB19-4ED1-B179-D50D5FED7BA7}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -44,6 +48,10 @@ Global {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 + {AB7C8AF3-BB19-4ED1-B179-D50D5FED7BA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AB7C8AF3-BB19-4ED1-B179-D50D5FED7BA7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AB7C8AF3-BB19-4ED1-B179-D50D5FED7BA7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AB7C8AF3-BB19-4ED1-B179-D50D5FED7BA7}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {CD3DDC8C-4415-46B1-9E3D-C71152DE0902} = {AE9859BA-F5B7-476C-9ACF-870E6CB944B0} @@ -51,5 +59,6 @@ Global {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} + {AB7C8AF3-BB19-4ED1-B179-D50D5FED7BA7} = {8EE5BA1E-6ECC-43C0-95C4-5FF1CE4FF319} EndGlobalSection EndGlobal diff --git a/README.md b/README.md index 4453a0c..78b2a6a 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,25 @@ -# LD Uninstaller +# LD Uninstaller (v2.8.0) +**Resmi Web Sitesi ve İndirme:** [https://ttmadethat.shop/#ldapps](https://ttmadethat.shop/#ldapps) -**LD Uninstaller**, Bulk Crap Uninstaller (BCU) mimarisini temel alan; donanım hızlandırmalı modern **Windows 11 Fluent Dark** arayüzü, 20 katmanlı derin kalıntı temizleme motoru, çoklu disk analizi ve akıllı otomasyon ajanıyla güçlendirilmiş açık kaynaklı, gelişmiş sistem yönetimi ve yazılım kaldırma çözümüdür. +**LD Uninstaller**, Bulk Crap Uninstaller (BCU) mimarisini temel alan; donanım hızlandırmalı modern **Windows 11 Fluent Dark** arayüzü, 20 katmanlı derin kalıntı temizleme motoru, Geri Dönüşüm Kutusu (Shell API) koruması, otomatik `.reg` yedekleme merkezi, çoklu disk analizi ve akıllı otomasyon ajanıyla güçlendirilmiş açık kaynaklı, profesyonel sistem yönetimi ve yazılım kaldırma çözümüdür. --- ## ✨ Öne Çıkan Özellikler ### 1. 🧹 20 Katmanlı Derin Kalıntı ve Artık Temizleme Motoru (Leftover Cleaner) -Kaldırma işlemi (tekli veya çoklu) bittiği anda otomatik olarak açılan kalıntı temizleme ekranı, sistemde hiçbir yazılımın tek bir izini dahi bırakmaz: +Kaldırma işlemi bittiği anda otomatik olarak açılan kalıntı temizleme ekranı, sistemde hiçbir yazılımın tek bir izini dahi bırakmaz: 1. **Ana Kurulum Dizinleri:** Kaldırıcı sonrası silinmeyen klasörler. -2. **Kullanıcı Verileri:** `%AppData%`, `%LocalAppData%`, `LocalLow`, `ProgramData`, `Documents`, `Saved Games`. +2. **Kullanıcı Verileri:** `%AppData%`, `%LocalAppData%`, `LocalLow`, `ProgramData`, `Saved Games` (Belgelerim / Documents otomatik silme riskine karşı korunmuştur). 3. **Kullanıcı Gizli Dizinleri (Dot-Folders):** Modern yazılımların `%USERPROFILE%` altındaki `.appname`, `.config`, `.cache` klasörleri. 4. **Ortak Kütüphaneler (Common Files):** `Common Files` altında terk edilen DLL ve bileşenler. 5. **Geçici Dosyalar (Temp):** `%TEMP%` ve `%LOCALAPPDATA%\Temp` kurulum/kaldırma artıkları. 6. **Çoklu Sürücüler & Boş Dizinler:** İkincil disklerdeki (`D:\`, `E:\`) oyun/yazılım artıkları ve içi boş kalan yayıncı klasörleri. -7. **Yazılım Kayıt Defteri Anahtarları:** `HKLM`, `HKCU` ve `WOW6432Node` Software dalları. -8. **Windows Hizmetleri & Sürücüler:** `HKLM\SYSTEM\CurrentControlSet\Services` taranarak uygulamaya ait arka plan servisleri tespit edilir ve `sc stop` + `sc delete` ile kaldırılır. +7. **Yazılım Kayıt Defteri Anahtarları:** `HKLM`, `HKCU` ve `WOW6432Node` Software dalları (silinmeden önce otomatik `.reg` yedeği alınır). +8. **Windows Hizmetleri & Sürücüler:** Yalnızca `ImagePath` hedefi kaldırılan uygulamanın `InstallLocation` klasörü altındaysa tespit edilir, kayıt defteri yedeklenir ve `sc stop` + `sc delete` ile kaldırılır. 9. **Görev Zamanlayıcı (Scheduled Tasks):** `C:\Windows\System32\Tasks` içindeki güncelleyici ve otomatik görevler taranarak temizlenir. 10. **Uygulama Başlatma Yolları (App Paths):** `App Paths` altındaki yetim kayıtlar. -11. **Başlangıç Kayıt Defteri Değerleri (Run & RunOnce):** Otomatik çalıştırma anahtarlarındaki ilgili değerler. +11. **Başlangıç Kayıt Defteri Değerleri (Run, RunOnce & Task Scheduler):** Otomatik çalıştırma anahtarlarındaki ilgili değerler. 12. **Gezgin Sağ Tık & COM Bileşenleri:** `ContextMenuHandlers`, `Approved` shell uzantıları ve ilişkili `CLSID` anahtarları. 13. **Windows Shell MuiCache:** MuiCache önbellek ve simge kayıtları. 14. **Uyumluluk Katmanı (AppCompatFlags):** Compatibility Assistant ve Layers geçmişi. @@ -29,63 +30,62 @@ Kaldırma işlemi (tekli veya çoklu) bittiği anda otomatik olarak açılan kal 19. **Kısayollar & Son Belgeler:** Masaüstü, Başlat Menüsü, Startup ve Recent kısayolları. 20. **Windows Installer (MSI) & Uninstall Kayıtları:** MSI Product/UserData ve Registry Uninstall girdileri. -### 2. ⚡ 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. +--- -### 3. 💾 Ç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)** dinamik olarak güncellenir. - -### 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. +### 2. 🛡️ Veri Güvenliği ve Geri Alma Garantisi +- **Windows Geri Dönüşüm Kutusu:** Tüm dosya ve dizin silme işlemleri `SHFileOperation` Win32 Shell API üzerinden Geri Dönüşüm Kutusu'na gönderilir (`FOF_ALLOWUNDO`). Kalıcı veri kaybı yaşanmaz. +- **Otomatik Kayıt Defteri Yedekleri:** Temizlenen her kayıt anahtarı silinmeden önce `%LocalAppData%\LDUninstaller\Backups` klasörüne standart `.reg` yedeği olarak aktarılır (32-bit anahtarlar için `/reg:32` kullanılır). +- **Yedekleme ve Geri Yükleme Merkezi:** Tek tıkla önceki yedekleri inceleme ve Windows Kayıt Defteri'ne geri aktarma (`reg import`). +- **Kullanıcı Koruma Listesi (Exclusion List):** Kalıntı ekranında veya araçlar menüsünde "Korumaya Al (Bir daha önerme)" seçeneği ile klasör veya kayıt defteri anahtarlarını kalıcı beyaz listeye alma (`%LocalAppData%\LDUninstaller\exclusions.json`). +- **Dinamik Sistem Kara Listesi (SafetyBlacklist):** `C:\Windows`, `System32`, `Program Files\WindowsApps`, kullanıcı profil kök dizinleri ve OneDrive kökleri hiçbir koşulda kalıntı olarak silinemez. --- -## 📦 Dağıtım ve Yayınlama (Release Management) +### 3. 💥 Yeni Özellikler (v2.8.0) +- **Zorla Kaldır (Force Uninstall):** Kaldırıcısı eksik, bozuk veya çalışmayan uygulamalar için doğrudan derin disk ve kayıt defteri kalıntı taraması. +- **Bozuk Girdi Temizleyici:** Uninstall yürütülebilir dosyası veya klasörü diskte artık var olmayan hayalet (ghost) kayıt defteri girdilerini tek tıkla bulup temizleme. +- **Winget Entegrasyonu:** Yüklü uygulamaları yeni bir bilgisayara taşımak için tek tıkla toplu Winget kurulum scripti (`.bat`) üretme. +- **Explorer Sağ Tık Menüsü Entegrasyonu:** `.exe` ve kısayol (`.lnk`) dosyalarına sağ tıklandığında "LD Uninstaller ile Kaldır" seçeneği. +- **90+ Gün Kullanılmayanlar Filtresi:** Bilgisayarda uzun süredir açılmayan veya güncellenmeyen yazılımları filtreleyerek disk alanı kazanımı sağlama. +- **Temizlik Raporu ve Log Görüntüleyici:** Yapılan her işlem için şık HTML raporu üretme ve arayüz içinden `trace.log` dosyasını gerçek zamanlı inceleme. +- **Kayıt Defterinde Doğrudan Aç:** Uygulamanın kayıt defteri anahtarını Regedit içinde tam konumunda açma (`LastKey` desteği). -Projeyi derlemek ve belirlenen kurallara göre tek klasörde paketlemek için PowerShell otomasyonu: +--- + +### 4. ⚡ Ultra Akıcı Performans & Sıfır Takılma +- **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. +- **Squarified Treemap:** Vektörel çizim elemanları, dondurulmuş Direct3D fırçaları ve statik tipografiler ile anında disk boyutu haritalaması. +- **Tekil Örnek (Single-Instance):** `Global\LDUninstaller_SingleInstance_Mutex` ile birden fazla pencerenin aynı anda açılarak çakışması engellenir. + +--- + +### 5. 🧪 Kapsamlı Birim Testleri (Unit Tests) +`tests/LDUninstaller.Tests` altında xUnit test paketi mevcuttur: +- `SafetyBlacklistTests`: Dinamik Windows, Documents, OneDrive ve registry anahtar koruma doğrulamaları. +- `JunkManagerTests`: Token ayrıştırma, stop-words filtresi (`Git` vs `GitHub`) ve sınır kuralları. +- `Sift4Tests`: Hızlı normalize benzerlik algoritması doğrulaması. ```powershell -# Ufak hata düzeltmesi / bugfix (0.0.1 artırır: v2.4.0 -> v2.4.1) -.\release.ps1 -Type patch - -# Orta / yeni özellik güncellemesi (0.1 artırır: v2.4.0 -> v2.5.0) -.\release.ps1 -Type minor - -# Büyük mimari güncelleme (1 artırır: v2.4.0 -> v3.0.0) -.\release.ps1 -Type major +dotnet test ``` -Script, kök dizindeki eski sürümleri temizler, yalnızca en güncel sürüm klasörünü (`LD Uninstaller vX.Y.Z`) oluşturur ve GitHub Releases üzerinde yayınlar. - --- ## 💻 Başlatma ve Kullanım ```powershell # Yönetici yetkili başlatıcı: -.\LD Uninstaller v2.5.0\LDUninstaller.Launcher.exe +.\LDUninstaller.Launcher.exe # veya doğrudan arayüz: -.\LD Uninstaller v2.5.0\LDUninstaller.UI.exe +.\LDUninstaller.UI.exe # SysAdmin ve Otomasyon için CLI aracı: -.\LD Uninstaller v2.5.0\LDUninstaller.CLI.exe list /F=table -.\LD Uninstaller v2.5.0\LDUninstaller.CLI.exe export software_inventory.json /F=json -.\LD Uninstaller v2.5.0\LDUninstaller.CLI.exe debloat --list +.\LDUninstaller.CLI.exe list /F=table +.\LDUninstaller.CLI.exe export software_inventory.json /F=json +.\LDUninstaller.CLI.exe uninstall "AppName" /Q /U /J=VeryGood +.\LDUninstaller.CLI.exe debloat --list ``` --- diff --git a/installer.iss b/installer.iss index 64cd5ca..4afd28b 100644 --- a/installer.iss +++ b/installer.iss @@ -1,14 +1,14 @@ #ifndef MyAppVersion -#define MyAppVersion "2.5.0" +#define MyAppVersion "2.8.0" #endif #ifndef SourceDir -#define SourceDir "LD Uninstaller v2.5.0" +#define SourceDir "LD Uninstaller v2.8.0" #endif #define MyAppName "LD Uninstaller" #define MyAppPublisher "LD Software" -#define MyAppURL "https://github.com/LilDosto/LD-Unistaller" +#define MyAppURL "https://ttmadethat.shop/#ldapps" #define MyAppExeName "LDUninstaller.Launcher.exe" [Setup] @@ -17,6 +17,7 @@ AppName={#MyAppName} AppVersion={#MyAppVersion} AppPublisher={#MyAppPublisher} AppPublisherURL={#MyAppURL} +AppSupportURL={#MyAppURL} AppUpdatesURL={#MyAppURL} DefaultDirName={autopf}\{#MyAppName} DisableProgramGroupPage=yes @@ -29,6 +30,8 @@ SolidCompression=yes WizardStyle=modern PrivilegesRequired=admin ArchitecturesInstallIn64BitMode=x64compatible +CloseApplications=yes +RestartApplications=no UninstallDisplayIcon={app}\{#MyAppExeName} [Languages] @@ -48,3 +51,16 @@ Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: de [Run] Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent + +[Registry] +Root: HKCU; Subkey: "Software\Classes\Directory\shell\LDForceUninstall"; ValueType: string; ValueData: "💥 LD ile Güçlü Kaldır"; Flags: uninsdeletekey +Root: HKCU; Subkey: "Software\Classes\Directory\shell\LDForceUninstall"; ValueType: string; ValueName: "Icon"; ValueData: """{app}\{#MyAppExeName}"",0"; Flags: uninsdeletekey +Root: HKCU; Subkey: "Software\Classes\Directory\shell\LDForceUninstall\command"; ValueType: string; ValueData: """{app}\{#MyAppExeName}"" --force-path ""%1"""; Flags: uninsdeletekey + +Root: HKCU; Subkey: "Software\Classes\exefile\shell\LDForceUninstall"; ValueType: string; ValueData: "💥 LD ile Güçlü Kaldır"; Flags: uninsdeletekey +Root: HKCU; Subkey: "Software\Classes\exefile\shell\LDForceUninstall"; ValueType: string; ValueName: "Icon"; ValueData: """{app}\{#MyAppExeName}"",0"; Flags: uninsdeletekey +Root: HKCU; Subkey: "Software\Classes\exefile\shell\LDForceUninstall\command"; ValueType: string; ValueData: """{app}\{#MyAppExeName}"" --force-path ""%1"""; Flags: uninsdeletekey + +Root: HKCU; Subkey: "Software\Classes\lnkfile\shell\LDForceUninstall"; ValueType: string; ValueData: "💥 LD ile Güçlü Kaldır"; Flags: uninsdeletekey +Root: HKCU; Subkey: "Software\Classes\lnkfile\shell\LDForceUninstall"; ValueType: string; ValueName: "Icon"; ValueData: """{app}\{#MyAppExeName}"",0"; Flags: uninsdeletekey +Root: HKCU; Subkey: "Software\Classes\lnkfile\shell\LDForceUninstall\command"; ValueType: string; ValueData: """{app}\{#MyAppExeName}"" --force-path ""%1"""; Flags: uninsdeletekey diff --git a/release.ps1 b/release.ps1 index 2028aae..25328a2 100644 --- a/release.ps1 +++ b/release.ps1 @@ -1,4 +1,4 @@ -param( +param( [ValidateSet("major", "minor", "patch", "current")] [string]$Type = "current", [string]$Message = "" @@ -12,7 +12,7 @@ $versionFile = Join-Path $root "version.json" $propsFile = Join-Path $root "Directory.Build.props" if (-not (Test-Path $versionFile)) { - @{ major = 2; minor = 5; patch = 0; version = "2.5.0" } | ConvertTo-Json | Set-Content $versionFile + @{ major = 2; minor = 8; patch = 0; version = "2.8.0" } | ConvertTo-Json | Set-Content $versionFile } $vData = Get-Content $versionFile -Raw | ConvertFrom-Json @@ -62,11 +62,12 @@ $propsContent = @" "@ Set-Content -Path $propsFile -Value $propsContent -Encoding UTF8 -Write-Host "==========================================" -ForegroundColor Cyan -Write-Host " LD UNINSTALLER SURUM YAYINLAMA: v$newVersion" -ForegroundColor Yellow -Write-Host "==========================================" -ForegroundColor Cyan +Write-Host "==========================================================" -ForegroundColor Cyan +Write-Host " LD UNINSTALLER WEB YAYIN PAKETLEYICI: v$newVersion" -ForegroundColor Yellow +Write-Host " Hedef Web Adresi: https://ttmadethat.shop/#ldapps" -ForegroundColor Green +Write-Host "==========================================================" -ForegroundColor Cyan -# 1. Ana klasorde eski surumleri temizle +# 1. Eski gecici dosyalari ve onceki paket klasorlerini temizle $oldFolders = Get-ChildItem -Path $root -Directory -Filter "LD Uninstaller v*" foreach ($old in $oldFolders) { Write-Host "Eski surum klasoru temizleniyor: $($old.Name)..." -ForegroundColor Gray @@ -75,9 +76,18 @@ foreach ($old in $oldFolders) { } catch { } } -# Eski kurulum exe ve zip dosyalarini temizle Get-ChildItem -Path $root -File -Filter "LD-Uninstaller-Setup-v*.exe" | Remove-Item -Force -ErrorAction SilentlyContinue Get-ChildItem -Path $root -File -Filter "LD-Uninstaller-v*.zip" | Remove-Item -Force -ErrorAction SilentlyContinue +Get-ChildItem -Path $root -File -Filter "LD-Uninstaller-Portable-*.zip" | Remove-Item -Force -ErrorAction SilentlyContinue + +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 { } + +$webUploadDir = Join-Path $root "web_upload" +if (Test-Path $webUploadDir) { + Remove-Item -Path $webUploadDir -Recurse -Force -ErrorAction SilentlyContinue +} +New-Item -ItemType Directory -Path $webUploadDir -Force | Out-Null $targetFolderName = "LD Uninstaller v$newVersion" $targetDir = Join-Path $root $targetFolderName @@ -86,7 +96,7 @@ Write-Host "Yeni surum klasoru olusturuluyor: $targetFolderName..." -ForegroundC New-Item -ItemType Directory -Path $targetDir -Force | Out-Null # 2. Projeleri Release modunda derle ve yayinla -Write-Host "Projeler derleniyor ve yayinlaniyor..." -ForegroundColor Cyan +Write-Host "`nProjeler Release modunda derleniyor..." -ForegroundColor Cyan $projects = @( "src/LDUninstaller.UI/LDUninstaller.UI.csproj", @@ -99,214 +109,138 @@ foreach ($proj in $projects) { $projPath = Join-Path $root $proj Write-Host " -> Yayinlaniyor: $proj" -ForegroundColor Gray dotnet publish $projPath -c Release -o $targetDir --nologo -v q + if ($LASTEXITCODE -ne 0) { + throw "Proje derlenemedi veya yayinlanamadi: $proj (ExitCode: $LASTEXITCODE)" + } } -# 3. Gereksiz pdb ve log dosyalarini temizle +# Gereksiz pdb dosyalarini temizle Get-ChildItem -Path $targetDir -Filter "*.pdb" | Remove-Item -Force -ErrorAction SilentlyContinue - -# 4. Eski publish ve dist klasorlerini 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. Windows Kurulum Sihirbazi (Setup.exe) ve ZIP Arsivini Olustur Copy-Item (Join-Path $root "app.ico") (Join-Path $targetDir "app.ico") -Force -# Inno Setup ile Setup.exe derle +# 3. Inno Setup ile Setup.exe derle +$cmdIscc = Get-Command iscc.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source $isccCandidates = @( + $cmdIscc, "C:\Users\lildosto\AppData\Local\Programs\Inno Setup 6\ISCC.exe", "C:\Program Files (x86)\Inno Setup 6\ISCC.exe", "C:\Program Files\Inno Setup 6\ISCC.exe" ) $isccPath = $null foreach ($cand in $isccCandidates) { - if (Test-Path $cand) { $isccPath = $cand; break } + if ($cand -and (Test-Path $cand)) { $isccPath = $cand; break } } $setupName = "LD-Uninstaller-Setup-v$newVersion.exe" $setupPath = Join-Path $root $setupName if ($isccPath -and (Test-Path (Join-Path $root "installer.iss"))) { - Write-Host "Windows Kurulum Sihirbazi derleniyor: $setupName..." -ForegroundColor Cyan + Write-Host "`nWindows Kurulum Sihirbazi (Setup.exe) derleniyor..." -ForegroundColor Cyan & $isccPath /Q "/DMyAppVersion=$newVersion" "/DSourceDir=$targetDir" (Join-Path $root "installer.iss") - if (Test-Path $setupPath) { - Write-Host "Kurulum dosyasi basariyla olusturuldu: $setupName" -ForegroundColor Green + if ($LASTEXITCODE -ne 0) { + throw "Inno Setup derleme hatasi! (ExitCode: $LASTEXITCODE)" } +} else { + Write-Host "UYARI: Inno Setup derleyicisi (ISCC.exe) bulunamadi." -ForegroundColor Yellow } -# Portable ZIP arsivi -$zipName = "LD-Uninstaller-v$newVersion.zip" -$zipPath = Join-Path $root $zipName -Write-Host "Surum zip arsivi olusturuluyor: $zipName..." -ForegroundColor Cyan -Compress-Archive -Path "$targetDir\*" -DestinationPath $zipPath -Force +# 4. Web Yayin Klasorune (web_upload) Dosyalari Hazirla +Write-Host "`nWeb yayin dosyalari 'web_upload/' klasorune kopyalaniyor..." -ForegroundColor Cyan -# 6. Git Islemleri ve GitHub Push -if (Test-Path (Join-Path $root ".git")) { - Write-Host "`nGit degisiklikleri isleniyor ve GitHub'a aktariliyor..." -ForegroundColor Cyan - try { - if ([string]::IsNullOrWhiteSpace($Message)) { - $Message = "Release v${newVersion}: Standart Windows Kurulum Sihirbazi ve Otomasyon" - } - git add . - git commit -m $Message - git tag -a "v$newVersion" -m "LD Uninstaller v$newVersion - $Message" -f - - $remote = git remote get-url origin 2>$null - if ($remote) { - Write-Host "GitHub'a gonderiliyor (origin master --tags)..." -ForegroundColor Yellow - git push origin master --tags -u -f - } - } catch { - Write-Host "Git islemi uyarisi: $_" -ForegroundColor Yellow - } +# 4.1 Setup.exe kopyala +$webSetupPath = Join-Path $webUploadDir $setupName +$webSetupLatestPath = Join-Path $webUploadDir "LD-Uninstaller-Setup-latest.exe" + +if (Test-Path $setupPath) { + Copy-Item $setupPath $webSetupPath -Force + Copy-Item $setupPath $webSetupLatestPath -Force + Write-Host " [+] $setupName eklendi" -ForegroundColor Green + Write-Host " [+] LD-Uninstaller-Setup-latest.exe eklendi" -ForegroundColor Green } -# 7. GitHub Releases API Uzerinde Surum ve Notlari Yayinla -try { - Write-Host "`nGitHub Releases API uzerinden surum ve notlar yayinlaniyor..." -ForegroundColor Cyan +# 4.2 Portable ZIP olustur +$zipName = "LD-Uninstaller-Portable-v$newVersion.zip" +$webZipPath = Join-Path $webUploadDir $zipName +$webZipLatestPath = Join-Path $webUploadDir "LD-Uninstaller-Portable-latest.zip" - $code = @" -using System; -using System.Runtime.InteropServices; -using System.Text; +Write-Host " [+] Portable ZIP arsivi olusturuluyor: $zipName..." -ForegroundColor Cyan +Compress-Archive -Path "$targetDir\*" -DestinationPath $webZipPath -Force +Copy-Item $webZipPath $webZipLatestPath -Force +Write-Host " [+] $zipName eklendi" -ForegroundColor Green +Write-Host " [+] LD-Uninstaller-Portable-latest.zip eklendi" -ForegroundColor Green -public class GitCredsEngine2 -{ - [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - public static extern bool CredRead(string target, int type, int reservedFlag, out IntPtr credentialPtr); - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct CREDENTIAL - { - public int Flags; - public int Type; - public string TargetName; - public string Comment; - public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten; - public int CredentialBlobSize; - public IntPtr CredentialBlob; - public int Persist; - public int AttributeCount; - public IntPtr Attributes; - public string TargetAlias; - public string UserName; - } - - public static string GetToken() - { - IntPtr credPtr; - if (CredRead("git:https://github.com", 1, 0, out credPtr)) - { - var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL)); - byte[] bytes = new byte[cred.CredentialBlobSize]; - Marshal.Copy(cred.CredentialBlob, bytes, 0, cred.CredentialBlobSize); - return Encoding.Unicode.GetString(bytes).Trim('\0', ' ', '\r', '\n'); - } - return null; - } +# 4.3 SHA256 Hash'lerini hesapla +$setupHash = "" +$setupSize = 0 +if (Test-Path $webSetupPath) { + $setupHash = (Get-FileHash -Path $webSetupPath -Algorithm SHA256).Hash + $setupSize = (Get-Item $webSetupPath).Length } + +$zipHash = "" +$zipSize = 0 +if (Test-Path $webZipPath) { + $zipHash = (Get-FileHash -Path $webZipPath -Algorithm SHA256).Hash + $zipSize = (Get-Item $webZipPath).Length +} + +# 4.4 Web icin version.json olustur +$notesText = if (![string]::IsNullOrWhiteSpace($Message)) { + $Message +} else { + "v${newVersion}: Gelismis veri koruma kalkani, Geri Donusum Kutusu entegrasyonu, Yedekleme ve Koruma Merkezi, Zorla Kaldir modu, Winget script uretici ve yuksek hizli 20 katmanli kalinti tarama motoru." +} + +$webVersionData = [ordered]@{ + version = $newVersion + downloadUrl = "https://ttmadethat.shop/downloads/$setupName" + latestUrl = "https://ttmadethat.shop/downloads/LD-Uninstaller-Setup-latest.exe" + portableUrl = "https://ttmadethat.shop/downloads/$zipName" + homepageUrl = "https://ttmadethat.shop/#ldapps" + releaseDate = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss") + releaseNotes = $notesText + sha256 = $setupHash + portableSha256 = $zipHash + setupSizeBytes = $setupSize + portableSizeBytes = $zipSize +} + +$webVersionJsonPath = Join-Path $webUploadDir "version.json" +$webVersionData | ConvertTo-Json -Depth 5 | Set-Content -Path $webVersionJsonPath -Encoding UTF8 +Write-Host " [+] version.json (Web API/Update Denetleyicisi) olusturuldu" -ForegroundColor Green + +# 4.5 sha256.txt olustur +$shaContent = @" +================================================================================ +LD Uninstaller v$newVersion - Dosya Doğrulama ve SHA256 Bilgileri +Yayın Tarihi: $((Get-Date).ToString("yyyy-MM-dd HH:mm:ss")) +Resmi Web: https://ttmadethat.shop/#ldapps +================================================================================ + +1. Kurulum Sihirbazı (Setup): + Dosya: $setupName + Boyut: $([math]::Round($setupSize / 1MB, 2)) MB ($setupSize bytes) + SHA256: $setupHash + +2. Kurulumsuz Sürüm (Portable ZIP): + Dosya: $zipName + Boyut: $([math]::Round($zipSize / 1MB, 2)) MB ($zipSize bytes) + SHA256: $zipHash + +================================================================================ +Doğrulama Komutu (PowerShell): +Get-FileHash -Algorithm SHA256 .\$setupName "@ - if (-not ([System.Management.Automation.PSTypeName]'GitCredsEngine2').Type) { - Add-Type -TypeDefinition $code -Language CSharp - } - - $token = [GitCredsEngine2]::GetToken() - if ($env:GITHUB_TOKEN) { $token = $env:GITHUB_TOKEN } - if ($env:GH_TOKEN) { $token = $env:GH_TOKEN } - if (-not $token) { - Write-Host "Uyari: GitHub kimlik belirteci bulunamadi. Release API atlaniyor." -ForegroundColor Yellow - } else { - $apiHeaders = @{ - "Authorization" = "Bearer $token" - "User-Agent" = "LDUninstaller-ReleaseScript" - "Accept" = "application/vnd.github+json" - } +$shaFilePath = Join-Path $webUploadDir "sha256.txt" +[System.IO.File]::WriteAllText($shaFilePath, $shaContent, [System.Text.Encoding]::UTF8) +Write-Host " [+] sha256.txt (Dogrulama Metni) olusturuldu" -ForegroundColor Green - $repoOwner = "LilDosto" - $repoName = "LD-Unistaller" +# 5. Ozet Bilgisi +Write-Host "`n==========================================================" -ForegroundColor Green +Write-Host " YAYIN DOSYALARI HAZIR! (web_upload/)" -ForegroundColor Yellow +Write-Host "==========================================================" -ForegroundColor Green +Write-Host "Sunucuya (ttmadethat.shop) yuklenecek klasor:" -ForegroundColor Cyan +Write-Host " -> $webUploadDir`n" -ForegroundColor White - # Changelog / Surum Notlari (Sablon dosyasindan UTF-8 olarak okunur) - $templatePath = Join-Path $root "release_notes_template.md" - $releaseNotes = "" - if (Test-Path $templatePath) { - $releaseNotes = [System.IO.File]::ReadAllText($templatePath, [System.Text.Encoding]::UTF8) - $releaseNotes = $releaseNotes.Replace("{VERSION}", $newVersion) - } else { - $releaseNotes = "LD Uninstaller v$newVersion guncellemesi." - } - - $releaseTitle = if (![string]::IsNullOrWhiteSpace($Message)) { $Message } else { "LDUninstaller-v$newVersion - Setup" } - - $releasePayload = @{ - tag_name = "v$newVersion" - name = $releaseTitle - body = $releaseNotes - draft = $false - prerelease = $false - } | ConvertTo-Json -Depth 5 - - $jsonBytes = [System.Text.Encoding]::UTF8.GetBytes($releasePayload) - - $releaseUrl = "https://api.github.com/repos/$repoOwner/$repoName/releases/tags/v$newVersion" - $ghRelease = $null - try { - $ghRelease = Invoke-RestMethod -Uri $releaseUrl -Headers $apiHeaders -Method Get -ErrorAction Stop - } catch { } - - if ($ghRelease) { - Write-Host "Mevcut release guncelleniyor (ID: $($ghRelease.id))..." -ForegroundColor Yellow - $patchUrl = "https://api.github.com/repos/$repoOwner/$repoName/releases/$($ghRelease.id)" - $ghRelease = Invoke-RestMethod -Uri $patchUrl -Headers $apiHeaders -Method Patch -Body $jsonBytes -ContentType "application/json; charset=utf-8" - } else { - Write-Host "Yeni release olusturuluyor..." -ForegroundColor Green - $postUrl = "https://api.github.com/repos/$repoOwner/$repoName/releases" - $ghRelease = Invoke-RestMethod -Uri $postUrl -Headers $apiHeaders -Method Post -Body $jsonBytes -ContentType "application/json; charset=utf-8" - } - - # Dosyalari release asset olarak yukle (Setup.exe ve zip) - $filesToUpload = @($setupPath, $zipPath) | Where-Object { Test-Path $_ } - foreach ($fPath in $filesToUpload) { - $fName = Split-Path $fPath -Leaf - Write-Host "Release varligi yukleniyor: $fName..." -ForegroundColor Cyan - - if ($ghRelease.assets) { - foreach ($asset in $ghRelease.assets) { - if ($asset.name -eq $fName) { - try { - Invoke-RestMethod -Uri "https://api.github.com/repos/$repoOwner/$repoName/releases/assets/$($asset.id)" -Headers $apiHeaders -Method Delete | Out-Null - } catch { } - } - } - } - - $uploadUri = $ghRelease.upload_url -replace '\{\?name,label\}', "?name=$fName" - $contentType = if ($fName.EndsWith(".exe")) { "application/vnd.microsoft.portable-executable" } else { "application/zip" } - $uploadHeaders = @{ - "Authorization" = "Bearer $token" - "User-Agent" = "LDUninstaller-ReleaseScript" - "Accept" = "application/vnd.github+json" - } - $fileBytes = [System.IO.File]::ReadAllBytes($fPath) - $uploadResult = Invoke-RestMethod -Uri $uploadUri -Headers $uploadHeaders -Method Post -Body $fileBytes -ContentType $contentType - Write-Host "Yuklendi: $($uploadResult.browser_download_url)" -ForegroundColor Green - } - - Write-Host "`nGitHub Release yayinda:" -ForegroundColor Yellow - Write-Host " -> https://github.com/$repoOwner/$repoName/releases/tag/v$newVersion" -ForegroundColor White - } -} catch { - Write-Host "GitHub Releases API islemi uyarisi: $_" -ForegroundColor Yellow -} - -Write-Host "`n[+] Basariyla Tamamlandi!" -ForegroundColor Green -Write-Host "Ana dizinde olusturulan son guncel surum klasoru:" -ForegroundColor Yellow -Write-Host " -> $targetFolderName" -ForegroundColor White -Write-Host "Standart Kurulum Paketi (Setup.exe):" -ForegroundColor Cyan -Write-Host " -> $setupName" -ForegroundColor White -Write-Host "GitHub Release hazir paketi:" -ForegroundColor White -Write-Host " -> $zipName" -ForegroundColor Cyan -Write-Host "Kullanima hazir yurutulebilir dosyalar:" -ForegroundColor Gray -Write-Host " - LDUninstaller.Launcher.exe (Yonetici yetkili baslatici)" -Write-Host " - LDUninstaller.UI.exe (Modern Fluent Arayuz)" -Write-Host " - LDUninstaller.CLI.exe (Konsol araci)" -Write-Host " - LDUninstaller.Automatizer.exe (Otomasyon ajani)`n" +Get-ChildItem -Path $webUploadDir | Format-Table Name, Length, LastWriteTime diff --git a/src/LDUninstaller.Automatizer/Program.cs b/src/LDUninstaller.Automatizer/Program.cs index 7e56fc7..a58ae0a 100644 --- a/src/LDUninstaller.Automatizer/Program.cs +++ b/src/LDUninstaller.Automatizer/Program.cs @@ -1,9 +1,12 @@ 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.Management; +using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using FlaUI.Core.AutomationElements; @@ -35,6 +38,9 @@ namespace LDUninstaller.Automatizer "anket", "survey", "homepage", "launch", "çalıştır" }; + private static DateTime _lastActivity = DateTime.Now; + private static bool _exitRequested = false; + [STAThread] static void Main(string[] args) { @@ -56,11 +62,26 @@ namespace LDUninstaller.Automatizer using var automation = new UIA3Automation(); Console.WriteLine("Daemon aktif. Named Pipe '\\\\.\\pipe\\LDUninstallerDaemon' dinleniyor..."); - while (true) + while (!_exitRequested) { try { - foreach (var kvp in MonitoredProcesses.ToArray()) + var pids = MonitoredProcesses.ToArray(); + if (pids.Length > 0) + { + _lastActivity = DateTime.Now; + } + else + { + // P12: If idle for 2 minutes and no active tasks, exit to free RAM + if ((DateTime.Now - _lastActivity).TotalMinutes > 2) + { + Console.WriteLine("[Daemon] Boşta kalma süresi aşıldı, otomatik sonlandırılıyor."); + break; + } + } + + foreach (var kvp in pids) { int pid = kvp.Key; DateTime startTime = kvp.Value; @@ -89,8 +110,24 @@ namespace LDUninstaller.Automatizer continue; } - // Automate UI windows for this PID - AutomateProcessWindows(automation, proc); + // Automate UI windows for this PID and its children (B19) + var allPids = new List { proc.Id }; + try + { + allPids.AddRange(GetChildProcessIds(proc.Id)); + } + catch { } + + foreach (int targetPid in allPids) + { + try + { + var targetProc = Process.GetProcessById(targetPid); + if (!targetProc.HasExited) + AutomateProcessWindows(automation, targetProc); + } + catch { } + } } catch (ArgumentException) { @@ -108,9 +145,25 @@ namespace LDUninstaller.Automatizer } } + private static List GetChildProcessIds(int parentId) + { + var results = new List(); + try + { + using var searcher = new ManagementObjectSearcher( + $"SELECT ProcessId FROM Win32_Process WHERE ParentProcessId={parentId}"); + foreach (var mo in searcher.Get()) + { + results.Add(Convert.ToInt32(mo["ProcessId"])); + } + } + catch { } + return results; + } + private static void StartPipeServer(CancellationToken token) { - while (!token.IsCancellationRequested) + while (!token.IsCancellationRequested && !_exitRequested) { try { @@ -119,13 +172,22 @@ namespace LDUninstaller.Automatizer using var reader = new StreamReader(server); string? line = reader.ReadLine(); - if (!string.IsNullOrWhiteSpace(line) && line.StartsWith("ATTACH:", StringComparison.OrdinalIgnoreCase)) + if (!string.IsNullOrWhiteSpace(line)) { - string pidStr = line["ATTACH:".Length..].Trim(); - if (int.TryParse(pidStr, out int pid)) + if (line.StartsWith("ATTACH:", StringComparison.OrdinalIgnoreCase)) { - Console.WriteLine($"[IPC] Takip edilecek PID alındı: {pid}"); - MonitoredProcesses.TryAdd(pid, DateTime.Now); + 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); + _lastActivity = DateTime.Now; + } + } + else if (line.Equals("SHUTDOWN", StringComparison.OrdinalIgnoreCase)) + { + _exitRequested = true; + break; } } } @@ -202,12 +264,12 @@ namespace LDUninstaller.Automatizer } } - // Check standard buttons + // Check standard buttons (B19: strict word/exact match) var buttons = win.FindAllDescendants(cf => cf.ByControlType(ControlType.Button)); foreach (var btn in buttons) { string btnId = btn.AutomationId ?? ""; - string btnText = btn.Name?.Trim().ToLowerInvariant() ?? ""; + string btnText = btn.Name?.Trim() ?? ""; // Prioritize NSIS standard Next button ID 1 or Close/Finish if (btnId == "1" || IsGoodButton(btnText)) @@ -229,13 +291,25 @@ namespace LDUninstaller.Automatizer 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)); + string clean = text.Trim().ToLowerInvariant(); + + foreach (var g in GoodButtonTexts) + { + if (clean.Equals(g, StringComparison.OrdinalIgnoreCase)) + return true; + + // Word boundary check for short words to avoid "book", "look", "token", etc. + if (Regex.IsMatch(clean, $@"\b{Regex.Escape(g)}\b", RegexOptions.IgnoreCase)) + return true; + } + return false; } private static bool IsBadButton(string text) { if (string.IsNullOrWhiteSpace(text)) return false; - return BadButtonTexts.Any(b => text.Contains(b, StringComparison.OrdinalIgnoreCase)); + string clean = text.Trim().ToLowerInvariant(); + return BadButtonTexts.Any(b => clean.Contains(b, StringComparison.OrdinalIgnoreCase)); } } } diff --git a/src/LDUninstaller.CLI/LDUninstaller.CLI.csproj b/src/LDUninstaller.CLI/LDUninstaller.CLI.csproj index 0dc3ba2..281d82c 100644 --- a/src/LDUninstaller.CLI/LDUninstaller.CLI.csproj +++ b/src/LDUninstaller.CLI/LDUninstaller.CLI.csproj @@ -7,6 +7,7 @@ enable LDUninstaller.CLI LDUninstaller.CLI + app.manifest diff --git a/src/LDUninstaller.CLI/Program.cs b/src/LDUninstaller.CLI/Program.cs index 2c34a4e..bd32b27 100644 --- a/src/LDUninstaller.CLI/Program.cs +++ b/src/LDUninstaller.CLI/Program.cs @@ -248,13 +248,26 @@ Parametreler: 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) + if (Console.IsInputRedirected) { - Console.WriteLine("İşlem iptal edildi."); - return 0; + Console.Write("\nDevam etmek istiyor musunuz? [E/H]: "); + string? line = Console.ReadLine()?.Trim(); + if (string.IsNullOrEmpty(line) || (!line.StartsWith("e", StringComparison.OrdinalIgnoreCase) && !line.StartsWith("y", StringComparison.OrdinalIgnoreCase))) + { + Console.WriteLine("İşlem iptal edildi."); + return 0; + } + } + else + { + 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; + } } } @@ -262,12 +275,17 @@ Parametreler: 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)) + var uninstalledApps = bulkTask.Items + .Where(i => i.IsEffectivelyUninstalled) + .Select(i => i.Entry) + .ToList(); + + // Automatic Junk Clean (only for effectively uninstalled apps) + if (uninstalledApps.Count > 0 && !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) + foreach (var a in uninstalledApps) { var junks = junkManager.ScanJunk(a); var cleanable = junks.Where(j => j.Confidence >= minConfidence).ToList(); diff --git a/src/LDUninstaller.CLI/app.manifest b/src/LDUninstaller.CLI/app.manifest new file mode 100644 index 0000000..0d1d1d1 --- /dev/null +++ b/src/LDUninstaller.CLI/app.manifest @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/LDUninstaller.Core/Algorithms/Sift4.cs b/src/LDUninstaller.Core/Algorithms/Sift4.cs index 2b9fb2d..4060f4f 100644 --- a/src/LDUninstaller.Core/Algorithms/Sift4.cs +++ b/src/LDUninstaller.Core/Algorithms/Sift4.cs @@ -71,6 +71,17 @@ namespace LDUninstaller.Core.Algorithms string clean1 = NormalizeName(s1); string clean2 = NormalizeName(s2); + return GetSimilarityNormalized(clean1, clean2, maxOffset); + } + + /// + /// OPTIMIZATION (P2): Önceden normalize edilmiş metinler için regex çağrılarını atlayan ultra hızlı benzerlik fonksiyonu. + /// + public static double GetSimilarityNormalized(string clean1, string clean2, int maxOffset = 5) + { + if (string.IsNullOrEmpty(clean1) && string.IsNullOrEmpty(clean2)) return 1.0; + if (string.IsNullOrEmpty(clean1) || string.IsNullOrEmpty(clean2)) return 0.0; + if (clean1.Equals(clean2, StringComparison.OrdinalIgnoreCase)) return 1.0; diff --git a/src/LDUninstaller.Core/Bulk/BulkUninstallTask.cs b/src/LDUninstaller.Core/Bulk/BulkUninstallTask.cs index 8c3244e..03ce13e 100644 --- a/src/LDUninstaller.Core/Bulk/BulkUninstallTask.cs +++ b/src/LDUninstaller.Core/Bulk/BulkUninstallTask.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.ComponentModel; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; +using System.Runtime.CompilerServices; using System.ServiceProcess; using System.Threading; using System.Threading.Tasks; @@ -24,19 +26,61 @@ namespace LDUninstaller.Core.Bulk Cancelled } - public class BulkUninstallEntry + public class BulkUninstallEntry : INotifyPropertyChanged { public ApplicationUninstallerEntry Entry { get; } - public BulkStatus Status { get; set; } = BulkStatus.Queued; - public string StatusMessage { get; set; } = "Kuyrukta"; + + private BulkStatus _status = BulkStatus.Queued; + public BulkStatus Status + { + get => _status; + set + { + if (_status != value) + { + _status = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(StatusBadgeColor)); + } + } + } + + private string _statusMessage = "Kuyrukta"; + public string StatusMessage + { + get => _statusMessage; + set + { + if (_statusMessage != value) + { + _statusMessage = value; + OnPropertyChanged(); + } + } + } + public bool PreferQuiet { get; set; } = true; public int ExitCode { get; set; } = -1; + public bool IsEffectivelyUninstalled { get; set; } + + public string StatusBadgeColor => Status switch + { + BulkStatus.Succeeded => "#10B981", + BulkStatus.Failed => "#EF4444", + BulkStatus.Running => "#3B82F6", + BulkStatus.Cancelled => "#F59E0B", + _ => "#6B7280" + }; public BulkUninstallEntry(ApplicationUninstallerEntry entry, bool preferQuiet = true) { Entry = entry; PreferQuiet = preferQuiet; } + + public event PropertyChangedEventHandler? PropertyChanged; + protected void OnPropertyChanged([CallerMemberName] string? name = null) => + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } public class BulkUninstallTask @@ -63,57 +107,77 @@ namespace LDUninstaller.Core.Bulk public async Task ExecuteAsync(CancellationToken cancellationToken = default) { + long restoreSeq = 0; if (CreateRestorePoint) { OnLog?.Invoke("Sistem Geri Yükleme Noktası oluşturuluyor..."); - await Task.Run(() => Win32.CreateRestorePoint("LD Uninstaller Bulk Pre-Restore Point", out _)); + await Task.Run(() => Win32.CreateRestorePoint("LD Uninstaller Bulk Pre-Restore Point", out restoreSeq)); + } + + if (EnableAutomatizer) + { + EnsureAutomatizerRunning(); } var throttler = new SemaphoreSlim(MaxConcurrentQuiet, MaxConcurrentQuiet); var runningTasks = new List(); - foreach (var item in Items) + try { - if (cancellationToken.IsCancellationRequested) + foreach (var item in Items) { - 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 () => + if (cancellationToken.IsCancellationRequested) { - try - { - await RunSingleItemAsync(item, cancellationToken); - } - finally - { - throttler.Release(); - } - }, cancellationToken); + item.Status = BulkStatus.Cancelled; + item.StatusMessage = "İptal edildi"; + continue; + } - runningTasks.Add(t); + bool isSerialized = IsSerializedType(item.Entry.UninstallerKind); + + if (isSerialized) + { + 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ı."); + await Task.WhenAll(runningTasks); + } + finally + { + if (restoreSeq > 0) + { + Win32.EndRestorePoint(restoreSeq); + } + + if (EnableAutomatizer) + { + StopAutomatizerDaemon(); + } + + OnLog?.Invoke("Tüm toplu kaldırma işlemleri tamamlandı."); + } } private async Task RunSingleItemAsync(BulkUninstallEntry item, CancellationToken cancellationToken) @@ -125,12 +189,9 @@ namespace LDUninstaller.Core.Bulk 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; @@ -159,7 +220,6 @@ namespace LDUninstaller.Core.Bulk } } - // 3. MSI Lock bool msiLocked = false; if (item.Entry.UninstallerKind == UninstallerType.Msiexec) { @@ -168,7 +228,6 @@ namespace LDUninstaller.Core.Bulk 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) @@ -184,27 +243,42 @@ namespace LDUninstaller.Core.Bulk OnItemStarted?.Invoke(item); OnLog?.Invoke($"Kaldırma başladı: {item.Entry.DisplayName}"); - // Pre-kill locking processes in install folder + // Pre-kill locking processes in install folder (B9, P9) PreKillLockingProcesses(item.Entry); - // Stop services in install folder + // Stop services in install folder (B9) 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 + // B18: Valid exit codes for success: 0, 1605 (already uninstalled), 1641, 3010 + bool exitCodeSuccess = exitCode == 0 || exitCode == 1605 || exitCode == 1641 || exitCode == 3010; + + // B3: Verify whether it is effectively uninstalled + bool isTargetGone = IsTargetEffectivelyRemoved(item.Entry); + + if (exitCodeSuccess || isTargetGone) { + item.IsEffectivelyUninstalled = true; item.Status = BulkStatus.Succeeded; - item.StatusMessage = exitCode == 3010 ? "Başarılı (Yeniden başlatma gerekli)" : "Başarıyla kaldırıldı"; + item.StatusMessage = (exitCode == 3010 || exitCode == 1641) + ? "Başarılı (Yeniden başlatma gerekli)" + : "Başarıyla kaldırıldı"; } else { + item.IsEffectivelyUninstalled = false; item.Status = BulkStatus.Failed; item.StatusMessage = $"Hata (Çıkış kodu: {exitCode})"; } } + catch (OperationCanceledException) + { + item.Status = BulkStatus.Cancelled; + item.StatusMessage = "İptal edildi"; + } catch (Exception ex) { item.Status = BulkStatus.Failed; @@ -226,6 +300,28 @@ namespace LDUninstaller.Core.Bulk } } + private static bool IsTargetEffectivelyRemoved(ApplicationUninstallerEntry entry) + { + // If install directory was populated and is now gone: + if (!string.IsNullOrWhiteSpace(entry.InstallLocation) && !Directory.Exists(entry.InstallLocation)) + return true; + + // If registry key existed and is now gone: + if (!string.IsNullOrWhiteSpace(entry.RegistryPath)) + { + try + { + var (hive, subKey, view) = RegistryJunkResult.ParseRegistryPath(entry.RegistryPath); + using var baseKey = Microsoft.Win32.RegistryKey.OpenBaseKey(hive, view); + using var key = baseKey.OpenSubKey(subKey); + if (key == null) return true; + } + catch { } + } + + return false; + } + private async Task ExecuteUninstallerProcessAsync(BulkUninstallEntry item, CancellationToken token) { string command = item.PreferQuiet && !string.IsNullOrWhiteSpace(item.Entry.QuietUninstallString) @@ -234,15 +330,34 @@ namespace LDUninstaller.Core.Bulk if (string.IsNullOrWhiteSpace(command)) { - // Simple delete fallback for orphaned software - if (item.Entry.IsOrphaned && Directory.Exists(item.Entry.InstallLocation)) + // Simple delete fallback for orphaned software (only if specifically marked orphaned) + if (item.Entry.IsOrphaned && Directory.Exists(item.Entry.InstallLocation) && !Junk.SafetyBlacklist.IsDangerousDirectory(item.Entry.InstallLocation)) { - Directory.Delete(item.Entry.InstallLocation, true); - return 0; + try + { + Win32.SendToRecycleBin(item.Entry.InstallLocation); + return 0; + } + catch { return -1; } } return -1; } + // B18: Protocol commands like steam:// + if (command.StartsWith("steam://", StringComparison.OrdinalIgnoreCase)) + { + try + { + Process.Start(new ProcessStartInfo(command) { UseShellExecute = true }); + await Task.Delay(4000, token); + return 0; + } + catch + { + return -1; + } + } + var (fileName, args) = SplitCommand(command); var psi = new ProcessStartInfo @@ -258,16 +373,139 @@ namespace LDUninstaller.Core.Bulk psi.WorkingDirectory = item.Entry.InstallLocation; } - using var process = Process.Start(psi); - if (process == null) return -1; - - if (EnableAutomatizer) + Process? process = null; + try { - NotifyAutomatizerDaemon(process.Id); + process = Process.Start(psi); + } + catch (Exception ex) + { + OnLog?.Invoke($"Çalıştırma hatası ({fileName}): {ex.Message}"); + return -1; } - await process.WaitForExitAsync(token); - return process.ExitCode; + if (process == null) return -1; + + using (process) + { + if (EnableAutomatizer) + { + NotifyAutomatizerDaemon(process.Id); + } + + var sw = Stopwatch.StartNew(); + + // Wait for main process + try + { + await process.WaitForExitAsync(token); + } + catch (OperationCanceledException) + { + try { Win32.GentleKillProcess(process, 1500); } catch { } + throw; + } + + int exitCode = process.ExitCode; + + // B4: Watch for child / temp uninstaller processes (Inno Setup / NSIS) + if (sw.ElapsedMilliseconds < 4000 && (exitCode == 0 || exitCode == 3010)) + { + await WaitForPotentialChildUninstallers(item.Entry, token); + } + + return exitCode; + } + } + + private static async Task WaitForPotentialChildUninstallers(ApplicationUninstallerEntry entry, CancellationToken token) + { + string tempDir = Path.GetTempPath(); + + for (int i = 0; i < 30; i++) + { + if (token.IsCancellationRequested) break; + + bool childActive = false; + try + { + // Inno Setup spawns _iu*.tmp processes + // NSIS spawns Au_.exe processes + var procs = Process.GetProcesses(); + foreach (var p in procs) + { + using (p) + { + try + { + string name = p.ProcessName.ToLowerInvariant(); + if (name.StartsWith("_iu") || name.Equals("au_") || name.Contains("uninstall")) + { + string? path = Win32.GetProcessPath(p.Id); + if (!string.IsNullOrEmpty(path) && path.StartsWith(tempDir, StringComparison.OrdinalIgnoreCase)) + { + childActive = true; + break; + } + } + } + catch { } + } + } + } + catch { } + + if (!childActive) + { + if (i >= 2) break; // If no child after a couple seconds, assume finished + } + + await Task.Delay(1000, token); + } + } + + private static void EnsureAutomatizerRunning() + { + _ = Task.Run(() => + { + try + { + var existing = Process.GetProcessesByName("LDUninstaller.Automatizer"); + if (existing.Length > 0) + { + foreach (var p in existing) p.Dispose(); + return; + } + + string baseDir = AppDomain.CurrentDomain.BaseDirectory; + string autoExe = Path.Combine(baseDir, "LDUninstaller.Automatizer.exe"); + if (File.Exists(autoExe)) + { + Process.Start(new ProcessStartInfo(autoExe, "--daemon") + { + UseShellExecute = false, + CreateNoWindow = true + }); + } + } + catch { } + }); + } + + private static void StopAutomatizerDaemon() + { + _ = Task.Run(() => + { + try + { + using var client = new NamedPipeClientStream(".", "LDUninstallerDaemon", PipeDirection.Out); + client.Connect(500); + using var writer = new StreamWriter(client); + writer.WriteLine("SHUTDOWN"); + writer.Flush(); + } + catch { } + }); } private static void NotifyAutomatizerDaemon(int pid) @@ -293,9 +531,11 @@ namespace LDUninstaller.Core.Bulk try { - string norm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\'); + // B9: Add trailing directory separator so C:\Foo doesn't kill C:\FooBar + string norm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar; int currentPid = Process.GetCurrentProcess().Id; var procs = Process.GetProcesses(); + foreach (var p in procs) { using (p) @@ -303,10 +543,12 @@ namespace LDUninstaller.Core.Bulk try { if (p.Id == currentPid) continue; - string? mainModule = p.MainModule?.FileName; - if (!string.IsNullOrWhiteSpace(mainModule)) + + // P9: Use Win32 QueryFullProcessImageName to avoid Access Denied Win32Exceptions + string? exePath = Win32.GetProcessPath(p.Id); + if (!string.IsNullOrWhiteSpace(exePath)) { - if (Path.GetFullPath(mainModule).StartsWith(norm, StringComparison.OrdinalIgnoreCase)) + if (Path.GetFullPath(exePath).StartsWith(norm, StringComparison.OrdinalIgnoreCase)) { Win32.GentleKillProcess(p, 2000); } @@ -326,8 +568,10 @@ namespace LDUninstaller.Core.Bulk try { - string norm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\'); + // B9: Add trailing separator and parse clean ImagePath + string norm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar; var services = ServiceController.GetServices(); + foreach (var sc in services) { using (sc) @@ -335,13 +579,22 @@ namespace LDUninstaller.Core.Bulk 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)) + string? rawPath = key?.GetValue("ImagePath")?.ToString(); + if (!string.IsNullOrWhiteSpace(rawPath)) { - if (sc.Status == ServiceControllerStatus.Running) + string cleanPath = rawPath.Replace("\"", "").Trim(); + if (cleanPath.StartsWith(@"\??\")) cleanPath = cleanPath.Substring(4); + + int exeIdx = cleanPath.IndexOf(".exe", StringComparison.OrdinalIgnoreCase); + if (exeIdx > 0) cleanPath = cleanPath.Substring(0, exeIdx + 4).Trim(); + + if (cleanPath.StartsWith(norm, StringComparison.OrdinalIgnoreCase)) { - sc.Stop(); - sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3)); + if (sc.Status == ServiceControllerStatus.Running) + { + sc.Stop(); + sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3)); + } } } } @@ -354,7 +607,9 @@ namespace LDUninstaller.Core.Bulk private static async Task WaitForActiveMsiProcesses(CancellationToken token) { - while (!token.IsCancellationRequested) + // B15: Timeout after 60 seconds + var sw = Stopwatch.StartNew(); + while (!token.IsCancellationRequested && sw.ElapsedMilliseconds < 60000) { var msiProcs = Process.GetProcessesByName("msiexec"); int count = msiProcs.Length; diff --git a/src/LDUninstaller.Core/Discovery/DirectoryFactory.cs b/src/LDUninstaller.Core/Discovery/DirectoryFactory.cs index c4d6ed1..22a0050 100644 --- a/src/LDUninstaller.Core/Discovery/DirectoryFactory.cs +++ b/src/LDUninstaller.Core/Discovery/DirectoryFactory.cs @@ -78,7 +78,7 @@ namespace LDUninstaller.Core.Discovery "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" + "Temp", "Packages", "Microsoft Help", "WindowsApps" }; foreach (var root in searchRoots) @@ -90,6 +90,7 @@ namespace LDUninstaller.Core.Discovery { string dirName = Path.GetFileName(dir); if (systemBlacklist.Contains(dirName)) continue; + if (Junk.SafetyBlacklist.IsDangerousDirectory(dir)) continue; // Check if this path or a subfolder is known if (IsAlreadyRegistered(dir)) continue; @@ -116,6 +117,8 @@ namespace LDUninstaller.Core.Discovery { string subName = Path.GetFileName(sub); if (subBlacklist.Contains(subName)) continue; + if (systemBlacklist.Contains(subName)) continue; + if (Junk.SafetyBlacklist.IsDangerousDirectory(sub)) continue; if (IsAlreadyRegistered(sub)) continue; var subEntry = AnalyzeFolder(sub, $"{dirName} - {subName}"); @@ -149,6 +152,10 @@ namespace LDUninstaller.Core.Discovery { return true; } + if (known.StartsWith(normalized + "\\", StringComparison.OrdinalIgnoreCase)) + { + return true; + } } } catch { } @@ -162,20 +169,24 @@ namespace LDUninstaller.Core.Discovery var files = Directory.GetFiles(dir, "*.exe", SearchOption.TopDirectoryOnly); if (files.Length == 0) return null; - // Look for dedicated uninstaller + // B7: Look strictly for dedicated uninstallers - NEVER accept setup or install as uninstaller! string? uninstaller = files.FirstOrDefault(f => { string name = Path.GetFileName(f).ToLowerInvariant(); - return name.Contains("unins") || name.Contains("uninstall") || name.Contains("setup"); + return name.StartsWith("unins") || name.StartsWith("uninstall") || name.Equals("uninstaller.exe"); }); 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; + if (uninstaller != null) + { + string uninsLower = Path.GetFileName(uninstaller).ToLowerInvariant(); + if (uninsLower.StartsWith("unins000")) kind = UninstallerType.InnoSetup; + else if (uninsLower.StartsWith("uninstall")) kind = UninstallerType.Nsis; + else kind = UninstallerType.Unknown; + } return new ApplicationUninstallerEntry { diff --git a/src/LDUninstaller.Core/Discovery/DiscoveryPipeline.cs b/src/LDUninstaller.Core/Discovery/DiscoveryPipeline.cs index 1ce03e3..237c77b 100644 --- a/src/LDUninstaller.Core/Discovery/DiscoveryPipeline.cs +++ b/src/LDUninstaller.Core/Discovery/DiscoveryPipeline.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; using LDUninstaller.Core.Algorithms; +using LDUninstaller.Core.InfoAdders; using LDUninstaller.Core.Models; namespace LDUninstaller.Core.Discovery @@ -19,13 +20,7 @@ namespace LDUninstaller.Core.Discovery 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) @@ -41,12 +36,7 @@ namespace LDUninstaller.Core.Discovery 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); + OnProgress?.Invoke("Paket yöneticileri ve platformlar taranıyor...", 30); var additionalResults = await Task.WhenAll(tasks); foreach (var set in additionalResults) @@ -54,11 +44,35 @@ namespace LDUninstaller.Core.Discovery allEntries.AddRange(set); } - OnProgress?.Invoke("Sonuçlar birleştiriliyor ve tekilleştiriliyor...", 80); - var merged = await Task.Run(() => MergeResults(allEntries)); + OnProgress?.Invoke("Kurulum konumları ve kimlikler çözümleniyor...", 50); + + // B7: Fill InstallLocation for registered apps first so DirectoryFactory doesn't falsely flag them as orphans! + var locGen = new InstallLocationGenerator(); + foreach (var entry in allEntries) + { + locGen.AddInfo(entry); + } + + var mergedRegistered = await Task.Run(() => MergeResults(allEntries)); + + if (includeOrphaned) + { + OnProgress?.Invoke("Sürücüler yetim ve sahipsiz klasörler için taranıyor...", 70); + + var knownLocations = mergedRegistered + .Select(x => x.InstallLocation) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .ToList(); + + var orphanEntries = await Task.Run(() => new DirectoryFactory(knownLocations).GetUninstallerEntries().ToList()); + mergedRegistered.AddRange(orphanEntries); + } + + OnProgress?.Invoke("Sonuçlar birleştiriliyor ve tekilleştiriliyor...", 90); + var mergedFinal = await Task.Run(() => MergeResults(mergedRegistered)); OnProgress?.Invoke("Tarama tamamlandı.", 100); - return merged; + return mergedFinal; } public static List MergeResults(IEnumerable entries) @@ -69,7 +83,6 @@ namespace LDUninstaller.Core.Discovery var nameMap = new Dictionary(StringComparer.OrdinalIgnoreCase); // OPTIMIZATION: Prefix bucket to replace O(N^2) inner scan with O(1) bucket lookup - // Pre-caches CleanName and Publisher to eliminate redundant Regex.Replace / Sift4.NormalizeName calls. var prefixBuckets = new Dictionary>(StringComparer.OrdinalIgnoreCase); foreach (var candidate in entries) @@ -116,7 +129,7 @@ namespace LDUninstaller.Core.Discovery for (int i = 0; i < bucketList.Count; i++) { var target = bucketList[i]; - double simName = Sift4.GetSimilarity(target.CleanName, cleanName); + double simName = Sift4.GetSimilarityNormalized(target.CleanName, cleanName); if (simName > 0.88) { if (string.IsNullOrWhiteSpace(target.Publisher) || string.IsNullOrWhiteSpace(candidate.Publisher)) @@ -124,7 +137,7 @@ namespace LDUninstaller.Core.Discovery existingFuzzy = target.Entry; break; } - double simPub = Sift4.GetSimilarity(target.Publisher, candidate.Publisher); + double simPub = Sift4.GetSimilarityNormalized(target.Publisher, candidate.Publisher); if (simPub > 0.70) { existingFuzzy = target.Entry; diff --git a/src/LDUninstaller.Core/Discovery/PackageManagersFactory.cs b/src/LDUninstaller.Core/Discovery/PackageManagersFactory.cs index 75a7eb0..ebfc64a 100644 --- a/src/LDUninstaller.Core/Discovery/PackageManagersFactory.cs +++ b/src/LDUninstaller.Core/Discovery/PackageManagersFactory.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; +using System.Threading.Tasks; using LDUninstaller.Core.Models; namespace LDUninstaller.Core.Discovery @@ -25,8 +26,15 @@ namespace LDUninstaller.Core.Discovery using var process = Process.Start(psi); if (process == null) return results; - string output = process.StandardOutput.ReadToEnd(); - process.WaitForExit(3000); + var readTask = process.StandardOutput.ReadToEndAsync(); + if (Task.WhenAny(readTask, Task.Delay(4000)).GetAwaiter().GetResult() != readTask) + { + try { process.Kill(true); } catch { } + return results; + } + + string output = readTask.GetAwaiter().GetResult(); + process.WaitForExit(1000); using var reader = new StringReader(output); string? line; @@ -122,8 +130,15 @@ namespace LDUninstaller.Core.Discovery using var process = Process.Start(psi); if (process == null) return results; - string output = process.StandardOutput.ReadToEnd(); - process.WaitForExit(5000); + var readTask = process.StandardOutput.ReadToEndAsync(); + if (Task.WhenAny(readTask, Task.Delay(6000)).GetAwaiter().GetResult() != readTask) + { + try { process.Kill(true); } catch { } + return results; + } + + string output = readTask.GetAwaiter().GetResult(); + process.WaitForExit(1000); using var reader = new StringReader(output); string? line; diff --git a/src/LDUninstaller.Core/Discovery/RegistryFactory.cs b/src/LDUninstaller.Core/Discovery/RegistryFactory.cs index 4773edb..9bb7cb2 100644 --- a/src/LDUninstaller.Core/Discovery/RegistryFactory.cs +++ b/src/LDUninstaller.Core/Discovery/RegistryFactory.cs @@ -93,14 +93,31 @@ namespace LDUninstaller.Core.Discovery installDate = dt2; } - // WindowsInstaller flag / MSI Product code + // WindowsInstaller flag / MSI Product code (B13: do NOT assume MSI just because key name is GUID) object? winInstallerVal = sub.GetValue("WindowsInstaller"); - bool isMsi = winInstallerVal is int wi && wi == 1; + bool hasWinInstallerFlag = winInstallerVal is int wi && wi == 1; + bool hasMsiUninstallString = (uninstallString != null && uninstallString.Contains("msiexec", StringComparison.OrdinalIgnoreCase)) || + (quietUninstallString != null && quietUninstallString.Contains("msiexec", StringComparison.OrdinalIgnoreCase)); + bool isMsi = hasWinInstallerFlag || hasMsiUninstallString; + Guid bundleGuid = Guid.Empty; if (Guid.TryParse(subKeyName, out var guid)) { bundleGuid = guid; - isMsi = true; + } + + // B14: Standardize RegistryPath so 32-bit keys and 64-bit keys have accurate paths + string regPath; + if (hive == RegistryHive.LocalMachine) + { + if (view == RegistryView.Registry32) + regPath = $@"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{subKeyName}"; + else + regPath = $@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{subKeyName}"; + } + else + { + regPath = $@"HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\{subKeyName}"; } var entry = new ApplicationUninstallerEntry @@ -116,7 +133,7 @@ namespace LDUninstaller.Core.Discovery DisplayIcon = displayIcon.Trim('\"'), AboutUrl = aboutUrl, RegistryKeyName = subKeyName, - RegistryPath = $"{hive}\\{subKeyPath}\\{subKeyName}", + RegistryPath = regPath, BundleProviderKey = bundleGuid, EstimatedSize = FileSize.FromBytes(estimatedSize), InstallDate = installDate, diff --git a/src/LDUninstaller.Core/Discovery/StoreAppFactory.cs b/src/LDUninstaller.Core/Discovery/StoreAppFactory.cs index e01f72b..ec33fb9 100644 --- a/src/LDUninstaller.Core/Discovery/StoreAppFactory.cs +++ b/src/LDUninstaller.Core/Discovery/StoreAppFactory.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; +using System.Threading.Tasks; using LDUninstaller.Core.Models; namespace LDUninstaller.Core.Discovery @@ -16,7 +17,6 @@ namespace LDUninstaller.Core.Discovery try { - // Run PowerShell to fetch NonDevelopment AppX packages var psi = new ProcessStartInfo { FileName = "powershell.exe", @@ -29,20 +29,17 @@ namespace LDUninstaller.Core.Discovery using var process = Process.Start(psi); if (process == null) return results; - string output = process.StandardOutput.ReadToEnd(); - - // FAULT TOLERANCE & PROCESS LIFECYCLE: - // Ensure process is never abandoned as a zombie task on timeout. - if (!process.WaitForExit(7000)) + // P5: Non-blocking asynchronous read with strict timeout + var readTask = process.StandardOutput.ReadToEndAsync(); + if (Task.WhenAny(readTask, Task.Delay(8000)).GetAwaiter().GetResult() != readTask) { - try - { - process.Kill(true); // Kill process tree immediately - } - catch { } + try { process.Kill(true); } catch { } return results; } + string output = readTask.GetAwaiter().GetResult(); + process.WaitForExit(1000); + using var reader = new StringReader(output); string? line; bool isHeader = true; @@ -56,7 +53,6 @@ namespace LDUninstaller.Core.Discovery continue; } - // CSV simple split var parts = SplitCsvLine(line); if (parts.Count < 5) continue; diff --git a/src/LDUninstaller.Core/InfoAdders/InfoAdders.cs b/src/LDUninstaller.Core/InfoAdders/InfoAdders.cs index a4dd76b..2dc5ece 100644 --- a/src/LDUninstaller.Core/InfoAdders/InfoAdders.cs +++ b/src/LDUninstaller.Core/InfoAdders/InfoAdders.cs @@ -1,7 +1,10 @@ using System; +using System.Collections.Concurrent; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security.Cryptography.X509Certificates; +using System.Text.Json; using System.Text.RegularExpressions; using LDUninstaller.Core.Models; using LDUninstaller.Core.Native; @@ -13,6 +16,73 @@ namespace LDUninstaller.Core.InfoAdders void AddInfo(ApplicationUninstallerEntry entry); } + internal class InfoCacheEntry + { + public long LastModifiedUtcTicks { get; set; } + public long SizeBytes { get; set; } + public bool? IsCertValid { get; set; } + } + + internal static class InfoCache + { + private static readonly string CachePath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "LDUninstaller", "cache.json"); + + private static readonly ConcurrentDictionary _cache = new(StringComparer.OrdinalIgnoreCase); + private static bool _loaded = false; + private static readonly object _saveLock = new(); + + public static void EnsureLoaded() + { + if (_loaded) return; + try + { + if (File.Exists(CachePath)) + { + string json = File.ReadAllText(CachePath); + var dict = JsonSerializer.Deserialize>(json); + if (dict != null) + { + foreach (var kvp in dict) + _cache[kvp.Key] = kvp.Value; + } + } + } + catch { } + _loaded = true; + } + + public static bool TryGet(string path, out InfoCacheEntry entry) + { + EnsureLoaded(); + return _cache.TryGetValue(path, out entry!); + } + + public static void Set(string path, InfoCacheEntry entry) + { + EnsureLoaded(); + _cache[path] = entry; + } + + public static void Save() + { + lock (_saveLock) + { + try + { + string dir = Path.GetDirectoryName(CachePath) ?? ""; + if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) + Directory.CreateDirectory(dir); + + string json = JsonSerializer.Serialize(_cache, new JsonSerializerOptions { WriteIndented = false }); + File.WriteAllText(CachePath, json); + } + catch { } + } + } + } + public class InstallLocationGenerator : IMissingInfoAdder { public void AddInfo(ApplicationUninstallerEntry entry) @@ -53,10 +123,11 @@ namespace LDUninstaller.Core.InfoAdders if (entry.UninstallerKind != UninstallerType.Unknown) return; - string unins = entry.UninstallString; + string unins = entry.UninstallString ?? string.Empty; string uninsLower = unins.ToLowerInvariant(); - if (uninsLower.Contains("msiexec.exe") || entry.BundleProviderKey != Guid.Empty) + // B13: Require actual msiexec in command or confirmed MSI flag + if (uninsLower.Contains("msiexec")) { entry.UninstallerKind = UninstallerType.Msiexec; } @@ -180,14 +251,23 @@ namespace LDUninstaller.Core.InfoAdders try { + var fi = new FileInfo(targetPath); + long ticks = fi.LastWriteTimeUtc.Ticks; + + if (InfoCache.TryGet(targetPath, out var cached) && cached.LastModifiedUtcTicks == ticks && cached.IsCertValid.HasValue) + { + entry.IsCertificateValid = cached.IsCertValid.Value; + return; + } + bool isValid = Win32.VerifyEmbeddedSignature(targetPath); entry.IsCertificateValid = isValid; - if (isValid) + InfoCache.Set(targetPath, new InfoCacheEntry { - var cert = X509Certificate.CreateFromSignedFile(targetPath); - entry.Certificate = new X509Certificate2(cert); - } + LastModifiedUtcTicks = ticks, + IsCertValid = isValid + }); } catch { @@ -212,10 +292,24 @@ namespace LDUninstaller.Core.InfoAdders try { - long totalBytes = CalculateDirSize(new DirectoryInfo(entry.InstallLocation), 0, 3); + var di = new DirectoryInfo(entry.InstallLocation); + long ticks = di.LastWriteTimeUtc.Ticks; + + if (InfoCache.TryGet(entry.InstallLocation, out var cached) && cached.LastModifiedUtcTicks == ticks && cached.SizeBytes > 0) + { + entry.EstimatedSize = FileSize.FromBytes(cached.SizeBytes); + return; + } + + long totalBytes = CalculateDirSize(di, 0, 3); if (totalBytes > 0) { entry.EstimatedSize = FileSize.FromBytes(totalBytes); + InfoCache.Set(entry.InstallLocation, new InfoCacheEntry + { + LastModifiedUtcTicks = ticks, + SizeBytes = totalBytes + }); } } catch { } @@ -308,9 +402,10 @@ namespace LDUninstaller.Core.InfoAdders } } - public void ProcessAll(System.Collections.Generic.IEnumerable entries) + public void ProcessAll(IEnumerable entries) { - System.Threading.Tasks.Parallel.ForEach(entries, new System.Threading.Tasks.ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, Process); + Parallel.ForEach(entries, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, Process); + InfoCache.Save(); } } } diff --git a/src/LDUninstaller.Core/Junk/ExclusionManager.cs b/src/LDUninstaller.Core/Junk/ExclusionManager.cs new file mode 100644 index 0000000..5a15fb0 --- /dev/null +++ b/src/LDUninstaller.Core/Junk/ExclusionManager.cs @@ -0,0 +1,182 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; + +namespace LDUninstaller.Core.Junk +{ + public class ExclusionItem + { + public string Path { get; set; } = string.Empty; + public bool IsRegex { get; set; } + public DateTime AddedAt { get; set; } = DateTime.Now; + public string Reason { get; set; } = string.Empty; + } + + public static class ExclusionManager + { + private static readonly object _lock = new(); + private static readonly HashSet _exactExclusions = new(StringComparer.OrdinalIgnoreCase); + private static readonly List _items = new(); + private static bool _loaded = false; + + public static string ExclusionFilePath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "LDUninstaller", "exclusions.json"); + + public static void EnsureLoaded() + { + if (_loaded) return; + lock (_lock) + { + if (_loaded) return; + LoadInternal(); + _loaded = true; + } + } + + private static void LoadInternal() + { + _exactExclusions.Clear(); + _items.Clear(); + + try + { + string path = ExclusionFilePath; + if (File.Exists(path)) + { + string json = File.ReadAllText(path); + var list = JsonSerializer.Deserialize>(json); + if (list != null) + { + foreach (var item in list) + { + if (!string.IsNullOrWhiteSpace(item.Path)) + { + string norm = NormalizePath(item.Path); + _exactExclusions.Add(norm); + _items.Add(item); + } + } + } + } + } + catch { } + } + + public static void Save() + { + lock (_lock) + { + try + { + string dir = Path.GetDirectoryName(ExclusionFilePath) ?? ""; + if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); + } + + string json = JsonSerializer.Serialize(_items, new JsonSerializerOptions { WriteIndented = true }); + File.WriteAllText(ExclusionFilePath, json); + } + catch { } + } + } + + public static bool IsExcluded(string targetPath) + { + if (string.IsNullOrWhiteSpace(targetPath)) return false; + EnsureLoaded(); + + string norm = NormalizePath(targetPath); + lock (_lock) + { + if (_exactExclusions.Contains(norm)) + return true; + + foreach (var item in _items) + { + if (item.IsRegex) + { + try + { + if (System.Text.RegularExpressions.Regex.IsMatch(norm, item.Path, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) + return true; + } + catch { } + } + else + { + string itemNorm = NormalizePath(item.Path); + if (norm.Equals(itemNorm, StringComparison.OrdinalIgnoreCase)) + return true; + if (norm.StartsWith(itemNorm + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + return true; + } + } + } + return false; + } + + public static bool AddExclusion(string path, string reason = "Kullanıcı Koruması", bool isRegex = false) + { + if (string.IsNullOrWhiteSpace(path)) return false; + EnsureLoaded(); + + lock (_lock) + { + string norm = NormalizePath(path); + if (_exactExclusions.Contains(norm)) + return false; + + var item = new ExclusionItem + { + Path = path.Trim(), + IsRegex = isRegex, + AddedAt = DateTime.Now, + Reason = reason + }; + + _items.Add(item); + _exactExclusions.Add(norm); + Save(); + return true; + } + } + + public static bool RemoveExclusion(string path) + { + if (string.IsNullOrWhiteSpace(path)) return false; + EnsureLoaded(); + + lock (_lock) + { + string norm = NormalizePath(path); + int removed = _items.RemoveAll(x => NormalizePath(x.Path).Equals(norm, StringComparison.OrdinalIgnoreCase)); + _exactExclusions.Remove(norm); + if (removed > 0) + { + Save(); + return true; + } + } + return false; + } + + public static List GetAllExclusions() + { + EnsureLoaded(); + lock (_lock) + { + return new List(_items); + } + } + + private static string NormalizePath(string p) + { + if (string.IsNullOrWhiteSpace(p)) return string.Empty; + return p.Replace('/', '\\').Trim().TrimEnd('\\'); + } + } +} diff --git a/src/LDUninstaller.Core/Junk/JunkManager.cs b/src/LDUninstaller.Core/Junk/JunkManager.cs index c7586af..0ccb16e 100644 --- a/src/LDUninstaller.Core/Junk/JunkManager.cs +++ b/src/LDUninstaller.Core/Junk/JunkManager.cs @@ -1,65 +1,170 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; +using System.Threading.Tasks; using LDUninstaller.Core.Algorithms; using LDUninstaller.Core.Models; using Microsoft.Win32; namespace LDUninstaller.Core.Junk { + public class JunkScanContext + { + public List<(string Name, string ImagePath, string DisplayName)> Services { get; set; } = new(); + public List<(string RelativePath, string TaskFile, string Content)> ScheduledTasks { get; set; } = new(); + public List<(string Hive, string KeyPath, string SubKeyName, string DefaultVal)> AppPaths { get; set; } = new(); + public List ShortcutFiles { get; set; } = new(); + + public static JunkScanContext CreateSnapshot() + { + var ctx = new JunkScanContext(); + + // 1. Snapshot Services + try + { + using var servicesKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services"); + if (servicesKey != null) + { + foreach (var svcName in servicesKey.GetSubKeyNames()) + { + try + { + using var svc = servicesKey.OpenSubKey(svcName); + if (svc == null) continue; + string? img = svc.GetValue("ImagePath")?.ToString(); + string? disp = svc.GetValue("DisplayName")?.ToString(); + if (!string.IsNullOrWhiteSpace(img)) + { + ctx.Services.Add((svcName, img, disp ?? svcName)); + } + } + catch { } + } + } + } + catch { } + + // 2. Snapshot Scheduled Tasks + try + { + string tasksDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "Tasks"); + if (Directory.Exists(tasksDir)) + { + foreach (var taskFile in Directory.GetFiles(tasksDir, "*", SearchOption.AllDirectories)) + { + if (taskFile.Contains(@"\Tasks\Microsoft\Windows", StringComparison.OrdinalIgnoreCase)) + continue; + + string relative = taskFile.Substring(tasksDir.Length).Replace('/', '\\'); + if (!relative.StartsWith("\\")) relative = "\\" + relative; + + string content = ""; + try { content = File.ReadAllText(taskFile); } catch { } + + ctx.ScheduledTasks.Add((relative, taskFile, content)); + } + } + } + catch { } + + // 3. Snapshot Shortcuts + var shortcutDirs = new[] + { + 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), + Environment.GetFolderPath(Environment.SpecialFolder.Startup), + Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft", "Windows", "Recent") + }; + + 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") + { + ctx.ShortcutFiles.Add(file); + } + } + } + catch { } + } + + return ctx; + } + } + public class JunkManager { public static string BackupDirectory => Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "LDUninstaller", "Backups"); + // B1: Expanded stop-words including 3-letter & common tech words private static readonly HashSet StopWords = new(StringComparer.OrdinalIgnoreCase) { "the", "and", "for", "with", "app", "application", "software", "corporation", "corp", "inc", "ltd", "gmbh", "edition", "desktop", "client", "runtime", "support", "installer", "setup", "unins", "uninstall", "windows", "microsoft", "x86", "x64", - "32bit", "64bit", "package", "driver", "update", "updater", "service" + "32bit", "64bit", "package", "driver", "update", "updater", "service", + "git", "win", "pro", "media", "player", "game", "games", "bin", "dev", "net", + "hub", "sdk", "tool", "tools", "core", "code", "run", "web", "site", "free", + "open", "file", "data", "base", "pack", "soft", "system", "systems", "tech", + "one", "all", "new", "home", "user", "work", "play", "view", "edit", "help", "info", "test" }; - public List ScanJunk(ApplicationUninstallerEntry entry) + public List ScanJunk(ApplicationUninstallerEntry entry, JunkScanContext? context = null) { var results = new List(); + context ??= JunkScanContext.CreateSnapshot(); + + // P1: Calculate tokens once per entry and pass to all scanners + var (cleanName, cleanPub, tokens) = GetMatchTokens(entry); // 1. Install Location leftover scanner ScanInstallLocation(entry, results); - // 2. Common drive junk scanner (AppData, LocalAppData, LocalLow, ProgramData, Documents, Saved Games) - ScanCommonDriveJunk(entry, results); + // 2. Common drive junk scanner (AppData, LocalAppData, LocalLow, ProgramData, Saved Games) - Documents excluded from auto-clean (B1) + ScanCommonDriveJunk(cleanName, cleanPub, tokens, results); // 3. User root dot-folders & config folders (.appname, .config, .cache) - ScanUserProfileDotFolders(entry, results); + ScanUserProfileDotFolders(tokens, results); // 4. Common Files and Temporary setup caches - ScanCommonFilesAndTemp(entry, results); + ScanCommonFilesAndTemp(cleanPub, tokens, results); - // 5. Multi-drive analysis & Empty parent publisher folder scanner - ScanAllDrivesForAppAndEmptyParent(entry, results); + // 5. Multi-drive analysis & Empty parent publisher folder scanner (B22) + ScanAllDrivesForAppAndEmptyParent(entry, cleanPub, tokens, results); - // 6. Software Registry Keys (HKLM, HKCU & WOW6432Node) - ScanSoftwareRegistryKeys(entry, results); + // 6. Software Registry Keys (HKLM, HKCU & WOW6432Node) (B5, B14) + ScanSoftwareRegistryKeys(cleanName, cleanPub, tokens, results); - // 7. Windows Services & Kernel/System Drivers - ScanServicesAndDrivers(entry, results); + // 7. Windows Services & Kernel/System Drivers (B6: strictly matching InstallLocation) + ScanServicesAndDrivers(entry, context, results); // 8. Windows Scheduled Tasks (Görev Zamanlayıcı) - ScanScheduledTasks(entry, results); + ScanScheduledTasks(entry, cleanPub, tokens, context, results); // 9. Application Launch Paths (App Paths) - ScanAppPaths(entry, results); + ScanAppPaths(entry, tokens, results); // 10. Startup Registry Keys (Run & RunOnce) - ScanStartupRunKeys(entry, results); + ScanStartupRunKeys(entry, tokens, results); // 11. COM Objects, CLSIDs & Context Menu Shell Extensions - ScanShellExtensionsAndCom(entry, results); + ScanShellExtensionsAndCom(entry, tokens, results); // 12. Windows Shell MuiCache ScanMuiCache(entry, results); @@ -71,21 +176,21 @@ namespace LDUninstaller.Core.Junk ScanFirewallRules(entry, results); // 15. Windows Prefetch scanner - ScanPrefetch(entry, results); + ScanPrefetch(tokens, results); // 16. Windows Error Reporting / CrashDumps - ScanWerDumps(entry, results); + ScanWerDumps(tokens, results); // 17. UserAssist ROT13 execution history scanner - ScanUserAssist(entry, results); + ScanUserAssist(tokens, results); // 18. Shortcuts & Recent items (Desktop, Start Menu, Startup, Recent) - ScanShortcutsAndRecent(entry, results); + ScanShortcutsAndRecent(tokens, context, results); // 19. Windows Installer (MSI) Orphaned Products - ScanMsiOrphanedProducts(entry, results); + ScanMsiOrphanedProducts(entry, cleanName, results); - // 20. Registry Uninstaller Entry Check (if uninstall key still exists) + // 20. Registry Uninstaller Entry Check (if uninstall key still exists) (B14) ScanRegistryUninstallKey(entry, results); // Apply Safety Blacklist filter and adjust Confidence @@ -114,30 +219,41 @@ namespace LDUninstaller.Core.Junk public List ScanMultiple(IEnumerable entries) { + var appList = entries.ToList(); + if (appList.Count == 0) return new List(); + + // P3: Snapshot system once for all apps + var context = JunkScanContext.CreateSnapshot(); + var bag = new ConcurrentBag(); + + Parallel.ForEach(appList, entry => + { + var list = ScanJunk(entry, context); + foreach (var j in list) + bag.Add(j); + }); + + // Deduplicate var all = new List(); var seenPaths = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var entry in entries) + foreach (var j in bag) { - var list = ScanJunk(entry); - foreach (var j in list) - { - string uniqueKey = $"{j.Type}:{j.Path}"; - if (j is RegistryJunkResult r && !string.IsNullOrEmpty(r.ValueName)) - uniqueKey += $":{r.ValueName}"; + string uniqueKey = $"{j.Type}:{j.Path}"; + if (j is RegistryJunkResult r && !string.IsNullOrEmpty(r.ValueName)) + uniqueKey += $":{r.ValueName}"; - if (!seenPaths.Contains(uniqueKey)) - { - seenPaths.Add(uniqueKey); - all.Add(j); - } + if (!seenPaths.Contains(uniqueKey)) + { + seenPaths.Add(uniqueKey); + all.Add(j); } } return all; } - private static (string cleanName, string cleanPublisher, List tokens) GetMatchTokens(ApplicationUninstallerEntry entry) + public static (string cleanName, string cleanPublisher, List tokens) GetMatchTokens(ApplicationUninstallerEntry entry) { string rawName = entry.DisplayName ?? string.Empty; string stripped = Regex.Replace(rawName, @"(\bv?\d+(\.\d+)+|\(x86\)|\(x64\)|\(amd64\)|sürümü|version)", " ", RegexOptions.IgnoreCase); @@ -146,7 +262,8 @@ namespace LDUninstaller.Core.Junk var tokens = new List(); - if (cleanName.Length >= 2 && !StopWords.Contains(cleanName)) + // Never add token if it's in StopWords or length < 3 + if (cleanName.Length >= 3 && !StopWords.Contains(cleanName)) tokens.Add(cleanName); if (cleanPub.Length >= 3 && !StopWords.Contains(cleanPub)) @@ -184,6 +301,15 @@ namespace LDUninstaller.Core.Junk return (cleanName, cleanPub, tokens); } + public static bool IsWordOrExactMatch(string target, string token) + { + if (string.IsNullOrWhiteSpace(target) || string.IsNullOrWhiteSpace(token)) return false; + if (target.Equals(token, StringComparison.OrdinalIgnoreCase)) return true; + + // Word boundary match: so "git" matches "git" or "git-client" but NEVER "github" + return Regex.IsMatch(target, $@"(^|[\s_\-\.\\]){Regex.Escape(token)}($|[\s_\-\.\\])", RegexOptions.IgnoreCase); + } + private void ScanInstallLocation(ApplicationUninstallerEntry entry, List results) { if (string.IsNullOrWhiteSpace(entry.InstallLocation) || !Directory.Exists(entry.InstallLocation)) @@ -203,18 +329,17 @@ namespace LDUninstaller.Core.Junk }); } - private void ScanCommonDriveJunk(ApplicationUninstallerEntry entry, List results) + private void ScanCommonDriveJunk(string cleanName, string cleanPub, List tokens, List results) { - var (cleanName, cleanPub, tokens) = GetMatchTokens(entry); if (tokens.Count == 0) return; + // B1: Documents is removed from auto-selected paths to protect user projects / code repositories 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") }; @@ -239,13 +364,13 @@ namespace LDUninstaller.Core.Junk } else if (!string.IsNullOrEmpty(cleanPub) && dirName.Equals(cleanPub, StringComparison.OrdinalIgnoreCase)) { - // Publisher folder: search subdirectories! + // Publisher folder: search subdirectories with strict match! 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)) + if (tokens.Any(t => IsWordOrExactMatch(subName, t) || Sift4.GetSimilarityNormalized(subName, t) >= 0.82)) { results.Add(new FileSystemJunkResult { @@ -262,7 +387,7 @@ namespace LDUninstaller.Core.Junk catch { } continue; } - else if (tokens.Any(t => dirName.Contains(t) || Sift4.GetSimilarity(dirName, t) >= 0.80)) + else if (tokens.Any(t => IsWordOrExactMatch(dirName, t) || Sift4.GetSimilarityNormalized(dirName, t) >= 0.85)) { matched = true; conf = ConfidenceLevel.Good; @@ -286,9 +411,8 @@ namespace LDUninstaller.Core.Junk } } - private void ScanUserProfileDotFolders(ApplicationUninstallerEntry entry, List results) + private void ScanUserProfileDotFolders(List tokens, List results) { - var (_, _, tokens) = GetMatchTokens(entry); if (tokens.Count == 0) return; string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); @@ -303,7 +427,8 @@ namespace LDUninstaller.Core.Junk if (SafetyBlacklist.IsDangerousDirectory(dir)) continue; string stripped = dirName.TrimStart('.').ToLowerInvariant(); - if (tokens.Any(t => stripped.Equals(t, StringComparison.OrdinalIgnoreCase) || stripped.StartsWith(t, StringComparison.OrdinalIgnoreCase))) + // B1: Strict word or exact match, never loose substring + if (tokens.Any(t => IsWordOrExactMatch(stripped, t))) { results.Add(new FileSystemJunkResult { @@ -327,7 +452,7 @@ namespace LDUninstaller.Core.Junk string dirName = Path.GetFileName(dir).ToLowerInvariant(); if (SafetyBlacklist.IsDangerousDirectory(dir)) continue; - if (tokens.Any(t => dirName.Contains(t) || Sift4.GetSimilarity(dirName, t) >= 0.80)) + if (tokens.Any(t => IsWordOrExactMatch(dirName, t) || Sift4.GetSimilarityNormalized(dirName, t) >= 0.85)) { results.Add(new FileSystemJunkResult { @@ -345,9 +470,8 @@ namespace LDUninstaller.Core.Junk catch { } } - private void ScanCommonFilesAndTemp(ApplicationUninstallerEntry entry, List results) + private void ScanCommonFilesAndTemp(string cleanPub, List tokens, List results) { - var (cleanName, cleanPub, tokens) = GetMatchTokens(entry); if (tokens.Count == 0) return; // Common Files @@ -372,7 +496,7 @@ namespace LDUninstaller.Core.Junk 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)) + if (tokens.Any(t => IsWordOrExactMatch(subName, t) || Sift4.GetSimilarityNormalized(subName, t) >= 0.80)) { results.Add(new FileSystemJunkResult { @@ -386,7 +510,7 @@ namespace LDUninstaller.Core.Junk } } } - else if (tokens.Any(t => dirName.Contains(t) || Sift4.GetSimilarity(dirName, t) >= 0.80)) + else if (tokens.Any(t => IsWordOrExactMatch(dirName, t) || Sift4.GetSimilarityNormalized(dirName, t) >= 0.85)) { results.Add(new FileSystemJunkResult { @@ -414,7 +538,7 @@ namespace LDUninstaller.Core.Junk string dirName = Path.GetFileName(dir).ToLowerInvariant(); if (SafetyBlacklist.IsDangerousDirectory(dir)) continue; - if (tokens.Any(t => dirName.Contains(t))) + if (tokens.Any(t => IsWordOrExactMatch(dirName, t))) { results.Add(new FileSystemJunkResult { @@ -432,11 +556,9 @@ namespace LDUninstaller.Core.Junk catch { } } - private void ScanAllDrivesForAppAndEmptyParent(ApplicationUninstallerEntry entry, List results) + private void ScanAllDrivesForAppAndEmptyParent(ApplicationUninstallerEntry entry, string cleanPub, List tokens, List results) { - var (_, _, tokens) = GetMatchTokens(entry); - - // Empty publisher folder cleanup + // B22: Empty publisher folder cleanup with strict safety if (!string.IsNullOrWhiteSpace(entry.InstallLocation)) { try @@ -444,22 +566,31 @@ namespace LDUninstaller.Core.Junk var parent = Directory.GetParent(entry.InstallLocation.TrimEnd('\\')); if (parent != null && parent.Exists && !SafetyBlacklist.IsDangerousDirectory(parent.FullName)) { - var entries = parent.GetFileSystemInfos(); - // Check if parent only contains the install location being removed or is completely empty - bool isEmptyOrOnlyTarget = entries.Length == 0 || - (entries.Length == 1 && entries[0].FullName.Equals(Path.GetFullPath(entry.InstallLocation).TrimEnd('\\'), StringComparison.OrdinalIgnoreCase)); + string parentName = parent.Name.ToLowerInvariant(); + string[] forbiddenGenericRoots = { "games", "oyunlar", "program files", "programs", "apps", "steamlibrary", "common" }; - if (isEmptyOrOnlyTarget) + // Only consider publisher folder if parent folder name actually matches publisher! + bool isPublisherFolder = !string.IsNullOrWhiteSpace(cleanPub) && + (parentName.Equals(cleanPub, StringComparison.OrdinalIgnoreCase) || Sift4.GetSimilarityNormalized(parentName, cleanPub) >= 0.85); + + if (isPublisherFolder && !forbiddenGenericRoots.Contains(parentName)) { - results.Add(new FileSystemJunkResult + var entries = parent.GetFileSystemInfos(); + bool isEmptyOrOnlyTarget = entries.Length == 0 || + (entries.Length == 1 && entries[0].FullName.Equals(Path.GetFullPath(entry.InstallLocation).TrimEnd('\\'), StringComparison.OrdinalIgnoreCase)); + + if (isEmptyOrOnlyTarget) { - EntryName = parent.Name, - Path = parent.FullName, - IsDirectory = true, - Confidence = ConfidenceLevel.VeryGood, - Reason = "Uygulama kaldırıldıktan sonra boş kalan ana yayıncı klasörü", - Selected = true - }); + results.Add(new FileSystemJunkResult + { + EntryName = parent.Name, + Path = parent.FullName, + IsDirectory = true, + Confidence = ConfidenceLevel.VeryGood, + Reason = "Uygulama kaldırıldıktan sonra boş kalan ana yayıncı klasörü", + Selected = true + }); + } } } } @@ -491,7 +622,7 @@ namespace LDUninstaller.Core.Junk string subName = Path.GetFileName(sub).ToLowerInvariant(); if (SafetyBlacklist.IsDangerousDirectory(sub)) continue; - if (tokens.Any(t => subName.Equals(t, StringComparison.OrdinalIgnoreCase) || Sift4.GetSimilarity(subName, t) >= 0.85)) + if (tokens.Any(t => IsWordOrExactMatch(subName, t) || Sift4.GetSimilarityNormalized(subName, t) >= 0.85)) { results.Add(new FileSystemJunkResult { @@ -511,42 +642,42 @@ namespace LDUninstaller.Core.Junk } } - private void ScanSoftwareRegistryKeys(ApplicationUninstallerEntry entry, List results) + private void ScanSoftwareRegistryKeys(string cleanName, string cleanPub, List tokens, 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")) + (Prefix: "HKCU\\Software", Key: Registry.CurrentUser.OpenSubKey("Software")), + (Prefix: "HKLM\\SOFTWARE", Key: Registry.LocalMachine.OpenSubKey("SOFTWARE")), + (Prefix: "HKLM_32\\Software", Key: RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("Software")) }; - foreach (var (hiveName, rootKey) in hives) + foreach (var (prefix, rootKey) in hives) { if (rootKey == null) continue; using (rootKey) { foreach (var subName in rootKey.GetSubKeyNames()) { - if (SafetyBlacklist.IsDangerousRegistryPath($"{hiveName}\\Software\\{subName}")) + string fullPath = $@"{prefix}\{subName}"; + if (SafetyBlacklist.IsDangerousRegistryPath(fullPath)) continue; string subLower = subName.ToLowerInvariant(); - if (subLower.Equals(cleanName, StringComparison.OrdinalIgnoreCase) || tokens.Any(t => subLower.Equals(t, StringComparison.OrdinalIgnoreCase))) + if (subLower.Equals(cleanName, StringComparison.OrdinalIgnoreCase) || tokens.Any(t => IsWordOrExactMatch(subLower, t))) { results.Add(new RegistryJunkResult { EntryName = subName, - Path = $@"{hiveName}\Software\{subName}", + Path = fullPath, 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)) + else if (!string.IsNullOrEmpty(cleanPub) && (subLower.Equals(cleanPub, StringComparison.OrdinalIgnoreCase) || Sift4.GetSimilarityNormalized(subLower, cleanPub) >= 0.85)) { // Publisher registry key -> scan app subkeys try @@ -557,12 +688,12 @@ namespace LDUninstaller.Core.Junk foreach (var appSub in pubKey.GetSubKeyNames()) { string appSubLower = appSub.ToLowerInvariant(); - if (tokens.Any(t => appSubLower.Contains(t) || Sift4.GetSimilarity(appSubLower, t) >= 0.75)) + if (tokens.Any(t => IsWordOrExactMatch(appSubLower, t) || Sift4.GetSimilarityNormalized(appSubLower, t) >= 0.80)) { results.Add(new RegistryJunkResult { EntryName = $"{subName}\\{appSub}", - Path = $@"{hiveName}\Software\{subName}\{appSub}", + Path = $@"{prefix}\{subName}\{appSub}", Confidence = ConfidenceLevel.VeryGood, Reason = "Yayıncı altındaki uygulama kayıt defteri anahtarı kalıntısı", Selected = true @@ -573,223 +704,149 @@ namespace LDUninstaller.Core.Junk } 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 ScanServicesAndDrivers(ApplicationUninstallerEntry entry, List results) + // B6: Services strictly matched against InstallLocation folder + private void ScanServicesAndDrivers(ApplicationUninstallerEntry entry, JunkScanContext context, List results) { - var (_, _, tokens) = GetMatchTokens(entry); - string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\').ToLowerInvariant(); + if (string.IsNullOrWhiteSpace(entry.InstallLocation)) return; + string installNorm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar; - try + foreach (var (svcName, imagePath, displayName) in context.Services) { - using var servicesKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services"); - if (servicesKey == null) return; + string cleanImagePath = imagePath.Replace("\"", "").Trim(); + if (cleanImagePath.StartsWith(@"\??\")) + cleanImagePath = cleanImagePath.Substring(4); - foreach (var svcName in servicesKey.GetSubKeyNames()) + // Strip executable arguments (e.g. "C:\Program Files\App\srv.exe -k runservice") + int exeIdx = cleanImagePath.IndexOf(".exe", StringComparison.OrdinalIgnoreCase); + if (exeIdx > 0) { - try + cleanImagePath = cleanImagePath.Substring(0, exeIdx + 4).Trim(); + } + + if (cleanImagePath.StartsWith(installNorm, StringComparison.OrdinalIgnoreCase)) + { + results.Add(new GenericJunkResult { - using var svc = servicesKey.OpenSubKey(svcName); - if (svc == null) continue; - - string? imagePath = svc.GetValue("ImagePath")?.ToString(); - string? displayName = svc.GetValue("DisplayName")?.ToString(); - string svcLower = svcName.ToLowerInvariant(); - - bool match = false; - string matchReason = ""; - - if (!string.IsNullOrEmpty(imagePath)) + EntryName = svcName, + Path = svcName, + Type = JunkType.Service, + Confidence = ConfidenceLevel.VeryGood, + Reason = $"Uygulamaya ait arka plan Windows Hizmeti ({displayName}) [{cleanImagePath}]", + Selected = true, + CustomAction = () => { - string cleanImagePath = imagePath.Replace("\"", "").Trim().ToLowerInvariant(); - if (cleanImagePath.StartsWith(@"\??\")) - cleanImagePath = cleanImagePath.Substring(4); - - // Ignore OS core binaries - if (!cleanImagePath.Contains(@"\windows\system32\svchost.exe") && - !cleanImagePath.Contains(@"\windows\system32\services.exe") && - !cleanImagePath.Contains(@"\windows\system32\lsass.exe")) + try { - if (!string.IsNullOrEmpty(installNorm) && cleanImagePath.Contains(installNorm)) + // Backup service registry key first + Directory.CreateDirectory(BackupDirectory); + string file = Path.Combine(BackupDirectory, $"service_backup_{DateTime.Now:yyyyMMdd_HHmmss}_{svcName}.reg"); + var psiBackup = new ProcessStartInfo("reg.exe", $"export \"HKLM\\SYSTEM\\CurrentControlSet\\Services\\{svcName}\" \"{file}\" /y") { - match = true; - matchReason = "Hizmet yolu kaldırılan uygulamanın kurulum klasörünü işaret ediyor"; - } - else if (tokens.Any(t => cleanImagePath.Contains(t) && !cleanImagePath.Contains("windows"))) - { - match = true; - matchReason = "Hizmet yolu kaldırılan uygulamanın dosyasını işaret ediyor"; - } + CreateNoWindow = true, + UseShellExecute = false + }; + using var pB = Process.Start(psiBackup); + pB?.WaitForExit(3000); + + // Stop service + var stopInfo = new ProcessStartInfo("sc.exe", $"stop \"{svcName}\"") { CreateNoWindow = true, UseShellExecute = false }; + using var pStop = Process.Start(stopInfo); + pStop?.WaitForExit(3000); + + // Delete service + var delInfo = new ProcessStartInfo("sc.exe", $"delete \"{svcName}\"") { CreateNoWindow = true, UseShellExecute = false }; + using var pDel = Process.Start(delInfo); + pDel?.WaitForExit(3000); + + using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default); + baseKey.DeleteSubKeyTree($@"SYSTEM\CurrentControlSet\Services\{svcName}", false); + return true; + } + catch + { + return false; } } - - if (!match && tokens.Count > 0) - { - if (tokens.Any(t => svcLower.Equals(t, StringComparison.OrdinalIgnoreCase)) || - (!string.IsNullOrEmpty(displayName) && tokens.Any(t => displayName.ToLowerInvariant().Contains(t)))) - { - match = true; - matchReason = "Hizmet adı veya açıklaması kaldırılan yazılımla eşleşiyor"; - } - } - - if (match) - { - results.Add(new GenericJunkResult - { - EntryName = svcName, - Path = svcName, - Type = JunkType.Service, - Confidence = ConfidenceLevel.VeryGood, - Reason = $"Uygulamaya ait arkaplan Windows Hizmeti ({displayName ?? svcName}) - {matchReason}", - Selected = true, - CustomAction = () => - { - try - { - var stopInfo = new ProcessStartInfo("sc.exe", $"stop \"{svcName}\"") { CreateNoWindow = true, UseShellExecute = false }; - using var pStop = Process.Start(stopInfo); - pStop?.WaitForExit(3000); - - var delInfo = new ProcessStartInfo("sc.exe", $"delete \"{svcName}\"") { CreateNoWindow = true, UseShellExecute = false }; - using var pDel = Process.Start(delInfo); - pDel?.WaitForExit(3000); - - using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default); - baseKey.DeleteSubKeyTree($@"SYSTEM\CurrentControlSet\Services\{svcName}", false); - return true; - } - catch - { - return false; - } - } - }); - } - } - catch { } + }); } } - catch { } } - private void ScanScheduledTasks(ApplicationUninstallerEntry entry, List results) + private void ScanScheduledTasks(ApplicationUninstallerEntry entry, string cleanPub, List tokens, JunkScanContext context, List results) { - var (_, cleanPub, tokens) = GetMatchTokens(entry); - string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\').ToLowerInvariant(); + string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar; - string tasksDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "Tasks"); - if (!Directory.Exists(tasksDir)) return; - - try + foreach (var (relativeTaskPath, taskFile, content) in context.ScheduledTasks) { - foreach (var taskFile in Directory.GetFiles(tasksDir, "*", SearchOption.AllDirectories)) + string fileName = Path.GetFileName(taskFile).ToLowerInvariant(); + bool match = false; + string matchReason = ""; + + if (!string.IsNullOrEmpty(installNorm) && content.IndexOf(installNorm, StringComparison.OrdinalIgnoreCase) >= 0) { - // Never touch Microsoft OS internal tasks - if (taskFile.Contains(@"\Tasks\Microsoft\Windows", StringComparison.OrdinalIgnoreCase)) - continue; + match = true; + matchReason = "Görev eylemi kaldırılan uygulamanın kurulum klasöründeki dosyayı çalıştırıyor"; + } + else if (tokens.Any(t => IsWordOrExactMatch(fileName, t)) || (!string.IsNullOrEmpty(cleanPub) && relativeTaskPath.IndexOf(cleanPub, StringComparison.OrdinalIgnoreCase) >= 0)) + { + match = true; + matchReason = "Görev adı kaldırılan yazılımla eşleşiyor"; + } - string relativeTaskPath = taskFile.Substring(tasksDir.Length).Replace('/', '\\'); - if (!relativeTaskPath.StartsWith("\\")) - relativeTaskPath = "\\" + relativeTaskPath; - - string fileName = Path.GetFileName(taskFile).ToLowerInvariant(); - bool match = false; - string matchReason = ""; - - // 1. Check path/filename tokens - if (tokens.Any(t => fileName.Contains(t)) || (!string.IsNullOrEmpty(cleanPub) && relativeTaskPath.ToLowerInvariant().Contains(cleanPub))) + if (match) + { + results.Add(new GenericJunkResult { - match = true; - matchReason = "Görev adı veya klasörü kaldırılan yazılımla eşleşiyor"; - } - - // 2. Read task XML command - if (!match) - { - try + EntryName = Path.GetFileName(taskFile), + Path = relativeTaskPath, + Type = JunkType.ScheduledTask, + Confidence = ConfidenceLevel.VeryGood, + Reason = $"Windows Görev Zamanlayıcı (Scheduled Task) kalıntısı - {matchReason}", + Selected = true, + CustomAction = () => { - string content = File.ReadAllText(taskFile).ToLowerInvariant(); - if (!string.IsNullOrEmpty(installNorm) && content.Contains(installNorm)) + try { - match = true; - matchReason = "Görev eylemi kaldırılan uygulamanın kurulum klasöründeki dosyayı çalıştırıyor"; + var psi = new ProcessStartInfo("schtasks.exe", $"/Delete /TN \"{relativeTaskPath}\" /F") + { + CreateNoWindow = true, + UseShellExecute = false + }; + using var p = Process.Start(psi); + p?.WaitForExit(3000); + + if (File.Exists(taskFile)) + File.Delete(taskFile); + + return true; } - else if (tokens.Any(t => content.Contains($"\\{t}.exe") || content.Contains($"\\{t}updater.exe"))) + catch { - match = true; - matchReason = "Görev komut satırı uygulamanın çalıştırılabilir dosyasını hedefliyor"; + return false; } } - catch { } - } - - if (match) - { - results.Add(new GenericJunkResult - { - EntryName = Path.GetFileName(taskFile), - Path = relativeTaskPath, - Type = JunkType.ScheduledTask, - Confidence = ConfidenceLevel.VeryGood, - Reason = $"Windows Görev Zamanlayıcı (Scheduled Task) kalıntısı - {matchReason}", - Selected = true, - CustomAction = () => - { - try - { - var psi = new ProcessStartInfo("schtasks.exe", $"/Delete /TN \"{relativeTaskPath}\" /F") - { - CreateNoWindow = true, - UseShellExecute = false - }; - using var p = Process.Start(psi); - p?.WaitForExit(3000); - - if (File.Exists(taskFile)) - File.Delete(taskFile); - - return true; - } - catch - { - return false; - } - } - }); - } + }); } } - catch { } } - private void ScanAppPaths(ApplicationUninstallerEntry entry, List results) + private void ScanAppPaths(ApplicationUninstallerEntry entry, List tokens, List results) { - var (_, _, tokens) = GetMatchTokens(entry); - string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\').ToLowerInvariant(); + string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar; var roots = new[] { - (Hive: "HKLM", Key: Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths")), - (Hive: "HKCU", Key: Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\App Paths")), - (Hive: "HKLM_32", Key: Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths")) + (Prefix: "HKLM", Key: Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths")), + (Prefix: "HKCU", Key: Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\App Paths")), + (Prefix: "HKLM_32", Key: RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths")) }; - foreach (var (hive, root) in roots) + foreach (var (prefix, root) in roots) { if (root == null) continue; using (root) @@ -805,21 +862,20 @@ namespace LDUninstaller.Core.Junk string subLower = sub.ToLowerInvariant(); bool match = false; - if (!string.IsNullOrEmpty(defaultVal) && !string.IsNullOrEmpty(installNorm) && defaultVal.ToLowerInvariant().Contains(installNorm)) + if (!string.IsNullOrEmpty(defaultVal) && !string.IsNullOrEmpty(installNorm) && defaultVal.StartsWith(installNorm, StringComparison.OrdinalIgnoreCase)) { match = true; } - else if (tokens.Any(t => subLower.Contains(t))) + else if (tokens.Any(t => IsWordOrExactMatch(subLower, t))) { match = true; } if (match) { - string basePath = hive.StartsWith("HKCU") ? "HKCU" : "HKLM"; - string path = hive == "HKLM_32" + string path = prefix == "HKLM_32" ? $@"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\{sub}" - : $@"{basePath}\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\{sub}"; + : $@"{prefix}\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\{sub}"; results.Add(new RegistryJunkResult { @@ -837,10 +893,9 @@ namespace LDUninstaller.Core.Junk } } - private void ScanStartupRunKeys(ApplicationUninstallerEntry entry, List results) + private void ScanStartupRunKeys(ApplicationUninstallerEntry entry, List tokens, List results) { - var (_, _, tokens) = GetMatchTokens(entry); - string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\').ToLowerInvariant(); + string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar; var locations = new[] { @@ -848,14 +903,20 @@ namespace LDUninstaller.Core.Junk (Hive: "HKLM", Path: @"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"), (Hive: "HKCU", Path: @"Software\Microsoft\Windows\CurrentVersion\Run"), (Hive: "HKCU", Path: @"Software\Microsoft\Windows\CurrentVersion\RunOnce"), - (Hive: "HKLM", Path: @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run") + (Hive: "HKLM_32", Path: @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run") }; foreach (var loc in locations) { try { - var baseKey = loc.Hive == "HKCU" ? Registry.CurrentUser : Registry.LocalMachine; + RegistryKey? baseKey = loc.Hive switch + { + "HKCU" => Registry.CurrentUser, + "HKLM_32" => RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32), + _ => Registry.LocalMachine + }; + using var key = baseKey.OpenSubKey(loc.Path); if (key == null) continue; @@ -867,17 +928,18 @@ namespace LDUninstaller.Core.Junk string valLower = valData.ToLowerInvariant(); bool match = false; - if (!string.IsNullOrEmpty(installNorm) && valLower.Contains(installNorm)) + if (!string.IsNullOrEmpty(installNorm) && valLower.Contains(installNorm.ToLowerInvariant())) match = true; - else if (tokens.Any(t => valName.ToLowerInvariant().Contains(t) || valLower.Contains($"\\{t}.exe"))) + else if (tokens.Any(t => IsWordOrExactMatch(valName.ToLowerInvariant(), t))) match = true; if (match) { + string hiveName = loc.Hive == "HKLM_32" ? "HKLM" : loc.Hive; results.Add(new RegistryJunkResult { EntryName = valName, - Path = $@"{loc.Hive}\{loc.Path}", + Path = $@"{hiveName}\{loc.Path}", ValueName = valName, Confidence = ConfidenceLevel.VeryGood, Reason = "Başlangıçta otomatik çalıştırma kayıt defteri girdisi (Run/RunOnce)", @@ -890,12 +952,10 @@ namespace LDUninstaller.Core.Junk } } - private void ScanShellExtensionsAndCom(ApplicationUninstallerEntry entry, List results) + private void ScanShellExtensionsAndCom(ApplicationUninstallerEntry entry, List tokens, List results) { - var (_, _, tokens) = GetMatchTokens(entry); - string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\').ToLowerInvariant(); + string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar; - // 1. ContextMenuHandlers string[] contextMenuKeys = { @"*\shellex\ContextMenuHandlers", @@ -915,7 +975,7 @@ namespace LDUninstaller.Core.Junk foreach (var sub in root.GetSubKeyNames()) { string subLower = sub.ToLowerInvariant(); - if (tokens.Any(t => subLower.Contains(t))) + if (tokens.Any(t => IsWordOrExactMatch(subLower, t))) { results.Add(new RegistryJunkResult { @@ -931,33 +991,7 @@ namespace LDUninstaller.Core.Junk catch { } } - // 2. Approved Shell Extensions - try - { - using var approved = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved"); - if (approved != null) - { - foreach (var valName in approved.GetValueNames()) - { - string? desc = approved.GetValue(valName)?.ToString(); - if (!string.IsNullOrEmpty(desc) && tokens.Any(t => desc.ToLowerInvariant().Contains(t))) - { - results.Add(new RegistryJunkResult - { - EntryName = desc, - Path = @"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved", - ValueName = valName, - Confidence = ConfidenceLevel.VeryGood, - Reason = "Onaylanmış kabuk uzantısı listesi girdisi (Shell Extension Approved)", - Selected = true - }); - } - } - } - } - catch { } - - // 3. Orphaned CLSIDs pointing into InstallLocation + // Orphaned CLSIDs pointing into InstallLocation if (!string.IsNullOrEmpty(installNorm)) { try @@ -978,7 +1012,7 @@ namespace LDUninstaller.Core.Junk if (sKey == null) continue; string? serverPath = sKey.GetValue(null)?.ToString(); - if (!string.IsNullOrEmpty(serverPath) && serverPath.ToLowerInvariant().Contains(installNorm)) + if (!string.IsNullOrEmpty(serverPath) && serverPath.StartsWith(installNorm, StringComparison.OrdinalIgnoreCase)) { results.Add(new RegistryJunkResult { @@ -1002,7 +1036,7 @@ namespace LDUninstaller.Core.Junk private void ScanMuiCache(ApplicationUninstallerEntry entry, List results) { - string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\').ToLowerInvariant(); + string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar; if (string.IsNullOrEmpty(installNorm)) return; string[] muiPaths = @@ -1020,7 +1054,7 @@ namespace LDUninstaller.Core.Junk foreach (var val in key.GetValueNames()) { - if (val.ToLowerInvariant().Contains(installNorm)) + if (val.StartsWith(installNorm, StringComparison.OrdinalIgnoreCase)) { results.Add(new RegistryJunkResult { @@ -1040,7 +1074,7 @@ namespace LDUninstaller.Core.Junk private void ScanAppCompatFlags(ApplicationUninstallerEntry entry, List results) { - string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\').ToLowerInvariant(); + string installNorm = string.IsNullOrWhiteSpace(entry.InstallLocation) ? "" : Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar; if (string.IsNullOrEmpty(installNorm)) return; var paths = new[] @@ -1060,7 +1094,7 @@ namespace LDUninstaller.Core.Junk foreach (var val in key.GetValueNames()) { - if (val.ToLowerInvariant().Contains(installNorm)) + if (val.StartsWith(installNorm, StringComparison.OrdinalIgnoreCase)) { results.Add(new RegistryJunkResult { @@ -1086,12 +1120,12 @@ namespace LDUninstaller.Core.Junk 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(); + string installNorm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar; foreach (var valName in key.GetValueNames()) { string? val = key.GetValue(valName)?.ToString(); - if (!string.IsNullOrWhiteSpace(val) && val.ToLowerInvariant().Contains(installNorm)) + if (!string.IsNullOrWhiteSpace(val) && val.IndexOf(installNorm, StringComparison.OrdinalIgnoreCase) >= 0) { results.Add(new RegistryJunkResult { @@ -1108,15 +1142,13 @@ namespace LDUninstaller.Core.Junk catch { } } - private void ScanPrefetch(ApplicationUninstallerEntry entry, List results) + private void ScanPrefetch(List tokens, List results) { try { string prefetchDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Prefetch"); if (!Directory.Exists(prefetchDir)) return; - var (_, _, tokens) = GetMatchTokens(entry); - foreach (var token in tokens.Take(3)) { if (token.Length < 3) continue; @@ -1138,9 +1170,8 @@ namespace LDUninstaller.Core.Junk catch { } } - private void ScanWerDumps(ApplicationUninstallerEntry entry, List results) + private void ScanWerDumps(List tokens, List results) { - var (_, _, tokens) = GetMatchTokens(entry); if (tokens.Count == 0) return; try @@ -1151,7 +1182,7 @@ namespace LDUninstaller.Core.Junk foreach (var file in Directory.GetFiles(crashDumps, "*.dmp")) { string fname = Path.GetFileName(file).ToLowerInvariant(); - if (tokens.Any(t => fname.Contains(t))) + if (tokens.Any(t => IsWordOrExactMatch(fname, t))) { results.Add(new FileSystemJunkResult { @@ -1165,41 +1196,17 @@ namespace LDUninstaller.Core.Junk } } } - - // WER ReportArchive - string werArchive = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Microsoft", "Windows", "WER", "ReportArchive"); - if (Directory.Exists(werArchive)) - { - foreach (var dir in Directory.GetDirectories(werArchive)) - { - string dname = Path.GetFileName(dir).ToLowerInvariant(); - if (tokens.Any(t => dname.Contains(t))) - { - results.Add(new FileSystemJunkResult - { - EntryName = Path.GetFileName(dir), - Path = dir, - IsDirectory = true, - Confidence = ConfidenceLevel.Good, - Reason = "Windows Hata Raporu arşiv klasörü (WER Report)", - Selected = true - }); - } - } - } } catch { } } - private void ScanUserAssist(ApplicationUninstallerEntry entry, List results) + private void ScanUserAssist(List tokens, List results) { try { using var uaKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist"); if (uaKey == null) return; - var (_, _, tokens) = GetMatchTokens(entry); - foreach (var sub in uaKey.GetSubKeyNames()) { using var countKey = uaKey.OpenSubKey($"{sub}\\Count", true); @@ -1208,7 +1215,7 @@ namespace LDUninstaller.Core.Junk foreach (var valName in countKey.GetValueNames()) { string decoded = Rot13(valName).ToLowerInvariant(); - if (tokens.Any(t => decoded.Contains(t))) + if (tokens.Any(t => IsWordOrExactMatch(decoded, t))) { results.Add(new RegistryJunkResult { @@ -1226,60 +1233,32 @@ namespace LDUninstaller.Core.Junk catch { } } - private void ScanShortcutsAndRecent(ApplicationUninstallerEntry entry, List results) + private void ScanShortcutsAndRecent(List tokens, JunkScanContext context, List results) { - var shortcutDirs = new List + foreach (var file in context.ShortcutFiles) { - 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), - Environment.GetFolderPath(Environment.SpecialFolder.Startup), - Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup), - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft", "Windows", "Recent") - }; - - var (_, _, tokens) = GetMatchTokens(entry); - - foreach (var dir in shortcutDirs) - { - if (!Directory.Exists(dir)) continue; - try + string fname = Path.GetFileNameWithoutExtension(file).ToLowerInvariant(); + if (tokens.Any(t => IsWordOrExactMatch(fname, t) || Sift4.GetSimilarityNormalized(fname, t) >= 0.88)) { - foreach (var file in Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)) + results.Add(new FileSystemJunkResult { - 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ü, Başlat menüsü veya Son Belgeler kısayol kalıntısı", - Selected = true - }); - } - } + 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 { } } } - private void ScanMsiOrphanedProducts(ApplicationUninstallerEntry entry, List results) + private void ScanMsiOrphanedProducts(ApplicationUninstallerEntry entry, string cleanName, List results) { - var (cleanName, _, _) = GetMatchTokens(entry); if (cleanName.Length < 3) return; try { - // HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products using var productsKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products"); if (productsKey != null) { @@ -1335,34 +1314,19 @@ namespace LDUninstaller.Core.Junk try { - RegistryKey? root = null; - string subPath = entry.RegistryPath; - - if (subPath.StartsWith("HKEY_LOCAL_MACHINE\\", StringComparison.OrdinalIgnoreCase)) + var (hive, subKey, view) = RegistryJunkResult.ParseRegistryPath(entry.RegistryPath); + using var baseKey = RegistryKey.OpenBaseKey(hive, view); + using var key = baseKey.OpenSubKey(subKey); + if (key != null) { - 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 { - 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 - }); - } + 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 { } diff --git a/src/LDUninstaller.Core/Junk/SafetyBlacklist.cs b/src/LDUninstaller.Core/Junk/SafetyBlacklist.cs index 16eabe3..2d727f7 100644 --- a/src/LDUninstaller.Core/Junk/SafetyBlacklist.cs +++ b/src/LDUninstaller.Core/Junk/SafetyBlacklist.cs @@ -7,6 +7,7 @@ namespace LDUninstaller.Core.Junk public static class SafetyBlacklist { private static readonly HashSet BlacklistedDirs = new(StringComparer.OrdinalIgnoreCase); + private static readonly List ProtectedPrefixes = new(); private static readonly HashSet BlacklistedRegPaths = new(StringComparer.OrdinalIgnoreCase); private static readonly HashSet ProtectedNames = new(StringComparer.OrdinalIgnoreCase) { @@ -14,38 +15,108 @@ namespace LDUninstaller.Core.Junk "windows defender", "windows security", "internet explorer", "microsoft.net", "windowspowershell", "dotnet", "common files", "desktop", "downloads", "documents", "pictures", "music", "videos", "appdata", "locallow", "roaming", "local", - "temp", "system volume information", "$recycle.bin", "recovery", "boot", "perflogs" + "temp", "system volume information", "$recycle.bin", "recovery", "boot", "perflogs", + "windowsapps", "package cache", "onedrive" }; + private static readonly string DynamicUsersRoot; + private static readonly string UserProfileDir; + static SafetyBlacklist() { - // Windows & System - AddDir(Environment.GetFolderPath(Environment.SpecialFolder.Windows)); + // Windows & System directories + string winDir = Environment.GetFolderPath(Environment.SpecialFolder.Windows); + AddDir(winDir); + AddPrefix(winDir); // Any file/folder inside C:\Windows must NEVER be treated as junk! + 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)); + + string pf = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); + AddDir(pf); + if (!string.IsNullOrEmpty(pf)) + { + AddPrefix(Path.Combine(pf, "WindowsApps")); + AddDir(Path.Combine(pf, "Common Files")); + } + + string pf86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); + if (!string.IsNullOrEmpty(pf86) && !pf86.Equals(pf, StringComparison.OrdinalIgnoreCase)) + { + AddDir(pf86); + AddPrefix(Path.Combine(pf86, "WindowsApps")); + AddDir(Path.Combine(pf86, "Common Files")); + } + + UserProfileDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + AddDir(UserProfileDir); + + // Dynamic Users parent directory (e.g. D:\Users or C:\Users on any non-standard drive) + string? usersParent = Path.GetDirectoryName(UserProfileDir); + DynamicUsersRoot = !string.IsNullOrWhiteSpace(usersParent) ? usersParent : @"C:\Users"; + AddDir(DynamicUsersRoot); + + // Core user personal folders + AddDir(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); + AddDir(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); + AddDir(Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory)); 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()) + // Package Cache + string commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); + if (!string.IsNullOrEmpty(commonAppData)) { - AddDir(drive.RootDirectory.FullName); + AddPrefix(Path.Combine(commonAppData, "Package Cache")); } + // OneDrive Roots + string[] oneDriveVars = { "OneDrive", "OneDriveConsumer", "OneDriveCommercial" }; + foreach (var v in oneDriveVars) + { + string? envVal = Environment.GetEnvironmentVariable(v); + if (!string.IsNullOrWhiteSpace(envVal) && Directory.Exists(envVal)) + { + AddDir(envVal); + AddDir(Path.Combine(envVal, "Documents")); + AddDir(Path.Combine(envVal, "Masaüstü")); + AddDir(Path.Combine(envVal, "Desktop")); + AddDir(Path.Combine(envVal, "Resimler")); + AddDir(Path.Combine(envVal, "Pictures")); + } + } + + // Drives roots + try + { + foreach (var drive in DriveInfo.GetDrives()) + { + AddDir(drive.RootDirectory.FullName); + } + } + catch { } + // Registry Core Containers & Blacklists BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion"); + BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows NT"); + BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion"); BlacklistedRegPaths.Add(@"HKLM\SYSTEM\CurrentControlSet"); BlacklistedRegPaths.Add(@"HKLM\SYSTEM\CurrentControlSet\Services"); BlacklistedRegPaths.Add(@"HKLM\SYSTEM"); BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft"); BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Classes"); + BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Policies"); + BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Policies\Microsoft"); + BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Policies\Microsoft\Windows"); BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft"); BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows"); BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion"); + BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer"); + BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"); + BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"); + BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer"); + BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Policies"); BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"); BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); @@ -63,6 +134,9 @@ namespace LDUninstaller.Core.Junk BlacklistedRegPaths.Add(@"HKCR\CLSID"); BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Classes\CLSID"); BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Classes\CLSID"); + BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\WOW6432Node\Microsoft"); + BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows"); + BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion"); } private static void AddDir(string? path) @@ -77,23 +151,53 @@ namespace LDUninstaller.Core.Junk } } + private static void AddPrefix(string? path) + { + if (!string.IsNullOrWhiteSpace(path)) + { + try + { + string norm = Path.GetFullPath(path).TrimEnd('\\') + Path.DirectorySeparatorChar; + if (!ProtectedPrefixes.Contains(norm)) + ProtectedPrefixes.Add(norm); + } + catch { } + } + } + public static bool IsDangerousDirectory(string path) { if (string.IsNullOrWhiteSpace(path)) return true; try { string norm = Path.GetFullPath(path).TrimEnd('\\'); + + // 1. Check exact blacklisted system directories if (BlacklistedDirs.Contains(norm)) return true; + // 2. Check protected subfolder prefixes (e.g. C:\Windows\...) + string normWithSep = norm + Path.DirectorySeparatorChar; + foreach (var pfx in ProtectedPrefixes) + { + if (normWithSep.StartsWith(pfx, StringComparison.OrdinalIgnoreCase)) + return true; + } + + // 3. User exclusion list + if (ExclusionManager.IsExcluded(norm)) + return true; + + // 4. Protected base folder names string name = Path.GetFileName(norm); if (ProtectedNames.Contains(name)) return true; - // Parent must not be directly root or users root without specific subfolder + // 5. Parent checks: cannot delete drive root, user root, or Users parent var di = new DirectoryInfo(norm); - if (di.Parent == null) return true; // e.g. C:\ - if (di.Parent.FullName.Equals(@"C:\Users", StringComparison.OrdinalIgnoreCase)) return true; + if (di.Parent == null) return true; // e.g. C:\ or D:\ + if (di.Parent.FullName.Equals(DynamicUsersRoot, StringComparison.OrdinalIgnoreCase)) return true; // e.g. C:\Users\Username directly + if (norm.Equals(UserProfileDir, StringComparison.OrdinalIgnoreCase)) return true; return false; } @@ -106,14 +210,37 @@ namespace LDUninstaller.Core.Junk public static bool IsDangerousRegistryPath(string regPath) { if (string.IsNullOrWhiteSpace(regPath)) return true; + + // Normalize HKLM_32 to standard WOW6432Node representation string norm = regPath.Replace("/", "\\").TrimEnd('\\'); + if (norm.StartsWith("HKLM_32\\Software", StringComparison.OrdinalIgnoreCase)) + { + norm = "HKLM\\SOFTWARE\\WOW6432Node" + norm.Substring("HKLM_32\\Software".Length); + } + else if (norm.StartsWith("HKLM_32\\", StringComparison.OrdinalIgnoreCase)) + { + norm = "HKLM\\" + norm.Substring("HKLM_32\\".Length); + } + + // User exclusion check + if (ExclusionManager.IsExcluded(norm)) + return true; + foreach (var bl in BlacklistedRegPaths) { if (norm.Equals(bl, StringComparison.OrdinalIgnoreCase)) return true; } - // Root hives - if (!norm.Contains('\\')) return true; + + // Root hives or 1-level subkeys under hives (e.g. HKLM\SOFTWARE, HKCU\Software, etc.) + int slashCount = 0; + for (int i = 0; i < norm.Length; i++) + { + if (norm[i] == '\\') slashCount++; + } + + if (slashCount <= 1) return true; // HKLM, HKLM\SOFTWARE + return false; } } diff --git a/src/LDUninstaller.Core/Models/ApplicationUninstallerEntry.cs b/src/LDUninstaller.Core/Models/ApplicationUninstallerEntry.cs index aede15f..7a4fef6 100644 --- a/src/LDUninstaller.Core/Models/ApplicationUninstallerEntry.cs +++ b/src/LDUninstaller.Core/Models/ApplicationUninstallerEntry.cs @@ -61,6 +61,26 @@ namespace LDUninstaller.Core.Models [System.Xml.Serialization.XmlIgnore] public List AdditionalJunk { get; } = new(); + public string InstallDateDisplay => InstallDate > DateTime.MinValue.AddYears(1) ? InstallDate.ToString("yyyy-MM-dd") : "—"; + + public string UninstallerKindDisplay => UninstallerKind switch + { + UninstallerType.InnoSetup => "Inno Setup", + UninstallerType.Nsis => "NSIS", + UninstallerType.Msiexec => "MSI (Windows Installer)", + UninstallerType.StoreApp => "Microsoft Store (UWP)", + UninstallerType.Steam => "Steam", + UninstallerType.InstallShield => "InstallShield", + UninstallerType.AdvancedInstaller => "Advanced Installer", + UninstallerType.Wise => "Wise", + UninstallerType.Squirrel => "Squirrel", + UninstallerType.ClickOnce => "ClickOnce", + UninstallerType.Chocolatey => "Chocolatey", + UninstallerType.Scoop => "Scoop", + UninstallerType.SimpleDelete => "Sahipsiz Klasör", + _ => UninstallerKind.ToString() + }; + public override string ToString() => $"{DisplayName} ({Publisher}) - {DisplayVersion} [{UninstallerKind}]"; } diff --git a/src/LDUninstaller.Core/Models/JunkResults.cs b/src/LDUninstaller.Core/Models/JunkResults.cs index 4d64767..059f198 100644 --- a/src/LDUninstaller.Core/Models/JunkResults.cs +++ b/src/LDUninstaller.Core/Models/JunkResults.cs @@ -36,6 +36,24 @@ namespace LDUninstaller.Core.Models _ => Type.ToString() }; ConfidenceLevel Confidence { get; } + string ConfidenceDisplay => Confidence switch + { + ConfidenceLevel.VeryGood => "Çok Yüksek", + ConfidenceLevel.Good => "İyi", + _ => "Orta / Düşük" + }; + string ConfidenceBadgeColor => Confidence switch + { + ConfidenceLevel.VeryGood => "#34D399", + ConfidenceLevel.Good => "#FBBF24", + _ => "#F87171" + }; + string ConfidenceBadgeBackground => Confidence switch + { + ConfidenceLevel.VeryGood => "#064E3B", + ConfidenceLevel.Good => "#451A03", + _ => "#450A0A" + }; string Reason { get; } bool Selected { get; set; } bool Delete(string backupDir); @@ -44,7 +62,7 @@ namespace LDUninstaller.Core.Models 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 Path { get; set; } = string.Empty; // e.g. HKLM\SOFTWARE\Vendor\AppName or HKLM_32\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; @@ -56,16 +74,22 @@ namespace LDUninstaller.Core.Models try { BackupToReg(backupDir); - var (hive, subKey) = ParseRegistryPath(Path); - using var baseKey = RegistryKey.OpenBaseKey(hive, RegistryView.Default); + var (hive, subKey, view) = ParseRegistryPath(Path); + using var baseKey = RegistryKey.OpenBaseKey(hive, view); + if (ValueName == null) { + // Check if key exists first + using var check = baseKey.OpenSubKey(subKey); + if (check == null) return false; + baseKey.DeleteSubKeyTree(subKey, false); } else { using var opened = baseKey.OpenSubKey(subKey, true); - opened?.DeleteValue(ValueName, false); + if (opened == null) return false; + opened.DeleteValue(ValueName, false); } return true; } @@ -80,9 +104,22 @@ namespace LDUninstaller.Core.Models try { Directory.CreateDirectory(backupDir); + string exportPath = Path; + string extraArgs = ""; + + if (exportPath.StartsWith("HKLM_32\\", StringComparison.OrdinalIgnoreCase)) + { + exportPath = "HKLM\\" + exportPath.Substring("HKLM_32\\".Length); + extraArgs = " /reg:32"; + } + else if (exportPath.Contains("WOW6432Node", StringComparison.OrdinalIgnoreCase)) + { + extraArgs = " /reg:32"; + } + 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") + var psi = new System.Diagnostics.ProcessStartInfo("reg.exe", $"export \"{exportPath}\" \"{file}\" /y{extraArgs}") { CreateNoWindow = true, UseShellExecute = false @@ -96,11 +133,24 @@ namespace LDUninstaller.Core.Models } } - private static (RegistryHive hive, string subKey) ParseRegistryPath(string fullPath) + public static (RegistryHive hive, string subKey, RegistryView view) ParseRegistryPath(string fullPath) { - int firstSlash = fullPath.IndexOf('\\'); - string hiveStr = firstSlash > 0 ? fullPath[..firstSlash] : fullPath; - string sub = firstSlash > 0 ? fullPath[(firstSlash + 1)..] : ""; + RegistryView view = RegistryView.Default; + string working = fullPath; + + if (working.StartsWith("HKLM_32\\", StringComparison.OrdinalIgnoreCase)) + { + view = RegistryView.Registry32; + working = "HKLM\\" + working.Substring("HKLM_32\\".Length); + } + else if (working.Contains("WOW6432Node", StringComparison.OrdinalIgnoreCase)) + { + view = RegistryView.Registry32; + } + + int firstSlash = working.IndexOf('\\'); + string hiveStr = firstSlash > 0 ? working[..firstSlash] : working; + string sub = firstSlash > 0 ? working[(firstSlash + 1)..] : ""; RegistryHive hive = hiveStr.ToUpperInvariant() switch { @@ -110,7 +160,8 @@ namespace LDUninstaller.Core.Models "HKU" or "HKEY_USERS" => RegistryHive.Users, _ => RegistryHive.LocalMachine }; - return (hive, sub); + + return (hive, sub, view); } } @@ -128,6 +179,19 @@ namespace LDUninstaller.Core.Models { try { + // B32: If target does not exist, return false + if (IsDirectory && !Directory.Exists(Path)) + return false; + if (!IsDirectory && !File.Exists(Path)) + return false; + + // B2: Always use Windows Shell API to send items safely to the Recycle Bin! + if (Native.Win32.SendToRecycleBin(Path)) + { + return true; + } + + // Fallback to direct delete if Shell operation was unsupported on volume if (IsDirectory) { if (Directory.Exists(Path)) @@ -152,7 +216,7 @@ namespace LDUninstaller.Core.Models } } } - return true; + return false; } catch { diff --git a/src/LDUninstaller.Core/Native/Win32.cs b/src/LDUninstaller.Core/Native/Win32.cs index 200830e..e92b479 100644 --- a/src/LDUninstaller.Core/Native/Win32.cs +++ b/src/LDUninstaller.Core/Native/Win32.cs @@ -29,7 +29,7 @@ namespace LDUninstaller.Core.Native try { using var wtd = new WinTrustFileInfo(filePath); - var data = new WinTrustData(wtd.Handle); + using var data = new WinTrustData(wtd.Handle); uint result = WinVerifyTrust(new IntPtr(-1), WINTRUST_ACTION_GENERIC_VERIFY_V2, data); return result == 0; // 0 == ERROR_SUCCESS } @@ -39,7 +39,7 @@ namespace LDUninstaller.Core.Native } } - // --- System Restore API (srclient.dll) --- + // --- System Restore API (srclient.dll) (B11) --- [DllImport("srclient.dll", CharSet = CharSet.Unicode)] public static extern bool SRSetRestorePointW(ref RESTOREPOINTINFO pRestorePointInit, ref STATEMGRSTATUS pSMgrStatus); @@ -65,11 +65,102 @@ namespace LDUninstaller.Core.Native } catch { - // Fallback / SR disabled on machine + // System Restore service disabled or policy prevented } return false; } + public static bool EndRestorePoint(long sequenceNumber) + { + if (sequenceNumber <= 0) return false; + try + { + var info = new RESTOREPOINTINFO + { + dwEventType = 101, // END_SYSTEM_CHANGE + dwRestorePtType = 0, + llSequenceNumber = sequenceNumber, + szDescription = string.Empty + }; + var status = new STATEMGRSTATUS(); + return SRSetRestorePointW(ref info, ref status) && status.nStatus == 0; + } + catch + { + return false; + } + } + + // --- Windows Shell File Operations: SendToRecycleBin (B2) --- + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct SHFILEOPSTRUCT + { + public IntPtr hwnd; + public uint wFunc; + public string pFrom; + public string? pTo; + public ushort fFlags; + public bool fAnyOperationsAborted; + public IntPtr hNameMappings; + public string? lpszProgressTitle; + } + + [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern int SHFileOperation(ref SHFILEOPSTRUCT lpFileOp); + + public const uint FO_DELETE = 0x0003; + public const ushort FOF_SILENT = 0x0004; + public const ushort FOF_NOCONFIRMATION = 0x0010; + public const ushort FOF_ALLOWUNDO = 0x0040; + public const ushort FOF_NOERRORUI = 0x0400; + + public static bool SendToRecycleBin(string path) + { + if (string.IsNullOrWhiteSpace(path)) return false; + if (!File.Exists(path) && !Directory.Exists(path)) return false; + + // 1. Primary: Microsoft Windows Desktop Shell Recycle Bin (IFileOperation wrapper) + try + { + if (Directory.Exists(path)) + { + Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory( + path, + Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, + Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin); + return !Directory.Exists(path); + } + else if (File.Exists(path)) + { + Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile( + path, + Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, + Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin); + return !File.Exists(path); + } + } + catch { } + + // 2. Secondary: Native SHFileOperation with guaranteed double-null termination + try + { + var shf = new SHFILEOPSTRUCT + { + hwnd = IntPtr.Zero, + wFunc = FO_DELETE, + pFrom = path + "\0\0", + pTo = null, + fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI + }; + int result = SHFileOperation(ref shf); + return result == 0 && !shf.fAnyOperationsAborted; + } + catch + { + return false; + } + } + // --- MoveFileEx (Reboot cleanup) --- [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool MoveFileEx(string lpExistingFileName, string? lpNewFileName, int dwFlags); @@ -87,7 +178,7 @@ namespace LDUninstaller.Core.Native } } - // --- Shell Icons --- + // --- Shell Icons & Handle Cleanup (P11) --- [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern uint ExtractIconEx(string szFileName, int nIconIndex, IntPtr[]? phiconLarge, IntPtr[]? phiconSmall, uint nIcons); @@ -113,6 +204,39 @@ namespace LDUninstaller.Core.Native public const uint SWP_NOSIZE = 0x0001; public const uint SWP_NOZORDER = 0x0004; + // --- Process Path by Win32 QueryFullProcessImageName (P9) --- + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + public static extern bool QueryFullProcessImageName(IntPtr hProcess, int dwFlags, StringBuilder lpExeName, ref int lpdwSize); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern bool CloseHandle(IntPtr hObject); + + public const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000; + + public static string? GetProcessPath(int processId) + { + IntPtr hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processId); + if (hProcess == IntPtr.Zero) return null; + try + { + var sb = new StringBuilder(1024); + int size = sb.Capacity; + if (QueryFullProcessImageName(hProcess, 0, sb, ref size)) + { + return sb.ToString(); + } + } + catch { } + finally + { + CloseHandle(hProcess); + } + return null; + } + public static void GentleKillProcess(Process process, int waitMs = 3000) { try @@ -162,7 +286,7 @@ namespace LDUninstaller.Core.Native } } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)] public struct RESTOREPOINTINFO { public int dwEventType; @@ -172,7 +296,7 @@ namespace LDUninstaller.Core.Native public string szDescription; } - [StructLayout(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct STATEMGRSTATUS { public int nStatus; @@ -207,28 +331,38 @@ namespace LDUninstaller.Core.Native } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct WINTRUST_FILE_INFO_NATIVE + { + public uint cbStruct; + [MarshalAs(UnmanagedType.LPWStr)] + public string pcwszFilePath; + public IntPtr hFile; + public IntPtr pgKnownSubject; + } + 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); + var native = new WINTRUST_FILE_INFO_NATIVE + { + cbStruct = (uint)Marshal.SizeOf(typeof(WINTRUST_FILE_INFO_NATIVE)), + pcwszFilePath = filePath, + hFile = IntPtr.Zero, + pgKnownSubject = IntPtr.Zero + }; + _nativeMemory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINTRUST_FILE_INFO_NATIVE))); + Marshal.StructureToPtr(native, _nativeMemory, false); } public void Dispose() { if (_nativeMemory != IntPtr.Zero) { + Marshal.DestroyStructure(_nativeMemory); Marshal.FreeHGlobal(_nativeMemory); _nativeMemory = IntPtr.Zero; } diff --git a/src/LDUninstaller.Core/Services/FileUnlockerService.cs b/src/LDUninstaller.Core/Services/FileUnlockerService.cs new file mode 100644 index 0000000..0e772c7 --- /dev/null +++ b/src/LDUninstaller.Core/Services/FileUnlockerService.cs @@ -0,0 +1,606 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.ServiceProcess; +using System.Threading; +using LDUninstaller.Core.Junk; +using LDUninstaller.Core.Native; +using Microsoft.Win32; + +namespace LDUninstaller.Core.Services +{ + public class ProcessLockInfo + { + public int ProcessId { get; set; } + public string ProcessName { get; set; } = string.Empty; + public string ExecutablePath { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public bool IsService { get; set; } + public string ServiceName { get; set; } = string.Empty; + } + + public class UnlockAndDestroyResult + { + public bool Success { get; set; } + public string TargetPath { get; set; } = string.Empty; + public int KilledProcessesCount { get; set; } + public int StoppedServicesCount { get; set; } + public int DeletedFilesCount { get; set; } + public List ErrorMessages { get; } = new(); + public bool ScheduledForReboot { get; set; } + } + + public static class FileUnlockerService + { + #region Windows Restart Manager Interop + private const int CCH_RM_SESSION_KEY = 32; + + [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)] + private static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey); + + [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)] + private static extern int RmRegisterResources( + uint pSessionHandle, + uint nFiles, + string[]? rgsFileNames, + uint nApplications, + RM_UNIQUE_PROCESS[]? rgApplications, + uint nServices, + string[]? rgsServiceNames); + + [DllImport("rstrtmgr.dll")] + private static extern int RmGetList( + uint pSessionHandle, + out uint pnProcInfoNeeded, + ref uint pnProcInfo, + [In, Out] RM_PROCESS_INFO[]? rgAffectedApps, + out uint lpdwRebootReasons); + + [DllImport("rstrtmgr.dll")] + private static extern int RmEndSession(uint pSessionHandle); + + [StructLayout(LayoutKind.Sequential)] + private struct RM_UNIQUE_PROCESS + { + public int dwProcessId; + public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct RM_PROCESS_INFO + { + public RM_UNIQUE_PROCESS Process; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] + public string strAppName; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] + public string strServiceShortName; + public int ApplicationType; + public uint AppStatus; + public uint TSSessionId; + [MarshalAs(UnmanagedType.Bool)] + public bool bRestartable; + } + #endregion + + /// + /// Kısayol (.lnk) veya dosya/klasör yolunu analiz ederek asıl kurulum klasörünü ve hedefi çözümler. + /// + public static (string targetFolder, string? primaryFile, string? originalLnk) ResolveTarget(string inputPath) + { + if (string.IsNullOrWhiteSpace(inputPath)) + return (string.Empty, null, null); + + string norm = Path.GetFullPath(inputPath).TrimEnd('\\'); + + // Eğer .lnk kısayolu ise, hedef exe'yi ve onun üst klasörünü çöz + if (norm.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase) && File.Exists(norm)) + { + string? resolved = ResolveShortcutTarget(norm); + if (!string.IsNullOrWhiteSpace(resolved)) + { + if (Directory.Exists(resolved)) + { + return (resolved, null, norm); + } + if (File.Exists(resolved)) + { + string? parent = Path.GetDirectoryName(resolved); + if (!string.IsNullOrWhiteSpace(parent) && Directory.Exists(parent)) + { + return (parent, resolved, norm); + } + } + } + } + + // Normal dosya ise üst klasörünü hedef klasör al (ör. C:\Program Files\App\app.exe) + if (File.Exists(norm)) + { + string? parent = Path.GetDirectoryName(norm); + if (!string.IsNullOrWhiteSpace(parent) && Directory.Exists(parent)) + { + return (parent, norm, null); + } + } + + // Normal klasör ise doğrudan kendisi + return (norm, null, null); + } + + public static string? ResolveShortcutTarget(string lnkPath) + { + try + { + Type? shellType = Type.GetTypeFromProgID("WScript.Shell"); + if (shellType != null) + { + dynamic? shell = Activator.CreateInstance(shellType); + if (shell != null) + { + dynamic? shortcut = shell.CreateShortcut(lnkPath); + string? target = shortcut?.TargetPath; + if (!string.IsNullOrWhiteSpace(target)) + return target; + } + } + } + catch { } + return null; + } + + /// + /// Hedef klasör ve içindeki dosyaları o an kilitleyen tüm süreçleri ve servisleri listeler. + /// + public static List InspectLocks(string targetPath) + { + var results = new Dictionary(); + if (string.IsNullOrWhiteSpace(targetPath) || (!Directory.Exists(targetPath) && !File.Exists(targetPath))) + return results.Values.ToList(); + + string normDir = Path.GetFullPath(targetPath).TrimEnd('\\'); + + // 1. Klasör içi imaj yoluna sahip süreçler + try + { + foreach (var proc in Process.GetProcesses()) + { + try + { + string? img = Win32.GetProcessPath(proc.Id); + if (!string.IsNullOrEmpty(img)) + { + string normImg = img.TrimEnd('\\'); + if (normImg.StartsWith(normDir + "\\", StringComparison.OrdinalIgnoreCase) || + normImg.Equals(normDir, StringComparison.OrdinalIgnoreCase)) + { + if (!results.ContainsKey(proc.Id)) + { + results[proc.Id] = new ProcessLockInfo + { + ProcessId = proc.Id, + ProcessName = proc.ProcessName, + ExecutablePath = img, + Description = "Klasör içinde çalışan aktif süreç" + }; + } + } + } + } + catch { } + finally { proc.Dispose(); } + } + } + catch { } + + // 2. Windows Restart Manager ile kilitli DLL/dosya tutan dış süreçler + try + { + var filesToCheck = new List(); + if (File.Exists(targetPath)) + { + filesToCheck.Add(targetPath); + } + else if (Directory.Exists(targetPath)) + { + // En kritik kilit adaylarını topla (exe, dll, sys, log, db) + var topFiles = Directory.EnumerateFiles(targetPath, "*.*", SearchOption.AllDirectories) + .Where(f => + { + string ext = Path.GetExtension(f).ToLowerInvariant(); + return ext is ".exe" or ".dll" or ".sys" or ".dat" or ".db" or ".log"; + }) + .Take(64) + .ToList(); + + filesToCheck.AddRange(topFiles); + } + + if (filesToCheck.Count > 0) + { + var rmProcs = GetProcessesLockingFilesWithRm(filesToCheck); + foreach (var rm in rmProcs) + { + if (!results.ContainsKey(rm.ProcessId)) + results[rm.ProcessId] = rm; + } + } + } + catch { } + + // 3. Klasör içi dosyaları kullanan Windows Servisleri + try + { + var services = FindServicesInDirectory(normDir); + foreach (var s in services) + { + // Servise ait bir PID varsa listeye ekle veya yeni bilgi oluştur + if (s.ProcessId > 0 && results.TryGetValue(s.ProcessId, out var existing)) + { + existing.IsService = true; + existing.ServiceName = s.ServiceName; + } + else + { + results[s.ProcessId > 0 ? s.ProcessId : -Math.Abs(s.ServiceName.GetHashCode())] = s; + } + } + } + catch { } + + return results.Values.ToList(); + } + + /// + /// 4 Aşamalı kilit kırma boru hattını çalıştırır, süreç ve servisleri sonlandırır ve klasörü tamamen siler. + /// + public static UnlockAndDestroyResult UnlockAndDestroy( + string targetPath, + bool sendToRecycleBin = true, + Action? onLog = null) + { + var res = new UnlockAndDestroyResult { TargetPath = targetPath }; + + if (string.IsNullOrWhiteSpace(targetPath) || (!Directory.Exists(targetPath) && !File.Exists(targetPath))) + { + res.Success = true; + return res; + } + + // GÜVENLİK KALKANI: Kritik sistem veya kullanıcı kök dizini ise asla silme! + if (SafetyBlacklist.IsDangerousDirectory(targetPath)) + { + string msg = $"GÜVENLİK ENGELİ: '{targetPath}' kritik bir Windows sistem veya profil kök dizinidir ve silinemez!"; + onLog?.Invoke(msg); + res.ErrorMessages.Add(msg); + res.Success = false; + return res; + } + + string normPath = Path.GetFullPath(targetPath).TrimEnd('\\'); + onLog?.Invoke($"[1/4] Kilit kırma başlatılıyor: {normPath}"); + + // AŞAMA 1 & 2: Süreçleri Sonlandırma (Restart Manager + Process Tree Kill) + var locks = InspectLocks(normPath); + int currentPid = Process.GetCurrentProcess().Id; + + foreach (var lockInfo in locks) + { + if (lockInfo.ProcessId <= 4 || lockInfo.ProcessId == currentPid) + continue; + + // explorer.exe kontrolü + if (lockInfo.ProcessName.Equals("explorer", StringComparison.OrdinalIgnoreCase)) + { + onLog?.Invoke("Dosya Gezgini (explorer.exe) kilit tutuyor; tutamaç serbest bırakılacak."); + continue; + } + + try + { + using var proc = Process.GetProcessById(lockInfo.ProcessId); + onLog?.Invoke($"Süreç sonlandırılıyor: {proc.ProcessName} (PID: {proc.Id})"); + proc.Kill(entireProcessTree: true); + proc.WaitForExit(1500); + res.KilledProcessesCount++; + } + catch { } + } + + // AŞAMA 3: İlgili Windows Servislerini Durdurma ve Kaldırma + var services = FindServicesInDirectory(normPath); + foreach (var svc in services) + { + try + { + onLog?.Invoke($"Servis durduruluyor ve kaldırılıyor: {svc.ServiceName}"); + using var sc = new ServiceController(svc.ServiceName); + if (sc.Status != ServiceControllerStatus.Stopped && sc.Status != ServiceControllerStatus.StopPending) + { + sc.Stop(); + sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3)); + } + + // sc delete ile servisi sistemden temizle + RunCommandSilent("sc.exe", $"delete \"{svc.ServiceName}\""); + res.StoppedServicesCount++; + } + catch { } + } + + // AŞAMA 4: İzinleri Sıfırlama ve Agresif Silme Döngüsü + onLog?.Invoke("[4/4] Dosya öznitelikleri sıfırlanıyor ve sahiplik alınıyor..."); + ResetAttributesAndTakeOwnership(normPath); + + // 5 Aşamalı Agresif Silme Döngüsü + for (int attempt = 1; attempt <= 5; attempt++) + { + if (!Directory.Exists(normPath) && !File.Exists(normPath)) + { + res.Success = true; + onLog?.Invoke("Hedef başarıyla silindi ve yok edildi!"); + return res; + } + + onLog?.Invoke($"Silme denemesi {attempt}/5..."); + + bool deleted = false; + if (sendToRecycleBin) + { + deleted = Win32.SendToRecycleBin(normPath); + } + + if (!deleted) + { + try + { + if (File.Exists(normPath)) + { + File.Delete(normPath); + deleted = !File.Exists(normPath); + } + else if (Directory.Exists(normPath)) + { + Directory.Delete(normPath, true); + deleted = !Directory.Exists(normPath); + } + } + catch (Exception ex) + { + res.ErrorMessages.Add($"Deneme {attempt} hatası: {ex.Message}"); + } + } + + if (deleted || (!Directory.Exists(normPath) && !File.Exists(normPath))) + { + res.Success = true; + onLog?.Invoke("Hedef klasör tamamen temizlendi."); + return res; + } + + // Silinemeyen dosya kaldıysa tekrar Restart Manager ile kilitleyen süreci avla + var remainingLocks = InspectLocks(normPath); + foreach (var rmProc in remainingLocks) + { + if (rmProc.ProcessId > 4 && rmProc.ProcessId != currentPid && !rmProc.ProcessName.Equals("explorer", StringComparison.OrdinalIgnoreCase)) + { + try + { + using var p = Process.GetProcessById(rmProc.ProcessId); + p.Kill(entireProcessTree: true); + res.KilledProcessesCount++; + } + catch { } + } + } + + Thread.Sleep(300); + } + + // Eğer hala silinemeyen bir kernel driver veya sistem dosyası kaldıysa, yeniden başlatmada silinmeye ayarla + if (Directory.Exists(normPath) || File.Exists(normPath)) + { + onLog?.Invoke("Bazı dosyalar çekirdek düzeyinde kilitli; ilk sistem yeniden başlatmasında (MoveFileEx) silinmek üzere zamanlanıyor..."); + ScheduleAllForRebootDelete(normPath); + res.ScheduledForReboot = true; + res.Success = true; + } + + return res; + } + + private static List GetProcessesLockingFilesWithRm(List filePaths) + { + var list = new List(); + string sessionKey = Guid.NewGuid().ToString(); + + int res = RmStartSession(out uint sessionHandle, 0, sessionKey); + if (res != 0) return list; + + try + { + int regRes = RmRegisterResources(sessionHandle, (uint)filePaths.Count, filePaths.ToArray(), 0, null, 0, null); + if (regRes != 0) return list; + + uint procInfoNeeded = 0; + uint procInfo = 0; + RM_PROCESS_INFO[]? processInfo = null; + + res = RmGetList(sessionHandle, out procInfoNeeded, ref procInfo, processInfo, out uint rebootReasons); + if (res == 234) // ERROR_MORE_DATA + { + processInfo = new RM_PROCESS_INFO[procInfoNeeded]; + procInfo = procInfoNeeded; + res = RmGetList(sessionHandle, out procInfoNeeded, ref procInfo, processInfo, out rebootReasons); + } + + if (res == 0 && processInfo != null) + { + foreach (var pi in processInfo) + { + int pid = pi.Process.dwProcessId; + if (pid <= 4) continue; + + string exePath = Win32.GetProcessPath(pid) ?? ""; + list.Add(new ProcessLockInfo + { + ProcessId = pid, + ProcessName = string.IsNullOrEmpty(pi.strAppName) ? Path.GetFileNameWithoutExtension(exePath) : pi.strAppName, + ExecutablePath = exePath, + ServiceName = pi.strServiceShortName, + IsService = !string.IsNullOrEmpty(pi.strServiceShortName), + Description = "Restart Manager tarafından yakalanan kilitli süreç" + }); + } + } + } + finally + { + RmEndSession(sessionHandle); + } + + return list; + } + + private static List FindServicesInDirectory(string dirPath) + { + var services = new List(); + string normDir = dirPath.TrimEnd('\\'); + + try + { + using var servicesKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services"); + if (servicesKey == null) return services; + + foreach (var svcName in servicesKey.GetSubKeyNames()) + { + try + { + using var svcKey = servicesKey.OpenSubKey(svcName); + string? imagePath = svcKey?.GetValue("ImagePath")?.ToString(); + if (string.IsNullOrWhiteSpace(imagePath)) continue; + + string clean = imagePath.Replace("\"", "").Trim(); + if (clean.StartsWith(@"\??\")) clean = clean.Substring(4); + + int exeIdx = clean.IndexOf(".exe", StringComparison.OrdinalIgnoreCase); + if (exeIdx > 0) clean = clean.Substring(0, exeIdx + 4).Trim(); + + if (clean.StartsWith(normDir + "\\", StringComparison.OrdinalIgnoreCase) || + clean.Equals(normDir, StringComparison.OrdinalIgnoreCase)) + { + int pid = GetServicePid(svcName); + services.Add(new ProcessLockInfo + { + ProcessId = pid, + ProcessName = svcName, + ExecutablePath = clean, + ServiceName = svcName, + IsService = true, + Description = $"Windows Servisi ({svcName})" + }); + } + } + catch { } + } + } + catch { } + + return services; + } + + private static int GetServicePid(string serviceName) + { + try + { + using var sc = new ServiceController(serviceName); + // ServiceProcessId is available via reflection or sc queryex + string output = RunCommandSilent("sc.exe", $"queryex \"{serviceName}\""); + foreach (var line in output.Split('\n')) + { + if (line.Contains("PID", StringComparison.OrdinalIgnoreCase)) + { + int colon = line.IndexOf(':'); + if (colon > 0 && int.TryParse(line.Substring(colon + 1).Trim(), out int pid)) + return pid; + } + } + } + catch { } + return 0; + } + + private static void ResetAttributesAndTakeOwnership(string path) + { + try + { + if (File.Exists(path)) + { + File.SetAttributes(path, FileAttributes.Normal); + } + else if (Directory.Exists(path)) + { + var di = new DirectoryInfo(path) { Attributes = FileAttributes.Normal }; + foreach (var info in di.GetFileSystemInfos("*", SearchOption.AllDirectories)) + { + try { info.Attributes = FileAttributes.Normal; } catch { } + } + + // Sahiplik alma (Take Ownership) + RunCommandSilent("takeown.exe", $"/f \"{path}\" /r /d y"); + RunCommandSilent("icacls.exe", $"\"{path}\" /grant administrators:F /t /c /q"); + } + } + catch { } + } + + private static void ScheduleAllForRebootDelete(string path) + { + try + { + if (File.Exists(path)) + { + Win32.MoveFileEx(path, null, Win32.MOVEFILE_DELAY_UNTIL_REBOOT); + } + else if (Directory.Exists(path)) + { + foreach (var file in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)) + { + Win32.MoveFileEx(file, null, Win32.MOVEFILE_DELAY_UNTIL_REBOOT); + } + foreach (var dir in Directory.GetDirectories(path, "*", SearchOption.AllDirectories).OrderByDescending(d => d.Length)) + { + Win32.MoveFileEx(dir, null, Win32.MOVEFILE_DELAY_UNTIL_REBOOT); + } + Win32.MoveFileEx(path, null, Win32.MOVEFILE_DELAY_UNTIL_REBOOT); + } + } + catch { } + } + + private static string RunCommandSilent(string fileName, string arguments) + { + try + { + var psi = new ProcessStartInfo(fileName, arguments) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var proc = Process.Start(psi); + if (proc == null) return string.Empty; + string output = proc.StandardOutput.ReadToEnd(); + proc.WaitForExit(3000); + return output; + } + catch + { + return string.Empty; + } + } + } +} diff --git a/src/LDUninstaller.Core/Services/ReportService.cs b/src/LDUninstaller.Core/Services/ReportService.cs new file mode 100644 index 0000000..4e68ba8 --- /dev/null +++ b/src/LDUninstaller.Core/Services/ReportService.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using LDUninstaller.Core.Models; + +namespace LDUninstaller.Core.Services +{ + public static class ReportService + { + public static string ReportsDirectory => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "LDUninstaller", + "Reports"); + + public static string GenerateHtmlReport( + IEnumerable uninstalledApps, + IEnumerable cleanedJunks, + string backupFolder) + { + try + { + if (!Directory.Exists(ReportsDirectory)) + Directory.CreateDirectory(ReportsDirectory); + + string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); + string filename = Path.Combine(ReportsDirectory, $"CleanupReport_{timestamp}.html"); + + var sb = new StringBuilder(); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine("LD Uninstaller - Kaldırma ve Temizlik Raporu"); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine("
"); + sb.AppendLine("

🛡️ LD Uninstaller - Kaldırma ve Temizlik Raporu

"); + sb.AppendLine($"
İşlem Tarihi: {DateTime.Now:yyyy-MM-dd HH:mm:ss} | Kayıt Defteri Yedek Dizini: {backupFolder}
"); + + sb.AppendLine("

📦 Kaldırılan Yazılımlar

"); + sb.AppendLine(""); + sb.AppendLine(""); + foreach (var app in uninstalledApps) + { + sb.AppendLine($""); + } + sb.AppendLine("
Yazılım AdıYayıncıSürümKaldırıcı Türü
{app.DisplayName}{app.Publisher}{app.DisplayVersion}{app.UninstallerKind}
"); + + var junkList = cleanedJunks.ToList(); + sb.AppendLine($"

🧹 Temizlenen Kalıntılar ve Artıklar ({junkList.Count} Öğe)

"); + if (junkList.Count > 0) + { + sb.AppendLine(""); + sb.AppendLine(""); + foreach (var junk in junkList) + { + sb.AppendLine($""); + } + sb.AppendLine("
TürGüvenAçıklamaYol
{junk.TypeDisplay}{junk.ConfidenceDisplay}{junk.Reason}{junk.Path}
"); + } + else + { + sb.AppendLine("

Kalıntı veya artık bulunamadı, sistem temiz.

"); + } + + sb.AppendLine("
LD Uninstaller 2.8.0 • Güvenli ve Derinlemesine Sistem Temizliği
"); + sb.AppendLine("
"); + sb.AppendLine(""); + sb.AppendLine(""); + + File.WriteAllText(filename, sb.ToString(), Encoding.UTF8); + return filename; + } + catch + { + return string.Empty; + } + } + } +} diff --git a/src/LDUninstaller.Core/Services/ShellIntegrationManager.cs b/src/LDUninstaller.Core/Services/ShellIntegrationManager.cs new file mode 100644 index 0000000..14ab943 --- /dev/null +++ b/src/LDUninstaller.Core/Services/ShellIntegrationManager.cs @@ -0,0 +1,75 @@ +using System; +using System.IO; +using Microsoft.Win32; + +namespace LDUninstaller.Core.Services +{ + public static class ShellIntegrationManager + { + public const string ContextMenuKey = "LDForceUninstall"; + public const string MenuText = "💥 LD ile Güçlü Kaldır"; + + private static readonly string[] Targets = { "Directory", "exefile", "lnkfile" }; + + public static bool IsRegistered() + { + try + { + using var key = Registry.CurrentUser.OpenSubKey($@"Software\Classes\Directory\shell\{ContextMenuKey}"); + return key != null; + } + catch + { + return false; + } + } + + public static bool Register(string appExePath) + { + if (string.IsNullOrWhiteSpace(appExePath) || !File.Exists(appExePath)) + return false; + + try + { + foreach (var target in Targets) + { + string subPath = $@"Software\Classes\{target}\shell\{ContextMenuKey}"; + using var menuKey = Registry.CurrentUser.CreateSubKey(subPath); + if (menuKey == null) continue; + + menuKey.SetValue("", MenuText, RegistryValueKind.String); + menuKey.SetValue("Icon", $"\"{appExePath}\",0", RegistryValueKind.String); + + using var cmdKey = menuKey.CreateSubKey("command"); + cmdKey?.SetValue("", $"\"{appExePath}\" --force-path \"%1\"", RegistryValueKind.String); + } + return true; + } + catch + { + return false; + } + } + + public static bool Unregister() + { + try + { + foreach (var target in Targets) + { + string subPath = $@"Software\Classes\{target}\shell"; + using var shellKey = Registry.CurrentUser.OpenSubKey(subPath, true); + shellKey?.DeleteSubKeyTree(ContextMenuKey, false); + + // Eski menü adı varsa onu da temizle + shellKey?.DeleteSubKeyTree("LDUninstaller", false); + } + return true; + } + catch + { + return false; + } + } + } +} diff --git a/src/LDUninstaller.Core/Services/UpdateChecker.cs b/src/LDUninstaller.Core/Services/UpdateChecker.cs new file mode 100644 index 0000000..bbfa2d9 --- /dev/null +++ b/src/LDUninstaller.Core/Services/UpdateChecker.cs @@ -0,0 +1,94 @@ +using System; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace LDUninstaller.Core.Services +{ + public class UpdateInfo + { + public bool HasUpdate { get; set; } + public string LatestVersion { get; set; } = string.Empty; + public string DownloadUrl { get; set; } = string.Empty; + public string HomepageUrl { get; set; } = "https://ttmadethat.shop/#ldapps"; + public string ReleaseNotes { get; set; } = string.Empty; + public string Sha256 { get; set; } = string.Empty; + } + + public static class UpdateChecker + { + private static readonly HttpClient _httpClient = new() + { + Timeout = TimeSpan.FromSeconds(5) + }; + + private static readonly string[] Endpoints = new[] + { + "https://ttmadethat.shop/ldapps/version.json", + "https://ttmadethat.shop/version.json", + "https://ttmadethat.shop/api/ldapps/version" + }; + + public static async Task CheckForUpdatesAsync(Version currentVersion, CancellationToken cancellationToken = default) + { + foreach (var url in Endpoints) + { + try + { + using var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.Add("User-Agent", "LDUninstaller-Client"); + + using var response = await _httpClient.SendAsync(request, cancellationToken); + if (!response.IsSuccessStatusCode) + continue; + + string json = await response.Content.ReadAsStringAsync(cancellationToken); + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + + string versionStr = GetStringProp(root, "version"); + string downloadUrl = GetStringProp(root, "downloadUrl"); + if (string.IsNullOrEmpty(downloadUrl)) downloadUrl = GetStringProp(root, "url"); + + string homepageUrl = GetStringProp(root, "homepageUrl"); + if (string.IsNullOrEmpty(homepageUrl)) homepageUrl = "https://ttmadethat.shop/#ldapps"; + + string notes = GetStringProp(root, "releaseNotes"); + if (string.IsNullOrEmpty(notes)) notes = GetStringProp(root, "notes"); + + string sha256 = GetStringProp(root, "sha256"); + + if (Version.TryParse(versionStr, out var remoteVer)) + { + bool hasUpdate = remoteVer > currentVersion; + return new UpdateInfo + { + HasUpdate = hasUpdate, + LatestVersion = versionStr, + DownloadUrl = string.IsNullOrEmpty(downloadUrl) ? homepageUrl : downloadUrl, + HomepageUrl = homepageUrl, + ReleaseNotes = notes, + Sha256 = sha256 + }; + } + } + catch + { + // Try next endpoint or return null if all fail + } + } + + return null; + } + + private static string GetStringProp(JsonElement element, string propName) + { + if (element.TryGetProperty(propName, out var prop)) + { + return prop.GetString() ?? string.Empty; + } + return string.Empty; + } + } +} diff --git a/src/LDUninstaller.Core/Services/WingetService.cs b/src/LDUninstaller.Core/Services/WingetService.cs new file mode 100644 index 0000000..ffe5868 --- /dev/null +++ b/src/LDUninstaller.Core/Services/WingetService.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using LDUninstaller.Core.Models; + +namespace LDUninstaller.Core.Services +{ + public class WingetUpgradeItem + { + public string Name { get; set; } = string.Empty; + public string Id { get; set; } = string.Empty; + public string Version { get; set; } = string.Empty; + public string AvailableVersion { get; set; } = string.Empty; + } + + public static class WingetService + { + public static bool IsWingetAvailable() + { + try + { + var psi = new ProcessStartInfo("winget", "--version") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var proc = Process.Start(psi); + if (proc == null) return false; + proc.WaitForExit(3000); + return proc.ExitCode == 0; + } + catch + { + return false; + } + } + + public static async Task> GetAvailableUpgradesAsync() + { + var results = new List(); + if (!IsWingetAvailable()) return results; + + await Task.Run(() => + { + try + { + var psi = new ProcessStartInfo("winget", "upgrade --include-unknown") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + StandardOutputEncoding = System.Text.Encoding.UTF8 + }; + + using var proc = Process.Start(psi); + if (proc == null) return; + + string output = proc.StandardOutput.ReadToEnd(); + proc.WaitForExit(15000); + + // Parse table output: Name | Id | Version | Available | Source + using var reader = new StringReader(output); + string? line; + bool inTable = false; + + while ((line = reader.ReadLine()) != null) + { + if (line.StartsWith("---") || line.Contains("------")) + { + inTable = true; + continue; + } + + if (!inTable || string.IsNullOrWhiteSpace(line)) continue; + + // Match columns separated by 2+ spaces + var parts = Regex.Split(line.Trim(), @"\s{2,}"); + if (parts.Length >= 4) + { + results.Add(new WingetUpgradeItem + { + Name = parts[0], + Id = parts[1], + Version = parts[2], + AvailableVersion = parts[3] + }); + } + } + } + catch { } + }); + + return results; + } + + public static string GenerateWingetExportScript(IEnumerable apps) + { + var sb = new System.Text.StringBuilder(); + sb.AppendLine("@echo off"); + sb.AppendLine("chcp 65001 >nul"); + sb.AppendLine("echo === LD Uninstaller - Toplu Yazilim Kurulum Scripti ==="); + sb.AppendLine("echo Bu script bilgisayarinizda kayitli yazilimlari Winget ile otomatik kurar."); + sb.AppendLine("echo."); + + foreach (var app in apps) + { + if (string.IsNullOrWhiteSpace(app.DisplayName) || app.SystemComponent || app.IsOrphaned) + continue; + + // Escape quotes + string safeName = app.DisplayName.Replace("\"", "").Trim(); + sb.AppendLine($"echo [{safeName}] kuruluyor..."); + sb.AppendLine($"winget install --name \"{safeName}\" -e --accept-package-agreements --accept-source-agreements"); + sb.AppendLine(); + } + + sb.AppendLine("echo Tum kurulum komutlari tamamlandi!"); + sb.AppendLine("pause"); + return sb.ToString(); + } + } +} diff --git a/src/LDUninstaller.Core/Startup/StartupManager.cs b/src/LDUninstaller.Core/Startup/StartupManager.cs index 82b0d87..252b3a0 100644 --- a/src/LDUninstaller.Core/Startup/StartupManager.cs +++ b/src/LDUninstaller.Core/Startup/StartupManager.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.ServiceProcess; +using System.Xml.Linq; using LDUninstaller.Core.Models; using Microsoft.Win32; @@ -10,15 +11,25 @@ namespace LDUninstaller.Core.Startup { public class StartupManager { + private static readonly HashSet CriticalSystemServices = new(StringComparer.OrdinalIgnoreCase) + { + "spooler", "searchindexer", "windefend", "securityhealthservice", "wuauserv", + "rpcss", "dcomlaunch", "eventlog", "plugplay", "dhcp", "dnscache", "cryptsvc", + "lanmanworkstation", "lanmanserver", "bfe", "mpssvc", "audioendpointbuilder", "audiosrv", + "samss", "lsass", "termservice", "w32time", "bits", "vss", "profsvc", "gpsvc" + }; + public static List GetAllStartupEntries() { var list = new List(); - // 1. Registry HKCU Run + // 1. Registry HKCU Run & RunOnce (F8) ScanRegistryRun(Registry.CurrentUser, @"Software\Microsoft\Windows\CurrentVersion\Run", StartupType.RegistryRun, list, isHklm: false, isWow64: false); + ScanRegistryRun(Registry.CurrentUser, @"Software\Microsoft\Windows\CurrentVersion\RunOnce", StartupType.RegistryRunOnce, list, isHklm: false, isWow64: false); - // 2. Registry HKLM Run + // 2. Registry HKLM Run & RunOnce (F8) ScanRegistryRun(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", StartupType.RegistryRun, list, isHklm: true, isWow64: false); + ScanRegistryRun(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", StartupType.RegistryRunOnce, list, isHklm: true, isWow64: false); // 3. Registry HKLM 32-bit (Wow6432Node) if (Environment.Is64BitOperatingSystem) @@ -50,7 +61,10 @@ namespace LDUninstaller.Core.Startup ScanFolder(Environment.GetFolderPath(Environment.SpecialFolder.Startup), "Kullanıcı Başlangıç Klasörü", list, isCommon: false); ScanFolder(Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup), "Tüm Kullanıcılar Başlangıç Klasörü", list, isCommon: true); - // 5. Services (3rd party automatic) + // 5. Task Scheduler Logon Tasks (F8) + ScanLogonScheduledTasks(list); + + // 6. 3rd-Party Services (Automatic/Disabled) (B20: filters critical OS services) ScanServices(list); return list; @@ -90,13 +104,17 @@ namespace LDUninstaller.Core.Startup if (ext != ".lnk" && ext != ".url" && ext != ".disabled") continue; string fileName = Path.GetFileName(file); - string displayName = Path.GetFileNameWithoutExtension(file); + string cleanFileName = fileName.EndsWith(".disabled", StringComparison.OrdinalIgnoreCase) + ? fileName.Substring(0, fileName.Length - ".disabled".Length) + : fileName; + + string displayName = Path.GetFileNameWithoutExtension(cleanFileName); bool isEnabled = !ext.Equals(".disabled", StringComparison.OrdinalIgnoreCase); - // Check StartupApproved for startup folder + // Check StartupApproved using clean original filename (B10) if (isEnabled) { - isEnabled = CheckStartupFolderApproved(fileName, isCommon); + isEnabled = CheckStartupFolderApproved(cleanFileName, isCommon); } list.Add(new StartupEntry @@ -112,6 +130,54 @@ namespace LDUninstaller.Core.Startup catch { } } + private static void ScanLogonScheduledTasks(List list) + { + try + { + string tasksDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "Tasks"); + if (!Directory.Exists(tasksDir)) return; + + foreach (var file in Directory.GetFiles(tasksDir, "*", SearchOption.AllDirectories)) + { + // Exclude standard Microsoft Windows internal tasks + if (file.Contains(@"\Tasks\Microsoft\Windows", StringComparison.OrdinalIgnoreCase)) + continue; + + try + { + string xml = File.ReadAllText(file); + if (xml.Contains(" d.Name.LocalName == "Command"); + if (execNode != null) + { + execPath = execNode.Value; + } + + bool isEnabled = !xml.Contains("false", StringComparison.OrdinalIgnoreCase); + + list.Add(new StartupEntry + { + Name = taskName, + Command = !string.IsNullOrEmpty(execPath) ? execPath : rel, + Type = StartupType.TaskScheduler, + Location = $@"Görev: \{rel}", + IsEnabled = isEnabled + }); + } + } + catch { } + } + } + catch { } + } + private static void ScanServices(List list) { try @@ -121,6 +187,10 @@ namespace LDUninstaller.Core.Startup { try { + // B20: Filter critical system services + if (CriticalSystemServices.Contains(sc.ServiceName)) + continue; + using var key = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{sc.ServiceName}"); if (key != null) { @@ -128,8 +198,7 @@ namespace LDUninstaller.Core.Startup string imgPath = key.GetValue("ImagePath")?.ToString() ?? ""; string imgLower = imgPath.ToLowerInvariant(); - // 2 = Automatic, 3 = Manual, 4 = Disabled - // Exclude internal OS services + // Exclude internal OS binaries if (!imgLower.Contains(@"\windows\system32\svchost.exe") && !imgLower.Contains(@"\windows\system32\services.exe") && !imgLower.Contains(@"\windows\system32\lsass.exe")) @@ -162,7 +231,6 @@ namespace LDUninstaller.Core.Startup string approvedSub = isWow64 ? @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run32" : @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"; - // First check HKCU using (var key = Registry.CurrentUser.OpenSubKey(approvedSub)) { if (key?.GetValue(entryName) is byte[] data && data.Length > 0) @@ -171,7 +239,6 @@ namespace LDUninstaller.Core.Startup } } - // If HKLM, also check HKLM StartupApproved if (isHklm) { using var hklmKey = Registry.LocalMachine.OpenSubKey(approvedSub); @@ -220,7 +287,7 @@ namespace LDUninstaller.Core.Startup ? 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 }; - if (entry.Type == StartupType.RegistryRun) + if (entry.Type == StartupType.RegistryRun || entry.Type == StartupType.RegistryRunOnce) { bool isWow64 = entry.Location.Contains("Wow6432Node", StringComparison.OrdinalIgnoreCase); bool isHklm = entry.Location.Contains("HKEY_LOCAL_MACHINE", StringComparison.OrdinalIgnoreCase) || entry.Location.Contains("HKLM", StringComparison.OrdinalIgnoreCase); @@ -228,13 +295,11 @@ namespace LDUninstaller.Core.Startup string approvedSub = isWow64 ? @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run32" : @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"; - // Always write to HKCU using (var key = Registry.CurrentUser.CreateSubKey(approvedSub)) { key?.SetValue(entry.Name, binaryData, RegistryValueKind.Binary); } - // If it was in HKLM, also write to HKLM if (isHklm) { try @@ -250,15 +315,18 @@ namespace LDUninstaller.Core.Startup } else if (entry.Type == StartupType.StartupFolder) { + // B10: Manage clean filename and preserve StartupApproved registration string fileName = Path.GetFileName(entry.Command); - bool isCommon = entry.Location.Contains("Tüm Kullanıcılar", StringComparison.OrdinalIgnoreCase) || entry.Location.Contains("All Users", StringComparison.OrdinalIgnoreCase); + string cleanFileName = fileName.EndsWith(".disabled", StringComparison.OrdinalIgnoreCase) + ? fileName.Substring(0, fileName.Length - ".disabled".Length) + : fileName; + bool isCommon = entry.Location.Contains("Tüm Kullanıcılar", StringComparison.OrdinalIgnoreCase) || entry.Location.Contains("All Users", StringComparison.OrdinalIgnoreCase); const string approvedFolderSub = @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder"; - // Write to StartupApproved\StartupFolder in HKCU using (var key = Registry.CurrentUser.CreateSubKey(approvedFolderSub)) { - key?.SetValue(fileName, binaryData, RegistryValueKind.Binary); + key?.SetValue(cleanFileName, binaryData, RegistryValueKind.Binary); } if (isCommon) @@ -266,38 +334,57 @@ namespace LDUninstaller.Core.Startup try { using var key = Registry.LocalMachine.CreateSubKey(approvedFolderSub); - key?.SetValue(fileName, binaryData, RegistryValueKind.Binary); + key?.SetValue(cleanFileName, binaryData, RegistryValueKind.Binary); } catch { } } - // Fallback rename if StartupApproved is not respected - try - { - if (!enable && File.Exists(entry.Command) && !entry.Command.EndsWith(".disabled", StringComparison.OrdinalIgnoreCase)) - { - string newPath = entry.Command + ".disabled"; - File.Move(entry.Command, newPath); - entry.Command = newPath; - } - else if (enable && File.Exists(entry.Command) && entry.Command.EndsWith(".disabled", StringComparison.OrdinalIgnoreCase)) - { - string newPath = entry.Command.Substring(0, entry.Command.Length - ".disabled".Length); - File.Move(entry.Command, newPath); - entry.Command = newPath; - } - } - catch { } + // Physical file rename + string dir = Path.GetDirectoryName(entry.Command) ?? ""; + string normalPath = Path.Combine(dir, cleanFileName); + string disabledPath = normalPath + ".disabled"; + if (!enable && File.Exists(normalPath)) + { + File.Move(normalPath, disabledPath, true); + entry.Command = disabledPath; + } + else if (enable && File.Exists(disabledPath)) + { + File.Move(disabledPath, normalPath, true); + entry.Command = normalPath; + } + + entry.IsEnabled = enable; + return true; + } + else if (entry.Type == StartupType.TaskScheduler) + { + // Toggle scheduled task via schtasks /change + string taskName = entry.Location.Replace("Görev: ", "").Trim(); + string state = enable ? "/ENABLE" : "/DISABLE"; + var psi = new ProcessStartInfo("schtasks.exe", $"/Change /TN \"{taskName}\" {state}") + { + CreateNoWindow = true, + UseShellExecute = false + }; + using var p = Process.Start(psi); + p?.WaitForExit(3000); entry.IsEnabled = enable; return true; } else if (entry.Type == StartupType.Service) { string svcName = !string.IsNullOrEmpty(entry.ServiceName) ? entry.ServiceName : entry.Name; + + // B20: Never allow stopping critical Windows services + if (CriticalSystemServices.Contains(svcName)) + { + return false; + } + int targetStartType = enable ? 2 : 4; // 2 = Auto, 4 = Disabled - // 1. Update Registry Start type directly try { using var key = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{svcName}", true); @@ -308,7 +395,6 @@ namespace LDUninstaller.Core.Startup } catch { } - // 2. Run sc.exe config start= auto / disabled try { string mode = enable ? "auto" : "disabled"; @@ -322,7 +408,6 @@ namespace LDUninstaller.Core.Startup } catch { } - // 3. Stop or Start the service try { using var sc = new ServiceController(svcName); diff --git a/src/LDUninstaller.Core/Tweaks/WindowsTweaks.cs b/src/LDUninstaller.Core/Tweaks/WindowsTweaks.cs index 40913a5..cd10b25 100644 --- a/src/LDUninstaller.Core/Tweaks/WindowsTweaks.cs +++ b/src/LDUninstaller.Core/Tweaks/WindowsTweaks.cs @@ -32,8 +32,22 @@ namespace LDUninstaller.Core.Tweaks }, RevertAction = () => { - using var key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows\DataCollection"); - key?.SetValue("AllowTelemetry", 1, RegistryValueKind.DWord); + EnableAndStartService("DiagTrack", 2); + EnableAndStartService("dmwappushservice", 3); + + try + { + using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Policies\Microsoft\Windows\DataCollection", true); + key?.DeleteValue("AllowTelemetry", false); + } + catch { } + + try + { + using var userKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack", true); + userKey?.DeleteValue("ShowedToastAtLevel", false); + } + catch { } } }, new DebloatTweak @@ -57,10 +71,23 @@ namespace LDUninstaller.Core.Tweaks }, 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); + try + { + 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); + } + catch { } + + try + { + using var policyKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Policies\Microsoft\Windows\Windows Search", true); + policyKey?.DeleteValue("AllowCortana", false); + policyKey?.DeleteValue("DisableWebSearch", false); + policyKey?.DeleteValue("ConnectedSearchUseWeb", false); + } + catch { } } }, new DebloatTweak @@ -165,5 +192,24 @@ namespace LDUninstaller.Core.Tweaks } catch { } } + + private static void EnableAndStartService(string serviceName, int startMode = 2) + { + try + { + using (var key = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{serviceName}", true)) + { + key?.SetValue("Start", startMode, RegistryValueKind.DWord); // 2 = Auto, 3 = Demand + } + + using var sc = new ServiceController(serviceName); + if (sc.Status != ServiceControllerStatus.Running && sc.Status != ServiceControllerStatus.StartPending) + { + sc.Start(); + sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(3)); + } + } + catch { } + } } } diff --git a/src/LDUninstaller.Launcher/Program.cs b/src/LDUninstaller.Launcher/Program.cs index 2c4624a..356d994 100644 --- a/src/LDUninstaller.Launcher/Program.cs +++ b/src/LDUninstaller.Launcher/Program.cs @@ -31,7 +31,7 @@ namespace LDUninstaller.Launcher var psi = new ProcessStartInfo { FileName = exePath, - Arguments = string.Join(" ", args), + Arguments = BuildArgumentString(args), UseShellExecute = true, Verb = "runas" }; @@ -68,7 +68,7 @@ namespace LDUninstaller.Launcher var psi = new ProcessStartInfo { FileName = uiPath, - Arguments = string.Join(" ", args), + Arguments = BuildArgumentString(args), UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(uiPath) }; @@ -90,5 +90,16 @@ namespace LDUninstaller.Launcher var principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } + + private static string BuildArgumentString(string[] args) + { + if (args == null || args.Length == 0) return string.Empty; + return string.Join(" ", args.Select(a => + { + if (string.IsNullOrEmpty(a)) return "\"\""; + if (a.Contains(" ") && !a.StartsWith("\"")) return $"\"{a}\""; + return a; + })); + } } } diff --git a/src/LDUninstaller.UI/App.xaml b/src/LDUninstaller.UI/App.xaml index 9550a79..4a740a5 100644 --- a/src/LDUninstaller.UI/App.xaml +++ b/src/LDUninstaller.UI/App.xaml @@ -4,22 +4,40 @@ StartupUri="MainWindow.xaml" ShutdownMode="OnMainWindowClose"> - - #0B0F19 - #111827 - #1F2937 - #283548 - #374151 - #4B5563 - #F9FAFB - #9CA3AF - #6B7280 - - #3B82F6 - #2563EB + + + #0F1115 + #15181E + #1A1E26 + #232833 + #2A303D + #2A303D + #3D4658 + #4F6386 + + + #F8FAFC + #CBD5E1 + #7E8B9F + #525D6F + + + #2563EB + #3B82F6 + #1D4ED8 + #60A5FA + #93C5FD + #14233C + #3B82F6 + + #10B981 - #EF4444 + #059669 + #064E3B + #F43F5E + #E11D48 #8B5CF6 + #0EA5E9 #F59E0B @@ -32,35 +50,64 @@ - + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + +