perf: LD Converter v1.2.0 - Ultra fluidity and responsiveness patch

This commit is contained in:
LilDosto 2026-10-28 03:58:50 +03:00
parent 24cfcf44e8
commit 921bd4fa3f
21 changed files with 676 additions and 410 deletions

1
.gitignore vendored
View file

@ -3,6 +3,7 @@
[Oo]bj/ [Oo]bj/
[Ll]og/ [Ll]og/
[Ll]ogs/ [Ll]ogs/
*.zip
# Visual Studio / Rider / VS Code caches # Visual Studio / Rider / VS Code caches
.vs/ .vs/

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -7,7 +7,7 @@
"targets": { "targets": {
".NETCoreApp,Version=v8.0": {}, ".NETCoreApp,Version=v8.0": {},
".NETCoreApp,Version=v8.0/win-x64": { ".NETCoreApp,Version=v8.0/win-x64": {
"LDConverter/1.1.0": { "LDConverter/1.2.0": {
"dependencies": { "dependencies": {
"Donustur.Core": "1.0.0", "Donustur.Core": "1.0.0",
"Donustur.Engine": "1.0.0" "Donustur.Engine": "1.0.0"
@ -157,7 +157,7 @@
} }
}, },
"libraries": { "libraries": {
"LDConverter/1.1.0": { "LDConverter/1.2.0": {
"type": "project", "type": "project",
"serviceable": false, "serviceable": false,
"sha512": "" "sha512": ""

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -92,8 +92,8 @@ public sealed class HistoryStore
{ {
_entries.RemoveRange(100, _entries.Count - 100); _entries.RemoveRange(100, _entries.Count - 100);
} }
SaveInternal();
} }
SaveInternal();
Changed?.Invoke(); Changed?.Invoke();
} }
@ -103,13 +103,10 @@ public sealed class HistoryStore
lock (_lock) lock (_lock)
{ {
removed = _entries.RemoveAll(e => e.Id == id) > 0; removed = _entries.RemoveAll(e => e.Id == id) > 0;
if (removed)
{
SaveInternal();
}
} }
if (removed) if (removed)
{ {
SaveInternal();
Changed?.Invoke(); Changed?.Invoke();
} }
} }
@ -119,29 +116,38 @@ public sealed class HistoryStore
lock (_lock) lock (_lock)
{ {
_entries.Clear(); _entries.Clear();
SaveInternal();
} }
SaveInternal();
Changed?.Invoke(); Changed?.Invoke();
} }
private void SaveInternal() private void SaveInternal()
{ {
try List<HistoryEntry> snapshot;
lock (_lock)
{ {
string dir = Path.GetDirectoryName(_filePath)!; snapshot = _entries.ToList();
if (!Directory.Exists(dir)) }
{
Directory.CreateDirectory(dir);
}
string json = JsonSerializer.Serialize(_entries, JsonOptions); Task.Run(() =>
string tmp = _filePath + ".tmp";
File.WriteAllText(tmp, json);
File.Move(tmp, _filePath, overwrite: true);
}
catch
{ {
// 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
}
});
} }
} }

View file

@ -58,25 +58,28 @@ public sealed class PreferencesStore
public void Save(AppPreferences preferences) public void Save(AppPreferences preferences)
{ {
try _current = preferences;
Changed?.Invoke(_current);
Task.Run(() =>
{ {
_current = preferences; try
string dir = Path.GetDirectoryName(_filePath)!;
if (!Directory.Exists(dir))
{ {
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);
} }
catch
string json = JsonSerializer.Serialize(preferences, JsonOptions); {
string tempFile = _filePath + ".tmp"; // Handle error silently
File.WriteAllText(tempFile, json); }
File.Move(tempFile, _filePath, overwrite: true); });
Changed?.Invoke(_current);
}
catch
{
// Handle error silently
}
} }
} }

View file

