diff --git a/.gitignore b/.gitignore index c6f1b94..d7f5bdc 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ [Oo]bj/ [Ll]og/ [Ll]ogs/ +*.zip # Visual Studio / Rider / VS Code caches .vs/ diff --git a/publish/Donustur.Core.dll b/publish/Donustur.Core.dll index b8dcf08..073a55c 100644 Binary files a/publish/Donustur.Core.dll and b/publish/Donustur.Core.dll differ diff --git a/publish/Donustur.Core.pdb b/publish/Donustur.Core.pdb index 4655b45..3567d50 100644 Binary files a/publish/Donustur.Core.pdb and b/publish/Donustur.Core.pdb differ diff --git a/publish/Donustur.Engine.dll b/publish/Donustur.Engine.dll index f464b68..09e2e02 100644 Binary files a/publish/Donustur.Engine.dll and b/publish/Donustur.Engine.dll differ diff --git a/publish/Donustur.Engine.pdb b/publish/Donustur.Engine.pdb index 942f9ec..26ee774 100644 Binary files a/publish/Donustur.Engine.pdb and b/publish/Donustur.Engine.pdb differ diff --git a/publish/LDConverter.deps.json b/publish/LDConverter.deps.json index 14e7e33..f701e41 100644 --- a/publish/LDConverter.deps.json +++ b/publish/LDConverter.deps.json @@ -7,7 +7,7 @@ "targets": { ".NETCoreApp,Version=v8.0": {}, ".NETCoreApp,Version=v8.0/win-x64": { - "LDConverter/1.1.0": { + "LDConverter/1.2.0": { "dependencies": { "Donustur.Core": "1.0.0", "Donustur.Engine": "1.0.0" @@ -157,7 +157,7 @@ } }, "libraries": { - "LDConverter/1.1.0": { + "LDConverter/1.2.0": { "type": "project", "serviceable": false, "sha512": "" diff --git a/publish/LDConverter.dll b/publish/LDConverter.dll index c401d36..05d4b17 100644 Binary files a/publish/LDConverter.dll and b/publish/LDConverter.dll differ diff --git a/publish/LDConverter.exe b/publish/LDConverter.exe index 083ea40..e338991 100644 Binary files a/publish/LDConverter.exe and b/publish/LDConverter.exe differ diff --git a/publish/LDConverter.pdb b/publish/LDConverter.pdb index 05adebc..ff7625d 100644 Binary files a/publish/LDConverter.pdb and b/publish/LDConverter.pdb differ diff --git a/src/Donustur.Core/Services/HistoryStore.cs b/src/Donustur.Core/Services/HistoryStore.cs index 01d11cb..a3aab5d 100644 --- a/src/Donustur.Core/Services/HistoryStore.cs +++ b/src/Donustur.Core/Services/HistoryStore.cs @@ -92,8 +92,8 @@ public sealed class HistoryStore { _entries.RemoveRange(100, _entries.Count - 100); } - SaveInternal(); } + SaveInternal(); Changed?.Invoke(); } @@ -103,13 +103,10 @@ public sealed class HistoryStore lock (_lock) { removed = _entries.RemoveAll(e => e.Id == id) > 0; - if (removed) - { - SaveInternal(); - } } if (removed) { + SaveInternal(); Changed?.Invoke(); } } @@ -119,29 +116,38 @@ public sealed class HistoryStore lock (_lock) { _entries.Clear(); - SaveInternal(); } + SaveInternal(); Changed?.Invoke(); } private void SaveInternal() { - try + List snapshot; + lock (_lock) { - string dir = Path.GetDirectoryName(_filePath)!; - if (!Directory.Exists(dir)) - { - Directory.CreateDirectory(dir); - } + snapshot = _entries.ToList(); + } - string json = JsonSerializer.Serialize(_entries, JsonOptions); - string tmp = _filePath + ".tmp"; - File.WriteAllText(tmp, json); - File.Move(tmp, _filePath, overwrite: true); - } - catch + Task.Run(() => { - // Silently handle IO errors - } + try + { + string dir = Path.GetDirectoryName(_filePath)!; + if (!Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); + } + + string json = JsonSerializer.Serialize(snapshot, JsonOptions); + string tmp = _filePath + ".tmp"; + File.WriteAllText(tmp, json); + File.Move(tmp, _filePath, overwrite: true); + } + catch + { + // Silently handle IO errors + } + }); } } diff --git a/src/Donustur.Core/Services/PreferencesStore.cs b/src/Donustur.Core/Services/PreferencesStore.cs index 59891e2..185429b 100644 --- a/src/Donustur.Core/Services/PreferencesStore.cs +++ b/src/Donustur.Core/Services/PreferencesStore.cs @@ -58,25 +58,28 @@ public sealed class PreferencesStore public void Save(AppPreferences preferences) { - try + _current = preferences; + Changed?.Invoke(_current); + + Task.Run(() => { - _current = preferences; - string dir = Path.GetDirectoryName(_filePath)!; - if (!Directory.Exists(dir)) + try { - Directory.CreateDirectory(dir); + string dir = Path.GetDirectoryName(_filePath)!; + if (!Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); + } + + string json = JsonSerializer.Serialize(preferences, JsonOptions); + string tempFile = _filePath + ".tmp"; + File.WriteAllText(tempFile, json); + File.Move(tempFile, _filePath, overwrite: true); } - - string json = JsonSerializer.Serialize(preferences, JsonOptions); - string tempFile = _filePath + ".tmp"; - File.WriteAllText(tempFile, json); - File.Move(tempFile, _filePath, overwrite: true); - - Changed?.Invoke(_current); - } - catch - { - // Handle error silently - } + catch + { + // Handle error silently + } + }); } } diff --git a/src/Donustur.Engine/ConversionDispatcher.cs b/src/Donustur.Engine/ConversionDispatcher.cs index b175f86..b5673a6 100644 --- a/src/Donustur.Engine/ConversionDispatcher.cs +++ b/src/Donustur.Engine/ConversionDispatcher.cs @@ -34,247 +34,250 @@ public sealed class ConversionDispatcher IProgress? progress = null, CancellationToken token = default) { - task.Status = ConversionTaskStatus.Running; - - // Ayarlar ekranından değiştirilmiş olabilecek harici motor yollarını senkronize et - _officeEngine.SetCustomPath(preferences.CustomLibreOfficePath); - _mediaEngine.SetCustomPath(preferences.CustomFfmpegPath); - - if (preferences.DefaultImageQuality is >= 10 and <= 100 && task.Options.ImageQuality == 85) + return await Task.Run(async () => { - task.Options.ImageQuality = preferences.DefaultImageQuality; - } + task.Status = ConversionTaskStatus.Running; - string targetAction = task.TargetActionId.ToLowerInvariant().TrimStart('.'); - string destination = ResolveDestinationFolder(task, preferences); + // Ayarlar ekranından değiştirilmiş olabilecek harici motor yollarını senkronize et + _officeEngine.SetCustomPath(preferences.CustomLibreOfficePath); + _mediaEngine.SetCustomPath(preferences.CustomFfmpegPath); - using var transaction = new ExportTransaction(); - - try - { - var files = task.InputFiles; - if (files.Count == 0) + if (preferences.DefaultImageQuality is >= 10 and <= 100 && task.Options.ImageQuality == 85) { - throw new InvalidOperationException("İşlenecek dosya bulunamadı."); + task.Options.ImageQuality = preferences.DefaultImageQuality; } - long totalInitialBytes = FileUtils.CalculateTotalBytes(files); - IReadOnlyList generatedStagedFiles; + string targetAction = task.TargetActionId.ToLowerInvariant().TrimStart('.'); + string destination = ResolveDestinationFolder(task, preferences); - // 1. QR İşlemleri (Görsel ve PDF destekli) - if (targetAction == "qr_read") + using var transaction = new ExportTransaction(); + + try { - var qrResults = new List(); - var decodedTexts = new List(); - - for (int i = 0; i < files.Count; i++) + var files = task.InputFiles; + if (files.Count == 0) { - token.ThrowIfCancellationRequested(); - string f = files[i]; - string? text = _qrEngine.ReadQrCode(f); - if (!string.IsNullOrWhiteSpace(text)) + throw new InvalidOperationException("İşlenecek dosya bulunamadı."); + } + + long totalInitialBytes = FileUtils.CalculateTotalBytes(files); + IReadOnlyList generatedStagedFiles; + + // 1. QR İşlemleri (Görsel ve PDF destekli) + if (targetAction == "qr_read") + { + var qrResults = new List(); + var decodedTexts = new List(); + + for (int i = 0; i < files.Count; i++) { - decodedTexts.Add(text); - string txtPath = SafePaths.GetUniquePath( - transaction.StagingDirectory, - Path.GetFileNameWithoutExtension(f) + "_QR.txt"); - await File.WriteAllTextAsync(txtPath, text, token); - qrResults.Add(txtPath); + token.ThrowIfCancellationRequested(); + string f = files[i]; + string? text = _qrEngine.ReadQrCode(f); + if (!string.IsNullOrWhiteSpace(text)) + { + decodedTexts.Add(text); + string txtPath = SafePaths.GetUniquePath( + transaction.StagingDirectory, + Path.GetFileNameWithoutExtension(f) + "_QR.txt"); + await File.WriteAllTextAsync(txtPath, text, token); + qrResults.Add(txtPath); + } + progress?.Report((double)(i + 1) / files.Count * 100.0); } - progress?.Report((double)(i + 1) / files.Count * 100.0); - } - if (qrResults.Count == 0) - { - throw new InvalidOperationException("Seçilen dosyada okunabilir bir QR kod veya barkod bulunamadı."); - } + if (qrResults.Count == 0) + { + throw new InvalidOperationException("Seçilen dosyada okunabilir bir QR kod veya barkod bulunamadı."); + } - task.CurrentStatusMessage = string.Join(" | ", decodedTexts); - generatedStagedFiles = qrResults; - } - // 2. Arşiv Çıkarma - else if (targetAction == "extract_folder") - { - var extractedDirs = new List(); - foreach (var f in files) - { - string dir = await _archiveEngine.ExtractAsync(f, transaction, task.Options.ArchivePassword, progress, token); - extractedDirs.Add(dir); + task.CurrentStatusMessage = string.Join(" | ", decodedTexts); + generatedStagedFiles = qrResults; } - generatedStagedFiles = extractedDirs; - } - // 3. ZIP Paketleme / Arşiv Dönüştürme - else if (targetAction == "zip") - { - string zip = await _archiveEngine.CreateZipAsync(files, transaction, null, progress, token); - generatedStagedFiles = new[] { zip }; - } - // 4. 7Z Paketleme / Arşiv Dönüştürme - else if (targetAction == "7z") - { - string sevenZ = await _archiveEngine.Create7zAsync(files, transaction, null, progress, token); - generatedStagedFiles = new[] { sevenZ }; - } - // 5. TAR.GZ Paketleme / Arşiv Dönüştürme - else if (targetAction == "tar_gz") - { - string tarGz = await _archiveEngine.CreateTarGzAsync(files, transaction, null, progress, token); - generatedStagedFiles = new[] { tarGz }; - } - // 6. Yeni Klasöre Toplama - else if (targetAction == "copy_folder") - { - string folder = await _archiveEngine.CollectToFolderAsync(files, transaction, progress, token); - generatedStagedFiles = new[] { folder }; - } - // 7. PDF veya Görsel Birleştirme - else if (targetAction == "pdf_merge") - { - if (files.All(FormatCatalog.IsImage)) + // 2. Arşiv Çıkarma + else if (targetAction == "extract_folder") { - generatedStagedFiles = await _imageEngine.ConvertImagesAsync(files, "pdf", transaction, task.Options, progress, token); + var extractedDirs = new List(); + foreach (var f in files) + { + string dir = await _archiveEngine.ExtractAsync(f, transaction, task.Options.ArchivePassword, progress, token); + extractedDirs.Add(dir); + } + generatedStagedFiles = extractedDirs; + } + // 3. ZIP Paketleme / Arşiv Dönüştürme + else if (targetAction == "zip") + { + string zip = await _archiveEngine.CreateZipAsync(files, transaction, null, progress, token); + generatedStagedFiles = new[] { zip }; + } + // 4. 7Z Paketleme / Arşiv Dönüştürme + else if (targetAction == "7z") + { + string sevenZ = await _archiveEngine.Create7zAsync(files, transaction, null, progress, token); + generatedStagedFiles = new[] { sevenZ }; + } + // 5. TAR.GZ Paketleme / Arşiv Dönüştürme + else if (targetAction == "tar_gz") + { + string tarGz = await _archiveEngine.CreateTarGzAsync(files, transaction, null, progress, token); + generatedStagedFiles = new[] { tarGz }; + } + // 6. Yeni Klasöre Toplama + else if (targetAction == "copy_folder") + { + string folder = await _archiveEngine.CollectToFolderAsync(files, transaction, progress, token); + generatedStagedFiles = new[] { folder }; + } + // 7. PDF veya Görsel Birleştirme + else if (targetAction == "pdf_merge") + { + if (files.All(FormatCatalog.IsImage)) + { + generatedStagedFiles = await _imageEngine.ConvertImagesAsync(files, "pdf", transaction, task.Options, progress, token); + } + else + { + var mergeable = files.Where(f => FormatCatalog.IsPdf(f) || FormatCatalog.IsImage(f)).ToList(); + if (mergeable.Count == 0) + { + throw new InvalidOperationException("PDF olarak birleştirmek için en az bir PDF veya görsel dosyası seçilmelidir."); + } + string merged = await _pdfEngine.MergePdfsAsync(mergeable, transaction, null, progress, token); + generatedStagedFiles = new[] { merged }; + } + } + // 8. PDF Sayfa Ayırma + else if (targetAction == "pdf_split") + { + var splitFiles = new List(); + foreach (var f in files.Where(FormatCatalog.IsPdf)) + { + var pages = await _pdfEngine.SplitPdfAsync(f, transaction, progress, token); + splitFiles.AddRange(pages); + } + generatedStagedFiles = splitFiles; + } + // 9. PDF'den Metin Çıkarma + else if (targetAction == "pdf_to_txt") + { + var txts = new List(); + foreach (var f in files) + { + string txt = await _pdfEngine.ExtractTextAsync(f, transaction, progress, token); + txts.Add(txt); + } + generatedStagedFiles = txts; + } + // 10. PDF'den Word (DOCX) Belgesine Dönüştürme + else if (targetAction == "pdf_to_docx") + { + var docxs = new List(); + foreach (var f in files) + { + string docx = await _pdfEngine.ConvertToDocxAsync(f, transaction, progress, token); + docxs.Add(docx); + } + generatedStagedFiles = docxs; + } + // 11. PDF'den Görsele (PNG veya JPG) Aktarma + else if (targetAction is "pdf_to_images" or "pdf_to_jpg") + { + string imgFormat = targetAction == "pdf_to_jpg" ? "jpg" : "png"; + var imgs = new List(); + foreach (var f in files) + { + var extracted = await _pdfEngine.ExtractImagesAsync(f, transaction, progress, token, imgFormat); + imgs.AddRange(extracted); + } + generatedStagedFiles = imgs; + } + // 12. Görsel İşlemleri (PNG, JPG, WEBP, AVIF, ICO, Çoklu Görsel -> GIF/PDF vb.) + else if (files.All(FormatCatalog.IsImage) && + targetAction is "png" or "jpg" or "webp" or "avif" or "ico" or "bmp" or "tiff" or "gif" or "pdf" or "compress_image") + { + generatedStagedFiles = await _imageEngine.ConvertImagesAsync(files, targetAction, transaction, task.Options, progress, token); + } + // 13. Video ve Ses Dönüşümleri + else if (files.Any(FormatCatalog.IsVideo) || files.Any(FormatCatalog.IsAudio) || + targetAction is "mp4" or "mp3" or "wav" or "aac" or "flac" or "ogg" or "mkv" or "webm" or "compress_video" or "compress_audio") + { + generatedStagedFiles = await _mediaEngine.ConvertMediaAsync(files, targetAction, transaction, task.Options, progress, token); + } + // 14. Ofis Belgeleri (DOCX, PPTX, XLSX, ODT, TXT, MD, HTML vb.) + else if (files.All(FormatCatalog.IsDocument) || targetAction is "docx" or "txt" or "html") + { + generatedStagedFiles = await _officeEngine.ConvertDocumentsAsync(files, targetAction, transaction, progress, token); + } + // 15. Tekil Görsel Yedeği + else if (targetAction is "png" or "jpg" or "webp" or "avif" or "ico" or "compress_image") + { + generatedStagedFiles = await _imageEngine.ConvertImagesAsync(files, targetAction, transaction, task.Options, progress, token); } else { - var mergeable = files.Where(f => FormatCatalog.IsPdf(f) || FormatCatalog.IsImage(f)).ToList(); - if (mergeable.Count == 0) - { - throw new InvalidOperationException("PDF olarak birleştirmek için en az bir PDF veya görsel dosyası seçilmelidir."); - } - string merged = await _pdfEngine.MergePdfsAsync(mergeable, transaction, null, progress, token); - generatedStagedFiles = new[] { merged }; + // Genel ZIP arşivleme yedeği + string zip = await _archiveEngine.CreateZipAsync(files, transaction, null, progress, token); + generatedStagedFiles = new[] { zip }; } - } - // 8. PDF Sayfa Ayırma - else if (targetAction == "pdf_split") - { - var splitFiles = new List(); - foreach (var f in files.Where(FormatCatalog.IsPdf)) + + // Dosyaları nihai hedef klasöre taşı (Commit) + var finalCommittedPaths = transaction.CommitTo(destination, task.Options.OverwriteExisting); + long totalFinalBytes = FileUtils.CalculateTotalBytes(finalCommittedPaths); + + task.Status = ConversionTaskStatus.Completed; + task.CompletedAt = DateTime.Now; + task.OutputFiles.AddRange(finalCommittedPaths); + + string sourceLabel = files.Count == 1 + ? FormatCatalog.NormalizeExtension(files[0]).ToUpperInvariant() + : $"{files.Count} ÖĞE"; + string targetLabel = FormatFriendlyActionLabel(targetAction); + + _historyStore?.Add(new HistoryEntry { - var pages = await _pdfEngine.SplitPdfAsync(f, transaction, progress, token); - splitFiles.AddRange(pages); - } - generatedStagedFiles = splitFiles; + Title = files.Count == 1 + ? Path.GetFileName(files[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) + : $"{files.Count} öğe ({Path.GetFileName(files[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))}...)", + FormatSummary = $"{sourceLabel} → {targetLabel}", + InputFiles = files.ToList(), + OutputFiles = finalCommittedPaths.ToList(), + OriginalSizeBytes = totalInitialBytes, + OutputSizeBytes = totalFinalBytes, + Timestamp = DateTime.Now, + Success = true + }); + + return new ConversionResult(true, finalCommittedPaths, null, task.Duration); } - // 9. PDF'den Metin Çıkarma - else if (targetAction == "pdf_to_txt") + catch (OperationCanceledException) { - var txts = new List(); - foreach (var f in files) + task.Status = ConversionTaskStatus.Cancelled; + task.CompletedAt = DateTime.Now; + return new ConversionResult(false, Array.Empty(), "İşlem kullanıcı tarafından iptal edildi."); + } + catch (Exception ex) + { + task.Status = ConversionTaskStatus.Failed; + task.CompletedAt = DateTime.Now; + task.ErrorMessage = ex.Message; + + _historyStore?.Add(new HistoryEntry { - string txt = await _pdfEngine.ExtractTextAsync(f, transaction, progress, token); - txts.Add(txt); - } - generatedStagedFiles = txts; - } - // 10. PDF'den Word (DOCX) Belgesine Dönüştürme - else if (targetAction == "pdf_to_docx") - { - var docxs = new List(); - foreach (var f in files) - { - string docx = await _pdfEngine.ConvertToDocxAsync(f, transaction, progress, token); - docxs.Add(docx); - } - generatedStagedFiles = docxs; - } - // 11. PDF'den Görsele (PNG veya JPG) Aktarma - else if (targetAction is "pdf_to_images" or "pdf_to_jpg") - { - string imgFormat = targetAction == "pdf_to_jpg" ? "jpg" : "png"; - var imgs = new List(); - foreach (var f in files) - { - var extracted = await _pdfEngine.ExtractImagesAsync(f, transaction, progress, token, imgFormat); - imgs.AddRange(extracted); - } - generatedStagedFiles = imgs; - } - // 12. Görsel İşlemleri (PNG, JPG, WEBP, AVIF, ICO, Çoklu Görsel -> GIF/PDF vb.) - else if (files.All(FormatCatalog.IsImage) && - targetAction is "png" or "jpg" or "webp" or "avif" or "ico" or "bmp" or "tiff" or "gif" or "pdf" or "compress_image") - { - generatedStagedFiles = await _imageEngine.ConvertImagesAsync(files, targetAction, transaction, task.Options, progress, token); - } - // 13. Video ve Ses Dönüşümleri - else if (files.Any(FormatCatalog.IsVideo) || files.Any(FormatCatalog.IsAudio) || - targetAction is "mp4" or "mp3" or "wav" or "aac" or "flac" or "ogg" or "mkv" or "webm" or "compress_video" or "compress_audio") - { - generatedStagedFiles = await _mediaEngine.ConvertMediaAsync(files, targetAction, transaction, task.Options, progress, token); - } - // 14. Ofis Belgeleri (DOCX, PPTX, XLSX, ODT, TXT, MD, HTML vb.) - else if (files.All(FormatCatalog.IsDocument) || targetAction is "docx" or "txt" or "html") - { - generatedStagedFiles = await _officeEngine.ConvertDocumentsAsync(files, targetAction, transaction, progress, token); - } - // 15. Tekil Görsel Yedeği - else if (targetAction is "png" or "jpg" or "webp" or "avif" or "ico" or "compress_image") - { - generatedStagedFiles = await _imageEngine.ConvertImagesAsync(files, targetAction, transaction, task.Options, progress, token); - } - else - { - // Genel ZIP arşivleme yedeği - string zip = await _archiveEngine.CreateZipAsync(files, transaction, null, progress, token); - generatedStagedFiles = new[] { zip }; - } + Title = task.InputFiles.Count == 1 + ? Path.GetFileName(task.InputFiles[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) + : $"{task.InputFiles.Count} dosya", + FormatSummary = FormatFriendlyActionLabel(targetAction), + InputFiles = task.InputFiles.ToList(), + OutputFiles = new List(), + Timestamp = DateTime.Now, + Success = false, + ErrorMessage = ex.Message + }); - // Dosyaları nihai hedef klasöre taşı (Commit) - var finalCommittedPaths = transaction.CommitTo(destination, task.Options.OverwriteExisting); - long totalFinalBytes = FileUtils.CalculateTotalBytes(finalCommittedPaths); - - task.Status = ConversionTaskStatus.Completed; - task.CompletedAt = DateTime.Now; - task.OutputFiles.AddRange(finalCommittedPaths); - - string sourceLabel = files.Count == 1 - ? FormatCatalog.NormalizeExtension(files[0]).ToUpperInvariant() - : $"{files.Count} ÖĞE"; - string targetLabel = FormatFriendlyActionLabel(targetAction); - - _historyStore?.Add(new HistoryEntry - { - Title = files.Count == 1 - ? Path.GetFileName(files[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) - : $"{files.Count} öğe ({Path.GetFileName(files[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))}...)", - FormatSummary = $"{sourceLabel} → {targetLabel}", - InputFiles = files.ToList(), - OutputFiles = finalCommittedPaths.ToList(), - OriginalSizeBytes = totalInitialBytes, - OutputSizeBytes = totalFinalBytes, - Timestamp = DateTime.Now, - Success = true - }); - - return new ConversionResult(true, finalCommittedPaths, null, task.Duration); - } - catch (OperationCanceledException) - { - task.Status = ConversionTaskStatus.Cancelled; - task.CompletedAt = DateTime.Now; - return new ConversionResult(false, Array.Empty(), "İşlem kullanıcı tarafından iptal edildi."); - } - catch (Exception ex) - { - task.Status = ConversionTaskStatus.Failed; - task.CompletedAt = DateTime.Now; - task.ErrorMessage = ex.Message; - - _historyStore?.Add(new HistoryEntry - { - Title = task.InputFiles.Count == 1 - ? Path.GetFileName(task.InputFiles[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) - : $"{task.InputFiles.Count} dosya", - FormatSummary = FormatFriendlyActionLabel(targetAction), - InputFiles = task.InputFiles.ToList(), - OutputFiles = new List(), - Timestamp = DateTime.Now, - Success = false, - ErrorMessage = ex.Message - }); - - return new ConversionResult(false, Array.Empty(), ex.Message, task.Duration); - } + return new ConversionResult(false, Array.Empty(), ex.Message, task.Duration); + } + }, token); } private static string FormatFriendlyActionLabel(string action) diff --git a/src/Donustur.Engine/ProcessRunner.cs b/src/Donustur.Engine/ProcessRunner.cs index 116206b..0570eca 100644 --- a/src/Donustur.Engine/ProcessRunner.cs +++ b/src/Donustur.Engine/ProcessRunner.cs @@ -39,13 +39,28 @@ public static class ProcessRunner using var process = new Process { StartInfo = psi, EnableRaisingEvents = true }; var stdOut = new StringBuilder(); var stdErr = new StringBuilder(); + long lastReportTicks = 0; + + void ReportThrottled(string line) + { + if (outputProgress == null) return; + long now = Environment.TickCount64; + if (now - Interlocked.Read(ref lastReportTicks) >= 60) // En fazla ~16 FPS raporlama (WPF Dispatcher koruması) + { + Interlocked.Exchange(ref lastReportTicks, now); + outputProgress.Report(line); + } + } process.OutputDataReceived += (_, e) => { if (e.Data != null) { - stdOut.AppendLine(e.Data); - outputProgress?.Report(e.Data); + lock (stdOut) + { + stdOut.AppendLine(e.Data); + } + ReportThrottled(e.Data); } }; @@ -53,8 +68,11 @@ public static class ProcessRunner { if (e.Data != null) { - stdErr.AppendLine(e.Data); - outputProgress?.Report(e.Data); + lock (stdErr) + { + stdErr.AppendLine(e.Data); + } + ReportThrottled(e.Data); } }; diff --git a/src/Donustur.UI/Controls/RadialWheelControl.cs b/src/Donustur.UI/Controls/RadialWheelControl.cs index 70a3e1e..4bb630f 100644 --- a/src/Donustur.UI/Controls/RadialWheelControl.cs +++ b/src/Donustur.UI/Controls/RadialWheelControl.cs @@ -2,7 +2,6 @@ using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Media; -using System.Windows.Media.Animation; using Donustur.Core.Math; using Donustur.Core.Models; @@ -75,11 +74,89 @@ public sealed class RadialWheelControl : Control public double OuterRadius { get; set; } = 175.0; public double InnerRadius { get; set; } = 48.0; + // --- Performans ve Akışkanlık İçin Dondurulmuş (Frozen) Grafik Nesneleri --- + private static readonly RadialGradientBrush GlowBrush; + private static readonly LinearGradientBrush ActiveSegmentBrush; + private static readonly Pen ActiveSegmentPen; + private static readonly SolidColorBrush DefaultSegmentBrush; + private static readonly Pen DefaultSegmentPen; + + private static readonly RadialGradientBrush HubShadowBrush; + private static readonly SolidColorBrush HubFillBrush; + private static readonly Pen HubBorderPen; + + private static readonly Typeface SegmentTypefaceRegular; + private static readonly Typeface SegmentTypefaceBold; + private static readonly Typeface HubTitleTypeface; + private static readonly Typeface HubSubtitleTypeface; + + private static readonly SolidColorBrush TextWhiteBrush; + private static readonly SolidColorBrush TextNormalBrush; + private static readonly SolidColorBrush TextSubBrush; + static RadialWheelControl() { DefaultStyleKeyProperty.OverrideMetadata( typeof(RadialWheelControl), new FrameworkPropertyMetadata(typeof(RadialWheelControl))); + + // Arka plan parlaması (Glow) + GlowBrush = new RadialGradientBrush + { + GradientOrigin = new Point(0.5, 0.5), + Center = new Point(0.5, 0.5), + RadiusX = 0.5, + RadiusY = 0.5 + }; + GlowBrush.GradientStops.Add(new GradientStop(Color.FromArgb(40, 99, 102, 241), 0.3)); + GlowBrush.GradientStops.Add(new GradientStop(Colors.Transparent, 1.0)); + GlowBrush.Freeze(); + + // Aktif dilim fırçası ve kalemi + ActiveSegmentBrush = new LinearGradientBrush( + Color.FromRgb(99, 102, 241), + Color.FromRgb(14, 165, 233), + new Point(0, 0), + new Point(1, 1)); + ActiveSegmentBrush.Freeze(); + + ActiveSegmentPen = new Pen(new SolidColorBrush(Color.FromArgb(220, 255, 255, 255)), 2.0); + ActiveSegmentPen.Brush.Freeze(); + ActiveSegmentPen.Freeze(); + + // Varsayılan dilim fırçası ve kalemi + DefaultSegmentBrush = new SolidColorBrush(Color.FromArgb(200, 24, 27, 36)); + DefaultSegmentBrush.Freeze(); + + DefaultSegmentPen = new Pen(new SolidColorBrush(Color.FromArgb(70, 255, 255, 255)), 1.0); + DefaultSegmentPen.Brush.Freeze(); + DefaultSegmentPen.Freeze(); + + // Merkez gösterge (Hub) + HubShadowBrush = new RadialGradientBrush(); + HubShadowBrush.GradientStops.Add(new GradientStop(Color.FromArgb(160, 0, 0, 0), 0.7)); + HubShadowBrush.GradientStops.Add(new GradientStop(Colors.Transparent, 1.0)); + HubShadowBrush.Freeze(); + + HubFillBrush = new SolidColorBrush(Color.FromRgb(18, 20, 28)); + HubFillBrush.Freeze(); + + HubBorderPen = new Pen(new SolidColorBrush(Color.FromArgb(120, 99, 102, 241)), 2.0); + HubBorderPen.Brush.Freeze(); + HubBorderPen.Freeze(); + + // Tipografiler + SegmentTypefaceRegular = new Typeface(new FontFamily("Segoe UI Variable Display, Segoe UI, Arial"), FontStyles.Normal, FontWeights.SemiBold, FontStretches.Normal); + SegmentTypefaceBold = new Typeface(new FontFamily("Segoe UI Variable Display, Segoe UI, Arial"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); + HubTitleTypeface = new Typeface(new FontFamily("Segoe UI Variable Display, Segoe UI"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); + HubSubtitleTypeface = new Typeface(new FontFamily("Segoe UI Variable Display, Segoe UI"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); + + // Metin fırçaları + TextWhiteBrush = Brushes.White; + TextNormalBrush = new SolidColorBrush(Color.FromRgb(220, 225, 235)); + TextNormalBrush.Freeze(); + TextSubBrush = new SolidColorBrush(Color.FromRgb(156, 163, 175)); + TextSubBrush.Freeze(); } public RadialWheelControl() @@ -109,16 +186,7 @@ public sealed class RadialWheelControl : Control double gapDegrees = total > 1 ? 2.5 : 0.0; // Arka plan parlaması (Glow) - var glowBrush = new RadialGradientBrush - { - GradientOrigin = new Point(0.5, 0.5), - Center = new Point(0.5, 0.5), - RadiusX = 0.5, - RadiusY = 0.5 - }; - glowBrush.GradientStops.Add(new GradientStop(Color.FromArgb(40, 99, 102, 241), 0.3)); - glowBrush.GradientStops.Add(new GradientStop(Colors.Transparent, 1.0)); - dc.DrawEllipse(glowBrush, null, new Point(centerX, centerY), OuterRadius + 10, OuterRadius + 10); + dc.DrawEllipse(GlowBrush, null, new Point(centerX, centerY), OuterRadius + 10, OuterRadius + 10); // Dilimleri çiz for (int i = 0; i < total; i++) @@ -137,27 +205,8 @@ public sealed class RadialWheelControl : Control InnerRadius, isHovered ? OuterRadius + 5 : OuterRadius, startAngle, sweepAngle); - Brush fillBrush; - Pen borderPen; - - if (isHovered) - { - // Vurgulu modern gradyan - var activeBrush = new LinearGradientBrush - { - StartPoint = new Point(0, 0), - EndPoint = new Point(1, 1) - }; - activeBrush.GradientStops.Add(new GradientStop(Color.FromRgb(99, 102, 241), 0.0)); // Indigo - activeBrush.GradientStops.Add(new GradientStop(Color.FromRgb(14, 165, 233), 1.0)); // Sky blue - fillBrush = activeBrush; - borderPen = new Pen(new SolidColorBrush(Color.FromArgb(220, 255, 255, 255)), 2.0); - } - else - { - fillBrush = new SolidColorBrush(Color.FromArgb(200, 24, 27, 36)); - borderPen = new Pen(new SolidColorBrush(Color.FromArgb(70, 255, 255, 255)), 1.0); - } + Brush fillBrush = isHovered ? ActiveSegmentBrush : DefaultSegmentBrush; + Pen borderPen = isHovered ? ActiveSegmentPen : DefaultSegmentPen; dc.DrawGeometry(fillBrush, borderPen, geom); @@ -174,10 +223,8 @@ public sealed class RadialWheelControl : Control private void DrawSegmentLabel(DrawingContext dc, string text, double x, double y, bool isHovered) { - var typeface = new Typeface(new FontFamily("Segoe UI Variable Display, Segoe UI, Arial"), - FontStyles.Normal, - isHovered ? FontWeights.Bold : FontWeights.SemiBold, - FontStretches.Normal); + var typeface = isHovered ? SegmentTypefaceBold : SegmentTypefaceRegular; + var brush = isHovered ? TextWhiteBrush : TextNormalBrush; var ft = new FormattedText( text, @@ -185,7 +232,7 @@ public sealed class RadialWheelControl : Control FlowDirection.LeftToRight, typeface, isHovered ? 14 : 12.5, - isHovered ? Brushes.White : new SolidColorBrush(Color.FromRgb(220, 225, 235)), + brush, 1.0); dc.DrawText(ft, new Point(x - (ft.Width / 2.0), y - (ft.Height / 2.0))); @@ -194,15 +241,10 @@ public sealed class RadialWheelControl : Control private void DrawCenterHub(DrawingContext dc, double centerX, double centerY) { // Merkez gölge - var hubShadow = new RadialGradientBrush(); - hubShadow.GradientStops.Add(new GradientStop(Color.FromArgb(160, 0, 0, 0), 0.7)); - hubShadow.GradientStops.Add(new GradientStop(Colors.Transparent, 1.0)); - dc.DrawEllipse(hubShadow, null, new Point(centerX, centerY), InnerRadius + 6, InnerRadius + 6); + dc.DrawEllipse(HubShadowBrush, null, new Point(centerX, centerY), InnerRadius + 6, InnerRadius + 6); // Merkez arkaplan - var hubFill = new SolidColorBrush(Color.FromRgb(18, 20, 28)); - var hubPen = new Pen(new SolidColorBrush(Color.FromArgb(120, 99, 102, 241)), 2.0); - dc.DrawEllipse(hubFill, hubPen, new Point(centerX, centerY), InnerRadius, InnerRadius); + dc.DrawEllipse(HubFillBrush, HubBorderPen, new Point(centerX, centerY), InnerRadius, InnerRadius); // Merkez metin string centerTitle; @@ -220,26 +262,24 @@ public sealed class RadialWheelControl : Control centerSubtitle = FileCount > 0 ? $"{FileCount} dosya" : "Bırakın"; } - var typefaceBold = new Typeface(new FontFamily("Segoe UI Variable Display, Segoe UI"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); var titleFt = new FormattedText( centerTitle, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, - typefaceBold, + HubTitleTypeface, 11.0, - Brushes.White, + TextWhiteBrush, 1.0); dc.DrawText(titleFt, new Point(centerX - (titleFt.Width / 2.0), centerY - 13)); - var typefaceRegular = new Typeface(new FontFamily("Segoe UI Variable Display, Segoe UI"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); var subFt = new FormattedText( centerSubtitle, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, - typefaceRegular, + HubSubtitleTypeface, 9.5, - new SolidColorBrush(Color.FromRgb(156, 163, 175)), + TextSubBrush, 1.0); dc.DrawText(subFt, new Point(centerX - (subFt.Width / 2.0), centerY + 3)); @@ -272,6 +312,7 @@ public sealed class RadialWheelControl : Control var geom = new PathGeometry(); geom.Figures.Add(figure); + geom.Freeze(); // GPU donanım hızlandırma ve sıfır GC tahsisi için dondur return geom; } } diff --git a/src/Donustur.UI/Donustur.UI.csproj b/src/Donustur.UI/Donustur.UI.csproj index 4cff925..996ab3b 100644 --- a/src/Donustur.UI/Donustur.UI.csproj +++ b/src/Donustur.UI/Donustur.UI.csproj @@ -15,7 +15,7 @@ LDConverter LD Converter LD Converter - 1.1.0 + 1.2.0 Assets\app.ico enable enable diff --git a/src/Donustur.UI/MainWindow.xaml.cs b/src/Donustur.UI/MainWindow.xaml.cs index 499869f..0172a49 100644 --- a/src/Donustur.UI/MainWindow.xaml.cs +++ b/src/Donustur.UI/MainWindow.xaml.cs @@ -210,21 +210,37 @@ public partial class MainWindow : Window EmptyPrompt.Visibility = Visibility.Collapsed; SelectedFilesPanel.Visibility = Visibility.Visible; - long totalBytes = FileUtils.CalculateTotalBytes(_selectedFiles); FilesCountLabel.Text = _selectedFiles.Count == 1 ? Path.GetFileName(_selectedFiles[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) : $"{_selectedFiles.Count} öğe seçildi"; - FilesSubLabel.Text = $"Toplam Boyut: {FileUtils.FormatBytes(totalBytes)}"; + FilesSubLabel.Text = "Boyut hesaplanıyor..."; RenderSelectedFileItems(); RebuildFormatChips(); + + // Toplam boyutu arka planda hesaplayarak UI'ı anında akıcı tut + var filesToMeasure = _selectedFiles.ToList(); + Task.Run(() => + { + long totalBytes = FileUtils.CalculateTotalBytes(filesToMeasure); + Dispatcher.BeginInvoke(() => + { + if (_selectedFiles.Count == filesToMeasure.Count) + { + FilesSubLabel.Text = $"Toplam Boyut: {FileUtils.FormatBytes(totalBytes)}"; + } + }); + }); } private void RenderSelectedFileItems() { SelectedFileItemsStack.Children.Clear(); - foreach (var filePath in _selectedFiles) + int maxVisible = 25; + var displayItems = _selectedFiles.Take(maxVisible).ToList(); + + foreach (var filePath in displayItems) { var row = new Border { @@ -256,10 +272,27 @@ public partial class MainWindow : Window DockPanel.SetDock(removeBtn, Dock.Right); dock.Children.Add(removeBtn); - long itemSize = FileUtils.CalculateTotalBytes(new[] { filePath }); + bool isDir = Directory.Exists(filePath); + string sizeStr; + try + { + if (!isDir && File.Exists(filePath)) + { + sizeStr = FileUtils.FormatBytes(new FileInfo(filePath).Length); + } + else + { + sizeStr = "Klasör"; + } + } + catch + { + sizeStr = "-"; + } + var sizeText = new TextBlock { - Text = FileUtils.FormatBytes(itemSize), + Text = sizeStr, FontSize = 11, Foreground = new SolidColorBrush(Color.FromRgb(107, 114, 128)), VerticalAlignment = VerticalAlignment.Center, @@ -268,7 +301,6 @@ public partial class MainWindow : Window DockPanel.SetDock(sizeText, Dock.Right); dock.Children.Add(sizeText); - bool isDir = Directory.Exists(filePath); string displayName = Path.GetFileName(filePath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); var nameText = new TextBlock { @@ -284,6 +316,26 @@ public partial class MainWindow : Window row.Child = dock; SelectedFileItemsStack.Children.Add(row); } + + if (_selectedFiles.Count > maxVisible) + { + var moreBadge = new Border + { + Background = new SolidColorBrush(Color.FromArgb(50, 99, 102, 241)), + CornerRadius = new CornerRadius(6), + Padding = new Thickness(10, 6, 10, 6), + Margin = new Thickness(0, 2, 0, 0), + HorizontalAlignment = HorizontalAlignment.Center + }; + moreBadge.Child = new TextBlock + { + Text = $"+ {_selectedFiles.Count - maxVisible} dosya daha seçili", + FontSize = 11.5, + FontWeight = FontWeights.SemiBold, + Foreground = new SolidColorBrush(Color.FromRgb(165, 180, 252)) + }; + SelectedFileItemsStack.Children.Add(moreBadge); + } } private void RebuildFormatChips() @@ -353,11 +405,8 @@ public partial class MainWindow : Window var progress = new Progress(val => { - Dispatcher.Invoke(() => - { - MainProgressBar.Value = val; - CurrentTaskStatusLabel.Text = $"{_selectedTool.DisplayName} işleniyor (%{val:F0})..."; - }); + MainProgressBar.Value = val; + CurrentTaskStatusLabel.Text = $"{_selectedTool.DisplayName} işleniyor (%{val:F0})..."; }); var task = new ConversionTask @@ -532,7 +581,7 @@ public partial class MainWindow : Window }; string? firstOut = entry.OutputFiles.FirstOrDefault(); - if (!string.IsNullOrWhiteSpace(firstOut) && (File.Exists(firstOut) || Directory.Exists(firstOut))) + if (!string.IsNullOrWhiteSpace(firstOut)) { var openFolderBtn = new Button { @@ -546,7 +595,17 @@ public partial class MainWindow : Window BorderThickness = new Thickness(0) }; string targetPath = firstOut; - openFolderBtn.Click += (_, _) => DesktopGeometry.RevealInExplorer(targetPath); + openFolderBtn.Click += (_, _) => + { + if (File.Exists(targetPath) || Directory.Exists(targetPath)) + { + DesktopGeometry.RevealInExplorer(targetPath); + } + else + { + MessageBox.Show("Hedef dosya veya klasör artık mevcut değil.", "Bilgi", MessageBoxButton.OK, MessageBoxImage.Information); + } + }; btnStack.Children.Add(openFolderBtn); } diff --git a/src/Donustur.UI/Services/GlobalDragController.cs b/src/Donustur.UI/Services/GlobalDragController.cs index 6878de4..d593643 100644 --- a/src/Donustur.UI/Services/GlobalDragController.cs +++ b/src/Donustur.UI/Services/GlobalDragController.cs @@ -1,4 +1,5 @@ using System.Runtime.InteropServices; +using System.Threading; using System.Windows; using System.Windows.Interop; using System.Windows.Threading; @@ -19,6 +20,9 @@ public sealed class GlobalDragController : IDisposable [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); + [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; } @@ -31,32 +35,39 @@ public sealed class GlobalDragController : IDisposable private readonly PreferencesStore _preferencesStore; private readonly Action> _onDropped; - private readonly DispatcherTimer _pollTimer; + private readonly System.Threading.Timer _backgroundTimer; private bool _isDragging; private bool _suppressedForCurrentDrag; private POINT _dragStartPos; private WheelWindow? _activeWheel; + private IntPtr _activeWheelHwnd = IntPtr.Zero; + private int _isDispatchingPos; + private bool _isDisposed; public GlobalDragController(PreferencesStore preferencesStore, Action> onDropped) { _preferencesStore = preferencesStore; _onDropped = onDropped; - // 30 ms (~33 FPS) sorgulama aralığı: CPU kullanımı %0.01 seviyesindedir. - _pollTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(30) }; - _pollTimer.Tick += OnPollTick; - _pollTimer.Start(); + // UI iş parçacığını asla meşgul etmeyen, arka plan iş parçacığı zamanlayıcısı (25ms ~ 40Hz) + _backgroundTimer = new System.Threading.Timer(OnBackgroundTick, null, 25, 25); } - private void OnPollTick(object? sender, EventArgs e) + private void OnBackgroundTick(object? state) { + if (_isDisposed) return; + if (!_preferencesStore.Current.Enabled) { if (_activeWheel != null) { - _activeWheel.CancelAndClose(); - _activeWheel = null; + DispatchToUi(() => + { + _activeWheel?.CancelAndClose(); + _activeWheel = null; + _activeWheelHwnd = IntPtr.Zero; + }); } _isDragging = false; _suppressedForCurrentDrag = false; @@ -70,8 +81,12 @@ public sealed class GlobalDragController : IDisposable // Sağ tık veya ESC ile çarkı iptal et if (_activeWheel != null && (rightDown || escapeDown)) { - _activeWheel.CancelAndClose(); - _activeWheel = null; + DispatchToUi(() => + { + _activeWheel?.CancelAndClose(); + _activeWheel = null; + _activeWheelHwnd = IntPtr.Zero; + }); _suppressedForCurrentDrag = true; return; } @@ -84,8 +99,15 @@ public sealed class GlobalDragController : IDisposable _suppressedForCurrentDrag = false; if (_activeWheel != null) { - _activeWheel.ExecuteSelectionAndClose(); - _activeWheel = null; + DispatchToUi(() => + { + if (_activeWheel != null) + { + _activeWheel.ExecuteSelectionAndClose(); + _activeWheel = null; + _activeWheelHwnd = IntPtr.Zero; + } + }); } } return; @@ -97,7 +119,7 @@ public sealed class GlobalDragController : IDisposable { _dragStartPos = currentPoint; _isDragging = true; - _suppressedForCurrentDrag = IsOwnWindowForeground(); + _suppressedForCurrentDrag = IsOwnWindowForeground(_activeWheelHwnd); return; } @@ -115,47 +137,61 @@ public sealed class GlobalDragController : IDisposable if (modifierPressed && _activeWheel == null) { - OpenWheel(currentPoint); + DispatchToUi(() => OpenWheel(currentPoint)); } else if (_activeWheel != null) { + var wheel = _activeWheel; // Eğer çark açıldıktan 350ms sonra hâlâ geçerli bir dosya sürüklemesi (OLE FileDrop) // algılanmadıysa (örneğin kullanıcı metin seçiyorsa), çarkı sessizce kapat. - if (!_activeWheel.HasValidFileDrag && - (DateTime.UtcNow - _activeWheel.OpenedAtUtc).TotalMilliseconds > 350) + if (!wheel.HasValidFileDrag && (DateTime.UtcNow - wheel.OpenedAtUtc).TotalMilliseconds > 350) { - _activeWheel.CancelAndClose(); - _activeWheel = null; + DispatchToUi(() => + { + wheel.CancelAndClose(); + if (_activeWheel == wheel) + { + _activeWheel = null; + _activeWheelHwnd = IntPtr.Zero; + } + }); _suppressedForCurrentDrag = true; return; } - _activeWheel.UpdateMousePosition(new Point(currentPoint.X, currentPoint.Y)); + // Fare konumu güncellemesini Dispatcher kuyruğunu şişirmeden (rate-limit) gönder + if (Interlocked.CompareExchange(ref _isDispatchingPos, 1, 0) == 0) + { + DispatchToUi(() => + { + try + { + wheel.UpdateMousePosition(new Point(currentPoint.X, currentPoint.Y)); + } + finally + { + Interlocked.Exchange(ref _isDispatchingPos, 0); + } + }); + } } } - private static bool IsOwnWindowForeground() + private static bool IsOwnWindowForeground(IntPtr activeWheelHwnd) { try { IntPtr fg = GetForegroundWindow(); - if (fg == IntPtr.Zero || Application.Current == null) return false; + if (fg == IntPtr.Zero) return false; + if (activeWheelHwnd != IntPtr.Zero && fg == activeWheelHwnd) return false; - foreach (Window win in Application.Current.Windows) - { - if (win is WheelWindow) continue; - var hwnd = new WindowInteropHelper(win).Handle; - if (hwnd != IntPtr.Zero && hwnd == fg) - { - return true; - } - } + GetWindowThreadProcessId(fg, out uint procId); + return procId == (uint)Environment.ProcessId; } catch { - // Hata durumunda engelleme + return false; } - return false; } private static bool CheckModifierPressed(string modifier) @@ -173,18 +209,53 @@ public sealed class GlobalDragController : IDisposable private void OpenWheel(POINT screenPoint) { + if (_activeWheel != null) return; + var prefs = _preferencesStore.Current; - _activeWheel = new WheelWindow(_onDropped, prefs.SoundEffectsEnabled, prefs.WheelScale); + var wheel = new WheelWindow(_onDropped, prefs.SoundEffectsEnabled, prefs.WheelScale); + _activeWheel = wheel; // Çarkı farenin tam merkezine konumlandır - DesktopGeometry.PlaceCentered(_activeWheel, screenPoint.X, screenPoint.Y); - _activeWheel.Show(); + DesktopGeometry.PlaceCentered(wheel, screenPoint.X, screenPoint.Y); + wheel.Show(); + + try + { + _activeWheelHwnd = new WindowInteropHelper(wheel).Handle; + } + catch + { + _activeWheelHwnd = IntPtr.Zero; + } + } + + private static void DispatchToUi(Action action) + { + var app = Application.Current; + if (app == null || app.Dispatcher.HasShutdownStarted || app.Dispatcher.HasShutdownFinished) return; + + if (app.Dispatcher.CheckAccess()) + { + action(); + } + else + { + app.Dispatcher.BeginInvoke(DispatcherPriority.Normal, action); + } } public void Dispose() { - _pollTimer.Stop(); - _activeWheel?.CancelAndClose(); - _activeWheel = null; + if (_isDisposed) return; + _isDisposed = true; + + _backgroundTimer.Dispose(); + + DispatchToUi(() => + { + _activeWheel?.CancelAndClose(); + _activeWheel = null; + _activeWheelHwnd = IntPtr.Zero; + }); } } diff --git a/src/Donustur.UI/Services/SingleInstance.cs b/src/Donustur.UI/Services/SingleInstance.cs index 9debba1..7d7a0b1 100644 --- a/src/Donustur.UI/Services/SingleInstance.cs +++ b/src/Donustur.UI/Services/SingleInstance.cs @@ -65,7 +65,7 @@ public sealed class SingleInstance : IDisposable string? msg = await reader.ReadLineAsync(_pipeCts.Token); if (string.IsNullOrWhiteSpace(msg)) continue; - System.Windows.Application.Current?.Dispatcher.Invoke(() => + System.Windows.Application.Current?.Dispatcher.BeginInvoke(() => { if (msg.StartsWith("FILES|", StringComparison.Ordinal)) { diff --git a/src/Donustur.UI/Services/SoundFeedback.cs b/src/Donustur.UI/Services/SoundFeedback.cs index 0f2c7bd..6680ff0 100644 --- a/src/Donustur.UI/Services/SoundFeedback.cs +++ b/src/Donustur.UI/Services/SoundFeedback.cs @@ -4,25 +4,31 @@ public static class SoundFeedback { public static void PlayTick() { - try + Task.Run(() => { - System.Media.SystemSounds.Beep.Play(); - } - catch - { - // Ses çalınamazsa sessizce geç - } + try + { + System.Media.SystemSounds.Beep.Play(); + } + catch + { + // Ses çalınamazsa sessizce geç + } + }); } public static void PlaySuccess() { - try + Task.Run(() => { - System.Media.SystemSounds.Asterisk.Play(); - } - catch - { - // Sessizce geç - } + try + { + System.Media.SystemSounds.Asterisk.Play(); + } + catch + { + // Sessizce geç + } + }); } } diff --git a/src/Donustur.UI/Windows/ProgressToastWindow.xaml.cs b/src/Donustur.UI/Windows/ProgressToastWindow.xaml.cs index b04b65d..8cfa0f4 100644 --- a/src/Donustur.UI/Windows/ProgressToastWindow.xaml.cs +++ b/src/Donustur.UI/Windows/ProgressToastWindow.xaml.cs @@ -55,25 +55,46 @@ public partial class ProgressToastWindow : Window } } + private static readonly System.Windows.Media.SolidColorBrush CompletedGreenBrush; + + static ProgressToastWindow() + { + CompletedGreenBrush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(16, 185, 129)); + CompletedGreenBrush.Freeze(); + } + public void UpdateProgress(double percent, string? status = null) { - Dispatcher.Invoke(() => + if (Dispatcher.HasShutdownStarted || Dispatcher.HasShutdownFinished) return; + + void Apply() { ProgressBar.Value = percent; if (!string.IsNullOrWhiteSpace(status)) { StatusText.Text = status; } - }); + } + + if (Dispatcher.CheckAccess()) + { + Apply(); + } + else + { + Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)Apply); + } } public void SetCompleted(IReadOnlyList outputFiles, string? decodedText = null) { - Dispatcher.Invoke(() => + if (Dispatcher.HasShutdownStarted || Dispatcher.HasShutdownFinished) return; + + void Apply() { _isCompletedOrFailed = true; ProgressBar.Value = 100; - ProgressBar.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(16, 185, 129)); + ProgressBar.Foreground = CompletedGreenBrush; TitleText.Text = "✓ Dönüştürme Tamamlandı"; if (!string.IsNullOrWhiteSpace(decodedText)) @@ -97,12 +118,23 @@ public partial class ProgressToastWindow : Window } _autoCloseTimer.Start(); - }); + } + + if (Dispatcher.CheckAccess()) + { + Apply(); + } + else + { + Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)Apply); + } } public void SetFailed(string error) { - Dispatcher.Invoke(() => + if (Dispatcher.HasShutdownStarted || Dispatcher.HasShutdownFinished) return; + + void Apply() { _isCompletedOrFailed = true; TitleText.Text = "✕ İşlem Tamamlanamadı"; @@ -110,7 +142,16 @@ public partial class ProgressToastWindow : Window StatusText.Text = error; ProgressBar.Visibility = Visibility.Collapsed; _autoCloseTimer.Start(); - }); + } + + if (Dispatcher.CheckAccess()) + { + Apply(); + } + else + { + Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)Apply); + } } private void OnCloseClick(object sender, RoutedEventArgs e) diff --git a/src/Donustur.UI/Windows/SettingsWindow.xaml.cs b/src/Donustur.UI/Windows/SettingsWindow.xaml.cs index a2c79e5..c7d8244 100644 --- a/src/Donustur.UI/Windows/SettingsWindow.xaml.cs +++ b/src/Donustur.UI/Windows/SettingsWindow.xaml.cs @@ -66,35 +66,52 @@ public partial class SettingsWindow : Window CustomFolderText.Text = prefs.CustomOutputDirectory; CustomFolderPanel.Visibility = OutputModeCombo.SelectedIndex == 2 ? Visibility.Visible : Visibility.Collapsed; - // Harici Motor Kontrolleri - var officeEngine = new OfficeDocumentEngine(prefs.CustomLibreOfficePath); - if (officeEngine.IsAvailable) - { - LibreOfficeStatusText.Text = $"✓ Hazır ({officeEngine.ResolveSofficePath()})"; - LibreOfficeStatusText.Foreground = System.Windows.Media.Brushes.LightGreen; - } - else - { - LibreOfficeStatusText.Text = "ℹ Kurulu değil (TXT/DOCX/HTML/PDF yerel motoru aktif; PPTX/XLSX için LibreOffice seçilebilir)"; - LibreOfficeStatusText.Foreground = System.Windows.Media.Brushes.Khaki; - } + // Harici Motor Kontrolleri (UI thread'i kilitlememesi için arka planda tara) + LibreOfficeStatusText.Text = "ℹ Kontrol ediliyor..."; + FfmpegStatusText.Text = "ℹ Kontrol ediliyor..."; + NativeEnginesStatusText.Text = "✓ Magick.NET, PdfPig ve SharpCompress hazır"; - var mediaEngine = new MediaEngine(prefs.CustomFfmpegPath); - if (mediaEngine.IsAvailable) + Task.Run(() => { - FfmpegStatusText.Text = $"✓ Hazır ({mediaEngine.ResolveFfmpegPath()})"; - FfmpegStatusText.Foreground = System.Windows.Media.Brushes.LightGreen; - } - else - { - FfmpegStatusText.Text = "✕ Bulunamadı (Video & ses dönüşümleri için ffmpeg.exe seçin veya winget ile kurun)"; - FfmpegStatusText.Foreground = System.Windows.Media.Brushes.IndianRed; - } + var officeEngine = new OfficeDocumentEngine(prefs.CustomLibreOfficePath); + bool officeAvailable = officeEngine.IsAvailable; + string? sofficePath = officeAvailable ? officeEngine.ResolveSofficePath() : null; - string? sevenZip = ArchiveEngine.Resolve7ZipPath(); - NativeEnginesStatusText.Text = sevenZip != null - ? $"✓ Magick.NET, PdfPig, SharpCompress ve 7-Zip ({sevenZip}) hazır" - : "✓ Magick.NET, PdfPig ve SharpCompress hazır (ZIP, TAR.GZ, Görsel, PDF, DOCX, QR)"; + var mediaEngine = new MediaEngine(prefs.CustomFfmpegPath); + bool mediaAvailable = mediaEngine.IsAvailable; + string? ffmpegPath = mediaAvailable ? mediaEngine.ResolveFfmpegPath() : null; + + string? sevenZip = ArchiveEngine.Resolve7ZipPath(); + + Dispatcher.BeginInvoke(() => + { + if (officeAvailable) + { + LibreOfficeStatusText.Text = $"✓ Hazır ({sofficePath})"; + LibreOfficeStatusText.Foreground = System.Windows.Media.Brushes.LightGreen; + } + else + { + LibreOfficeStatusText.Text = "ℹ Kurulu değil (TXT/DOCX/HTML/PDF yerel motoru aktif; PPTX/XLSX için LibreOffice seçilebilir)"; + LibreOfficeStatusText.Foreground = System.Windows.Media.Brushes.Khaki; + } + + if (mediaAvailable) + { + FfmpegStatusText.Text = $"✓ Hazır ({ffmpegPath})"; + FfmpegStatusText.Foreground = System.Windows.Media.Brushes.LightGreen; + } + else + { + FfmpegStatusText.Text = "✕ Bulunamadı (Video & ses dönüşümleri için ffmpeg.exe seçin veya winget ile kurun)"; + FfmpegStatusText.Foreground = System.Windows.Media.Brushes.IndianRed; + } + + NativeEnginesStatusText.Text = sevenZip != null + ? $"✓ Magick.NET, PdfPig, SharpCompress ve 7-Zip ({sevenZip}) hazır" + : "✓ Magick.NET, PdfPig ve SharpCompress hazır (ZIP, TAR.GZ, Görsel, PDF, DOCX, QR)"; + }); + }); } private void OnScaleSliderChanged(object sender, RoutedPropertyChangedEventArgs e)