commit 24cfcf44e80ab7a5932d97630b76b834ccefcf49 Author: LilDosto Date: Tue Oct 27 22:41:27 2026 +0300 feat: LD Converter v1.1.0 - Full engine, UI, custom icon & single-instance release diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c6f1b94 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +# Build intermediates +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio / Rider / VS Code caches +.vs/ +.idea/ +.vscode/ +*.user +*.suo +*.userosscache +*.sln.docstates +TestResults/ +*.DotSettings.user diff --git a/Donustur.sln b/Donustur.sln new file mode 100644 index 0000000..de3d424 --- /dev/null +++ b/Donustur.sln @@ -0,0 +1,50 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{35B7845F-528A-445E-A621-66D16C8781FE}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Donustur.Core", "src\Donustur.Core\Donustur.Core.csproj", "{A66A55A6-BD61-43EF-A73C-17DA990FA19A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Donustur.Engine", "src\Donustur.Engine\Donustur.Engine.csproj", "{95295F12-8EC1-4BCB-8A8B-5144E9142BDB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Donustur.UI", "src\Donustur.UI\Donustur.UI.csproj", "{C193D18F-2854-4CA3-A011-296E454B518C}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{66ACE05A-6B60-4D21-A6BA-5BD0CDB30737}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Donustur.Tests", "tests\Donustur.Tests\Donustur.Tests.csproj", "{9F90D082-CC34-4C03-8E19-D34694A2270B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A66A55A6-BD61-43EF-A73C-17DA990FA19A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A66A55A6-BD61-43EF-A73C-17DA990FA19A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A66A55A6-BD61-43EF-A73C-17DA990FA19A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A66A55A6-BD61-43EF-A73C-17DA990FA19A}.Release|Any CPU.Build.0 = Release|Any CPU + {95295F12-8EC1-4BCB-8A8B-5144E9142BDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {95295F12-8EC1-4BCB-8A8B-5144E9142BDB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {95295F12-8EC1-4BCB-8A8B-5144E9142BDB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {95295F12-8EC1-4BCB-8A8B-5144E9142BDB}.Release|Any CPU.Build.0 = Release|Any CPU + {C193D18F-2854-4CA3-A011-296E454B518C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C193D18F-2854-4CA3-A011-296E454B518C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C193D18F-2854-4CA3-A011-296E454B518C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C193D18F-2854-4CA3-A011-296E454B518C}.Release|Any CPU.Build.0 = Release|Any CPU + {9F90D082-CC34-4C03-8E19-D34694A2270B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9F90D082-CC34-4C03-8E19-D34694A2270B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9F90D082-CC34-4C03-8E19-D34694A2270B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9F90D082-CC34-4C03-8E19-D34694A2270B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {A66A55A6-BD61-43EF-A73C-17DA990FA19A} = {35B7845F-528A-445E-A621-66D16C8781FE} + {95295F12-8EC1-4BCB-8A8B-5144E9142BDB} = {35B7845F-528A-445E-A621-66D16C8781FE} + {C193D18F-2854-4CA3-A011-296E454B518C} = {35B7845F-528A-445E-A621-66D16C8781FE} + {9F90D082-CC34-4C03-8E19-D34694A2270B} = {66ACE05A-6B60-4D21-A6BA-5BD0CDB30737} + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md new file mode 100644 index 0000000..cde7757 --- /dev/null +++ b/README.md @@ -0,0 +1,44 @@ +# LD Converter 🚀 + +> **Yeni Nesil, Optimize & Akıcı Dosya Dönüştürme Aracı** +> .NET 8, WPF ve modern asenkron mimari ile tasarlanmış yüksek performanslı masaüstü dosya dönüştürücü. + +--- + +## 🌟 Öne Çıkan Özellikler + +1. **Sıfır Tıklama (Zero-Click) Çarkı (Radial Wheel):** + - Masaüstünde veya klasörde herhangi bir dosyayı (veya dosya grubunu) sürüklerken **Shift** (veya **Ctrl**) tuşuna basılı tuttuğunuz anda fare imlecinizin etrafında dairesel işlem çarkı açılır. + - Dosyayı istediğiniz dilimin üzerine bırakın; dönüştürme anında başlar. + +2. **Dinamik ve Akıllı Format Eşleme:** + - Görseller (PNG, JPG, WebP, AVIF, BMP, TIFF, GIF, ICO, HEIC) + - Belgeler (DOCX, PPTX, XLSX, ODT, RTF, TXT, HTML, EPUB) + - PDF İşlemleri (Sayfalara ayırma, PDF & Görsel birleştirme, metin çıkarma, DOCX'e çevirme, sayfaları PNG/JPG olarak dışa aktarma) + - Medya (MP4, MKV, AVI, MOV, WebM -> MP3, WAV, AAC, FLAC, OGG, GIF) + - Arşivleme (ZIP, 7Z, TAR.GZ, RAR) + - Karekod (QR Code) okuma ve tek tıklamayla yüksek çözünürlüklü QR üretme. + +3. **Atomik Evreleme (ExportTransaction):** + - Dosyalar önce güvenli bir geçici alanda işlenir; işlem başarıyla tamamlandığında hedef klasöre aktarılır. Yarım kalmış veya bozuk dosyalar sisteminizi kirletmez. + +4. **Fluent UI / Dark Theme & Tekil Örnek (Single Instance):** + - Windows 11 Fluent tasarım dili, koyu tema, özel LD Converter simgesi, donanım hızlandırmalı WPF vektörel çizim motoru. + - Aynı anda birden fazla örnek açılmasını engeller; pencere kapatıldığında arka planda gereksiz süreç bırakmaz. + +--- + +## ⚡ Çalıştırma + +### Hazır Derlenmiş Sürümden Başlatma: +`publish/LDConverter.exe` dosyasını çift tıklayarak doğrudan çalıştırabilirsiniz. + +### Kaynak Koddan Çalıştırma: +```bash +dotnet run --project src/Donustur.UI/Donustur.UI.csproj +``` + +### Testleri Çalıştırma: +```bash +dotnet test +``` diff --git a/publish/Donustur.Core.dll b/publish/Donustur.Core.dll new file mode 100644 index 0000000..b8dcf08 Binary files /dev/null and b/publish/Donustur.Core.dll differ diff --git a/publish/Donustur.Core.pdb b/publish/Donustur.Core.pdb new file mode 100644 index 0000000..4655b45 Binary files /dev/null and b/publish/Donustur.Core.pdb differ diff --git a/publish/Donustur.Engine.dll b/publish/Donustur.Engine.dll new file mode 100644 index 0000000..f464b68 Binary files /dev/null and b/publish/Donustur.Engine.dll differ diff --git a/publish/Donustur.Engine.pdb b/publish/Donustur.Engine.pdb new file mode 100644 index 0000000..942f9ec Binary files /dev/null and b/publish/Donustur.Engine.pdb differ diff --git a/publish/ICSharpCode.SharpZipLib.dll b/publish/ICSharpCode.SharpZipLib.dll new file mode 100644 index 0000000..08de420 Binary files /dev/null and b/publish/ICSharpCode.SharpZipLib.dll differ diff --git a/publish/LDConverter.deps.json b/publish/LDConverter.deps.json new file mode 100644 index 0000000..14e7e33 --- /dev/null +++ b/publish/LDConverter.deps.json @@ -0,0 +1,239 @@ +{ + "runtimeTarget": { + "name": ".NETCoreApp,Version=v8.0/win-x64", + "signature": "" + }, + "compilationOptions": {}, + "targets": { + ".NETCoreApp,Version=v8.0": {}, + ".NETCoreApp,Version=v8.0/win-x64": { + "LDConverter/1.1.0": { + "dependencies": { + "Donustur.Core": "1.0.0", + "Donustur.Engine": "1.0.0" + }, + "runtime": { + "LDConverter.dll": {} + } + }, + "Magick.NET-Q8-x64/15.0.0": { + "dependencies": { + "Magick.NET.Core": "15.0.0" + }, + "runtime": { + "lib/netstandard20/Magick.NET-Q8-x64.dll": { + "assemblyVersion": "15.0.0.0", + "fileVersion": "15.0.0.0" + } + }, + "native": { + "runtimes/win-x64/native/Magick.Native-Q8-x64.dll": { + "fileVersion": "7.1.2.33" + } + } + }, + "Magick.NET.Core/15.0.0": { + "runtime": { + "lib/netstandard20/Magick.NET.Core.dll": { + "assemblyVersion": "15.0.0.0", + "fileVersion": "15.0.0.0" + } + } + }, + "PdfPig/0.1.16": { + "runtime": { + "lib/net8.0/UglyToad.PdfPig.Core.dll": { + "assemblyVersion": "0.1.16.0", + "fileVersion": "0.1.16.0" + }, + "lib/net8.0/UglyToad.PdfPig.DocumentLayoutAnalysis.dll": { + "assemblyVersion": "0.1.16.0", + "fileVersion": "0.1.16.0" + }, + "lib/net8.0/UglyToad.PdfPig.Fonts.dll": { + "assemblyVersion": "0.1.16.0", + "fileVersion": "0.1.16.0" + }, + "lib/net8.0/UglyToad.PdfPig.Package.dll": { + "assemblyVersion": "0.1.16.0", + "fileVersion": "0.1.16.0" + }, + "lib/net8.0/UglyToad.PdfPig.Tokenization.dll": { + "assemblyVersion": "0.1.16.0", + "fileVersion": "0.1.16.0" + }, + "lib/net8.0/UglyToad.PdfPig.Tokens.dll": { + "assemblyVersion": "0.1.16.0", + "fileVersion": "0.1.16.0" + }, + "lib/net8.0/UglyToad.PdfPig.dll": { + "assemblyVersion": "0.1.16.0", + "fileVersion": "0.1.16.0" + } + } + }, + "PdfSharpCore/1.3.67": { + "dependencies": { + "SharpZipLib": "1.4.2", + "SixLabors.Fonts": "1.0.0-beta17", + "SixLabors.ImageSharp": "1.0.4" + }, + "runtime": { + "lib/net8.0/PdfSharpCore.dll": { + "assemblyVersion": "1.3.67.0", + "fileVersion": "1.3.67.0" + } + }, + "resources": { + "lib/net8.0/de/PdfSharpCore.resources.dll": { + "locale": "de" + } + } + }, + "SharpCompress/0.50.7": { + "runtime": { + "lib/net8.0/SharpCompress.dll": { + "assemblyVersion": "0.50.7.0", + "fileVersion": "0.50.7.0" + } + } + }, + "SharpZipLib/1.4.2": { + "runtime": { + "lib/net6.0/ICSharpCode.SharpZipLib.dll": { + "assemblyVersion": "1.4.2.13", + "fileVersion": "1.4.2.13" + } + } + }, + "SixLabors.Fonts/1.0.0-beta17": { + "runtime": { + "lib/netcoreapp3.1/SixLabors.Fonts.dll": { + "assemblyVersion": "1.0.0.0", + "fileVersion": "1.0.0.0" + } + } + }, + "SixLabors.ImageSharp/1.0.4": { + "runtime": { + "lib/netcoreapp3.1/SixLabors.ImageSharp.dll": { + "assemblyVersion": "1.0.0.0", + "fileVersion": "1.0.4.0" + } + } + }, + "ZXing.Net/0.16.11": { + "runtime": { + "lib/net8.0/zxing.dll": { + "assemblyVersion": "0.16.11.0", + "fileVersion": "0.16.11.0" + } + } + }, + "Donustur.Core/1.0.0": { + "runtime": { + "Donustur.Core.dll": { + "assemblyVersion": "1.0.0", + "fileVersion": "1.0.0.0" + } + } + }, + "Donustur.Engine/1.0.0": { + "dependencies": { + "Donustur.Core": "1.0.0", + "Magick.NET-Q8-x64": "15.0.0", + "PdfPig": "0.1.16", + "PdfSharpCore": "1.3.67", + "SharpCompress": "0.50.7", + "ZXing.Net": "0.16.11" + }, + "runtime": { + "Donustur.Engine.dll": { + "assemblyVersion": "1.0.0", + "fileVersion": "1.0.0.0" + } + } + } + } + }, + "libraries": { + "LDConverter/1.1.0": { + "type": "project", + "serviceable": false, + "sha512": "" + }, + "Magick.NET-Q8-x64/15.0.0": { + "type": "package", + "serviceable": true, + "sha512": "sha512-RVfIbAddWlHEr6aJiYAYIRn1P7bQUoSv9GJN0fZmcatnenaD4KTtzoxOFYq67KXegLTsBQHsGdjzgGDW5d4Ing==", + "path": "magick.net-q8-x64/15.0.0", + "hashPath": "magick.net-q8-x64.15.0.0.nupkg.sha512" + }, + "Magick.NET.Core/15.0.0": { + "type": "package", + "serviceable": true, + "sha512": "sha512-mP/VovMRuXBX2Rcnn1wWu0Zur6cjsf8IQhmTUCrasEk8cyAtN5sjHE7NxiH88whw8/2mjRvuphKUwj6bAZslpQ==", + "path": "magick.net.core/15.0.0", + "hashPath": "magick.net.core.15.0.0.nupkg.sha512" + }, + "PdfPig/0.1.16": { + "type": "package", + "serviceable": true, + "sha512": "sha512-qQcbsNMYVY+K5ELptax2S8thNMk0+rSQq3H/KdYj3LLcko8yTCz8y5KIvsKxIyAuTN0ZYNnfsZkM+0EvxTwHVA==", + "path": "pdfpig/0.1.16", + "hashPath": "pdfpig.0.1.16.nupkg.sha512" + }, + "PdfSharpCore/1.3.67": { + "type": "package", + "serviceable": true, + "sha512": "sha512-6Cvj9nX6RwIJFIQC8eJFCYYUu9Qa2t9LWh4i0SXFi3hqkX/ssUGKfzp+9JZZXbkp0lHeeH/9UYFHelLqIusPrQ==", + "path": "pdfsharpcore/1.3.67", + "hashPath": "pdfsharpcore.1.3.67.nupkg.sha512" + }, + "SharpCompress/0.50.7": { + "type": "package", + "serviceable": true, + "sha512": "sha512-amxjOlPKUFb33ohAVahPCCBHLtToYOOb6JGyM40q8DnT6KYoBLW1TtW6uLEXbv40S7ej6ikf6VmAXGBaFL6Klg==", + "path": "sharpcompress/0.50.7", + "hashPath": "sharpcompress.0.50.7.nupkg.sha512" + }, + "SharpZipLib/1.4.2": { + "type": "package", + "serviceable": true, + "sha512": "sha512-yjj+3zgz8zgXpiiC3ZdF/iyTBbz2fFvMxZFEBPUcwZjIvXOf37Ylm+K58hqMfIBt5JgU/Z2uoUS67JmTLe973A==", + "path": "sharpziplib/1.4.2", + "hashPath": "sharpziplib.1.4.2.nupkg.sha512" + }, + "SixLabors.Fonts/1.0.0-beta17": { + "type": "package", + "serviceable": true, + "sha512": "sha512-qubgVovAoSR7vyv9tJ68gSzRIPWz7HBjTM9rwAaLjpcJ6T50arnX+GHAZcC0r2mVagyRMknCNda3DGoe8StUUQ==", + "path": "sixlabors.fonts/1.0.0-beta17", + "hashPath": "sixlabors.fonts.1.0.0-beta17.nupkg.sha512" + }, + "SixLabors.ImageSharp/1.0.4": { + "type": "package", + "serviceable": true, + "sha512": "sha512-H2rPiEr2ddBOltOuqRYhpLBAsQXDAhbzMMhhuksnBG2oefup1MXMchALe7yYkKJksNbtxbZHKeM6dn/68I75qw==", + "path": "sixlabors.imagesharp/1.0.4", + "hashPath": "sixlabors.imagesharp.1.0.4.nupkg.sha512" + }, + "ZXing.Net/0.16.11": { + "type": "package", + "serviceable": true, + "sha512": "sha512-OZfAVu88hl87BffQ+rlWCj/vLvAhhCK4QnFaoveeF/MY8SjHNSYBQ3qyUEWlPKNgBQGh1syXhCDg10vUnCsqkg==", + "path": "zxing.net/0.16.11", + "hashPath": "zxing.net.0.16.11.nupkg.sha512" + }, + "Donustur.Core/1.0.0": { + "type": "project", + "serviceable": false, + "sha512": "" + }, + "Donustur.Engine/1.0.0": { + "type": "project", + "serviceable": false, + "sha512": "" + } + } +} \ No newline at end of file diff --git a/publish/LDConverter.dll b/publish/LDConverter.dll new file mode 100644 index 0000000..c401d36 Binary files /dev/null and b/publish/LDConverter.dll differ diff --git a/publish/LDConverter.exe b/publish/LDConverter.exe new file mode 100644 index 0000000..083ea40 Binary files /dev/null and b/publish/LDConverter.exe differ diff --git a/publish/LDConverter.pdb b/publish/LDConverter.pdb new file mode 100644 index 0000000..05adebc Binary files /dev/null and b/publish/LDConverter.pdb differ diff --git a/publish/LDConverter.runtimeconfig.json b/publish/LDConverter.runtimeconfig.json new file mode 100644 index 0000000..8fbd17c --- /dev/null +++ b/publish/LDConverter.runtimeconfig.json @@ -0,0 +1,19 @@ +{ + "runtimeOptions": { + "tfm": "net8.0", + "frameworks": [ + { + "name": "Microsoft.NETCore.App", + "version": "8.0.0" + }, + { + "name": "Microsoft.WindowsDesktop.App", + "version": "8.0.0" + } + ], + "configProperties": { + "System.Reflection.Metadata.MetadataUpdater.IsSupported": false, + "System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": true + } + } +} \ No newline at end of file diff --git a/publish/Magick.NET-Q8-x64.dll b/publish/Magick.NET-Q8-x64.dll new file mode 100644 index 0000000..3afc7fe Binary files /dev/null and b/publish/Magick.NET-Q8-x64.dll differ diff --git a/publish/Magick.NET.Core.dll b/publish/Magick.NET.Core.dll new file mode 100644 index 0000000..4236523 Binary files /dev/null and b/publish/Magick.NET.Core.dll differ diff --git a/publish/Magick.Native-Q8-x64.dll b/publish/Magick.Native-Q8-x64.dll new file mode 100644 index 0000000..f94f185 Binary files /dev/null and b/publish/Magick.Native-Q8-x64.dll differ diff --git a/publish/PdfSharpCore.dll b/publish/PdfSharpCore.dll new file mode 100644 index 0000000..820cf28 Binary files /dev/null and b/publish/PdfSharpCore.dll differ diff --git a/publish/SharpCompress.dll b/publish/SharpCompress.dll new file mode 100644 index 0000000..7760266 Binary files /dev/null and b/publish/SharpCompress.dll differ diff --git a/publish/SixLabors.Fonts.dll b/publish/SixLabors.Fonts.dll new file mode 100644 index 0000000..0b4caab Binary files /dev/null and b/publish/SixLabors.Fonts.dll differ diff --git a/publish/SixLabors.ImageSharp.dll b/publish/SixLabors.ImageSharp.dll new file mode 100644 index 0000000..109ac6d Binary files /dev/null and b/publish/SixLabors.ImageSharp.dll differ diff --git a/publish/UglyToad.PdfPig.Core.dll b/publish/UglyToad.PdfPig.Core.dll new file mode 100644 index 0000000..493720b Binary files /dev/null and b/publish/UglyToad.PdfPig.Core.dll differ diff --git a/publish/UglyToad.PdfPig.DocumentLayoutAnalysis.dll b/publish/UglyToad.PdfPig.DocumentLayoutAnalysis.dll new file mode 100644 index 0000000..10febf0 Binary files /dev/null and b/publish/UglyToad.PdfPig.DocumentLayoutAnalysis.dll differ diff --git a/publish/UglyToad.PdfPig.Fonts.dll b/publish/UglyToad.PdfPig.Fonts.dll new file mode 100644 index 0000000..8a3bd41 Binary files /dev/null and b/publish/UglyToad.PdfPig.Fonts.dll differ diff --git a/publish/UglyToad.PdfPig.Package.dll b/publish/UglyToad.PdfPig.Package.dll new file mode 100644 index 0000000..417c4d1 Binary files /dev/null and b/publish/UglyToad.PdfPig.Package.dll differ diff --git a/publish/UglyToad.PdfPig.Tokenization.dll b/publish/UglyToad.PdfPig.Tokenization.dll new file mode 100644 index 0000000..8980db3 Binary files /dev/null and b/publish/UglyToad.PdfPig.Tokenization.dll differ diff --git a/publish/UglyToad.PdfPig.Tokens.dll b/publish/UglyToad.PdfPig.Tokens.dll new file mode 100644 index 0000000..ed8295e Binary files /dev/null and b/publish/UglyToad.PdfPig.Tokens.dll differ diff --git a/publish/UglyToad.PdfPig.dll b/publish/UglyToad.PdfPig.dll new file mode 100644 index 0000000..a63f584 Binary files /dev/null and b/publish/UglyToad.PdfPig.dll differ diff --git a/publish/de/PdfSharpCore.resources.dll b/publish/de/PdfSharpCore.resources.dll new file mode 100644 index 0000000..de96ea4 Binary files /dev/null and b/publish/de/PdfSharpCore.resources.dll differ diff --git a/publish/zxing.dll b/publish/zxing.dll new file mode 100644 index 0000000..4bfc2b8 Binary files /dev/null and b/publish/zxing.dll differ diff --git a/src/Donustur.Core/Catalog/FormatCatalog.cs b/src/Donustur.Core/Catalog/FormatCatalog.cs new file mode 100644 index 0000000..7674444 --- /dev/null +++ b/src/Donustur.Core/Catalog/FormatCatalog.cs @@ -0,0 +1,215 @@ +using Donustur.Core.Models; + +namespace Donustur.Core.Catalog; + +public static class FormatCatalog +{ + private static readonly HashSet ImageExts = new(StringComparer.OrdinalIgnoreCase) + { + "jpg", "jpeg", "png", "webp", "avif", "bmp", "tiff", "tif", "gif", "ico", "svg", "heic", "heif" + }; + + private static readonly HashSet VideoExts = new(StringComparer.OrdinalIgnoreCase) + { + "mp4", "mkv", "avi", "mov", "webm", "flv", "wmv", "m4v" + }; + + private static readonly HashSet AudioExts = new(StringComparer.OrdinalIgnoreCase) + { + "mp3", "wav", "aac", "m4a", "flac", "ogg", "opus", "wma" + }; + + private static readonly HashSet DocumentExts = new(StringComparer.OrdinalIgnoreCase) + { + "docx", "doc", "pptx", "ppt", "xlsx", "xls", "odt", "rtf", "txt", "md", "html", "htm", "epub" + }; + + private static readonly HashSet ArchiveExts = new(StringComparer.OrdinalIgnoreCase) + { + "zip", "7z", "tar", "gz", "tgz", "rar" + }; + + public static string NormalizeExtension(string path) + { + if (string.IsNullOrWhiteSpace(path)) return string.Empty; + if (Directory.Exists(path)) return "folder"; + + string ext = Path.GetExtension(path).TrimStart('.').ToLowerInvariant(); + return ext switch + { + "jpeg" or "jpe" => "jpg", + "heif" => "heic", + "markdown" => "md", + "tgz" => "gz", + "htm" => "html", + "tif" => "tiff", + _ => ext + }; + } + + public static bool IsDirectory(string path) => !string.IsNullOrWhiteSpace(path) && Directory.Exists(path); + public static bool IsImage(string path) => !IsDirectory(path) && ImageExts.Contains(NormalizeExtension(path)); + public static bool IsVideo(string path) => !IsDirectory(path) && VideoExts.Contains(NormalizeExtension(path)); + public static bool IsAudio(string path) => !IsDirectory(path) && AudioExts.Contains(NormalizeExtension(path)); + public static bool IsDocument(string path) => !IsDirectory(path) && DocumentExts.Contains(NormalizeExtension(path)); + public static bool IsPdf(string path) => !IsDirectory(path) && NormalizeExtension(path) == "pdf"; + public static bool IsArchive(string path) => !IsDirectory(path) && ArchiveExts.Contains(NormalizeExtension(path)); + + /// + /// Gelen dosya listesine göre çark üzerinde gösterilecek en uygun seçenekleri üretir. + /// 6 ila 8 dilim ideal bir çark deneyimi sağlar. + /// + public static IReadOnlyList GetChoicesForFiles(IReadOnlyList filePaths) + { + if (filePaths.Count == 0) + { + return GetDefaultChoices(); + } + + bool anyDirs = filePaths.Any(IsDirectory); + if (anyDirs) + { + return new List + { + new("zip", "ZIP Arşivi Oluştur", "Arşiv", "Archive", "Seçili klasör ve dosyaları ZIP arşivine sıkıştır"), + new("7z", "7Z Arşivi Oluştur", "Arşiv", "Archive", "Ultra sıkıştırma ile 7Z arşivi oluştur"), + new("tar_gz", "TAR.GZ Yap", "Arşiv", "Archive", "Linux uyumlu .tar.gz paketi oluştur"), + new("copy_folder", "Yeni Klasöre Topla", "Dosya", "Folder", "İçeriği yeni bir klasörde organize et") + }; + } + + bool allImages = filePaths.All(IsImage); + bool allVideos = filePaths.All(IsVideo); + bool allAudios = filePaths.All(IsAudio); + bool allPdfs = filePaths.All(IsPdf); + bool allDocs = filePaths.All(IsDocument); + bool allArchives = filePaths.All(IsArchive); + + // Görseller + if (allImages) + { + var list = new List + { + new("png", "PNG", "Görsel", "Image", "Kayıpsız PNG formatına dönüştür"), + new("jpg", "JPG", "Görsel", "Image", "Yüksek uyumlu JPG formatına dönüştür"), + new("webp", "WebP", "Görsel", "Web", "Modern, hafif WebP formatına dönüştür"), + new("avif", "AVIF", "Görsel", "Sparkle", "Yeni nesil ultra sıkıştırılmış AVIF"), + new("pdf", "PDF", "Belge", "Pdf", "Görsellerden PDF belgesi oluştur"), + new("ico", "ICO (İkon)", "Görsel", "Icon", "Windows simgesi (.ico) oluştur") + }; + + if (filePaths.Count == 1) + { + list.Add(new("qr_read", "QR Oku", "Araç", "QrCode", "Görseldeki QR kodu tara ve çöz")); + list.Add(new("compress_image", "Sıkıştır", "Optimizasyon", "Compress", "Kalite kaybı olmadan boyutu küçült")); + } + else + { + list.Add(new("gif", "Animasyonlu GIF", "Görsel", "Sparkle", "Görsellerden hareketli GIF oluştur")); + list.Add(new("zip", "ZIP Arşivi", "Arşiv", "Archive", "Tüm görselleri tek ZIP dosyası yap")); + list.Add(new("compress_image", "Hepsini Sıkıştır", "Optimizasyon", "Compress", "Tüm görselleri optimize et")); + } + return list; + } + + // PDF'ler + if (allPdfs) + { + var list = new List + { + new("pdf_to_images", "Sayfaları PNG Yap", "Görsel", "Image", "PDF sayfalarını yüksek çözünürlüklü PNG'ye aktar"), + new("pdf_to_jpg", "Sayfaları JPG Yap", "Görsel", "Image", "PDF sayfalarını JPG resimleri olarak kaydet"), + new("pdf_to_txt", "Metin Çıkar (TXT)", "Belge", "Text", "PDF içindeki tüm metinleri TXT olarak kaydet"), + new("pdf_to_docx", "DOCX Yap", "Belge", "Document", "Word belgesine (.docx) dönüştür"), + new("qr_read", "QR Oku", "Araç", "QrCode", "PDF sayfalarındaki QR kodları tara") + }; + + if (filePaths.Count > 1) + { + list.Insert(0, new("pdf_merge", "PDF'leri Birleştir", "Belge", "PdfMerge", "Tüm PDF'leri tek bir dosyada birleştir")); + } + else + { + list.Add(new("pdf_split", "Sayfaları Ayır", "Belge", "Split", "Her sayfayı ayrı bir PDF yap")); + } + list.Add(new("zip", "ZIP Arşivi", "Arşiv", "Archive", "PDF'leri ZIP olarak arşivle")); + return list; + } + + // Belgeler (DOCX, PPTX, XLSX, TXT, HTML, MD...) + if (allDocs) + { + return new List + { + new("pdf", "PDF Yap", "Belge", "Pdf", "Ofis belgesini PDF formatına dönüştür"), + new("docx", "DOCX Yap", "Belge", "Document", "Modern Word belgesine çevir"), + new("txt", "Düz Metin (TXT)", "Belge", "Text", "Yalnızca metin içeriğini kaydet"), + new("html", "HTML Web Sayfası", "Belge", "Web", "Web formatında HTML çıktısı al"), + new("zip", "ZIP Paketle", "Arşiv", "Archive", "Belgeleri sıkıştırılmış ZIP yap") + }; + } + + // Videolar + if (allVideos) + { + return new List + { + new("mp4", "MP4 Yap", "Video", "Video", "Evrensel MP4 (H.264 / AAC) dönüştür"), + new("mp3", "Sesi MP3 Yap", "Ses", "Audio", "Videodan sesi ayırıp MP3 olarak kaydet"), + new("gif", "Animasyonlu GIF", "Görsel", "Sparkle", "Videoyu hafif ve canlı GIF yap"), + new("webm", "WebM Yap", "Video", "Web", "Web uyumlu VP9/WebM formatına dönüştür"), + new("mkv", "MKV Yap", "Video", "Video", "Yüksek kaliteli MKV konteyneri"), + new("compress_video", "Video Sıkıştır", "Optimizasyon", "Compress", "Kaliteyi koruyarak dosya boyutunu düşür") + }; + } + + // Sesler + if (allAudios) + { + return new List + { + new("mp3", "MP3 Yap", "Ses", "Audio", "Yüksek uyumlu 192kbps MP3"), + new("wav", "WAV Yap", "Ses", "Audio", "Kayıpsız stüdyo WAV formatı"), + new("aac", "AAC / M4A", "Ses", "Audio", "Modern yüksek kaliteli AAC"), + new("flac", "FLAC Yap", "Ses", "Audio", "Kayıpsız FLAC sıkıştırması"), + new("ogg", "OGG Vorbis", "Ses", "Audio", "Açık kaynak OGG formatı"), + new("compress_audio", "Sesi Sıkıştır", "Optimizasyon", "Compress", "Ses boyutunu küçült") + }; + } + + // Arşivler + if (allArchives) + { + return new List + { + new("extract_folder", "Klasöre Çıkar", "Arşiv", "Unpack", "Arşiv içeriğini klasöre çıkar"), + new("zip", "ZIP Formatına Çevir", "Arşiv", "Archive", "Arşivi standart ZIP yap"), + new("7z", "7Z Formatına Çevir", "Arşiv", "Archive", "Ultra sıkıştırmalı 7-Zip yap"), + new("tar_gz", "TAR.GZ Yap", "Arşiv", "Archive", "Linux uyumlu .tar.gz yap") + }; + } + + // Karışık dosyalar + return new List + { + new("zip", "ZIP Arşivi Oluştur", "Arşiv", "Archive", "Tüm seçili dosyaları ZIP dosyasına topla"), + new("7z", "7Z Arşivi Oluştur", "Arşiv", "Archive", "Ultra sıkıştırma ile 7Z arşivi oluştur"), + new("tar_gz", "TAR.GZ Oluştur", "Arşiv", "Archive", "Dosyaları .tar.gz olarak arşivle"), + new("pdf_merge", "Görsel & PDF Birleştir", "Belge", "PdfMerge", "Desteklenen belgeleri tek PDF yap"), + new("copy_folder", "Yeni Klasöre Topla", "Dosya", "Folder", "Dosyaları organize bir klasöre kopyala") + }; + } + + private static IReadOnlyList GetDefaultChoices() + { + return new List + { + new("png", "PNG", "Görsel", "Image", "PNG dönüştür"), + new("jpg", "JPG", "Görsel", "Image", "JPG dönüştür"), + new("webp", "WebP", "Görsel", "Web", "WebP dönüştür"), + new("pdf", "PDF", "Belge", "Pdf", "PDF oluştur"), + new("mp3", "MP3", "Ses", "Audio", "MP3 ses çıkar"), + new("zip", "ZIP Arşivi", "Arşiv", "Archive", "Dosyaları ZIP arşivine sıkıştır") + }; + } +} diff --git a/src/Donustur.Core/Donustur.Core.csproj b/src/Donustur.Core/Donustur.Core.csproj new file mode 100644 index 0000000..fa71b7a --- /dev/null +++ b/src/Donustur.Core/Donustur.Core.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/src/Donustur.Core/Math/WheelMath.cs b/src/Donustur.Core/Math/WheelMath.cs new file mode 100644 index 0000000..9fdaeaf --- /dev/null +++ b/src/Donustur.Core/Math/WheelMath.cs @@ -0,0 +1,79 @@ +namespace Donustur.Core.Math; + +public readonly record struct WheelPoint(double X, double Y); + +public static class WheelMath +{ + /// + /// Fare koordinatına göre fare imlecinin hangi dilim üzerinde olduğunu hesaplar. + /// Dilimler saat yönünde, üstten (90 derece ofsetle) başlar. + /// Merkezdeki ölü bölgede veya çarkın dışındaysa -1 döner. + /// + public static int GetSegmentIndex( + double centerX, + double centerY, + double mouseX, + double mouseY, + int totalSegments, + double deadZoneRadius = 42, + double outerRadius = 175) + { + if (totalSegments <= 0) return -1; + + double dx = mouseX - centerX; + double dy = mouseY - centerY; + double distance = System.Math.Sqrt(dx * dx + dy * dy); + + if (distance < deadZoneRadius || distance > outerRadius) + return -1; + + // dy aşağı doğru pozitif olduğu için ekran koordinatlarında Math.Atan2(dy, dx) + double angleRad = System.Math.Atan2(dy, dx); + double angleDeg = angleRad * (180.0 / System.Math.PI); + + // Standart matematik: 0 derece sağ, 90 derece alt. + // Biz ilk dilimi tam tepeye (saat 12) ortalamak istiyoruz. + // Saat 12 açısı: -90 derece (veya 270 derece). + // Normalize 0 - 360 + if (angleDeg < 0) angleDeg += 360.0; + + // Tepe noktayı (270°) 0° başlangıcına eşlemek için: + // Saat yönünde: 270° -> 0, 0° -> 90, 90° -> 180, 180° -> 270. + // clockAngle = (angleDeg + 90) % 360 + double clockAngle = (angleDeg + 90.0) % 360.0; + + double segmentAngle = 360.0 / totalSegments; + // İlk dilimi tepeye ortalamak için yarım dilim ofset: + double shifted = (clockAngle + (segmentAngle / 2.0)) % 360.0; + + int index = (int)(shifted / segmentAngle); + if (index < 0) index = 0; + if (index >= totalSegments) index = totalSegments - 1; + + return index; + } + + /// + /// Verilen dilimin merkez açısını (derece cinsinden) hesaplar. + /// 0. dilim saat 12 yönündedir (tepede). + /// + public static double GetSegmentCenterAngle(int segmentIndex, int totalSegments) + { + if (totalSegments <= 0) return 0; + double segmentAngle = 360.0 / totalSegments; + // Saat 12 (270 derece ekran koordinatı) + index * segmentAngle + double angle = -90.0 + (segmentIndex * segmentAngle); + return angle; + } + + /// + /// Açı ve yarıçapa göre çember üzerindeki koordinatı hesaplar. + /// + public static WheelPoint GetPointOnCircle(double centerX, double centerY, double radius, double angleInDegrees) + { + double angleRad = angleInDegrees * (System.Math.PI / 180.0); + double x = centerX + (radius * System.Math.Cos(angleRad)); + double y = centerY + (radius * System.Math.Sin(angleRad)); + return new WheelPoint(x, y); + } +} diff --git a/src/Donustur.Core/Models/AppPreferences.cs b/src/Donustur.Core/Models/AppPreferences.cs new file mode 100644 index 0000000..6ee43a2 --- /dev/null +++ b/src/Donustur.Core/Models/AppPreferences.cs @@ -0,0 +1,18 @@ +namespace Donustur.Core.Models; + +public sealed class AppPreferences +{ + public bool Enabled { get; set; } = true; + public string DragModifier { get; set; } = "Shift"; // Shift, Ctrl, Alt, Shift+Ctrl + public double WheelScale { get; set; } = 1.0; + public string Theme { get; set; } = "Dark"; // Dark, Light, System + public string OutputDirectoryMode { get; set; } = "SameAsSource"; // SameAsSource, Desktop, Custom + public string CustomOutputDirectory { get; set; } = string.Empty; + public bool SoundEffectsEnabled { get; set; } = true; + public bool RunAtStartup { get; set; } = false; + public bool MinimizeToTray { get; set; } = false; + public bool AutoOpenOutputFolder { get; set; } = false; + public string? CustomFfmpegPath { get; set; } + public string? CustomLibreOfficePath { get; set; } + public int DefaultImageQuality { get; set; } = 85; +} diff --git a/src/Donustur.Core/Models/ConversionOptions.cs b/src/Donustur.Core/Models/ConversionOptions.cs new file mode 100644 index 0000000..e588515 --- /dev/null +++ b/src/Donustur.Core/Models/ConversionOptions.cs @@ -0,0 +1,21 @@ +namespace Donustur.Core.Models; + +/// +/// Dönüştürme işlemleri için yapılandırma seçenekleri. +/// +public sealed class ConversionOptions +{ + public int ImageQuality { get; set; } = 85; + public int? ResizeWidth { get; set; } + public int? ResizeHeight { get; set; } + public bool StripMetadata { get; set; } = false; + public int PdfDpi { get; set; } = 200; + public string? ArchivePassword { get; set; } + public string VideoPreset { get; set; } = "faster"; + public int VideoCrf { get; set; } = 23; + public string AudioBitrate { get; set; } = "192k"; + public string? DestinationFolder { get; set; } + public bool OverwriteExisting { get; set; } = false; + + public static ConversionOptions Default => new(); +} diff --git a/src/Donustur.Core/Models/ConversionTask.cs b/src/Donustur.Core/Models/ConversionTask.cs new file mode 100644 index 0000000..0a39915 --- /dev/null +++ b/src/Donustur.Core/Models/ConversionTask.cs @@ -0,0 +1,38 @@ +namespace Donustur.Core.Models; + +public enum ConversionTaskStatus +{ + Queued, + Running, + Completed, + Failed, + Cancelled +} + +/// +/// Bir dönüştürme görevinin durum ve çıktı bilgilerini temsil eder. +/// +public sealed class ConversionTask +{ + public string Id { get; init; } = Guid.NewGuid().ToString("N"); + public IReadOnlyList InputFiles { get; init; } = Array.Empty(); + public string TargetActionId { get; init; } = string.Empty; + public string TargetDisplayName { get; init; } = string.Empty; + public ConversionOptions Options { get; init; } = new(); + public ConversionTaskStatus Status { get; set; } = ConversionTaskStatus.Queued; + public double ProgressPercentage { get; set; } + public string? CurrentStatusMessage { get; set; } + public List OutputFiles { get; } = new(); + public DateTime CreatedAt { get; init; } = DateTime.Now; + public DateTime? CompletedAt { get; set; } + public string? ErrorMessage { get; set; } + + public TimeSpan? Duration => CompletedAt.HasValue ? CompletedAt.Value - CreatedAt : null; +} + +public sealed record ConversionResult( + bool Success, + IReadOnlyList OutputFiles, + string? ErrorMessage = null, + TimeSpan? Duration = null +); diff --git a/src/Donustur.Core/Models/ToolChoice.cs b/src/Donustur.Core/Models/ToolChoice.cs new file mode 100644 index 0000000..e9b330c --- /dev/null +++ b/src/Donustur.Core/Models/ToolChoice.cs @@ -0,0 +1,13 @@ +namespace Donustur.Core.Models; + +/// +/// Çark üzerinde veya arayüzde gösterilen dönüştürme/işlem seçeneği. +/// +public sealed record ToolChoice( + string Id, + string DisplayName, + string Category, + string IconKey, + string Description, + bool RequiresOptions = false +); diff --git a/src/Donustur.Core/Services/HistoryStore.cs b/src/Donustur.Core/Services/HistoryStore.cs new file mode 100644 index 0000000..01d11cb --- /dev/null +++ b/src/Donustur.Core/Services/HistoryStore.cs @@ -0,0 +1,147 @@ +using System.Text.Json; + +namespace Donustur.Core.Services; + +public sealed class HistoryEntry +{ + public string Id { get; set; } = Guid.NewGuid().ToString("N"); + public string Title { get; set; } = string.Empty; + public string FormatSummary { get; set; } = string.Empty; + public List InputFiles { get; set; } = new(); + public List OutputFiles { get; set; } = new(); + public long OriginalSizeBytes { get; set; } + public long OutputSizeBytes { get; set; } + public DateTime Timestamp { get; set; } = DateTime.Now; + public bool Success { get; set; } = true; + public string? ErrorMessage { get; set; } +} + +public sealed class HistoryStore +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + PropertyNameCaseInsensitive = true + }; + + private readonly string _filePath; + private readonly List _entries = new(); + private readonly object _lock = new(); + + public IReadOnlyList Entries + { + get + { + lock (_lock) + { + return _entries.ToList(); + } + } + } + + public event Action? Changed; + + public HistoryStore(string? customPath = null) + { + if (!string.IsNullOrWhiteSpace(customPath)) + { + _filePath = customPath; + } + else + { + string localData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + string appDir = Path.Combine(localData, "LDConverter"); + Directory.CreateDirectory(appDir); + _filePath = Path.Combine(appDir, "history.json"); + } + + Load(); + } + + private void Load() + { + lock (_lock) + { + _entries.Clear(); + try + { + if (File.Exists(_filePath)) + { + string json = File.ReadAllText(_filePath); + var list = JsonSerializer.Deserialize>(json, JsonOptions); + if (list != null) + { + _entries.AddRange(list); + } + } + } + catch + { + // Silently fallback on empty history + } + } + } + + public void Add(HistoryEntry entry) + { + lock (_lock) + { + _entries.Insert(0, entry); + // En fazla son 100 işlemi sakla + if (_entries.Count > 100) + { + _entries.RemoveRange(100, _entries.Count - 100); + } + SaveInternal(); + } + Changed?.Invoke(); + } + + public void Remove(string id) + { + bool removed; + lock (_lock) + { + removed = _entries.RemoveAll(e => e.Id == id) > 0; + if (removed) + { + SaveInternal(); + } + } + if (removed) + { + Changed?.Invoke(); + } + } + + public void Clear() + { + lock (_lock) + { + _entries.Clear(); + SaveInternal(); + } + Changed?.Invoke(); + } + + private void SaveInternal() + { + try + { + string dir = Path.GetDirectoryName(_filePath)!; + if (!Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); + } + + string json = JsonSerializer.Serialize(_entries, 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 new file mode 100644 index 0000000..59891e2 --- /dev/null +++ b/src/Donustur.Core/Services/PreferencesStore.cs @@ -0,0 +1,82 @@ +using System.Text.Json; +using Donustur.Core.Models; + +namespace Donustur.Core.Services; + +public sealed class PreferencesStore +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + PropertyNameCaseInsensitive = true + }; + + private readonly string _filePath; + private AppPreferences _current; + + public AppPreferences Current => _current; + + public event Action? Changed; + + public PreferencesStore(string? customPath = null) + { + if (!string.IsNullOrWhiteSpace(customPath)) + { + _filePath = customPath; + } + else + { + string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + string appDir = Path.Combine(appData, "LDConverter"); + Directory.CreateDirectory(appDir); + _filePath = Path.Combine(appDir, "preferences.json"); + } + + _current = Load(); + } + + private AppPreferences Load() + { + try + { + if (File.Exists(_filePath)) + { + string json = File.ReadAllText(_filePath); + var loaded = JsonSerializer.Deserialize(json, JsonOptions); + if (loaded != null) return loaded; + } + } + catch + { + // Fallback to defaults on error + } + + var defaultPrefs = new AppPreferences(); + Save(defaultPrefs); + return defaultPrefs; + } + + public void Save(AppPreferences preferences) + { + try + { + _current = preferences; + 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); + + Changed?.Invoke(_current); + } + catch + { + // Handle error silently + } + } +} diff --git a/src/Donustur.Core/Transactions/ExportTransaction.cs b/src/Donustur.Core/Transactions/ExportTransaction.cs new file mode 100644 index 0000000..0b38cac --- /dev/null +++ b/src/Donustur.Core/Transactions/ExportTransaction.cs @@ -0,0 +1,118 @@ +using Donustur.Core.Utils; + +namespace Donustur.Core.Transactions; + +/// +/// Dönüştürme sırasında hedef klasörün yarım/bozuk dosyalarla kirlenmesini önleyen +/// atomik evreleme (staging) yöneticisi. Farklı disk sürücüleri (C:, D:, USB) arasında +/// klasör hiyerarşisini koruyarak güvenli aktarım yapar. +/// +public sealed class ExportTransaction : IDisposable +{ + private bool _disposed; + public bool IsCommitted { get; private set; } + + public string StagingDirectory { get; } + + public ExportTransaction(string? baseDir = null) + { + string root = string.IsNullOrWhiteSpace(baseDir) + ? Path.Combine(Path.GetTempPath(), "LDConverter") + : baseDir; + + StagingDirectory = Path.Combine(root, "staging_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(StagingDirectory); + } + + /// + /// Staging klasöründeki tüm dosya ve alt klasörleri yapısını koruyarak hedef klasöre taşır. + /// + public List CommitTo(string destinationFolder, bool overwrite = false) + { + if (_disposed) + throw new ObjectDisposedException(nameof(ExportTransaction)); + + if (!Directory.Exists(destinationFolder)) + { + Directory.CreateDirectory(destinationFolder); + } + + var finalPaths = new List(); + + // 1. Üst seviye dosyaları taşı + var topFiles = Directory.GetFiles(StagingDirectory, "*", SearchOption.TopDirectoryOnly); + foreach (var sourceFile in topFiles) + { + string fileName = Path.GetFileName(sourceFile); + string dest = Path.Combine(destinationFolder, fileName); + + if (!overwrite && (File.Exists(dest) || Directory.Exists(dest))) + { + dest = SafePaths.GetUniquePath(destinationFolder, fileName); + } + + File.Move(sourceFile, dest, overwrite: true); + finalPaths.Add(dest); + } + + // 2. Üst seviye klasörleri (örn. arşivden çıkarılan klasörler) alt yapısıyla birlikte taşı + var topDirs = Directory.GetDirectories(StagingDirectory, "*", SearchOption.TopDirectoryOnly); + foreach (var sourceDir in topDirs) + { + string dirName = Path.GetFileName(sourceDir); + string destDir = Path.Combine(destinationFolder, dirName); + + if (!overwrite && (Directory.Exists(destDir) || File.Exists(destDir))) + { + destDir = SafePaths.GetUniquePath(destinationFolder, dirName); + } + + MoveDirectoryCrossVolume(sourceDir, destDir); + finalPaths.Add(destDir); + } + + IsCommitted = true; + return finalPaths; + } + + private static void MoveDirectoryCrossVolume(string sourceDir, string destDir) + { + Directory.CreateDirectory(destDir); + + foreach (var dir in Directory.GetDirectories(sourceDir, "*", SearchOption.AllDirectories)) + { + string relative = Path.GetRelativePath(sourceDir, dir); + Directory.CreateDirectory(Path.Combine(destDir, relative)); + } + + foreach (var file in Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories)) + { + string relative = Path.GetRelativePath(sourceDir, file); + string targetFile = Path.Combine(destDir, relative); + string? targetParent = Path.GetDirectoryName(targetFile); + if (!string.IsNullOrEmpty(targetParent)) + { + Directory.CreateDirectory(targetParent); + } + File.Move(file, targetFile, overwrite: true); + } + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + + try + { + if (Directory.Exists(StagingDirectory)) + { + Directory.Delete(StagingDirectory, recursive: true); + } + } + catch + { + // Arka plandaki kilitli dosyalar için sessizce geç + } + } +} diff --git a/src/Donustur.Core/Utils/FileUtils.cs b/src/Donustur.Core/Utils/FileUtils.cs new file mode 100644 index 0000000..733e887 --- /dev/null +++ b/src/Donustur.Core/Utils/FileUtils.cs @@ -0,0 +1,64 @@ +namespace Donustur.Core.Utils; + +public static class FileUtils +{ + private static readonly string[] SizeSuffixes = { "B", "KB", "MB", "GB", "TB" }; + + public static string FormatBytes(long bytes) + { + if (bytes < 0) return "-" + FormatBytes(-bytes); + if (bytes == 0) return "0 B"; + + int mag = (int)System.Math.Log(bytes, 1024); + if (mag >= SizeSuffixes.Length) mag = SizeSuffixes.Length - 1; + + decimal adjustedSize = (decimal)bytes / (1L << (mag * 10)); + return string.Format("{0:n1} {1}", adjustedSize, SizeSuffixes[mag]); + } + + public static string FormatPercentChange(long initialBytes, long finalBytes) + { + if (initialBytes <= 0) return "0%"; + double diff = (double)(finalBytes - initialBytes) / initialBytes * 100.0; + if (diff > 0) + return $"+{diff:F1}%"; + return $"{diff:F1}%"; + } + + /// + /// Verilen dosya veya klasör yollarının toplam bayt boyutunu hesaplar. + /// + public static long CalculateTotalBytes(IEnumerable paths) + { + long total = 0; + foreach (var path in paths) + { + try + { + if (File.Exists(path)) + { + total += new FileInfo(path).Length; + } + else if (Directory.Exists(path)) + { + foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) + { + try + { + total += new FileInfo(file).Length; + } + catch + { + // Erişilemeyen alt dosyaları atla + } + } + } + } + catch + { + // Erişilemeyen yolları atla + } + } + return total; + } +} diff --git a/src/Donustur.Core/Utils/SafePaths.cs b/src/Donustur.Core/Utils/SafePaths.cs new file mode 100644 index 0000000..1badd58 --- /dev/null +++ b/src/Donustur.Core/Utils/SafePaths.cs @@ -0,0 +1,35 @@ +namespace Donustur.Core.Utils; + +public static class SafePaths +{ + public static string EnsureDirectory(string path) + { + if (!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + return path; + } + + public static string GetUniquePath(string directory, string desiredFileName) + { + EnsureDirectory(directory); + string targetPath = Path.Combine(directory, desiredFileName); + if (!File.Exists(targetPath) && !Directory.Exists(targetPath)) + { + return targetPath; + } + + string nameWithoutExt = Path.GetFileNameWithoutExtension(desiredFileName); + string ext = Path.GetExtension(desiredFileName); + int counter = 1; + + do + { + targetPath = Path.Combine(directory, $"{nameWithoutExt} ({counter}){ext}"); + counter++; + } while (File.Exists(targetPath) || Directory.Exists(targetPath)); + + return targetPath; + } +} diff --git a/src/Donustur.Engine/Archives/ArchiveEngine.cs b/src/Donustur.Engine/Archives/ArchiveEngine.cs new file mode 100644 index 0000000..bba9810 --- /dev/null +++ b/src/Donustur.Engine/Archives/ArchiveEngine.cs @@ -0,0 +1,522 @@ +using System.IO.Compression; +using Donustur.Core.Catalog; +using Donustur.Core.Transactions; +using Donustur.Core.Utils; +using SharpCompress.Archives; +using SharpCompress.Common; +using SharpCompress.Readers; +using SharpCompress.Writers; + +namespace Donustur.Engine.Archives; + +public sealed class ArchiveEngine +{ + public static string? Resolve7ZipPath() + { + string[] candidates = + { + @"C:\Program Files\7-Zip\7z.exe", + @"C:\Program Files (x86)\7-Zip\7z.exe", + @"C:\ProgramData\chocolatey\bin\7z.exe" + }; + + foreach (var c in candidates) + { + if (File.Exists(c)) return c; + } + + string? pathEnv = Environment.GetEnvironmentVariable("PATH"); + if (pathEnv != null) + { + foreach (var segment in pathEnv.Split(Path.PathSeparator)) + { + if (string.IsNullOrWhiteSpace(segment)) continue; + string combined = Path.Combine(segment.Trim(), "7z.exe"); + if (File.Exists(combined)) return combined; + } + } + + return null; + } + + public bool Is7ZipAvailable => Resolve7ZipPath() != null; + + /// + /// Arşiv dosyasını klasöre çıkarır. ZIP, 7Z, TAR, GZ, TGZ, RAR destekler. + /// + public async Task ExtractAsync( + string archivePath, + ExportTransaction transaction, + string? password = null, + IProgress? progress = null, + CancellationToken token = default) + { + string baseName = GetCleanArchiveBaseName(archivePath); + string extractDir = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + "_Cikarilan"); + Directory.CreateDirectory(extractDir); + + await Task.Run(() => + { + ExtractToDirectoryInternal(archivePath, extractDir, password, progress, token); + }, token); + + return extractDir; + } + + private static void ExtractToDirectoryInternal( + string archivePath, + string extractDir, + string? password, + IProgress? progress, + CancellationToken token) + { + string lowerName = Path.GetFileName(archivePath).ToLowerInvariant(); + var readerOptions = new ReaderOptions { Password = password }; + + // .tar.gz / .tgz / .gz akış tabanlı arşivler için ReaderFactory kullan + if (lowerName.EndsWith(".tar.gz") || lowerName.EndsWith(".tgz") || lowerName.EndsWith(".gz")) + { + using var fileStream = File.OpenRead(archivePath); + using var reader = ReaderFactory.OpenReader(fileStream, readerOptions); + while (reader.MoveToNextEntry()) + { + token.ThrowIfCancellationRequested(); + if (!reader.Entry.IsDirectory) + { + reader.WriteEntryToDirectory(extractDir, new ExtractionOptions + { + ExtractFullPath = true, + Overwrite = true + }); + } + } + progress?.Report(100.0); + return; + } + + using var archive = ArchiveFactory.OpenArchive(archivePath, readerOptions); + var entries = archive.Entries.Where(e => !e.IsDirectory).ToList(); + int total = Math.Max(1, entries.Count); + + for (int i = 0; i < entries.Count; i++) + { + token.ThrowIfCancellationRequested(); + var entry = entries[i]; + entry.WriteToDirectory(extractDir, new ExtractionOptions + { + ExtractFullPath = true, + Overwrite = true + }); + + progress?.Report((double)(i + 1) / total * 100.0); + } + } + + /// + /// Verilen dosyaları (veya mevcut arşivlerin içeriğini) ZIP arşivi olarak paketler. + /// + public async Task CreateZipAsync( + IReadOnlyList files, + ExportTransaction transaction, + string? zipName = null, + IProgress? progress = null, + CancellationToken token = default) + { + // Eğer girdilerin tamamı zaten arşivse (örn. .rar veya .7z -> .zip dönüşümü), önce açıp sonra ZIP yap + if (files.Count > 0 && files.All(FormatCatalog.IsArchive)) + { + return await ConvertArchivesToFormatAsync(files, "zip", transaction, progress, token); + } + + string name = string.IsNullOrWhiteSpace(zipName) + ? (files.Count == 1 ? Path.GetFileNameWithoutExtension(files[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) + ".zip" : "Arsiv.zip") + : zipName; + + if (!name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) + { + name += ".zip"; + } + + string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, name); + + await Task.Run(() => + { + using var zipStream = new FileStream(outputPath, FileMode.Create); + using var archive = new ZipArchive(zipStream, ZipArchiveMode.Create); + var usedEntryNames = new HashSet(StringComparer.OrdinalIgnoreCase); + + for (int i = 0; i < files.Count; i++) + { + token.ThrowIfCancellationRequested(); + string file = files[i]; + + if (File.Exists(file)) + { + string entryName = GetUniqueArchiveEntryName(Path.GetFileName(file), usedEntryNames); + archive.CreateEntryFromFile(file, entryName, CompressionLevel.Optimal); + } + else if (Directory.Exists(file)) + { + string dirName = Path.GetFileName(file.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); + AddDirectoryToZip(archive, file, dirName, usedEntryNames); + } + + progress?.Report((double)(i + 1) / files.Count * 100.0); + } + }, token); + + return outputPath; + } + + /// + /// Verilen dosyaları .tar.gz olarak paketler. + /// + public async Task CreateTarGzAsync( + IReadOnlyList files, + ExportTransaction transaction, + string? archiveName = null, + IProgress? progress = null, + CancellationToken token = default) + { + if (files.Count > 0 && files.All(FormatCatalog.IsArchive)) + { + return await ConvertArchivesToFormatAsync(files, "tar_gz", transaction, progress, token); + } + + string baseName = string.IsNullOrWhiteSpace(archiveName) + ? (files.Count == 1 ? GetCleanArchiveBaseName(files[0]) : "Arsiv") + : GetCleanArchiveBaseName(archiveName); + + string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + ".tar.gz"); + + await Task.Run(() => + { + using var stream = File.OpenWrite(outputPath); + var writerOptions = new WriterOptions(CompressionType.GZip) { LeaveStreamOpen = false }; + using var writer = WriterFactory.OpenWriter(stream, ArchiveType.Tar, writerOptions); + + for (int i = 0; i < files.Count; i++) + { + token.ThrowIfCancellationRequested(); + string item = files[i]; + + if (File.Exists(item)) + { + writer.Write(Path.GetFileName(item), item); + } + else if (Directory.Exists(item)) + { + string prefix = Path.GetFileName(item.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); + foreach (var subFile in Directory.GetFiles(item, "*", SearchOption.AllDirectories)) + { + token.ThrowIfCancellationRequested(); + string rel = Path.Combine(prefix, Path.GetRelativePath(item, subFile)).Replace('\\', '/'); + writer.Write(rel, subFile); + } + } + + progress?.Report((double)(i + 1) / files.Count * 100.0); + } + }, token); + + return outputPath; + } + + /// + /// Verilen dosyaları 7-Zip (.7z) olarak paketler. Sistemde 7z.exe varsa kullanır. + /// + public async Task Create7zAsync( + IReadOnlyList files, + ExportTransaction transaction, + string? archiveName = null, + IProgress? progress = null, + CancellationToken token = default) + { + if (files.Count > 0 && files.All(FormatCatalog.IsArchive)) + { + return await ConvertArchivesToFormatAsync(files, "7z", transaction, progress, token); + } + + string? sevenZipExe = Resolve7ZipPath(); + if (sevenZipExe == null) + { + throw new FileNotFoundException( + "7-Zip (7z.exe) sistemde bulunamadı. .7z formatında sıkıştırma için 7-Zip kurulu olmalıdır (veya ZIP / TAR.GZ seçeneğini kullanabilirsiniz)."); + } + + string baseName = string.IsNullOrWhiteSpace(archiveName) + ? (files.Count == 1 ? GetCleanArchiveBaseName(files[0]) : "Arsiv") + : GetCleanArchiveBaseName(archiveName); + + string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + ".7z"); + string quotedFiles = string.Join(" ", files.Select(f => $"\"{f}\"")); + string args = $"a -t7z -mx=7 -y \"{outputPath}\" {quotedFiles}"; + + progress?.Report(25.0); + var result = await ProcessRunner.RunAsync(sevenZipExe, args, token: token); + if (result.ExitCode != 0) + { + throw new InvalidOperationException($"7-Zip arşivleme hatası ({result.ExitCode}): {result.StandardError}"); + } + + progress?.Report(100.0); + return outputPath; + } + + /// + /// Mevcut bir arşivi (RAR, 7Z, ZIP, TAR.GZ) açıp hedef arşiv formatına (ZIP, 7Z, TAR.GZ) dönüştürür. + /// + private async Task ConvertArchivesToFormatAsync( + IReadOnlyList archiveFiles, + string targetFormat, + ExportTransaction transaction, + IProgress? progress, + CancellationToken token) + { + string tempExtractRoot = Path.Combine(Path.GetTempPath(), "Donustur", "repack_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempExtractRoot); + + try + { + for (int i = 0; i < archiveFiles.Count; i++) + { + token.ThrowIfCancellationRequested(); + string archivePath = archiveFiles[i]; + string subDir = archiveFiles.Count == 1 + ? tempExtractRoot + : Path.Combine(tempExtractRoot, GetCleanArchiveBaseName(archivePath)); + Directory.CreateDirectory(subDir); + + await Task.Run(() => + { + ExtractToDirectoryInternal(archivePath, subDir, null, null, token); + }, token); + + progress?.Report((double)(i + 1) / archiveFiles.Count * 50.0); + } + + var extractedItems = Directory.GetFileSystemEntries(tempExtractRoot).ToList(); + if (extractedItems.Count == 0) + { + throw new InvalidOperationException("Kaynak arşiv boş olduğu için dönüştürülemedi."); + } + + string baseName = archiveFiles.Count == 1 + ? GetCleanArchiveBaseName(archiveFiles[0]) + : "Donusturulen_Arsiv"; + + return targetFormat switch + { + "7z" => await Create7zFromExtractedAsync(extractedItems, baseName, transaction, progress, token), + "tar_gz" => await CreateTarGzFromExtractedAsync(extractedItems, baseName, transaction, progress, token), + _ => await CreateZipFromExtractedAsync(extractedItems, baseName, transaction, progress, token) + }; + } + finally + { + try + { + if (Directory.Exists(tempExtractRoot)) + { + Directory.Delete(tempExtractRoot, recursive: true); + } + } + catch + { + // Geçici klasör temizleme hatasını yoksay + } + } + } + + private async Task CreateZipFromExtractedAsync( + IReadOnlyList items, + string baseName, + ExportTransaction transaction, + IProgress? progress, + CancellationToken token) + { + string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + ".zip"); + await Task.Run(() => + { + using var zipStream = new FileStream(outputPath, FileMode.Create); + using var archive = new ZipArchive(zipStream, ZipArchiveMode.Create); + var usedNames = new HashSet(StringComparer.OrdinalIgnoreCase); + + for (int i = 0; i < items.Count; i++) + { + token.ThrowIfCancellationRequested(); + string item = items[i]; + if (File.Exists(item)) + { + string entryName = GetUniqueArchiveEntryName(Path.GetFileName(item), usedNames); + archive.CreateEntryFromFile(item, entryName, CompressionLevel.Optimal); + } + else if (Directory.Exists(item)) + { + AddDirectoryToZip(archive, item, Path.GetFileName(item), usedNames); + } + progress?.Report(50.0 + ((double)(i + 1) / items.Count * 50.0)); + } + }, token); + return outputPath; + } + + private async Task CreateTarGzFromExtractedAsync( + IReadOnlyList items, + string baseName, + ExportTransaction transaction, + IProgress? progress, + CancellationToken token) + { + string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + ".tar.gz"); + await Task.Run(() => + { + using var stream = File.OpenWrite(outputPath); + var writerOptions = new WriterOptions(CompressionType.GZip) { LeaveStreamOpen = false }; + using var writer = WriterFactory.OpenWriter(stream, ArchiveType.Tar, writerOptions); + + for (int i = 0; i < items.Count; i++) + { + token.ThrowIfCancellationRequested(); + string item = items[i]; + if (File.Exists(item)) + { + writer.Write(Path.GetFileName(item), item); + } + else if (Directory.Exists(item)) + { + string prefix = Path.GetFileName(item); + foreach (var subFile in Directory.GetFiles(item, "*", SearchOption.AllDirectories)) + { + token.ThrowIfCancellationRequested(); + string rel = Path.Combine(prefix, Path.GetRelativePath(item, subFile)).Replace('\\', '/'); + writer.Write(rel, subFile); + } + } + progress?.Report(50.0 + ((double)(i + 1) / items.Count * 50.0)); + } + }, token); + return outputPath; + } + + private async Task Create7zFromExtractedAsync( + IReadOnlyList items, + string baseName, + ExportTransaction transaction, + IProgress? progress, + CancellationToken token) + { + string? sevenZipExe = Resolve7ZipPath(); + if (sevenZipExe == null) + { + throw new FileNotFoundException("7-Zip (7z.exe) sistemde bulunamadı."); + } + + string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + ".7z"); + string quotedFiles = string.Join(" ", items.Select(f => $"\"{f}\"")); + string args = $"a -t7z -mx=7 -y \"{outputPath}\" {quotedFiles}"; + + var result = await ProcessRunner.RunAsync(sevenZipExe, args, token: token); + if (result.ExitCode != 0) + { + throw new InvalidOperationException($"7-Zip arşivleme hatası ({result.ExitCode}): {result.StandardError}"); + } + progress?.Report(100.0); + return outputPath; + } + + /// + /// Seçili dosya ve klasörleri yeni bir klasör altında toplar. + /// + public async Task CollectToFolderAsync( + IReadOnlyList files, + ExportTransaction transaction, + IProgress? progress = null, + CancellationToken token = default) + { + string folderName = $"Toplanan_Dosyalar_{DateTime.Now:yyyyMMdd_HHmm}"; + string targetFolder = SafePaths.GetUniquePath(transaction.StagingDirectory, folderName); + Directory.CreateDirectory(targetFolder); + + await Task.Run(() => + { + for (int i = 0; i < files.Count; i++) + { + token.ThrowIfCancellationRequested(); + string item = files[i]; + if (File.Exists(item)) + { + string destFile = SafePaths.GetUniquePath(targetFolder, Path.GetFileName(item)); + File.Copy(item, destFile, overwrite: true); + } + else if (Directory.Exists(item)) + { + string dirName = Path.GetFileName(item.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); + string destSubDir = SafePaths.GetUniquePath(targetFolder, dirName); + CopyDirectoryRecursive(item, destSubDir, token); + } + + progress?.Report((double)(i + 1) / files.Count * 100.0); + } + }, token); + + return targetFolder; + } + + private static void CopyDirectoryRecursive(string sourceDir, string destDir, CancellationToken token) + { + Directory.CreateDirectory(destDir); + foreach (var dir in Directory.GetDirectories(sourceDir, "*", SearchOption.AllDirectories)) + { + token.ThrowIfCancellationRequested(); + string rel = Path.GetRelativePath(sourceDir, dir); + Directory.CreateDirectory(Path.Combine(destDir, rel)); + } + foreach (var file in Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories)) + { + token.ThrowIfCancellationRequested(); + string rel = Path.GetRelativePath(sourceDir, file); + File.Copy(file, Path.Combine(destDir, rel), overwrite: true); + } + } + + private static string GetCleanArchiveBaseName(string path) + { + string name = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); + if (name.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase)) + { + return name[..^7]; + } + return Path.GetFileNameWithoutExtension(name); + } + + private static string GetUniqueArchiveEntryName(string desiredName, HashSet usedNames) + { + if (usedNames.Add(desiredName)) return desiredName; + + string nameNoExt = Path.GetFileNameWithoutExtension(desiredName); + string ext = Path.GetExtension(desiredName); + int counter = 1; + string candidate; + do + { + candidate = $"{nameNoExt} ({counter}){ext}"; + counter++; + } while (!usedNames.Add(candidate)); + + return candidate; + } + + private static void AddDirectoryToZip(ZipArchive archive, string sourceDir, string entryPrefix, HashSet usedNames) + { + foreach (var file in Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories)) + { + string relative = Path.GetRelativePath(sourceDir, file); + string entryName = Path.Combine(entryPrefix, relative).Replace('\\', '/'); + if (usedNames.Add(entryName)) + { + archive.CreateEntryFromFile(file, entryName, CompressionLevel.Optimal); + } + } + } +} diff --git a/src/Donustur.Engine/ConversionDispatcher.cs b/src/Donustur.Engine/ConversionDispatcher.cs new file mode 100644 index 0000000..b175f86 --- /dev/null +++ b/src/Donustur.Engine/ConversionDispatcher.cs @@ -0,0 +1,344 @@ +using Donustur.Core.Catalog; +using Donustur.Core.Models; +using Donustur.Core.Services; +using Donustur.Core.Transactions; +using Donustur.Core.Utils; +using Donustur.Engine.Archives; +using Donustur.Engine.Documents; +using Donustur.Engine.Images; +using Donustur.Engine.Media; +using Donustur.Engine.Qr; + +namespace Donustur.Engine; + +public sealed class ConversionDispatcher +{ + private readonly ImageMagickEngine _imageEngine = new(); + private readonly OfficeDocumentEngine _officeEngine; + private readonly PdfEngine _pdfEngine = new(); + private readonly MediaEngine _mediaEngine; + private readonly ArchiveEngine _archiveEngine = new(); + private readonly QrEngine _qrEngine = new(); + private readonly HistoryStore? _historyStore; + + public ConversionDispatcher(AppPreferences preferences, HistoryStore? historyStore = null) + { + _officeEngine = new OfficeDocumentEngine(preferences.CustomLibreOfficePath); + _mediaEngine = new MediaEngine(preferences.CustomFfmpegPath); + _historyStore = historyStore; + } + + public async Task ExecuteTaskAsync( + ConversionTask task, + AppPreferences preferences, + 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) + { + task.Options.ImageQuality = preferences.DefaultImageQuality; + } + + string targetAction = task.TargetActionId.ToLowerInvariant().TrimStart('.'); + string destination = ResolveDestinationFolder(task, preferences); + + using var transaction = new ExportTransaction(); + + try + { + var files = task.InputFiles; + if (files.Count == 0) + { + 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++) + { + 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); + } + + 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); + } + 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 + { + // 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) + 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); + } + } + + private static string FormatFriendlyActionLabel(string action) + { + return action switch + { + "pdf_to_images" => "PNG", + "pdf_to_jpg" => "JPG", + "pdf_to_txt" => "TXT", + "pdf_to_docx" => "DOCX", + "pdf_merge" => "PDF BİRLEŞTİR", + "pdf_split" => "PDF AYIR", + "extract_folder" => "KLASÖRE ÇIKAR", + "copy_folder" => "KLASÖRE TOPLA", + "compress_image" or "compress_video" or "compress_audio" => "SIKIŞTIR", + "qr_read" => "QR OKU", + "tar_gz" => "TAR.GZ", + _ => action.ToUpperInvariant() + }; + } + + public static string ResolveDestinationFolder(ConversionTask task, AppPreferences preferences) + { + if (!string.IsNullOrWhiteSpace(task.Options.DestinationFolder) && Directory.Exists(task.Options.DestinationFolder)) + { + return task.Options.DestinationFolder; + } + + if (preferences.OutputDirectoryMode == "Desktop") + { + return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); + } + + if (preferences.OutputDirectoryMode == "Custom" && + !string.IsNullOrWhiteSpace(preferences.CustomOutputDirectory)) + { + try + { + if (!Directory.Exists(preferences.CustomOutputDirectory)) + { + Directory.CreateDirectory(preferences.CustomOutputDirectory); + } + return preferences.CustomOutputDirectory; + } + catch + { + // Özel klasör oluşturulamazsa kaynak klasöre dön + } + } + + // SameAsSource (Hem dosya hem klasör girdilerini destekler) + if (task.InputFiles.Count > 0) + { + string first = task.InputFiles[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + if (File.Exists(first) || Directory.Exists(first)) + { + string? dir = Path.GetDirectoryName(first); + if (!string.IsNullOrWhiteSpace(dir) && Directory.Exists(dir)) + { + return dir; + } + } + } + + return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); + } +} diff --git a/src/Donustur.Engine/Documents/DocxHelper.cs b/src/Donustur.Engine/Documents/DocxHelper.cs new file mode 100644 index 0000000..8c5fc4f --- /dev/null +++ b/src/Donustur.Engine/Documents/DocxHelper.cs @@ -0,0 +1,136 @@ +using System.IO.Compression; +using System.Security; +using System.Text; +using System.Xml.Linq; + +namespace Donustur.Engine.Documents; + +/// +/// Harici ofis kurulumuna ihtiyaç duymadan standart OpenXML (.docx) dosyaları +/// oluşturmak ve mevcut .docx dosyalarından metin okumak için yerel yardımcı. +/// +public static class DocxHelper +{ + public static void CreateDocxFromPages(string outputPath, IReadOnlyList pages) + { + if (File.Exists(outputPath)) + { + File.Delete(outputPath); + } + + using var fs = new FileStream(outputPath, FileMode.Create, FileAccess.Write); + using var archive = new ZipArchive(fs, ZipArchiveMode.Create); + + // 1. [Content_Types].xml + WriteZipText(archive, "[Content_Types].xml", """ + + + + + + + """); + + // 2. _rels/.rels + WriteZipText(archive, "_rels/.rels", """ + + + + + """); + + // 3. word/document.xml + var sb = new StringBuilder(); + sb.AppendLine(""""""); + sb.AppendLine(""""""); + sb.AppendLine(" "); + + for (int p = 0; p < pages.Count; p++) + { + string pageText = SanitizeXmlChars(pages[p] ?? string.Empty); + string[] lines = pageText.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); + + foreach (var line in lines) + { + string escaped = SecurityElement.Escape(line) ?? string.Empty; + sb.AppendLine(" "); + if (!string.IsNullOrEmpty(escaped)) + { + sb.AppendLine($" {escaped}"); + } + sb.AppendLine(" "); + } + + if (p < pages.Count - 1) + { + sb.AppendLine(" "); + } + } + + sb.AppendLine(" "); + sb.AppendLine(""); + + WriteZipText(archive, "word/document.xml", sb.ToString()); + } + + public static string ExtractTextFromDocx(string docxPath) + { + using var fs = File.OpenRead(docxPath); + using var archive = new ZipArchive(fs, ZipArchiveMode.Read); + var docEntry = archive.GetEntry("word/document.xml"); + if (docEntry == null) + { + throw new InvalidOperationException("Geçerli bir DOCX belgesi değil (word/document.xml bulunamadı)."); + } + + using var entryStream = docEntry.Open(); + var xdoc = XDocument.Load(entryStream); + XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + + var sb = new StringBuilder(); + foreach (var para in xdoc.Descendants(w + "p")) + { + var paraText = new StringBuilder(); + foreach (var node in para.Descendants()) + { + if (node.Name == w + "t") + { + paraText.Append(node.Value); + } + else if (node.Name == w + "tab") + { + paraText.Append('\t'); + } + else if (node.Name == w + "br") + { + paraText.AppendLine(); + } + } + sb.AppendLine(paraText.ToString()); + } + + return sb.ToString(); + } + + private static void WriteZipText(ZipArchive archive, string entryName, string content) + { + var entry = archive.CreateEntry(entryName, CompressionLevel.Optimal); + using var stream = entry.Open(); + using var writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + writer.Write(content.Trim()); + } + + private static string SanitizeXmlChars(string input) + { + if (string.IsNullOrEmpty(input)) return string.Empty; + var sb = new StringBuilder(input.Length); + foreach (char c in input) + { + if (c == '\t' || c == '\n' || c == '\r' || (c >= 0x20 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD)) + { + sb.Append(c); + } + } + return sb.ToString(); + } +} diff --git a/src/Donustur.Engine/Documents/OfficeDocumentEngine.cs b/src/Donustur.Engine/Documents/OfficeDocumentEngine.cs new file mode 100644 index 0000000..0ef7a6a --- /dev/null +++ b/src/Donustur.Engine/Documents/OfficeDocumentEngine.cs @@ -0,0 +1,315 @@ +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using Donustur.Core.Catalog; +using Donustur.Core.Transactions; +using Donustur.Core.Utils; +using PdfSharpCore.Drawing; +using PdfSharpCore.Pdf; + +namespace Donustur.Engine.Documents; + +public sealed class OfficeDocumentEngine +{ + private string? _customPath; + + public OfficeDocumentEngine(string? customPath = null) + { + _customPath = customPath; + } + + public void SetCustomPath(string? customPath) + { + _customPath = customPath; + } + + /// + /// LibreOffice soffice.exe yolunu bulur. + /// + public string? ResolveSofficePath() + { + if (!string.IsNullOrWhiteSpace(_customPath) && File.Exists(_customPath)) + { + return _customPath; + } + + string[] standardLocations = + { + @"C:\Program Files\LibreOffice\program\soffice.exe", + @"C:\Program Files (x86)\LibreOffice\program\soffice.exe" + }; + + foreach (var loc in standardLocations) + { + if (File.Exists(loc)) + return loc; + } + + string? pathEnv = Environment.GetEnvironmentVariable("PATH"); + if (pathEnv != null) + { + foreach (var path in pathEnv.Split(Path.PathSeparator)) + { + if (string.IsNullOrWhiteSpace(path)) continue; + string combined = Path.Combine(path.Trim(), "soffice.exe"); + if (File.Exists(combined)) + return combined; + } + } + + return null; + } + + public bool IsAvailable => ResolveSofficePath() != null; + + /// + /// Ofis ve metin belgelerini (DOCX, PPTX, XLSX, ODT, TXT, MD, HTML vb.) PDF veya diğer formatlara dönüştürür. + /// LibreOffice kuruluysa tam sadakatli motoru kullanır; kurulu değilse yerel OpenXML/PDF/HTML motoruna başvurur. + /// + public async Task> ConvertDocumentsAsync( + IReadOnlyList inputFiles, + string targetFormat, + ExportTransaction transaction, + IProgress? progress = null, + CancellationToken token = default) + { + var outputFiles = new List(); + string formatKey = targetFormat.ToLowerInvariant().TrimStart('.'); + string? sofficePath = ResolveSofficePath(); + + for (int i = 0; i < inputFiles.Count; i++) + { + token.ThrowIfCancellationRequested(); + string inputFile = inputFiles[i]; + string sourceExt = FormatCatalog.NormalizeExtension(inputFile); + string baseName = Path.GetFileNameWithoutExtension(inputFile); + + // Kaynak ve hedef uzantı aynıysa doğrudan kopyala + if (string.Equals(sourceExt, formatKey, StringComparison.OrdinalIgnoreCase)) + { + string copyDest = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + "." + formatKey); + File.Copy(inputFile, copyDest, overwrite: true); + outputFiles.Add(copyDest); + progress?.Report((double)(i + 1) / inputFiles.Count * 100.0); + continue; + } + + string? generatedPath = null; + + // 1. Öncelik: LibreOffice kuruluysa izole profil ile çalıştır + if (sofficePath != null) + { + generatedPath = await TryConvertWithLibreOfficeAsync(sofficePath, inputFile, formatKey, transaction, token); + } + + // 2. Yedek: Yerel dönüştürücü (TXT, MD, HTML, DOCX <-> PDF, DOCX, TXT, HTML) + if (generatedPath == null || !File.Exists(generatedPath)) + { + if (CanConvertNatively(sourceExt, formatKey)) + { + generatedPath = await Task.Run(() => ConvertNatively(inputFile, sourceExt, formatKey, transaction), token); + } + else if (sofficePath == null) + { + throw new FileNotFoundException( + $"'{sourceExt.ToUpperInvariant()} → {formatKey.ToUpperInvariant()}' dönüşümü için LibreOffice gereklidir. " + + "Lütfen LibreOffice'i yükleyin (www.libreoffice.org) veya Ayarlar ekranından soffice.exe yolunu belirtin."); + } + else + { + throw new InvalidOperationException($"Belge dönüştürülemedi: {Path.GetFileName(inputFile)}"); + } + } + + outputFiles.Add(generatedPath); + progress?.Report((double)(i + 1) / inputFiles.Count * 100.0); + } + + return outputFiles; + } + + private static async Task TryConvertWithLibreOfficeAsync( + string sofficePath, + string inputFile, + string formatKey, + ExportTransaction transaction, + CancellationToken token) + { + string tempProfileDir = Path.Combine(Path.GetTempPath(), "Donustur", "lo_profile_" + Guid.NewGuid().ToString("N")); + string tempOutDir = Path.Combine(transaction.StagingDirectory, "lo_work_" + Guid.NewGuid().ToString("N")[..6]); + Directory.CreateDirectory(tempProfileDir); + Directory.CreateDirectory(tempOutDir); + + try + { + string profileUri = new Uri(tempProfileDir).AbsoluteUri; + string filterArg = formatKey == "txt" ? "txt:Text (encoded):UTF8" : formatKey; + string args = $"-env:UserInstallation={profileUri} --headless --norestore --convert-to \"{filterArg}\" --outdir \"{tempOutDir}\" \"{inputFile}\""; + + var result = await ProcessRunner.RunAsync(sofficePath, args, token: token); + if (result.ExitCode != 0) + { + return null; + } + + var generated = Directory.GetFiles(tempOutDir); + if (generated.Length == 0) + { + return null; + } + + string desiredFileName = Path.GetFileNameWithoutExtension(inputFile) + "." + formatKey; + string finalStagedPath = SafePaths.GetUniquePath(transaction.StagingDirectory, desiredFileName); + File.Move(generated[0], finalStagedPath, overwrite: true); + return finalStagedPath; + } + catch + { + return null; + } + finally + { + try { if (Directory.Exists(tempOutDir)) Directory.Delete(tempOutDir, true); } catch { } + try { if (Directory.Exists(tempProfileDir)) Directory.Delete(tempProfileDir, true); } catch { } + } + } + + private static bool CanConvertNatively(string sourceExt, string targetFormat) + { + bool supportedSource = sourceExt is "txt" or "md" or "html" or "docx"; + bool supportedTarget = targetFormat is "txt" or "html" or "docx" or "pdf"; + return supportedSource && supportedTarget; + } + + private static string ConvertNatively(string inputFile, string sourceExt, string targetFormat, ExportTransaction transaction) + { + string baseName = Path.GetFileNameWithoutExtension(inputFile); + string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, $"{baseName}.{targetFormat}"); + + string plainText = ReadDocumentPlainText(inputFile, sourceExt); + + switch (targetFormat) + { + case "txt": + File.WriteAllText(outPath, plainText, Encoding.UTF8); + break; + + case "docx": + DocxHelper.CreateDocxFromPages(outPath, new[] { plainText }); + break; + + case "html": + string html = BuildHtmlFromText(baseName, plainText); + File.WriteAllText(outPath, html, Encoding.UTF8); + break; + + case "pdf": + RenderTextToPdf(plainText, outPath); + break; + + default: + throw new NotSupportedException($"Desteklenmeyen hedef belge formatı: {targetFormat}"); + } + + return outPath; + } + + private static string ReadDocumentPlainText(string inputFile, string sourceExt) + { + if (sourceExt == "docx") + { + return DocxHelper.ExtractTextFromDocx(inputFile); + } + + string raw = File.ReadAllText(inputFile, Encoding.UTF8); + if (sourceExt == "html") + { + string withoutScripts = Regex.Replace(raw, @"<(script|style)[^>]*?>.*?", "", RegexOptions.Singleline | RegexOptions.IgnoreCase); + string withBreaks = Regex.Replace(withoutScripts, @"<(br|p|div|li|tr|h[1-6])[^>]*?>", "\n", RegexOptions.IgnoreCase); + string stripped = Regex.Replace(withBreaks, @"<[^>]+>", ""); + return WebUtility.HtmlDecode(stripped).Trim(); + } + + return raw; + } + + private static string BuildHtmlFromText(string title, string text) + { + var sb = new StringBuilder(); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine(" "); + sb.AppendLine(" "); + sb.AppendLine($" {WebUtility.HtmlEncode(title)}"); + sb.AppendLine(" "); + sb.AppendLine(""); + sb.AppendLine(""); + + string[] lines = text.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); + foreach (var line in lines) + { + sb.AppendLine($"

{WebUtility.HtmlEncode(line)}

"); + } + + sb.AppendLine(""); + sb.AppendLine(""); + return sb.ToString(); + } + + private static void RenderTextToPdf(string text, string outputPath) + { + using var document = new PdfDocument(); + var font = new XFont("Arial", 11, XFontStyle.Regular); + + string[] rawLines = (text ?? string.Empty).Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); + var wrappedLines = new List(); + const int maxChars = 90; + + foreach (var raw in rawLines) + { + if (string.IsNullOrEmpty(raw)) + { + wrappedLines.Add(string.Empty); + continue; + } + + string rem = raw; + while (rem.Length > 0) + { + int len = Math.Min(maxChars, rem.Length); + wrappedLines.Add(rem[..len]); + rem = rem[len..]; + } + } + + if (wrappedLines.Count == 0) + { + wrappedLines.Add(string.Empty); + } + + const double margin = 45; + const double lineHeight = 16; + int lineIndex = 0; + + while (lineIndex < wrappedLines.Count) + { + var page = document.AddPage(); + using var gfx = XGraphics.FromPdfPage(page); + double y = margin; + double maxY = page.Height.Point - margin; + + while (lineIndex < wrappedLines.Count && y + lineHeight <= maxY) + { + string line = wrappedLines[lineIndex++]; + if (!string.IsNullOrEmpty(line)) + { + gfx.DrawString(line, font, XBrushes.Black, new XPoint(margin, y + 11)); + } + y += lineHeight; + } + } + + document.Save(outputPath); + } +} diff --git a/src/Donustur.Engine/Documents/PdfEngine.cs b/src/Donustur.Engine/Documents/PdfEngine.cs new file mode 100644 index 0000000..9279cf8 --- /dev/null +++ b/src/Donustur.Engine/Documents/PdfEngine.cs @@ -0,0 +1,357 @@ +using System.Text; +using Donustur.Core.Catalog; +using Donustur.Core.Transactions; +using Donustur.Core.Utils; +using ImageMagick; +using ImageMagick.Drawing; +using PdfSharpCore.Pdf; +using PdfSharpCore.Pdf.IO; +using UglyToad.PdfPig; +using UglyToad.PdfPig.DocumentLayoutAnalysis.TextExtractor; + +namespace Donustur.Engine.Documents; + +public sealed class PdfEngine +{ + /// + /// Çoklu PDF belgelerini (veya PDF + Görsel karışımını) tek bir PDF dosyasında birleştirir. + /// + public async Task MergePdfsAsync( + IReadOnlyList inputFiles, + ExportTransaction transaction, + string? outputName = null, + IProgress? progress = null, + CancellationToken token = default) + { + string name = string.IsNullOrWhiteSpace(outputName) ? "Birlestirilmis_Belge.pdf" : outputName; + if (!name.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)) + { + name += ".pdf"; + } + string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, name); + + await Task.Run(() => + { + using var outputDoc = new PdfSharpCore.Pdf.PdfDocument(); + + for (int i = 0; i < inputFiles.Count; i++) + { + token.ThrowIfCancellationRequested(); + string input = inputFiles[i]; + + if (FormatCatalog.IsPdf(input)) + { + using var inputDoc = PdfReader.Open(input, PdfDocumentOpenMode.Import); + for (int pageIndex = 0; pageIndex < inputDoc.PageCount; pageIndex++) + { + outputDoc.AddPage(inputDoc.Pages[pageIndex]); + } + } + else if (FormatCatalog.IsImage(input)) + { + string tempImgPdf = Path.Combine(Path.GetTempPath(), $"donustur_img_{Guid.NewGuid():N}.pdf"); + try + { + using (var img = new MagickImage(input)) + { + img.AutoOrient(); + img.Write(tempImgPdf, MagickFormat.Pdf); + } + using var imgPdfDoc = PdfReader.Open(tempImgPdf, PdfDocumentOpenMode.Import); + for (int pageIndex = 0; pageIndex < imgPdfDoc.PageCount; pageIndex++) + { + outputDoc.AddPage(imgPdfDoc.Pages[pageIndex]); + } + } + finally + { + if (File.Exists(tempImgPdf)) + { + try { File.Delete(tempImgPdf); } catch { } + } + } + } + + progress?.Report((double)(i + 1) / inputFiles.Count * 100.0); + } + + if (outputDoc.PageCount == 0) + { + throw new InvalidOperationException("Birleştirilecek geçerli bir PDF veya görsel sayfası bulunamadı."); + } + + outputDoc.Save(outputPath); + }, token); + + return outputPath; + } + + /// + /// Bir PDF belgesinin sayfalarını ayrı PDF dosyalarına böler. + /// + public async Task> SplitPdfAsync( + string inputPdf, + ExportTransaction transaction, + IProgress? progress = null, + CancellationToken token = default) + { + var outputPaths = new List(); + string baseName = Path.GetFileNameWithoutExtension(inputPdf); + + await Task.Run(() => + { + using var inputDoc = PdfReader.Open(inputPdf, PdfDocumentOpenMode.Import); + int total = inputDoc.PageCount; + + for (int i = 0; i < total; i++) + { + token.ThrowIfCancellationRequested(); + + using var singleDoc = new PdfSharpCore.Pdf.PdfDocument(); + singleDoc.AddPage(inputDoc.Pages[i]); + + string pageName = $"{baseName}_Sayfa_{i + 1:D2}.pdf"; + string pagePath = SafePaths.GetUniquePath(transaction.StagingDirectory, pageName); + singleDoc.Save(pagePath); + outputPaths.Add(pagePath); + + progress?.Report((double)(i + 1) / total * 100.0); + } + }, token); + + return outputPaths; + } + + /// + /// PDF belgesindeki tüm metinleri çıkarıp .txt dosyası olarak kaydeder. + /// + public async Task ExtractTextAsync( + string inputPdf, + ExportTransaction transaction, + IProgress? progress = null, + CancellationToken token = default) + { + string outName = Path.GetFileNameWithoutExtension(inputPdf) + ".txt"; + string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, outName); + + await Task.Run(() => + { + using var document = UglyToad.PdfPig.PdfDocument.Open(inputPdf); + var sb = new StringBuilder(); + int totalPages = document.NumberOfPages; + + for (int i = 1; i <= totalPages; i++) + { + token.ThrowIfCancellationRequested(); + var page = document.GetPage(i); + string pageText = ExtractPageTextFormatted(page); + + sb.AppendLine($"--- Sayfa {i} ---"); + sb.AppendLine(pageText); + sb.AppendLine(); + + progress?.Report((double)i / totalPages * 100.0); + } + + File.WriteAllText(outPath, sb.ToString(), Encoding.UTF8); + }, token); + + return outPath; + } + + /// + /// PDF belgesini Word (.docx) belgesine dönüştürür. + /// + public async Task ConvertToDocxAsync( + string inputPdf, + ExportTransaction transaction, + IProgress? progress = null, + CancellationToken token = default) + { + string outName = Path.GetFileNameWithoutExtension(inputPdf) + ".docx"; + string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, outName); + + await Task.Run(() => + { + using var document = UglyToad.PdfPig.PdfDocument.Open(inputPdf); + int totalPages = document.NumberOfPages; + var pages = new List(totalPages); + + for (int i = 1; i <= totalPages; i++) + { + token.ThrowIfCancellationRequested(); + var page = document.GetPage(i); + pages.Add(ExtractPageTextFormatted(page)); + progress?.Report((double)i / totalPages * 90.0); + } + + DocxHelper.CreateDocxFromPages(outPath, pages); + progress?.Report(100.0); + }, token); + + return outPath; + } + + /// + /// PDF içindeki görselleri veya sayfaları hedef görsel formatında (png/jpg) dışa aktarır. + /// + public async Task> ExtractImagesAsync( + string inputPdf, + ExportTransaction transaction, + IProgress? progress = null, + CancellationToken token = default, + string targetFormat = "png") + { + var outputs = new List(); + string baseName = Path.GetFileNameWithoutExtension(inputPdf); + bool isJpg = targetFormat.Equals("jpg", StringComparison.OrdinalIgnoreCase) || + targetFormat.Equals("jpeg", StringComparison.OrdinalIgnoreCase) || + targetFormat.Equals("pdf_to_jpg", StringComparison.OrdinalIgnoreCase); + + string ext = isJpg ? ".jpg" : ".png"; + MagickFormat magickFormat = isJpg ? MagickFormat.Jpg : MagickFormat.Png; + + await Task.Run(() => + { + using var document = UglyToad.PdfPig.PdfDocument.Open(inputPdf); + int totalPages = document.NumberOfPages; + int imageIndex = 1; + + for (int i = 1; i <= totalPages; i++) + { + token.ThrowIfCancellationRequested(); + var page = document.GetPage(i); + var images = page.GetImages().ToList(); + int extractedOnPage = 0; + + foreach (var pdfImg in images) + { + try + { + MagickImage? mImg = null; + if (pdfImg.TryGetPng(out byte[]? pngBytes) && pngBytes != null && pngBytes.Length > 0) + { + mImg = new MagickImage(pngBytes); + } + else + { + byte[] rawBytes = pdfImg.RawBytes.ToArray(); + if (rawBytes.Length > 0) + { + mImg = new MagickImage(rawBytes); + } + } + + if (mImg != null) + { + using (mImg) + { + if (isJpg) + { + if (mImg.HasAlpha) + { + mImg.ColorAlpha(MagickColors.White); + } + mImg.Quality = 90; + } + + string imgName = $"{baseName}_Sayfa{i:D2}_Gorsel{imageIndex:D2}{ext}"; + string imgPath = SafePaths.GetUniquePath(transaction.StagingDirectory, imgName); + mImg.Write(imgPath, magickFormat); + outputs.Add(imgPath); + imageIndex++; + extractedOnPage++; + } + } + } + catch + { + // Desteklenmeyen ham görsel akışını atla + } + } + + // Eğer sayfada gömülü bitmap yoksa, sayfa metnini yüksek çözünürlüklü görsel sayfasına işle + if (extractedOnPage == 0) + { + string pageText = ExtractPageTextFormatted(page); + string pageImgName = $"{baseName}_Sayfa_{i:D2}{ext}"; + string pageImgPath = SafePaths.GetUniquePath(transaction.StagingDirectory, pageImgName); + RenderTextPageToImage(pageText, i, totalPages, pageImgPath, magickFormat); + outputs.Add(pageImgPath); + } + + progress?.Report((double)i / totalPages * 100.0); + } + }, token); + + return outputs; + } + + private static string ExtractPageTextFormatted(UglyToad.PdfPig.Content.Page page) + { + try + { + string ordered = ContentOrderTextExtractor.GetText(page); + if (!string.IsNullOrWhiteSpace(ordered)) + { + return ordered; + } + } + catch + { + // Yedek olarak standart page.Text kullan + } + return page.Text ?? string.Empty; + } + + private static void RenderTextPageToImage(string pageText, int pageNumber, int totalPages, string outputPath, MagickFormat format) + { + using var canvas = new MagickImage(MagickColors.White, 1240, 1754); + var drawables = new Drawables() + .Font("Arial") + .FontPointSize(18) + .FillColor(MagickColors.Black); + + string[] rawLines = (pageText ?? string.Empty).Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); + double y = 80; + const int maxCharsPerLine = 95; + + foreach (var rawLine in rawLines) + { + if (y > 1660) break; + + if (string.IsNullOrWhiteSpace(rawLine)) + { + y += 24; + continue; + } + + string remaining = rawLine; + while (remaining.Length > 0 && y <= 1660) + { + string chunk = remaining.Length > maxCharsPerLine + ? remaining[..maxCharsPerLine] + : remaining; + remaining = remaining.Length > maxCharsPerLine + ? remaining[maxCharsPerLine..] + : string.Empty; + + drawables.Text(70, y, chunk); + y += 26; + } + } + + // Sayfa alt bilgisi + drawables + .FontPointSize(14) + .FillColor(new MagickColor("#6B7280")) + .Text(560, 1710, $"Sayfa {pageNumber} / {totalPages}"); + + canvas.Draw(drawables); + if (format == MagickFormat.Jpg) + { + canvas.Quality = 90; + } + canvas.Write(outputPath, format); + } +} diff --git a/src/Donustur.Engine/Donustur.Engine.csproj b/src/Donustur.Engine/Donustur.Engine.csproj new file mode 100644 index 0000000..3b6d7eb --- /dev/null +++ b/src/Donustur.Engine/Donustur.Engine.csproj @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + net8.0 + enable + enable + + + diff --git a/src/Donustur.Engine/Images/ImageMagickEngine.cs b/src/Donustur.Engine/Images/ImageMagickEngine.cs new file mode 100644 index 0000000..37323e2 --- /dev/null +++ b/src/Donustur.Engine/Images/ImageMagickEngine.cs @@ -0,0 +1,177 @@ +using ImageMagick; +using Donustur.Core.Models; +using Donustur.Core.Transactions; +using Donustur.Core.Utils; + +namespace Donustur.Engine.Images; + +public sealed class ImageMagickEngine +{ + private static readonly HashSet SupportedImageExtensions = new(StringComparer.OrdinalIgnoreCase) + { + "jpg", "jpeg", "png", "webp", "avif", "bmp", "tiff", "tif", "gif", "ico", "svg", "heic", "heif" + }; + + public bool CanHandle(string extension) + { + return SupportedImageExtensions.Contains(extension.TrimStart('.')); + } + + /// + /// Tek veya çoklu görselleri hedef formata dönüştürür. + /// + public async Task> ConvertImagesAsync( + IReadOnlyList inputFiles, + string targetFormat, + ExportTransaction transaction, + ConversionOptions options, + IProgress? progress = null, + CancellationToken token = default) + { + var outputPaths = new List(); + string formatKey = targetFormat.ToLowerInvariant().TrimStart('.'); + + // Çoklu görsellerden tek PDF oluşturma + if (formatKey == "pdf") + { + string pdfName = inputFiles.Count == 1 + ? Path.GetFileNameWithoutExtension(inputFiles[0]) + ".pdf" + : "Birlestirilmis_Gorseller.pdf"; + + string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, pdfName); + + await Task.Run(() => + { + using var collection = new MagickImageCollection(); + for (int i = 0; i < inputFiles.Count; i++) + { + token.ThrowIfCancellationRequested(); + var image = new MagickImage(inputFiles[i]); + image.AutoOrient(); + collection.Add(image); + progress?.Report((double)(i + 1) / inputFiles.Count * 100.0); + } + collection.Write(outPath, MagickFormat.Pdf); + }, token); + + outputPaths.Add(outPath); + return outputPaths; + } + + // Çoklu görsellerden animasyonlu GIF oluşturma + if (formatKey == "gif" && inputFiles.Count > 1) + { + string gifName = "Animasyon.gif"; + string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, gifName); + + await Task.Run(() => + { + using var collection = new MagickImageCollection(); + for (int i = 0; i < inputFiles.Count; i++) + { + token.ThrowIfCancellationRequested(); + var img = new MagickImage(inputFiles[i]); + img.AutoOrient(); + img.AnimationDelay = 40; // 400ms + collection.Add(img); + progress?.Report((double)(i + 1) / inputFiles.Count * 90.0); + } + collection.Optimize(); + collection.Write(outPath, MagickFormat.Gif); + progress?.Report(100.0); + }, token); + + outputPaths.Add(outPath); + return outputPaths; + } + + // Birebir görsel dönüşümleri + MagickFormat magickFormat = MapFormat(formatKey); + + for (int i = 0; i < inputFiles.Count; i++) + { + token.ThrowIfCancellationRequested(); + string inputPath = inputFiles[i]; + string fileNameWithoutExt = Path.GetFileNameWithoutExtension(inputPath); + string extensionWithDot = formatKey == "compress_image" + ? Path.GetExtension(inputPath) + : "." + formatKey; + + string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, fileNameWithoutExt + extensionWithDot); + + await Task.Run(() => + { + using var image = new MagickImage(inputPath); + image.AutoOrient(); + + if (options.StripMetadata) + { + image.Strip(); + } + + if (options.ResizeWidth.HasValue || options.ResizeHeight.HasValue) + { + var geo = new MagickGeometry((uint)(options.ResizeWidth ?? 0), (uint)(options.ResizeHeight ?? 0)) + { + IgnoreAspectRatio = false + }; + image.Resize(geo); + } + + if (formatKey == "compress_image") + { + image.Quality = (uint)System.Math.Clamp(options.ImageQuality, 10, 95); + image.Strip(); + image.Write(outPath); + } + else if (magickFormat == MagickFormat.Ico) + { + // Oranı koruyarak 256x256 şeffaf tuvale ortala + image.Resize(new MagickGeometry(256, 256) { IgnoreAspectRatio = false }); + image.BackgroundColor = MagickColors.Transparent; + image.Extent(256, 256, Gravity.Center); + image.Write(outPath, MagickFormat.Ico); + } + else + { + if (magickFormat is MagickFormat.Jpg or MagickFormat.Jpeg) + { + // Şeffaf PNG/WebP görseller JPG'ye çevrilirken siyah arka plan oluşmasını önle + if (image.HasAlpha) + { + image.ColorAlpha(MagickColors.White); + } + } + + if (magickFormat is MagickFormat.Jpg or MagickFormat.Jpeg or MagickFormat.WebP or MagickFormat.Avif) + { + image.Quality = (uint)System.Math.Clamp(options.ImageQuality, 10, 100); + } + image.Write(outPath, magickFormat); + } + }, token); + + outputPaths.Add(outPath); + progress?.Report((double)(i + 1) / inputFiles.Count * 100.0); + } + + return outputPaths; + } + + private static MagickFormat MapFormat(string format) + { + return format.ToLowerInvariant() switch + { + "png" => MagickFormat.Png, + "jpg" or "jpeg" => MagickFormat.Jpg, + "webp" => MagickFormat.WebP, + "avif" => MagickFormat.Avif, + "bmp" => MagickFormat.Bmp, + "tiff" or "tif" => MagickFormat.Tiff, + "ico" => MagickFormat.Ico, + "gif" => MagickFormat.Gif, + "pdf" => MagickFormat.Pdf, + _ => MagickFormat.Png + }; + } +} diff --git a/src/Donustur.Engine/Media/MediaEngine.cs b/src/Donustur.Engine/Media/MediaEngine.cs new file mode 100644 index 0000000..90bc9e8 --- /dev/null +++ b/src/Donustur.Engine/Media/MediaEngine.cs @@ -0,0 +1,174 @@ +using Donustur.Core.Models; +using Donustur.Core.Transactions; +using Donustur.Core.Utils; + +namespace Donustur.Engine.Media; + +public sealed class MediaEngine +{ + private string? _customPath; + + public MediaEngine(string? customPath = null) + { + _customPath = customPath; + } + + public void SetCustomPath(string? customPath) + { + _customPath = customPath; + } + + /// + /// FFmpeg çalıştırılabilir dosya yolunu bulur. + /// + public string? ResolveFfmpegPath() + { + if (!string.IsNullOrWhiteSpace(_customPath) && File.Exists(_customPath)) + { + return _customPath; + } + + string baseDir = AppContext.BaseDirectory; + string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + + string[] candidatePaths = + { + Path.Combine(baseDir, "tools", "ffmpeg.exe"), + Path.Combine(baseDir, "ffmpeg.exe"), + Path.Combine(localAppData, @"Microsoft\WinGet\Links\ffmpeg.exe"), + Path.Combine(userProfile, @"scoop\shims\ffmpeg.exe"), + @"C:\ffmpeg\bin\ffmpeg.exe", + @"C:\Program Files\ffmpeg\bin\ffmpeg.exe", + @"C:\ProgramData\chocolatey\bin\ffmpeg.exe" + }; + + foreach (var path in candidatePaths) + { + if (File.Exists(path)) + return path; + } + + // WinGet paket klasörlerini dinamik tara + string wingetPackages = Path.Combine(localAppData, @"Microsoft\WinGet\Packages"); + if (Directory.Exists(wingetPackages)) + { + try + { + foreach (var pkgDir in Directory.EnumerateDirectories(wingetPackages, "*FFmpeg*")) + { + var found = Directory.EnumerateFiles(pkgDir, "ffmpeg.exe", SearchOption.AllDirectories).FirstOrDefault(); + if (found != null) + return found; + } + } + catch + { + // Erişim hatasında devam et + } + } + + string? pathEnv = Environment.GetEnvironmentVariable("PATH"); + if (pathEnv != null) + { + foreach (var segment in pathEnv.Split(Path.PathSeparator)) + { + if (string.IsNullOrWhiteSpace(segment)) continue; + string combined = Path.Combine(segment.Trim(), "ffmpeg.exe"); + if (File.Exists(combined)) + return combined; + } + } + + return null; + } + + public bool IsAvailable => ResolveFfmpegPath() != null; + + /// + /// Video veya ses dosyasını hedef formata dönüştürür. + /// + public async Task> ConvertMediaAsync( + IReadOnlyList inputFiles, + string targetFormat, + ExportTransaction transaction, + ConversionOptions options, + IProgress? progress = null, + CancellationToken token = default) + { + string? ffmpegPath = ResolveFfmpegPath(); + if (ffmpegPath == null) + { + throw new FileNotFoundException( + "FFmpeg bulunamadı. Medya dönüştürme için FFmpeg gereklidir. Lütfen Ayarlar ekranından ffmpeg.exe yolunu seçin veya 'winget install Gyan.FFmpeg' komutuyla yükleyin."); + } + + var outputFiles = new List(); + string formatKey = targetFormat.ToLowerInvariant().TrimStart('.'); + + for (int i = 0; i < inputFiles.Count; i++) + { + token.ThrowIfCancellationRequested(); + string inputFile = inputFiles[i]; + string fileName = Path.GetFileNameWithoutExtension(inputFile); + string outputExt = GetExtensionForFormat(formatKey, inputFile); + string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, fileName + outputExt); + + string arguments = BuildArguments(inputFile, outputPath, formatKey, options); + + var result = await ProcessRunner.RunAsync(ffmpegPath, arguments, token: token); + if (result.ExitCode != 0) + { + throw new InvalidOperationException($"FFmpeg dönüştürme hatası ({result.ExitCode}): {result.StandardError}"); + } + + if (File.Exists(outputPath)) + { + outputFiles.Add(outputPath); + } + + progress?.Report((double)(i + 1) / inputFiles.Count * 100.0); + } + + return outputFiles; + } + + private static string GetExtensionForFormat(string formatKey, string inputFile) + { + return formatKey switch + { + "mp4" => ".mp4", + "mkv" => ".mkv", + "webm" => ".webm", + "mp3" => ".mp3", + "wav" => ".wav", + "aac" => ".m4a", + "flac" => ".flac", + "ogg" => ".ogg", + "gif" => ".gif", + // Sıkıştırma işlemlerinde H.264/MP3 kodekleriyle tam uyumluluk için standart konteyner kullan + "compress_video" => ".mp4", + "compress_audio" => ".mp3", + _ => "." + formatKey + }; + } + + private static string BuildArguments(string input, string output, string formatKey, ConversionOptions options) + { + return formatKey switch + { + "mp4" => $"-y -i \"{input}\" -c:v libx264 -preset {options.VideoPreset} -crf {options.VideoCrf} -c:a aac -b:a {options.AudioBitrate} \"{output}\"", + "mkv" => $"-y -i \"{input}\" -c:v libx264 -preset {options.VideoPreset} -crf {options.VideoCrf} -c:a aac \"{output}\"", + "webm" => $"-y -i \"{input}\" -c:v libvpx-vp9 -b:v 0 -crf 30 -c:a libopus \"{output}\"", + "mp3" => $"-y -i \"{input}\" -vn -c:a libmp3lame -b:a {options.AudioBitrate} \"{output}\"", + "wav" => $"-y -i \"{input}\" -vn -c:a pcm_s16le \"{output}\"", + "aac" => $"-y -i \"{input}\" -vn -c:a aac -b:a {options.AudioBitrate} \"{output}\"", + "flac" => $"-y -i \"{input}\" -vn -c:a flac \"{output}\"", + "ogg" => $"-y -i \"{input}\" -vn -c:a libvorbis -q:a 5 \"{output}\"", + "gif" => $"-y -i \"{input}\" -vf \"fps=15,scale=480:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse\" \"{output}\"", + "compress_video" => $"-y -i \"{input}\" -c:v libx264 -crf 28 -preset fast -c:a aac -b:a 128k \"{output}\"", + "compress_audio" => $"-y -i \"{input}\" -vn -c:a libmp3lame -b:a 96k \"{output}\"", + _ => $"-y -i \"{input}\" \"{output}\"" + }; + } +} diff --git a/src/Donustur.Engine/ProcessRunner.cs b/src/Donustur.Engine/ProcessRunner.cs new file mode 100644 index 0000000..116206b --- /dev/null +++ b/src/Donustur.Engine/ProcessRunner.cs @@ -0,0 +1,86 @@ +using System.Diagnostics; +using System.Text; + +namespace Donustur.Engine; + +public static class ProcessRunner +{ + public sealed record ProcessOutput(int ExitCode, string StandardOutput, string StandardError); + + /// + /// Harici CLI araçlarını (FFmpeg, LibreOffice vb.) UI'ı dondurmadan, + /// CancellationToken ile süreç ağacını sonlandırabilen güvenli çalıştırıcı. + /// + public static async Task RunAsync( + string exePath, + string arguments, + string? workingDirectory = null, + IProgress? outputProgress = null, + CancellationToken token = default) + { + if (!File.Exists(exePath)) + { + throw new FileNotFoundException($"Çalıştırılacak araç bulunamadı: {exePath}"); + } + + var psi = new ProcessStartInfo + { + FileName = exePath, + Arguments = arguments, + WorkingDirectory = workingDirectory ?? Path.GetDirectoryName(exePath) ?? string.Empty, + CreateNoWindow = true, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + StandardOutputEncoding = Encoding.UTF8, + StandardErrorEncoding = Encoding.UTF8 + }; + + using var process = new Process { StartInfo = psi, EnableRaisingEvents = true }; + var stdOut = new StringBuilder(); + var stdErr = new StringBuilder(); + + process.OutputDataReceived += (_, e) => + { + if (e.Data != null) + { + stdOut.AppendLine(e.Data); + outputProgress?.Report(e.Data); + } + }; + + process.ErrorDataReceived += (_, e) => + { + if (e.Data != null) + { + stdErr.AppendLine(e.Data); + outputProgress?.Report(e.Data); + } + }; + + process.Start(); + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + + // CancellationToken ile işlem iptal edilirse süreci ve alt süreçlerini zorla sonlandır + using (token.Register(() => + { + try + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + } + } + catch + { + // Süreç zaten kapanmış olabilir + } + })) + { + await process.WaitForExitAsync(token); + } + + return new ProcessOutput(process.ExitCode, stdOut.ToString(), stdErr.ToString()); + } +} diff --git a/src/Donustur.Engine/Qr/QrEngine.cs b/src/Donustur.Engine/Qr/QrEngine.cs new file mode 100644 index 0000000..9dfb08e --- /dev/null +++ b/src/Donustur.Engine/Qr/QrEngine.cs @@ -0,0 +1,161 @@ +using Donustur.Core.Catalog; +using Donustur.Core.Transactions; +using Donustur.Core.Utils; +using ImageMagick; +using UglyToad.PdfPig; +using ZXing; +using ZXing.Common; +using ZXing.QrCode; + +namespace Donustur.Engine.Qr; + +public sealed class QrEngine +{ + /// + /// Görsel veya PDF dosyasından QR kod(ları) okur ve metnini döner. + /// + public string? ReadQrCode(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath)) + return null; + + if (FormatCatalog.IsPdf(filePath)) + { + return ReadQrFromPdf(filePath); + } + + try + { + using var image = new MagickImage(filePath); + return DecodeFromMagickImage(image); + } + catch + { + return null; + } + } + + private static string? ReadQrFromPdf(string pdfPath) + { + try + { + var foundTexts = new List(); + using var document = PdfDocument.Open(pdfPath); + + for (int i = 1; i <= document.NumberOfPages; i++) + { + var page = document.GetPage(i); + foreach (var pdfImg in page.GetImages()) + { + try + { + MagickImage? mImg = null; + if (pdfImg.TryGetPng(out byte[]? pngBytes) && pngBytes != null && pngBytes.Length > 0) + { + mImg = new MagickImage(pngBytes); + } + else + { + byte[] raw = pdfImg.RawBytes.ToArray(); + if (raw.Length > 0) + { + mImg = new MagickImage(raw); + } + } + + if (mImg != null) + { + using (mImg) + { + string? decoded = DecodeFromMagickImage(mImg); + if (!string.IsNullOrWhiteSpace(decoded) && !foundTexts.Contains(decoded)) + { + foundTexts.Add(decoded); + } + } + } + } + catch + { + // Okunamayan alt görselleri atla + } + } + } + + return foundTexts.Count > 0 ? string.Join(Environment.NewLine + Environment.NewLine, foundTexts) : null; + } + catch + { + return null; + } + } + + private static string? DecodeFromMagickImage(MagickImage image) + { + image.AutoOrient(); + + // Şeffaf arka planlı QR kodların doğru okunması için beyaz zemine oturt + if (image.HasAlpha) + { + image.ColorAlpha(MagickColors.White); + } + + using var pixels = image.GetPixels(); + byte[]? rgb = pixels.ToByteArray(PixelMapping.RGB); + if (rgb == null) return null; + + var luminanceSource = new RGBLuminanceSource( + rgb, + (int)image.Width, + (int)image.Height, + RGBLuminanceSource.BitmapFormat.RGB24); + + var reader = new BarcodeReaderGeneric + { + AutoRotate = true, + Options = new DecodingOptions + { + TryHarder = true, + PossibleFormats = new[] { BarcodeFormat.QR_CODE, BarcodeFormat.DATA_MATRIX, BarcodeFormat.AZTEC, BarcodeFormat.CODE_128, BarcodeFormat.EAN_13 } + } + }; + + var result = reader.Decode(luminanceSource); + return result?.Text; + } + + /// + /// Verilen metinden yüksek çözünürlüklü bir QR kod PNG görseli üretir. + /// + public string GenerateQrCode(string text, ExportTransaction transaction, int size = 600) + { + string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, "Karekod_" + Guid.NewGuid().ToString("N")[..6] + ".png"); + + var writer = new BarcodeWriterPixelData + { + Format = BarcodeFormat.QR_CODE, + Options = new QrCodeEncodingOptions + { + Width = size, + Height = size, + Margin = 4, + CharacterSet = "UTF-8" + } + }; + + var pixelData = writer.Write(text); + + // PixelDataRenderer varsayılan olarak BGRA32 üretir (B, G, R, A) + var readSettings = new MagickReadSettings + { + Width = (uint)pixelData.Width, + Height = (uint)pixelData.Height, + Format = MagickFormat.Bgra + }; + + using var image = new MagickImage(pixelData.Pixels, readSettings); + image.Write(outPath, MagickFormat.Png); + + return outPath; + } +} diff --git a/src/Donustur.UI/App.xaml b/src/Donustur.UI/App.xaml new file mode 100644 index 0000000..be95b0d --- /dev/null +++ b/src/Donustur.UI/App.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/src/Donustur.UI/App.xaml.cs b/src/Donustur.UI/App.xaml.cs new file mode 100644 index 0000000..d820ba4 --- /dev/null +++ b/src/Donustur.UI/App.xaml.cs @@ -0,0 +1,202 @@ +using System.IO; +using System.Windows; +using Donustur.Core.Models; +using Donustur.Core.Services; +using Donustur.Engine; +using Donustur.UI.Services; +using Donustur.UI.Windows; + +namespace Donustur.UI; + +public partial class App : Application +{ + private SingleInstance? _singleInstance; + private PreferencesStore? _preferencesStore; + private HistoryStore? _historyStore; + private ConversionDispatcher? _dispatcher; + private GlobalDragController? _dragController; + private TrayHost? _trayHost; + private MainWindow? _mainWindow; + private bool _isExiting; + + protected override void OnStartup(StartupEventArgs e) + { + // 1. Aynı anda iki kez açılmasını senkron olarak engelle + _singleInstance = new SingleInstance(); + if (!_singleInstance.IsPrimaryInstance) + { + SingleInstance.NotifyAndFocusPrimaryInstance(e.Args); + _singleInstance.Dispose(); + Environment.Exit(0); + return; + } + + base.OnStartup(e); + + DispatcherUnhandledException += (_, args) => + { + args.Handled = true; + MessageBox.Show( + $"Beklenmeyen bir hata oluştu:\n{args.Exception.Message}", + "LD Converter", + MessageBoxButton.OK, + MessageBoxImage.Warning); + }; + + TaskScheduler.UnobservedTaskException += (_, args) => + { + args.SetObserved(); + }; + + _singleInstance.StartListening(); + _singleInstance.ShowRequestReceived += BringMainWindowToFront; + _singleInstance.FilesReceived += files => + { + _mainWindow?.SetSelectedFiles(files); + }; + + // Servisleri başlat + _preferencesStore = new PreferencesStore(); + _historyStore = new HistoryStore(); + _dispatcher = new ConversionDispatcher(_preferencesStore.Current, _historyStore); + + // Global sürükleme ve çark kontrolcüsü + _dragController = new GlobalDragController(_preferencesStore, HandleWheelDroppedFiles); + + // Sistem Tepsisi (Tray) + _trayHost = new TrayHost( + _preferencesStore, + openMainWindow: BringMainWindowToFront, + openSettings: OpenSettingsWindow, + exitApp: ExitApplication); + + _preferencesStore.Changed += _ => _trayHost.UpdateStatus(); + + // Ana Pencereyi Oluştur + _mainWindow = new MainWindow( + _preferencesStore, + _historyStore, + _dispatcher, + onExitRequested: ExitApplication); + + // Komut satırı argümanları (Dosya veya klasör ile açılmışsa) + if (e.Args.Length > 0) + { + var validPaths = e.Args.Where(p => File.Exists(p) || Directory.Exists(p)).ToList(); + if (validPaths.Count > 0) + { + _mainWindow.SetSelectedFiles(validPaths); + } + } + + _mainWindow.Show(); + } + + private void BringMainWindowToFront() + { + if (_mainWindow == null) return; + + if (!_mainWindow.IsVisible) + { + _mainWindow.Show(); + } + + if (_mainWindow.WindowState == WindowState.Minimized) + { + _mainWindow.WindowState = WindowState.Normal; + } + + _mainWindow.Topmost = true; + _mainWindow.Activate(); + _mainWindow.Topmost = false; + _mainWindow.Focus(); + } + + private void OpenSettingsWindow() + { + if (_preferencesStore == null) return; + var win = new SettingsWindow(_preferencesStore); + if (_mainWindow != null && _mainWindow.IsVisible) + { + win.Owner = _mainWindow; + } + win.ShowDialog(); + } + + private async void HandleWheelDroppedFiles(ToolChoice choice, IReadOnlyList files) + { + if (_dispatcher == null || _preferencesStore == null || files.Count == 0) return; + + using var cts = new CancellationTokenSource(); + + // Kayan bildirim penceresi oluştur + var toast = new ProgressToastWindow( + $"{choice.DisplayName} Dönüştürülüyor...", + onCancelRequested: () => cts.Cancel()); + toast.Show(); + + var progress = new Progress(val => + { + toast.UpdateProgress(val, $"{choice.DisplayName} işleniyor (%{val:F0})..."); + }); + + var task = new ConversionTask + { + InputFiles = files, + TargetActionId = choice.Id, + TargetDisplayName = choice.DisplayName, + Options = new ConversionOptions + { + ImageQuality = _preferencesStore.Current.DefaultImageQuality + } + }; + + var result = await _dispatcher.ExecuteTaskAsync(task, _preferencesStore.Current, progress, cts.Token); + + if (result.Success) + { + string? decodedQr = choice.Id == "qr_read" ? task.CurrentStatusMessage : null; + toast.SetCompleted(result.OutputFiles, decodedQr); + + if (_preferencesStore.Current.SoundEffectsEnabled) + { + SoundFeedback.PlaySuccess(); + } + + if (_preferencesStore.Current.AutoOpenOutputFolder && result.OutputFiles.Count > 0) + { + DesktopGeometry.RevealInExplorer(result.OutputFiles[0]); + } + } + else + { + toast.SetFailed(result.ErrorMessage ?? "İşlem başarısız oldu."); + } + } + + private void ExitApplication() + { + if (_isExiting) return; + _isExiting = true; + + _dragController?.Dispose(); + _dragController = null; + + _trayHost?.Dispose(); + _trayHost = null; + + _singleInstance?.Dispose(); + _singleInstance = null; + + Shutdown(); + Environment.Exit(0); + } + + protected override void OnExit(ExitEventArgs e) + { + _dragController?.Dispose(); + _trayHost?.Dispose(); + _singleInstance?.Dispose(); + base.OnExit(e); + } +} diff --git a/src/Donustur.UI/AssemblyInfo.cs b/src/Donustur.UI/AssemblyInfo.cs new file mode 100644 index 0000000..cc29e7f --- /dev/null +++ b/src/Donustur.UI/AssemblyInfo.cs @@ -0,0 +1,10 @@ +using System.Windows; + +[assembly:ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] diff --git a/src/Donustur.UI/Assets/app.ico b/src/Donustur.UI/Assets/app.ico new file mode 100644 index 0000000..e85e5c1 Binary files /dev/null and b/src/Donustur.UI/Assets/app.ico differ diff --git a/src/Donustur.UI/Controls/RadialWheelControl.cs b/src/Donustur.UI/Controls/RadialWheelControl.cs new file mode 100644 index 0000000..70a3e1e --- /dev/null +++ b/src/Donustur.UI/Controls/RadialWheelControl.cs @@ -0,0 +1,277 @@ +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; + +namespace Donustur.UI.Controls; + +public sealed class RadialWheelControl : Control +{ + public static readonly DependencyProperty ChoicesProperty = + DependencyProperty.Register( + nameof(Choices), + typeof(IReadOnlyList), + typeof(RadialWheelControl), + new FrameworkPropertyMetadata(Array.Empty(), FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty HoveredIndexProperty = + DependencyProperty.Register( + nameof(HoveredIndex), + typeof(int), + typeof(RadialWheelControl), + new FrameworkPropertyMetadata(-1, FrameworkPropertyMetadataOptions.AffectsRender, OnHoveredIndexChanged)); + + public static readonly DependencyProperty FileCountProperty = + DependencyProperty.Register( + nameof(FileCount), + typeof(int), + typeof(RadialWheelControl), + new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty FileSummaryProperty = + DependencyProperty.Register( + nameof(FileSummary), + typeof(string), + typeof(RadialWheelControl), + new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsRender)); + + public IReadOnlyList Choices + { + get => (IReadOnlyList)GetValue(ChoicesProperty); + set => SetValue(ChoicesProperty, value); + } + + public int HoveredIndex + { + get => (int)GetValue(HoveredIndexProperty); + set => SetValue(HoveredIndexProperty, value); + } + + public int FileCount + { + get => (int)GetValue(FileCountProperty); + set => SetValue(FileCountProperty, value); + } + + public string FileSummary + { + get => (string)GetValue(FileSummaryProperty); + set => SetValue(FileSummaryProperty, value); + } + + public event Action? HoverChanged; + + private static void OnHoveredIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + if (d is RadialWheelControl wheel) + { + wheel.HoverChanged?.Invoke((int)e.NewValue); + } + } + + public double OuterRadius { get; set; } = 175.0; + public double InnerRadius { get; set; } = 48.0; + + static RadialWheelControl() + { + DefaultStyleKeyProperty.OverrideMetadata( + typeof(RadialWheelControl), + new FrameworkPropertyMetadata(typeof(RadialWheelControl))); + } + + public RadialWheelControl() + { + Width = (OuterRadius * 2) + 20; + Height = (OuterRadius * 2) + 20; + } + + protected override void OnRender(DrawingContext dc) + { + base.OnRender(dc); + + double centerX = ActualWidth / 2.0; + double centerY = ActualHeight / 2.0; + + if (centerX <= 0 || centerY <= 0) + { + centerX = Width / 2.0; + centerY = Height / 2.0; + } + + var choices = Choices; + int total = choices?.Count ?? 0; + if (total == 0) return; + + double segmentAngle = 360.0 / total; + 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); + + // Dilimleri çiz + for (int i = 0; i < total; i++) + { + bool isHovered = (i == HoveredIndex); + var choice = choices![i]; + + // Açı aralıkları + double midAngle = WheelMath.GetSegmentCenterAngle(i, total); + double startAngle = midAngle - ((segmentAngle - gapDegrees) / 2.0); + double sweepAngle = segmentAngle - gapDegrees; + + // Segment Geometrisi + var geom = CreateAnnularSectorGeometry( + centerX, centerY, + 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); + } + + dc.DrawGeometry(fillBrush, borderPen, geom); + + // Metin ve İkon Konumlandırma + double labelRadius = (InnerRadius + OuterRadius) / 2.0; + var labelPos = WheelMath.GetPointOnCircle(centerX, centerY, labelRadius, midAngle); + + DrawSegmentLabel(dc, choice.DisplayName, labelPos.X, labelPos.Y, isHovered); + } + + // Merkez Yuvarlak Gösterge (Center Hub) + DrawCenterHub(dc, centerX, centerY); + } + + 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 ft = new FormattedText( + text, + CultureInfo.CurrentUICulture, + FlowDirection.LeftToRight, + typeface, + isHovered ? 14 : 12.5, + isHovered ? Brushes.White : new SolidColorBrush(Color.FromRgb(220, 225, 235)), + 1.0); + + dc.DrawText(ft, new Point(x - (ft.Width / 2.0), y - (ft.Height / 2.0))); + } + + 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); + + // 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); + + // Merkez metin + string centerTitle; + string centerSubtitle; + + if (HoveredIndex >= 0 && Choices != null && HoveredIndex < Choices.Count) + { + var choice = Choices[HoveredIndex]; + centerTitle = choice.DisplayName; + centerSubtitle = choice.Category; + } + else + { + centerTitle = "LD Converter"; + 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, + 11.0, + Brushes.White, + 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, + 9.5, + new SolidColorBrush(Color.FromRgb(156, 163, 175)), + 1.0); + + dc.DrawText(subFt, new Point(centerX - (subFt.Width / 2.0), centerY + 3)); + } + + private static Geometry CreateAnnularSectorGeometry( + double centerX, double centerY, + double innerR, double outerR, + double startAngleDeg, double sweepAngleDeg) + { + double endAngleDeg = startAngleDeg + sweepAngleDeg; + var p1 = WheelMath.GetPointOnCircle(centerX, centerY, innerR, startAngleDeg); + var p2 = WheelMath.GetPointOnCircle(centerX, centerY, outerR, startAngleDeg); + var p3 = WheelMath.GetPointOnCircle(centerX, centerY, outerR, endAngleDeg); + var p4 = WheelMath.GetPointOnCircle(centerX, centerY, innerR, endAngleDeg); + + bool isLargeArc = sweepAngleDeg > 180.0; + + var figure = new PathFigure + { + StartPoint = new Point(p1.X, p1.Y), + IsClosed = true, + IsFilled = true + }; + + figure.Segments.Add(new LineSegment(new Point(p2.X, p2.Y), isStroked: true)); + figure.Segments.Add(new ArcSegment(new Point(p3.X, p3.Y), new Size(outerR, outerR), 0, isLargeArc, SweepDirection.Clockwise, isStroked: true)); + figure.Segments.Add(new LineSegment(new Point(p4.X, p4.Y), isStroked: true)); + figure.Segments.Add(new ArcSegment(new Point(p1.X, p1.Y), new Size(innerR, innerR), 0, isLargeArc, SweepDirection.Counterclockwise, isStroked: true)); + + var geom = new PathGeometry(); + geom.Figures.Add(figure); + return geom; + } +} diff --git a/src/Donustur.UI/Donustur.UI.csproj b/src/Donustur.UI/Donustur.UI.csproj new file mode 100644 index 0000000..4cff925 --- /dev/null +++ b/src/Donustur.UI/Donustur.UI.csproj @@ -0,0 +1,29 @@ + + + + + + + + + + + + + WinExe + net8.0-windows + LDConverter + LD Converter + LD Converter + 1.1.0 + Assets\app.ico + enable + enable + true + true + app.manifest + + $(NoWarn);WFAC010 + + + diff --git a/src/Donustur.UI/GlobalUsings.cs b/src/Donustur.UI/GlobalUsings.cs new file mode 100644 index 0000000..7985d6f --- /dev/null +++ b/src/Donustur.UI/GlobalUsings.cs @@ -0,0 +1,31 @@ +// Conflict resolution aliases for WPF + WinForms coexistence +// WPF types take priority over WinForms throughout the project +global using Application = System.Windows.Application; +global using Point = System.Windows.Point; +global using DragEventArgs = System.Windows.DragEventArgs; +global using Control = System.Windows.Controls.Control; +global using MouseEventArgs = System.Windows.Input.MouseEventArgs; +global using KeyEventArgs = System.Windows.Input.KeyEventArgs; +global using Color = System.Windows.Media.Color; +global using Brushes = System.Windows.Media.Brushes; +global using Brush = System.Windows.Media.Brush; +global using FontFamily = System.Windows.Media.FontFamily; +global using Pen = System.Windows.Media.Pen; +global using Size = System.Windows.Size; +global using Orientation = System.Windows.Controls.Orientation; +global using RadioButton = System.Windows.Controls.RadioButton; +global using Button = System.Windows.Controls.Button; +global using MessageBox = System.Windows.MessageBox; +global using MessageBoxButton = System.Windows.MessageBoxButton; +global using MessageBoxImage = System.Windows.MessageBoxImage; +global using FontStyle = System.Windows.FontStyle; +global using FontStyles = System.Windows.FontStyles; +global using FlowDirection = System.Windows.FlowDirection; +global using DataFormats = System.Windows.DataFormats; +global using DragDropEffects = System.Windows.DragDropEffects; +global using StreamReader = System.IO.StreamReader; +global using StreamWriter = System.IO.StreamWriter; +global using OpenFileDialog = Microsoft.Win32.OpenFileDialog; +global using Clipboard = System.Windows.Clipboard; +global using Cursors = System.Windows.Input.Cursors; +global using HorizontalAlignment = System.Windows.HorizontalAlignment; diff --git a/src/Donustur.UI/MainWindow.xaml b/src/Donustur.UI/MainWindow.xaml new file mode 100644 index 0000000..48771b5 --- /dev/null +++ b/src/Donustur.UI/MainWindow.xaml @@ -0,0 +1,407 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Donustur.UI/Windows/ProgressToastWindow.xaml.cs b/src/Donustur.UI/Windows/ProgressToastWindow.xaml.cs new file mode 100644 index 0000000..b04b65d --- /dev/null +++ b/src/Donustur.UI/Windows/ProgressToastWindow.xaml.cs @@ -0,0 +1,149 @@ +using System.IO; +using System.Windows; +using System.Windows.Threading; +using Donustur.UI.Services; + +namespace Donustur.UI.Windows; + +public partial class ProgressToastWindow : Window +{ + private static readonly List ActiveToasts = new(); + + private string? _firstOutputFile; + private string? _copiedPayload; + private bool _isCompletedOrFailed; + private readonly Action? _onCancelRequested; + private readonly DispatcherTimer _autoCloseTimer; + + public ProgressToastWindow(string initialTitle, Action? onCancelRequested = null) + { + InitializeComponent(); + Icon = AppIconProvider.GetWindowIcon(); + TitleText.Text = initialTitle; + _onCancelRequested = onCancelRequested; + + _autoCloseTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5.5) }; + _autoCloseTimer.Tick += (_, _) => Close(); + + Loaded += (_, _) => + { + if (!ActiveToasts.Contains(this)) + { + ActiveToasts.Add(this); + } + RepositionAllToasts(); + }; + + Closed += (_, _) => + { + _autoCloseTimer.Stop(); + ActiveToasts.Remove(this); + RepositionAllToasts(); + }; + } + + private static void RepositionAllToasts() + { + double workAreaRight = SystemParameters.WorkArea.Right; + double workAreaBottom = SystemParameters.WorkArea.Bottom; + + for (int i = 0; i < ActiveToasts.Count; i++) + { + var toast = ActiveToasts[i]; + toast.Left = workAreaRight - toast.Width - 15; + toast.Top = workAreaBottom - ((i + 1) * (toast.Height - 5)) - 10; + } + } + + public void UpdateProgress(double percent, string? status = null) + { + Dispatcher.Invoke(() => + { + ProgressBar.Value = percent; + if (!string.IsNullOrWhiteSpace(status)) + { + StatusText.Text = status; + } + }); + } + + public void SetCompleted(IReadOnlyList outputFiles, string? decodedText = null) + { + Dispatcher.Invoke(() => + { + _isCompletedOrFailed = true; + ProgressBar.Value = 100; + ProgressBar.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(16, 185, 129)); + TitleText.Text = "✓ Dönüştürme Tamamlandı"; + + if (!string.IsNullOrWhiteSpace(decodedText)) + { + _copiedPayload = decodedText; + try { Clipboard.SetText(decodedText); } catch { } + StatusText.Text = $"QR: {decodedText} (Panoya kopyalandı)"; + CopyTextButton.Visibility = Visibility.Visible; + } + else + { + StatusText.Text = outputFiles.Count == 1 + ? Path.GetFileName(outputFiles[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) + : $"{outputFiles.Count} öğe hazırlandı"; + } + + if (outputFiles.Count > 0) + { + _firstOutputFile = outputFiles[0]; + ActionPanel.Visibility = Visibility.Visible; + } + + _autoCloseTimer.Start(); + }); + } + + public void SetFailed(string error) + { + Dispatcher.Invoke(() => + { + _isCompletedOrFailed = true; + TitleText.Text = "✕ İşlem Tamamlanamadı"; + TitleText.Foreground = System.Windows.Media.Brushes.IndianRed; + StatusText.Text = error; + ProgressBar.Visibility = Visibility.Collapsed; + _autoCloseTimer.Start(); + }); + } + + private void OnCloseClick(object sender, RoutedEventArgs e) + { + if (!_isCompletedOrFailed) + { + _onCancelRequested?.Invoke(); + } + Close(); + } + + private void OnCopyTextClick(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(_copiedPayload)) + { + try + { + Clipboard.SetText(_copiedPayload); + CopyTextButton.Content = "✓ Kopyalandı"; + } + catch + { + // Pano meşgulse sessizce geç + } + } + } + + private void OnOpenFolderClick(object sender, RoutedEventArgs e) + { + if (!string.IsNullOrWhiteSpace(_firstOutputFile)) + { + DesktopGeometry.RevealInExplorer(_firstOutputFile); + } + Close(); + } +} diff --git a/src/Donustur.UI/Windows/SettingsWindow.xaml b/src/Donustur.UI/Windows/SettingsWindow.xaml new file mode 100644 index 0000000..b749b3e --- /dev/null +++ b/src/Donustur.UI/Windows/SettingsWindow.xaml @@ -0,0 +1,365 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Donustur.UI/Windows/SettingsWindow.xaml.cs b/src/Donustur.UI/Windows/SettingsWindow.xaml.cs new file mode 100644 index 0000000..a2c79e5 --- /dev/null +++ b/src/Donustur.UI/Windows/SettingsWindow.xaml.cs @@ -0,0 +1,234 @@ +using System.Windows; +using System.Windows.Controls; +using Donustur.Core.Services; +using Donustur.Engine.Archives; +using Donustur.Engine.Documents; +using Donustur.Engine.Media; +using Donustur.UI.Services; +using Microsoft.Win32; + +namespace Donustur.UI.Windows; + +public partial class SettingsWindow : Window +{ + private const string StartupRunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; + private const string AppName = "LDConverter"; + + private readonly PreferencesStore _preferencesStore; + + public SettingsWindow(PreferencesStore preferencesStore) + { + InitializeComponent(); + _preferencesStore = preferencesStore; + Icon = AppIconProvider.GetWindowIcon(); + + DwmBackdrop.ApplyFluentBackdrop(this, DwmBackdrop.BackdropType.MainWindow, darkMode: true); + + Loaded += (_, _) => LoadValues(); + } + + private void LoadValues() + { + var prefs = _preferencesStore.Current; + + EnableWheelCheck.IsChecked = prefs.Enabled; + + // Modifier + foreach (ComboBoxItem item in ModifierCombo.Items) + { + if (string.Equals(item.Content.ToString(), prefs.DragModifier, StringComparison.OrdinalIgnoreCase)) + { + ModifierCombo.SelectedItem = item; + break; + } + } + if (ModifierCombo.SelectedItem == null) ModifierCombo.SelectedIndex = 0; + + ScaleSlider.Value = Math.Clamp(prefs.WheelScale, 0.8, 1.4); + ScaleValueLabel.Text = $"{ScaleSlider.Value:0.00}x"; + + QualitySlider.Value = Math.Clamp(prefs.DefaultImageQuality, 20, 100); + QualityValueLabel.Text = $"%{QualitySlider.Value:F0}"; + + SoundCheck.IsChecked = prefs.SoundEffectsEnabled; + MinimizeToTrayCheck.IsChecked = prefs.MinimizeToTray; + AutoOpenCheck.IsChecked = prefs.AutoOpenOutputFolder; + RunAtStartupCheck.IsChecked = IsStartupEnabled(); + + // Output mode + OutputModeCombo.SelectedIndex = prefs.OutputDirectoryMode switch + { + "Desktop" => 1, + "Custom" => 2, + _ => 0 + }; + + 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; + } + + var mediaEngine = new MediaEngine(prefs.CustomFfmpegPath); + if (mediaEngine.IsAvailable) + { + 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; + } + + 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)"; + } + + private void OnScaleSliderChanged(object sender, RoutedPropertyChangedEventArgs e) + { + if (ScaleValueLabel != null) + { + ScaleValueLabel.Text = $"{e.NewValue:0.00}x"; + } + } + + private void OnQualitySliderChanged(object sender, RoutedPropertyChangedEventArgs e) + { + if (QualityValueLabel != null) + { + QualityValueLabel.Text = $"%{e.NewValue:F0}"; + } + } + + private void OnOutputModeChanged(object sender, SelectionChangedEventArgs e) + { + if (CustomFolderPanel != null) + { + CustomFolderPanel.Visibility = OutputModeCombo.SelectedIndex == 2 ? Visibility.Visible : Visibility.Collapsed; + } + } + + private void OnBrowseFolderClick(object sender, RoutedEventArgs e) + { + var dlg = new OpenFolderDialog + { + Title = "Dönüştürülen Dosyaların Kaydedileceği Klasörü Seçin" + }; + if (dlg.ShowDialog() == true) + { + CustomFolderText.Text = dlg.FolderName; + } + } + + private void OnBrowseLibreOfficeClick(object sender, RoutedEventArgs e) + { + var dlg = new Microsoft.Win32.OpenFileDialog + { + Filter = "soffice.exe|soffice.exe|Tüm Dosyalar (*.*)|*.*", + Title = "LibreOffice soffice.exe dosyasını seçin" + }; + if (dlg.ShowDialog() == true) + { + var prefs = _preferencesStore.Current; + prefs.CustomLibreOfficePath = dlg.FileName; + _preferencesStore.Save(prefs); + LoadValues(); + } + } + + private void OnBrowseFfmpegClick(object sender, RoutedEventArgs e) + { + var dlg = new Microsoft.Win32.OpenFileDialog + { + Filter = "ffmpeg.exe|ffmpeg.exe|Tüm Dosyalar (*.*)|*.*", + Title = "FFmpeg ffmpeg.exe dosyasını seçin" + }; + if (dlg.ShowDialog() == true) + { + var prefs = _preferencesStore.Current; + prefs.CustomFfmpegPath = dlg.FileName; + _preferencesStore.Save(prefs); + LoadValues(); + } + } + + private void OnStartupToggle(object sender, RoutedEventArgs e) + { + SetStartupEnabled(RunAtStartupCheck.IsChecked == true); + } + + private static bool IsStartupEnabled() + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(StartupRunKey, false); + return key?.GetValue(AppName) != null; + } + catch + { + return false; + } + } + + private static void SetStartupEnabled(bool enable) + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(StartupRunKey, true); + if (key != null) + { + if (enable) + { + string exePath = Environment.ProcessPath ?? ""; + key.SetValue(AppName, $"\"{exePath}\""); + } + else + { + key.DeleteValue(AppName, false); + } + } + } + catch + { + // İzin hatası vb. + } + } + + private void OnSaveClick(object sender, RoutedEventArgs e) + { + var prefs = _preferencesStore.Current; + + prefs.Enabled = EnableWheelCheck.IsChecked == true; + prefs.DragModifier = (ModifierCombo.SelectedItem as ComboBoxItem)?.Content.ToString() ?? "Shift"; + prefs.WheelScale = Math.Round(ScaleSlider.Value, 2); + prefs.DefaultImageQuality = (int)Math.Round(QualitySlider.Value); + prefs.SoundEffectsEnabled = SoundCheck.IsChecked == true; + prefs.MinimizeToTray = MinimizeToTrayCheck.IsChecked == true; + prefs.AutoOpenOutputFolder = AutoOpenCheck.IsChecked == true; + prefs.RunAtStartup = RunAtStartupCheck.IsChecked == true; + + prefs.OutputDirectoryMode = OutputModeCombo.SelectedIndex switch + { + 1 => "Desktop", + 2 => "Custom", + _ => "SameAsSource" + }; + prefs.CustomOutputDirectory = CustomFolderText.Text.Trim(); + + _preferencesStore.Save(prefs); + Close(); + } +} diff --git a/src/Donustur.UI/Windows/WheelWindow.xaml b/src/Donustur.UI/Windows/WheelWindow.xaml new file mode 100644 index 0000000..3252b74 --- /dev/null +++ b/src/Donustur.UI/Windows/WheelWindow.xaml @@ -0,0 +1,24 @@ + + + + + + + + + diff --git a/src/Donustur.UI/Windows/WheelWindow.xaml.cs b/src/Donustur.UI/Windows/WheelWindow.xaml.cs new file mode 100644 index 0000000..aeae4f8 --- /dev/null +++ b/src/Donustur.UI/Windows/WheelWindow.xaml.cs @@ -0,0 +1,245 @@ +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Interop; +using System.Windows.Media; +using System.Windows.Media.Animation; +using Donustur.Core.Catalog; +using Donustur.Core.Math; +using Donustur.Core.Models; +using Donustur.UI.Services; + +namespace Donustur.UI.Windows; + +public partial class WheelWindow : Window +{ + private const int GWL_EXSTYLE = -20; + private const int WS_EX_NOACTIVATE = 0x08000000; + private const int WS_EX_TOOLWINDOW = 0x00000080; + private const int WS_EX_TOPMOST = 0x00000008; + + [DllImport("user32.dll")] + private static extern int GetWindowLong(IntPtr hWnd, int nIndex); + + [DllImport("user32.dll")] + private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); + + private readonly Action> _onDropped; + private readonly bool _soundEnabled; + private readonly double _targetScale; + private IReadOnlyList _activeFiles = Array.Empty(); + private bool _isClosing; + private bool _selectionExecuted; + + public DateTime OpenedAtUtc { get; } = DateTime.UtcNow; + public bool HasValidFileDrag { get; private set; } + + public WheelWindow(Action> onDropped, bool soundEnabled = true, double scale = 1.0) + { + InitializeComponent(); + _onDropped = onDropped; + _soundEnabled = soundEnabled; + _targetScale = Math.Clamp(scale, 0.75, 1.5); + + // Ölçek büyütüldüğünde çarkın pencere sınırlarından kırpılmasını önle + double baseSize = 390.0; + Width = Math.Ceiling(baseSize * _targetScale); + Height = Math.Ceiling(baseSize * _targetScale); + + WheelScale.ScaleX = _targetScale; + WheelScale.ScaleY = _targetScale; + + // Varsayılan seçeneklerle başlat + RadialControl.Choices = FormatCatalog.GetChoicesForFiles(Array.Empty()); + + DragEnter += OnDragEnter; + DragOver += OnDragOver; + DragLeave += OnDragLeave; + Drop += OnDrop; + + Loaded += (_, _) => AnimateOpen(); + } + + protected override void OnSourceInitialized(EventArgs e) + { + base.OnSourceInitialized(e); + + // Pencerenin odağı çalmamasını ve OLE sürüklemeyi bozmamasını sağla + var handle = new WindowInteropHelper(this).Handle; + int exStyle = GetWindowLong(handle, GWL_EXSTYLE); + SetWindowLong(handle, GWL_EXSTYLE, exStyle | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST); + } + + private void AnimateOpen() + { + var scaleAnim = new DoubleAnimation(_targetScale * 0.7, _targetScale, TimeSpan.FromMilliseconds(120)) + { + EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut } + }; + var fadeAnim = new DoubleAnimation(0.0, 1.0, TimeSpan.FromMilliseconds(100)); + + WheelScale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnim); + WheelScale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnim); + RootGrid.BeginAnimation(OpacityProperty, fadeAnim); + } + + public void AnimateClose(Action? onComplete = null) + { + if (_isClosing) return; + _isClosing = true; + + var scaleAnim = new DoubleAnimation(_targetScale, _targetScale * 0.8, TimeSpan.FromMilliseconds(90)); + var fadeAnim = new DoubleAnimation(1.0, 0.0, TimeSpan.FromMilliseconds(90)); + + fadeAnim.Completed += (_, _) => + { + try + { + Close(); + } + catch + { + // Pencere zaten kapanmış olabilir + } + onComplete?.Invoke(); + }; + + WheelScale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnim); + WheelScale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnim); + RootGrid.BeginAnimation(OpacityProperty, fadeAnim); + } + + public void CancelAndClose() + { + _selectionExecuted = true; + RadialControl.HoveredIndex = -1; + AnimateClose(); + } + + public void UpdateMousePosition(Point screenPoint) + { + if (!IsLoaded || _isClosing) return; + try + { + if (PresentationSource.FromVisual(this) == null) return; + var clientPos = PointFromScreen(screenPoint); + UpdateSegmentFromPoint(clientPos); + } + catch + { + // Pencere kapanırken oluşan koordinat dönüşüm hatasını yoksay + } + } + + private void OnDragEnter(object sender, DragEventArgs e) + { + if (e.Data.GetDataPresent(DataFormats.FileDrop)) + { + HasValidFileDrag = true; + e.Effects = DragDropEffects.Copy; + if (e.Data.GetData(DataFormats.FileDrop) is string[] files && files.Length > 0) + { + _activeFiles = files; + RadialControl.FileCount = files.Length; + RadialControl.Choices = FormatCatalog.GetChoicesForFiles(files); + } + } + else + { + e.Effects = DragDropEffects.None; + } + e.Handled = true; + } + + private void OnDragOver(object sender, DragEventArgs e) + { + if (e.Data.GetDataPresent(DataFormats.FileDrop)) + { + HasValidFileDrag = true; + e.Effects = DragDropEffects.Copy; + Point pos = e.GetPosition(this); + UpdateSegmentFromPoint(pos); + } + else + { + e.Effects = DragDropEffects.None; + } + e.Handled = true; + } + + private void OnDragLeave(object sender, DragEventArgs e) + { + if (!_isClosing && !_selectionExecuted) + { + RadialControl.HoveredIndex = -1; + } + } + + private void UpdateSegmentFromPoint(Point pos) + { + if (_isClosing || _selectionExecuted) return; + + double centerX = ActualWidth / 2.0; + double centerY = ActualHeight / 2.0; + if (centerX <= 0 || centerY <= 0) + { + centerX = Width / 2.0; + centerY = Height / 2.0; + } + + int total = RadialControl.Choices?.Count ?? 0; + int newIndex = WheelMath.GetSegmentIndex( + centerX, centerY, + pos.X, pos.Y, + total, + RadialControl.InnerRadius * _targetScale, + RadialControl.OuterRadius * _targetScale); + + if (newIndex != RadialControl.HoveredIndex) + { + RadialControl.HoveredIndex = newIndex; + if (newIndex >= 0 && _soundEnabled) + { + SoundFeedback.PlayTick(); + } + } + } + + private void OnDrop(object sender, DragEventArgs e) + { + if (e.Data.GetDataPresent(DataFormats.FileDrop)) + { + HasValidFileDrag = true; + if (e.Data.GetData(DataFormats.FileDrop) is string[] files && files.Length > 0) + { + _activeFiles = files; + } + } + + Point dropPos = e.GetPosition(this); + UpdateSegmentFromPoint(dropPos); + ExecuteSelectionAndClose(); + e.Handled = true; + } + + public void ExecuteSelectionAndClose() + { + if (_selectionExecuted) return; + _selectionExecuted = true; + + int index = RadialControl.HoveredIndex; + var choices = RadialControl.Choices; + var files = _activeFiles; + + ToolChoice? selected = (index >= 0 && choices != null && index < choices.Count) + ? choices[index] + : null; + + AnimateClose(() => + { + if (selected != null && files.Count > 0) + { + _onDropped(selected, files); + } + }); + } +} diff --git a/src/Donustur.UI/app.manifest b/src/Donustur.UI/app.manifest new file mode 100644 index 0000000..0f3a1dc --- /dev/null +++ b/src/Donustur.UI/app.manifest @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2, PerMonitor + + + diff --git a/tests/Donustur.Tests/Donustur.Tests.csproj b/tests/Donustur.Tests/Donustur.Tests.csproj new file mode 100644 index 0000000..8c4b947 --- /dev/null +++ b/tests/Donustur.Tests/Donustur.Tests.csproj @@ -0,0 +1,28 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + + + + + + + + + + + + + diff --git a/tests/Donustur.Tests/DonusturTests.cs b/tests/Donustur.Tests/DonusturTests.cs new file mode 100644 index 0000000..36c43c6 --- /dev/null +++ b/tests/Donustur.Tests/DonusturTests.cs @@ -0,0 +1,394 @@ +using Donustur.Core.Catalog; +using Donustur.Core.Math; +using Donustur.Core.Models; +using Donustur.Core.Transactions; +using Donustur.Core.Utils; +using Donustur.Engine; +using Donustur.Engine.Archives; +using Donustur.Engine.Documents; +using Donustur.Engine.Images; +using Donustur.Engine.Qr; +using ImageMagick; +using PdfSharpCore.Drawing; +using PdfSharpCore.Pdf; +using Xunit; + +namespace Donustur.Tests; + +public class WheelMathTests +{ + [Fact] + public void DeadZone_ReturnsNegativeOne() + { + int segment = WheelMath.GetSegmentIndex(200, 200, 200, 200, 6); + Assert.Equal(-1, segment); + + int farSegment = WheelMath.GetSegmentIndex(200, 200, 200, 400, 6); + Assert.Equal(-1, farSegment); + } + + [Fact] + public void ValidAngle_ReturnsValidSegmentIndex() + { + int segmentRight = WheelMath.GetSegmentIndex(200, 200, 280, 200, 8); + Assert.InRange(segmentRight, 0, 7); + + int segmentDown = WheelMath.GetSegmentIndex(200, 200, 200, 280, 8); + Assert.InRange(segmentDown, 0, 7); + } + + [Fact] + public void PointOnCircle_CalculatesCorrectly() + { + var pt = WheelMath.GetPointOnCircle(100, 100, 50, 0); + Assert.Equal(150, pt.X, 1); + Assert.Equal(100, pt.Y, 1); + } +} + +public class FormatCatalogTests +{ + [Fact] + public void DetectsImageType() + { + Assert.True(FormatCatalog.IsImage("photo.PNG")); + Assert.True(FormatCatalog.IsImage("image.webp")); + Assert.True(FormatCatalog.IsImage("graphic.avif")); + } + + [Fact] + public void DetectsPdfType() + { + Assert.True(FormatCatalog.IsPdf("document.PDF")); + } + + [Fact] + public void DetectsDocumentType() + { + Assert.True(FormatCatalog.IsDocument("report.docx")); + Assert.True(FormatCatalog.IsDocument("notes.txt")); + } + + [Fact] + public void DetectsVideoType() + { + Assert.True(FormatCatalog.IsVideo("movie.mp4")); + Assert.True(FormatCatalog.IsVideo("clip.mkv")); + } + + [Fact] + public void GetChoicesForSingleImage_ReturnsExpectedChoices() + { + var choices = FormatCatalog.GetChoicesForFiles(new[] { "test.png" }); + Assert.NotEmpty(choices); + Assert.Contains(choices, c => c.Id == "webp"); + Assert.Contains(choices, c => c.Id == "jpg"); + Assert.Contains(choices, c => c.Id == "pdf"); + } + + [Fact] + public void GetChoicesForMultipleImages_IncludesAnimatedGif() + { + var choices = FormatCatalog.GetChoicesForFiles(new[] { "1.png", "2.png" }); + Assert.Contains(choices, c => c.Id == "gif"); + } + + [Fact] + public void GetChoicesForSinglePdf_ReturnsExpectedChoices() + { + var choices = FormatCatalog.GetChoicesForFiles(new[] { "sample.pdf" }); + Assert.NotEmpty(choices); + Assert.Contains(choices, c => c.Id == "pdf_to_images"); + Assert.Contains(choices, c => c.Id == "pdf_to_txt"); + Assert.Contains(choices, c => c.Id == "pdf_to_docx"); + } + + [Fact] + public void GetChoicesForMultiplePdfs_IncludesMerge() + { + var choices = FormatCatalog.GetChoicesForFiles(new[] { "1.pdf", "2.pdf" }); + Assert.Contains(choices, c => c.Id == "pdf_merge"); + } +} + +public class SafePathsTests +{ + [Fact] + public void GeneratesUniquePathWhenConflictExists() + { + string tempDir = Path.Combine(Path.GetTempPath(), "DonusturTest_" + Guid.NewGuid()); + Directory.CreateDirectory(tempDir); + try + { + string file1 = Path.Combine(tempDir, "output.txt"); + File.WriteAllText(file1, "hello"); + + string unique = SafePaths.GetUniquePath(tempDir, "output.txt"); + Assert.NotEqual(file1, unique); + Assert.Contains("output (1).txt", unique); + } + finally + { + if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); + } + } +} + +public class ExportTransactionTests +{ + [Fact] + public void CommitTo_MovesStagedFilesToDestination() + { + string baseDir = Path.Combine(Path.GetTempPath(), "DonusturTxBase_" + Guid.NewGuid()); + string destDir = Path.Combine(Path.GetTempPath(), "DonusturTxDest_" + Guid.NewGuid()); + Directory.CreateDirectory(destDir); + try + { + using (var tx = new ExportTransaction(baseDir)) + { + string stagedFile = Path.Combine(tx.StagingDirectory, "result.txt"); + File.WriteAllText(stagedFile, "done"); + + var committed = tx.CommitTo(destDir); + Assert.Single(committed); + Assert.True(File.Exists(committed[0])); + Assert.True(tx.IsCommitted); + } + } + finally + { + if (Directory.Exists(baseDir)) Directory.Delete(baseDir, true); + if (Directory.Exists(destDir)) Directory.Delete(destDir, true); + } + } + + [Fact] + public void CommitTo_PreservesDirectoryHierarchy() + { + string baseDir = Path.Combine(Path.GetTempPath(), "DonusturTxDirBase_" + Guid.NewGuid()); + string destDir = Path.Combine(Path.GetTempPath(), "DonusturTxDirDest_" + Guid.NewGuid()); + Directory.CreateDirectory(destDir); + try + { + using (var tx = new ExportTransaction(baseDir)) + { + string nestedDir = Path.Combine(tx.StagingDirectory, "Pack_Cikarilan", "SubFolder"); + Directory.CreateDirectory(nestedDir); + File.WriteAllText(Path.Combine(nestedDir, "inner.txt"), "nested content"); + + var committed = tx.CommitTo(destDir); + Assert.Single(committed); + Assert.True(Directory.Exists(committed[0])); + Assert.True(File.Exists(Path.Combine(committed[0], "SubFolder", "inner.txt"))); + } + } + finally + { + if (Directory.Exists(baseDir)) Directory.Delete(baseDir, true); + if (Directory.Exists(destDir)) Directory.Delete(destDir, true); + } + } + + [Fact] + public void DisposeWithoutCommit_CleansUpStaging() + { + string baseDir = Path.Combine(Path.GetTempPath(), "DonusturTxRollback_" + Guid.NewGuid()); + string stagingDir; + using (var tx = new ExportTransaction(baseDir)) + { + stagingDir = tx.StagingDirectory; + string stagedFile = Path.Combine(tx.StagingDirectory, "temporary.txt"); + File.WriteAllText(stagedFile, "discard me"); + } + + Assert.False(Directory.Exists(stagingDir)); + } +} + +public class ImageEngineTests +{ + [Fact] + public async Task ConvertsPngToWebpAndHandlesSameBaseNames() + { + string tempDir = Path.Combine(Path.GetTempPath(), "DonusturImgTest_" + Guid.NewGuid()); + Directory.CreateDirectory(tempDir); + try + { + string inputPng = Path.Combine(tempDir, "sample.png"); + string inputBmp = Path.Combine(tempDir, "sample.bmp"); + using (var image = new MagickImage(MagickColors.Crimson, 100, 100)) + { + image.Write(inputPng); + image.Write(inputBmp); + } + + var engine = new ImageMagickEngine(); + using var tx = new ExportTransaction(tempDir); + var options = new ConversionOptions { ImageQuality = 85 }; + + var outputs = await engine.ConvertImagesAsync( + new[] { inputPng, inputBmp }, + "webp", + tx, + options, + null, + CancellationToken.None); + + Assert.Equal(2, outputs.Count); + Assert.NotEqual(outputs[0], outputs[1]); + Assert.All(outputs, p => Assert.True(File.Exists(p) && new FileInfo(p).Length > 0)); + } + finally + { + if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); + } + } +} + +public class PdfAndDocxEngineTests +{ + private static string CreateSamplePdf(string dir, string fileName, string content) + { + string path = Path.Combine(dir, fileName); + using var doc = new PdfDocument(); + var page = doc.AddPage(); + using var gfx = XGraphics.FromPdfPage(page); + var font = new XFont("Arial", 14, XFontStyle.Regular); + gfx.DrawString(content, font, XBrushes.Black, new XPoint(50, 100)); + doc.Save(path); + return path; + } + + [Fact] + public async Task PdfToDocx_And_PdfToJpg_WorkThroughDispatcher() + { + string tempDir = Path.Combine(Path.GetTempPath(), "DonusturPdfDocxTest_" + Guid.NewGuid()); + Directory.CreateDirectory(tempDir); + try + { + string pdfPath = CreateSamplePdf(tempDir, "rapor.pdf", "Merhaba Dunya PDF Test Icerigi"); + var prefs = new AppPreferences + { + OutputDirectoryMode = "Custom", + CustomOutputDirectory = tempDir + }; + var dispatcher = new ConversionDispatcher(prefs); + + // 1. pdf_to_docx + var docxTask = new ConversionTask + { + InputFiles = new[] { pdfPath }, + TargetActionId = "pdf_to_docx", + TargetDisplayName = "DOCX Yap" + }; + var docxRes = await dispatcher.ExecuteTaskAsync(docxTask, prefs); + Assert.True(docxRes.Success, docxRes.ErrorMessage); + Assert.Single(docxRes.OutputFiles); + Assert.EndsWith(".docx", docxRes.OutputFiles[0], StringComparison.OrdinalIgnoreCase); + + string extractedFromDocx = DocxHelper.ExtractTextFromDocx(docxRes.OutputFiles[0]); + Assert.Contains("Merhaba", extractedFromDocx); + + // 2. pdf_to_jpg + var jpgTask = new ConversionTask + { + InputFiles = new[] { pdfPath }, + TargetActionId = "pdf_to_jpg", + TargetDisplayName = "Sayfaları JPG Yap" + }; + var jpgRes = await dispatcher.ExecuteTaskAsync(jpgTask, prefs); + Assert.True(jpgRes.Success, jpgRes.ErrorMessage); + Assert.NotEmpty(jpgRes.OutputFiles); + Assert.EndsWith(".jpg", jpgRes.OutputFiles[0], StringComparison.OrdinalIgnoreCase); + } + finally + { + if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); + } + } + + [Fact] + public async Task MergePdfAndImage_CreatesCombinedPdf() + { + string tempDir = Path.Combine(Path.GetTempPath(), "DonusturMergeMixTest_" + Guid.NewGuid()); + Directory.CreateDirectory(tempDir); + try + { + string pdfPath = CreateSamplePdf(tempDir, "sayfa1.pdf", "Birinci Sayfa"); + string imgPath = Path.Combine(tempDir, "sayfa2.png"); + using (var img = new MagickImage(MagickColors.CornflowerBlue, 200, 200)) + { + img.Write(imgPath); + } + + var pdfEngine = new PdfEngine(); + using var tx = new ExportTransaction(tempDir); + string merged = await pdfEngine.MergePdfsAsync(new[] { pdfPath, imgPath }, tx); + + Assert.True(File.Exists(merged)); + using var doc = UglyToad.PdfPig.PdfDocument.Open(merged); + Assert.Equal(2, doc.NumberOfPages); + } + finally + { + if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); + } + } +} + +public class ArchiveEngineTests +{ + [Fact] + public async Task CreateAndExtractTarGz_PreservesFiles() + { + string tempDir = Path.Combine(Path.GetTempPath(), "DonusturArchiveTest_" + Guid.NewGuid()); + Directory.CreateDirectory(tempDir); + try + { + string f1 = Path.Combine(tempDir, "a.txt"); + File.WriteAllText(f1, "icerik A"); + + var engine = new ArchiveEngine(); + using var tx = new ExportTransaction(tempDir); + + string tarGz = await engine.CreateTarGzAsync(new[] { f1 }, tx); + Assert.True(File.Exists(tarGz)); + Assert.EndsWith(".tar.gz", tarGz, StringComparison.OrdinalIgnoreCase); + + string extractedDir = await engine.ExtractAsync(tarGz, tx); + Assert.True(Directory.Exists(extractedDir)); + Assert.True(File.Exists(Path.Combine(extractedDir, "a.txt"))); + } + finally + { + if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); + } + } +} + +public class QrEngineTests +{ + [Fact] + public void GenerateAndReadQrCode() + { + string tempDir = Path.Combine(Path.GetTempPath(), "DonusturQrTest_" + Guid.NewGuid()); + Directory.CreateDirectory(tempDir); + try + { + var qrEngine = new QrEngine(); + using var tx = new ExportTransaction(tempDir); + string payload = "https://github.com/donustur"; + + string qrFile = qrEngine.GenerateQrCode(payload, tx, 300); + Assert.True(File.Exists(qrFile)); + + string? decoded = qrEngine.ReadQrCode(qrFile); + Assert.NotNull(decoded); + Assert.Equal(payload, decoded); + } + finally + { + if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); + } + } +}