@ -34,247 +34,250 @@ public sealed class ConversionDispatcher
IProgress<double>? progress = null, IProgress<double>? progress = null,
CancellationToken token = default) CancellationToken token = default)
{ {
task.Status = ConversionTaskStatus.Running; return await Task.Run(async () =>
// 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)
{ {
task.Options.ImageQuality = preferences.DefaultImageQuality; task.Status = ConversionTaskStatus.Running;
}
string targetAction = task.TargetActionId.ToLowerInvariant().TrimStart('.'); // Ayarlar ekranından değiştirilmiş olabilecek harici motor yollarını senkronize et
string destination = ResolveDestinationFolder(task, preferences); _officeEngine.SetCustomPath(preferences.CustomLibreOfficePath);
_mediaEngine.SetCustomPath(preferences.CustomFfmpegPath);
using var transaction = new ExportTransaction(); if (preferences.DefaultImageQuality is >= 10 and <= 100 && task.Options.ImageQuality == 85)
try
{
var files = task.InputFiles;
if (files.Count == 0)
{ {
throw new InvalidOperationException("İşlenecek dosya bulunamadı."); task.Options.ImageQuality = preferences.DefaultImageQuality;
} }
long totalInitialBytes = FileUtils.CalculateTotalBytes(files); string targetAction = task.TargetActionId.ToLowerInvariant().TrimStart('.');
IReadOnlyList<string> generatedStagedFiles; string destination = ResolveDestinationFolder(task, preferences);
// 1. QR İşlemleri (Görsel ve PDF destekli) using var transaction = new ExportTransaction();
if (targetAction == "qr_read")
try
{ {
var qrResults = new List<string>(); var files = task.InputFiles;
var decodedTexts = new List<string>(); if (files.Count == 0)
for (int i = 0; i < files.Count; i++)
{ {
token.ThrowIfCancellationRequested(); throw new InvalidOperationException("İşlenecek dosya bulunamadı.");
string f = files[i]; }
string? text = _qrEngine.ReadQrCode(f);
if (!string.IsNullOrWhiteSpace(text)) long totalInitialBytes = FileUtils.CalculateTotalBytes(files);
IReadOnlyList<string> generatedStagedFiles;
// 1. QR İşlemleri (Görsel ve PDF destekli)
if (targetAction == "qr_read")
{
var qrResults = new List<string>();
var decodedTexts = new List<string>();
for (int i = 0; i < files.Count; i++)
{ {
decodedTexts.Add(text); token.ThrowIfCancellationRequested();
string txtPath = SafePaths.GetUniquePath( string f = files[i];
transaction.StagingDirectory, string? text = _qrEngine.ReadQrCode(f);
Path.GetFileNameWithoutExtension(f) + "_QR.txt"); if (!string.IsNullOrWhiteSpace(text))
await File.WriteAllTextAsync(txtPath, text, token); {
qrResults.Add(txtPath); 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) if (qrResults.Count == 0)
{ {
throw new InvalidOperationException("Seçilen dosyada okunabilir bir QR kod veya barkod bulunamadı."); throw new InvalidOperationException("Seçilen dosyada okunabilir bir QR kod veya barkod bulunamadı.");
} }
task.CurrentStatusMessage = string.Join(" | ", decodedTexts); task.CurrentStatusMessage = string.Join(" | ", decodedTexts);
generatedStagedFiles = qrResults; generatedStagedFiles = qrResults;
}
// 2. Arşiv Çıkarma
else if (targetAction == "extract_folder")
{
var extractedDirs = new List<string>();
foreach (var f in files)
{
string dir = await _archiveEngine.ExtractAsync(f, transaction, task.Options.ArchivePassword, progress, token);
extractedDirs.Add(dir);
} }
generatedStagedFiles = extractedDirs; // 2. Arşiv Çıkarma
} else if (targetAction == "extract_folder")
// 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); var extractedDirs = new List<string>();
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<string>();
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<string>();
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<string>();
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<string>();
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 else
{ {
var mergeable = files.Where(f => FormatCatalog.IsPdf(f) || FormatCatalog.IsImage(f)).ToList(); // Genel ZIP arşivleme yedeği
if (mergeable.Count == 0) string zip = await _archiveEngine.CreateZipAsync(files, transaction, null, progress, token);
{ generatedStagedFiles = new[] { zip };
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 // Dosyaları nihai hedef klasöre taşı (Commit)
else if (targetAction == "pdf_split") var finalCommittedPaths = transaction.CommitTo(destination, task.Options.OverwriteExisting);
{ long totalFinalBytes = FileUtils.CalculateTotalBytes(finalCommittedPaths);
var splitFiles = new List<string>();
foreach (var f in files.Where(FormatCatalog.IsPdf)) 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); Title = files.Count == 1
splitFiles.AddRange(pages); ? Path.GetFileName(files[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
} : $"{files.Count} öğe ({Path.GetFileName(files[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))}...)",
generatedStagedFiles = splitFiles; 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 catch (OperationCanceledException)
else if (targetAction == "pdf_to_txt")
{ {
var txts = new List<string>(); task.Status = ConversionTaskStatus.Cancelled;
foreach (var f in files) task.CompletedAt = DateTime.Now;
return new ConversionResult(false, Array.Empty<string>(), "İş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); Title = task.InputFiles.Count == 1
txts.Add(txt); ? Path.GetFileName(task.InputFiles[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
} : $"{task.InputFiles.Count} dosya",
generatedStagedFiles = txts; FormatSummary = FormatFriendlyActionLabel(targetAction),
} InputFiles = task.InputFiles.ToList(),
// 10. PDF'den Word (DOCX) Belgesine Dönüştürme OutputFiles = new List<string>(),
else if (targetAction == "pdf_to_docx") Timestamp = DateTime.Now,
{ Success = false,
var docxs = new List<string>(); ErrorMessage = ex.Message
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<string>();
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 };
}
// Dosyaları nihai hedef klasöre taşı (Commit) return new ConversionResult(false, Array.Empty<string>(), ex.Message, task.Duration);
var finalCommittedPaths = transaction.CommitTo(destination, task.Options.OverwriteExisting); }
long totalFinalBytes = FileUtils.CalculateTotalBytes(finalCommittedPaths); }, token);
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<string>(), "İş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<string>(),
Timestamp = DateTime.Now,
Success = false,
ErrorMessage = ex.Message
});
return new ConversionResult(false, Array.Empty<string>(), ex.Message, task.Duration);
}
} }
private static string FormatFriendlyActionLabel(string action) private static string FormatFriendlyActionLabel(string action)

View file

@ -39,13 +39,28 @@ public static class ProcessRunner
using var process = new Process { StartInfo = psi, EnableRaisingEvents = true }; using var process = new Process { StartInfo = psi, EnableRaisingEvents = true };
var stdOut = new StringBuilder(); var stdOut = new StringBuilder();
var stdErr = 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) => process.OutputDataReceived += (_, e) =>
{ {
if (e.Data != null) if (e.Data != null)
{ {
stdOut.AppendLine(e.Data); lock (stdOut)
outputProgress?.Report(e.Data); {
stdOut.AppendLine(e.Data);
}
ReportThrottled(e.Data);
} }
}; };
@ -53,8 +68,11 @@ public static class ProcessRunner
{ {
if (e.Data != null) if (e.Data != null)
{ {
stdErr.AppendLine(e.Data); lock (stdErr)
outputProgress?.Report(e.Data); {
stdErr.AppendLine(e.Data);
}
ReportThrottled(e.Data);
} }
}; };

View file

@ -2,7 +2,6 @@ using System.Globalization;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Media.Animation;
using Donustur.Core.Math; using Donustur.Core.Math;
using Donustur.Core.Models; using Donustur.Core.Models;
@ -75,11 +74,89 @@ public sealed class RadialWheelControl : Control
public double OuterRadius { get; set; } = 175.0; public double OuterRadius { get; set; } = 175.0;
public double InnerRadius { get; set; } = 48.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() static RadialWheelControl()
{ {
DefaultStyleKeyProperty.OverrideMetadata( DefaultStyleKeyProperty.OverrideMetadata(
typeof(RadialWheelControl), typeof(RadialWheelControl),
new FrameworkPropertyMetadata(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() public RadialWheelControl()
@ -109,16 +186,7 @@ public sealed class RadialWheelControl : Control
double gapDegrees = total > 1 ? 2.5 : 0.0; double gapDegrees = total > 1 ? 2.5 : 0.0;
// Arka plan parlaması (Glow) // Arka plan parlaması (Glow)
var glowBrush = new RadialGradientBrush dc.DrawEllipse(GlowBrush, null, new Point(centerX, centerY), OuterRadius + 10, OuterRadius + 10);
{
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);
// Dilimleri çiz // Dilimleri çiz
for (int i = 0; i < total; i++) for (int i = 0; i < total; i++)
@ -137,27 +205,8 @@ public sealed class RadialWheelControl : Control
InnerRadius, isHovered ? OuterRadius + 5 : OuterRadius, InnerRadius, isHovered ? OuterRadius + 5 : OuterRadius,
startAngle, sweepAngle); startAngle, sweepAngle);
Brush fillBrush; Brush fillBrush = isHovered ? ActiveSegmentBrush : DefaultSegmentBrush;
Pen borderPen; Pen borderPen = isHovered ? ActiveSegmentPen : DefaultSegmentPen;
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);
}
dc.DrawGeometry(fillBrush, borderPen, geom); 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) 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"), var typeface = isHovered ? SegmentTypefaceBold : SegmentTypefaceRegular;
FontStyles.Normal, var brush = isHovered ? TextWhiteBrush : TextNormalBrush;
isHovered ? FontWeights.Bold : FontWeights.SemiBold,
FontStretches.Normal);
var ft = new FormattedText( var ft = new FormattedText(
text, text,
@ -185,7 +232,7 @@ public sealed class RadialWheelControl : Control
FlowDirection.LeftToRight, FlowDirection.LeftToRight,
typeface, typeface,
isHovered ? 14 : 12.5, isHovered ? 14 : 12.5,
isHovered ? Brushes.White : new SolidColorBrush(Color.FromRgb(220, 225, 235)), brush,
1.0); 1.0);
dc.DrawText(ft, new Point(x - (ft.Width / 2.0), y - (ft.Height / 2.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) private void DrawCenterHub(DrawingContext dc, double centerX, double centerY)
{ {
// Merkez gölge // Merkez gölge
var hubShadow = new RadialGradientBrush(); dc.DrawEllipse(HubShadowBrush, null, new Point(centerX, centerY), InnerRadius + 6, InnerRadius + 6);
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);
// Merkez arkaplan // Merkez arkaplan
var hubFill = new SolidColorBrush(Color.FromRgb(18, 20, 28)); dc.DrawEllipse(HubFillBrush, HubBorderPen, new Point(centerX, centerY), InnerRadius, InnerRadius);
var hubPen = new Pen(new SolidColorBrush(Color.FromArgb(120, 99, 102, 241)), 2.0);
dc.DrawEllipse(hubFill, hubPen, new Point(centerX, centerY), InnerRadius, InnerRadius);
// Merkez metin // Merkez metin
string centerTitle; string centerTitle;
@ -220,26 +262,24 @@ public sealed class RadialWheelControl : Control
centerSubtitle = FileCount > 0 ? $"{FileCount} dosya" : "Bırakın"; 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( var titleFt = new FormattedText(
centerTitle, centerTitle,
CultureInfo.CurrentUICulture, CultureInfo.CurrentUICulture,
FlowDirection.LeftToRight, FlowDirection.LeftToRight,
typefaceBold, HubTitleTypeface,
11.0, 11.0,
Brushes.White, TextWhiteBrush,
1.0); 1.0);
dc.DrawText(titleFt, new Point(centerX - (titleFt.Width / 2.0), centerY - 13)); 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( var subFt = new FormattedText(
centerSubtitle, centerSubtitle,
CultureInfo.CurrentUICulture, CultureInfo.CurrentUICulture,
FlowDirection.LeftToRight, FlowDirection.LeftToRight,
typefaceRegular, HubSubtitleTypeface,
9.5, 9.5,
new SolidColorBrush(Color.FromRgb(156, 163, 175)), TextSubBrush,
1.0); 1.0);
dc.DrawText(subFt, new Point(centerX - (subFt.Width / 2.0), centerY + 3)); 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(); var geom = new PathGeometry();
geom.Figures.Add(figure); geom.Figures.Add(figure);
geom.Freeze(); // GPU donanım hızlandırma ve sıfır GC tahsisi için dondur
return geom; return geom;
} }
} }

View file

@ -15,7 +15,7 @@
<AssemblyName>LDConverter</AssemblyName> <AssemblyName>LDConverter</AssemblyName>
<Product>LD Converter</Product> <Product>LD Converter</Product>
<Title>LD Converter</Title> <Title>LD Converter</Title>
<Version>1.1.0</Version> <Version>1.2.0</Version>
<ApplicationIcon>Assets\app.ico</ApplicationIcon> <ApplicationIcon>Assets\app.ico</ApplicationIcon>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>

View file

@ -210,21 +210,37 @@ public partial class MainWindow : Window
EmptyPrompt.Visibility = Visibility.Collapsed; EmptyPrompt.Visibility = Visibility.Collapsed;
SelectedFilesPanel.Visibility = Visibility.Visible; SelectedFilesPanel.Visibility = Visibility.Visible;
long totalBytes = FileUtils.CalculateTotalBytes(_selectedFiles);
FilesCountLabel.Text = _selectedFiles.Count == 1 FilesCountLabel.Text = _selectedFiles.Count == 1
? Path.GetFileName(_selectedFiles[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) ? Path.GetFileName(_selectedFiles[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
: $"{_selectedFiles.Count} öğe seçildi"; : $"{_selectedFiles.Count} öğe seçildi";
FilesSubLabel.Text = $"Toplam Boyut: {FileUtils.FormatBytes(totalBytes)}"; FilesSubLabel.Text = "Boyut hesaplanıyor...";
RenderSelectedFileItems(); RenderSelectedFileItems();
RebuildFormatChips(); 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() private void RenderSelectedFileItems()
{ {
SelectedFileItemsStack.Children.Clear(); 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 var row = new Border
{ {
@ -256,10 +272,27 @@ public partial class MainWindow : Window
DockPanel.SetDock(removeBtn, Dock.Right); DockPanel.SetDock(removeBtn, Dock.Right);
dock.Children.Add(removeBtn); 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 var sizeText = new TextBlock
{ {
Text = FileUtils.FormatBytes(itemSize), Text = sizeStr,
FontSize = 11, FontSize = 11,
Foreground = new SolidColorBrush(Color.FromRgb(107, 114, 128)), Foreground = new SolidColorBrush(Color.FromRgb(107, 114, 128)),
VerticalAlignment = VerticalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,
@ -268,7 +301,6 @@ public partial class MainWindow : Window
DockPanel.SetDock(sizeText, Dock.Right); DockPanel.SetDock(sizeText, Dock.Right);
dock.Children.Add(sizeText); dock.Children.Add(sizeText);
bool isDir = Directory.Exists(filePath);
string displayName = Path.GetFileName(filePath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); string displayName = Path.GetFileName(filePath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
var nameText = new TextBlock var nameText = new TextBlock
{ {
@ -284,6 +316,26 @@ public partial class MainWindow : Window
row.Child = dock; row.Child = dock;
SelectedFileItemsStack.Children.Add(row); 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() private void RebuildFormatChips()
@ -353,11 +405,8 @@ public partial class MainWindow : Window
var progress = new Progress<double>(val => var progress = new Progress<double>(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 var task = new ConversionTask
@ -532,7 +581,7 @@ public partial class MainWindow : Window
}; };
string? firstOut = entry.OutputFiles.FirstOrDefault(); string? firstOut = entry.OutputFiles.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(firstOut) && (File.Exists(firstOut) || Directory.Exists(firstOut))) if (!string.IsNullOrWhiteSpace(firstOut))
{ {
var openFolderBtn = new Button var openFolderBtn = new Button
{ {
@ -546,7 +595,17 @@ public partial class MainWindow : Window
BorderThickness = new Thickness(0) BorderThickness = new Thickness(0)
}; };
string targetPath = firstOut; 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); btnStack.Children.Add(openFolderBtn);
} }

View file

@ -1,4 +1,5 @@
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading;
using System.Windows; using System.Windows;
using System.Windows.Interop; using System.Windows.Interop;
using System.Windows.Threading; using System.Windows.Threading;
@ -19,6 +20,9 @@ public sealed class GlobalDragController : IDisposable
[DllImport("user32.dll")] [DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow(); private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
public struct POINT { public int X; public int Y; } public struct POINT { public int X; public int Y; }
@ -31,32 +35,39 @@ public sealed class GlobalDragController : IDisposable
private readonly PreferencesStore _preferencesStore; private readonly PreferencesStore _preferencesStore;
private readonly Action<ToolChoice, IReadOnlyList<string>> _onDropped; private readonly Action<ToolChoice, IReadOnlyList<string>> _onDropped;
private readonly DispatcherTimer _pollTimer; private readonly System.Threading.Timer _backgroundTimer;
private bool _isDragging; private bool _isDragging;
private bool _suppressedForCurrentDrag; private bool _suppressedForCurrentDrag;
private POINT _dragStartPos; private POINT _dragStartPos;
private WheelWindow? _activeWheel; private WheelWindow? _activeWheel;
private IntPtr _activeWheelHwnd = IntPtr.Zero;
private int _isDispatchingPos;
private bool _isDisposed;
public GlobalDragController(PreferencesStore preferencesStore, Action<ToolChoice, IReadOnlyList<string>> onDropped) public GlobalDragController(PreferencesStore preferencesStore, Action<ToolChoice, IReadOnlyList<string>> onDropped)
{ {
_preferencesStore = preferencesStore; _preferencesStore = preferencesStore;
_onDropped = onDropped; _onDropped = onDropped;
// 30 ms (~33 FPS) sorgulama aralığı: CPU kullanımı %0.01 seviyesindedir. // UI iş parçacığını asla meşgul etmeyen, arka plan iş parçacığı zamanlayıcısı (25ms ~ 40Hz)
_pollTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(30) }; _backgroundTimer = new System.Threading.Timer(OnBackgroundTick, null, 25, 25);
_pollTimer.Tick += OnPollTick;
_pollTimer.Start();
} }
private void OnPollTick(object? sender, EventArgs e) private void OnBackgroundTick(object? state)
{ {
if (_isDisposed) return;
if (!_preferencesStore.Current.Enabled) if (!_preferencesStore.Current.Enabled)
{ {
if (_activeWheel != null) if (_activeWheel != null)
{ {
_activeWheel.CancelAndClose(); DispatchToUi(() =>
_activeWheel = null; {
_activeWheel?.CancelAndClose();
_activeWheel = null;
_activeWheelHwnd = IntPtr.Zero;
});
} }
_isDragging = false; _isDragging = false;
_suppressedForCurrentDrag = false; _suppressedForCurrentDrag = false;
@ -70,8 +81,12 @@ public sealed class GlobalDragController : IDisposable
// Sağ tık veya ESC ile çarkı iptal et // Sağ tık veya ESC ile çarkı iptal et
if (_activeWheel != null && (rightDown || escapeDown)) if (_activeWheel != null && (rightDown || escapeDown))
{ {
_activeWheel.CancelAndClose(); DispatchToUi(() =>
_activeWheel = null; {
_activeWheel?.CancelAndClose();
_activeWheel = null;
_activeWheelHwnd = IntPtr.Zero;
});
_suppressedForCurrentDrag = true; _suppressedForCurrentDrag = true;
return; return;
} }
@ -84,8 +99,15 @@ public sealed class GlobalDragController : IDisposable
_suppressedForCurrentDrag = false; _suppressedForCurrentDrag = false;
if (_activeWheel != null) if (_activeWheel != null)
{ {
_activeWheel.ExecuteSelectionAndClose(); DispatchToUi(() =>
_activeWheel = null; {
if (_activeWheel != null)
{
_activeWheel.ExecuteSelectionAndClose();
_activeWheel = null;
_activeWheelHwnd = IntPtr.Zero;
}
});
} }
} }
return; return;
@ -97,7 +119,7 @@ public sealed class GlobalDragController : IDisposable
{ {
_dragStartPos = currentPoint; _dragStartPos = currentPoint;
_isDragging = true; _isDragging = true;
_suppressedForCurrentDrag = IsOwnWindowForeground(); _suppressedForCurrentDrag = IsOwnWindowForeground(_activeWheelHwnd);
return; return;
} }
@ -115,47 +137,61 @@ public sealed class GlobalDragController : IDisposable
if (modifierPressed && _activeWheel == null) if (modifierPressed && _activeWheel == null)
{ {
OpenWheel(currentPoint); DispatchToUi(() => OpenWheel(currentPoint));
} }
else if (_activeWheel != null) 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) // 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. // algılanmadıysa (örneğin kullanıcı metin seçiyorsa), çarkı sessizce kapat.
if (!_activeWheel.HasValidFileDrag && if (!wheel.HasValidFileDrag && (DateTime.UtcNow - wheel.OpenedAtUtc).TotalMilliseconds > 350)
(DateTime.UtcNow - _activeWheel.OpenedAtUtc).TotalMilliseconds > 350)
{ {
_activeWheel.CancelAndClose(); DispatchToUi(() =>
_activeWheel = null; {
wheel.CancelAndClose();
if (_activeWheel == wheel)
{
_activeWheel = null;
_activeWheelHwnd = IntPtr.Zero;
}
});
_suppressedForCurrentDrag = true; _suppressedForCurrentDrag = true;
return; 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 try
{ {
IntPtr fg = GetForegroundWindow(); 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) GetWindowThreadProcessId(fg, out uint procId);
{ return procId == (uint)Environment.ProcessId;
if (win is WheelWindow) continue;
var hwnd = new WindowInteropHelper(win).Handle;
if (hwnd != IntPtr.Zero && hwnd == fg)
{
return true;
}
}
} }
catch catch
{ {
// Hata durumunda engelleme return false;
} }
return false;
} }
private static bool CheckModifierPressed(string modifier) private static bool CheckModifierPressed(string modifier)
@ -173,18 +209,53 @@ public sealed class GlobalDragController : IDisposable
private void OpenWheel(POINT screenPoint) private void OpenWheel(POINT screenPoint)
{ {
if (_activeWheel != null) return;
var prefs = _preferencesStore.Current; 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 // Çarkı farenin tam merkezine konumlandır
DesktopGeometry.PlaceCentered(_activeWheel, screenPoint.X, screenPoint.Y); DesktopGeometry.PlaceCentered(wheel, screenPoint.X, screenPoint.Y);
_activeWheel.Show(); 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() public void Dispose()
{ {
_pollTimer.Stop(); if (_isDisposed) return;
_activeWheel?.CancelAndClose(); _isDisposed = true;
_activeWheel = null;
_backgroundTimer.Dispose();
DispatchToUi(() =>
{
_activeWheel?.CancelAndClose();
_activeWheel = null;
_activeWheelHwnd = IntPtr.Zero;
});
} }
} }

View file

@ -65,7 +65,7 @@ public sealed class SingleInstance : IDisposable
string? msg = await reader.ReadLineAsync(_pipeCts.Token); string? msg = await reader.ReadLineAsync(_pipeCts.Token);
if (string.IsNullOrWhiteSpace(msg)) continue; if (string.IsNullOrWhiteSpace(msg)) continue;
System.Windows.Application.Current?.Dispatcher.Invoke(() => System.Windows.Application.Current?.Dispatcher.BeginInvoke(() =>
{ {
if (msg.StartsWith("FILES|", StringComparison.Ordinal)) if (msg.StartsWith("FILES|", StringComparison.Ordinal))
{ {

View file

@ -4,25 +4,31 @@ public static class SoundFeedback
{ {
public static void PlayTick() public static void PlayTick()
{ {
try Task.Run(() =>
{ {
System.Media.SystemSounds.Beep.Play(); try
} {
catch System.Media.SystemSounds.Beep.Play();
{ }
// Ses çalınamazsa sessizce geç catch
} {
// Ses çalınamazsa sessizce geç
}
});
} }
public static void PlaySuccess() public static void PlaySuccess()
{ {
try Task.Run(() =>
{ {
System.Media.SystemSounds.Asterisk.Play(); try
} {
catch System.Media.SystemSounds.Asterisk.Play();
{ }
// Sessizce geç catch
} {
// Sessizce geç
}
});
} }
} }

View file

@ -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) public void UpdateProgress(double percent, string? status = null)
{ {
Dispatcher.Invoke(() => if (Dispatcher.HasShutdownStarted || Dispatcher.HasShutdownFinished) return;
void Apply()
{ {
ProgressBar.Value = percent; ProgressBar.Value = percent;
if (!string.IsNullOrWhiteSpace(status)) if (!string.IsNullOrWhiteSpace(status))
{ {
StatusText.Text = status; StatusText.Text = status;
} }
}); }
if (Dispatcher.CheckAccess())
{
Apply();
}
else
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)Apply);
}
} }
public void SetCompleted(IReadOnlyList<string> outputFiles, string? decodedText = null) public void SetCompleted(IReadOnlyList<string> outputFiles, string? decodedText = null)
{ {
Dispatcher.Invoke(() => if (Dispatcher.HasShutdownStarted || Dispatcher.HasShutdownFinished) return;
void Apply()
{ {
_isCompletedOrFailed = true; _isCompletedOrFailed = true;
ProgressBar.Value = 100; 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ı"; TitleText.Text = "✓ Dönüştürme Tamamlandı";
if (!string.IsNullOrWhiteSpace(decodedText)) if (!string.IsNullOrWhiteSpace(decodedText))
@ -97,12 +118,23 @@ public partial class ProgressToastWindow : Window
} }
_autoCloseTimer.Start(); _autoCloseTimer.Start();
}); }
if (Dispatcher.CheckAccess())
{
Apply();
}
else
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)Apply);
}
} }
public void SetFailed(string error) public void SetFailed(string error)
{ {
Dispatcher.Invoke(() => if (Dispatcher.HasShutdownStarted || Dispatcher.HasShutdownFinished) return;
void Apply()
{ {
_isCompletedOrFailed = true; _isCompletedOrFailed = true;
TitleText.Text = "✕ İşlem Tamamlanamadı"; TitleText.Text = "✕ İşlem Tamamlanamadı";
@ -110,7 +142,16 @@ public partial class ProgressToastWindow : Window
StatusText.Text = error; StatusText.Text = error;
ProgressBar.Visibility = Visibility.Collapsed; ProgressBar.Visibility = Visibility.Collapsed;
_autoCloseTimer.Start(); _autoCloseTimer.Start();
}); }
if (Dispatcher.CheckAccess())
{
Apply();
}
else
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)Apply);
}
} }
private void OnCloseClick(object sender, RoutedEventArgs e) private void OnCloseClick(object sender, RoutedEventArgs e)

View file

@ -66,35 +66,52 @@ public partial class SettingsWindow : Window
CustomFolderText.Text = prefs.CustomOutputDirectory; CustomFolderText.Text = prefs.CustomOutputDirectory;
CustomFolderPanel.Visibility = OutputModeCombo.SelectedIndex == 2 ? Visibility.Visible : Visibility.Collapsed; CustomFolderPanel.Visibility = OutputModeCombo.SelectedIndex == 2 ? Visibility.Visible : Visibility.Collapsed;
// Harici Motor Kontrolleri // Harici Motor Kontrolleri (UI thread'i kilitlememesi için arka planda tara)
var officeEngine = new OfficeDocumentEngine(prefs.CustomLibreOfficePath); LibreOfficeStatusText.Text = "ℹ Kontrol ediliyor...";
if (officeEngine.IsAvailable) FfmpegStatusText.Text = "ℹ Kontrol ediliyor...";
{ NativeEnginesStatusText.Text = "✓ Magick.NET, PdfPig ve SharpCompress hazır";
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;
}
var mediaEngine = new MediaEngine(prefs.CustomFfmpegPath); Task.Run(() =>
if (mediaEngine.IsAvailable)
{ {
FfmpegStatusText.Text = $"✓ Hazır ({mediaEngine.ResolveFfmpegPath()})"; var officeEngine = new OfficeDocumentEngine(prefs.CustomLibreOfficePath);
FfmpegStatusText.Foreground = System.Windows.Media.Brushes.LightGreen; bool officeAvailable = officeEngine.IsAvailable;
} string? sofficePath = officeAvailable ? officeEngine.ResolveSofficePath() : null;
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;
}
string? sevenZip = ArchiveEngine.Resolve7ZipPath(); var mediaEngine = new MediaEngine(prefs.CustomFfmpegPath);
NativeEnginesStatusText.Text = sevenZip != null bool mediaAvailable = mediaEngine.IsAvailable;
? $"✓ Magick.NET, PdfPig, SharpCompress ve 7-Zip ({sevenZip}) hazır" string? ffmpegPath = mediaAvailable ? mediaEngine.ResolveFfmpegPath() : null;
: "✓ Magick.NET, PdfPig ve SharpCompress hazır (ZIP, TAR.GZ, Görsel, PDF, DOCX, QR)";
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<double> e) private void OnScaleSliderChanged(object sender, RoutedPropertyChangedEventArgs<double> e)