feat: LD Converter v1.1.0 - Full engine, UI, custom icon & single-instance release
This commit is contained in:
commit
24cfcf44e8
76 changed files with 7612 additions and 0 deletions
16
.gitignore
vendored
Normal file
16
.gitignore
vendored
Normal file
|
|
@ -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
|
||||
50
Donustur.sln
Normal file
50
Donustur.sln
Normal file
|
|
@ -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
|
||||
44
README.md
Normal file
44
README.md
Normal file
|
|
@ -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
|
||||
```
|
||||
BIN
publish/Donustur.Core.dll
Normal file
BIN
publish/Donustur.Core.dll
Normal file
Binary file not shown.
BIN
publish/Donustur.Core.pdb
Normal file
BIN
publish/Donustur.Core.pdb
Normal file
Binary file not shown.
BIN
publish/Donustur.Engine.dll
Normal file
BIN
publish/Donustur.Engine.dll
Normal file
Binary file not shown.
BIN
publish/Donustur.Engine.pdb
Normal file
BIN
publish/Donustur.Engine.pdb
Normal file
Binary file not shown.
BIN
publish/ICSharpCode.SharpZipLib.dll
Normal file
BIN
publish/ICSharpCode.SharpZipLib.dll
Normal file
Binary file not shown.
239
publish/LDConverter.deps.json
Normal file
239
publish/LDConverter.deps.json
Normal file
|
|
@ -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": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
publish/LDConverter.dll
Normal file
BIN
publish/LDConverter.dll
Normal file
Binary file not shown.
BIN
publish/LDConverter.exe
Normal file
BIN
publish/LDConverter.exe
Normal file
Binary file not shown.
BIN
publish/LDConverter.pdb
Normal file
BIN
publish/LDConverter.pdb
Normal file
Binary file not shown.
19
publish/LDConverter.runtimeconfig.json
Normal file
19
publish/LDConverter.runtimeconfig.json
Normal file
|
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
publish/Magick.NET-Q8-x64.dll
Normal file
BIN
publish/Magick.NET-Q8-x64.dll
Normal file
Binary file not shown.
BIN
publish/Magick.NET.Core.dll
Normal file
BIN
publish/Magick.NET.Core.dll
Normal file
Binary file not shown.
BIN
publish/Magick.Native-Q8-x64.dll
Normal file
BIN
publish/Magick.Native-Q8-x64.dll
Normal file
Binary file not shown.
BIN
publish/PdfSharpCore.dll
Normal file
BIN
publish/PdfSharpCore.dll
Normal file
Binary file not shown.
BIN
publish/SharpCompress.dll
Normal file
BIN
publish/SharpCompress.dll
Normal file
Binary file not shown.
BIN
publish/SixLabors.Fonts.dll
Normal file
BIN
publish/SixLabors.Fonts.dll
Normal file
Binary file not shown.
BIN
publish/SixLabors.ImageSharp.dll
Normal file
BIN
publish/SixLabors.ImageSharp.dll
Normal file
Binary file not shown.
BIN
publish/UglyToad.PdfPig.Core.dll
Normal file
BIN
publish/UglyToad.PdfPig.Core.dll
Normal file
Binary file not shown.
BIN
publish/UglyToad.PdfPig.DocumentLayoutAnalysis.dll
Normal file
BIN
publish/UglyToad.PdfPig.DocumentLayoutAnalysis.dll
Normal file
Binary file not shown.
BIN
publish/UglyToad.PdfPig.Fonts.dll
Normal file
BIN
publish/UglyToad.PdfPig.Fonts.dll
Normal file
Binary file not shown.
BIN
publish/UglyToad.PdfPig.Package.dll
Normal file
BIN
publish/UglyToad.PdfPig.Package.dll
Normal file
Binary file not shown.
BIN
publish/UglyToad.PdfPig.Tokenization.dll
Normal file
BIN
publish/UglyToad.PdfPig.Tokenization.dll
Normal file
Binary file not shown.
BIN
publish/UglyToad.PdfPig.Tokens.dll
Normal file
BIN
publish/UglyToad.PdfPig.Tokens.dll
Normal file
Binary file not shown.
BIN
publish/UglyToad.PdfPig.dll
Normal file
BIN
publish/UglyToad.PdfPig.dll
Normal file
Binary file not shown.
BIN
publish/de/PdfSharpCore.resources.dll
Normal file
BIN
publish/de/PdfSharpCore.resources.dll
Normal file
Binary file not shown.
BIN
publish/zxing.dll
Normal file
BIN
publish/zxing.dll
Normal file
Binary file not shown.
215
src/Donustur.Core/Catalog/FormatCatalog.cs
Normal file
215
src/Donustur.Core/Catalog/FormatCatalog.cs
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
using Donustur.Core.Models;
|
||||
|
||||
namespace Donustur.Core.Catalog;
|
||||
|
||||
public static class FormatCatalog
|
||||
{
|
||||
private static readonly HashSet<string> ImageExts = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"jpg", "jpeg", "png", "webp", "avif", "bmp", "tiff", "tif", "gif", "ico", "svg", "heic", "heif"
|
||||
};
|
||||
|
||||
private static readonly HashSet<string> VideoExts = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"mp4", "mkv", "avi", "mov", "webm", "flv", "wmv", "m4v"
|
||||
};
|
||||
|
||||
private static readonly HashSet<string> AudioExts = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"mp3", "wav", "aac", "m4a", "flac", "ogg", "opus", "wma"
|
||||
};
|
||||
|
||||
private static readonly HashSet<string> DocumentExts = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"docx", "doc", "pptx", "ppt", "xlsx", "xls", "odt", "rtf", "txt", "md", "html", "htm", "epub"
|
||||
};
|
||||
|
||||
private static readonly HashSet<string> 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));
|
||||
|
||||
/// <summary>
|
||||
/// Gelen dosya listesine göre çark üzerinde gösterilecek en uygun seçenekleri üretir.
|
||||
/// 6 ila 8 dilim ideal bir çark deneyimi sağlar.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<ToolChoice> GetChoicesForFiles(IReadOnlyList<string> filePaths)
|
||||
{
|
||||
if (filePaths.Count == 0)
|
||||
{
|
||||
return GetDefaultChoices();
|
||||
}
|
||||
|
||||
bool anyDirs = filePaths.Any(IsDirectory);
|
||||
if (anyDirs)
|
||||
{
|
||||
return new List<ToolChoice>
|
||||
{
|
||||
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<ToolChoice>
|
||||
{
|
||||
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<ToolChoice>
|
||||
{
|
||||
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<ToolChoice>
|
||||
{
|
||||
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<ToolChoice>
|
||||
{
|
||||
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<ToolChoice>
|
||||
{
|
||||
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<ToolChoice>
|
||||
{
|
||||
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<ToolChoice>
|
||||
{
|
||||
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<ToolChoice> GetDefaultChoices()
|
||||
{
|
||||
return new List<ToolChoice>
|
||||
{
|
||||
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")
|
||||
};
|
||||
}
|
||||
}
|
||||
9
src/Donustur.Core/Donustur.Core.csproj
Normal file
9
src/Donustur.Core/Donustur.Core.csproj
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
79
src/Donustur.Core/Math/WheelMath.cs
Normal file
79
src/Donustur.Core/Math/WheelMath.cs
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
namespace Donustur.Core.Math;
|
||||
|
||||
public readonly record struct WheelPoint(double X, double Y);
|
||||
|
||||
public static class WheelMath
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verilen dilimin merkez açısını (derece cinsinden) hesaplar.
|
||||
/// 0. dilim saat 12 yönündedir (tepede).
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Açı ve yarıçapa göre çember üzerindeki koordinatı hesaplar.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
18
src/Donustur.Core/Models/AppPreferences.cs
Normal file
18
src/Donustur.Core/Models/AppPreferences.cs
Normal file
|
|
@ -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;
|
||||
}
|
||||
21
src/Donustur.Core/Models/ConversionOptions.cs
Normal file
21
src/Donustur.Core/Models/ConversionOptions.cs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
namespace Donustur.Core.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Dönüştürme işlemleri için yapılandırma seçenekleri.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
38
src/Donustur.Core/Models/ConversionTask.cs
Normal file
38
src/Donustur.Core/Models/ConversionTask.cs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
namespace Donustur.Core.Models;
|
||||
|
||||
public enum ConversionTaskStatus
|
||||
{
|
||||
Queued,
|
||||
Running,
|
||||
Completed,
|
||||
Failed,
|
||||
Cancelled
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bir dönüştürme görevinin durum ve çıktı bilgilerini temsil eder.
|
||||
/// </summary>
|
||||
public sealed class ConversionTask
|
||||
{
|
||||
public string Id { get; init; } = Guid.NewGuid().ToString("N");
|
||||
public IReadOnlyList<string> InputFiles { get; init; } = Array.Empty<string>();
|
||||
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<string> 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<string> OutputFiles,
|
||||
string? ErrorMessage = null,
|
||||
TimeSpan? Duration = null
|
||||
);
|
||||
13
src/Donustur.Core/Models/ToolChoice.cs
Normal file
13
src/Donustur.Core/Models/ToolChoice.cs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
namespace Donustur.Core.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Çark üzerinde veya arayüzde gösterilen dönüştürme/işlem seçeneği.
|
||||
/// </summary>
|
||||
public sealed record ToolChoice(
|
||||
string Id,
|
||||
string DisplayName,
|
||||
string Category,
|
||||
string IconKey,
|
||||
string Description,
|
||||
bool RequiresOptions = false
|
||||
);
|
||||
147
src/Donustur.Core/Services/HistoryStore.cs
Normal file
147
src/Donustur.Core/Services/HistoryStore.cs
Normal file
|
|
@ -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<string> InputFiles { get; set; } = new();
|
||||
public List<string> 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<HistoryEntry> _entries = new();
|
||||
private readonly object _lock = new();
|
||||
|
||||
public IReadOnlyList<HistoryEntry> 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<List<HistoryEntry>>(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
|
||||
}
|
||||
}
|
||||
}
|
||||
82
src/Donustur.Core/Services/PreferencesStore.cs
Normal file
82
src/Donustur.Core/Services/PreferencesStore.cs
Normal file
|
|
@ -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<AppPreferences>? 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<AppPreferences>(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
|
||||
}
|
||||
}
|
||||
}
|
||||
118
src/Donustur.Core/Transactions/ExportTransaction.cs
Normal file
118
src/Donustur.Core/Transactions/ExportTransaction.cs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
using Donustur.Core.Utils;
|
||||
|
||||
namespace Donustur.Core.Transactions;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Staging klasöründeki tüm dosya ve alt klasörleri yapısını koruyarak hedef klasöre taşır.
|
||||
/// </summary>
|
||||
public List<string> CommitTo(string destinationFolder, bool overwrite = false)
|
||||
{
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException(nameof(ExportTransaction));
|
||||
|
||||
if (!Directory.Exists(destinationFolder))
|
||||
{
|
||||
Directory.CreateDirectory(destinationFolder);
|
||||
}
|
||||
|
||||
var finalPaths = new List<string>();
|
||||
|
||||
// 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ç
|
||||
}
|
||||
}
|
||||
}
|
||||
64
src/Donustur.Core/Utils/FileUtils.cs
Normal file
64
src/Donustur.Core/Utils/FileUtils.cs
Normal file
|
|
@ -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}%";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verilen dosya veya klasör yollarının toplam bayt boyutunu hesaplar.
|
||||
/// </summary>
|
||||
public static long CalculateTotalBytes(IEnumerable<string> 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;
|
||||
}
|
||||
}
|
||||
35
src/Donustur.Core/Utils/SafePaths.cs
Normal file
35
src/Donustur.Core/Utils/SafePaths.cs
Normal file
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
522
src/Donustur.Engine/Archives/ArchiveEngine.cs
Normal file
522
src/Donustur.Engine/Archives/ArchiveEngine.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Arşiv dosyasını klasöre çıkarır. ZIP, 7Z, TAR, GZ, TGZ, RAR destekler.
|
||||
/// </summary>
|
||||
public async Task<string> ExtractAsync(
|
||||
string archivePath,
|
||||
ExportTransaction transaction,
|
||||
string? password = null,
|
||||
IProgress<double>? 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<double>? 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verilen dosyaları (veya mevcut arşivlerin içeriğini) ZIP arşivi olarak paketler.
|
||||
/// </summary>
|
||||
public async Task<string> CreateZipAsync(
|
||||
IReadOnlyList<string> files,
|
||||
ExportTransaction transaction,
|
||||
string? zipName = null,
|
||||
IProgress<double>? 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<string>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verilen dosyaları .tar.gz olarak paketler.
|
||||
/// </summary>
|
||||
public async Task<string> CreateTarGzAsync(
|
||||
IReadOnlyList<string> files,
|
||||
ExportTransaction transaction,
|
||||
string? archiveName = null,
|
||||
IProgress<double>? 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verilen dosyaları 7-Zip (.7z) olarak paketler. Sistemde 7z.exe varsa kullanır.
|
||||
/// </summary>
|
||||
public async Task<string> Create7zAsync(
|
||||
IReadOnlyList<string> files,
|
||||
ExportTransaction transaction,
|
||||
string? archiveName = null,
|
||||
IProgress<double>? 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private async Task<string> ConvertArchivesToFormatAsync(
|
||||
IReadOnlyList<string> archiveFiles,
|
||||
string targetFormat,
|
||||
ExportTransaction transaction,
|
||||
IProgress<double>? 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<string> CreateZipFromExtractedAsync(
|
||||
IReadOnlyList<string> items,
|
||||
string baseName,
|
||||
ExportTransaction transaction,
|
||||
IProgress<double>? 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<string>(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<string> CreateTarGzFromExtractedAsync(
|
||||
IReadOnlyList<string> items,
|
||||
string baseName,
|
||||
ExportTransaction transaction,
|
||||
IProgress<double>? 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<string> Create7zFromExtractedAsync(
|
||||
IReadOnlyList<string> items,
|
||||
string baseName,
|
||||
ExportTransaction transaction,
|
||||
IProgress<double>? 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seçili dosya ve klasörleri yeni bir klasör altında toplar.
|
||||
/// </summary>
|
||||
public async Task<string> CollectToFolderAsync(
|
||||
IReadOnlyList<string> files,
|
||||
ExportTransaction transaction,
|
||||
IProgress<double>? 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<string> 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<string> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
344
src/Donustur.Engine/ConversionDispatcher.cs
Normal file
344
src/Donustur.Engine/ConversionDispatcher.cs
Normal file
|
|
@ -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<ConversionResult> ExecuteTaskAsync(
|
||||
ConversionTask task,
|
||||
AppPreferences preferences,
|
||||
IProgress<double>? 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<string> generatedStagedFiles;
|
||||
|
||||
// 1. QR İşlemleri (Görsel ve PDF destekli)
|
||||
if (targetAction == "qr_read")
|
||||
{
|
||||
var qrResults = new List<string>();
|
||||
var decodedTexts = new List<string>();
|
||||
|
||||
for (int i = 0; i < files.Count; i++)
|
||||
{
|
||||
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<string>();
|
||||
foreach (var f in files)
|
||||
{
|
||||
string dir = await _archiveEngine.ExtractAsync(f, transaction, task.Options.ArchivePassword, progress, token);
|
||||
extractedDirs.Add(dir);
|
||||
}
|
||||
generatedStagedFiles = extractedDirs;
|
||||
}
|
||||
// 3. ZIP Paketleme / Arşiv Dönüştürme
|
||||
else if (targetAction == "zip")
|
||||
{
|
||||
string zip = await _archiveEngine.CreateZipAsync(files, transaction, null, progress, token);
|
||||
generatedStagedFiles = new[] { zip };
|
||||
}
|
||||
// 4. 7Z Paketleme / Arşiv Dönüştürme
|
||||
else if (targetAction == "7z")
|
||||
{
|
||||
string sevenZ = await _archiveEngine.Create7zAsync(files, transaction, null, progress, token);
|
||||
generatedStagedFiles = new[] { sevenZ };
|
||||
}
|
||||
// 5. TAR.GZ Paketleme / Arşiv Dönüştürme
|
||||
else if (targetAction == "tar_gz")
|
||||
{
|
||||
string tarGz = await _archiveEngine.CreateTarGzAsync(files, transaction, null, progress, token);
|
||||
generatedStagedFiles = new[] { tarGz };
|
||||
}
|
||||
// 6. Yeni Klasöre Toplama
|
||||
else if (targetAction == "copy_folder")
|
||||
{
|
||||
string folder = await _archiveEngine.CollectToFolderAsync(files, transaction, progress, token);
|
||||
generatedStagedFiles = new[] { folder };
|
||||
}
|
||||
// 7. PDF veya Görsel Birleştirme
|
||||
else if (targetAction == "pdf_merge")
|
||||
{
|
||||
if (files.All(FormatCatalog.IsImage))
|
||||
{
|
||||
generatedStagedFiles = await _imageEngine.ConvertImagesAsync(files, "pdf", transaction, task.Options, progress, token);
|
||||
}
|
||||
else
|
||||
{
|
||||
var mergeable = files.Where(f => FormatCatalog.IsPdf(f) || FormatCatalog.IsImage(f)).ToList();
|
||||
if (mergeable.Count == 0)
|
||||
{
|
||||
throw new InvalidOperationException("PDF olarak birleştirmek için en az bir PDF veya görsel dosyası seçilmelidir.");
|
||||
}
|
||||
string merged = await _pdfEngine.MergePdfsAsync(mergeable, transaction, null, progress, token);
|
||||
generatedStagedFiles = new[] { merged };
|
||||
}
|
||||
}
|
||||
// 8. PDF Sayfa Ayırma
|
||||
else if (targetAction == "pdf_split")
|
||||
{
|
||||
var splitFiles = new List<string>();
|
||||
foreach (var f in files.Where(FormatCatalog.IsPdf))
|
||||
{
|
||||
var pages = await _pdfEngine.SplitPdfAsync(f, transaction, progress, token);
|
||||
splitFiles.AddRange(pages);
|
||||
}
|
||||
generatedStagedFiles = splitFiles;
|
||||
}
|
||||
// 9. PDF'den Metin Çıkarma
|
||||
else if (targetAction == "pdf_to_txt")
|
||||
{
|
||||
var txts = new List<string>();
|
||||
foreach (var f in files)
|
||||
{
|
||||
string txt = await _pdfEngine.ExtractTextAsync(f, transaction, progress, token);
|
||||
txts.Add(txt);
|
||||
}
|
||||
generatedStagedFiles = txts;
|
||||
}
|
||||
// 10. PDF'den Word (DOCX) Belgesine Dönüştürme
|
||||
else if (targetAction == "pdf_to_docx")
|
||||
{
|
||||
var docxs = new List<string>();
|
||||
foreach (var f in files)
|
||||
{
|
||||
string docx = await _pdfEngine.ConvertToDocxAsync(f, transaction, progress, token);
|
||||
docxs.Add(docx);
|
||||
}
|
||||
generatedStagedFiles = docxs;
|
||||
}
|
||||
// 11. PDF'den Görsele (PNG veya JPG) Aktarma
|
||||
else if (targetAction is "pdf_to_images" or "pdf_to_jpg")
|
||||
{
|
||||
string imgFormat = targetAction == "pdf_to_jpg" ? "jpg" : "png";
|
||||
var imgs = new List<string>();
|
||||
foreach (var f in files)
|
||||
{
|
||||
var extracted = await _pdfEngine.ExtractImagesAsync(f, transaction, progress, token, imgFormat);
|
||||
imgs.AddRange(extracted);
|
||||
}
|
||||
generatedStagedFiles = imgs;
|
||||
}
|
||||
// 12. Görsel İşlemleri (PNG, JPG, WEBP, AVIF, ICO, Çoklu Görsel -> GIF/PDF vb.)
|
||||
else if (files.All(FormatCatalog.IsImage) &&
|
||||
targetAction is "png" or "jpg" or "webp" or "avif" or "ico" or "bmp" or "tiff" or "gif" or "pdf" or "compress_image")
|
||||
{
|
||||
generatedStagedFiles = await _imageEngine.ConvertImagesAsync(files, targetAction, transaction, task.Options, progress, token);
|
||||
}
|
||||
// 13. Video ve Ses Dönüşümleri
|
||||
else if (files.Any(FormatCatalog.IsVideo) || files.Any(FormatCatalog.IsAudio) ||
|
||||
targetAction is "mp4" or "mp3" or "wav" or "aac" or "flac" or "ogg" or "mkv" or "webm" or "compress_video" or "compress_audio")
|
||||
{
|
||||
generatedStagedFiles = await _mediaEngine.ConvertMediaAsync(files, targetAction, transaction, task.Options, progress, token);
|
||||
}
|
||||
// 14. Ofis Belgeleri (DOCX, PPTX, XLSX, ODT, TXT, MD, HTML vb.)
|
||||
else if (files.All(FormatCatalog.IsDocument) || targetAction is "docx" or "txt" or "html")
|
||||
{
|
||||
generatedStagedFiles = await _officeEngine.ConvertDocumentsAsync(files, targetAction, transaction, progress, token);
|
||||
}
|
||||
// 15. Tekil Görsel Yedeği
|
||||
else if (targetAction is "png" or "jpg" or "webp" or "avif" or "ico" or "compress_image")
|
||||
{
|
||||
generatedStagedFiles = await _imageEngine.ConvertImagesAsync(files, targetAction, transaction, task.Options, progress, token);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 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<string>(), "İşlem kullanıcı tarafından iptal edildi.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
task.Status = ConversionTaskStatus.Failed;
|
||||
task.CompletedAt = DateTime.Now;
|
||||
task.ErrorMessage = ex.Message;
|
||||
|
||||
_historyStore?.Add(new HistoryEntry
|
||||
{
|
||||
Title = task.InputFiles.Count == 1
|
||||
? Path.GetFileName(task.InputFiles[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
|
||||
: $"{task.InputFiles.Count} dosya",
|
||||
FormatSummary = FormatFriendlyActionLabel(targetAction),
|
||||
InputFiles = task.InputFiles.ToList(),
|
||||
OutputFiles = new List<string>(),
|
||||
Timestamp = DateTime.Now,
|
||||
Success = false,
|
||||
ErrorMessage = ex.Message
|
||||
});
|
||||
|
||||
return new ConversionResult(false, Array.Empty<string>(), ex.Message, task.Duration);
|
||||
}
|
||||
}
|
||||
|
||||
private static string FormatFriendlyActionLabel(string action)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
136
src/Donustur.Engine/Documents/DocxHelper.cs
Normal file
136
src/Donustur.Engine/Documents/DocxHelper.cs
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
using System.IO.Compression;
|
||||
using System.Security;
|
||||
using System.Text;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Donustur.Engine.Documents;
|
||||
|
||||
/// <summary>
|
||||
/// Harici ofis kurulumuna ihtiyaç duymadan standart OpenXML (.docx) dosyaları
|
||||
/// oluşturmak ve mevcut .docx dosyalarından metin okumak için yerel yardımcı.
|
||||
/// </summary>
|
||||
public static class DocxHelper
|
||||
{
|
||||
public static void CreateDocxFromPages(string outputPath, IReadOnlyList<string> 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", """
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
||||
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
||||
<Default Extension="xml" ContentType="application/xml"/>
|
||||
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
|
||||
</Types>
|
||||
""");
|
||||
|
||||
// 2. _rels/.rels
|
||||
WriteZipText(archive, "_rels/.rels", """
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
|
||||
</Relationships>
|
||||
""");
|
||||
|
||||
// 3. word/document.xml
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine("""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>""");
|
||||
sb.AppendLine("""<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">""");
|
||||
sb.AppendLine(" <w:body>");
|
||||
|
||||
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(" <w:p>");
|
||||
if (!string.IsNullOrEmpty(escaped))
|
||||
{
|
||||
sb.AppendLine($" <w:r><w:t xml:space=\"preserve\">{escaped}</w:t></w:r>");
|
||||
}
|
||||
sb.AppendLine(" </w:p>");
|
||||
}
|
||||
|
||||
if (p < pages.Count - 1)
|
||||
{
|
||||
sb.AppendLine(" <w:p><w:r><w:br w:type=\"page\"/></w:r></w:p>");
|
||||
}
|
||||
}
|
||||
|
||||
sb.AppendLine(" </w:body>");
|
||||
sb.AppendLine("</w:document>");
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
315
src/Donustur.Engine/Documents/OfficeDocumentEngine.cs
Normal file
315
src/Donustur.Engine/Documents/OfficeDocumentEngine.cs
Normal file
|
|
@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// LibreOffice soffice.exe yolunu bulur.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<string>> ConvertDocumentsAsync(
|
||||
IReadOnlyList<string> inputFiles,
|
||||
string targetFormat,
|
||||
ExportTransaction transaction,
|
||||
IProgress<double>? progress = null,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var outputFiles = new List<string>();
|
||||
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<string?> 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)[^>]*?>.*?</\1>", "", 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("<!DOCTYPE html>");
|
||||
sb.AppendLine("<html lang=\"tr\">");
|
||||
sb.AppendLine("<head>");
|
||||
sb.AppendLine(" <meta charset=\"UTF-8\">");
|
||||
sb.AppendLine(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
|
||||
sb.AppendLine($" <title>{WebUtility.HtmlEncode(title)}</title>");
|
||||
sb.AppendLine(" <style>body{font-family:'Segoe UI',system-ui,sans-serif;line-height:1.6;max-width:800px;margin:40px auto;padding:0 20px;color:#1f2937;background:#ffffff;}p{margin:0 0 12px 0;white-space:pre-wrap;}</style>");
|
||||
sb.AppendLine("</head>");
|
||||
sb.AppendLine("<body>");
|
||||
|
||||
string[] lines = text.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n');
|
||||
foreach (var line in lines)
|
||||
{
|
||||
sb.AppendLine($" <p>{WebUtility.HtmlEncode(line)}</p>");
|
||||
}
|
||||
|
||||
sb.AppendLine("</body>");
|
||||
sb.AppendLine("</html>");
|
||||
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<string>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
357
src/Donustur.Engine/Documents/PdfEngine.cs
Normal file
357
src/Donustur.Engine/Documents/PdfEngine.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Çoklu PDF belgelerini (veya PDF + Görsel karışımını) tek bir PDF dosyasında birleştirir.
|
||||
/// </summary>
|
||||
public async Task<string> MergePdfsAsync(
|
||||
IReadOnlyList<string> inputFiles,
|
||||
ExportTransaction transaction,
|
||||
string? outputName = null,
|
||||
IProgress<double>? 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bir PDF belgesinin sayfalarını ayrı PDF dosyalarına böler.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<string>> SplitPdfAsync(
|
||||
string inputPdf,
|
||||
ExportTransaction transaction,
|
||||
IProgress<double>? progress = null,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var outputPaths = new List<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PDF belgesindeki tüm metinleri çıkarıp .txt dosyası olarak kaydeder.
|
||||
/// </summary>
|
||||
public async Task<string> ExtractTextAsync(
|
||||
string inputPdf,
|
||||
ExportTransaction transaction,
|
||||
IProgress<double>? 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PDF belgesini Word (.docx) belgesine dönüştürür.
|
||||
/// </summary>
|
||||
public async Task<string> ConvertToDocxAsync(
|
||||
string inputPdf,
|
||||
ExportTransaction transaction,
|
||||
IProgress<double>? 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<string>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PDF içindeki görselleri veya sayfaları hedef görsel formatında (png/jpg) dışa aktarır.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<string>> ExtractImagesAsync(
|
||||
string inputPdf,
|
||||
ExportTransaction transaction,
|
||||
IProgress<double>? progress = null,
|
||||
CancellationToken token = default,
|
||||
string targetFormat = "png")
|
||||
{
|
||||
var outputs = new List<string>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
21
src/Donustur.Engine/Donustur.Engine.csproj
Normal file
21
src/Donustur.Engine/Donustur.Engine.csproj
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Donustur.Core\Donustur.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Magick.NET-Q8-x64" Version="15.0.0" />
|
||||
<PackageReference Include="PdfPig" Version="0.1.16" />
|
||||
<PackageReference Include="PdfSharpCore" Version="1.3.67" />
|
||||
<PackageReference Include="SharpCompress" Version="0.50.7" />
|
||||
<PackageReference Include="ZXing.Net" Version="0.16.11" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
177
src/Donustur.Engine/Images/ImageMagickEngine.cs
Normal file
177
src/Donustur.Engine/Images/ImageMagickEngine.cs
Normal file
|
|
@ -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<string> 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('.'));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tek veya çoklu görselleri hedef formata dönüştürür.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<string>> ConvertImagesAsync(
|
||||
IReadOnlyList<string> inputFiles,
|
||||
string targetFormat,
|
||||
ExportTransaction transaction,
|
||||
ConversionOptions options,
|
||||
IProgress<double>? progress = null,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var outputPaths = new List<string>();
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
174
src/Donustur.Engine/Media/MediaEngine.cs
Normal file
174
src/Donustur.Engine/Media/MediaEngine.cs
Normal file
|
|
@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// FFmpeg çalıştırılabilir dosya yolunu bulur.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Video veya ses dosyasını hedef formata dönüştürür.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<string>> ConvertMediaAsync(
|
||||
IReadOnlyList<string> inputFiles,
|
||||
string targetFormat,
|
||||
ExportTransaction transaction,
|
||||
ConversionOptions options,
|
||||
IProgress<double>? 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>();
|
||||
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}\""
|
||||
};
|
||||
}
|
||||
}
|
||||
86
src/Donustur.Engine/ProcessRunner.cs
Normal file
86
src/Donustur.Engine/ProcessRunner.cs
Normal file
|
|
@ -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);
|
||||
|
||||
/// <summary>
|
||||
/// 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ı.
|
||||
/// </summary>
|
||||
public static async Task<ProcessOutput> RunAsync(
|
||||
string exePath,
|
||||
string arguments,
|
||||
string? workingDirectory = null,
|
||||
IProgress<string>? 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());
|
||||
}
|
||||
}
|
||||
161
src/Donustur.Engine/Qr/QrEngine.cs
Normal file
161
src/Donustur.Engine/Qr/QrEngine.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Görsel veya PDF dosyasından QR kod(ları) okur ve metnini döner.
|
||||
/// </summary>
|
||||
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<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verilen metinden yüksek çözünürlüklü bir QR kod PNG görseli üretir.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
9
src/Donustur.UI/App.xaml
Normal file
9
src/Donustur.UI/App.xaml
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
<Application x:Class="Donustur.UI.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:Donustur.UI"
|
||||
ShutdownMode="OnExplicitShutdown">
|
||||
<Application.Resources>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
202
src/Donustur.UI/App.xaml.cs
Normal file
202
src/Donustur.UI/App.xaml.cs
Normal file
|
|
@ -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<string> 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<double>(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);
|
||||
}
|
||||
}
|
||||
10
src/Donustur.UI/AssemblyInfo.cs
Normal file
10
src/Donustur.UI/AssemblyInfo.cs
Normal file
|
|
@ -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)
|
||||
)]
|
||||
BIN
src/Donustur.UI/Assets/app.ico
Normal file
BIN
src/Donustur.UI/Assets/app.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 29 KiB |
277
src/Donustur.UI/Controls/RadialWheelControl.cs
Normal file
277
src/Donustur.UI/Controls/RadialWheelControl.cs
Normal file
|
|
@ -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<ToolChoice>),
|
||||
typeof(RadialWheelControl),
|
||||
new FrameworkPropertyMetadata(Array.Empty<ToolChoice>(), 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<ToolChoice> Choices
|
||||
{
|
||||
get => (IReadOnlyList<ToolChoice>)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<int>? 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;
|
||||
}
|
||||
}
|
||||
29
src/Donustur.UI/Donustur.UI.csproj
Normal file
29
src/Donustur.UI/Donustur.UI.csproj
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Donustur.Core\Donustur.Core.csproj" />
|
||||
<ProjectReference Include="..\Donustur.Engine\Donustur.Engine.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Resource Include="Assets\app.ico" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<AssemblyName>LDConverter</AssemblyName>
|
||||
<Product>LD Converter</Product>
|
||||
<Title>LD Converter</Title>
|
||||
<Version>1.1.0</Version>
|
||||
<ApplicationIcon>Assets\app.ico</ApplicationIcon>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UseWPF>true</UseWPF>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<!-- WPF tiplerine öncelik ver: WinForms tipleri sadece TrayHost'ta tam qualified isimle kullanılır -->
|
||||
<NoWarn>$(NoWarn);WFAC010</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
31
src/Donustur.UI/GlobalUsings.cs
Normal file
31
src/Donustur.UI/GlobalUsings.cs
Normal file
|
|
@ -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;
|
||||
407
src/Donustur.UI/MainWindow.xaml
Normal file
407
src/Donustur.UI/MainWindow.xaml
Normal file
|
|
@ -0,0 +1,407 @@
|
|||
<Window x:Class="Donustur.UI.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="LD Converter"
|
||||
Width="940" Height="700"
|
||||
MinWidth="800" MinHeight="580"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
Background="#0E121B"
|
||||
Foreground="#FFFFFF"
|
||||
AllowDrop="True">
|
||||
<Window.Resources>
|
||||
<Style TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable Display, Segoe UI, Arial"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="NavTabButton" TargetType="RadioButton">
|
||||
<Setter Property="Background" Value="Transparent"/>
|
||||
<Setter Property="Foreground" Value="#9CA3AF"/>
|
||||
<Setter Property="FontSize" Value="13.5"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Padding" Value="16,8"/>
|
||||
<Setter Property="Margin" Value="0,0,8,0"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="RadioButton">
|
||||
<Border x:Name="border" Background="{TemplateBinding Background}" CornerRadius="8" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter TargetName="border" Property="Background" Value="#252A3D"/>
|
||||
<Setter Property="Foreground" Value="#FFFFFF"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="border" Property="Background" Value="#1C2130"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ActionButton" TargetType="Button">
|
||||
<Setter Property="Background" Value="#6366F1"/>
|
||||
<Setter Property="Foreground" Value="#FFFFFF"/>
|
||||
<Setter Property="FontSize" Value="13"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Padding" Value="18,10"/>
|
||||
<Setter Property="BorderThickness" Value="0"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border x:Name="btnBorder" Background="{TemplateBinding Background}" CornerRadius="8" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="btnBorder" Property="Background" Value="#4F46E5"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter TargetName="btnBorder" Property="Background" Value="#374151"/>
|
||||
<Setter Property="Foreground" Value="#9CA3AF"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="SecondaryButton" TargetType="Button">
|
||||
<Setter Property="Background" Value="#262C3D"/>
|
||||
<Setter Property="Foreground" Value="#E5E7EB"/>
|
||||
<Setter Property="FontSize" Value="12.5"/>
|
||||
<Setter Property="FontWeight" Value="Medium"/>
|
||||
<Setter Property="Padding" Value="14,10"/>
|
||||
<Setter Property="BorderThickness" Value="0"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border x:Name="secBorder" Background="{TemplateBinding Background}" CornerRadius="8" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="secBorder" Property="Background" Value="#323A50"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ChipButton" TargetType="RadioButton">
|
||||
<Setter Property="Background" Value="#1A2030"/>
|
||||
<Setter Property="Foreground" Value="#D1D5DB"/>
|
||||
<Setter Property="FontSize" Value="12"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Padding" Value="14,8"/>
|
||||
<Setter Property="Margin" Value="0,0,8,8"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="BorderBrush" Value="#2F384F"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="RadioButton">
|
||||
<Border x:Name="chipBorder" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="20" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter TargetName="chipBorder" Property="Background" Value="#6366F1"/>
|
||||
<Setter TargetName="chipBorder" Property="BorderBrush" Value="#818CF8"/>
|
||||
<Setter Property="Foreground" Value="#FFFFFF"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="chipBorder" Property="BorderBrush" Value="#6366F1"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</Window.Resources>
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<!-- Üst Navigasyon / Header -->
|
||||
<RowDefinition Height="64"/>
|
||||
<!-- İçerik Alanı -->
|
||||
<RowDefinition Height="*"/>
|
||||
<!-- Durum Çubuğu -->
|
||||
<RowDefinition Height="34"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Üst Başlık & Sekmeler -->
|
||||
<Border Grid.Row="0" Background="#141824" BorderBrush="#252D42" BorderThickness="0,0,0,1" Padding="20,0">
|
||||
<Grid VerticalAlignment="Center">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Logo & İsim -->
|
||||
<StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<Image x:Name="HeaderLogoImage" Width="36" Height="36" Margin="0,0,12,0" RenderOptions.BitmapScalingMode="HighQuality"/>
|
||||
<StackPanel VerticalAlignment="Center">
|
||||
<TextBlock Text="LD Converter" FontSize="16" FontWeight="Bold" Foreground="#FFFFFF"/>
|
||||
<TextBlock Text="Hızlı Medya & Belge Aracı" FontSize="10.5" Foreground="#9CA3AF"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Navigasyon Sekmeleri -->
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
|
||||
<RadioButton x:Name="TabConvert" Content="Dönüştür" Style="{StaticResource NavTabButton}" IsChecked="True" Checked="OnTabChanged"/>
|
||||
<RadioButton x:Name="TabHistory" Content="Kitaplık" Style="{StaticResource NavTabButton}" Checked="OnTabChanged"/>
|
||||
<RadioButton x:Name="TabTools" Content="Hızlı Araçlar" Style="{StaticResource NavTabButton}" Checked="OnTabChanged"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Sağ Üst Butonlar -->
|
||||
<StackPanel Grid.Column="2" Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<Button x:Name="WheelStatusButton"
|
||||
Background="#1F293D"
|
||||
Foreground="#E5E7EB"
|
||||
BorderBrush="#374151"
|
||||
BorderThickness="1"
|
||||
Padding="12,6"
|
||||
Margin="0,0,10,0"
|
||||
Cursor="Hand"
|
||||
ToolTip="Sürükleme çarkını hızlıca aç/kapat"
|
||||
Click="OnToggleWheelClick">
|
||||
<Button.Resources>
|
||||
<Style TargetType="Border">
|
||||
<Setter Property="CornerRadius" Value="16"/>
|
||||
</Style>
|
||||
</Button.Resources>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Ellipse x:Name="WheelStatusLed" Width="8" Height="8" Fill="#10B981" Margin="0,0,8,0" VerticalAlignment="Center"/>
|
||||
<TextBlock x:Name="WheelStatusLabel" Text="Çark: Shift" FontSize="11.5" FontWeight="SemiBold"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
|
||||
<Button Content="⚙️ Ayarlar"
|
||||
Background="Transparent"
|
||||
Foreground="#9CA3AF"
|
||||
BorderThickness="0"
|
||||
FontSize="12.5"
|
||||
Cursor="Hand"
|
||||
Padding="8,6"
|
||||
Click="OnOpenSettingsClick"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- İçerik Sayfaları -->
|
||||
<Grid Grid.Row="1" Margin="24">
|
||||
<!-- 1. DÖNÜŞTÜR SEKMESİ -->
|
||||
<Grid x:Name="ConvertView" Visibility="Visible">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Sürükle Bırak Alanı -->
|
||||
<Border x:Name="DropZoneBorder"
|
||||
Grid.Row="0"
|
||||
Background="#131722"
|
||||
BorderBrush="#374151"
|
||||
BorderThickness="2"
|
||||
CornerRadius="16"
|
||||
AllowDrop="True"
|
||||
DragEnter="OnMainDragEnter"
|
||||
DragOver="OnMainDragOver"
|
||||
DragLeave="OnMainDragLeave"
|
||||
Drop="OnMainDrop">
|
||||
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Center" Margin="24">
|
||||
<StackPanel x:Name="EmptyPrompt" HorizontalAlignment="Center">
|
||||
<Border Width="68" Height="68" Background="#1E2333" CornerRadius="34" HorizontalAlignment="Center" Margin="0,0,0,16">
|
||||
<TextBlock Text="📁" FontSize="30" HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<TextBlock Text="Dosyaları veya klasörleri buraya sürükleyip bırakın"
|
||||
FontSize="17" FontWeight="Bold"
|
||||
Foreground="#FFFFFF" HorizontalAlignment="Center"/>
|
||||
<TextBlock Text="veya bilgisayarınızdan seçmek için aşağıdaki butonları kullanın"
|
||||
FontSize="12.5" Foreground="#9CA3AF"
|
||||
HorizontalAlignment="Center" Margin="0,4,0,18"/>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
|
||||
<Button Content="Dosya Seçin..."
|
||||
Style="{StaticResource ActionButton}"
|
||||
Click="OnSelectFilesClick"/>
|
||||
<Button Content="Klasör Seçin..."
|
||||
Style="{StaticResource SecondaryButton}"
|
||||
Margin="10,0,0,0"
|
||||
Click="OnSelectFolderClick"/>
|
||||
</StackPanel>
|
||||
<TextBlock Text="💡 İpucu: Masaüstünde veya klasörde dosyayı sürüklerken Shift tuşuna basarak hızlı çarkı açabilirsiniz!"
|
||||
FontSize="11.5" Foreground="#818CF8"
|
||||
HorizontalAlignment="Center" Margin="0,22,0,0"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Seçili Dosyalar Paneli -->
|
||||
<StackPanel x:Name="SelectedFilesPanel" Visibility="Collapsed" HorizontalAlignment="Center" Width="700">
|
||||
<TextBlock x:Name="FilesCountLabel" Text="3 dosya seçildi" FontSize="16" FontWeight="Bold" HorizontalAlignment="Center" Margin="0,0,0,4"/>
|
||||
<TextBlock x:Name="FilesSubLabel" Text="Toplam boyut: 1.4 MB" FontSize="12" Foreground="#9CA3AF" HorizontalAlignment="Center" Margin="0,0,0,12"/>
|
||||
|
||||
<!-- Seçili Dosya Listesi -->
|
||||
<Border Background="#0E121B" BorderBrush="#252D42" BorderThickness="1" CornerRadius="10" Padding="8" MaxHeight="135" Margin="0,0,0,16">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel x:Name="SelectedFileItemsStack"/>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
|
||||
<TextBlock Text="Hedef İşlemi / Formatı Seçin:" FontSize="13" FontWeight="SemiBold" Foreground="#E5E7EB" HorizontalAlignment="Center" Margin="0,0,0,10"/>
|
||||
|
||||
<!-- Format Çipleri -->
|
||||
<WrapPanel x:Name="FormatChipsPanel" HorizontalAlignment="Center" Margin="0,0,0,6"/>
|
||||
<TextBlock x:Name="SelectedToolDescriptionLabel" Text="" FontSize="11.5" Foreground="#818CF8" HorizontalAlignment="Center" Margin="0,0,0,14"/>
|
||||
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,4,0,0">
|
||||
<Button x:Name="StartConvertButton"
|
||||
Content="Dönüştürmeyi Başlat"
|
||||
Style="{StaticResource ActionButton}"
|
||||
Click="OnStartConvertClick"/>
|
||||
<Button Content="+ Dosya Ekle"
|
||||
Style="{StaticResource SecondaryButton}"
|
||||
Margin="10,0,0,0"
|
||||
Click="OnAddMoreFilesClick"/>
|
||||
<Button Content="Temizle"
|
||||
Style="{StaticResource SecondaryButton}"
|
||||
Margin="8,0,0,0"
|
||||
Click="OnClearSelectionClick"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Dönüştürme İlerleme Barı -->
|
||||
<Grid x:Name="ProgressGrid" Grid.Row="1" Margin="0,16,0,0" Visibility="Collapsed">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<StackPanel Grid.Column="0" VerticalAlignment="Center">
|
||||
<TextBlock x:Name="CurrentTaskStatusLabel" Text="İşleniyor..." FontSize="12.5" Foreground="#E5E7EB" Margin="0,0,0,6"/>
|
||||
<ProgressBar x:Name="MainProgressBar" Height="6" Minimum="0" Maximum="100" Value="0" Foreground="#6366F1" Background="#1E2333" BorderThickness="0"/>
|
||||
</StackPanel>
|
||||
<Button x:Name="CancelConvertButton"
|
||||
Grid.Column="1"
|
||||
Content="İptal Et"
|
||||
Background="#7F1D1D"
|
||||
Foreground="#FCA5A5"
|
||||
BorderThickness="0"
|
||||
Padding="12,6"
|
||||
Margin="14,0,0,0"
|
||||
FontSize="12"
|
||||
VerticalAlignment="Bottom"
|
||||
Cursor="Hand"
|
||||
Click="OnCancelConvertClick">
|
||||
<Button.Resources>
|
||||
<Style TargetType="Border"><Setter Property="CornerRadius" Value="6"/></Style>
|
||||
</Button.Resources>
|
||||
</Button>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<!-- 2. KİTAPLIK / GEÇMİŞ SEKMESİ -->
|
||||
<Grid x:Name="HistoryView" Visibility="Collapsed">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<DockPanel Grid.Row="0" Margin="0,0,0,16">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Dönüşüm Geçmişi" FontSize="18" FontWeight="Bold" Foreground="#FFFFFF"/>
|
||||
<TextBlock Text="Tamamlanan işlemleriniz ve boyut tasarrufu özetleri" FontSize="11.5" Foreground="#9CA3AF"/>
|
||||
</StackPanel>
|
||||
<Button Content="Geçmişi Temizle"
|
||||
HorizontalAlignment="Right"
|
||||
VerticalAlignment="Center"
|
||||
Background="#262C3D"
|
||||
Foreground="#E5E7EB"
|
||||
BorderThickness="0"
|
||||
Padding="12,6"
|
||||
FontSize="12"
|
||||
Cursor="Hand"
|
||||
Click="OnClearHistoryClick">
|
||||
<Button.Resources>
|
||||
<Style TargetType="Border"><Setter Property="CornerRadius" Value="6"/></Style>
|
||||
</Button.Resources>
|
||||
</Button>
|
||||
</DockPanel>
|
||||
|
||||
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel x:Name="HistoryItemsList"/>
|
||||
</ScrollViewer>
|
||||
</Grid>
|
||||
|
||||
<!-- 3. HIZLI ARAÇLAR SEKMESİ -->
|
||||
<Grid x:Name="ToolsView" Visibility="Collapsed">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel MaxWidth="740" HorizontalAlignment="Center">
|
||||
<!-- QR Kod Oluşturucu & Okuyucu Kartı -->
|
||||
<Border Background="#141824" BorderBrush="#252D42" BorderThickness="1" CornerRadius="12" Padding="20" Margin="0,0,0,16">
|
||||
<StackPanel>
|
||||
<TextBlock Text="📱 QR Kod Oluşturucu & Okuyucu" FontSize="16" FontWeight="Bold" Margin="0,0,0,4"/>
|
||||
<TextBlock Text="Bağlantı veya metinden yüksek çözünürlüklü QR kod üretin ya da mevcut görsel/PDF içindeki QR kodu okuyun." FontSize="12" Foreground="#9CA3AF" Margin="0,0,0,14"/>
|
||||
<DockPanel Margin="0,0,0,10">
|
||||
<Button Content="QR Görseli Üret" Style="{StaticResource ActionButton}" DockPanel.Dock="Right" Margin="10,0,0,0" Click="OnToolGenerateQrClick"/>
|
||||
<TextBox x:Name="QrInputText" Text="https://" Background="#262C3D" Foreground="#FFFFFF" BorderBrush="#374151" Padding="10,8" FontSize="13" VerticalContentAlignment="Center" KeyDown="OnQrInputKeyDown"/>
|
||||
</DockPanel>
|
||||
|
||||
<Separator Background="#252D42" Margin="0,6,0,12"/>
|
||||
|
||||
<DockPanel>
|
||||
<Button Content="Görsel veya PDF'den QR Oku..." Style="{StaticResource SecondaryButton}" DockPanel.Dock="Left" Click="OnToolReadQrClick"/>
|
||||
<Button x:Name="CopyDecodedQrButton" Content="Metni Kopyala" Visibility="Collapsed" Style="{StaticResource ActionButton}" DockPanel.Dock="Right" Margin="8,0,0,0" Padding="12,8" Click="OnCopyDecodedQrClick"/>
|
||||
<TextBox x:Name="DecodedQrResultBox" Visibility="Collapsed" IsReadOnly="True" Background="#1C2233" Foreground="#A5B4FC" BorderBrush="#374151" Padding="10,7" Margin="10,0,0,0" FontSize="12.5" VerticalContentAlignment="Center"/>
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- PDF Birleştirici Kartı -->
|
||||
<Border Background="#141824" BorderBrush="#252D42" BorderThickness="1" CornerRadius="12" Padding="20" Margin="0,0,0,16">
|
||||
<StackPanel>
|
||||
<TextBlock Text="📑 PDF & Görsel Birleştirici" FontSize="16" FontWeight="Bold" Margin="0,0,0,4"/>
|
||||
<TextBlock Text="Birden fazla PDF belgesini veya görseli seçtiğiniz sırayla tek bir PDF dosyasında birleştirin." FontSize="12" Foreground="#9CA3AF" Margin="0,0,0,14"/>
|
||||
<Button Content="PDF / Görsel Dosyalarını Seç ve Birleştir..."
|
||||
Style="{StaticResource ActionButton}"
|
||||
HorizontalAlignment="Left"
|
||||
Click="OnToolMergePdfsClick"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Arşiv Paketleyici Kartı -->
|
||||
<Border Background="#141824" BorderBrush="#252D42" BorderThickness="1" CornerRadius="12" Padding="20">
|
||||
<StackPanel>
|
||||
<TextBlock Text="📦 Hızlı Arşivleyici (ZIP / TAR.GZ)" FontSize="16" FontWeight="Bold" Margin="0,0,0,4"/>
|
||||
<TextBlock Text="Birden çok dosyayı anında sıkıştırılmış arşiv paketine dönüştürün." FontSize="12" Foreground="#9CA3AF" Margin="0,0,0,14"/>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Button Content="Dosyaları Seç ve ZIP Yap..."
|
||||
Style="{StaticResource ActionButton}"
|
||||
Click="OnToolQuickZipClick"/>
|
||||
<Button Content="Dosyaları Seç ve TAR.GZ Yap..."
|
||||
Style="{StaticResource SecondaryButton}"
|
||||
Margin="10,0,0,0"
|
||||
Click="OnToolQuickTarGzClick"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<!-- Alt Durum Çubuğu -->
|
||||
<Border Grid.Row="2" Background="#0B0E15" BorderBrush="#1F2536" BorderThickness="0,1,0,0" Padding="20,0">
|
||||
<DockPanel VerticalAlignment="Center">
|
||||
<TextBlock x:Name="FooterStatusLabel" Text="LD Converter hazır. Sürükleyin ve dönüştürün." FontSize="11.5" Foreground="#9CA3AF" TextTrimming="CharacterEllipsis"/>
|
||||
<TextBlock Text="LD Converter v1.1.0" HorizontalAlignment="Right" FontSize="11" Foreground="#6B7280"/>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Window>
|
||||
794
src/Donustur.UI/MainWindow.xaml.cs
Normal file
794
src/Donustur.UI/MainWindow.xaml.cs
Normal file
|
|
@ -0,0 +1,794 @@
|
|||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Donustur.Core.Catalog;
|
||||
using Donustur.Core.Models;
|
||||
using Donustur.Core.Services;
|
||||
using Donustur.Core.Transactions;
|
||||
using Donustur.Core.Utils;
|
||||
using Donustur.Engine;
|
||||
using Donustur.Engine.Qr;
|
||||
using Donustur.UI.Services;
|
||||
using Donustur.UI.Windows;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace Donustur.UI;
|
||||
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
private readonly PreferencesStore _preferencesStore;
|
||||
private readonly HistoryStore _historyStore;
|
||||
private readonly ConversionDispatcher _dispatcher;
|
||||
private readonly Action? _onExitRequested;
|
||||
|
||||
private List<string> _selectedFiles = new();
|
||||
private ToolChoice? _selectedTool;
|
||||
private CancellationTokenSource? _activeCts;
|
||||
|
||||
public MainWindow(
|
||||
PreferencesStore preferencesStore,
|
||||
HistoryStore historyStore,
|
||||
ConversionDispatcher dispatcher,
|
||||
Action? onExitRequested = null)
|
||||
{
|
||||
InitializeComponent();
|
||||
_preferencesStore = preferencesStore;
|
||||
_historyStore = historyStore;
|
||||
_dispatcher = dispatcher;
|
||||
_onExitRequested = onExitRequested;
|
||||
|
||||
var appIcon = AppIconProvider.GetWindowIcon();
|
||||
Icon = appIcon;
|
||||
HeaderLogoImage.Source = appIcon;
|
||||
DwmBackdrop.ApplyFluentBackdrop(this, DwmBackdrop.BackdropType.MainWindow, darkMode: true);
|
||||
|
||||
UpdateWheelStatusDisplay();
|
||||
_preferencesStore.Changed += _ => Dispatcher.Invoke(UpdateWheelStatusDisplay);
|
||||
_historyStore.Changed += () => Dispatcher.Invoke(RenderHistory);
|
||||
|
||||
Loaded += (_, _) => RenderHistory();
|
||||
Closing += OnWindowClosing;
|
||||
}
|
||||
|
||||
private void UpdateWheelStatusDisplay()
|
||||
{
|
||||
bool enabled = _preferencesStore.Current.Enabled;
|
||||
string mod = _preferencesStore.Current.DragModifier;
|
||||
WheelStatusLed.Fill = enabled
|
||||
? new SolidColorBrush(Color.FromRgb(16, 185, 129))
|
||||
: new SolidColorBrush(Color.FromRgb(156, 163, 175));
|
||||
WheelStatusLabel.Text = enabled ? $"Çark: {mod} (Aktif)" : "Çark: Kapalı";
|
||||
}
|
||||
|
||||
private void OnToggleWheelClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var prefs = _preferencesStore.Current;
|
||||
prefs.Enabled = !prefs.Enabled;
|
||||
_preferencesStore.Save(prefs);
|
||||
}
|
||||
|
||||
private void OnOpenSettingsClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var win = new SettingsWindow(_preferencesStore) { Owner = this };
|
||||
win.ShowDialog();
|
||||
}
|
||||
|
||||
private void OnTabChanged(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (ConvertView == null || HistoryView == null || ToolsView == null) return;
|
||||
|
||||
ConvertView.Visibility = TabConvert.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
|
||||
HistoryView.Visibility = TabHistory.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
|
||||
ToolsView.Visibility = TabTools.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
|
||||
|
||||
if (TabHistory.IsChecked == true)
|
||||
{
|
||||
RenderHistory();
|
||||
}
|
||||
}
|
||||
|
||||
#region Drag & Drop & File Selection In Main Window
|
||||
|
||||
private void OnMainDragEnter(object sender, DragEventArgs e)
|
||||
{
|
||||
if (e.Data.GetDataPresent(DataFormats.FileDrop))
|
||||
{
|
||||
e.Effects = DragDropEffects.Copy;
|
||||
DropZoneBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(99, 102, 241));
|
||||
DropZoneBorder.Background = new SolidColorBrush(Color.FromArgb(25, 99, 102, 241));
|
||||
}
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
private void OnMainDragOver(object sender, DragEventArgs e)
|
||||
{
|
||||
e.Effects = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Copy : DragDropEffects.None;
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
private void OnMainDragLeave(object sender, DragEventArgs e)
|
||||
{
|
||||
DropZoneBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(55, 65, 81));
|
||||
DropZoneBorder.Background = new SolidColorBrush(Color.FromRgb(19, 23, 34));
|
||||
}
|
||||
|
||||
private void OnMainDrop(object sender, DragEventArgs e)
|
||||
{
|
||||
DropZoneBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(55, 65, 81));
|
||||
DropZoneBorder.Background = new SolidColorBrush(Color.FromRgb(19, 23, 34));
|
||||
|
||||
if (e.Data.GetDataPresent(DataFormats.FileDrop))
|
||||
{
|
||||
if (e.Data.GetData(DataFormats.FileDrop) is string[] files && files.Length > 0)
|
||||
{
|
||||
if (_selectedFiles.Count > 0)
|
||||
{
|
||||
AddFilesToSelection(files);
|
||||
}
|
||||
else
|
||||
{
|
||||
SetSelectedFiles(files);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSelectFilesClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dlg = new OpenFileDialog
|
||||
{
|
||||
Multiselect = true,
|
||||
Title = "Dönüştürülecek Dosyaları Seçin"
|
||||
};
|
||||
|
||||
if (dlg.ShowDialog() == true && dlg.FileNames.Length > 0)
|
||||
{
|
||||
SetSelectedFiles(dlg.FileNames);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSelectFolderClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dlg = new OpenFolderDialog
|
||||
{
|
||||
Multiselect = true,
|
||||
Title = "Arşivlenecek veya İşlenecek Klasörü Seçin"
|
||||
};
|
||||
|
||||
if (dlg.ShowDialog() == true && dlg.FolderNames.Length > 0)
|
||||
{
|
||||
SetSelectedFiles(dlg.FolderNames);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnAddMoreFilesClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dlg = new OpenFileDialog
|
||||
{
|
||||
Multiselect = true,
|
||||
Title = "Listeye Eklenecek Dosyaları Seçin"
|
||||
};
|
||||
|
||||
if (dlg.ShowDialog() == true && dlg.FileNames.Length > 0)
|
||||
{
|
||||
AddFilesToSelection(dlg.FileNames);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddFilesToSelection(IEnumerable<string> newFiles)
|
||||
{
|
||||
var merged = _selectedFiles
|
||||
.Concat(newFiles)
|
||||
.Where(p => File.Exists(p) || Directory.Exists(p))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
|
||||
SetSelectedFiles(merged);
|
||||
}
|
||||
|
||||
public void SetSelectedFiles(IReadOnlyList<string> files)
|
||||
{
|
||||
_selectedFiles = files
|
||||
.Where(p => File.Exists(p) || Directory.Exists(p))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
|
||||
if (_selectedFiles.Count == 0)
|
||||
{
|
||||
OnClearSelectionClick(this, new RoutedEventArgs());
|
||||
return;
|
||||
}
|
||||
|
||||
if (TabConvert.IsChecked != true)
|
||||
{
|
||||
TabConvert.IsChecked = true;
|
||||
}
|
||||
|
||||
EmptyPrompt.Visibility = Visibility.Collapsed;
|
||||
SelectedFilesPanel.Visibility = Visibility.Visible;
|
||||
|
||||
long totalBytes = FileUtils.CalculateTotalBytes(_selectedFiles);
|
||||
FilesCountLabel.Text = _selectedFiles.Count == 1
|
||||
? Path.GetFileName(_selectedFiles[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
|
||||
: $"{_selectedFiles.Count} öğe seçildi";
|
||||
|
||||
FilesSubLabel.Text = $"Toplam Boyut: {FileUtils.FormatBytes(totalBytes)}";
|
||||
|
||||
RenderSelectedFileItems();
|
||||
RebuildFormatChips();
|
||||
}
|
||||
|
||||
private void RenderSelectedFileItems()
|
||||
{
|
||||
SelectedFileItemsStack.Children.Clear();
|
||||
foreach (var filePath in _selectedFiles)
|
||||
{
|
||||
var row = new Border
|
||||
{
|
||||
Background = new SolidColorBrush(Color.FromRgb(22, 27, 40)),
|
||||
CornerRadius = new CornerRadius(6),
|
||||
Padding = new Thickness(10, 5, 10, 5),
|
||||
Margin = new Thickness(0, 0, 0, 4)
|
||||
};
|
||||
|
||||
var dock = new DockPanel();
|
||||
|
||||
var removeBtn = new Button
|
||||
{
|
||||
Content = "✕",
|
||||
Background = Brushes.Transparent,
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(156, 163, 175)),
|
||||
BorderThickness = new Thickness(0),
|
||||
FontSize = 11,
|
||||
Padding = new Thickness(6, 0, 2, 0),
|
||||
Cursor = Cursors.Hand,
|
||||
ToolTip = "Bu öğeyi listeden çıkar"
|
||||
};
|
||||
string capturedPath = filePath;
|
||||
removeBtn.Click += (_, _) =>
|
||||
{
|
||||
_selectedFiles.RemoveAll(p => string.Equals(p, capturedPath, StringComparison.OrdinalIgnoreCase));
|
||||
SetSelectedFiles(_selectedFiles);
|
||||
};
|
||||
DockPanel.SetDock(removeBtn, Dock.Right);
|
||||
dock.Children.Add(removeBtn);
|
||||
|
||||
long itemSize = FileUtils.CalculateTotalBytes(new[] { filePath });
|
||||
var sizeText = new TextBlock
|
||||
{
|
||||
Text = FileUtils.FormatBytes(itemSize),
|
||||
FontSize = 11,
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(107, 114, 128)),
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Margin = new Thickness(10, 0, 8, 0)
|
||||
};
|
||||
DockPanel.SetDock(sizeText, Dock.Right);
|
||||
dock.Children.Add(sizeText);
|
||||
|
||||
bool isDir = Directory.Exists(filePath);
|
||||
string displayName = Path.GetFileName(filePath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
|
||||
var nameText = new TextBlock
|
||||
{
|
||||
Text = (isDir ? "📁 " : "📄 ") + displayName,
|
||||
FontSize = 12,
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(229, 231, 235)),
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis,
|
||||
ToolTip = filePath
|
||||
};
|
||||
dock.Children.Add(nameText);
|
||||
|
||||
row.Child = dock;
|
||||
SelectedFileItemsStack.Children.Add(row);
|
||||
}
|
||||
}
|
||||
|
||||
private void RebuildFormatChips()
|
||||
{
|
||||
string? previousToolId = _selectedTool?.Id;
|
||||
FormatChipsPanel.Children.Clear();
|
||||
var choices = FormatCatalog.GetChoicesForFiles(_selectedFiles);
|
||||
|
||||
RadioButton? targetRadio = null;
|
||||
foreach (var choice in choices)
|
||||
{
|
||||
var radio = new RadioButton
|
||||
{
|
||||
Content = choice.DisplayName,
|
||||
Tag = choice,
|
||||
ToolTip = choice.Description,
|
||||
Style = (Style)FindResource("ChipButton")
|
||||
};
|
||||
|
||||
radio.Checked += (s, _) =>
|
||||
{
|
||||
if (s is RadioButton rb && rb.Tag is ToolChoice tc)
|
||||
{
|
||||
_selectedTool = tc;
|
||||
SelectedToolDescriptionLabel.Text = tc.Description;
|
||||
}
|
||||
};
|
||||
|
||||
FormatChipsPanel.Children.Add(radio);
|
||||
if (targetRadio == null || string.Equals(choice.Id, previousToolId, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
targetRadio = radio;
|
||||
}
|
||||
}
|
||||
|
||||
if (targetRadio != null)
|
||||
{
|
||||
targetRadio.IsChecked = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnClearSelectionClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
_selectedFiles.Clear();
|
||||
_selectedTool = null;
|
||||
SelectedFileItemsStack.Children.Clear();
|
||||
SelectedFilesPanel.Visibility = Visibility.Collapsed;
|
||||
EmptyPrompt.Visibility = Visibility.Visible;
|
||||
}
|
||||
|
||||
private void OnCancelConvertClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
_activeCts?.Cancel();
|
||||
}
|
||||
|
||||
private async void OnStartConvertClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (_selectedFiles.Count == 0 || _selectedTool == null) return;
|
||||
|
||||
_activeCts?.Dispose();
|
||||
_activeCts = new CancellationTokenSource();
|
||||
|
||||
StartConvertButton.IsEnabled = false;
|
||||
ProgressGrid.Visibility = Visibility.Visible;
|
||||
MainProgressBar.Value = 0;
|
||||
CurrentTaskStatusLabel.Text = $"{_selectedTool.DisplayName} işleniyor...";
|
||||
|
||||
var progress = new Progress<double>(val =>
|
||||
{
|
||||
Dispatcher.Invoke(() =>
|
||||
{
|
||||
MainProgressBar.Value = val;
|
||||
CurrentTaskStatusLabel.Text = $"{_selectedTool.DisplayName} işleniyor (%{val:F0})...";
|
||||
});
|
||||
});
|
||||
|
||||
var task = new ConversionTask
|
||||
{
|
||||
InputFiles = _selectedFiles.ToList(),
|
||||
TargetActionId = _selectedTool.Id,
|
||||
TargetDisplayName = _selectedTool.DisplayName,
|
||||
Options = new ConversionOptions
|
||||
{
|
||||
ImageQuality = _preferencesStore.Current.DefaultImageQuality
|
||||
}
|
||||
};
|
||||
|
||||
var result = await _dispatcher.ExecuteTaskAsync(task, _preferencesStore.Current, progress, _activeCts.Token);
|
||||
|
||||
ProgressGrid.Visibility = Visibility.Collapsed;
|
||||
StartConvertButton.IsEnabled = true;
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
if (task.TargetActionId == "qr_read" && !string.IsNullOrWhiteSpace(task.CurrentStatusMessage))
|
||||
{
|
||||
try { Clipboard.SetText(task.CurrentStatusMessage); } catch { }
|
||||
FooterStatusLabel.Text = $"✓ QR Okundu (Panoya kopyalandı): {task.CurrentStatusMessage}";
|
||||
MessageBox.Show(
|
||||
$"Okunan QR Kod İçeriği (Panoya kopyalandı):\n\n{task.CurrentStatusMessage}",
|
||||
"QR Kod Sonucu",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Information);
|
||||
}
|
||||
else
|
||||
{
|
||||
FooterStatusLabel.Text = $"✓ {_selectedTool.DisplayName} işlemi tamamlandı ({result.OutputFiles.Count} öğe hazırlandı).";
|
||||
}
|
||||
|
||||
if (_preferencesStore.Current.SoundEffectsEnabled)
|
||||
{
|
||||
SoundFeedback.PlaySuccess();
|
||||
}
|
||||
|
||||
if (_preferencesStore.Current.AutoOpenOutputFolder && result.OutputFiles.Count > 0)
|
||||
{
|
||||
DesktopGeometry.RevealInExplorer(result.OutputFiles[0]);
|
||||
}
|
||||
|
||||
OnClearSelectionClick(sender, e);
|
||||
}
|
||||
else if (task.Status == ConversionTaskStatus.Cancelled)
|
||||
{
|
||||
FooterStatusLabel.Text = "ℹ İşlem iptal edildi.";
|
||||
}
|
||||
else
|
||||
{
|
||||
FooterStatusLabel.Text = $"✕ Hata: {result.ErrorMessage}";
|
||||
MessageBox.Show(result.ErrorMessage ?? "Dönüştürme başarısız oldu.", "LD Converter Hatası", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Kitaplık / Geçmiş
|
||||
|
||||
private void RenderHistory()
|
||||
{
|
||||
HistoryItemsList.Children.Clear();
|
||||
var entries = _historyStore.Entries;
|
||||
|
||||
if (entries.Count == 0)
|
||||
{
|
||||
var emptyText = new TextBlock
|
||||
{
|
||||
Text = "Henüz dönüştürülmüş dosya yok. İlk dosyanızı sürükleyip dönüştürün!",
|
||||
FontSize = 13,
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(156, 163, 175)),
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
Margin = new Thickness(0, 40, 0, 0)
|
||||
};
|
||||
HistoryItemsList.Children.Add(emptyText);
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
var card = CreateHistoryCard(entry);
|
||||
HistoryItemsList.Children.Add(card);
|
||||
}
|
||||
}
|
||||
|
||||
private Border CreateHistoryCard(HistoryEntry entry)
|
||||
{
|
||||
var border = new Border
|
||||
{
|
||||
Background = new SolidColorBrush(Color.FromRgb(20, 24, 36)),
|
||||
BorderBrush = new SolidColorBrush(Color.FromRgb(37, 45, 66)),
|
||||
BorderThickness = new Thickness(1),
|
||||
CornerRadius = new CornerRadius(10),
|
||||
Padding = new Thickness(16, 12, 16, 12),
|
||||
Margin = new Thickness(0, 0, 0, 10)
|
||||
};
|
||||
|
||||
var grid = new Grid();
|
||||
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
|
||||
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
|
||||
|
||||
var infoStack = new StackPanel();
|
||||
var titleRow = new StackPanel { Orientation = Orientation.Horizontal };
|
||||
|
||||
var badge = new Border
|
||||
{
|
||||
Background = entry.Success
|
||||
? new SolidColorBrush(Color.FromRgb(99, 102, 241))
|
||||
: new SolidColorBrush(Color.FromRgb(239, 68, 68)),
|
||||
CornerRadius = new CornerRadius(4),
|
||||
Padding = new Thickness(6, 2, 6, 2),
|
||||
Margin = new Thickness(0, 0, 8, 0),
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
badge.Child = new TextBlock
|
||||
{
|
||||
Text = entry.FormatSummary,
|
||||
FontSize = 10,
|
||||
FontWeight = FontWeights.Bold,
|
||||
Foreground = Brushes.White
|
||||
};
|
||||
titleRow.Children.Add(badge);
|
||||
|
||||
titleRow.Children.Add(new TextBlock
|
||||
{
|
||||
Text = entry.Title,
|
||||
FontSize = 13.5,
|
||||
FontWeight = FontWeights.SemiBold,
|
||||
Foreground = Brushes.White,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
});
|
||||
infoStack.Children.Add(titleRow);
|
||||
|
||||
string timeText = $"{entry.Timestamp:dd.MM.yyyy HH:mm}";
|
||||
string detailLine;
|
||||
if (!entry.Success && !string.IsNullOrWhiteSpace(entry.ErrorMessage))
|
||||
{
|
||||
detailLine = $"{timeText} · Hata: {entry.ErrorMessage}";
|
||||
}
|
||||
else if (entry.OriginalSizeBytes > 0 && entry.OutputSizeBytes > 0)
|
||||
{
|
||||
detailLine = $"{timeText} · {FileUtils.FormatBytes(entry.OriginalSizeBytes)} → {FileUtils.FormatBytes(entry.OutputSizeBytes)} ({FileUtils.FormatPercentChange(entry.OriginalSizeBytes, entry.OutputSizeBytes)})";
|
||||
}
|
||||
else
|
||||
{
|
||||
detailLine = timeText;
|
||||
}
|
||||
|
||||
infoStack.Children.Add(new TextBlock
|
||||
{
|
||||
Text = detailLine,
|
||||
FontSize = 11,
|
||||
Foreground = entry.Success
|
||||
? new SolidColorBrush(Color.FromRgb(156, 163, 175))
|
||||
: new SolidColorBrush(Color.FromRgb(248, 113, 113)),
|
||||
Margin = new Thickness(0, 4, 0, 0),
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
});
|
||||
|
||||
grid.Children.Add(infoStack);
|
||||
Grid.SetColumn(infoStack, 0);
|
||||
|
||||
var btnStack = new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Margin = new Thickness(12, 0, 0, 0)
|
||||
};
|
||||
|
||||
string? firstOut = entry.OutputFiles.FirstOrDefault();
|
||||
if (!string.IsNullOrWhiteSpace(firstOut) && (File.Exists(firstOut) || Directory.Exists(firstOut)))
|
||||
{
|
||||
var openFolderBtn = new Button
|
||||
{
|
||||
Content = "Klasörde Göster",
|
||||
Background = new SolidColorBrush(Color.FromRgb(38, 44, 61)),
|
||||
Foreground = Brushes.White,
|
||||
Padding = new Thickness(10, 6, 10, 6),
|
||||
Margin = new Thickness(0, 0, 6, 0),
|
||||
FontSize = 11.5,
|
||||
Cursor = Cursors.Hand,
|
||||
BorderThickness = new Thickness(0)
|
||||
};
|
||||
string targetPath = firstOut;
|
||||
openFolderBtn.Click += (_, _) => DesktopGeometry.RevealInExplorer(targetPath);
|
||||
btnStack.Children.Add(openFolderBtn);
|
||||
}
|
||||
|
||||
var deleteItemBtn = new Button
|
||||
{
|
||||
Content = "✕",
|
||||
ToolTip = "Kaydı Sil",
|
||||
Background = Brushes.Transparent,
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(156, 163, 175)),
|
||||
Padding = new Thickness(8, 5, 8, 5),
|
||||
FontSize = 11.5,
|
||||
Cursor = Cursors.Hand,
|
||||
BorderThickness = new Thickness(0)
|
||||
};
|
||||
string entryId = entry.Id;
|
||||
deleteItemBtn.Click += (_, _) => _historyStore.Remove(entryId);
|
||||
btnStack.Children.Add(deleteItemBtn);
|
||||
|
||||
grid.Children.Add(btnStack);
|
||||
Grid.SetColumn(btnStack, 1);
|
||||
|
||||
border.Child = grid;
|
||||
return border;
|
||||
}
|
||||
|
||||
private void OnClearHistoryClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
_historyStore.Clear();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Hızlı Araçlar
|
||||
|
||||
private void OnQrInputKeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.Key == Key.Enter)
|
||||
{
|
||||
OnToolGenerateQrClick(sender, new RoutedEventArgs());
|
||||
}
|
||||
}
|
||||
|
||||
private void OnToolGenerateQrClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
string text = QrInputText.Text?.Trim() ?? "";
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
MessageBox.Show("Lütfen QR koda dönüştürülecek bir metin veya bağlantı girin.", "QR Kod Üretici", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var tx = new ExportTransaction();
|
||||
var qrEngine = new QrEngine();
|
||||
qrEngine.GenerateQrCode(text, tx, 600);
|
||||
|
||||
var dummyTask = new ConversionTask { TargetActionId = "qr_generate" };
|
||||
string targetDir = ConversionDispatcher.ResolveDestinationFolder(dummyTask, _preferencesStore.Current);
|
||||
var committed = tx.CommitTo(targetDir);
|
||||
|
||||
if (committed.Count > 0)
|
||||
{
|
||||
long outSize = FileUtils.CalculateTotalBytes(committed);
|
||||
_historyStore.Add(new HistoryEntry
|
||||
{
|
||||
Title = text.Length > 36 ? text[..36] + "..." : text,
|
||||
FormatSummary = "METİN → QR PNG",
|
||||
OutputFiles = committed,
|
||||
OutputSizeBytes = outSize,
|
||||
Timestamp = DateTime.Now,
|
||||
Success = true
|
||||
});
|
||||
|
||||
if (_preferencesStore.Current.SoundEffectsEnabled)
|
||||
{
|
||||
SoundFeedback.PlaySuccess();
|
||||
}
|
||||
|
||||
FooterStatusLabel.Text = $"✓ QR Kod oluşturuldu: {Path.GetFileName(committed[0])}";
|
||||
DesktopGeometry.RevealInExplorer(committed[0]);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
FooterStatusLabel.Text = $"✕ QR oluşturma hatası: {ex.Message}";
|
||||
MessageBox.Show(ex.Message, "QR Kod Hatası", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnToolReadQrClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dlg = new OpenFileDialog
|
||||
{
|
||||
Filter = "Görsel ve PDF Dosyaları|*.png;*.jpg;*.jpeg;*.webp;*.bmp;*.gif;*.tiff;*.pdf|Tüm Dosyalar (*.*)|*.*",
|
||||
Title = "QR Kodu Okunacak Görsel veya PDF Dosyasını Seçin"
|
||||
};
|
||||
|
||||
if (dlg.ShowDialog() != true || string.IsNullOrWhiteSpace(dlg.FileName))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
var qrEngine = new QrEngine();
|
||||
string? decoded = qrEngine.ReadQrCode(dlg.FileName);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(decoded))
|
||||
{
|
||||
DecodedQrResultBox.Text = decoded;
|
||||
DecodedQrResultBox.Visibility = Visibility.Visible;
|
||||
CopyDecodedQrButton.Visibility = Visibility.Visible;
|
||||
CopyDecodedQrButton.Content = "Metni Kopyala";
|
||||
|
||||
try { Clipboard.SetText(decoded); } catch { }
|
||||
if (_preferencesStore.Current.SoundEffectsEnabled)
|
||||
{
|
||||
SoundFeedback.PlaySuccess();
|
||||
}
|
||||
FooterStatusLabel.Text = $"✓ QR Kod okundu ve panoya kopyalandı: {decoded}";
|
||||
}
|
||||
else
|
||||
{
|
||||
FooterStatusLabel.Text = "✕ Seçilen dosyada okunabilir bir QR kod bulunamadı.";
|
||||
MessageBox.Show("Seçilen dosyada okunabilir bir QR kod veya barkod bulunamadı.", "QR Okuyucu", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
FooterStatusLabel.Text = $"✕ QR okuma hatası: {ex.Message}";
|
||||
MessageBox.Show(ex.Message, "QR Okuma Hatası", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnCopyDecodedQrClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(DecodedQrResultBox.Text))
|
||||
{
|
||||
try
|
||||
{
|
||||
Clipboard.SetText(DecodedQrResultBox.Text);
|
||||
CopyDecodedQrButton.Content = "✓ Kopyalandı";
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Pano meşgul
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnToolMergePdfsClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dlg = new OpenFileDialog
|
||||
{
|
||||
Filter = "PDF ve Görsel Dosyaları|*.pdf;*.png;*.jpg;*.jpeg;*.webp;*.bmp;*.tiff|PDF Belgeleri (*.pdf)|*.pdf",
|
||||
Multiselect = true,
|
||||
Title = "Birleştirilecek PDF veya Görsel Dosyalarını Seçin"
|
||||
};
|
||||
|
||||
if (dlg.ShowDialog() == true && dlg.FileNames.Length > 0)
|
||||
{
|
||||
await RunQuickToolTaskAsync(dlg.FileNames, "pdf_merge", "PDF Birleştirme");
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnToolQuickZipClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dlg = new OpenFileDialog
|
||||
{
|
||||
Multiselect = true,
|
||||
Title = "ZIP Formatında Sıkıştırılacak Dosyaları Seçin"
|
||||
};
|
||||
|
||||
if (dlg.ShowDialog() == true && dlg.FileNames.Length > 0)
|
||||
{
|
||||
await RunQuickToolTaskAsync(dlg.FileNames, "zip", "Hızlı ZIP");
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnToolQuickTarGzClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dlg = new OpenFileDialog
|
||||
{
|
||||
Multiselect = true,
|
||||
Title = "TAR.GZ Formatında Sıkıştırılacak Dosyaları Seçin"
|
||||
};
|
||||
|
||||
if (dlg.ShowDialog() == true && dlg.FileNames.Length > 0)
|
||||
{
|
||||
await RunQuickToolTaskAsync(dlg.FileNames, "tar_gz", "Hızlı TAR.GZ");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunQuickToolTaskAsync(IReadOnlyList<string> files, string actionId, string displayName)
|
||||
{
|
||||
FooterStatusLabel.Text = $"{displayName} işlemi yürütülüyor...";
|
||||
var task = new ConversionTask
|
||||
{
|
||||
InputFiles = files,
|
||||
TargetActionId = actionId,
|
||||
TargetDisplayName = displayName,
|
||||
Options = new ConversionOptions
|
||||
{
|
||||
ImageQuality = _preferencesStore.Current.DefaultImageQuality
|
||||
}
|
||||
};
|
||||
|
||||
var result = await _dispatcher.ExecuteTaskAsync(task, _preferencesStore.Current);
|
||||
if (result.Success && result.OutputFiles.Count > 0)
|
||||
{
|
||||
if (_preferencesStore.Current.SoundEffectsEnabled)
|
||||
{
|
||||
SoundFeedback.PlaySuccess();
|
||||
}
|
||||
FooterStatusLabel.Text = $"✓ {displayName} tamamlandı: {Path.GetFileName(result.OutputFiles[0])}";
|
||||
DesktopGeometry.RevealInExplorer(result.OutputFiles[0]);
|
||||
}
|
||||
else
|
||||
{
|
||||
FooterStatusLabel.Text = $"✕ {displayName} hatası: {result.ErrorMessage}";
|
||||
MessageBox.Show(result.ErrorMessage ?? "İşlem başarısız oldu.", "Hızlı Araç Hatası", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private void OnWindowClosing(object? sender, System.ComponentModel.CancelEventArgs e)
|
||||
{
|
||||
if (_preferencesStore.Current.MinimizeToTray)
|
||||
{
|
||||
e.Cancel = true;
|
||||
Hide();
|
||||
return;
|
||||
}
|
||||
|
||||
_activeCts?.Cancel();
|
||||
if (_onExitRequested != null)
|
||||
{
|
||||
_onExitRequested.Invoke();
|
||||
}
|
||||
else
|
||||
{
|
||||
Application.Current?.Shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
127
src/Donustur.UI/Services/AppIconProvider.cs
Normal file
127
src/Donustur.UI/Services/AppIconProvider.cs
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
using System.Drawing;
|
||||
using System.Drawing.Drawing2D;
|
||||
using System.Drawing.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
|
||||
namespace Donustur.UI.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Sistem tepsisi (Tray), görev çubuğu ve tüm uygulama pencereleri için
|
||||
/// yüksek çözünürlüklü "LD Converter" simgesini üretir.
|
||||
/// </summary>
|
||||
public static class AppIconProvider
|
||||
{
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
private static extern bool DestroyIcon(IntPtr hIcon);
|
||||
|
||||
private static Icon? _cachedTrayIcon;
|
||||
private static ImageSource? _cachedWindowIcon;
|
||||
|
||||
public static Icon GetTrayIcon()
|
||||
{
|
||||
if (_cachedTrayIcon != null) return _cachedTrayIcon;
|
||||
|
||||
using var bmp = RenderLogoBitmap(64);
|
||||
IntPtr hIcon = bmp.GetHicon();
|
||||
_cachedTrayIcon = (Icon)Icon.FromHandle(hIcon).Clone();
|
||||
DestroyIcon(hIcon);
|
||||
return _cachedTrayIcon;
|
||||
}
|
||||
|
||||
public static ImageSource GetWindowIcon()
|
||||
{
|
||||
if (_cachedWindowIcon != null) return _cachedWindowIcon;
|
||||
|
||||
using var bmp = RenderLogoBitmap(128);
|
||||
IntPtr hIcon = bmp.GetHicon();
|
||||
try
|
||||
{
|
||||
var source = Imaging.CreateBitmapSourceFromHIcon(
|
||||
hIcon,
|
||||
Int32Rect.Empty,
|
||||
BitmapSizeOptions.FromEmptyOptions());
|
||||
source.Freeze();
|
||||
_cachedWindowIcon = source;
|
||||
return source;
|
||||
}
|
||||
finally
|
||||
{
|
||||
DestroyIcon(hIcon);
|
||||
}
|
||||
}
|
||||
|
||||
private static Bitmap RenderLogoBitmap(int size)
|
||||
{
|
||||
var bmp = new Bitmap(size, size);
|
||||
using var g = Graphics.FromImage(bmp);
|
||||
g.SmoothingMode = SmoothingMode.AntiAlias;
|
||||
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
|
||||
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
|
||||
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
|
||||
g.Clear(System.Drawing.Color.Transparent);
|
||||
|
||||
float pad = size * 0.04f;
|
||||
var rect = new RectangleF(pad, pad, size - (pad * 2), size - (pad * 2));
|
||||
using var path = CreateRoundedRect(rect, size * 0.24f);
|
||||
using var bgBrush = new System.Drawing.Drawing2D.LinearGradientBrush(
|
||||
rect,
|
||||
System.Drawing.Color.FromArgb(255, 79, 70, 229), // Deep Indigo
|
||||
System.Drawing.Color.FromArgb(255, 6, 182, 212), // Vibrant Cyan
|
||||
45f);
|
||||
g.FillPath(bgBrush, path);
|
||||
|
||||
// İç parlaklık çerçevesi
|
||||
using var borderPen = new System.Drawing.Pen(
|
||||
System.Drawing.Color.FromArgb(95, 255, 255, 255),
|
||||
Math.Max(1.0f, size * 0.02f));
|
||||
g.DrawPath(borderPen, path);
|
||||
|
||||
// Dış dönüşüm yayları
|
||||
float ringPad = size * 0.16f;
|
||||
var ringRect = new RectangleF(ringPad, ringPad, size - (ringPad * 2), size - (ringPad * 2));
|
||||
using var ringPen = new System.Drawing.Pen(
|
||||
System.Drawing.Color.FromArgb(235, 255, 255, 255),
|
||||
Math.Max(1.5f, size * 0.055f))
|
||||
{
|
||||
StartCap = LineCap.Round,
|
||||
EndCap = LineCap.ArrowAnchor
|
||||
};
|
||||
|
||||
g.DrawArc(ringPen, ringRect, 195, 140);
|
||||
g.DrawArc(ringPen, ringRect, 15, 140);
|
||||
|
||||
// Merkez "LD" monogramı
|
||||
float fontSize = size * 0.30f;
|
||||
using var font = new Font("Segoe UI", fontSize, System.Drawing.FontStyle.Bold, GraphicsUnit.Pixel);
|
||||
using var sf = new StringFormat
|
||||
{
|
||||
Alignment = StringAlignment.Center,
|
||||
LineAlignment = StringAlignment.Center
|
||||
};
|
||||
var textRect = new RectangleF(0, size * 0.01f, size, size);
|
||||
g.DrawString("LD", font, System.Drawing.Brushes.White, textRect, sf);
|
||||
|
||||
return bmp;
|
||||
}
|
||||
|
||||
private static GraphicsPath CreateRoundedRect(RectangleF bounds, float radius)
|
||||
{
|
||||
float diameter = radius * 2;
|
||||
var arc = new RectangleF(bounds.Location, new SizeF(diameter, diameter));
|
||||
var path = new GraphicsPath();
|
||||
|
||||
path.AddArc(arc, 180, 90);
|
||||
arc.X = bounds.Right - diameter;
|
||||
path.AddArc(arc, 270, 90);
|
||||
arc.Y = bounds.Bottom - diameter;
|
||||
path.AddArc(arc, 0, 90);
|
||||
arc.X = bounds.Left;
|
||||
path.AddArc(arc, 90, 90);
|
||||
path.CloseFigure();
|
||||
return path;
|
||||
}
|
||||
}
|
||||
113
src/Donustur.UI/Services/DesktopGeometry.cs
Normal file
113
src/Donustur.UI/Services/DesktopGeometry.cs
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace Donustur.UI.Services;
|
||||
|
||||
public static class DesktopGeometry
|
||||
{
|
||||
private const uint MONITOR_DEFAULTTONEAREST = 2;
|
||||
private const int MDT_EFFECTIVE_DPI = 0;
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr MonitorFromPoint(POINT pt, uint dwFlags);
|
||||
|
||||
[DllImport("shcore.dll")]
|
||||
private static extern int GetDpiForMonitor(IntPtr hmonitor, int dpiType, out uint dpiX, out uint dpiY);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct POINT { public int X; public int Y; }
|
||||
|
||||
public static double GetDpiScaleAtPoint(int screenX, int screenY)
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr hMonitor = MonitorFromPoint(new POINT { X = screenX, Y = screenY }, MONITOR_DEFAULTTONEAREST);
|
||||
if (hMonitor != IntPtr.Zero && GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, out uint dpiX, out _) == 0 && dpiX > 0)
|
||||
{
|
||||
return dpiX / 96.0;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Eski sistemlerde varsayılan ölçeğe dön
|
||||
}
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ekran piksel koordinatını (Physical Pixels) pencerenin DPI ölçeğine uygun
|
||||
/// WPF Device Independent Pixel (DIP) koordinatına çevirir.
|
||||
/// </summary>
|
||||
public static Point ScreenPixelsToDip(Visual visual, int screenX, int screenY)
|
||||
{
|
||||
var source = PresentationSource.FromVisual(visual);
|
||||
if (source?.CompositionTarget != null)
|
||||
{
|
||||
var matrix = source.CompositionTarget.TransformFromDevice;
|
||||
return matrix.Transform(new Point(screenX, screenY));
|
||||
}
|
||||
|
||||
double scale = GetDpiScaleAtPoint(screenX, screenY);
|
||||
return new Point(screenX / scale, screenY / scale);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Çarkı farenin koordinatına ortalar ve çoklu monitör sınırlarının dışına taşmasını önler.
|
||||
/// </summary>
|
||||
public static void PlaceCentered(Window window, int screenPixelX, int screenPixelY)
|
||||
{
|
||||
double dpiScale = GetDpiScaleAtPoint(screenPixelX, screenPixelY);
|
||||
var source = PresentationSource.FromVisual(window);
|
||||
if (source?.CompositionTarget != null && source.CompositionTarget.TransformToDevice.M11 > 0)
|
||||
{
|
||||
dpiScale = source.CompositionTarget.TransformToDevice.M11;
|
||||
}
|
||||
|
||||
double dipX = screenPixelX / (dpiScale > 0 ? dpiScale : 1.0);
|
||||
double dipY = screenPixelY / (dpiScale > 0 ? dpiScale : 1.0);
|
||||
|
||||
double targetLeft = dipX - (window.Width / 2.0);
|
||||
double targetTop = dipY - (window.Height / 2.0);
|
||||
|
||||
// Çoklu monitör sanal ekran sınırlarını kontrol et (negatif koordinatları destekler)
|
||||
double minLeft = SystemParameters.VirtualScreenLeft;
|
||||
double minTop = SystemParameters.VirtualScreenTop;
|
||||
double maxRight = minLeft + SystemParameters.VirtualScreenWidth;
|
||||
double maxBottom = minTop + SystemParameters.VirtualScreenHeight;
|
||||
|
||||
if (targetLeft < minLeft) targetLeft = minLeft;
|
||||
if (targetTop < minTop) targetTop = minTop;
|
||||
if (targetLeft + window.Width > maxRight) targetLeft = maxRight - window.Width;
|
||||
if (targetTop + window.Height > maxBottom) targetTop = maxBottom - window.Height;
|
||||
|
||||
window.Left = targetLeft;
|
||||
window.Top = targetTop;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dosya veya klasörü Windows Gezgini'nde güvenli şekilde seçerek açar.
|
||||
/// </summary>
|
||||
public static void RevealInExplorer(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)) return;
|
||||
try
|
||||
{
|
||||
if (File.Exists(path) || Directory.Exists(path))
|
||||
{
|
||||
Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = "explorer.exe",
|
||||
Arguments = $"/select,\"{path}\"",
|
||||
UseShellExecute = true
|
||||
});
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Gezgin başlatılamazsa sessizce geç
|
||||
}
|
||||
}
|
||||
}
|
||||
59
src/Donustur.UI/Services/DwmBackdrop.cs
Normal file
59
src/Donustur.UI/Services/DwmBackdrop.cs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
using System.Windows.Interop;
|
||||
|
||||
namespace Donustur.UI.Services;
|
||||
|
||||
public static class DwmBackdrop
|
||||
{
|
||||
private const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
|
||||
private const int DWMWA_WINDOW_CORNER_PREFERENCE = 33;
|
||||
private const int DWMWA_SYSTEMBACKDROP_TYPE = 38;
|
||||
|
||||
public enum BackdropType
|
||||
{
|
||||
Auto = 0,
|
||||
None = 1,
|
||||
MainWindow = 2, // Mica
|
||||
TransientWindow = 3, // Acrylic
|
||||
TabbedWindow = 4 // Mica Alt
|
||||
}
|
||||
|
||||
[DllImport("dwmapi.dll")]
|
||||
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
|
||||
|
||||
public static void ApplyFluentBackdrop(Window window, BackdropType backdrop = BackdropType.TransientWindow, bool darkMode = true)
|
||||
{
|
||||
IntPtr hwnd = new WindowInteropHelper(window).Handle;
|
||||
if (hwnd == IntPtr.Zero)
|
||||
{
|
||||
window.SourceInitialized += (_, _) =>
|
||||
{
|
||||
IntPtr h = new WindowInteropHelper(window).Handle;
|
||||
ApplyInternal(h, backdrop, darkMode);
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
ApplyInternal(hwnd, backdrop, darkMode);
|
||||
}
|
||||
|
||||
private static void ApplyInternal(IntPtr hwnd, BackdropType backdrop, bool darkMode)
|
||||
{
|
||||
try
|
||||
{
|
||||
int dark = darkMode ? 1 : 0;
|
||||
DwmSetWindowAttribute(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE, ref dark, sizeof(int));
|
||||
|
||||
int corner = 2; // DWMWCP_ROUND
|
||||
DwmSetWindowAttribute(hwnd, DWMWA_WINDOW_CORNER_PREFERENCE, ref corner, sizeof(int));
|
||||
|
||||
int backdropValue = (int)backdrop;
|
||||
DwmSetWindowAttribute(hwnd, DWMWA_SYSTEMBACKDROP_TYPE, ref backdropValue, sizeof(int));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Windows 10 veya eski sürümlerde sessizce devam et
|
||||
}
|
||||
}
|
||||
}
|
||||
190
src/Donustur.UI/Services/GlobalDragController.cs
Normal file
190
src/Donustur.UI/Services/GlobalDragController.cs
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Threading;
|
||||
using Donustur.Core.Models;
|
||||
using Donustur.Core.Services;
|
||||
using Donustur.UI.Windows;
|
||||
|
||||
namespace Donustur.UI.Services;
|
||||
|
||||
public sealed class GlobalDragController : IDisposable
|
||||
{
|
||||
[DllImport("user32.dll")]
|
||||
private static extern short GetAsyncKeyState(int vKey);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool GetCursorPos(out POINT lpPoint);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct POINT { public int X; public int Y; }
|
||||
|
||||
private const int VK_LBUTTON = 0x01;
|
||||
private const int VK_RBUTTON = 0x02;
|
||||
private const int VK_SHIFT = 0x10;
|
||||
private const int VK_CONTROL = 0x11;
|
||||
private const int VK_MENU = 0x12; // ALT
|
||||
private const int VK_ESCAPE = 0x1B;
|
||||
|
||||
private readonly PreferencesStore _preferencesStore;
|
||||
private readonly Action<ToolChoice, IReadOnlyList<string>> _onDropped;
|
||||
private readonly DispatcherTimer _pollTimer;
|
||||
|
||||
private bool _isDragging;
|
||||
private bool _suppressedForCurrentDrag;
|
||||
private POINT _dragStartPos;
|
||||
private WheelWindow? _activeWheel;
|
||||
|
||||
public GlobalDragController(PreferencesStore preferencesStore, Action<ToolChoice, IReadOnlyList<string>> onDropped)
|
||||
{
|
||||
_preferencesStore = preferencesStore;
|
||||
_onDropped = onDropped;
|
||||
|
||||
// 30 ms (~33 FPS) sorgulama aralığı: CPU kullanımı %0.01 seviyesindedir.
|
||||
_pollTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(30) };
|
||||
_pollTimer.Tick += OnPollTick;
|
||||
_pollTimer.Start();
|
||||
}
|
||||
|
||||
private void OnPollTick(object? sender, EventArgs e)
|
||||
{
|
||||
if (!_preferencesStore.Current.Enabled)
|
||||
{
|
||||
if (_activeWheel != null)
|
||||
{
|
||||
_activeWheel.CancelAndClose();
|
||||
_activeWheel = null;
|
||||
}
|
||||
_isDragging = false;
|
||||
_suppressedForCurrentDrag = false;
|
||||
return;
|
||||
}
|
||||
|
||||
bool leftDown = (GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0;
|
||||
bool rightDown = (GetAsyncKeyState(VK_RBUTTON) & 0x8000) != 0;
|
||||
bool escapeDown = (GetAsyncKeyState(VK_ESCAPE) & 0x8000) != 0;
|
||||
|
||||
// Sağ tık veya ESC ile çarkı iptal et
|
||||
if (_activeWheel != null && (rightDown || escapeDown))
|
||||
{
|
||||
_activeWheel.CancelAndClose();
|
||||
_activeWheel = null;
|
||||
_suppressedForCurrentDrag = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!leftDown)
|
||||
{
|
||||
if (_isDragging)
|
||||
{
|
||||
_isDragging = false;
|
||||
_suppressedForCurrentDrag = false;
|
||||
if (_activeWheel != null)
|
||||
{
|
||||
_activeWheel.ExecuteSelectionAndClose();
|
||||
_activeWheel = null;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
GetCursorPos(out POINT currentPoint);
|
||||
|
||||
if (!_isDragging)
|
||||
{
|
||||
_dragStartPos = currentPoint;
|
||||
_isDragging = true;
|
||||
_suppressedForCurrentDrag = IsOwnWindowForeground();
|
||||
return;
|
||||
}
|
||||
|
||||
if (_suppressedForCurrentDrag)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Fare en az 8 piksel hareket etmişse sürükleme kabul edilir
|
||||
int deltaX = Math.Abs(currentPoint.X - _dragStartPos.X);
|
||||
int deltaY = Math.Abs(currentPoint.Y - _dragStartPos.Y);
|
||||
if (deltaX + deltaY < 8) return;
|
||||
|
||||
bool modifierPressed = CheckModifierPressed(_preferencesStore.Current.DragModifier);
|
||||
|
||||
if (modifierPressed && _activeWheel == null)
|
||||
{
|
||||
OpenWheel(currentPoint);
|
||||
}
|
||||
else if (_activeWheel != null)
|
||||
{
|
||||
// Eğer çark açıldıktan 350ms sonra hâlâ geçerli bir dosya sürüklemesi (OLE FileDrop)
|
||||
// algılanmadıysa (örneğin kullanıcı metin seçiyorsa), çarkı sessizce kapat.
|
||||
if (!_activeWheel.HasValidFileDrag &&
|
||||
(DateTime.UtcNow - _activeWheel.OpenedAtUtc).TotalMilliseconds > 350)
|
||||
{
|
||||
_activeWheel.CancelAndClose();
|
||||
_activeWheel = null;
|
||||
_suppressedForCurrentDrag = true;
|
||||
return;
|
||||
}
|
||||
|
||||
_activeWheel.UpdateMousePosition(new Point(currentPoint.X, currentPoint.Y));
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsOwnWindowForeground()
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr fg = GetForegroundWindow();
|
||||
if (fg == IntPtr.Zero || Application.Current == null) return false;
|
||||
|
||||
foreach (Window win in Application.Current.Windows)
|
||||
{
|
||||
if (win is WheelWindow) continue;
|
||||
var hwnd = new WindowInteropHelper(win).Handle;
|
||||
if (hwnd != IntPtr.Zero && hwnd == fg)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Hata durumunda engelleme
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool CheckModifierPressed(string modifier)
|
||||
{
|
||||
return modifier.ToLowerInvariant() switch
|
||||
{
|
||||
"ctrl" or "control" => (GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0,
|
||||
"alt" => (GetAsyncKeyState(VK_MENU) & 0x8000) != 0,
|
||||
"shift+ctrl" or "ctrl+shift" =>
|
||||
((GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0) &&
|
||||
((GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0),
|
||||
_ => (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0 // Varsayılan: Shift
|
||||
};
|
||||
}
|
||||
|
||||
private void OpenWheel(POINT screenPoint)
|
||||
{
|
||||
var prefs = _preferencesStore.Current;
|
||||
_activeWheel = new WheelWindow(_onDropped, prefs.SoundEffectsEnabled, prefs.WheelScale);
|
||||
|
||||
// Çarkı farenin tam merkezine konumlandır
|
||||
DesktopGeometry.PlaceCentered(_activeWheel, screenPoint.X, screenPoint.Y);
|
||||
_activeWheel.Show();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_pollTimer.Stop();
|
||||
_activeWheel?.CancelAndClose();
|
||||
_activeWheel = null;
|
||||
}
|
||||
}
|
||||
170
src/Donustur.UI/Services/SingleInstance.cs
Normal file
170
src/Donustur.UI/Services/SingleInstance.cs
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace Donustur.UI.Services;
|
||||
|
||||
public sealed class SingleInstance : IDisposable
|
||||
{
|
||||
private const string PipeName = "LDConverter_App_Pipe";
|
||||
private const string MutexName = @"Local\LDConverter_SingleInstance_Mutex_v1";
|
||||
private const int SW_RESTORE = 9;
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool SetForegroundWindow(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool IsIconic(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool AllowSetForegroundWindow(int dwProcessId);
|
||||
|
||||
private readonly Mutex _mutex;
|
||||
private readonly bool _ownsMutex;
|
||||
private CancellationTokenSource? _pipeCts;
|
||||
|
||||
public bool IsPrimaryInstance => _ownsMutex;
|
||||
|
||||
public event Action? ShowRequestReceived;
|
||||
public event Action<IReadOnlyList<string>>? FilesReceived;
|
||||
|
||||
public SingleInstance()
|
||||
{
|
||||
_mutex = new Mutex(false, MutexName);
|
||||
try
|
||||
{
|
||||
_ownsMutex = _mutex.WaitOne(0, false);
|
||||
}
|
||||
catch (AbandonedMutexException)
|
||||
{
|
||||
// Önceki süreç beklenmedik şekilde kapandıysa kilidi devral
|
||||
_ownsMutex = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void StartListening()
|
||||
{
|
||||
if (!_ownsMutex) return;
|
||||
|
||||
_pipeCts = new CancellationTokenSource();
|
||||
Task.Run(async () =>
|
||||
{
|
||||
while (!_pipeCts.Token.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var server = new NamedPipeServerStream(PipeName, PipeDirection.In);
|
||||
await server.WaitForConnectionAsync(_pipeCts.Token);
|
||||
|
||||
using var reader = new StreamReader(server, Encoding.UTF8);
|
||||
string? msg = await reader.ReadLineAsync(_pipeCts.Token);
|
||||
if (string.IsNullOrWhiteSpace(msg)) continue;
|
||||
|
||||
System.Windows.Application.Current?.Dispatcher.Invoke(() =>
|
||||
{
|
||||
if (msg.StartsWith("FILES|", StringComparison.Ordinal))
|
||||
{
|
||||
var files = msg["FILES|".Length..]
|
||||
.Split('|', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Where(p => File.Exists(p) || Directory.Exists(p))
|
||||
.ToList();
|
||||
|
||||
if (files.Count > 0)
|
||||
{
|
||||
FilesReceived?.Invoke(files);
|
||||
}
|
||||
}
|
||||
ShowRequestReceived?.Invoke();
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Bağlantı sıfırlanmasında devam et
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void NotifyAndFocusPrimaryInstance(string[]? args = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Mevcut örneğin penceresine odak izni ver ve öne getir
|
||||
using var currentProc = Process.GetCurrentProcess();
|
||||
var otherProcs = Process.GetProcessesByName(currentProc.ProcessName)
|
||||
.Where(p => p.Id != currentProc.Id);
|
||||
|
||||
foreach (var proc in otherProcs)
|
||||
{
|
||||
try
|
||||
{
|
||||
AllowSetForegroundWindow(proc.Id);
|
||||
IntPtr hWnd = proc.MainWindowHandle;
|
||||
if (hWnd != IntPtr.Zero)
|
||||
{
|
||||
if (IsIconic(hWnd))
|
||||
{
|
||||
ShowWindow(hWnd, SW_RESTORE);
|
||||
}
|
||||
SetForegroundWindow(hWnd);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Erişim hatasını yoksay
|
||||
}
|
||||
finally
|
||||
{
|
||||
proc.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Süreç tarama hatasını yoksay
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var client = new NamedPipeClientStream(".", PipeName, PipeDirection.Out);
|
||||
client.Connect(400);
|
||||
using var writer = new StreamWriter(client, Encoding.UTF8);
|
||||
|
||||
if (args != null && args.Length > 0)
|
||||
{
|
||||
writer.WriteLine("FILES|" + string.Join("|", args));
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine("SHOW");
|
||||
}
|
||||
writer.Flush();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Birincil örnek yanıt vermediyse sessizce geç
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_pipeCts?.Cancel();
|
||||
if (_ownsMutex)
|
||||
{
|
||||
try
|
||||
{
|
||||
_mutex.ReleaseMutex();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Zaten serbest bırakılmış olabilir
|
||||
}
|
||||
}
|
||||
_mutex.Dispose();
|
||||
}
|
||||
}
|
||||
28
src/Donustur.UI/Services/SoundFeedback.cs
Normal file
28
src/Donustur.UI/Services/SoundFeedback.cs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
namespace Donustur.UI.Services;
|
||||
|
||||
public static class SoundFeedback
|
||||
{
|
||||
public static void PlayTick()
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Media.SystemSounds.Beep.Play();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ses çalınamazsa sessizce geç
|
||||
}
|
||||
}
|
||||
|
||||
public static void PlaySuccess()
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Media.SystemSounds.Asterisk.Play();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Sessizce geç
|
||||
}
|
||||
}
|
||||
}
|
||||
90
src/Donustur.UI/Services/TrayHost.cs
Normal file
90
src/Donustur.UI/Services/TrayHost.cs
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
using System.Windows.Forms;
|
||||
using Donustur.Core.Services;
|
||||
|
||||
namespace Donustur.UI.Services;
|
||||
|
||||
public sealed class TrayHost : IDisposable
|
||||
{
|
||||
private readonly NotifyIcon _notifyIcon;
|
||||
private readonly PreferencesStore _preferencesStore;
|
||||
private readonly Action _openMainWindow;
|
||||
private readonly Action _openSettings;
|
||||
private readonly Action _exitApp;
|
||||
private readonly ToolStripMenuItem _toggleWheelItem;
|
||||
|
||||
public TrayHost(
|
||||
PreferencesStore preferencesStore,
|
||||
Action openMainWindow,
|
||||
Action openSettings,
|
||||
Action exitApp)
|
||||
{
|
||||
_preferencesStore = preferencesStore;
|
||||
_openMainWindow = openMainWindow;
|
||||
_openSettings = openSettings;
|
||||
_exitApp = exitApp;
|
||||
|
||||
var contextMenu = new ContextMenuStrip();
|
||||
|
||||
var openItem = new ToolStripMenuItem("LD Converter'ı Aç");
|
||||
openItem.Font = new System.Drawing.Font(openItem.Font, System.Drawing.FontStyle.Bold);
|
||||
openItem.Click += (_, _) => _openMainWindow();
|
||||
contextMenu.Items.Add(openItem);
|
||||
|
||||
contextMenu.Items.Add(new ToolStripSeparator());
|
||||
|
||||
_toggleWheelItem = new ToolStripMenuItem($"Sürükleme Çarkı ({_preferencesStore.Current.DragModifier})");
|
||||
_toggleWheelItem.Checked = _preferencesStore.Current.Enabled;
|
||||
_toggleWheelItem.Click += (_, _) =>
|
||||
{
|
||||
var p = _preferencesStore.Current;
|
||||
p.Enabled = !p.Enabled;
|
||||
_preferencesStore.Save(p);
|
||||
_toggleWheelItem.Checked = p.Enabled;
|
||||
};
|
||||
contextMenu.Items.Add(_toggleWheelItem);
|
||||
|
||||
var settingsItem = new ToolStripMenuItem("Ayarlar...");
|
||||
settingsItem.Click += (_, _) => _openSettings();
|
||||
contextMenu.Items.Add(settingsItem);
|
||||
|
||||
contextMenu.Items.Add(new ToolStripSeparator());
|
||||
|
||||
var exitItem = new ToolStripMenuItem("Çıkış");
|
||||
exitItem.Click += (_, _) => _exitApp();
|
||||
contextMenu.Items.Add(exitItem);
|
||||
|
||||
_notifyIcon = new NotifyIcon
|
||||
{
|
||||
Icon = AppIconProvider.GetTrayIcon(),
|
||||
Text = "LD Converter - Hızlı Dosya Dönüştürücü",
|
||||
ContextMenuStrip = contextMenu,
|
||||
Visible = true
|
||||
};
|
||||
|
||||
_notifyIcon.DoubleClick += (_, _) => _openMainWindow();
|
||||
}
|
||||
|
||||
public void ShowToast(string title, string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
_notifyIcon.ShowBalloonTip(3000, title, message, ToolTipIcon.Info);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Sessizce geç
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdateStatus()
|
||||
{
|
||||
_toggleWheelItem.Checked = _preferencesStore.Current.Enabled;
|
||||
_toggleWheelItem.Text = $"Sürükleme Çarkı ({_preferencesStore.Current.DragModifier})";
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_notifyIcon.Visible = false;
|
||||
_notifyIcon.Dispose();
|
||||
}
|
||||
}
|
||||
112
src/Donustur.UI/Windows/ProgressToastWindow.xaml
Normal file
112
src/Donustur.UI/Windows/ProgressToastWindow.xaml
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
<Window x:Class="Donustur.UI.Windows.ProgressToastWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="LD Converter"
|
||||
Width="350" Height="145"
|
||||
WindowStyle="None"
|
||||
AllowsTransparency="True"
|
||||
Background="Transparent"
|
||||
ShowInTaskbar="False"
|
||||
Topmost="True"
|
||||
ShowActivated="False"
|
||||
WindowStartupLocation="Manual">
|
||||
<Border Background="#F2181C26"
|
||||
BorderBrush="#35FFFFFF"
|
||||
BorderThickness="1"
|
||||
CornerRadius="14"
|
||||
Margin="10">
|
||||
<Border.Effect>
|
||||
<DropShadowEffect BlurRadius="20" ShadowDepth="4" Opacity="0.45" Color="#000000" />
|
||||
</Border.Effect>
|
||||
|
||||
<Grid Margin="16,12,16,12">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Başlık ve İptal/Kapat Butonu -->
|
||||
<Grid Grid.Row="0">
|
||||
<TextBlock x:Name="TitleText"
|
||||
Text="Dönüştürülüyor..."
|
||||
FontSize="13.5"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="#FFFFFF"
|
||||
Margin="0,0,24,0"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
<Button x:Name="CloseButton"
|
||||
Content="✕"
|
||||
ToolTip="İptal Et / Kapat"
|
||||
HorizontalAlignment="Right"
|
||||
Background="Transparent"
|
||||
Foreground="#9CA3AF"
|
||||
BorderThickness="0"
|
||||
Cursor="Hand"
|
||||
FontSize="11.5"
|
||||
Click="OnCloseClick" />
|
||||
</Grid>
|
||||
|
||||
<!-- Durum Açıklaması -->
|
||||
<TextBlock x:Name="StatusText"
|
||||
Grid.Row="1"
|
||||
Text="Dosyalar işleniyor..."
|
||||
FontSize="11.5"
|
||||
Foreground="#9CA3AF"
|
||||
TextTrimming="CharacterEllipsis"
|
||||
Margin="0,4,0,8" />
|
||||
|
||||
<!-- İlerleme Çubuğu -->
|
||||
<ProgressBar x:Name="ProgressBar"
|
||||
Grid.Row="2"
|
||||
Height="5"
|
||||
Minimum="0" Maximum="100"
|
||||
Value="0"
|
||||
Foreground="#6366F1"
|
||||
Background="#2D3343"
|
||||
BorderThickness="0" />
|
||||
|
||||
<!-- İşlem Butonları (Tamamlandığında görünür) -->
|
||||
<StackPanel x:Name="ActionPanel"
|
||||
Grid.Row="3"
|
||||
Orientation="Horizontal"
|
||||
HorizontalAlignment="Right"
|
||||
Margin="0,8,0,0"
|
||||
Visibility="Collapsed">
|
||||
<Button x:Name="CopyTextButton"
|
||||
Content="Metni Kopyala"
|
||||
Visibility="Collapsed"
|
||||
Background="#6366F1"
|
||||
Foreground="#FFFFFF"
|
||||
BorderThickness="0"
|
||||
Padding="10,4"
|
||||
Margin="0,0,6,0"
|
||||
FontSize="11"
|
||||
Cursor="Hand"
|
||||
Click="OnCopyTextClick">
|
||||
<Button.Resources>
|
||||
<Style TargetType="Border">
|
||||
<Setter Property="CornerRadius" Value="6"/>
|
||||
</Style>
|
||||
</Button.Resources>
|
||||
</Button>
|
||||
<Button x:Name="OpenFolderButton"
|
||||
Content="Klasörde Göster"
|
||||
Background="#2D3343"
|
||||
Foreground="#E0E7FF"
|
||||
BorderThickness="0"
|
||||
Padding="10,4"
|
||||
FontSize="11"
|
||||
Cursor="Hand"
|
||||
Click="OnOpenFolderClick">
|
||||
<Button.Resources>
|
||||
<Style TargetType="Border">
|
||||
<Setter Property="CornerRadius" Value="6"/>
|
||||
</Style>
|
||||
</Button.Resources>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Window>
|
||||
149
src/Donustur.UI/Windows/ProgressToastWindow.xaml.cs
Normal file
149
src/Donustur.UI/Windows/ProgressToastWindow.xaml.cs
Normal file
|
|
@ -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<ProgressToastWindow> 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<string> 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();
|
||||
}
|
||||
}
|
||||
365
src/Donustur.UI/Windows/SettingsWindow.xaml
Normal file
365
src/Donustur.UI/Windows/SettingsWindow.xaml
Normal file
|
|
@ -0,0 +1,365 @@
|
|||
<Window x:Class="Donustur.UI.Windows.SettingsWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="LD Converter - Ayarlar"
|
||||
Width="600" Height="720"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
Background="#12151E"
|
||||
Foreground="#FFFFFF"
|
||||
WindowStyle="SingleBorderWindow"
|
||||
ResizeMode="NoResize">
|
||||
<Window.Resources>
|
||||
<Style TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable Display, Segoe UI"/>
|
||||
</Style>
|
||||
<Style x:Key="SectionTitle" TargetType="TextBlock">
|
||||
<Setter Property="FontSize" Value="13.5"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Foreground" Value="#818CF8"/>
|
||||
<Setter Property="Margin" Value="0,14,0,8"/>
|
||||
</Style>
|
||||
<Style x:Key="SettingLabel" TargetType="TextBlock">
|
||||
<Setter Property="FontSize" Value="12.5"/>
|
||||
<Setter Property="FontWeight" Value="Medium"/>
|
||||
<Setter Property="Foreground" Value="#F3F4F6"/>
|
||||
<Setter Property="VerticalAlignment" Value="Center"/>
|
||||
</Style>
|
||||
<Style x:Key="SettingDesc" TargetType="TextBlock">
|
||||
<Setter Property="FontSize" Value="11"/>
|
||||
<Setter Property="Foreground" Value="#9CA3AF"/>
|
||||
<Setter Property="Margin" Value="0,2,0,0"/>
|
||||
</Style>
|
||||
|
||||
<!-- Koyu Tema ComboBox Stili -->
|
||||
<Style x:Key="DarkComboBoxItem" TargetType="ComboBoxItem">
|
||||
<Setter Property="Background" Value="#1E2333"/>
|
||||
<Setter Property="Foreground" Value="#F3F4F6"/>
|
||||
<Setter Property="Padding" Value="10,7"/>
|
||||
<Setter Property="BorderThickness" Value="0"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ComboBoxItem">
|
||||
<Border x:Name="itemBorder" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter />
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsHighlighted" Value="True">
|
||||
<Setter TargetName="itemBorder" Property="Background" Value="#4F46E5"/>
|
||||
<Setter Property="Foreground" Value="#FFFFFF"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="itemBorder" Property="Background" Value="#312E81"/>
|
||||
<Setter Property="Foreground" Value="#FFFFFF"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="DarkComboBox" TargetType="ComboBox">
|
||||
<Setter Property="Foreground" Value="#F3F4F6"/>
|
||||
<Setter Property="Background" Value="#252B3D"/>
|
||||
<Setter Property="BorderBrush" Value="#374151"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="FontSize" Value="12"/>
|
||||
<Setter Property="Padding" Value="10,6"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="ItemContainerStyle" Value="{StaticResource DarkComboBoxItem}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ComboBox">
|
||||
<Grid>
|
||||
<ToggleButton x:Name="ToggleButton"
|
||||
Focusable="False"
|
||||
IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
|
||||
ClickMode="Press">
|
||||
<ToggleButton.Template>
|
||||
<ControlTemplate TargetType="ToggleButton">
|
||||
<Border x:Name="border"
|
||||
Background="#252B3D"
|
||||
BorderBrush="#3B4256"
|
||||
BorderThickness="1"
|
||||
CornerRadius="6">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="26"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Path Grid.Column="1"
|
||||
HorizontalAlignment="Center"
|
||||
VerticalAlignment="Center"
|
||||
Data="M 0 0 L 4 4 L 8 0 Z"
|
||||
Fill="#9CA3AF"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="border" Property="BorderBrush" Value="#6366F1"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</ToggleButton.Template>
|
||||
</ToggleButton>
|
||||
|
||||
<ContentPresenter x:Name="ContentSite"
|
||||
IsHitTestVisible="False"
|
||||
Content="{TemplateBinding SelectionBoxItem}"
|
||||
ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
|
||||
ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"
|
||||
Margin="10,6,28,6"
|
||||
VerticalAlignment="Center"
|
||||
HorizontalAlignment="Left"/>
|
||||
|
||||
<Popup x:Name="Popup"
|
||||
Placement="Bottom"
|
||||
IsOpen="{TemplateBinding IsDropDownOpen}"
|
||||
AllowsTransparency="True"
|
||||
Focusable="False"
|
||||
PopupAnimation="Slide">
|
||||
<Grid x:Name="DropDown"
|
||||
SnapsToDevicePixels="True"
|
||||
MinWidth="{TemplateBinding ActualWidth}"
|
||||
MaxHeight="{TemplateBinding MaxDropDownHeight}">
|
||||
<Border x:Name="DropDownBorder"
|
||||
Background="#1E2333"
|
||||
BorderBrush="#4F46E5"
|
||||
BorderThickness="1"
|
||||
CornerRadius="6"
|
||||
Margin="0,2,0,0">
|
||||
<ScrollViewer SnapsToDevicePixels="True">
|
||||
<StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained"/>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Popup>
|
||||
</Grid>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Modern Toggle Switch CheckBox Stili -->
|
||||
<Style x:Key="ModernSwitch" TargetType="CheckBox">
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="CheckBox">
|
||||
<Border x:Name="switchTrack" Width="42" Height="22" CornerRadius="11" Background="#374151" Padding="2">
|
||||
<Ellipse x:Name="switchThumb" Width="18" Height="18" Fill="#D1D5DB" HorizontalAlignment="Left"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter TargetName="switchTrack" Property="Background" Value="#6366F1"/>
|
||||
<Setter TargetName="switchThumb" Property="Fill" Value="#FFFFFF"/>
|
||||
<Setter TargetName="switchThumb" Property="HorizontalAlignment" Value="Right"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</Window.Resources>
|
||||
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" Padding="24,16,24,24">
|
||||
<StackPanel>
|
||||
<!-- Başlık -->
|
||||
<TextBlock Text="Uygulama Ayarları" FontSize="20" FontWeight="Bold" Foreground="#FFFFFF" Margin="0,0,0,4"/>
|
||||
<TextBlock Text="Sürükleme çarkını, çıktı hedeflerini ve dönüştürme motorlarını yapılandırın." FontSize="12" Foreground="#9CA3AF" Margin="0,0,0,12"/>
|
||||
|
||||
<!-- Çark & Sürükleme -->
|
||||
<TextBlock Text="Sürükleme & Çark Davranışı" Style="{StaticResource SectionTitle}"/>
|
||||
<Border Background="#1A1E2B" BorderBrush="#262C3D" BorderThickness="1" CornerRadius="10" Padding="14" Margin="0,0,0,10">
|
||||
<StackPanel>
|
||||
<!-- Aktif/Pasif -->
|
||||
<DockPanel Margin="0,0,0,12">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Sürükleme Çarkı Etkin" Style="{StaticResource SettingLabel}"/>
|
||||
<TextBlock Text="Dosya sürüklerken seçilen tuşa basıldığında çark açılır." Style="{StaticResource SettingDesc}"/>
|
||||
</StackPanel>
|
||||
<CheckBox x:Name="EnableWheelCheck" Style="{StaticResource ModernSwitch}" HorizontalAlignment="Right" VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
|
||||
<Separator Background="#2D3343" Margin="0,2,0,12"/>
|
||||
|
||||
<!-- Kısayol Tuşu -->
|
||||
<DockPanel Margin="0,0,0,12">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Tetikleyici Tuş (Modifier)" Style="{StaticResource SettingLabel}"/>
|
||||
<TextBlock Text="Sürükleme anında basılı tutulacak klavye tuşu." Style="{StaticResource SettingDesc}"/>
|
||||
</StackPanel>
|
||||
<ComboBox x:Name="ModifierCombo" Style="{StaticResource DarkComboBox}" Width="140" HorizontalAlignment="Right" VerticalAlignment="Center">
|
||||
<ComboBoxItem Content="Shift"/>
|
||||
<ComboBoxItem Content="Ctrl"/>
|
||||
<ComboBoxItem Content="Alt"/>
|
||||
<ComboBoxItem Content="Shift+Ctrl"/>
|
||||
</ComboBox>
|
||||
</DockPanel>
|
||||
|
||||
<Separator Background="#2D3343" Margin="0,2,0,12"/>
|
||||
|
||||
<!-- Çark Boyutu -->
|
||||
<DockPanel Margin="0,0,0,12">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Çark Boyut Ölçeği" Style="{StaticResource SettingLabel}"/>
|
||||
<TextBlock Text="Radial menünün ekrandaki büyüklüğü." Style="{StaticResource SettingDesc}"/>
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center">
|
||||
<TextBlock x:Name="ScaleValueLabel" Text="1.0x" FontSize="12" FontWeight="SemiBold" Foreground="#A5B4FC" Width="36" TextAlignment="Right" VerticalAlignment="Center" Margin="0,0,8,0"/>
|
||||
<Slider x:Name="ScaleSlider" Width="130" Minimum="0.8" Maximum="1.4" Value="1.0" SmallChange="0.05" LargeChange="0.1" VerticalAlignment="Center" ValueChanged="OnScaleSliderChanged"/>
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
|
||||
<Separator Background="#2D3343" Margin="0,2,0,12"/>
|
||||
|
||||
<!-- Ses Efektleri -->
|
||||
<DockPanel>
|
||||
<StackPanel>
|
||||
<TextBlock Text="Dokunsal Ses Geri Bildirimi" Style="{StaticResource SettingLabel}"/>
|
||||
<TextBlock Text="Dilimler arasında gezinirken ve işlem bitince ses çalar." Style="{StaticResource SettingDesc}"/>
|
||||
</StackPanel>
|
||||
<CheckBox x:Name="SoundCheck" Style="{StaticResource ModernSwitch}" HorizontalAlignment="Right" VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Çıktı Klasörü & Kalite -->
|
||||
<TextBlock Text="Çıktı & Kalite Yönetimi" Style="{StaticResource SectionTitle}"/>
|
||||
<Border Background="#1A1E2B" BorderBrush="#262C3D" BorderThickness="1" CornerRadius="10" Padding="14" Margin="0,0,0,10">
|
||||
<StackPanel>
|
||||
<DockPanel Margin="0,0,0,12">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Kayıt Konumu" Style="{StaticResource SettingLabel}"/>
|
||||
<TextBlock Text="Dönüştürülen dosyaların kaydedileceği yer." Style="{StaticResource SettingDesc}"/>
|
||||
</StackPanel>
|
||||
<ComboBox x:Name="OutputModeCombo" Style="{StaticResource DarkComboBox}" Width="210" HorizontalAlignment="Right" VerticalAlignment="Center" SelectionChanged="OnOutputModeChanged">
|
||||
<ComboBoxItem Content="Kaynak Dosyayla Aynı Klasör"/>
|
||||
<ComboBoxItem Content="Masaüstü"/>
|
||||
<ComboBoxItem Content="Özel Klasör"/>
|
||||
</ComboBox>
|
||||
</DockPanel>
|
||||
|
||||
<!-- Özel Klasör Seçimi -->
|
||||
<DockPanel x:Name="CustomFolderPanel" Margin="0,0,0,12" Visibility="Collapsed">
|
||||
<Button Content="Gözat..." Width="75" DockPanel.Dock="Right" Margin="8,0,0,0" Click="OnBrowseFolderClick" Background="#374151" Foreground="#FFFFFF" BorderThickness="0" Padding="8,6" Cursor="Hand">
|
||||
<Button.Resources>
|
||||
<Style TargetType="Border"><Setter Property="CornerRadius" Value="6"/></Style>
|
||||
</Button.Resources>
|
||||
</Button>
|
||||
<TextBox x:Name="CustomFolderText" Background="#252B3D" Foreground="#FFFFFF" BorderBrush="#3B4256" Padding="8,5" VerticalContentAlignment="Center"/>
|
||||
</DockPanel>
|
||||
|
||||
<Separator Background="#2D3343" Margin="0,2,0,12"/>
|
||||
|
||||
<!-- Görsel Sıkıştırma Kalitesi -->
|
||||
<DockPanel Margin="0,0,0,12">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Görsel Kalitesi (JPG / WebP / AVIF)" Style="{StaticResource SettingLabel}"/>
|
||||
<TextBlock Text="Yüksek değer daha iyi görüntü kalitesi, düşük değer daha küçük boyut sağlar." Style="{StaticResource SettingDesc}"/>
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center">
|
||||
<TextBlock x:Name="QualityValueLabel" Text="%85" FontSize="12" FontWeight="SemiBold" Foreground="#A5B4FC" Width="36" TextAlignment="Right" VerticalAlignment="Center" Margin="0,0,8,0"/>
|
||||
<Slider x:Name="QualitySlider" Width="130" Minimum="20" Maximum="100" Value="85" SmallChange="5" LargeChange="10" VerticalAlignment="Center" ValueChanged="OnQualitySliderChanged"/>
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
|
||||
<Separator Background="#2D3343" Margin="0,2,0,12"/>
|
||||
|
||||
<DockPanel>
|
||||
<StackPanel>
|
||||
<TextBlock Text="İşlem Sonrası Klasörü Aç" Style="{StaticResource SettingLabel}"/>
|
||||
<TextBlock Text="Dönüştürme bitince hedef dosyayı Windows Gezgini'nde gösterir." Style="{StaticResource SettingDesc}"/>
|
||||
</StackPanel>
|
||||
<CheckBox x:Name="AutoOpenCheck" Style="{StaticResource ModernSwitch}" HorizontalAlignment="Right" VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Sistem & Başlangıç -->
|
||||
<TextBlock Text="Sistem Entegrasyonu" Style="{StaticResource SectionTitle}"/>
|
||||
<Border Background="#1A1E2B" BorderBrush="#262C3D" BorderThickness="1" CornerRadius="10" Padding="14" Margin="0,0,0,10">
|
||||
<StackPanel>
|
||||
<DockPanel Margin="0,0,0,12">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Kapatıldığında Sistem Tepsisinde Kal" Style="{StaticResource SettingLabel}"/>
|
||||
<TextBlock Text="Pencere kapandığında arka planda saat yanında çalışmaya devam eder." Style="{StaticResource SettingDesc}"/>
|
||||
</StackPanel>
|
||||
<CheckBox x:Name="MinimizeToTrayCheck" Style="{StaticResource ModernSwitch}" HorizontalAlignment="Right" VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
|
||||
<Separator Background="#2D3343" Margin="0,2,0,12"/>
|
||||
|
||||
<DockPanel>
|
||||
<StackPanel>
|
||||
<TextBlock Text="Windows Başlangıcında Otomatik Başlat" Style="{StaticResource SettingLabel}"/>
|
||||
<TextBlock Text="Bilgisayar açıldığında LD Converter hazır bekler." Style="{StaticResource SettingDesc}"/>
|
||||
</StackPanel>
|
||||
<CheckBox x:Name="RunAtStartupCheck" Style="{StaticResource ModernSwitch}" HorizontalAlignment="Right" VerticalAlignment="Center" Click="OnStartupToggle"/>
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Harici Motor Durumu -->
|
||||
<TextBlock Text="Dönüştürme Motorları & Durum" Style="{StaticResource SectionTitle}"/>
|
||||
<Border Background="#1A1E2B" BorderBrush="#262C3D" BorderThickness="1" CornerRadius="10" Padding="14" Margin="0,0,0,18">
|
||||
<StackPanel>
|
||||
<!-- LibreOffice -->
|
||||
<DockPanel Margin="0,0,0,8">
|
||||
<Button Content="soffice.exe Seç..." DockPanel.Dock="Right" HorizontalAlignment="Right" VerticalAlignment="Center" Background="#2D3548" Foreground="#FFFFFF" BorderThickness="0" Padding="10,5" Cursor="Hand" Click="OnBrowseLibreOfficeClick">
|
||||
<Button.Resources>
|
||||
<Style TargetType="Border"><Setter Property="CornerRadius" Value="6"/></Style>
|
||||
</Button.Resources>
|
||||
</Button>
|
||||
<StackPanel>
|
||||
<TextBlock Text="LibreOffice (Ofis Belgeleri Motoru)" Style="{StaticResource SettingLabel}"/>
|
||||
<TextBlock x:Name="LibreOfficeStatusText" Text="Kontrol ediliyor..." Style="{StaticResource SettingDesc}" TextTrimming="CharacterEllipsis"/>
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
|
||||
<Separator Background="#2D3343" Margin="0,4,0,10"/>
|
||||
|
||||
<!-- FFmpeg -->
|
||||
<DockPanel Margin="0,0,0,8">
|
||||
<Button Content="ffmpeg.exe Seç..." DockPanel.Dock="Right" HorizontalAlignment="Right" VerticalAlignment="Center" Background="#2D3548" Foreground="#FFFFFF" BorderThickness="0" Padding="10,5" Cursor="Hand" Click="OnBrowseFfmpegClick">
|
||||
<Button.Resources>
|
||||
<Style TargetType="Border"><Setter Property="CornerRadius" Value="6"/></Style>
|
||||
</Button.Resources>
|
||||
</Button>
|
||||
<StackPanel>
|
||||
<TextBlock Text="FFmpeg (Video & Ses Motoru)" Style="{StaticResource SettingLabel}"/>
|
||||
<TextBlock x:Name="FfmpegStatusText" Text="Kontrol ediliyor..." Style="{StaticResource SettingDesc}" TextTrimming="CharacterEllipsis"/>
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
|
||||
<Separator Background="#2D3343" Margin="0,4,0,10"/>
|
||||
|
||||
<!-- 7-Zip & Yerel Motorlar -->
|
||||
<DockPanel>
|
||||
<StackPanel>
|
||||
<TextBlock Text="Yerel Motorlar (Magick.NET, PdfPig, SharpCompress, 7-Zip)" Style="{StaticResource SettingLabel}"/>
|
||||
<TextBlock x:Name="NativeEnginesStatusText" Text="✓ Görsel, PDF, DOCX, QR ve Arşiv motorları aktif" Style="{StaticResource SettingDesc}" Foreground="#86EFAC"/>
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Kaydet Butonu -->
|
||||
<Button Content="Ayarları Kaydet ve Kapat"
|
||||
Height="40"
|
||||
Background="#6366F1"
|
||||
Foreground="#FFFFFF"
|
||||
FontWeight="SemiBold"
|
||||
FontSize="13.5"
|
||||
BorderThickness="0"
|
||||
Cursor="Hand"
|
||||
Click="OnSaveClick">
|
||||
<Button.Resources>
|
||||
<Style TargetType="Border">
|
||||
<Setter Property="CornerRadius" Value="8"/>
|
||||
</Style>
|
||||
</Button.Resources>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Window>
|
||||
234
src/Donustur.UI/Windows/SettingsWindow.xaml.cs
Normal file
234
src/Donustur.UI/Windows/SettingsWindow.xaml.cs
Normal file
|
|
@ -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<double> e)
|
||||
{
|
||||
if (ScaleValueLabel != null)
|
||||
{
|
||||
ScaleValueLabel.Text = $"{e.NewValue:0.00}x";
|
||||
}
|
||||
}
|
||||
|
||||
private void OnQualitySliderChanged(object sender, RoutedPropertyChangedEventArgs<double> 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();
|
||||
}
|
||||
}
|
||||
24
src/Donustur.UI/Windows/WheelWindow.xaml
Normal file
24
src/Donustur.UI/Windows/WheelWindow.xaml
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
<Window x:Class="Donustur.UI.Windows.WheelWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:controls="clr-namespace:Donustur.UI.Controls"
|
||||
Title="LD Converter Çarkı"
|
||||
Width="380" Height="380"
|
||||
WindowStyle="None"
|
||||
AllowsTransparency="True"
|
||||
Background="Transparent"
|
||||
ShowInTaskbar="False"
|
||||
Topmost="True"
|
||||
ShowActivated="False"
|
||||
AllowDrop="True"
|
||||
WindowStartupLocation="Manual">
|
||||
<Grid x:Name="RootGrid" RenderTransformOrigin="0.5,0.5">
|
||||
<Grid.RenderTransform>
|
||||
<ScaleTransform x:Name="WheelScale" ScaleX="1.0" ScaleY="1.0" />
|
||||
</Grid.RenderTransform>
|
||||
|
||||
<controls:RadialWheelControl x:Name="RadialControl"
|
||||
HorizontalAlignment="Center"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</Window>
|
||||
245
src/Donustur.UI/Windows/WheelWindow.xaml.cs
Normal file
245
src/Donustur.UI/Windows/WheelWindow.xaml.cs
Normal file
|
|
@ -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<ToolChoice, IReadOnlyList<string>> _onDropped;
|
||||
private readonly bool _soundEnabled;
|
||||
private readonly double _targetScale;
|
||||
private IReadOnlyList<string> _activeFiles = Array.Empty<string>();
|
||||
private bool _isClosing;
|
||||
private bool _selectionExecuted;
|
||||
|
||||
public DateTime OpenedAtUtc { get; } = DateTime.UtcNow;
|
||||
public bool HasValidFileDrag { get; private set; }
|
||||
|
||||
public WheelWindow(Action<ToolChoice, IReadOnlyList<string>> 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<string>());
|
||||
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
25
src/Donustur.UI/app.manifest
Normal file
25
src/Donustur.UI/app.manifest
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.1.0.0" name="LDConverter.app"/>
|
||||
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
|
||||
<security>
|
||||
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
|
||||
</requestedPrivileges>
|
||||
</security>
|
||||
</trustInfo>
|
||||
|
||||
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
|
||||
<application>
|
||||
<!-- Windows 10 & 11 -->
|
||||
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
|
||||
</application>
|
||||
</compatibility>
|
||||
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
|
||||
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
</assembly>
|
||||
28
tests/Donustur.Tests/Donustur.Tests.csproj
Normal file
28
tests/Donustur.Tests/Donustur.Tests.csproj
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
|
||||
<PackageReference Include="xunit" Version="2.5.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Donustur.Core\Donustur.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\Donustur.Engine\Donustur.Engine.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
394
tests/Donustur.Tests/DonusturTests.cs
Normal file
394
tests/Donustur.Tests/DonusturTests.cs
Normal file
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue