diff --git a/.gitignore b/.gitignore index d7f5bdc..34a5388 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,21 @@ [Oo]bj/ [Ll]og/ [Ll]ogs/ +*.log *.zip +# Python PyInstaller artifacts +build/ +dist/ +publish/ +*.spec +*.docx +LD-Converter-*-Setup.exe +tools/*.exe +!tools/cjxl.exe +!tools/djxl.exe +publish/tools/*.exe +temp_out/ +test_math.pdf # Visual Studio / Rider / VS Code caches .vs/ @@ -15,3 +29,29 @@ *.sln.docstates TestResults/ *.DotSettings.user + +# Keys & Updates +.keys/ +dist-updates/ +dist-ui/ +node_modules/ +src-tauri/target/ + +# Security & Local Server Scripts (NEVER commit) +bağlan.bat +*baglan*.bat +ba*lan.bat +publish.ps1 +publish.bat +release.ps1 +.keys/ +*.key +*.pem +*.pfx +*.p12 +*.sig +.env +.env.* +!.env.example +secrets.* +config.local.* diff --git a/Donustur.sln b/Donustur.sln deleted file mode 100644 index de3d424..0000000 --- a/Donustur.sln +++ /dev/null @@ -1,50 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31903.59 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{35B7845F-528A-445E-A621-66D16C8781FE}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Donustur.Core", "src\Donustur.Core\Donustur.Core.csproj", "{A66A55A6-BD61-43EF-A73C-17DA990FA19A}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Donustur.Engine", "src\Donustur.Engine\Donustur.Engine.csproj", "{95295F12-8EC1-4BCB-8A8B-5144E9142BDB}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Donustur.UI", "src\Donustur.UI\Donustur.UI.csproj", "{C193D18F-2854-4CA3-A011-296E454B518C}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{66ACE05A-6B60-4D21-A6BA-5BD0CDB30737}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Donustur.Tests", "tests\Donustur.Tests\Donustur.Tests.csproj", "{9F90D082-CC34-4C03-8E19-D34694A2270B}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A66A55A6-BD61-43EF-A73C-17DA990FA19A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A66A55A6-BD61-43EF-A73C-17DA990FA19A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A66A55A6-BD61-43EF-A73C-17DA990FA19A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A66A55A6-BD61-43EF-A73C-17DA990FA19A}.Release|Any CPU.Build.0 = Release|Any CPU - {95295F12-8EC1-4BCB-8A8B-5144E9142BDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {95295F12-8EC1-4BCB-8A8B-5144E9142BDB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {95295F12-8EC1-4BCB-8A8B-5144E9142BDB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {95295F12-8EC1-4BCB-8A8B-5144E9142BDB}.Release|Any CPU.Build.0 = Release|Any CPU - {C193D18F-2854-4CA3-A011-296E454B518C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C193D18F-2854-4CA3-A011-296E454B518C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C193D18F-2854-4CA3-A011-296E454B518C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C193D18F-2854-4CA3-A011-296E454B518C}.Release|Any CPU.Build.0 = Release|Any CPU - {9F90D082-CC34-4C03-8E19-D34694A2270B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9F90D082-CC34-4C03-8E19-D34694A2270B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9F90D082-CC34-4C03-8E19-D34694A2270B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9F90D082-CC34-4C03-8E19-D34694A2270B}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {A66A55A6-BD61-43EF-A73C-17DA990FA19A} = {35B7845F-528A-445E-A621-66D16C8781FE} - {95295F12-8EC1-4BCB-8A8B-5144E9142BDB} = {35B7845F-528A-445E-A621-66D16C8781FE} - {C193D18F-2854-4CA3-A011-296E454B518C} = {35B7845F-528A-445E-A621-66D16C8781FE} - {9F90D082-CC34-4C03-8E19-D34694A2270B} = {66ACE05A-6B60-4D21-A6BA-5BD0CDB30737} - EndGlobalSection -EndGlobal diff --git a/README.md b/README.md index 8018a8b..0ae6bc7 100644 --- a/README.md +++ b/README.md @@ -1,54 +1,98 @@ -# LD Converter 🚀 +
-[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Release](https://img.shields.io/github/v/release/LilDosto/LD-Converter)](https://github.com/LilDosto/LD-Converter/releases) +# 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ü. +**Hızlı, çevrimdışı ve çok formatlı masaüstü dosya dönüştürücü • Fast, offline, multi-format desktop file converter** + +[![License: MIT](https://img.shields.io/badge/License-MIT-10B981?style=for-the-badge)](./LICENSE) +[![Version](https://img.shields.io/badge/Version-v3.6.4-blue?style=for-the-badge)](https://git.ttmadethat.shop/LilDosto/LD-Converter/releases/latest) +[![Stack](https://img.shields.io/badge/Stack-Tauri%20v2%20%7C%20Rust%20%7C%20React%2019-orange?style=for-the-badge)](https://v2.tauri.app) +[![Platform](https://img.shields.io/badge/Platform-Windows%2010%2F11%20x64-0078D6?style=for-the-badge)](https://git.ttmadethat.shop/LilDosto/LD-Converter/releases/latest) + +[🇹🇷 Türkçe](#-türkçe) • [🇬🇧 English](#-english) • [📦 Releases](https://git.ttmadethat.shop/LilDosto/LD-Converter/releases/latest) + +
--- -## 🌟 Öne Çıkan Özellikler +## 🇹🇷 Türkçe -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. +**LD Converter**, Windows için Tauri v2, Rust ve React 19 ile geliştirilmiş; görsel, PDF, ofis belgesi, video/ses, arşiv ve OCR/QR işlemlerini tek çatı altında toplayan çevrimdışı bir masaüstü dosya dönüştürme uygulamasıdır. -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. +### Özellikler -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. +- **Görsel Dönüştürme & Optimizasyon:** PNG, JPG, WebP, AVIF, BMP, TIFF, ICO, GIF, JPEG XL (`cjxl`/`djxl`) ve görsellerden PDF oluşturma; kalite/boyut ayarlama, yeniden boyutlandırma ve EXIF/GPS meta verisi temizleme. +- **PDF & Denklem İşleme:** PDF birleştirme, sayfa ayırma, sayfa aralığı çıkarma, 90°/180°/270° döndürme; PDF → TXT / DOCX / PNG / JPG / Denklem DOCX (OMML). +- **Dahili Ofis Belge Motoru:** DOCX, ODT, PPTX, XLSX, RTF, TXT, Markdown, HTML ve EPUB dosyalarını harici program gerektirmeden PDF, DOCX, TXT veya HTML formatlarına dönüştürme (DOCX çıktı ve vektör PDF desteği; Pandoc varsa OMML denklem dönüşümü). +- **Video & Ses (FFmpeg):** MP4, MKV, WebM, GIF, MP3, WAV, AAC/M4A, FLAC ve OGG dönüşümleri; kırpma, sessize alma, CRF/preset/bitrate ve sıkıştırma ayarları. +- **Arşiv & OCR / QR:** Zip-Slip korumalı ZIP oluşturma/çıkarma, 7-Zip ile 7Z / TAR.GZ / RAR / şifreli ZIP desteği; Windows yerleşik OCR (görsel/PDF → TXT/DOCX) ve dahili `rqrr` QR kod okuyucu. +- **Masaüstü Entegrasyonu:** Dosya ve klasör sağ tık menüsü (**LD Converter ile Dönüştür**), sistem tepsisinde çalışma, başlangıçta otomatik başlatma, dönüşüm geçmişi, tanılama günlüğü (`--self-test`) ve imzalı OTA güncelleme. +- **Otomatik Araç Yönetimi:** Açılışta eksik veya eski FFmpeg / Pandoc / 7-Zip araçlarını denetleyerek `%LOCALAPPDATA%\LDConverter\tools` altına otomatik kurar. -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. +### Teknoloji Yığını ---- +- **Masaüstü & Çekirdek:** Tauri v2 (`tauri 2.12`), Rust (`image`, `lopdf`, `printpdf`, `zip`, `sevenz-rust2`, `rqrr`, `resvg`, `latex2mathml`, `rayon`, `tokio`, Windows OCR/GDI API) +- **Arayüz:** React 19, TypeScript, Tailwind CSS v4, Zustand, Framer Motion, Vite -## ⚡ Çalıştırma +### Kurulum ve Kullanım -### Hazır Derlenmiş Sürümden Başlatma: -`publish/LDConverter.exe` dosyasını çift tıklayarak doğrudan çalıştırabilirsiniz. +**Son Kullanıcı:** +1. [Releases](https://git.ttmadethat.shop/LilDosto/LD-Converter/releases/latest) sayfasından `LD-Converter_3.6.4_x64-setup.exe` dosyasını indirin ve çalıştırın (Microsoft Edge WebView2 Runtime gereklidir). +2. Uygulamaya dosya/klasör sürükleyerek veya Windows Gezgini'nde dosyaya sağ tıklayıp **LD Converter ile Dönüştür** menüsünden dönüşüm başlatın. -### Kaynak Koddan Çalıştırma: -```bash -dotnet run --project src/Donustur.UI/Donustur.UI.csproj +**Geliştirici (Kaynaktan Derleme):** +```powershell +npm install +npm run tauri dev # Geliştirme modunda çalıştır +npm run tauri build # Üretim kurulum paketini derle ``` - -### Testleri Çalıştırma: -```bash -dotnet test +Rust motor testleri ve tanılama: +```powershell +cd src-tauri +cargo test -- --test-threads=1 ``` --- -## 📄 Lisans +## 🇬🇧 English -Bu proje **[MIT Lisansı](LICENSE)** ile lisanslanmıştır. Daha fazla bilgi için [LICENSE](LICENSE) dosyasına göz atabilirsiniz. +**LD Converter** is a fast, offline Windows desktop file converter built with Tauri v2, Rust, and React 19, uniting image, PDF, office document, video/audio, archive, and OCR/QR workflows in one application. +### Features + +- **Image Conversion & Optimization:** Convert between PNG, JPG, WebP, AVIF, BMP, TIFF, ICO, GIF, JPEG XL (`cjxl`/`djxl`), and images-to-PDF; resize, adjust quality, and strip EXIF/GPS metadata. +- **PDF & Math Equations:** Merge PDFs, split pages, extract page ranges, rotate 90°/180°/270°, and convert PDF → TXT / DOCX / PNG / JPG / OMML Equation DOCX. +- **Built-in Office Engine:** Convert DOCX, ODT, PPTX, XLSX, RTF, TXT, Markdown, HTML, and EPUB to PDF, DOCX, TXT, or HTML without external office suites (formatting-preserving DOCX & vector PDF support, plus Pandoc OMML equation conversion when available). +- **Video & Audio (FFmpeg):** Convert MP4, MKV, WebM, GIF, MP3, WAV, AAC/M4A, FLAC, and OGG with trim, mute, CRF/preset/bitrate, and compression controls. +- **Archives & OCR / QR:** Zip-Slip-safe ZIP creation/extraction and 7Z / TAR.GZ / RAR / encrypted ZIP via 7-Zip; Windows built-in OCR (images/PDF → TXT/DOCX) and built-in `rqrr` QR code reading. +- **Desktop Integration:** Windows Explorer context menu (**Convert with LD Converter**), system tray support, autostart option, conversion history, diagnostic logging (`--self-test`), and Minisign-verified OTA updates. +- **Automatic Tool Resolver:** Checks for missing or outdated FFmpeg / Pandoc / 7-Zip binaries on startup and provisions them under `%LOCALAPPDATA%\LDConverter\tools`. + +### Tech Stack + +- **Desktop & Backend:** Tauri v2 (`tauri 2.12`), Rust (`image`, `lopdf`, `printpdf`, `zip`, `sevenz-rust2`, `rqrr`, `resvg`, `latex2mathml`, `rayon`, `tokio`, Windows OCR/GDI APIs) +- **Frontend:** React 19, TypeScript, Tailwind CSS v4, Zustand, Framer Motion, Vite + +### Installation & Usage + +**End Users:** +1. Download `LD-Converter_3.6.4_x64-setup.exe` from the [Releases](https://git.ttmadethat.shop/LilDosto/LD-Converter/releases/latest) page and run the installer (requires Microsoft Edge WebView2 Runtime). +2. Drag and drop files/folders into the app or right-click files in Windows Explorer to convert directly. + +**Developers (Build from Source):** +```powershell +npm install +npm run tauri dev # Run in development mode +npm run tauri build # Build production installer +``` +Run Rust backend tests: +```powershell +cd src-tauri +cargo test -- --test-threads=1 +``` + +--- + +## 📄 Lisans / License + +Bu proje [MIT Lisansı](./LICENSE) altında lisanslanmıştır. • Licensed under the [MIT License](./LICENSE). diff --git a/index.html b/index.html new file mode 100644 index 0000000..d544a4e --- /dev/null +++ b/index.html @@ -0,0 +1,13 @@ + + + + + + LD Converter + + + +
+ + + diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..c6990e7 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2471 @@ +{ + "name": "ld-converter", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ld-converter", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "@tauri-apps/api": "^2.12.4", + "@tauri-apps/plugin-dialog": "^2.8.4", + "@tauri-apps/plugin-fs": "^2.7.1", + "@tauri-apps/plugin-os": "^2.4.0", + "@tauri-apps/plugin-process": "^2.4.0", + "@tauri-apps/plugin-shell": "^2.6.0", + "@tauri-apps/plugin-updater": "^2.14.1", + "clsx": "^2.1.1", + "framer-motion": "^14.13.0", + "lucide-react": "^1.72.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "tailwind-merge": "^3.7.0", + "zustand": "^5.1.0" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.3.5", + "@tauri-apps/cli": "^2.12.4", + "@types/node": "^26.6.6", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^6.3.0", + "autoprefixer": "^10.6.2", + "postcss": "^8.5.32", + "tailwindcss": "^4.3.5", + "typescript": "^7.0.2", + "vite": "^8.3.8" + } + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.0.tgz", + "integrity": "sha512-K+NU2HDCEem4sClgHH4ZZXwdJeNFkJo+hRk479DIwdIviAPN2hFJH1KHHwg8CxHQXvi0M5XY4deTXINfIiSG6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tailwindcss/node": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.5.tgz", + "integrity": "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.5", + "jiti": "^2.7.0", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.5.tgz", + "integrity": "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-x64": "4.3.5", + "@tailwindcss/oxide-freebsd-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-x64-musl": "4.3.5", + "@tailwindcss/oxide-wasm32-wasi": "4.3.5", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.5.tgz", + "integrity": "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.5.tgz", + "integrity": "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.5.tgz", + "integrity": "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.5.tgz", + "integrity": "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.5.tgz", + "integrity": "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.5.tgz", + "integrity": "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.5.tgz", + "integrity": "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.5.tgz", + "integrity": "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.5.tgz", + "integrity": "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.5.tgz", + "integrity": "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@emnapi/wasi-threads": "^1.2.3", + "@napi-rs/wasm-runtime": "^1.2.2", + "@tybys/wasm-util": "^0.10.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.2", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "dev": true, + "inBundle": true, + "license": "0BSD", + "optional": true + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.5.tgz", + "integrity": "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.5.tgz", + "integrity": "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/vite": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.5.tgz", + "integrity": "sha512-BCNiY0a1ZjdOHVqw7kyb7U72BwfMF3dfUuN+tQsLWky/J5JOI/r7abibglXfygrZhVO/3u3V+E25kkKTeMkXaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tailwindcss/node": "4.3.5", + "@tailwindcss/oxide": "4.3.5", + "tailwindcss": "4.3.5" + }, + "peerDependencies": { + "vite": "^5.2.0 || ^6 || ^7 || ^8" + } + }, + "node_modules/@tauri-apps/api": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.4.tgz", + "integrity": "sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg==", + "license": "Apache-2.0 OR MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/tauri" + } + }, + "node_modules/@tauri-apps/cli": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.4.tgz", + "integrity": "sha512-JI9bHfudSRJikGOrjbXEm6RjzzvmKuLc+JixB1NE8hNzQkNlCCIC3pTES3uypkR9lxHrsbxzcnSwhI2IxBQphw==", + "dev": true, + "license": "Apache-2.0 OR MIT", + "bin": { + "tauri": "tauri.js" + }, + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/tauri" + }, + "optionalDependencies": { + "@tauri-apps/cli-darwin-arm64": "2.12.4", + "@tauri-apps/cli-darwin-x64": "2.12.4", + "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.4", + "@tauri-apps/cli-linux-arm64-gnu": "2.12.4", + "@tauri-apps/cli-linux-arm64-musl": "2.12.4", + "@tauri-apps/cli-linux-riscv64-gnu": "2.12.4", + "@tauri-apps/cli-linux-x64-gnu": "2.12.4", + "@tauri-apps/cli-linux-x64-musl": "2.12.4", + "@tauri-apps/cli-win32-arm64-msvc": "2.12.4", + "@tauri-apps/cli-win32-ia32-msvc": "2.12.4", + "@tauri-apps/cli-win32-x64-msvc": "2.12.4" + } + }, + "node_modules/@tauri-apps/cli-darwin-arm64": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.4.tgz", + "integrity": "sha512-OxqKSckIkoJ6vX2AjifIJpTasFC0Hbdoo7gEiCmAjauABO3U8m2MRsLWe+QTiBwDx1mIrvgA+rvI7tvDnbnHVg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-darwin-x64": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.4.tgz", + "integrity": "sha512-fz76/77wMMJOaaUN6n3CybRG0P/MTEjjqYk81mGPyhi9m6Ue5T+LWBnJP/AkPooNatBPI2vtulGqomyMJ44lCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm-gnueabihf": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.4.tgz", + "integrity": "sha512-K0w8Bof6Lt8QKLAYhRy0yy36ZH5iA/35VuSOvnxyjvCUZ+A3JKsUTlALviH/sVgAlisaPzzmeJSH8XOn4Q2HBA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm64-gnu": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.4.tgz", + "integrity": "sha512-j5rOnjmRUwWrm1oosf0zBYl4D+fqydgUROFCk0hvKZxvbTT8SOERes0QB7rBV/XWNy+kM6pCKzb3oSm2sRglzg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm64-musl": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.4.tgz", + "integrity": "sha512-aOue3Fy6Jb7+oWcfAVUsVHfeTybSCt2CZoU06aO4jv4d2Ks/KnaTPwMAK3CLEduGOvBLY1lbBBrIyomqLLH5Sg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-riscv64-gnu": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.4.tgz", + "integrity": "sha512-Fx6GShY/RvST+t6LMlTHAwd66+1tEaAAGrnU7cysVfaiRP1BKng5Vl6rVmO6rSLOA1Sp1dRzNYM4f0OWQGb7qA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-x64-gnu": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.4.tgz", + "integrity": "sha512-tNzZSa79Z1nRpHxEpQ38lsAFpKlFlYvoXzjTV+lRRn/zSf3wrdUC3wnLcq2XEadchPu4ttK0zivhYzr+XGD19Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-x64-musl": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.4.tgz", + "integrity": "sha512-jmZ1pr0xEqUhuEusWtt9Yt+GF6lCnGHUmIL+KIknpbjK/XQ2qkhDBhaxK/JMHM2A8dAacVXCxXJk2EXpwhQUfA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-arm64-msvc": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.4.tgz", + "integrity": "sha512-fGo8pgEHZxdSYgZ/J98m1usJ7NHKmKbq7k6uT0x1rpOq6Bg2YVzzpaAblWk710f5LHYBJIL5QIFS5IrD+4gmTg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-ia32-msvc": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.4.tgz", + "integrity": "sha512-ezl8sQIcjYsye3TUnTH5VcWmWzccZASlQm7hlZt0dYyj1XD0qpVW47u2xYVrIKui0F8uQv/7QGZixdWiClBsbg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-x64-msvc": { + "version": "2.12.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.4.tgz", + "integrity": "sha512-DJhDeCqjLDNMWYFy7ZS8cfeAHX2RK0RbQMLiA3bMVVkXRDJ4NBYiHriGqsUhsr9iG41aTb+dJGkFPmPw1gWwVw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/plugin-dialog": { + "version": "2.8.4", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-dialog/-/plugin-dialog-2.8.4.tgz", + "integrity": "sha512-+6ZOiXenOaxXwb8qCbBPdT2jX2cFPaVVHGIskrpmJLpmWj+qKRTD6X/z9x7hTdSQn7NedcoXCkWGej4a7dC4lw==", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@tauri-apps/api": "^2.12.0" + } + }, + "node_modules/@tauri-apps/plugin-fs": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-fs/-/plugin-fs-2.7.1.tgz", + "integrity": "sha512-4TBVjpi/q8PuNzjpkAc2iBGXMTLjOrAyfTiiOL8ORaJCZJRG3tjzmQ4sqs2CMG75FvLyRkOkERfP7AyY4iBNwQ==", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@tauri-apps/api": "^2.12.0" + } + }, + "node_modules/@tauri-apps/plugin-os": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-os/-/plugin-os-2.4.0.tgz", + "integrity": "sha512-XFQjntNNI3Vlqdy4WUGwiXX8DByzKVvoemAcUVkBm9NJPGmoDtII5i+vfuAzWaJfOE5cUJJLUDqXBnd4reSAIA==", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@tauri-apps/api": "^2.12.0" + } + }, + "node_modules/@tauri-apps/plugin-process": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-process/-/plugin-process-2.4.0.tgz", + "integrity": "sha512-GddrmsSLAYrLa/yTXlXK/YRDzUgYeeOnUXTbiyvJWkmI424RmDPD3FVLeqcon7rv6O6ZfhBilcrHWnSo7o6hIQ==", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@tauri-apps/api": "^2.12.0" + } + }, + "node_modules/@tauri-apps/plugin-shell": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-shell/-/plugin-shell-2.6.0.tgz", + "integrity": "sha512-z9LZGSr8jfD0FWWJ+CdD99i2FQcmJ26ebNJlYJdrlFdMLcggUS29BYrfS4hJlXO1UAI6A6r084vJUAG5734Y6w==", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@tauri-apps/api": "^2.12.0" + } + }, + "node_modules/@tauri-apps/plugin-updater": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-updater/-/plugin-updater-2.14.1.tgz", + "integrity": "sha512-Hr7nlBm1wT6xbwzjZ/S36YULazu8MNlj5vvOwMl47fXI7HTa5Bjl1PbDEwVHaZTAKzE1VZsUy35UqnbrQxmYQw==", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@tauri-apps/api": "^2.12.0" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.3.0.tgz", + "integrity": "sha512-H9E955aVvD2F4zNHCw4eIZbIfF6xKldlh7MNu+hSU7xwQzh65lI/N+CJWqmfhi0PEjDXIt/H7T7J/4wU63KJiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": ">=0.152.0 <0.157.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/autoprefixer": { + "version": "10.6.2", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.6.2.tgz", + "integrity": "sha512-VOw9/yGTGwPPgzFcODtcv6zhEPIeIWkRSe10L2ri2f5vZ7ID7lCt6jZzRF5/ubgOZ+szYydmEF5AYsA5jxX1tA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.9", + "caniuse-lite": "^1.0.30001810", + "fraction.js": "^5.3.4", + "picocolors": "^1.1.1", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.36", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.36.tgz", + "integrity": "sha512-AbPFGS4K9S3meMRCLTM0Zas+e9X7b5ygUBOboDT5zevCZt9ByKSbMtKhwyVqW+oL8WemPVsbP7X3rdZcIyOa0w==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", + "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.33", + "caniuse-lite": "^1.0.30001819", + "electron-to-chromium": "^1.5.464", + "node-releases": "^2.0.60", + "update-browserslist-db": "^1.3.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001826", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001826.tgz", + "integrity": "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.483", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.483.tgz", + "integrity": "sha512-zkGOvf625oaZgK+mhTF4hl3aTAfIOOnR7Jey0e7fUktdJWrB/wsLnzPKvWaqZkMCJ1yzUkAh6IqDJ9GMr3pR2Q==", + "dev": true, + "license": "ISC" + }, + "node_modules/enhanced-resolve": { + "version": "5.27.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", + "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fraction.js": { + "version": "5.3.4", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz", + "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/rawify" + } + }, + "node_modules/framer-motion": { + "version": "14.13.0", + "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-14.13.0.tgz", + "integrity": "sha512-62FgGVeqEI3pgI5jG/d6yagg/hX9z7Vw3ytE0gGAsDXWBBruUCr74b5LQJXMSF1E62Zp7HKO88nDu/hhUdRSCQ==", + "license": "MIT", + "dependencies": { + "motion-dom": "14.13.0", + "motion-utils": "14.7.0", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0", + "remix": "^3.1.0" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "react-dom": { + "optional": true + }, + "remix": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lucide-react": { + "version": "1.72.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.72.0.tgz", + "integrity": "sha512-fbF5i1GU8GODETa3Q7rXqrJrcx3iPYrQtxthom103zGx+Z0BGwKYAW9s+9435ohYJ7hQm0av0PoZcqI1CRwNrg==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/motion-dom": { + "version": "14.13.0", + "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-14.13.0.tgz", + "integrity": "sha512-nWrB6Psw7mFTBNL9r5hw9nm/a5+21WZ1LymOml/V2b43LdiIDO1oi+oBMSR3bcyuzEQKJoaa+t5qnsCWYhcNvA==", + "license": "MIT", + "dependencies": { + "motion-utils": "14.7.0" + } + }, + "node_modules/motion-utils": { + "version": "14.7.0", + "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-14.7.0.tgz", + "integrity": "sha512-woO0/Nb7ys75f94fjvQi/6leiHGvZUYkeHUPEZ3vxsV+9OpEVhkxp01x8MlRwX0zt31EqgXsKDAoBoJLC148Tw==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.63", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.63.tgz", + "integrity": "sha512-6li2QanLsAXpIH2R6j77MzRyvOyrvdTqlKtO4CgBdHGNvN99ZZfyxszHc5o5+IZBWD5u6Hzwg83JoGXmqZNG9Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/rolldown": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tailwind-merge": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.7.0.tgz", + "integrity": "sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, + "node_modules/tailwindcss": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz", + "integrity": "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", + "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD" + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/zustand": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.1.0.tgz", + "integrity": "sha512-ciJZlP48M1PTQbVQq81CGVFxHTLpZNrFjKqwjtCU34AWuXTZT/jrF3p9+fI84Cf1eSCMLapxqBy/SNTfwOBuqA==", + "license": "MIT", + "engines": { + "node": ">=12.20.0" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "immer": ">=9.0.6", + "react": ">=18.0.0", + "use-sync-external-store": ">=1.2.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + }, + "use-sync-external-store": { + "optional": true + } + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..e8f36cf --- /dev/null +++ b/package.json @@ -0,0 +1,52 @@ +{ + "name": "ld-converter", + "version": "3.6.4", + "description": "[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)", + "main": "index.js", + "directories": { + "test": "tests" + }, + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "tauri": "tauri" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/LilDosto/LD-Converter.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "module", + "bugs": { + "url": "https://github.com/LilDosto/LD-Converter/issues" + }, + "homepage": "https://github.com/LilDosto/LD-Converter#readme", + "devDependencies": { + "@tailwindcss/vite": "^4.3.5", + "@tauri-apps/cli": "^2.12.4", + "@types/node": "^26.6.6", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^6.3.0", + "autoprefixer": "^10.6.2", + "postcss": "^8.5.32", + "tailwindcss": "^4.3.5", + "typescript": "^7.0.2", + "vite": "^8.3.8" + }, + "dependencies": { + "@tauri-apps/api": "^2.12.4", + "@tauri-apps/plugin-dialog": "^2.8.4", + "@tauri-apps/plugin-process": "^2.4.0", + "@tauri-apps/plugin-updater": "^2.14.1", + "clsx": "^2.1.1", + "framer-motion": "^14.13.0", + "lucide-react": "^1.72.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "tailwind-merge": "^3.7.0", + "zustand": "^5.1.0" + } +} diff --git a/public/logo.png b/public/logo.png new file mode 100644 index 0000000..fc57b01 Binary files /dev/null and b/public/logo.png differ diff --git a/publish/Donustur.Core.dll b/publish/Donustur.Core.dll deleted file mode 100644 index 574e476..0000000 Binary files a/publish/Donustur.Core.dll and /dev/null differ diff --git a/publish/Donustur.Core.pdb b/publish/Donustur.Core.pdb deleted file mode 100644 index 3be8875..0000000 Binary files a/publish/Donustur.Core.pdb and /dev/null differ diff --git a/publish/Donustur.Engine.dll b/publish/Donustur.Engine.dll deleted file mode 100644 index 4cb85f9..0000000 Binary files a/publish/Donustur.Engine.dll and /dev/null differ diff --git a/publish/Donustur.Engine.pdb b/publish/Donustur.Engine.pdb deleted file mode 100644 index 1faeeac..0000000 Binary files a/publish/Donustur.Engine.pdb and /dev/null differ diff --git a/publish/ICSharpCode.SharpZipLib.dll b/publish/ICSharpCode.SharpZipLib.dll deleted file mode 100644 index 08de420..0000000 Binary files a/publish/ICSharpCode.SharpZipLib.dll and /dev/null differ diff --git a/publish/LDConverter.deps.json b/publish/LDConverter.deps.json deleted file mode 100644 index e8fc0b4..0000000 --- a/publish/LDConverter.deps.json +++ /dev/null @@ -1,239 +0,0 @@ -{ - "runtimeTarget": { - "name": ".NETCoreApp,Version=v8.0/win-x64", - "signature": "" - }, - "compilationOptions": {}, - "targets": { - ".NETCoreApp,Version=v8.0": {}, - ".NETCoreApp,Version=v8.0/win-x64": { - "LDConverter/1.3.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.3.0": { - "type": "project", - "serviceable": false, - "sha512": "" - }, - "Magick.NET-Q8-x64/15.0.0": { - "type": "package", - "serviceable": true, - "sha512": "sha512-RVfIbAddWlHEr6aJiYAYIRn1P7bQUoSv9GJN0fZmcatnenaD4KTtzoxOFYq67KXegLTsBQHsGdjzgGDW5d4Ing==", - "path": "magick.net-q8-x64/15.0.0", - "hashPath": "magick.net-q8-x64.15.0.0.nupkg.sha512" - }, - "Magick.NET.Core/15.0.0": { - "type": "package", - "serviceable": true, - "sha512": "sha512-mP/VovMRuXBX2Rcnn1wWu0Zur6cjsf8IQhmTUCrasEk8cyAtN5sjHE7NxiH88whw8/2mjRvuphKUwj6bAZslpQ==", - "path": "magick.net.core/15.0.0", - "hashPath": "magick.net.core.15.0.0.nupkg.sha512" - }, - "PdfPig/0.1.16": { - "type": "package", - "serviceable": true, - "sha512": "sha512-qQcbsNMYVY+K5ELptax2S8thNMk0+rSQq3H/KdYj3LLcko8yTCz8y5KIvsKxIyAuTN0ZYNnfsZkM+0EvxTwHVA==", - "path": "pdfpig/0.1.16", - "hashPath": "pdfpig.0.1.16.nupkg.sha512" - }, - "PdfSharpCore/1.3.67": { - "type": "package", - "serviceable": true, - "sha512": "sha512-6Cvj9nX6RwIJFIQC8eJFCYYUu9Qa2t9LWh4i0SXFi3hqkX/ssUGKfzp+9JZZXbkp0lHeeH/9UYFHelLqIusPrQ==", - "path": "pdfsharpcore/1.3.67", - "hashPath": "pdfsharpcore.1.3.67.nupkg.sha512" - }, - "SharpCompress/0.50.7": { - "type": "package", - "serviceable": true, - "sha512": "sha512-amxjOlPKUFb33ohAVahPCCBHLtToYOOb6JGyM40q8DnT6KYoBLW1TtW6uLEXbv40S7ej6ikf6VmAXGBaFL6Klg==", - "path": "sharpcompress/0.50.7", - "hashPath": "sharpcompress.0.50.7.nupkg.sha512" - }, - "SharpZipLib/1.4.2": { - "type": "package", - "serviceable": true, - "sha512": "sha512-yjj+3zgz8zgXpiiC3ZdF/iyTBbz2fFvMxZFEBPUcwZjIvXOf37Ylm+K58hqMfIBt5JgU/Z2uoUS67JmTLe973A==", - "path": "sharpziplib/1.4.2", - "hashPath": "sharpziplib.1.4.2.nupkg.sha512" - }, - "SixLabors.Fonts/1.0.0-beta17": { - "type": "package", - "serviceable": true, - "sha512": "sha512-qubgVovAoSR7vyv9tJ68gSzRIPWz7HBjTM9rwAaLjpcJ6T50arnX+GHAZcC0r2mVagyRMknCNda3DGoe8StUUQ==", - "path": "sixlabors.fonts/1.0.0-beta17", - "hashPath": "sixlabors.fonts.1.0.0-beta17.nupkg.sha512" - }, - "SixLabors.ImageSharp/1.0.4": { - "type": "package", - "serviceable": true, - "sha512": "sha512-H2rPiEr2ddBOltOuqRYhpLBAsQXDAhbzMMhhuksnBG2oefup1MXMchALe7yYkKJksNbtxbZHKeM6dn/68I75qw==", - "path": "sixlabors.imagesharp/1.0.4", - "hashPath": "sixlabors.imagesharp.1.0.4.nupkg.sha512" - }, - "ZXing.Net/0.16.11": { - "type": "package", - "serviceable": true, - "sha512": "sha512-OZfAVu88hl87BffQ+rlWCj/vLvAhhCK4QnFaoveeF/MY8SjHNSYBQ3qyUEWlPKNgBQGh1syXhCDg10vUnCsqkg==", - "path": "zxing.net/0.16.11", - "hashPath": "zxing.net.0.16.11.nupkg.sha512" - }, - "Donustur.Core/1.0.0": { - "type": "project", - "serviceable": false, - "sha512": "" - }, - "Donustur.Engine/1.0.0": { - "type": "project", - "serviceable": false, - "sha512": "" - } - } -} \ No newline at end of file diff --git a/publish/LDConverter.dll b/publish/LDConverter.dll deleted file mode 100644 index 06f4169..0000000 Binary files a/publish/LDConverter.dll and /dev/null differ diff --git a/publish/LDConverter.exe b/publish/LDConverter.exe deleted file mode 100644 index 8dc2fd7..0000000 Binary files a/publish/LDConverter.exe and /dev/null differ diff --git a/publish/LDConverter.pdb b/publish/LDConverter.pdb deleted file mode 100644 index 5ecd5fe..0000000 Binary files a/publish/LDConverter.pdb and /dev/null differ diff --git a/publish/LDConverter.runtimeconfig.json b/publish/LDConverter.runtimeconfig.json deleted file mode 100644 index 8fbd17c..0000000 --- a/publish/LDConverter.runtimeconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "runtimeOptions": { - "tfm": "net8.0", - "frameworks": [ - { - "name": "Microsoft.NETCore.App", - "version": "8.0.0" - }, - { - "name": "Microsoft.WindowsDesktop.App", - "version": "8.0.0" - } - ], - "configProperties": { - "System.Reflection.Metadata.MetadataUpdater.IsSupported": false, - "System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": true - } - } -} \ No newline at end of file diff --git a/publish/Magick.NET-Q8-x64.dll b/publish/Magick.NET-Q8-x64.dll deleted file mode 100644 index 3afc7fe..0000000 Binary files a/publish/Magick.NET-Q8-x64.dll and /dev/null differ diff --git a/publish/Magick.NET.Core.dll b/publish/Magick.NET.Core.dll deleted file mode 100644 index 4236523..0000000 Binary files a/publish/Magick.NET.Core.dll and /dev/null differ diff --git a/publish/Magick.Native-Q8-x64.dll b/publish/Magick.Native-Q8-x64.dll deleted file mode 100644 index f94f185..0000000 Binary files a/publish/Magick.Native-Q8-x64.dll and /dev/null differ diff --git a/publish/PdfSharpCore.dll b/publish/PdfSharpCore.dll deleted file mode 100644 index 820cf28..0000000 Binary files a/publish/PdfSharpCore.dll and /dev/null differ diff --git a/publish/SharpCompress.dll b/publish/SharpCompress.dll deleted file mode 100644 index 7760266..0000000 Binary files a/publish/SharpCompress.dll and /dev/null differ diff --git a/publish/SixLabors.Fonts.dll b/publish/SixLabors.Fonts.dll deleted file mode 100644 index 0b4caab..0000000 Binary files a/publish/SixLabors.Fonts.dll and /dev/null differ diff --git a/publish/SixLabors.ImageSharp.dll b/publish/SixLabors.ImageSharp.dll deleted file mode 100644 index 109ac6d..0000000 Binary files a/publish/SixLabors.ImageSharp.dll and /dev/null differ diff --git a/publish/UglyToad.PdfPig.Core.dll b/publish/UglyToad.PdfPig.Core.dll deleted file mode 100644 index 493720b..0000000 Binary files a/publish/UglyToad.PdfPig.Core.dll and /dev/null differ diff --git a/publish/UglyToad.PdfPig.DocumentLayoutAnalysis.dll b/publish/UglyToad.PdfPig.DocumentLayoutAnalysis.dll deleted file mode 100644 index 10febf0..0000000 Binary files a/publish/UglyToad.PdfPig.DocumentLayoutAnalysis.dll and /dev/null differ diff --git a/publish/UglyToad.PdfPig.Fonts.dll b/publish/UglyToad.PdfPig.Fonts.dll deleted file mode 100644 index 8a3bd41..0000000 Binary files a/publish/UglyToad.PdfPig.Fonts.dll and /dev/null differ diff --git a/publish/UglyToad.PdfPig.Package.dll b/publish/UglyToad.PdfPig.Package.dll deleted file mode 100644 index 417c4d1..0000000 Binary files a/publish/UglyToad.PdfPig.Package.dll and /dev/null differ diff --git a/publish/UglyToad.PdfPig.Tokenization.dll b/publish/UglyToad.PdfPig.Tokenization.dll deleted file mode 100644 index 8980db3..0000000 Binary files a/publish/UglyToad.PdfPig.Tokenization.dll and /dev/null differ diff --git a/publish/UglyToad.PdfPig.Tokens.dll b/publish/UglyToad.PdfPig.Tokens.dll deleted file mode 100644 index ed8295e..0000000 Binary files a/publish/UglyToad.PdfPig.Tokens.dll and /dev/null differ diff --git a/publish/UglyToad.PdfPig.dll b/publish/UglyToad.PdfPig.dll deleted file mode 100644 index a63f584..0000000 Binary files a/publish/UglyToad.PdfPig.dll and /dev/null differ diff --git a/publish/de/PdfSharpCore.resources.dll b/publish/de/PdfSharpCore.resources.dll deleted file mode 100644 index de96ea4..0000000 Binary files a/publish/de/PdfSharpCore.resources.dll and /dev/null differ diff --git a/publish/zxing.dll b/publish/zxing.dll deleted file mode 100644 index 4bfc2b8..0000000 Binary files a/publish/zxing.dll and /dev/null differ diff --git a/site/add_ld_converter_route.py b/site/add_ld_converter_route.py new file mode 100644 index 0000000..9d002cb --- /dev/null +++ b/site/add_ld_converter_route.py @@ -0,0 +1,40 @@ +import os +import shutil +from pathlib import Path + +p = Path('/opt/tylorindar-safelink/main.py') +if not p.exists(): + print('FastAPI main.py not found at expected path.') + raise SystemExit(1) + +t = p.read_text(encoding='utf-8') +if 'async def ld_converter_page' in t: + print('LD Converter route already present') + raise SystemExit(0) + +needle = '@app.get("/{code}")\nasync def redirect_shortlink' +insert = '''@app.get("/ld-converter", include_in_schema=False) +@app.get("/ld-converter/", include_in_schema=False) +async def ld_converter_page(): + page = os.path.join(static_dir, "ld-converter.html") + if os.path.exists(page): + return FileResponse( + page, + media_type="text/html", + headers={"Cache-Control": "no-store, max-age=0"}, + ) + raise HTTPException(status_code=404, detail="LD Converter sayfası bulunamadı.") + +''' + +if needle not in t: + print('Catch-all route needle not found in main.py') + raise SystemExit(1) + +backup_path = Path('/opt/tylorindar-safelink/backups/main.py.bak-ld-converter-page') +backup_path.parent.mkdir(parents=True, exist_ok=True) +shutil.copy2(p, backup_path) + +t = t.replace(needle, insert + needle, 1) +p.write_text(t, encoding='utf-8') +print('LD Converter route successfully added to main.py') diff --git a/site/ld-converter.html b/site/ld-converter.html new file mode 100644 index 0000000..b96c6f6 --- /dev/null +++ b/site/ld-converter.html @@ -0,0 +1,545 @@ + + + + + + LD Converter — Tauri v2 & Rust ile Yeni Nesil Masaüstü Dönüştürücü | v3.6.4 + + + + + + + + + + + + + + + + +
+ + + +
+
+
Tauri v2 & Rust 64-Bit Core
+

Ultra Hızlı. Sıfır Bloat.

+

+ Dosyalarını pencereye sürükle-bırak veya Windows Gezgini sağ tık menüsünden dönüştür: + JPEG XL (JXL), Word Denklem Formülleri (OMML), PDF & OCR, Canlı FFmpeg Medya ve 7-Zip Güvenliği tek bir şık masaüstü uygulamasında buluştu. +

+ +
+ ● Windows 11 / 10 Uyumlu + Pure Rust Image & Archive Core + 100% Çevrimdışı Çalışır +
+
+ + +
+
+ Saf Rust Mimarisi + Zero-Python · Zero-Bloat +
+ +
+
+ 📐 +
+ OMML Denklem DOCX + PDF & LaTeX → <m:oMath> +
+
+
+ 📄 +
+ PDF Düzen Motoru + DOCX, PNG/JPG, Ayır/Birleştir +
+
+
+ ✨ +
+ JPEG XL & Modern Görsel + JXL, WebP, AVIF, ICO, GIF +
+
+
+ 🎬 +
+ Canlı FFmpeg Medya + MP4, MKV, MP3, Trim & % Takibi +
+
+
+ 📦 +
+ Güvenli 7Z / ZIP + Zip Slip Koruması · AES +
+
+
+ 🖱️ +
+ Explorer Sağ Tık & OCR + Tek Tık Menü · Çevrimdışı OCR +
+
+
+ +
+ Sürükle-Bırak + Explorer Sağ Tık Menüsü + ● %100 Çevrimdışı +
+
+
+ + +
+
+
+ < 15 ms + Tauri v2 Başlatma Hızı +
+
+ 100% + OMML Denklem Uyumu +
+
+ 12+ + Görsel & Medya Formatı +
+
+ Sağ Tık + Explorer Menü Entegrasyonu +
+
+
+ + +
+
+
+ Öne Çıkan Yetenekler +

Masaüstü Dönüşümünde Standartları Yeniden Belirledik

+
+

Yalnızca dosya uzantısını değiştiren yüzeysel araçlar yerine; derin piksel, vektör, OMML ve matris düzeyinde çalışan saf Rust mimarisi.

+
+ +
+
+
📐
+

Markdown & PDF'ten Gerçek Word Denklemlerine (OMML)

+

+ Akademik makaleler, ders notları veya formül dolu dökümanlar artık Word'e resim olarak yapışmıyor. $E = mc^2$ gibi LaTeX formülleri doğrudan Microsoft Word'ün yerleşik <m:oMath> denklem motoruna çevrilir; tıklayıp düzenleyebilirsiniz. +

+ ✓ LaTeX $...$ & $$...$$  →  Microsoft Word OMML +
+ +
+
✨
+

JPEG XL (JXL) Çift Yönlü Motor

+

+ Gömülü cjxl / djxl motoru sayesinde JPEG XL dosyalarını tüm resim formatlarına çevirin veya fotoğraflarınızı JXL'e sıkıştırın. Ek kurulum ya da FFmpeg derlemesi gerekmez. +

+ JXL ↔ PNG / JPG / WebP / BMP / TIFF +
+ +
+
🎬
+

Canlı FFmpeg Medya Laboratuvarı

+

+ Video ve ses dosyalarını dönüştürürken arka planda donup kalmayın. Canlı yüzde (1%..99%), 00:00:00 Trim ve Sesi Kaldır (Mute) seçenekleriyle tam kontrol elinizde. +

+ H.264 / AAC / MP3 / Trim +
+ +
+
🛡️
+

Zip Slip Korumalı Arşivleme

+

+ Arşiv dosyalarını açarken dizin dışına taşma (Zip Slip) saldırılarını kanonik yol doğrulamasıyla engeller; şifreli 7Z ve ZIP dosyalarını güvenle açar. +

+ ZIP · 7Z · RAR · AES-256 +
+ +
+
🔍
+

Çevrimdışı Akıllı OCR & QR Kod

+

+ Taranmış belgeler ve resimlerdeki yazıları internete göndermeden metne dökün. Görseldeki QR kodları tek dokunuşla panoya kopyalayın. +

+ rqrr Core + Yerleşik OCR +
+
+
+ + +
+
+
+ Dönüşüm Rotaları +

En Popüler İş Akışları

+
+

Karmaşık komut satırları veya web sitelerine dosya yükleme derdi yok.

+
+ +
+
+
+ Akademik & Belge + OMML Pipeline +
+
+ Formulas.md + ➔ + LaTeX Parser + ➔ + Düzenlenebilir Word (.docx) +
+

Matematik sembolleri, kesirler, integraller ve matrisler Word'ün yerel denklem editörüyle tam uyumlu çıkar.

+
+ +
+
+ Yeni Nesil Görsel + Next-Gen Graphics +
+
+ Photo.jxl + ➔ + Rust Image / FFmpeg + ➔ + WebP / PNG / JPG +
+

İster yüzlerce fotoğrafı WebP yapın, ister web siteniz için ultra hafif kayıpsız JXL çıktısı alın.

+
+
+
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KategoriGirdi FormatlarıÇıktı & Özel YeteneklerÇekirdek Motor
GörsellerPNG, JPG, WebP, JXL, AVIF, BMP, TIFF, GIF, ICOKalite ayarı, boyutlandırma, animasyonlu GIF yapmaPure Rust + FFmpeg
Matematik & BelgeMarkdown (.md), PDF, DOCX, TXT, HTMLOMML <m:oMath> düzenlenebilir denklem çıktısıPandoc & LD Math Engine
Medya (Video / Ses)MP4, MKV, AVI, MOV, WEBM, MP3, WAV, FLAC, AACCanlı yüzde akışı, 00:00:00 Trim, Sesi KaldırFFmpeg Stream Engine
Arşiv & GüvenlikZIP, 7Z, TAR, GZ, RARZip Slip koruması, AES şifreli açma, @listfileRust Zip & 7-Zip CLI
+
+ + +
+
+
+
Güncel Kararlı Sürüm
+
LD Converter v3.6.4
+

+ Tauri v2 + Rust mimarisi, saf Rust OMML denklem & ofis motoru, Explorer sağ tık menüsü ve GPU ivmesiyle sıfır hata onaylı Windows 10/11 masaüstü paketi. +

+ +
+ SHA-256: 1A5E0BC161A0645578FDF2A12D7A4CD9D5C0B394692DDF386D0D704A605D5CB3 +
+
+
+
+
SİSTEM GEREKSİNİMLERİ
+
    +
  • Windows 10 / Windows 11 (x64)
  • +
  • WebView2 Runtime (Sistemle hazır gelir)
  • +
  • Kurulum boyutu: ~8.3 MB (Tauri v2 + Saf Rust Çekirdeği)
  • +
  • Dahili Rust Motoru: Pandoc/Python gerekmez, cjxl/djxl gömülü
  • +
+
+
+
+
+ + + + diff --git a/src-tauri/.cargo/config.toml b/src-tauri/.cargo/config.toml new file mode 100644 index 0000000..285c22f --- /dev/null +++ b/src-tauri/.cargo/config.toml @@ -0,0 +1,5 @@ +[build] +# Proje yolu boşluk içerdiği için derleme çıktısı ayrı bir dizine alınır +# (windres/cc boşluklu yolda hata verir). +target-dir = "C:/Users/lildosto/target_ld" +rustflags = ["-C", "link-arg=C:/Users/lildosto/target_ld/comctl6.o"] diff --git a/src-tauri/.gitignore b/src-tauri/.gitignore new file mode 100644 index 0000000..502406b --- /dev/null +++ b/src-tauri/.gitignore @@ -0,0 +1,4 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ +/gen/schemas diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock new file mode 100644 index 0000000..14dc52e --- /dev/null +++ b/src-tauri/Cargo.lock @@ -0,0 +1,7107 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher 0.4.4", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher 0.5.2", + "cpubits", + "cpufeatures 0.3.1", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "aliasable" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd" + +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib 2.0.4", +] + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib 3.0.0", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "allsorts-azul" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab097a7be305dd66b2b6917f5efb6b723129ce4b2cd11aa1a0afcc293c7dc08e" +dependencies = [ + "bitflags 2.13.2", + "brotli-decompressor 5.0.3", + "encoding_rs", + "enumflags2", + "flate2", + "glyph-names", + "log", + "ouroboros", + "pathfinder_geometry", + "rustc-hash", + "tinyvec", + "ucd-trie", + "unicode-canonical-combining-class", + "unicode-general-category", + "unicode-joining-type", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "atk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" +dependencies = [ + "atk-sys", + "glib", + "libc", +] + +[[package]] +name = "atk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey", + "rayon", + "thiserror 2.0.21", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom 8.0.0", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "azul-core" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77fa7633a4f9f683b529723420e9c23081828d00b908472f0457a778b24d8e4c" +dependencies = [ + "azul-css", + "gl-context-loader", + "libm", + "rust-fontconfig", +] + +[[package]] +name = "azul-css" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "093faf3f26d2164c3aa0cdf9891de966e5f813d3d964a027752bcafa03b355d2" +dependencies = [ + "azul-simplecss", + "libm", +] + +[[package]] +name = "azul-layout" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b390d8128afd50d0a07f3c9bc2481b1ff5298b809c73278c54f720f3bb8c23ae" +dependencies = [ + "allsorts-azul", + "azul-core", + "azul-css", + "base64 0.22.1", + "brotli-decompressor 5.0.3", + "hyphenation", + "lru 0.18.5", + "regex-lite", + "roxmltree 0.21.2", + "rust-fontconfig", + "serde", + "smallvec", + "taffy", + "thiserror 2.0.21", + "tinyvec", + "unicode-bidi", + "unicode-normalization", + "unicode-segmentation", + "xmlparser", + "xmlwriter", +] + +[[package]] +name = "azul-simplecss" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "beea02de84f7d4c090ccf9a2bddcd0595105b35c2ed0c9a0ed66aca4b79559bd" + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec 0.8.0", +] + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec 0.10.2", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bit-vec" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + +[[package]] +name = "brotli" +version = "9.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", + "brotli-decompressor 6.3.1", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib 2.0.4", + "alloc-stdlib 0.2.4", +] + +[[package]] +name = "brotli-decompressor" +version = "6.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", +] + +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "built" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + +[[package]] +name = "bzip2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" +dependencies = [ + "libbz2-rs-sys", +] + +[[package]] +name = "cairo-rs" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" +dependencies = [ + "bitflags 2.13.2", + "cairo-sys-rs", + "glib", + "libc", + "once_cell", + "thiserror 1.0.69", +] + +[[package]] +name = "cairo-sys-rs" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "camino" +version = "1.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" +dependencies = [ + "serde_core", +] + +[[package]] +name = "cargo-platform" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" +dependencies = [ + "serde", +] + +[[package]] +name = "cargo_metadata" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba" +dependencies = [ + "camino", + "cargo-platform", + "semver", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "cargo_toml" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9" +dependencies = [ + "semver", + "serde", + "toml 1.2.1+spec-1.1.0", +] + +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher 0.4.4", +] + +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher 0.5.2", +] + +[[package]] +name = "cc" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfb" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3" +dependencies = [ + "fnv", + "uuid", + "web-time", +] + +[[package]] +name = "cfg-expr" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +dependencies = [ + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout 0.1.4", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout 0.2.6", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "time", + "version_check", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "libc", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "cssparser" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf 0.13.1", + "smallvec", +] + +[[package]] +name = "cssparser" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11119743ad110e8c1bdccd930d7f5c30c99e5fc76a7b63ec9807e84eef0c5f59" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf 0.14.0", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" +dependencies = [ + "quote", + "syn 3.0.10", +] + +[[package]] +name = "ctor" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.10", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + +[[package]] +name = "dbus" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e" +dependencies = [ + "libc", + "libdbus-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", +] + +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys 0.4.1", +] + +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys 0.5.0", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users 0.4.6", + "windows-sys 0.48.0", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users 0.5.3", + "windows-sys 0.61.2", +] + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dlopen2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4" +dependencies = [ + "dlopen2_derive", + "libc", + "once_cell", + "winapi", +] + +[[package]] +name = "dlopen2_derive" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dom_query" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc" +dependencies = [ + "bit-set 0.8.0", + "cssparser 0.37.0", + "foldhash 0.2.0", + "html5ever 0.39.0", + "precomputed-hash", + "selectors 0.38.0", + "tendril", +] + +[[package]] +name = "dom_query" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498c698ac51127148a3984450e51fca7f01805a91d7a1f7a24af0a5f761e3385" +dependencies = [ + "bit-set 0.11.1", + "cssparser 0.38.0", + "foldhash 0.2.0", + "html5ever 0.40.1", + "precomputed-hash", + "selectors 0.41.0", + "tendril", +] + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +dependencies = [ + "serde", +] + +[[package]] +name = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "ecb" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26f2a8b3e564eba0877223dc343703ad0385794e882e6d13f3a4dd5c6b1f41ac" +dependencies = [ + "cipher 0.5.2", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "embed-resource" +version = "3.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f" +dependencies = [ + "cc", + "memchr", + "rustc_version", + "toml 1.2.1+spec-1.1.0", + "vswhom", + "winreg", +] + +[[package]] +name = "embed_plist" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "fontconfig-parser" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" +dependencies = [ + "roxmltree 0.20.0", +] + +[[package]] +name = "fontdb" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3a6f9af55fb97ad673fb7a69533eb2f967648a06fa21f8c9bb2cd6d33975716" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser 0.24.1", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fst" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ab85b9b05e3978cc9a9cf8fea7f01b494e1a09ed3037e16ba39edc7a29eb61a" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "g2gen" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5a7e0eb46f83a20260b850117d204366674e85d3a908d90865c78df9a6b1dfc" +dependencies = [ + "g2poly", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "g2p" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "539e2644c030d3bf4cd208cb842d2ce2f80e82e6e8472390bcef83ceba0d80ad" +dependencies = [ + "g2gen", + "g2poly", +] + +[[package]] +name = "g2poly" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "312d2295c7302019c395cfb90dacd00a82a2eabd700429bba9c7a3f38dbbe11b" + +[[package]] +name = "gdk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" +dependencies = [ + "cairo-rs", + "gdk-pixbuf", + "gdk-sys", + "gio", + "glib", + "libc", + "pango", +] + +[[package]] +name = "gdk-pixbuf" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" +dependencies = [ + "gdk-pixbuf-sys", + "gio", + "glib", + "libc", + "once_cell", +] + +[[package]] +name = "gdk-pixbuf-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gdk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkwayland-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" +dependencies = [ + "gdk-sys", + "glib-sys", + "gobject-sys", + "libc", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkx11" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe" +dependencies = [ + "gdk", + "gdkx11-sys", + "gio", + "glib", + "libc", + "x11", +] + +[[package]] +name = "gdkx11-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" +dependencies = [ + "gdk-sys", + "glib-sys", + "libc", + "system-deps", + "x11", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "gif" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b" +dependencies = [ + "color_quant", + "weezl 0.1.12", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl 0.1.12", +] + +[[package]] +name = "gio" +version = "0.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "gio-sys", + "glib", + "libc", + "once_cell", + "pin-project-lite", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "gio-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "winapi", +] + +[[package]] +name = "gl-context-loader" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca63cb2488b847c12d1ca56034ba0f15613972c0dc0f8a957f525707567b23d" + +[[package]] +name = "glib" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "once_cell", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "glib-macros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" +dependencies = [ + "heck 0.4.1", + "proc-macro-crate 2.0.2", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "glib-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" +dependencies = [ + "libc", + "system-deps", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "glyph-names" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3531d702d6c1a3ba92a5fb55a404c7b8c476c8e7ca249951077afcbe4bc807f" + +[[package]] +name = "gobject-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "grid" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b40ca9252762c466af32d0b1002e91e4e1bc5398f77455e55474deb466355ff5" + +[[package]] +name = "gtk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" +dependencies = [ + "atk", + "cairo-rs", + "field-offset", + "futures-channel", + "gdk", + "gdk-pixbuf", + "gio", + "glib", + "gtk-sys", + "gtk3-macros", + "libc", + "pango", + "pkg-config", +] + +[[package]] +name = "gtk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" +dependencies = [ + "atk-sys", + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "system-deps", +] + +[[package]] +name = "gtk3-macros" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" +dependencies = [ + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "html5ever" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" +dependencies = [ + "log", + "markup5ever 0.39.0", +] + +[[package]] +name = "html5ever" +version = "0.40.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456a1a377e608e555d22ddab27ac0114bc7a7b4199078108e34c2aeae6c9b130" +dependencies = [ + "log", + "markup5ever 0.40.0", + "memchr", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "hyphenation" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcf4dd4c44ae85155502a52c48739c8a48185d1449fff1963cffee63c28a50f0" +dependencies = [ + "bincode", + "fst", + "hyphenation_commons", + "pocket-resources", + "serde", +] + +[[package]] +name = "hyphenation_commons" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5febe7a2ade5c7d98eb8b75f946c046b335324b06a14ea0998271504134c05bf" +dependencies = [ + "fst", + "serde", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ico" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d75e94d66081e4d8dcd098bd8dc5254800fea14a26389b298410158d834de167" +dependencies = [ + "byteorder", + "png 0.18.1", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif 0.14.2", + "image-webp 0.2.4", + "moxcms", + "num-traits", + "png 0.18.1", + "ravif", + "rgb", + "tiff", + "zune-core 0.5.3", + "zune-jpeg 0.5.15", +] + +[[package]] +name = "image-webp" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f79afb8cbee2ef20f59ccd477a218c12a93943d075b492015ecb1bb81f8ee904" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imagesize" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285" + +[[package]] +name = "imgref" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "infer" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4" +dependencies = [ + "cfb", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding 0.3.3", + "generic-array", +] + +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "block-padding 0.4.2", + "hybrid-array", +] + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "javascriptcore-rs" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" +dependencies = [ + "bitflags 1.3.2", + "glib", + "javascriptcore-rs-sys", +] + +[[package]] +name = "javascriptcore-rs-sys" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "jiff" +version = "0.2.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffe6854081f5ac0a3046a9b223729ccd7a20b1e0e8277e44dc0660eedf67dfe2" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b4ff49b2887190c760b86207b55cdcaabbdecaf7a0660d68aa2ed6f652abf0a" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "json-patch" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" +dependencies = [ + "jsonptr", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "jsonptr" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "keyboard-types" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" +dependencies = [ + "bitflags 2.13.2", + "serde", +] + +[[package]] +name = "kurbo" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62" +dependencies = [ + "arrayvec", + "euclid", + "smallvec", +] + +[[package]] +name = "latex2mathml" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "678cf5bdb3ba63a264e6e0c9eee36538ca1d2da0afa4dd801c1f96309e710765" + +[[package]] +name = "ld-converter" +version = "3.6.4" +dependencies = [ + "chrono", + "crc32fast", + "dirs 5.0.1", + "flate2", + "image", + "latex2mathml", + "lopdf 0.33.0", + "printpdf", + "quick-xml 0.37.5", + "rayon", + "resvg", + "roxmltree 0.21.2", + "rqrr", + "serde", + "serde_json", + "sevenz-rust2", + "tauri", + "tauri-build", + "tauri-plugin-dialog", + "tauri-plugin-process", + "tauri-plugin-updater", + "thiserror 2.0.21", + "tiny-skia", + "tokio", + "ttf-parser 0.25.1", + "unicode-normalization", + "uuid", + "walkdir", + "windows", + "windows-core", + "windows-sys 0.61.2", + "zip 2.6.1", +] + +[[package]] +name = "libappindicator" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" +dependencies = [ + "glib", + "gtk", + "gtk-sys", + "libappindicator-sys", + "log", +] + +[[package]] +name = "libappindicator-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf" +dependencies = [ + "gtk-sys", + "libloading", + "once_cell", +] + +[[package]] +name = "libbz2-rs-sys" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32f454fd6831a29c0e827ed075bca2a15be201bd57f4168f0fd1041124eab17e" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libdbus-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" +dependencies = [ + "pkg-config", +] + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "linked-hash-map" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "lopdf" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c14afa083a906d49e1bda105ddbf8175016e2658954e6d0c3e612f886df3db" +dependencies = [ + "chrono", + "encoding_rs", + "flate2", + "indexmap 2.14.2", + "itoa", + "linked-hash-map", + "log", + "md-5 0.10.6", + "nom 7.1.3", + "rayon", + "time", + "weezl 0.1.12", +] + +[[package]] +name = "lopdf" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e2ec995d822e05cabc3f06d196ee43650af3fe4fe38012cacb35e0c3d113b68" +dependencies = [ + "aes 0.9.4", + "bitflags 2.13.2", + "cbc 0.2.1", + "ecb", + "encoding_rs", + "flate2", + "getrandom 0.4.3", + "indexmap 2.14.2", + "itoa", + "log", + "md-5 0.11.0", + "nom 8.0.0", + "rand 0.10.3", + "rangemap", + "sha2 0.11.1", + "stringprep", + "thiserror 2.0.21", + "weezl 0.2.1", +] + +[[package]] +name = "lru" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" + +[[package]] +name = "lzma-rust2" +version = "0.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca93e534d1142d1d0dcca6d25fe302508a5dfb40b302802904577725ea0b695b" + +[[package]] +name = "markup5ever" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" +dependencies = [ + "log", + "tendril", + "web_atoms 0.2.6", +] + +[[package]] +name = "markup5ever" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab3dc68ac4a0f5719e560136778c1ee716e296030d75dbd4484e37e39e3a842" +dependencies = [ + "log", + "tendril", + "web_atoms 0.3.0", +] + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest 0.10.7", +] + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "minisign-verify" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "mmapio" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0204e2cac68f5b2e35b7ec8cb5d906f6e58e78dad8066a30b6ee54da99bb03dd" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "muda" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996" +dependencies = [ + "crossbeam-channel", + "dpi", + "gtk", + "keyboard-types", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "once_cell", + "png 0.18.1", + "serde", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", + "objc2-exception-helper", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-core-foundation", + "objc2-foundation", + "objc2-quartz-core", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-location" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-exception-helper" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a" +dependencies = [ + "cc", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-osa-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-app-kit", + "objc2-foundation", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image", + "objc2-core-location", + "objc2-core-text", + "objc2-foundation", + "objc2-quartz-core", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-web-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "osakit" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b" +dependencies = [ + "objc2", + "objc2-foundation", + "objc2-osa-kit", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "ouroboros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0f050db9c44b97a94723127e6be766ac5c340c48f2c4bb3ffa11713744be59" +dependencies = [ + "aliasable", + "ouroboros_macro", + "static_assertions", +] + +[[package]] +name = "ouroboros_macro" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c7028bdd3d43083f6d8d4d5187680d0d3560d54df4cc9d752005268b41e64d0" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pango" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" +dependencies = [ + "gio", + "glib", + "libc", + "once_cell", + "pango-sys", +] + +[[package]] +name = "pango-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + +[[package]] +name = "pathfinder_geometry" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b7e7b4ea703700ce73ebf128e1450eb69c3a8329199ffbfb9b2a0418e5ad3" +dependencies = [ + "log", + "pathfinder_simd", +] + +[[package]] +name = "pathfinder_simd" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4500030c302e4af1d423f36f3b958d1aecb6c04184356ed5a833bf6b60435777" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros 0.13.1", + "phf_shared 0.13.1", + "serde", +] + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros 0.14.0", + "phf_shared 0.14.0", + "serde", +] + +[[package]] +name = "phf_codegen" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf_codegen" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared 0.14.0", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plist" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" +dependencies = [ + "base64 0.23.1", + "indexmap 2.14.2", + "quick-xml 0.42.0", + "serde", + "time", +] + +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "pocket-resources" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c135f38778ad324d9e9ee68690bac2c1a51f340fdf96ca13e2ab3914eb2e51d8" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppmd-rust" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd4acc8d264ea385db64ccfdcdfd5909ee9eda0975666723d59f3bfec80b3611" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "printpdf" +version = "0.12.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e8829ac96180b3c07de6a880766f9e0bbcbccd1869744a9d347ba0d830ae94" +dependencies = [ + "allsorts-azul", + "azul-core", + "azul-css", + "azul-layout", + "base64 0.22.1", + "flate2", + "getrandom 0.4.3", + "image", + "lopdf 0.44.0", + "rust-fontconfig", + "serde", + "serde_derive", + "serde_json", + "smallvec", + "time", + "wasm-bindgen", + "wasm-bindgen-futures", + "weezl 0.2.1", + "xmlparser", +] + +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + +[[package]] +name = "proc-macro-crate" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24" +dependencies = [ + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.19+spec-1.1.0", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "version_check", + "yansi", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.37.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb" +dependencies = [ + "memchr", +] + +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rangemap" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" + +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand 0.9.5", + "rand_chacha", + "simd_helpers", + "thiserror 2.0.21", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rgb", +] + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 1.0.69", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "resvg" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a325d5e8d1cebddd070b13f44cec8071594ab67d1012797c121f27a669b7958" +dependencies = [ + "gif 0.13.3", + "image-webp 0.1.3", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", + "zune-jpeg 0.4.21", +] + +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2", + "dispatch2", + "glib-sys", + "gobject-sys", + "gtk-sys", + "js-sys", + "libc", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "percent-encoding", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + +[[package]] +name = "rqrr" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48eaf9c75f2a8f231b09036c115a45a9845313f7faa6a39fa45a2a2bd06a27c7" +dependencies = [ + "g2p", + "image", + "lru 0.12.5", +] + +[[package]] +name = "rust-fontconfig" +version = "5.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5799956a5fa7abd968823c4d4876f2eb9301d5c02e2f53d0dc9471c001c782" +dependencies = [ + "allsorts-azul", + "mmapio", + "xmlparser", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni 0.22.4", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "rustybuzz" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c85d1ccd519e61834798eb52c4e886e8c2d7d698dd3d6ce0b1b47eb8557f1181" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "core_maths", + "log", + "smallvec", + "ttf-parser 0.24.1", + "unicode-bidi-mirroring", + "unicode-ccc", + "unicode-properties", + "unicode-script", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "indexmap 1.9.3", + "schemars_derive", + "serde", + "serde_json", + "url", + "uuid", +] + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.119", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "selectors" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d" +dependencies = [ + "bitflags 2.13.2", + "cssparser 0.37.0", + "derive_more", + "log", + "new_debug_unreachable", + "phf 0.13.1", + "phf_codegen 0.13.1", + "precomputed-hash", + "rustc-hash", + "servo_arc 0.4.3", + "smallvec", +] + +[[package]] +name = "selectors" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8322aebea94a6cc288ff884e8a49bdbceef60206c400c6c46d22e62fc4fd91a6" +dependencies = [ + "bitflags 2.13.2", + "cssparser 0.38.0", + "derive_more", + "log", + "new_debug_unreachable", + "precomputed-hash", + "rustc-hash", + "servo_arc 0.5.0", + "smallvec", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-untagged" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" +dependencies = [ + "erased-serde", + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_with" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" +dependencies = [ + "base64 0.23.1", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.2", + "jiff", + "schemars 0.9.0", + "schemars 1.2.3", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serialize-to-javascript" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5" +dependencies = [ + "serde", + "serde_json", + "serialize-to-javascript-impl", +] + +[[package]] +name = "serialize-to-javascript-impl" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "servo_arc" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "servo_arc" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4eceb519ec34d8290aaf6e46f435102f2bfa63f22b05a144fb16ab266d3b198" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "sevenz-rust2" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29225600349ef74beda5a9fffb36ac660a24613c0bde9315d0c49be1d51e9c24" +dependencies = [ + "aes 0.8.4", + "bzip2", + "cbc 0.1.2", + "crc32fast", + "getrandom 0.4.3", + "js-sys", + "lzma-rust2", + "ppmd-rust", + "sha2 0.10.9", + "wasm-bindgen", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "softbuffer" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" +dependencies = [ + "bytemuck", + "js-sys", + "ndk", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "objc2-quartz-core", + "raw-window-handle", + "redox_syscall", + "tracing", + "wasm-bindgen", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "soup3" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" +dependencies = [ + "futures-channel", + "gio", + "glib", + "libc", + "soup3-sys", +] + +[[package]] +name = "soup3-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "static_vcruntime" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff7589a1859b09232522bb9edf076ca7fcf14ded96685d3fa629db73023ffbb7" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + +[[package]] +name = "string_cache" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared 0.13.1", + "precomputed-hash", +] + +[[package]] +name = "string_cache" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffa8a5dbe8b3f0bbe29d4c3225daafaeead63afdc1b65fc4c01a1384166038e6" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared 0.14.0", + "precomputed-hash", +] + +[[package]] +name = "string_cache_codegen" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", +] + +[[package]] +name = "string_cache_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928dcdf75e47626b3617a976ec205d9f057584c371c1f23b782129268d0e6edc" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", + "proc-macro2", + "quote", +] + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "svgtypes" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc" +dependencies = [ + "kurbo", + "siphasher", +] + +[[package]] +name = "swift-rs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cefd87076fd385308ee4aff597256c902f1fbb4d031de1558efc12f8ffefadd9" +dependencies = [ + "base64 0.21.7", + "serde", + "serde_json", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "system-deps" +version = "6.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +dependencies = [ + "cfg-expr", + "heck 0.5.0", + "pkg-config", + "toml 0.8.2", + "version-compare", +] + +[[package]] +name = "taffy" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aea22054047c16c3f34d3ac473a2170be1424b1115b2a3adcf28cfb067c88859" +dependencies = [ + "arrayvec", + "grid", + "serde", + "slotmap", +] + +[[package]] +name = "tao" +version = "0.37.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5777b06fe6435126ae8d816eba269e050e1e10d302cf5461e9c49eccabc3548" +dependencies = [ + "bitflags 2.13.2", + "block2", + "core-foundation 0.10.1", + "core-graphics", + "crossbeam-channel", + "dbus", + "dispatch2", + "dlopen2", + "dpi", + "gdkwayland-sys", + "gdkx11-sys", + "gtk", + "jni 0.21.1", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "parking_lot", + "percent-encoding", + "raw-window-handle", + "tao-macros", + "unicode-segmentation", + "url", + "windows", + "windows-core", + "windows-version", + "x11-dl", +] + +[[package]] +name = "tao-macros" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + +[[package]] +name = "tauri" +version = "2.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fb0244332cfb9cee7e2a568bf5da29a36ed8fdbd717f6f47a66b6b7b358c072" +dependencies = [ + "anyhow", + "bytes", + "cookie", + "dirs 7.0.0", + "dunce", + "embed_plist", + "getrandom 0.3.4", + "glob", + "gtk", + "heck 0.5.0", + "http", + "jni 0.21.1", + "libc", + "log", + "mime", + "muda", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "objc2-web-kit", + "percent-encoding", + "plist", + "raw-window-handle", + "reqwest", + "serde", + "serde_json", + "serde_repr", + "serialize-to-javascript", + "swift-rs", + "tauri-build", + "tauri-macros", + "tauri-runtime", + "tauri-runtime-wry", + "tauri-utils", + "thiserror 2.0.21", + "tokio", + "tray-icon", + "url", + "webkit2gtk", + "webview2-com", + "window-vibrancy", + "windows", +] + +[[package]] +name = "tauri-build" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adddb0e648752aaac5da9c3c3c6a68e1e87cab55e3b757b18a9441ef8c3ac614" +dependencies = [ + "anyhow", + "cargo_toml", + "dirs 7.0.0", + "glob", + "heck 0.5.0", + "json-patch", + "schemars 0.8.22", + "semver", + "serde", + "serde_json", + "static_vcruntime", + "strsim", + "tauri-utils", + "tauri-winres", + "walkdir", +] + +[[package]] +name = "tauri-codegen" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb37631cf71dab5e8ab55e1bdd701e18a52653d90b78e71d0e5598b1e0a61316" +dependencies = [ + "base64 0.23.1", + "brotli", + "ico", + "json-patch", + "plist", + "png 0.18.1", + "proc-macro2", + "quote", + "semver", + "serde", + "serde_json", + "sha2 0.10.9", + "syn 2.0.119", + "tauri-utils", + "thiserror 2.0.21", + "time", + "url", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-macros" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc38db58854c10fb5f91a887ed8bf82d3239bb92b5d8db86eda09e96d9963d1" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", + "tauri-codegen", + "tauri-utils", +] + +[[package]] +name = "tauri-plugin" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67fb21a77e8f94e8beb3325e583102488659365af0a3948b7ea244c5b779c291" +dependencies = [ + "anyhow", + "glob", + "plist", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri-utils", + "walkdir", +] + +[[package]] +name = "tauri-plugin-dialog" +version = "2.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce0fb9c2b6d34a9720627ed930ebc8af26f61e648695aecaeb03d5c33c5896f5" +dependencies = [ + "log", + "raw-window-handle", + "rfd", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "tauri-plugin-fs", + "thiserror 2.0.21", + "url", +] + +[[package]] +name = "tauri-plugin-fs" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d58eb1d4984e535f47a642ffec09a2da6f5c18a12b5902d12126cb7626d628b" +dependencies = [ + "anyhow", + "dunce", + "glob", + "log", + "objc2-foundation", + "percent-encoding", + "schemars 0.8.22", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "tauri-utils", + "thiserror 2.0.21", + "toml 1.2.1+spec-1.1.0", + "url", +] + +[[package]] +name = "tauri-plugin-process" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74ae3d8549ae564c0397377373e262f340908eb23a5b9fbe03f2a00007dc0038" +dependencies = [ + "tauri", + "tauri-plugin", +] + +[[package]] +name = "tauri-plugin-updater" +version = "2.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d957abbcb3f9f6c76d22a3a0f012f30880640d0bccb5634d2b12a9937e4c872b" +dependencies = [ + "base64 0.23.1", + "dirs 7.0.0", + "flate2", + "futures-util", + "http", + "infer", + "libc", + "log", + "minisign-verify", + "osakit", + "percent-encoding", + "reqwest", + "rustls", + "semver", + "serde", + "serde_json", + "tar", + "tauri", + "tauri-plugin", + "tempfile", + "thiserror 2.0.21", + "time", + "tokio", + "url", + "windows-sys 0.61.2", + "zip 9.5.1", +] + +[[package]] +name = "tauri-runtime" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c55766d99cea69055904d1735b93c2049302b2e09effd462120deb5581d78e9" +dependencies = [ + "cookie", + "dpi", + "gtk", + "http", + "jni 0.21.1", + "objc2", + "objc2-ui-kit", + "objc2-web-kit", + "raw-window-handle", + "serde", + "serde_json", + "tauri-utils", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webview2-com", + "windows", +] + +[[package]] +name = "tauri-runtime-wry" +version = "2.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f" +dependencies = [ + "gtk", + "http", + "jni 0.21.1", + "log", + "objc2", + "objc2-app-kit", + "percent-encoding", + "raw-window-handle", + "softbuffer", + "tao", + "tauri-runtime", + "tauri-utils", + "url", + "webkit2gtk", + "webview2-com", + "windows", + "wry", +] + +[[package]] +name = "tauri-utils" +version = "2.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3" +dependencies = [ + "anyhow", + "brotli", + "cargo_metadata", + "ctor", + "dom_query 0.28.0", + "dunce", + "glob", + "http", + "infer", + "json-patch", + "log", + "memchr", + "phf 0.13.1", + "plist", + "proc-macro2", + "quote", + "regex", + "schemars 0.8.22", + "semver", + "serde", + "serde-untagged", + "serde_json", + "serde_with", + "swift-rs", + "thiserror 2.0.21", + "toml 1.2.1+spec-1.1.0", + "url", + "urlpattern", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-winres" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c52bb6904475a6ca662f15ef787f18ade61d5740a1ee12c45d3b748efdb6f796" +dependencies = [ + "dunce", + "embed-resource", + "toml 1.2.1+spec-1.1.0", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "tendril" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" +dependencies = [ + "new_debug_unreachable", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl 0.1.12", + "zune-jpeg 0.5.15", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png 0.17.16", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "toml" +version = "1.2.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +dependencies = [ + "indexmap 2.14.2", + "serde_core", + "serde_spanned 1.1.3", + "toml_datetime 1.1.3+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.5", +] + +[[package]] +name = "toml_datetime" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap 2.14.2", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" +dependencies = [ + "indexmap 2.14.2", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap 2.14.2", + "toml_datetime 1.1.3+spec-1.1.0", + "toml_parser", + "winnow 1.0.5", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tray-icon" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" +dependencies = [ + "crossbeam-channel", + "dirs 7.0.0", + "libappindicator", + "muda", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "once_cell", + "png 0.18.1", + "serde", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "ttf-parser" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be21190ff5d38e8b4a2d3b6a3ae57f612cc39c96e83cedeaf7abc338a8bac4a" +dependencies = [ + "core_maths", +] + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-bidi-mirroring" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64af057ad7466495ca113126be61838d8af947f41d93a949980b2389a118082f" + +[[package]] +name = "unicode-canonical-combining-class" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41c99d5174052d02ce765418e826597a1be18f32c114e35d9e22f92390239561" + +[[package]] +name = "unicode-ccc" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "260bc6647b3893a9a90668360803a15f96b85a5257b1c3a0c3daf6ae2496de42" + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-joining-type" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8d00a78170970967fdb83f9d49b92f959ab2bb829186b113e4f4604ad98e180" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + +[[package]] +name = "unicode-script" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-vo" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "urlpattern" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b" +dependencies = [ + "icu_properties", + "regex", + "serde", + "url", +] + +[[package]] +name = "usvg" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7447e703d7223b067607655e625e0dbca80822880248937da65966194c4864e6" +dependencies = [ + "base64 0.22.1", + "data-url", + "flate2", + "fontdb", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree 0.20.0", + "rustybuzz", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.29.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vswhom" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" +dependencies = [ + "libc", + "vswhom-sys", +] + +[[package]] +name = "vswhom-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web_atoms" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3" +dependencies = [ + "phf 0.13.1", + "phf_codegen 0.13.1", + "string_cache 0.9.0", + "string_cache_codegen 0.6.1", +] + +[[package]] +name = "web_atoms" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7572660c8890448ba236b7376f27e389c6a7e1c70195622faced601f855c0ada" +dependencies = [ + "phf 0.14.0", + "phf_codegen 0.14.0", + "string_cache 0.11.0", + "string_cache_codegen 0.11.2", +] + +[[package]] +name = "webkit2gtk" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793" +dependencies = [ + "bitflags 1.3.2", + "cairo-rs", + "gdk", + "gdk-sys", + "gio", + "gio-sys", + "glib", + "glib-sys", + "gobject-sys", + "gtk", + "gtk-sys", + "javascriptcore-rs", + "libc", + "once_cell", + "soup3", + "webkit2gtk-sys", +] + +[[package]] +name = "webkit2gtk-sys" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5" +dependencies = [ + "bitflags 1.3.2", + "cairo-sys-rs", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "gtk-sys", + "javascriptcore-rs-sys", + "libc", + "pkg-config", + "soup3-sys", + "system-deps", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webview2-com" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6" +dependencies = [ + "webview2-com-macros", + "webview2-com-sys", + "windows", + "windows-core", +] + +[[package]] +name = "webview2-com-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "webview2-com-sys" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb" +dependencies = [ + "thiserror 2.0.21", + "windows", + "windows-core", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "weezl" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "window-vibrancy" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580" +dependencies = [ + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "objc2-quartz-core", + "raw-window-handle", + "windows-sys 0.61.2", + "windows-version", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-version" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "winreg" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" +dependencies = [ + "cfg-if", + "windows-sys 0.61.2", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "wry" +version = "0.57.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a490119196d02a51d0871df7b9119a1f3e46d75b7e90053a801454d5c6b3491c" +dependencies = [ + "base64 0.23.1", + "block2", + "cookie", + "crossbeam-channel", + "dirs 7.0.0", + "dom_query 0.29.0", + "dpi", + "dunce", + "gdkx11", + "gtk", + "http", + "javascriptcore-rs", + "jni 0.21.1", + "libc", + "ndk", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "objc2-ui-kit", + "objc2-web-kit", + "percent-encoding", + "raw-window-handle", + "sha2 0.10.9", + "soup3", + "tao-macros", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webkit2gtk-sys", + "webview2-com", + "windows", + "windows-core", + "windows-version", + "x11-dl", +] + +[[package]] +name = "x11" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "xattr" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08" +dependencies = [ + "libc", + "rustix", +] + +[[package]] +name = "xmlparser" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" + +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zip" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" +dependencies = [ + "arbitrary", + "crc32fast", + "crossbeam-utils", + "flate2", + "indexmap 2.14.2", + "memchr", + "time", + "zopfli", +] + +[[package]] +name = "zip" +version = "9.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302" +dependencies = [ + "constant_time_eq", + "crc32fast", + "getrandom 0.4.3", + "indexmap 2.14.2", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zeroize", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + +[[package]] +name = "zune-core" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" +dependencies = [ + "zune-core 0.4.12", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core 0.5.3", +] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml new file mode 100644 index 0000000..7582d49 --- /dev/null +++ b/src-tauri/Cargo.toml @@ -0,0 +1,56 @@ +[package] +name = "ld-converter" +version = "3.6.4" +description = "Next-Gen High Performance Desktop Converter" +authors = ["LilDosto"] +license = "MIT" +edition = "2021" + +[lib] +name = "app_lib" +crate-type = ["staticlib", "rlib"] + +[build-dependencies] +tauri-build = { version = "2.7.4", features = [] } + +[dependencies] +tauri = { version = "2.12.5", features = ["tray-icon"] } +tauri-plugin-dialog = "2" +tauri-plugin-updater = "2" +tauri-plugin-process = "2" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +thiserror = "2.0" +tokio = { version = "1", features = ["full"] } +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "bmp", "tiff", "ico", "gif", "avif"] } +lopdf = "0.33" +zip = { version = "2", default-features = false, features = ["deflate", "time"] } +walkdir = "2" +uuid = { version = "1", features = ["v4"] } +chrono = { version = "0.4", features = ["serde"] } +dirs = "5" +rqrr = "0.8" +printpdf = { version = "0.12.9", features = ["png", "jpeg", "gif"] } +roxmltree = "0.21.2" +quick-xml = "0.37" +latex2mathml = "0.2" +resvg = "0.44" +tiny-skia = "0.11" +flate2 = "1.1" +crc32fast = "1.5" +rayon = "1.10" +sevenz-rust2 = "0.20" +ttf-parser = "0.25.1" +unicode-normalization = "0.1" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging", "Win32_System_Threading", "Win32_Foundation", "Win32_Graphics_Gdi"] } +windows = { version = "0.62", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Variant", "Win32_Graphics_Imaging", "Win32_UI_Shell", "Data_Pdf", "Storage", "Storage_Streams"] } +windows-core = "0.62" + +[profile.release] +lto = "thin" +strip = "symbols" +opt-level = 3 +codegen-units = 1 +panic = "abort" diff --git a/src-tauri/WebView2Loader.dll b/src-tauri/WebView2Loader.dll new file mode 100644 index 0000000..bc1bb74 Binary files /dev/null and b/src-tauri/WebView2Loader.dll differ diff --git a/src-tauri/build.rs b/src-tauri/build.rs new file mode 100644 index 0000000..458feb3 --- /dev/null +++ b/src-tauri/build.rs @@ -0,0 +1,10 @@ +fn main() { + // Özel uygulama manifesti comctl6.o içinde geliyor (aşağıdaki .cargo/config.toml). + // Tauri'nin kendi manifestini de eklersek "multiple non-default manifests" hatası oluşur. + let windows = tauri_build::WindowsAttributes::new_without_app_manifest(); + if let Err(e) = tauri_build::try_build( + tauri_build::Attributes::new().windows_attributes(windows), + ) { + eprintln!("tauri-build error: {e}"); + } +} diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json new file mode 100644 index 0000000..b50c89b --- /dev/null +++ b/src-tauri/capabilities/default.json @@ -0,0 +1,20 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "default", + "description": "enables the default permissions for LD Converter", + "windows": [ + "main" + ], + "permissions": [ + "core:default", + "core:window:allow-start-dragging", + "core:window:allow-minimize", + "core:window:allow-toggle-maximize", + "core:window:allow-close", + "core:window:allow-hide", + "core:window:allow-show", + "dialog:default", + "updater:default", + "process:default" + ] +} diff --git a/src-tauri/icons/128x128.png b/src-tauri/icons/128x128.png new file mode 100644 index 0000000..ad3ef3a Binary files /dev/null and b/src-tauri/icons/128x128.png differ diff --git a/src-tauri/icons/128x128@2x.png b/src-tauri/icons/128x128@2x.png new file mode 100644 index 0000000..88365bd Binary files /dev/null and b/src-tauri/icons/128x128@2x.png differ diff --git a/src-tauri/icons/32x32.png b/src-tauri/icons/32x32.png new file mode 100644 index 0000000..2a8b646 Binary files /dev/null and b/src-tauri/icons/32x32.png differ diff --git a/src-tauri/icons/64x64.png b/src-tauri/icons/64x64.png new file mode 100644 index 0000000..a35707c Binary files /dev/null and b/src-tauri/icons/64x64.png differ diff --git a/src-tauri/icons/Square107x107Logo.png b/src-tauri/icons/Square107x107Logo.png new file mode 100644 index 0000000..8bb5b31 Binary files /dev/null and b/src-tauri/icons/Square107x107Logo.png differ diff --git a/src-tauri/icons/Square142x142Logo.png b/src-tauri/icons/Square142x142Logo.png new file mode 100644 index 0000000..9990431 Binary files /dev/null and b/src-tauri/icons/Square142x142Logo.png differ diff --git a/src-tauri/icons/Square150x150Logo.png b/src-tauri/icons/Square150x150Logo.png new file mode 100644 index 0000000..df64777 Binary files /dev/null and b/src-tauri/icons/Square150x150Logo.png differ diff --git a/src-tauri/icons/Square284x284Logo.png b/src-tauri/icons/Square284x284Logo.png new file mode 100644 index 0000000..13b7601 Binary files /dev/null and b/src-tauri/icons/Square284x284Logo.png differ diff --git a/src-tauri/icons/Square30x30Logo.png b/src-tauri/icons/Square30x30Logo.png new file mode 100644 index 0000000..656ad23 Binary files /dev/null and b/src-tauri/icons/Square30x30Logo.png differ diff --git a/src-tauri/icons/Square310x310Logo.png b/src-tauri/icons/Square310x310Logo.png new file mode 100644 index 0000000..4084a68 Binary files /dev/null and b/src-tauri/icons/Square310x310Logo.png differ diff --git a/src-tauri/icons/Square44x44Logo.png b/src-tauri/icons/Square44x44Logo.png new file mode 100644 index 0000000..93aef91 Binary files /dev/null and b/src-tauri/icons/Square44x44Logo.png differ diff --git a/src-tauri/icons/Square71x71Logo.png b/src-tauri/icons/Square71x71Logo.png new file mode 100644 index 0000000..55468d3 Binary files /dev/null and b/src-tauri/icons/Square71x71Logo.png differ diff --git a/src-tauri/icons/Square89x89Logo.png b/src-tauri/icons/Square89x89Logo.png new file mode 100644 index 0000000..157e68c Binary files /dev/null and b/src-tauri/icons/Square89x89Logo.png differ diff --git a/src-tauri/icons/StoreLogo.png b/src-tauri/icons/StoreLogo.png new file mode 100644 index 0000000..f05f750 Binary files /dev/null and b/src-tauri/icons/StoreLogo.png differ diff --git a/src-tauri/icons/icon.icns b/src-tauri/icons/icon.icns new file mode 100644 index 0000000..cd4a7fa Binary files /dev/null and b/src-tauri/icons/icon.icns differ diff --git a/src-tauri/icons/icon.ico b/src-tauri/icons/icon.ico new file mode 100644 index 0000000..4bc4cc1 Binary files /dev/null and b/src-tauri/icons/icon.ico differ diff --git a/src-tauri/icons/icon.png b/src-tauri/icons/icon.png new file mode 100644 index 0000000..ad07ded Binary files /dev/null and b/src-tauri/icons/icon.png differ diff --git a/src-tauri/src/catalog/mod.rs b/src-tauri/src/catalog/mod.rs new file mode 100644 index 0000000..bc8a379 --- /dev/null +++ b/src-tauri/src/catalog/mod.rs @@ -0,0 +1,264 @@ +use std::collections::HashSet; +use std::path::Path; + +use crate::models::ToolChoice; + +pub struct FormatCatalog; + +impl FormatCatalog { + pub fn image_extensions() -> &'static [&'static str] { + &[ + "jpg", "jpeg", "png", "webp", "avif", "jxl", "jpegxl", "bmp", "tiff", "tif", "gif", + "ico", "svg", "heic", "heif", "cr2", "nef", "arw", + ] + } + + pub fn video_extensions() -> &'static [&'static str] { + &["mp4", "mkv", "avi", "mov", "webm", "flv", "wmv", "m4v"] + } + + pub fn audio_extensions() -> &'static [&'static str] { + &["mp3", "wav", "aac", "m4a", "flac", "ogg", "opus", "wma"] + } + + pub fn document_extensions() -> &'static [&'static str] { + &[ + "docx", "doc", "pptx", "ppt", "xlsx", "xls", "odt", "rtf", "txt", "md", "markdown", + "html", "htm", "epub", "pdf", + ] + } + + pub fn archive_extensions() -> &'static [&'static str] { + &["zip", "7z", "tar", "gz", "tgz", "rar"] + } + + pub fn normalize_extension(file_path: &str) -> String { + let p = Path::new(file_path); + if p.is_dir() { + return "folder".to_string(); + } + match p.extension().and_then(|e| e.to_str()).map(|s| s.to_lowercase()) { + Some(ext) => match ext.as_str() { + "jpeg" | "jpe" => "jpg".to_string(), + "jpegxl" => "jxl".to_string(), + "heif" => "heic".to_string(), + "markdown" => "md".to_string(), + "tgz" => "gz".to_string(), + "htm" => "html".to_string(), + "tif" => "tiff".to_string(), + _ => ext, + }, + None => String::new(), + } + } + + pub fn is_image(file_path: &str) -> bool { + let ext = Self::normalize_extension(file_path); + Self::image_extensions().contains(&ext.as_str()) + } + + pub fn is_video(file_path: &str) -> bool { + let ext = Self::normalize_extension(file_path); + Self::video_extensions().contains(&ext.as_str()) + } + + pub fn is_audio(file_path: &str) -> bool { + let ext = Self::normalize_extension(file_path); + Self::audio_extensions().contains(&ext.as_str()) + } + + pub fn is_pdf(file_path: &str) -> bool { + Self::normalize_extension(file_path) == "pdf" + } + + pub fn is_markdown(file_path: &str) -> bool { + Self::normalize_extension(file_path) == "md" + } + + pub fn is_document(file_path: &str) -> bool { + let ext = Self::normalize_extension(file_path); + Self::document_extensions().contains(&ext.as_str()) + } + + pub fn is_archive(file_path: &str) -> bool { + let ext = Self::normalize_extension(file_path); + Self::archive_extensions().contains(&ext.as_str()) + } + + pub fn get_choices_for_files( + files: &[String], + hidden_format_ids: Option<&[String]>, + jxl_supported: bool, + ) -> Vec { + let mut raw = Self::build_choices_core(files); + + // JPEG XL desteği olmayan sistemlerde seçenek hiç sunulmaz + if !jxl_supported { + raw.retain(|c| c.id != "jxl" && c.id != "pdf_to_jxl"); + } + + if let Some(hidden) = hidden_format_ids { + if !hidden.is_empty() { + let hidden_set: HashSet<&str> = hidden.iter().map(|s| s.as_str()).collect(); + let filtered: Vec = raw + .iter() + .filter(|c| !hidden_set.contains(c.id.as_str())) + .cloned() + .collect(); + if filtered.len() >= 2 { + return filtered; + } + } + } + raw + } + + fn build_choices_core(files: &[String]) -> Vec { + if files.is_empty() { + return Self::get_default_choices(); + } + + let any_dirs = files.iter().any(|f| Path::new(f).is_dir()); + if any_dirs { + return vec![ + ToolChoice::new("zip", "ZIP Arşivi", "Arşiv", "Archive", "Seçili klasör ve dosyaları ZIP yap"), + ToolChoice::new("7z", "7Z Arşivi", "Arşiv", "Archive", "Ultra sıkıştırma ile 7Z arşivi oluştur"), + ToolChoice::new("tar_gz", "TAR.GZ Yap", "Arşiv", "Archive", "Linux uyumlu .tar.gz paketi oluştur"), + ToolChoice::new("copy_folder", "Yeni Klasöre Topla", "Dosya", "Folder", "İçeriği yeni bir klasörde topla"), + ]; + } + + let all_images = files.iter().all(|f| Self::is_image(f)); + let all_videos = files.iter().all(|f| Self::is_video(f)); + let all_audios = files.iter().all(|f| Self::is_audio(f)); + let all_pdfs = files.iter().all(|f| Self::is_pdf(f)); + let all_docs = files.iter().all(|f| Self::is_document(f)); + let all_archives = files.iter().all(|f| Self::is_archive(f)); + + if all_images { + let mut list = vec![ + ToolChoice::new("png", "PNG", "Görsel", "Image", "Kayıpsız PNG formatına dönüştür"), + ToolChoice::new("jpg", "JPG", "Görsel", "Image", "Yüksek uyumlu JPG formatına dönüştür"), + ToolChoice::new("webp", "WebP", "Görsel", "Globe", "Modern, hafif WebP formatına dönüştür"), + ToolChoice::new("jxl", "JPEG XL (JXL)", "Görsel", "Sparkles", "Yeni nesil ultra verimli JPEG XL"), + ToolChoice::new("avif", "AVIF", "Görsel", "Sparkles", "Yeni nesil sıkıştırılmış AVIF formatı"), + ToolChoice::new("bmp", "BMP", "Görsel", "Image", "Sıkıştırmasız Bitmap formatı"), + ToolChoice::new("tiff", "TIFF", "Görsel", "Image", "Baskı ve arşiv için TIFF formatı"), + ToolChoice::new("ico", "ICO (İkon)", "Görsel", "Folder", "Windows uygulama simgesi (.ico) yap"), + ToolChoice::new("pdf", "PDF", "Belge", "FileText", "Görsellerden tek PDF belgesi oluştur"), + ToolChoice::new("img_to_txt", "Metin Çıkar (OCR)", "Belge", "FileText", "Görseldeki yazıları OCR ile metne (.txt) çevir"), + ToolChoice::new("img_to_docx", "Word Yap (OCR)", "Belge", "FileText", "Görseldeki yazıları OCR ile Word (.docx) belgesine çevir"), + ]; + + if files.len() == 1 { + list.push(ToolChoice::new("qr_read", "QR Kod Oku", "Araç", "QrCode", "Görseldeki QR kodu tara ve çöz")); + list.push(ToolChoice::new("compress_image", "Sıkıştır", "Optimizasyon", "Minimize2", "Kalite kaybı olmadan boyutu küçült")); + } else { + list.push(ToolChoice::new("gif", "Animasyonlu GIF", "Görsel", "Sparkles", "Görsellerden hareketli GIF oluştur")); + list.push(ToolChoice::new("zip", "ZIP Arşivi", "Arşiv", "Archive", "Tüm görselleri tek ZIP dosyası yap")); + list.push(ToolChoice::new("compress_image", "Hepsini Sıkıştır", "Optimizasyon", "Minimize2", "Tüm görselleri optimize et")); + } + return list; + } + + if all_pdfs { + let mut list = vec![ + ToolChoice::new("pdf_to_docx", "DOCX", "Belge", "FileText", "PDF belgesini standart Word belgesine dönüştür"), + ToolChoice::new("pdf_to_math_docx", "Denklem DOCX", "Belge", "FunctionSquare", "PDF matematik formüllerini düzenlenebilir Word denklemine (OMML) aktar"), + ToolChoice::new("pdf_to_images", "Sayfaları PNG Yap", "Görsel", "Image", "PDF sayfalarını yüksek çözünürlüklü PNG'ye aktar"), + ToolChoice::new("pdf_to_jpg", "Sayfaları JPG Yap", "Görsel", "Image", "PDF sayfalarını JPG resimleri olarak kaydet"), + ToolChoice::new("pdf_to_jxl", "Sayfaları JXL Yap", "Görsel", "Sparkles", "PDF sayfalarını JPEG XL formatında kaydet"), + ToolChoice::new("pdf_to_txt", "Metin Çıkar (TXT)", "Belge", "FileText", "PDF içindeki tüm metinleri TXT olarak kaydet"), + ToolChoice::new("qr_read", "QR Oku", "Araç", "QrCode", "PDF sayfalarındaki QR kodları tara"), + ]; + + if files.len() > 1 { + list.insert(0, ToolChoice::new("pdf_merge", "PDF'leri Birleştir", "Belge", "Layers", "Tüm PDF'leri tek bir dosyada birleştir")); + } else { + list.push(ToolChoice::new("pdf_split", "Sayfaları Ayır", "Belge", "Scissors", "Her sayfayı ayrı PDF yap veya sayfa aralığı seç")); + } + list.push(ToolChoice::new( + "pdf_compress", + "PDF Sıkıştır", + "Optimizasyon", + "Minimize2", + "Görselleri optimize ederek PDF boyutunu küçült ve kısıtlamaları kaldır", + )); + list.push(ToolChoice::new("zip", "ZIP Arşivi", "Arşiv", "Archive", "PDF'leri ZIP olarak arşivle")); + return list; + } + + if all_docs { + let any_markdown = files.iter().any(|f| Self::is_markdown(f)); + let mut list = vec![ + ToolChoice::new("pdf", "PDF Yap", "Belge", "FileText", "Belgeyi PDF formatına dönüştür"), + ToolChoice::new("docx", "DOCX Yap", "Belge", "FileText", "Modern Word belgesine çevir"), + ]; + + if any_markdown { + list.push(ToolChoice::new( + "docx_math", + "Denklem DOCX", + "Belge", + "FunctionSquare", + "Markdown LaTeX ($...$, $$...$$) formüllerini düzenlenebilir Word denklemine (OMML) dönüştür", + )); + } + + list.push(ToolChoice::new("txt", "Düz Metin (TXT)", "Belge", "FileText", "Yalnızca metin içeriğini kaydet")); + list.push(ToolChoice::new("html", "HTML Web", "Belge", "Globe", "Web formatında HTML çıktısı al")); + list.push(ToolChoice::new("zip", "ZIP Paketle", "Arşiv", "Archive", "Belgeleri sıkıştırılmış ZIP yap")); + return list; + } + + if all_videos { + return vec![ + ToolChoice::new("mp4", "MP4 Yap", "Video", "Video", "Evrensel MP4 (H.264 / AAC) dönüştür"), + ToolChoice::new("mp3", "Sesi MP3 Yap", "Ses", "Music", "Videodan sesi ayırıp MP3 olarak kaydet"), + ToolChoice::new("gif", "Animasyonlu GIF", "Görsel", "Sparkles", "Videoyu hafif ve canlı GIF yap"), + ToolChoice::new("webm", "WebM Yap", "Video", "Globe", "Web uyumlu VP9/WebM formatına dönüştür"), + ToolChoice::new("mkv", "MKV Yap", "Video", "Video", "Yüksek kaliteli MKV konteyneri"), + ToolChoice::new("compress_video", "Video Sıkıştır", "Optimizasyon", "Minimize2", "Kaliteyi koruyarak dosya boyutunu düşür"), + ]; + } + + if all_audios { + return vec![ + ToolChoice::new("mp3", "MP3 Yap", "Ses", "Music", "Yüksek uyumlu 192kbps MP3"), + ToolChoice::new("wav", "WAV Yap", "Ses", "Music", "Kayıpsız stüdyo WAV formatı"), + ToolChoice::new("aac", "AAC / M4A", "Ses", "Music", "Modern yüksek kaliteli AAC"), + ToolChoice::new("flac", "FLAC Yap", "Ses", "Music", "Kayıpsız FLAC sıkıştırması"), + ToolChoice::new("ogg", "OGG Vorbis", "Ses", "Music", "Açık kaynak OGG formatı"), + ToolChoice::new("compress_audio", "Sesi Sıkıştır", "Optimizasyon", "Minimize2", "Ses boyutunu küçült"), + ]; + } + + if all_archives { + return vec![ + ToolChoice::new("extract_folder", "Klasöre Çıkar", "Arşiv", "FolderOpen", "Arşiv içeriğini klasöre çıkar"), + ToolChoice::new("zip", "ZIP Formatına Çevir", "Arşiv", "Archive", "Arşivi standart ZIP yap"), + ToolChoice::new("7z", "7Z Formatına Çevir", "Arşiv", "Archive", "Ultra sıkıştırmalı 7-Zip yap"), + ToolChoice::new("tar_gz", "TAR.GZ Yap", "Arşiv", "Archive", "Linux uyumlu .tar.gz yap"), + ]; + } + + vec![ + ToolChoice::new("zip", "ZIP Arşivi Oluştur", "Arşiv", "Archive", "Tüm seçili dosyaları ZIP dosyasına topla"), + ToolChoice::new("7z", "7Z Arşivi Oluştur", "Arşiv", "Archive", "Ultra sıkıştırma ile 7Z arşivi oluştur"), + ToolChoice::new("tar_gz", "TAR.GZ Oluştur", "Arşiv", "Archive", "Dosyaları .tar.gz olarak arşivle"), + ToolChoice::new("pdf_merge", "Görsel & PDF Birleştir", "Belge", "Layers", "Desteklenen belgeleri tek PDF yap"), + ToolChoice::new("copy_folder", "Yeni Klasöre Topla", "Dosya", "Folder", "Dosyaları yeni bir klasörde topla"), + ] + } + + pub fn get_default_choices() -> Vec { + vec![ + ToolChoice::new("png", "PNG", "Görsel", "Image", "PNG dönüştür"), + ToolChoice::new("jpg", "JPG", "Görsel", "Image", "JPG dönüştür"), + ToolChoice::new("webp", "WebP", "Görsel", "Globe", "WebP dönüştür"), + ToolChoice::new("pdf", "PDF", "Belge", "FileText", "PDF oluştur"), + ToolChoice::new("mp3", "MP3", "Ses", "Music", "MP3 ses çıkar"), + ToolChoice::new("zip", "ZIP Arşivi", "Arşiv", "Archive", "Dosyaları ZIP arşivine sıkıştır"), + ] + } +} diff --git a/src-tauri/src/cli.rs b/src-tauri/src/cli.rs new file mode 100644 index 0000000..e50f533 --- /dev/null +++ b/src-tauri/src/cli.rs @@ -0,0 +1,121 @@ +//! Komut satırından dönüştürme (Explorer sağ tık menüsü için). +//! +//! Kullanım: `ld-converter.exe --convert ` +//! Arayüz açılmaz; sonuç bir mesaj penceresiyle bildirilir. + +use std::path::Path; + +use crate::error::AppError; +use crate::logging; +use crate::models::{AppPreferences, ConversionOptions}; +use crate::services::{ConversionDispatcher, ProgressEmitter}; +use crate::utils::message_box; + +fn parse(args: &[String]) -> Option<(String, Vec)> { + let index = args.iter().position(|arg| arg == "--convert")?; + let action = args.get(index + 1)?.clone(); + let files: Vec = args[index + 2..] + .iter() + .filter(|arg| !arg.starts_with("--")) + .cloned() + .collect(); + if files.is_empty() { + return None; + } + Some((action, files)) +} + +/// `--convert` işaretini işler. Komut satırı bu moddaysa süreç burada biter. +pub fn run(args: &[String]) -> i32 { + let silent = args.iter().any(|arg| arg == "--silent"); + let notify = |title: &str, message: &str, is_error: bool| { + if !silent { + message_box(title, message, is_error); + } + }; + + let Some((action, files)) = parse(args) else { + notify( + "LD Converter", + "Kullanım: ld-converter.exe --convert ", + true, + ); + return 2; + }; + + let existing: Vec = files + .into_iter() + .filter(|file| Path::new(file).exists()) + .collect(); + if existing.is_empty() { + notify("LD Converter", "Seçilen dosya bulunamadı.", true); + return 2; + } + + logging::info(&format!( + "Komut satırı dönüşümü: eylem={}, dosya={}", + action, + existing.len() + )); + + let runtime = match tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(err) => { + notify("LD Converter", &format!("Motor başlatılamadı: {}", err), true); + return 1; + } + }; + + let result = runtime.block_on(async { + ConversionDispatcher::execute_task( + ProgressEmitter::silent(), + existing.clone(), + action.clone(), + ConversionOptions::default(), + AppPreferences::default(), + std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + uuid::Uuid::new_v4().to_string(), + ) + .await + }); + + match result { + Ok(conversion) => { + logging::info(&format!( + "Komut satırı dönüşümü tamamlandı: {} çıktı", + conversion.output_files.len() + )); + let first = conversion + .output_files + .first() + .cloned() + .unwrap_or_default(); + let folder = Path::new(&first) + .parent() + .map(|path| path.display().to_string()) + .unwrap_or(first); + notify( + "LD Converter", + &format!( + "Dönüştürme tamamlandı.\n\n{} dosya oluşturuldu.\n\nKlasör:\n{}", + conversion.output_files.len(), + folder + ), + false, + ); + 0 + } + Err(err) => { + let text = match &err { + AppError::UnsupportedFormat(message) => message.clone(), + other => other.to_string(), + }; + logging::error(&format!("Komut satırı dönüşümü başarısız: {}", text)); + notify("LD Converter - Dönüştürme Hatası", &text, true); + 1 + } + } +} diff --git a/src-tauri/src/commands/catalog.rs b/src-tauri/src/commands/catalog.rs new file mode 100644 index 0000000..0138fe5 --- /dev/null +++ b/src-tauri/src/commands/catalog.rs @@ -0,0 +1,17 @@ +use crate::catalog::FormatCatalog; +use crate::error::AppResult; +use crate::models::ToolChoice; + +#[tauri::command] +pub async fn get_choices_for_files(files: Vec) -> AppResult> { + Ok(FormatCatalog::get_choices_for_files( + &files, + None, + crate::services::EngineResolver::jxl_available(), + )) +} + +#[tauri::command] +pub fn get_default_choices() -> AppResult> { + Ok(FormatCatalog::get_default_choices()) +} diff --git a/src-tauri/src/commands/conversion.rs b/src-tauri/src/commands/conversion.rs new file mode 100644 index 0000000..793df05 --- /dev/null +++ b/src-tauri/src/commands/conversion.rs @@ -0,0 +1,153 @@ +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use tauri::{AppHandle, State}; +use uuid::Uuid; + +use crate::error::AppResult; +use crate::models::{ConversionOptions, ConversionResult, HistoryEntry}; +use crate::services::ConversionDispatcher; +use crate::state::AppState; +use crate::utils::{friendly_action_label, total_size}; + +#[tauri::command] +pub async fn execute_conversion( + app_handle: AppHandle, + input_files: Vec, + target_action_id: String, + options: Option, + task_id: Option, + state: State<'_, AppState>, +) -> AppResult { + let task_id = task_id + .filter(|id| !id.trim().is_empty()) + .unwrap_or_else(|| Uuid::new_v4().to_string()); + let cancel_flag = Arc::new(AtomicBool::new(false)); + + { + let mut map = state.active_cancellations.write().await; + map.insert(task_id.clone(), cancel_flag.clone()); + } + + let prefs = { + let r = state.preferences.read().await; + r.clone() + }; + + let opts = options.unwrap_or_default(); + crate::logging::info(&format!( + "Dönüştürme başladı: eylem={}, dosya={}, görev={}", + target_action_id, + input_files.len(), + task_id + )); + let result = ConversionDispatcher::execute_task( + crate::services::ProgressEmitter(Some(app_handle)), + input_files.clone(), + target_action_id.clone(), + opts, + prefs, + cancel_flag, + task_id.clone(), + ) + .await; + + { + let mut map = state.active_cancellations.write().await; + map.remove(&task_id); + } + + let summary_title = if input_files.len() == 1 { + input_files + .first() + .map(|f| { + std::path::Path::new(f) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or(f) + .to_string() + }) + .unwrap_or_else(|| "Bilinmeyen Dosya".to_string()) + } else { + format!("{} dosya", input_files.len()) + }; + + let original_size: u64 = input_files.iter().map(|f| total_size(f)).sum(); + let output_size: u64 = match &result { + Ok(res) => res.output_files.iter().map(|f| total_size(f)).sum(), + Err(_) => 0, + }; + + let format_summary = friendly_action_label(&target_action_id); + + let (entry, res_return) = match &result { + Ok(res) => ( + HistoryEntry { + id: task_id, + title: summary_title, + format_summary, + input_files, + output_files: res.output_files.clone(), + original_size_bytes: original_size, + output_size_bytes: output_size, + timestamp: chrono::Utc::now(), + success: res.success, + error_message: None, + }, + result, + ), + Err(err) => ( + HistoryEntry { + id: task_id, + title: summary_title, + format_summary, + input_files, + output_files: Vec::new(), + original_size_bytes: original_size, + output_size_bytes: 0, + timestamp: chrono::Utc::now(), + success: false, + error_message: Some(err.to_string()), + }, + result, + ), + }; + + { + let mut hist = state.history.write().await; + hist.insert(0, entry); + if hist.len() > 100 { + hist.truncate(100); + } + AppState::save_history_to_disk(&hist); + } + + match &res_return { + Ok(res) => crate::logging::info(&format!( + "Dönüştürme tamamlandı: eylem={}, çıktı={}, süre={}ms", + target_action_id, + res.output_files.len(), + res.duration_ms + )), + Err(err) => crate::logging::error(&format!( + "Dönüştürme hatası: eylem={}, hata={}", + target_action_id, err + )), + } + + res_return +} + +#[tauri::command] +pub async fn cancel_conversion( + task_id: String, + state: State<'_, AppState>, +) -> AppResult { + let map = state.active_cancellations.read().await; + if let Some(flag) = map.get(&task_id) { + flag.store(true, Ordering::Relaxed); + Ok(true) + } else { + Ok(false) + } +} + diff --git a/src-tauri/src/commands/history.rs b/src-tauri/src/commands/history.rs new file mode 100644 index 0000000..d653798 --- /dev/null +++ b/src-tauri/src/commands/history.rs @@ -0,0 +1,19 @@ +use tauri::State; + +use crate::error::AppResult; +use crate::models::HistoryEntry; +use crate::state::AppState; + +#[tauri::command] +pub async fn get_history(state: State<'_, AppState>) -> AppResult> { + let r = state.history.read().await; + Ok(r.clone()) +} + +#[tauri::command] +pub async fn clear_history(state: State<'_, AppState>) -> AppResult<()> { + let mut w = state.history.write().await; + w.clear(); + AppState::save_history_to_disk(&w); + Ok(()) +} diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs new file mode 100644 index 0000000..cba9df1 --- /dev/null +++ b/src-tauri/src/commands/mod.rs @@ -0,0 +1,13 @@ +pub mod catalog; +pub mod conversion; +pub mod history; +pub mod preferences; +pub mod system; +pub mod window; + +pub use catalog::*; +pub use conversion::*; +pub use history::*; +pub use preferences::*; +pub use system::*; +pub use window::*; diff --git a/src-tauri/src/commands/preferences.rs b/src-tauri/src/commands/preferences.rs new file mode 100644 index 0000000..2845d5d --- /dev/null +++ b/src-tauri/src/commands/preferences.rs @@ -0,0 +1,28 @@ +use tauri::State; + +use crate::error::AppResult; +use crate::models::AppPreferences; +use crate::state::AppState; + +#[tauri::command] +pub async fn get_preferences(state: State<'_, AppState>) -> AppResult { + let r = state.preferences.read().await; + Ok(r.clone()) +} + +#[tauri::command] +pub async fn save_preferences( + preferences: AppPreferences, + state: State<'_, AppState>, +) -> AppResult<()> { + let mut w = state.preferences.write().await; + *w = preferences.clone(); + crate::services::engine_resolver::set_custom_paths( + &preferences.custom_ffmpeg_path, + &preferences.custom_pandoc_path, + &preferences.custom_seven_zip_path, + ); + crate::services::autostart::set_enabled(preferences.start_with_windows); + AppState::save_preferences_to_disk(&preferences); + Ok(()) +} diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs new file mode 100644 index 0000000..bfe6488 --- /dev/null +++ b/src-tauri/src/commands/system.rs @@ -0,0 +1,77 @@ +use std::path::Path; +use std::process::Command; +use tauri::State; + +use crate::error::{AppError, AppResult}; +use crate::services::dispatcher::ConversionDispatcher; +use crate::services::engine_resolver::{EngineResolver, EngineStatus}; +use crate::state::AppState; + +#[tauri::command] +pub async fn resolve_tools_status(state: State<'_, AppState>) -> AppResult { + let prefs = state.preferences.read().await; + Ok(EngineResolver::resolve_all( + Some(&prefs.custom_ffmpeg_path), + Some(&prefs.custom_pandoc_path), + Some(&prefs.custom_seven_zip_path), + )) +} + +#[tauri::command] +pub fn open_folder(path: String) -> AppResult<()> { + let p = Path::new(&path); + let target = if p.is_file() { + p.parent().unwrap_or(p) + } else { + p + }; + + if !target.exists() { + return Err(AppError::NotFound(target.to_string_lossy().to_string())); + } + + #[cfg(target_os = "windows")] + { + Command::new("explorer") + .arg(target) + .spawn() + .map_err(|e| AppError::Generic(format!("Klasör açılamadı: {}", e)))?; + } + + #[cfg(target_os = "macos")] + { + Command::new("open") + .arg(target) + .spawn() + .map_err(|e| AppError::Generic(format!("Klasör açılamadı: {}", e)))?; + } + + #[cfg(target_os = "linux")] + { + Command::new("xdg-open") + .arg(target) + .spawn() + .map_err(|e| AppError::Generic(format!("Klasör açılamadı: {}", e)))?; + } + + Ok(()) +} + +#[tauri::command] +pub fn read_qr(image_path: String) -> AppResult { + ConversionDispatcher::read_qr_any(&image_path) +} + +/// Günlük (log) klasörünün yolunu döner; Ayarlar ekranındaki "Günlük Klasörünü Aç" düğmesi kullanır. +#[tauri::command] +pub fn log_directory() -> AppResult { + crate::logging::log_dir() + .map(|path| path.to_string_lossy().to_string()) + .ok_or_else(|| AppError::NotFound("Günlük klasörü belirlenemedi.".to_string())) +} + +/// Seçili dosyaların bayt cinsinden boyutlarını döner (arayüzdeki dosya kartları için). +#[tauri::command] +pub fn file_sizes(paths: Vec) -> Vec { + paths.iter().map(|path| crate::utils::total_size(path)).collect() +} diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rs new file mode 100644 index 0000000..e64f460 --- /dev/null +++ b/src-tauri/src/commands/window.rs @@ -0,0 +1,22 @@ +use tauri::Window; + +use crate::error::AppResult; + +#[tauri::command] +pub fn minimize_window(window: Window) -> AppResult<()> { + window.minimize().map_err(|e| crate::error::AppError::Generic(e.to_string())) +} + +#[tauri::command] +pub fn maximize_window(window: Window) -> AppResult<()> { + if window.is_maximized().unwrap_or(false) { + window.unmaximize().map_err(|e| crate::error::AppError::Generic(e.to_string())) + } else { + window.maximize().map_err(|e| crate::error::AppError::Generic(e.to_string())) + } +} + +#[tauri::command] +pub fn close_window(window: Window) -> AppResult<()> { + window.close().map_err(|e| crate::error::AppError::Generic(e.to_string())) +} diff --git a/src-tauri/src/error.rs b/src-tauri/src/error.rs new file mode 100644 index 0000000..76a427c --- /dev/null +++ b/src-tauri/src/error.rs @@ -0,0 +1,46 @@ +use serde::Serialize; +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum AppError { + #[error("Dosya veya dizin bulunamadı: {0}")] + NotFound(String), + + #[error("G/Ç (I/O) Hatası: {0}")] + Io(#[from] std::io::Error), + + #[error("Görsel İşleme Hatası: {0}")] + Image(#[from] image::ImageError), + + #[error("PDF İşleme Hatası: {0}")] + Pdf(String), + + #[error("Arşivleme Hatası: {0}")] + Archive(String), + + #[error("Dönüştürme Motoru Hatası: {0}")] + Engine(String), + + #[error("İşlem kullanıcı tarafından iptal edildi")] + Cancelled, + + #[error("Desteklenmeyen veya geçersiz format: {0}")] + UnsupportedFormat(String), + + #[error("JSON Serileştirme Hatası: {0}")] + Serialization(#[from] serde_json::Error), + + #[error("İşlem Hatası: {0}")] + Generic(String), +} + +impl Serialize for AppError { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + serializer.serialize_str(&self.to_string()) + } +} + +pub type AppResult = Result; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs new file mode 100644 index 0000000..88e40ca --- /dev/null +++ b/src-tauri/src/lib.rs @@ -0,0 +1,224 @@ +pub mod catalog; +pub mod cli; +pub mod commands; +pub mod error; +pub mod logging; +pub mod models; +pub mod selftest; +pub mod services; +pub mod state; +pub mod utils; + +use tauri::menu::{Menu, MenuItem}; +use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}; +use tauri::{Manager, WindowEvent}; + +/// Aynı anda yalnızca tek örneğin çalışmasını sağlar; ikinci örnek açılırsa +/// mevcut pencereyi öne getirip kendini kapatır. +#[cfg(windows)] +fn acquire_single_instance() -> bool { + use windows_sys::Win32::Foundation::{GetLastError, ERROR_ALREADY_EXISTS}; + use windows_sys::Win32::System::Threading::CreateMutexW; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + FindWindowW, SetForegroundWindow, ShowWindow, SW_RESTORE, + }; + + let wide = |value: &str| -> Vec { value.encode_utf16().chain(std::iter::once(0)).collect() }; + + let mutex_name = wide("Local\\LDConverterSingleInstance"); + let handle = unsafe { CreateMutexW(std::ptr::null(), 0, mutex_name.as_ptr()) }; + if handle.is_null() { + logging::warn("Tek örnek kilidi oluşturulamadı; normal başlatmaya devam ediliyor."); + return true; + } + + let already_running = unsafe { GetLastError() } == ERROR_ALREADY_EXISTS; + if !already_running { + // Kilit süreç boyunca açık kalmalı: tanıtıcıyı kapatmıyoruz, süreç bitince OS serbest bırakır. + let _keep_alive = handle; + return true; + } + + let title = wide("LD Converter"); + let existing = unsafe { FindWindowW(std::ptr::null(), title.as_ptr()) }; + if !existing.is_null() { + unsafe { + ShowWindow(existing, SW_RESTORE); + SetForegroundWindow(existing); + } + logging::info("İkinci örnek başlatıldı; mevcut pencere öne getirildi."); + } else { + logging::warn("İkinci örnek başlatıldı ancak mevcut pencere bulunamadı."); + } + false +} + +/// Başlatma hatalarını (özellikle WebView2 Runtime sorunlarını) sessiz çökmek yerine +/// kullanıcıya anlaşılır bir pencere ile bildirir ve günlüğe yazar. +#[cfg(windows)] +fn install_startup_error_dialog() { + let default_hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let detail = info.to_string(); + logging::error(&format!("PANIK: {}", detail)); + + let is_webview2 = detail.to_lowercase().contains("webview2"); + let (title, guidance) = if is_webview2 { + ( + "LD Converter - Başlatma Hatası", + "Bu hata genellikle Microsoft Edge WebView2 Runtime bileşeninin eksik veya bozuk olmasından kaynaklanır.\n\ + https://go.microsoft.com/fwlink/p/?LinkId=2124703 adresinden WebView2 Runtime kurulumunu yapıp uygulamayı yeniden başlatın.", + ) + } else { + ( + "LD Converter - Beklenmeyen Hata", + "Uygulama çalışırken beklenmeyen bir sistem hatası meydana geldi.", + ) + }; + + let message = format!( + "LD Converter bir sorunla karşılaştı.\n\n{}\n\n{}\n\nAyrıntılar günlük dosyasında: %LOCALAPPDATA%\\LDConverter\\logs\\ld-converter.log", + detail, guidance + ); + show_message_box(title, &message); + default_hook(info); + })); +} + +#[cfg(windows)] +fn show_message_box(title: &str, text: &str) { + use windows_sys::Win32::UI::WindowsAndMessaging::{MessageBoxW, MB_ICONERROR, MB_OK}; + + let wide = |value: &str| -> Vec { value.encode_utf16().chain(std::iter::once(0)).collect() }; + let text_wide = wide(text); + let title_wide = wide(title); + unsafe { + MessageBoxW( + std::ptr::null_mut(), + text_wide.as_ptr(), + title_wide.as_ptr(), + MB_OK | MB_ICONERROR, + ); + } +} + +fn show_main_window(app: &tauri::AppHandle) { + if let Some(window) = app.get_webview_window("main") { + let _ = window.show(); + let _ = window.unminimize(); + let _ = window.set_focus(); + } +} + +fn build_tray(app: &tauri::AppHandle) -> tauri::Result<()> { + let show_item = MenuItem::with_id(app, "show", "Pencereyi Göster", true, None::<&str>)?; + let quit_item = MenuItem::with_id(app, "quit", "Çıkış", true, None::<&str>)?; + let menu = Menu::with_items(app, &[&show_item, &quit_item])?; + + let mut builder = TrayIconBuilder::with_id("ld-converter-tray") + .tooltip("LD Converter") + .menu(&menu) + .show_menu_on_left_click(false) + .on_menu_event(|app, event| match event.id.as_ref() { + "show" => show_main_window(app), + "quit" => app.exit(0), + _ => {} + }) + .on_tray_icon_event(|tray, event| { + if let TrayIconEvent::Click { + button: MouseButton::Left, + button_state: MouseButtonState::Up, + .. + } = event + { + show_main_window(tray.app_handle()); + } + }); + + if let Some(icon) = app.default_window_icon() { + builder = builder.icon(icon.clone()); + } + builder.build(app)?; + Ok(()) +} + +#[cfg_attr(mobile, tauri::mobile_entry_point)] +pub fn run() { + logging::info(&format!( + "LD Converter {} başlatılıyor", + env!("CARGO_PKG_VERSION") + )); + + #[cfg(windows)] + { + install_startup_error_dialog(); + if !acquire_single_instance() { + std::process::exit(0); + } + } + + let builder = tauri::Builder::default() + .plugin(tauri_plugin_dialog::init()) + .plugin(tauri_plugin_process::init()) + .plugin(tauri_plugin_updater::Builder::new().build()) + .setup(|app| { + let state = state::AppState::new(); + let start_with_windows = tauri::async_runtime::block_on(state.preferences.read()).start_with_windows; + app.manage(state); + services::autostart::set_enabled(start_with_windows); + + // `--tray` ile başlatıldıysa pencere gizli kalır (otomatik başlatma). + if std::env::args().any(|arg| arg == "--tray") { + if let Some(main) = app.get_webview_window("main") { + let _ = main.hide(); + } + } + + // Ana pencere kapanınca uygulama tepsiden çalışmaya devam eder. + if let Some(main) = app.get_webview_window("main") { + let main_for_event = main.clone(); + main.on_window_event(move |event| { + if let WindowEvent::CloseRequested { api, .. } = event { + api.prevent_close(); + let _ = main_for_event.hide(); + logging::info("Pencere gizlendi; uygulama tepside çalışıyor."); + } + }); + } + + build_tray(app.handle())?; + + services::engine_updater::start(app.handle().clone()); + + // Explorer sağ tık menüsü (HKCU, yönetici gerekmez) + if let Ok(exe) = std::env::current_exe() { + let exe = exe.to_string_lossy().to_string(); + std::thread::spawn(move || services::shell_menu::install(&exe)); + } + logging::info("Uygulama hazır (tepsi etkin)"); + Ok(()) + }) + .invoke_handler(tauri::generate_handler![ + commands::get_choices_for_files, + commands::get_default_choices, + commands::execute_conversion, + commands::cancel_conversion, + commands::get_preferences, + commands::save_preferences, + commands::get_history, + commands::clear_history, + commands::resolve_tools_status, + commands::open_folder, + commands::read_qr, + commands::log_directory, + commands::file_sizes, + commands::minimize_window, + commands::maximize_window, + commands::close_window, + ]); + + if let Err(e) = builder.run(tauri::generate_context!()) { + logging::error(&format!("Tauri uygulaması başlatılamadı: {}", e)); + eprintln!("Tauri uygulaması başlatılırken hata oluştu: {}", e); + } +} diff --git a/src-tauri/src/logging.rs b/src-tauri/src/logging.rs new file mode 100644 index 0000000..9caf731 --- /dev/null +++ b/src-tauri/src/logging.rs @@ -0,0 +1,65 @@ +//! Basit, dosya tabanlı günlük sistemi. +//! +//! - `%LOCALAPPDATA%\LDConverter\logs\ld-converter.log` dosyasına yazar. +//! - Dosya 512 KB'ı aşınca tek bir yedek (`ld-converter.1.log`) tutup sıfırdan başlar. +//! - Panikler de bu dosyaya yazılır (kullanıcıdan rapor isteyebilmek için). + +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::PathBuf; +use std::sync::Mutex; + +const MAX_LOG_BYTES: u64 = 512 * 1024; + +static LOCK: Mutex<()> = Mutex::new(()); + +pub fn log_dir() -> Option { + dirs::data_local_dir().map(|dir| dir.join("LDConverter").join("logs")) +} + +pub fn log_path() -> Option { + log_dir().map(|dir| dir.join("ld-converter.log")) +} + +fn rotate_if_needed(path: &std::path::Path) { + let too_big = fs::metadata(path).map(|meta| meta.len() > MAX_LOG_BYTES).unwrap_or(false); + if !too_big { + return; + } + let backup = path.with_file_name("ld-converter.1.log"); + let _ = fs::remove_file(&backup); + let _ = fs::rename(path, &backup); +} + +/// Günlüğe satır yazar. Günlük yazılamazsa sessizce yutar; uygulama akışını etkilemez. +pub fn write(level: &str, message: &str) { + let Some(path) = log_path() else { return }; + let Some(parent) = path.parent() else { return }; + + let _guard = match LOCK.lock() { + Ok(guard) => guard, + Err(poisoned) => poisoned.into_inner(), + }; + + if fs::create_dir_all(parent).is_err() { + return; + } + rotate_if_needed(&path); + + let stamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f"); + if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(&path) { + let _ = writeln!(file, "[{}] [{}] {}", stamp, level, message); + } +} + +pub fn info(message: &str) { + write("INFO", message); +} + +pub fn warn(message: &str) { + write("WARN", message); +} + +pub fn error(message: &str) { + write("ERROR", message); +} diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs new file mode 100644 index 0000000..5022be5 --- /dev/null +++ b/src-tauri/src/main.rs @@ -0,0 +1,20 @@ +// Prevents additional console window on Windows in release, DO NOT REMOVE!! +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] +// comctl6 manifesti nedeniyle oluşan ld uyarısını sustur (bkz. lib.rs). +#![allow(linker_messages)] + +fn main() { + let args: Vec = std::env::args().collect(); + + // Tanılama: arayüz açmadan tüm motorları sınar (rapor: %TEMP%\ld_selftest_report.txt) + if args.iter().any(|arg| arg == "--self-test") { + std::process::exit(app_lib::selftest::run()); + } + + // Explorer sağ tık menüsünden gelen dönüştürme isteği (arayüz açılmaz) + if args.iter().any(|arg| arg == "--convert") { + std::process::exit(app_lib::cli::run(&args)); + } + + app_lib::run(); +} diff --git a/src-tauri/src/models/choice.rs b/src-tauri/src/models/choice.rs new file mode 100644 index 0000000..78fdb4a --- /dev/null +++ b/src-tauri/src/models/choice.rs @@ -0,0 +1,28 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ToolChoice { + pub id: String, + pub display_name: String, + pub category: String, + pub icon_name: String, + pub description: String, +} + +impl ToolChoice { + pub fn new( + id: impl Into, + display_name: impl Into, + category: impl Into, + icon_name: impl Into, + description: impl Into, + ) -> Self { + Self { + id: id.into(), + display_name: display_name.into(), + category: category.into(), + icon_name: icon_name.into(), + description: description.into(), + } + } +} diff --git a/src-tauri/src/models/history.rs b/src-tauri/src/models/history.rs new file mode 100644 index 0000000..028fa54 --- /dev/null +++ b/src-tauri/src/models/history.rs @@ -0,0 +1,16 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HistoryEntry { + pub id: String, + pub title: String, + pub format_summary: String, + pub input_files: Vec, + pub output_files: Vec, + pub original_size_bytes: u64, + pub output_size_bytes: u64, + pub timestamp: DateTime, + pub success: bool, + pub error_message: Option, +} diff --git a/src-tauri/src/models/mod.rs b/src-tauri/src/models/mod.rs new file mode 100644 index 0000000..7096fa1 --- /dev/null +++ b/src-tauri/src/models/mod.rs @@ -0,0 +1,9 @@ +pub mod choice; +pub mod history; +pub mod preferences; +pub mod task; + +pub use choice::ToolChoice; +pub use history::HistoryEntry; +pub use preferences::{AppPreferences, OutputDirectoryMode, ThemeMode}; +pub use task::{ConversionOptions, ConversionResult, ProgressEvent}; diff --git a/src-tauri/src/models/preferences.rs b/src-tauri/src/models/preferences.rs new file mode 100644 index 0000000..33ec9f5 --- /dev/null +++ b/src-tauri/src/models/preferences.rs @@ -0,0 +1,60 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +pub enum ThemeMode { + #[default] + Dark, + Light, + System, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +pub enum OutputDirectoryMode { + #[default] + SameAsSource, + Desktop, + Custom, +} + +fn default_true() -> bool { + true +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AppPreferences { + pub output_directory_mode: OutputDirectoryMode, + pub custom_output_directory: String, + pub overwrite_existing: bool, + pub play_sound_effects: bool, + pub theme: ThemeMode, + pub default_image_quality: u8, + pub custom_ffmpeg_path: String, + pub custom_pandoc_path: String, + pub custom_seven_zip_path: String, + #[serde(default = "default_true")] + pub auto_update_on_startup: bool, + #[serde(default = "default_true")] + pub start_with_windows: bool, + /// Ayar şeması sürümü; eski dosyalarda kalite varsayılanlarını yükseltmek için kullanılır. + #[serde(default)] + pub settings_version: u32, +} + +impl Default for AppPreferences { + fn default() -> Self { + Self { + output_directory_mode: OutputDirectoryMode::SameAsSource, + custom_output_directory: String::new(), + overwrite_existing: false, + play_sound_effects: true, + theme: ThemeMode::Dark, + default_image_quality: 100, + custom_ffmpeg_path: String::new(), + custom_pandoc_path: String::new(), + custom_seven_zip_path: String::new(), + auto_update_on_startup: true, + start_with_windows: true, + settings_version: 2, + } + } +} diff --git a/src-tauri/src/models/task.rs b/src-tauri/src/models/task.rs new file mode 100644 index 0000000..2fe2870 --- /dev/null +++ b/src-tauri/src/models/task.rs @@ -0,0 +1,58 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ConversionOptions { + pub destination_folder: Option, + pub overwrite_existing: bool, + pub image_quality: u8, + pub target_width: Option, + pub target_height: Option, + pub strip_metadata: bool, + pub video_preset: Option, + pub video_crf: Option, + pub audio_bitrate_kbps: Option, + pub start_time: Option, + pub end_time: Option, + pub mute_audio: bool, + pub pdf_page_range: Option, + pub pdf_rotate_degrees: Option, + pub archive_password: Option, +} + +impl Default for ConversionOptions { + fn default() -> Self { + Self { + destination_folder: None, + overwrite_existing: false, + image_quality: 100, + target_width: None, + target_height: None, + strip_metadata: false, + video_preset: Some("slow".to_string()), + video_crf: Some(18), + audio_bitrate_kbps: Some(320), + start_time: None, + end_time: None, + mute_audio: false, + pdf_page_range: None, + pdf_rotate_degrees: None, + archive_password: None, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ProgressEvent { + pub task_id: String, + pub percent: f64, + pub message: String, + pub current_file: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ConversionResult { + pub success: bool, + pub output_files: Vec, + pub error_message: Option, + pub duration_ms: u64, +} diff --git a/src-tauri/src/selftest.rs b/src-tauri/src/selftest.rs new file mode 100644 index 0000000..dddd3a1 --- /dev/null +++ b/src-tauri/src/selftest.rs @@ -0,0 +1,1010 @@ +//! Kurulu uygulamanın kendi kendini sınaması: `LDConverter.exe --self-test`. +//! Arayüz (WebView2) olmadan dönüştürme motorlarını gerçek dosyalarla çalıştırır, +//! sonucu hem konsola hem rapor dosyasına yazar. Tanılama için tasarlanmıştır. + +use std::fmt::Write as _; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; +use std::sync::Arc; + +use crate::models::{AppPreferences, ConversionOptions}; +use crate::services::{ + ArchiveEngine, ConversionDispatcher, DocumentEngine, EngineResolver, OcrEngine, PdfEngine, + PdfTools, ProgressEmitter, +}; + +struct Report { + lines: String, + passed: usize, + failed: usize, + skipped: usize, +} + +impl Report { + fn new() -> Self { + Self { + lines: String::new(), + passed: 0, + failed: 0, + skipped: 0, + } + } + + fn line(&mut self, text: String) { + println!("{}", text); + self.lines.push_str(&text); + self.lines.push_str("\r\n"); + } + + fn pass(&mut self, name: &str, detail: &str) { + self.passed += 1; + self.line(format!("[PASS] {} - {}", name, detail)); + } + + fn fail(&mut self, name: &str, detail: &str) { + self.failed += 1; + self.line(format!("[FAIL] {} - {}", name, detail)); + } + + fn skip(&mut self, name: &str, why: &str) { + self.skipped += 1; + self.line(format!("[SKIP] {} - {}", name, why)); + } + + fn check(&mut self, name: &str, result: Result) { + match result { + Ok(detail) => self.pass(name, &detail), + Err(err) => self.fail(name, &err), + } + } +} + +fn temp_dir() -> PathBuf { + let dir = std::env::temp_dir().join(format!("ld_selftest_{}", uuid::Uuid::new_v4())); + let _ = fs::create_dir_all(&dir); + dir +} + +fn create_image(path: &Path, width: u32, height: u32) -> Result<(), String> { + let img = image::RgbImage::from_fn(width, height, |x, y| { + image::Rgb([(x % 255) as u8, (y % 255) as u8, 120]) + }); + img.save(path) + .map_err(|e| format!("test görseli yazılamadı: {}", e)) +} + +fn create_dense_rgba_png(path: &Path, width: u32, height: u32) -> Result<(), String> { + let img = image::RgbaImage::from_fn(width, height, |x, y| { + let r = ((x.wrapping_mul(3).wrapping_add(y)) % 256) as u8; + let g = ((x.wrapping_add(y.wrapping_mul(5))) % 256) as u8; + let b = ((x ^ y) % 256) as u8; + image::Rgba([r, g, b, 255]) + }); + img.save(path) + .map_err(|e| format!("yoğun RGBA PNG yazılamadı: {}", e)) +} + +fn encode_base64(input: &[u8]) -> String { + const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(input.len().div_ceil(3) * 4); + for chunk in input.chunks(3) { + let b0 = chunk[0] as u32; + let b1 = chunk.get(1).copied().unwrap_or(0) as u32; + let b2 = chunk.get(2).copied().unwrap_or(0) as u32; + let triple = (b0 << 16) | (b1 << 8) | b2; + out.push(TABLE[((triple >> 18) & 0x3F) as usize] as char); + out.push(TABLE[((triple >> 12) & 0x3F) as usize] as char); + out.push(if chunk.len() > 1 { + TABLE[((triple >> 6) & 0x3F) as usize] as char + } else { + '=' + }); + out.push(if chunk.len() > 2 { + TABLE[(triple & 0x3F) as usize] as char + } else { + '=' + }); + } + out +} + +fn docx_contains_omath(docx_path: &Path) -> Result { + let file = fs::File::open(docx_path).map_err(|e| format!("DOCX açılamadı: {}", e))?; + let mut archive = + zip::ZipArchive::new(file).map_err(|e| format!("DOCX ZIP okunamadı: {}", e))?; + let mut entry = archive + .by_name("word/document.xml") + .map_err(|e| format!("word/document.xml bulunamadı: {}", e))?; + let mut xml = String::new(); + std::io::Read::read_to_string(&mut entry, &mut xml) + .map_err(|e| format!("document.xml okunamadı: {}", e))?; + Ok(xml.contains(" Result { + let doc = lopdf::Document::load(pdf_path).map_err(|e| format!("PDF yüklenemedi: {}", e))?; + let mut image_count = 0usize; + let mut link_count = 0usize; + for obj in doc.objects.values() { + let dict_opt = obj + .as_dict() + .ok() + .or_else(|| obj.as_stream().ok().map(|s| &s.dict)); + if let Some(dict) = dict_opt { + if let Ok(subtype) = dict.get(b"Subtype").and_then(|v| v.as_name()) { + if subtype == b"Image" { + image_count += 1; + } else if subtype == b"Link" { + link_count += 1; + } + } + } + } + let has_outlines = doc + .trailer + .get(b"Root") + .ok() + .and_then(|o| o.as_reference().ok()) + .and_then(|id| doc.get_dictionary(id).ok()) + .map(|cat| cat.has(b"Outlines")) + .unwrap_or(false); + + if image_count == 0 { + return Err("Vektör PDF içinde gömülü görsel XObject bulunamadı".to_string()); + } + if !has_outlines { + return Err("Vektör PDF Katalog içinde /Outlines yer imi bulunamadı".to_string()); + } + if link_count == 0 { + return Err("Vektör PDF içinde /Subtype /Link bağlantısı bulunamadı".to_string()); + } + + Ok(format!( + "{} (IMAGES={}, OUTLINES=true, LINKS={})", + pdf_path.display(), + image_count, + link_count + )) +} + +fn run_action( + files: Vec, + action: &str, + options: ConversionOptions, +) -> Result { + let runtime = tokio::runtime::Runtime::new().map_err(|e| e.to_string())?; + runtime.block_on(async move { + ConversionDispatcher::execute_task( + ProgressEmitter::silent(), + files, + action.to_string(), + options, + AppPreferences::default(), + Arc::new(AtomicBool::new(false)), + uuid::Uuid::new_v4().to_string(), + ) + .await + .map_err(|e| e.to_string()) + }) +} + +fn expect_file(result: Result) -> Result { + let result = result?; + let first = result + .output_files + .first() + .ok_or_else(|| "çıktı dosyası döndürülmedi".to_string())?; + let path = PathBuf::from(first); + if !path.exists() { + return Err(format!("çıktı yok: {}", first)); + } + Ok(format!("{} ({} bayt)", path.display(), fs::metadata(&path).map(|m| m.len()).unwrap_or(0))) +} + +pub fn run() -> i32 { + let mut report = Report::new(); + let started = std::time::Instant::now(); + let dir = temp_dir(); + + report.line("=== LD Converter Kendi Kendini Sınama Raporu ===".to_string()); + report.line(format!("Sürüm: {}", env!("CARGO_PKG_VERSION"))); + report.line(format!("Yürütülebilir dosya: {}", std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_default())); + report.line(format!("Test klasörü: {}", dir.display())); + report.line(String::new()); + + // --- Motorlar + report.line("--- Motorlar ---".to_string()); + report.line(format!("FFmpeg: {:?}", EngineResolver::resolve_ffmpeg(None))); + report.line(format!("Pandoc: {:?}", EngineResolver::resolve_pandoc(None))); + report.line(format!("7-Zip: {:?}", EngineResolver::resolve_7zip(None))); + report.line(format!("Tesseract: {:?}", EngineResolver::resolve_tesseract())); + report.line("Denklem & Ofis Motoru (Dahili Rust): hazır".to_string()); + report.line(format!("PDF sayfa render (WinRT) hazır: {}", PdfTools::available())); + report.line(format!( + "JPEG XL desteği: {} (cjxl: {:?}, djxl: {:?})", + EngineResolver::jxl_available(), + EngineResolver::resolve_jxl_encoder(), + EngineResolver::resolve_jxl_decoder() + )); + report.line(String::new()); + + // --- Görseller + let img_a = dir.join("a.png"); + let img_b = dir.join("b.png"); + if let Err(err) = create_image(&img_a, 320, 220) { + report.fail("test görseli üretimi", &err); + return 1; + } + if let Err(err) = create_image(&img_b, 240, 360) { + report.fail("test görseli üretimi", &err); + return 1; + } + let img_a_s = img_a.to_string_lossy().to_string(); + let img_b_s = img_b.to_string_lossy().to_string(); + let out_dir = dir.join("out"); + let _ = fs::create_dir_all(&out_dir); + let dest = Some(out_dir.to_string_lossy().to_string()); + + for format in ["jpg", "webp", "bmp", "tiff", "ico", "gif"] { + let opts = ConversionOptions { + destination_folder: dest.clone(), + image_quality: 82, + ..Default::default() + }; + let result = run_action(vec![img_a_s.clone()], format, opts).and_then(|res| { + let path = res.output_files.first().cloned().unwrap_or_default(); + if path.to_lowercase().ends_with(&format!(".{}", format)) { + Ok(res) + } else { + Err(format!("beklenen uzantı .{}, üretilen: {}", format, path)) + } + }); + report.check(&format!("görsel -> {}", format.to_uppercase()), expect_file(result)); + } + + let resize = run_action( + vec![img_a_s.clone()], + "jpg", + ConversionOptions { + destination_folder: dest.clone(), + target_width: Some(100), + ..Default::default() + }, + ) + .and_then(|res| { + let path = res.output_files.first().cloned().unwrap_or_default(); + let loaded = image::open(&path).map_err(|e| e.to_string())?; + if loaded.width() == 100 { + Ok(format!("genişlik={}", loaded.width())) + } else { + Err(format!("genişlik 100 olmalı, bulunan: {}", loaded.width())) + } + }); + report.check("yeniden boyutlandırma (100px)", resize); + + report.check( + "görsel sıkıştırma", + expect_file(run_action( + vec![img_a_s.clone()], + "compress_image", + ConversionOptions { + destination_folder: dest.clone(), + image_quality: 70, + ..Default::default() + }, + )), + ); + + let dense_png = dir.join("dense.png"); + if let Err(err) = create_dense_rgba_png(&dense_png, 512, 512) { + report.fail("yoğun RGBA PNG üretimi", &err); + } else { + let orig_len = fs::metadata(&dense_png).map(|m| m.len()).unwrap_or(0); + let dense_s = dense_png.to_string_lossy().to_string(); + report.check( + "PNG sıkıştırma (nicemleme)", + run_action( + vec![dense_s], + "compress_image", + ConversionOptions { + destination_folder: dest.clone(), + image_quality: 75, + ..Default::default() + }, + ) + .and_then(|res| { + let path = res + .output_files + .first() + .ok_or_else(|| "çıktı dosyası üretilmedi".to_string())?; + let out_len = fs::metadata(path).map(|m| m.len()).unwrap_or(0); + if out_len == 0 || orig_len == 0 { + return Err("PNG dosya boyutu 0".to_string()); + } + let reduction = 100.0 - (out_len as f64 / orig_len as f64) * 100.0; + if out_len * 100 <= orig_len * 60 { + Ok(format!( + "{} -> {} bayt ({:.1}% küçüldü)", + orig_len, out_len, reduction + )) + } else { + Err(format!( + "PNG yeterince sıkışmadı: {} -> {} bayt ({:.1}%)", + orig_len, out_len, reduction + )) + } + }), + ); + } + + let svg_file = dir.join("test.svg"); + let _ = fs::write( + &svg_file, + r##""##, + ); + let svg_s = svg_file.to_string_lossy().to_string(); + report.check( + "SVG -> PNG (1024px+)", + run_action( + vec![svg_s.clone()], + "png", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .and_then(|res| { + let path = res + .output_files + .first() + .ok_or_else(|| "SVG->PNG çıktısı yok".to_string())?; + let loaded = image::open(path).map_err(|e| format!("SVG->PNG açılamadı: {}", e))?; + if loaded.width() >= 1024 || loaded.height() >= 1024 { + Ok(format!("{}x{}", loaded.width(), loaded.height())) + } else { + Err(format!( + "küçük SVG en az 1024px ölçeklenmeliydi, bulunan: {}x{}", + loaded.width(), + loaded.height() + )) + } + }), + ); + + report.check( + "SVG -> PDF", + expect_file(run_action( + vec![svg_s], + "pdf", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + )) + .and_then(|detail| { + let pdf = detail.split(" (").next().unwrap_or("").to_string(); + match PdfEngine::page_count(&pdf) { + Ok(1) => Ok(detail), + Ok(other) => Err(format!("sayfa sayısı 1 olmalı, bulunan: {}", other)), + Err(e) => Err(e.to_string()), + } + }), + ); + + // --- PDF + report.check( + "görseller -> PDF", + expect_file(run_action( + vec![img_a_s.clone(), img_b_s.clone()], + "pdf", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + )) + .and_then(|detail| { + let pdf = detail.split(" (").next().unwrap_or("").to_string(); + match PdfEngine::page_count(&pdf) { + Ok(2) => Ok(detail), + Ok(other) => Err(format!("sayfa sayısı 2 olmalı, bulunan: {}", other)), + Err(e) => Err(e.to_string()), + } + }), + ); + + let single_pdf = out_dir.join("tek.pdf"); + let _ = PdfEngine::merge(std::slice::from_ref(&img_a_s), &single_pdf, &ConversionOptions::default()); + + report.check( + "PDF birleştirme (PDF + görsel)", + expect_file(run_action( + vec![ + single_pdf.to_string_lossy().to_string(), + img_b_s.clone(), + ], + "pdf_merge", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + )), + ); + + report.check( + "PDF sayfalarını ayırma", + run_action( + vec![single_pdf.to_string_lossy().to_string()], + "pdf_split", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .and_then(|res| { + if res.output_files.is_empty() { + Err("çıktı yok".to_string()) + } else { + Ok(format!("{} sayfa dosyası", res.output_files.len())) + } + }), + ); + + report.check( + "PDF döndürme + sayfa aralığı", + expect_file(run_action( + vec![single_pdf.to_string_lossy().to_string()], + "pdf_split", + ConversionOptions { + destination_folder: dest.clone(), + pdf_rotate_degrees: Some(90), + pdf_page_range: Some("1".to_string()), + ..Default::default() + }, + )), + ); + + // Metin katmanlı PDF üret (harici araç gerekmez: dahili minimal PDF yazıcı) + let mut text_pdf: Option = None; + let fixture_pdf = dir.join("metin.pdf"); + match PdfEngine::write_simple_text_pdf( + "MERHABA LD CONVERTER\nDenklem: $x^2 + y^2 = z^2$", + &fixture_pdf, + ) { + Ok(path) => text_pdf = Some(path), + Err(err) => report.fail("test PDF üretimi", &err.to_string()), + } + + match &text_pdf { + Some(pdf) => { + let pdf_s = pdf.to_string_lossy().to_string(); + report.check( + "PDF -> TXT (metin çıkarma)", + expect_file(run_action( + vec![pdf_s.clone()], + "pdf_to_txt", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + )) + .and_then(|detail| { + let path = detail.split(" (").next().unwrap_or("").to_string(); + let content = fs::read_to_string(&path).unwrap_or_default().to_lowercase(); + if content.contains("merhaba") { + Ok(detail) + } else { + Err(format!("metin bulunamadı; içerik: {:?}", content.chars().take(80).collect::())) + } + }), + ); + + report.check( + "PDF -> DOCX", + expect_file(run_action( + vec![pdf_s.clone()], + "pdf_to_docx", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + )), + ); + + report.check( + "PDF -> Denklem DOCX ()", + run_action( + vec![pdf_s.clone()], + "pdf_to_math_docx", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .and_then(|res| { + let path = res + .output_files + .first() + .ok_or_else(|| "DOCX çıktısı yok".to_string())?; + if docx_contains_omath(Path::new(path))? { + Ok(format!("{} ( doğrulandı)", path)) + } else { + Err("word/document.xml içinde PNG (WinRT/sayfa rasterleştirme)", + run_action( + vec![pdf_s.clone()], + "pdf_to_images", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .and_then(|res| { + let path = res + .output_files + .first() + .ok_or_else(|| "PDF->PNG çıktısı yok".to_string())?; + let loaded = + image::open(path).map_err(|e| format!("PNG açılamadı: {}", e))?; + if loaded.width() > 0 && loaded.height() > 0 { + Ok(format!("{} ({}x{})", path, loaded.width(), loaded.height())) + } else { + Err("geçersiz PNG boyutu".to_string()) + } + }), + ); + } + None => { + report.skip("PDF -> TXT", "test PDF üretilemedi"); + report.skip("PDF -> DOCX", "test PDF üretilemedi"); + report.skip("PDF -> Denklem DOCX ()", "test PDF üretilemedi"); + report.skip("PDF -> PNG", "test PDF üretilemedi"); + } + } + + report.check( + "PDF sıkıştırma (pdf_compress)", + run_action( + vec![single_pdf.to_string_lossy().to_string()], + "pdf_compress", + ConversionOptions { + destination_folder: dest.clone(), + image_quality: 65, + ..Default::default() + }, + ) + .and_then(|res| { + let path = res + .output_files + .first() + .ok_or_else(|| "sıkıştırılmış PDF yok".to_string())?; + let pages = PdfEngine::page_count(path).map_err(|e| e.to_string())?; + let bytes = fs::metadata(path).map(|m| m.len()).unwrap_or(0); + if pages == 0 || bytes == 0 { + Err("sıkıştırılmış PDF geçersiz".to_string()) + } else { + Ok(format!("{} ({} sayfa, {} bayt)", path, pages, bytes)) + } + }), + ); + + // --- OCR + let ocr_image = dir.join("ocr.png"); + let ocr_ready = create_text_image(&ocr_image); + if ocr_ready { + let ocr_result = OcrEngine::recognize_image(&ocr_image.to_string_lossy()); + match ocr_result { + Ok(text) => report.pass("OCR metin tanıma", &format!("tanınan: {:?}", text.lines().next().unwrap_or(""))), + Err(err) => report.fail("OCR metin tanıma", &err.to_string()), + } + report.check( + "görsel -> TXT (OCR)", + expect_file(run_action( + vec![ocr_image.to_string_lossy().to_string()], + "img_to_txt", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + )), + ); + report.check( + "görsel -> DOCX (OCR)", + expect_file(run_action( + vec![ocr_image.to_string_lossy().to_string()], + "img_to_docx", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + )), + ); + } else { + report.skip("OCR metin tanıma", "test görseli üretilemedi"); + report.skip("görsel -> TXT (OCR)", "test görseli üretilemedi"); + report.skip("görsel -> DOCX (OCR)", "test görseli üretilemedi"); + } + + // --- Arşivler + let zip_path = out_dir.join("arsiv_self.zip"); + match ArchiveEngine::create_zip(std::slice::from_ref(&img_a_s), &zip_path) { + Ok(_) => report.pass("ZIP oluşturma", &zip_path.display().to_string()), + Err(e) => report.fail("ZIP oluşturma", &e.to_string()), + } + report.check( + "ZIP çıkarma", + run_action( + vec![zip_path.to_string_lossy().to_string()], + "extract_folder", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .and_then(|res| { + let dir = res.output_files.first().cloned().ok_or("çıktı yok")?; + if Path::new(&dir).is_dir() { + Ok(dir) + } else { + Err("çıkarma klasörü oluşmadı".to_string()) + } + }), + ); + + let sevenz_res = run_action( + vec![img_a_s.clone()], + "7z", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ); + match &sevenz_res { + Ok(res) => { + if let Some(archive_file) = res.output_files.first() { + let sz = fs::metadata(archive_file).map(|m| m.len()).unwrap_or(0); + report.pass( + "7Z oluşturma (saf Rust)", + &format!("{} ({} bayt)", archive_file, sz), + ); + report.check( + "7Z çıkarma (saf Rust)", + run_action( + vec![archive_file.clone()], + "extract_folder", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .and_then(|ext| { + let out_dir_p = ext + .output_files + .first() + .ok_or_else(|| "çıkarma klasörü döndürülmedi".to_string())?; + let has_files = fs::read_dir(out_dir_p) + .map(|mut rd| rd.next().is_some()) + .unwrap_or(false); + if Path::new(out_dir_p).is_dir() && has_files { + Ok(out_dir_p.clone()) + } else { + Err("7Z çıkarma klasörü boş".to_string()) + } + }), + ); + } else { + report.fail("7Z oluşturma (saf Rust)", "çıktı dosyası yok"); + report.skip("7Z çıkarma (saf Rust)", "7Z üretilemedi"); + } + } + Err(e) => { + report.fail("7Z oluşturma (saf Rust)", e); + report.skip("7Z çıkarma (saf Rust)", "7Z üretilemedi"); + } + } + + report.check( + "TAR.GZ oluşturma (saf Rust)", + expect_file(run_action( + vec![img_a_s.clone()], + "tar_gz", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + )), + ); + + report.check( + "klasöre toplama", + run_action( + vec![img_a_s.clone(), img_b_s.clone()], + "copy_folder", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .and_then(|res| { + let dir = res.output_files.first().cloned().ok_or("çıktı yok")?; + if Path::new(&dir).is_dir() { + Ok(dir) + } else { + Err("klasör oluşmadı".to_string()) + } + }), + ); + + // --- Medya + if let Some(ffmpeg) = EngineResolver::resolve_ffmpeg(None) { + let wav = dir.join("ton.wav"); + let mut cmd = std::process::Command::new(&ffmpeg); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x08000000); + } + let ok = cmd + .arg("-y") + .arg("-f") + .arg("lavfi") + .arg("-i") + .arg("sine=frequency=440:duration=1") + .arg("-c:a") + .arg("pcm_s16le") + .arg(&wav) + .status() + .map(|s| s.success()) + .unwrap_or(false); + if ok && wav.exists() { + report.check( + "WAV -> MP3", + expect_file(run_action( + vec![wav.to_string_lossy().to_string()], + "mp3", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + )), + ); + report.check( + "ses sıkıştırma", + expect_file(run_action( + vec![wav.to_string_lossy().to_string()], + "compress_audio", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + )), + ); + } else { + report.skip("WAV -> MP3", "test WAV üretilemedi"); + report.skip("ses sıkıştırma", "test WAV üretilemedi"); + } + } else { + report.skip("WAV -> MP3", "FFmpeg yok"); + report.skip("ses sıkıştırma", "FFmpeg yok"); + } + + // --- Belgeler (tamamı dahili motor; harici program gerekmez) + let doc_txt = dir.join("belge.txt"); + let _ = fs::write(&doc_txt, "Merhaba dunya\nLD Converter self test"); + report.check( + "TXT -> DOCX", + expect_file(run_action( + vec![doc_txt.to_string_lossy().to_string()], + "docx", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + )), + ); + + let md = dir.join("formul.md"); + let _ = fs::write(&md, "# Baslik\n\nDenklem: $x^2 + y^2 = z^2$\n"); + report.check( + "MD -> Denklem DOCX ()", + run_action( + vec![md.to_string_lossy().to_string()], + "docx_math", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .and_then(|res| { + let path = res + .output_files + .first() + .ok_or_else(|| "MD->DOCX çıktısı yok".to_string())?; + if docx_contains_omath(Path::new(path))? { + Ok(format!("{} ( doğrulandı)", path)) + } else { + Err("word/document.xml içinde PDF (dahili)", + expect_file(run_action( + vec![md.to_string_lossy().to_string()], + "pdf", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + )), + ); + + let html_file = dir.join("rapor.html"); + let img_bytes = fs::read(&img_a).unwrap_or_default(); + let img_b64 = encode_base64(&img_bytes); + let html_body = format!( + "\ +

Kurumsal Özet & Test

\ +

Bağlantı: LD Web

\ +
AlanDurum
VektörHazır
\ +

\"logo\"/

\ + ", + img_b64 + ); + let _ = fs::write(&html_file, html_body); + report.check( + "HTML -> Vektör PDF (IMAGES >= 1)", + run_action( + vec![html_file.to_string_lossy().to_string()], + "pdf", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .and_then(|res| { + let path = res + .output_files + .first() + .ok_or_else(|| "HTML->PDF çıktısı yok".to_string())?; + inspect_vector_pdf(Path::new(path)) + }), + ); + + // --- Dahili motor (harici program kurmadan çalışan yollar) + report.line(String::new()); + report.line("--- Dahili (kurulum gerektirmeyen) motor ---".to_string()); + + let builtin_txt = dir.join("dahili_kaynak.txt"); + let _ = fs::write( + &builtin_txt, + "LD Converter dahili motor testi\nTürkçe karakterler: şğüıİÖÇ\n\nÜçüncü paragraf.", + ); + let builtin_txt_s = builtin_txt.to_string_lossy().to_string(); + + report.check( + "TXT -> PDF (dahili, GDI)", + DocumentEngine::convert(&builtin_txt_s, "pdf", &dir, true) + .map_err(|e| e.to_string()) + .and_then(|path| { + let pages = PdfEngine::page_count(&path.to_string_lossy()) + .map_err(|e| e.to_string())?; + if pages == 0 { + Err("PDF sayfası üretilmedi".to_string()) + } else { + Ok(format!("{} ({} sayfa)", path.display(), pages)) + } + }), + ); + + let builtin_docx = DocumentEngine::convert(&builtin_txt_s, "docx", &dir, true); + report.check( + "TXT -> DOCX (dahili)", + builtin_docx + .map_err(|e| e.to_string()) + .and_then(|path| { + let text = DocumentEngine::extract_text(&path.to_string_lossy()) + .map_err(|e| e.to_string())?; + if text.contains("Türkçe") && text.contains("dahili motor") { + Ok(path.display().to_string()) + } else { + Err(format!("metin geri okunamadı: {:?}", text.chars().take(60).collect::())) + } + }), + ); + + report.check( + "TXT -> HTML (dahili)", + DocumentEngine::convert(&builtin_txt_s, "html", &dir, true) + .map(|path| path.display().to_string()) + .map_err(|e| e.to_string()), + ); + + match &text_pdf { + Some(pdf) => { + let pdf_s = pdf.to_string_lossy().to_string(); + report.check( + "PDF -> TXT (dahili çözücü)", + crate::services::pdf_text::extract_pages(&pdf_s) + .map_err(|e| e.to_string()) + .and_then(|pages| { + let text = pages.join("\n"); + if text.to_lowercase().contains("merhaba") { + Ok(format!("{} sayfa, metin okundu", pages.len())) + } else { + Err(format!( + "metin bulunamadı: {:?}", + text.chars().take(60).collect::() + )) + } + }), + ); + } + None => report.skip("PDF -> TXT (dahili çözücü)", "test PDF üretilemedi"), + } + + #[cfg(windows)] + report.check( + "Metin -> görüntü (GDI)", + crate::services::gdi_render::render_text_pages("LD Converter GDI testi", 26, 800, 600, 40) + .map(|pages| format!("{} sayfa çizildi", pages.len())) + .map_err(|e| e.to_string()), + ); + + // --- Özet + report.line(String::new()); + let mut summary = String::new(); + let _ = write!( + summary, + "ÖZET: {} başarılı, {} başarısız, {} atlandı ({} ms)", + report.passed, + report.failed, + report.skipped, + started.elapsed().as_millis() + ); + report.line(summary); + + let report_path = std::env::var("LD_SELFTEST_REPORT") + .map(PathBuf::from) + .unwrap_or_else(|_| std::env::temp_dir().join("ld_selftest_report.txt")); + let _ = fs::write(&report_path, &report.lines); + println!("Rapor dosyası: {}", report_path.display()); + + let _ = fs::remove_dir_all(&dir); + + if report.failed > 0 { + 1 + } else { + 0 + } +} + +/// OCR testi için metin görseli üretir (Windows GDI dahili yolu). +fn create_text_image(output: &Path) -> bool { + #[cfg(windows)] + { + if let Ok(pages) = crate::services::gdi_render::render_text_pages( + "MERHABA DUNYA\nLD CONVERTER 2026", + 64, + 1000, + 260, + 30, + ) { + if let Some(first) = pages.first() { + if first.save(output).is_ok() && output.exists() { + return true; + } + } + } + } + + #[cfg(not(windows))] + let _ = output; + false +} diff --git a/src-tauri/src/services/archive_engine.rs b/src-tauri/src/services/archive_engine.rs new file mode 100644 index 0000000..47b8be9 --- /dev/null +++ b/src-tauri/src/services/archive_engine.rs @@ -0,0 +1,654 @@ +use std::fs::{self, File}; +use std::io::{BufReader, BufWriter, Write}; +use std::path::{Component, Path, PathBuf}; +use std::process::Command; + +#[cfg(windows)] +use std::os::windows::process::CommandExt; + +use sevenz_rust2::{ArchiveEntry, ArchiveWriter}; +use walkdir::WalkDir; +use zip::write::SimpleFileOptions; +use zip::{ZipArchive, ZipWriter}; + +use crate::error::{AppError, AppResult}; +use crate::services::engine_resolver::EngineResolver; + +pub struct ArchiveEngine; + +impl ArchiveEngine { + pub fn create_zip( + input_paths: &[String], + output_zip: &Path, + ) -> AppResult { + let file = File::create(output_zip)?; + let mut zip = ZipWriter::new(BufWriter::new(file)); + let options = SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated) + .unix_permissions(0o755); + + Self::visit_archive_inputs(input_paths, output_zip, |entry_path, archive_name, is_dir| { + if is_dir { + zip.add_directory(format!("{}/", archive_name), options) + .map_err(|e| AppError::Archive(format!("Klasör eklenemedi: {}", e)))?; + } else { + zip.start_file(archive_name, options) + .map_err(|e| AppError::Archive(format!("ZIP girdisi açılamadı: {}", e)))?; + let mut f = File::open(entry_path)?; + std::io::copy(&mut f, &mut zip)?; + } + Ok(()) + })?; + + zip.finish() + .map_err(|e| AppError::Archive(format!("ZIP tamamlanamadı: {}", e)))?; + + Ok(output_zip.to_path_buf()) + } + + pub fn create_7z(input_paths: &[String], output_7z: &Path) -> AppResult { + match Self::create_7z_pure_rust(input_paths, output_7z) { + Ok(path) => Ok(path), + Err(err) => { + if EngineResolver::resolve_7zip(None).is_some() { + Self::create_7z_via_7zip(input_paths, output_7z) + } else { + Err(err) + } + } + } + } + + fn create_7z_pure_rust(input_paths: &[String], output_7z: &Path) -> AppResult { + if let Some(parent) = output_7z.parent() { + if !parent.as_os_str().is_empty() { + fs::create_dir_all(parent)?; + } + } + let mut writer = ArchiveWriter::create(output_7z) + .map_err(|e| AppError::Archive(format!("7Z yazıcısı başlatılamadı: {}", e)))?; + + Self::visit_archive_inputs(input_paths, output_7z, |entry_path, archive_name, is_dir| { + let entry = ArchiveEntry::from_path(entry_path, archive_name); + if is_dir { + writer + .push_archive_entry::(entry, None) + .map_err(|e| AppError::Archive(format!("7Z klasör girdisi eklenemedi: {}", e)))?; + } else { + let file = File::open(entry_path)?; + writer + .push_archive_entry(entry, Some(file)) + .map_err(|e| AppError::Archive(format!("7Z dosya girdisi eklenemedi: {}", e)))?; + } + Ok(()) + })?; + + writer + .finish() + .map_err(|e| AppError::Archive(format!("7Z arşivi tamamlanamadı: {}", e)))?; + + Ok(output_7z.to_path_buf()) + } + + fn create_7z_via_7zip(input_paths: &[String], output_7z: &Path) -> AppResult { + let seven_zip = EngineResolver::resolve_7zip(None).ok_or_else(|| { + AppError::Archive( + "7Z arşivi oluşturmak için sistemde 7-Zip kurulu olmalıdır.".to_string(), + ) + })?; + + let mut cmd = Command::new(seven_zip); + #[cfg(windows)] + cmd.creation_flags(0x08000000); + cmd.arg("a") + .arg("-t7z") + .arg("-mx=9") + .arg("-y") + .arg(output_7z); + + for item in input_paths { + if Path::new(item).exists() && !Self::same_file(Path::new(item), output_7z) { + cmd.arg(item); + } + } + + let status = cmd + .status() + .map_err(|e| AppError::Archive(format!("7-Zip çalıştırılamadı: {}", e)))?; + + if status.success() && output_7z.exists() { + Ok(output_7z.to_path_buf()) + } else { + Err(AppError::Archive("7Z arşivi oluşturulamadı.".to_string())) + } + } + + fn visit_archive_inputs( + input_paths: &[String], + output_archive: &Path, + mut on_entry: F, + ) -> AppResult<()> + where + F: FnMut(&Path, String, bool) -> AppResult<()>, + { + for item in input_paths { + let path = Path::new(item); + if !path.exists() { + continue; + } + if path.is_file() { + if Self::same_file(path, output_archive) { + continue; + } + let name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("file") + .to_string(); + on_entry(path, name, false)?; + } else if path.is_dir() { + let prefix = path.parent().unwrap_or(path); + for entry in WalkDir::new(path).into_iter().flatten() { + let entry_path = entry.path(); + if Self::same_file(entry_path, output_archive) { + continue; + } + let rel_path = entry_path + .strip_prefix(prefix) + .unwrap_or(entry_path) + .to_string_lossy() + .replace('\\', "/"); + + if entry_path.is_file() { + on_entry(entry_path, rel_path, false)?; + } else if entry_path.is_dir() && !rel_path.is_empty() { + on_entry(entry_path, rel_path, true)?; + } + } + } + } + Ok(()) + } + + pub fn create_tar_gz(input_paths: &[String], output_path: &Path) -> AppResult { + if let Ok(path) = Self::create_tar_gz_pure_rust(input_paths, output_path) { + return Ok(path); + } + + let temp_tar = std::env::temp_dir().join(format!("ld_tar_{}.tar", uuid::Uuid::new_v4())); + + // 1) TAR oluştur (7-Zip varsa), 2) GZIP'e sıkıştır + if let Some(seven_zip) = EngineResolver::resolve_7zip(None) { + let mut cmd = Command::new(&seven_zip); + #[cfg(windows)] + cmd.creation_flags(0x08000000); + cmd.arg("a").arg("-ttar").arg("-y").arg(&temp_tar); + for item in input_paths { + if Path::new(item).exists() { + cmd.arg(item); + } + } + let status = cmd + .status() + .map_err(|e| AppError::Archive(format!("7-Zip çalıştırılamadı: {}", e)))?; + if !status.success() || !temp_tar.exists() { + let _ = fs::remove_file(&temp_tar); + return Err(AppError::Archive("TAR paketi oluşturulamadı.".to_string())); + } + + let mut gz = Command::new(&seven_zip); + #[cfg(windows)] + gz.creation_flags(0x08000000); + let status = gz + .arg("a") + .arg("-tgzip") + .arg("-y") + .arg(output_path) + .arg(&temp_tar) + .status() + .map_err(|e| AppError::Archive(format!("7-Zip çalıştırılamadı: {}", e)))?; + let _ = fs::remove_file(&temp_tar); + + if status.success() && output_path.exists() { + return Ok(output_path.to_path_buf()); + } + return Err(AppError::Archive("TAR.GZ arşivi oluşturulamadı.".to_string())); + } + + // 7-Zip yoksa Windows'un yerleşik bsdtar aracını kullan + let mut cmd = Command::new("tar"); + #[cfg(windows)] + cmd.creation_flags(0x08000000); + cmd.arg("-czf").arg(output_path); + for item in input_paths { + let p = Path::new(item); + if p.exists() { + cmd.arg("-C") + .arg(p.parent().unwrap_or_else(|| Path::new("."))) + .arg(p.file_name().unwrap_or_default()); + } + } + let status = cmd + .status() + .map_err(|e| AppError::Archive(format!("tar çalıştırılamadı: {}", e)))?; + if status.success() && output_path.exists() { + Ok(output_path.to_path_buf()) + } else { + Err(AppError::Archive( + "TAR.GZ oluşturmak için 7-Zip veya tar gereklidir.".to_string(), + )) + } + } + + fn create_tar_gz_pure_rust(input_paths: &[String], output_path: &Path) -> AppResult { + let out_file = File::create(output_path)?; + let gz = flate2::write::GzEncoder::new( + BufWriter::new(out_file), + flate2::Compression::default(), + ); + let mut tar_writer = BufWriter::new(gz); + + Self::visit_archive_inputs(input_paths, output_path, |entry_path, archive_name, is_dir| { + let clean_name = archive_name.replace('\\', "/"); + let entry_name = if is_dir && !clean_name.ends_with('/') { + format!("{}/", clean_name) + } else { + clean_name + }; + let size = if is_dir { + 0u64 + } else { + fs::metadata(entry_path).map(|m| m.len()).unwrap_or(0) + }; + let mtime = fs::metadata(entry_path) + .ok() + .and_then(|m| m.modified().ok()) + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_secs()) + .unwrap_or(0); + + write_ustar_header(&mut tar_writer, &entry_name, size, mtime, is_dir)?; + if !is_dir && size > 0 { + let mut reader = BufReader::new(File::open(entry_path)?); + let copied = std::io::copy(&mut reader, &mut tar_writer)?; + let rem = (512 - (copied % 512)) % 512; + if rem > 0 { + let pad = [0u8; 512]; + tar_writer.write_all(&pad[..rem as usize])?; + } + } + Ok(()) + })?; + + // İki 512 baytlık sıfır blok TAR sonu işaretçisidir. + tar_writer.write_all(&[0u8; 1024])?; + let gz = tar_writer + .into_inner() + .map_err(|e| AppError::Archive(format!("TAR tamponu boşaltılamadı: {}", e)))?; + gz.finish()?; + + if output_path.exists() { + Ok(output_path.to_path_buf()) + } else { + Err(AppError::Archive("TAR.GZ oluşturulamadı.".to_string())) + } + } + + /// Seçili dosya/klasörleri yeni bir alt klasöre kopyalar. + pub fn copy_to_folder(input_paths: &[String], destination_dir: &Path) -> AppResult { + fs::create_dir_all(destination_dir)?; + let stamp = chrono::Local::now().format("%Y%m%d_%H%M%S"); + let mut target = destination_dir.join(format!("LD_Klasor_{}", stamp)); + let mut counter = 1; + while target.exists() { + target = destination_dir.join(format!("LD_Klasor_{} ({})", stamp, counter)); + counter += 1; + } + fs::create_dir_all(&target)?; + + for item in input_paths { + let src = Path::new(item); + if !src.exists() { + continue; + } + let name = src + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("dosya"); + let dest = target.join(name); + if src.is_dir() { + Self::copy_dir_recursive(src, &dest)?; + } else { + fs::copy(src, &dest)?; + } + } + + Ok(target) + } + + fn copy_dir_recursive(src: &Path, dest: &Path) -> AppResult<()> { + fs::create_dir_all(dest)?; + for entry in fs::read_dir(src)? { + let entry = entry?; + let path = entry.path(); + let child = dest.join(entry.file_name()); + if path.is_dir() { + Self::copy_dir_recursive(&path, &child)?; + } else { + fs::copy(&path, &child)?; + } + } + Ok(()) + } + + fn same_file(a: &Path, b: &Path) -> bool { + match (a.canonicalize(), b.canonicalize()) { + (Ok(ca), Ok(cb)) => ca == cb, + _ => false, + } + } + + pub fn extract_archive( + archive_path: &str, + destination_dir: &Path, + password: Option<&str>, + ) -> AppResult { + let path = Path::new(archive_path); + if !path.exists() { + return Err(AppError::NotFound(archive_path.to_string())); + } + + fs::create_dir_all(destination_dir)?; + let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_lowercase(); + + let has_password = password.map(|p| !p.is_empty()).unwrap_or(false); + + if ext == "zip" { + // Şifreli ZIP'ler saf Rust çözücüyle açılamaz; 7-Zip'e devret + if has_password && EngineResolver::resolve_7zip(None).is_some() { + return Self::extract_via_7zip(path, destination_dir, password); + } + match Self::extract_zip_pure_rust(path, destination_dir) { + Ok(result) => Ok(result), + Err(err) => { + if EngineResolver::resolve_7zip(None).is_some() { + Self::extract_via_7zip(path, destination_dir, password) + } else { + Err(err) + } + } + } + } else if ext == "7z" { + if has_password { + return Self::extract_via_7zip(path, destination_dir, password); + } + match Self::extract_7z_pure_rust(path, destination_dir) { + Ok(result) => Ok(result), + Err(err) => { + if EngineResolver::resolve_7zip(None).is_some() { + Self::extract_via_7zip(path, destination_dir, password) + } else { + Err(err) + } + } + } + } else { + Self::extract_via_7zip(path, destination_dir, password) + } + } + + fn safe_extract_target( + destination_dir: &Path, + canonical_dest: &Path, + entry_name: &str, + ) -> AppResult> { + let normalized = entry_name.replace('\\', "/"); + let mut clean_rel = PathBuf::new(); + for comp in Path::new(&normalized).components() { + match comp { + Component::Normal(part) => clean_rel.push(part), + Component::CurDir => {} + Component::ParentDir | Component::RootDir | Component::Prefix(_) => { + return Err(AppError::Archive( + "Güvenlik Uyarısı: Zip-Slip tespit edildi.".to_string(), + )); + } + } + } + if clean_rel.as_os_str().is_empty() { + return Ok(None); + } + + let outpath = destination_dir.join(clean_rel); + if let Some(parent) = outpath.parent() { + fs::create_dir_all(parent)?; + let canonical_parent = parent.canonicalize()?; + if !canonical_parent.starts_with(canonical_dest) { + return Err(AppError::Archive( + "Güvenlik Uyarısı: Zip-Slip tespit edildi.".to_string(), + )); + } + } + + Ok(Some(outpath)) + } + + fn extract_7z_pure_rust( + archive_path: &Path, + destination_dir: &Path, + ) -> AppResult { + let canonical_dest = destination_dir.canonicalize()?; + let mut recorded_err: Option = None; + + let res = sevenz_rust2::decompress_file_with_extract_fn( + archive_path, + destination_dir, + |entry, reader, _dest| { + if entry.is_anti_item { + return Ok(true); + } + let outpath = match Self::safe_extract_target( + destination_dir, + &canonical_dest, + entry.name(), + ) { + Ok(Some(p)) => p, + Ok(None) => return Ok(true), + Err(e) => { + let msg = e.to_string(); + recorded_err = Some(e); + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + msg, + ) + .into()); + } + }; + + if entry.is_directory() { + fs::create_dir_all(&outpath)?; + } else { + if let Some(parent) = outpath.parent() { + fs::create_dir_all(parent)?; + } + let mut outfile = File::create(&outpath)?; + std::io::copy(reader, &mut outfile)?; + } + Ok(true) + }, + ); + + if let Some(err) = recorded_err { + return Err(err); + } + res.map_err(|e| AppError::Archive(format!("7Z arşivi okunamadı: {}", e)))?; + Ok(destination_dir.to_path_buf()) + } + + fn extract_zip_pure_rust( + archive_path: &Path, + destination_dir: &Path, + ) -> AppResult { + let file = File::open(archive_path)?; + let mut archive = ZipArchive::new(BufReader::new(file)) + .map_err(|e| AppError::Archive(format!("ZIP arşivi okunamadı: {}", e)))?; + + let canonical_dest = destination_dir.canonicalize()?; + + for i in 0..archive.len() { + let mut file = archive + .by_index(i) + .map_err(|e| AppError::Archive(format!("Arşiv dosyası açılamadı: {}", e)))?; + + let enclosed = match file.enclosed_name() { + Some(p) => p.to_owned(), + None => continue, + }; + + let outpath = destination_dir.join(enclosed); + + // Zip Slip Security Protection + if let Some(parent) = outpath.parent() { + fs::create_dir_all(parent)?; + let canonical_parent = parent.canonicalize()?; + if !canonical_parent.starts_with(&canonical_dest) { + return Err(AppError::Archive( + "Güvenlik Uyarısı: Zip-Slip tespit edildi.".to_string(), + )); + } + } + + if file.is_dir() { + fs::create_dir_all(&outpath)?; + } else { + let mut outfile = File::create(&outpath)?; + std::io::copy(&mut file, &mut outfile)?; + } + } + + Ok(destination_dir.to_path_buf()) + } + + fn extract_via_7zip( + archive_path: &Path, + destination_dir: &Path, + password: Option<&str>, + ) -> AppResult { + let seven_zip = EngineResolver::resolve_7zip(None).ok_or_else(|| { + AppError::Archive( + "Bu arşivi (7Z/RAR) çıkarmak için sistemde 7-Zip kurulu olmalıdır.".to_string(), + ) + })?; + + let mut cmd = Command::new(seven_zip); + #[cfg(windows)] + cmd.creation_flags(0x08000000); + cmd.arg("x") + .arg(archive_path) + .arg(format!("-o{}", destination_dir.display())) + .arg("-y"); + + if let Some(pwd) = password { + if !pwd.is_empty() { + cmd.arg(format!("-p{}", pwd)); + } + } + + let status = cmd + .status() + .map_err(|e| AppError::Archive(format!("7-Zip çalıştırılamadı: {}", e)))?; + + if status.success() { + Ok(destination_dir.to_path_buf()) + } else { + Err(AppError::Archive( + "7-Zip arşiv çıkarma işlemi başarısız oldu (Hatalı şifre veya bozuk arşiv)." + .to_string(), + )) + } + } +} + +fn write_ustar_header( + writer: &mut W, + name: &str, + size: u64, + mtime: u64, + is_dir: bool, +) -> AppResult<()> { + let mut header = [0u8; 512]; + let bytes = name.as_bytes(); + let (prefix_bytes, name_bytes) = if bytes.len() <= 100 { + (&[][..], bytes) + } else if let Some(split) = bytes.iter().rposition(|&b| b == b'/') { + let (p, n) = (&bytes[..split], &bytes[split + 1..]); + if p.len() <= 155 && n.len() <= 100 { + (p, n) + } else { + (&[][..], &bytes[..100.min(bytes.len())]) + } + } else { + (&[][..], &bytes[..100.min(bytes.len())]) + }; + + header[..name_bytes.len()].copy_from_slice(name_bytes); + if !prefix_bytes.is_empty() { + header[345..345 + prefix_bytes.len()].copy_from_slice(prefix_bytes); + } + + let mode = if is_dir { b"0000755\0" } else { b"0000644\0" }; + header[100..108].copy_from_slice(mode); + header[108..116].copy_from_slice(b"0000000\0"); + header[116..124].copy_from_slice(b"0000000\0"); + + let size_str = format!("{:011o}\0", size); + header[124..136].copy_from_slice(size_str.as_bytes()); + let mtime_str = format!("{:011o}\0", mtime & 0o77777777777); + header[136..148].copy_from_slice(mtime_str.as_bytes()); + + header[148..156].copy_from_slice(b" "); + header[156] = if is_dir { b'5' } else { b'0' }; + header[257..263].copy_from_slice(b"ustar\0"); + header[263..265].copy_from_slice(b"00"); + + let checksum: u32 = header.iter().map(|&b| b as u32).sum(); + let cksum_str = format!("{:06o}\0 ", checksum); + header[148..156].copy_from_slice(cksum_str.as_bytes()); + + writer.write_all(&header)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pure_rust_7z_roundtrip_and_tar_gz_creation() -> Result<(), Box> { + let dir = std::env::temp_dir().join(format!("ld_arc_test_{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir)?; + + let src = dir.join("merhaba.txt"); + let payload = b"LD Converter 3.5.0 saf Rust arsiv testi"; + std::fs::write(&src, payload)?; + let src_str = src.to_string_lossy().to_string(); + + let archive_7z = dir.join("paket.7z"); + ArchiveEngine::create_7z_pure_rust(std::slice::from_ref(&src_str), &archive_7z)?; + assert!(archive_7z.exists()); + + let extract_dir = dir.join("extracted"); + ArchiveEngine::extract_archive(&archive_7z.to_string_lossy(), &extract_dir, None)?; + let extracted_bytes = std::fs::read(extract_dir.join("merhaba.txt"))?; + assert_eq!(extracted_bytes, payload); + + let archive_tgz = dir.join("paket.tar.gz"); + ArchiveEngine::create_tar_gz_pure_rust(&[src_str], &archive_tgz)?; + let tgz_bytes = std::fs::read(&archive_tgz)?; + assert!(tgz_bytes.len() > 10); + assert_eq!(&tgz_bytes[..2], &[0x1f, 0x8b]); + + let _ = std::fs::remove_dir_all(&dir); + Ok(()) + } +} diff --git a/src-tauri/src/services/autostart.rs b/src-tauri/src/services/autostart.rs new file mode 100644 index 0000000..3cd8d38 --- /dev/null +++ b/src-tauri/src/services/autostart.rs @@ -0,0 +1,78 @@ +//! Windows oturum açılışında otomatik başlatma (tepside sessiz). +//! +//! Uygulamanın oturum açılışında `--tray` ile (pencere göstermeden) başlamasını yönetir. + +use std::process::{Command, Stdio}; + +use crate::logging; + +const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run"; +const STARTUP_APPROVED_KEY: &str = + r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"; +const VALUE_NAME: &str = "LDConverter"; + +fn reg_command(args: &[&str]) -> Command { + let mut command = Command::new("reg.exe"); + command.args(args).stdin(Stdio::null()).stdout(Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x08000000); + } + command +} + +fn exe_path() -> Option { + std::env::current_exe() + .ok() + .map(|path| path.to_string_lossy().to_string()) +} + +/// Oturum açılışında başlatmayı açar/kapatır (HKCU Run kaydı). +pub fn set_enabled(enabled: bool) { + let Some(exe) = exe_path() else { return }; + + if enabled { + let value = format!("\"{}\" --tray", exe); + let mut command = reg_command(&[ + "add", + RUN_KEY, + "/v", + VALUE_NAME, + "/t", + "REG_SZ", + "/d", + &value, + "/f", + ]); + command.stderr(Stdio::null()); + if command.status().map(|status| status.success()).unwrap_or(false) { + // Görev Yöneticisi tarafından önceden devre dışı bırakılmış bir onay kaydı varsa temizle + let mut clear_approved = + reg_command(&["delete", STARTUP_APPROVED_KEY, "/v", VALUE_NAME, "/f"]); + clear_approved.stderr(Stdio::null()); + let _ = clear_approved.status(); + logging::info("Otomatik başlatma açıldı (HKCU Run)"); + } else { + logging::warn("Otomatik başlatma yazılamadı"); + } + } else { + let mut command = reg_command(&["delete", RUN_KEY, "/v", VALUE_NAME, "/f"]); + command.stderr(Stdio::null()); + let _ = command.status(); + logging::info("Otomatik başlatma kapatıldı"); + } +} + +/// Kayıt defterindeki değer bu exe'ye mi işaret ediyor? +pub fn is_installed_for_current_exe() -> bool { + let Some(exe) = exe_path() else { return false }; + let mut command = reg_command(&["query", RUN_KEY, "/v", VALUE_NAME]); + command.stderr(Stdio::null()); + match command.output() { + Ok(output) if output.status.success() => { + String::from_utf8_lossy(&output.stdout).contains(&exe) + } + _ => false, + } +} diff --git a/src-tauri/src/services/dispatcher.rs b/src-tauri/src/services/dispatcher.rs new file mode 100644 index 0000000..77ab50d --- /dev/null +++ b/src-tauri/src/services/dispatcher.rs @@ -0,0 +1,1315 @@ +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::Instant; + +use rayon::prelude::*; + +use crate::catalog::FormatCatalog; +use crate::error::{AppError, AppResult}; +use crate::models::{ + AppPreferences, ConversionOptions, ConversionResult, OutputDirectoryMode, ProgressEvent, +}; +use crate::services::archive_engine::ArchiveEngine; +use crate::services::docx_writer::DocxWriter; +use crate::services::image_engine::ImageEngine; +use crate::services::math_engine::MathEngine; +use crate::services::media_engine::MediaEngine; +use crate::services::ocr_engine::OcrEngine; +use crate::services::pdf_engine::PdfEngine; +use crate::services::pdf_tools::PdfTools; +use crate::services::progress::ProgressEmitter; +use crate::services::qr_engine::QrEngine; + +pub struct ConversionDispatcher; + +impl ConversionDispatcher { + pub async fn execute_task( + emitter: ProgressEmitter, + input_files: Vec, + target_action_id: String, + options: ConversionOptions, + preferences: AppPreferences, + cancel_flag: Arc, + task_id: String, + ) -> AppResult { + let start_time = Instant::now(); + + if input_files.is_empty() { + return Err(AppError::Generic("Dönüştürülecek dosya seçilmedi.".to_string())); + } + for file in &input_files { + if !Path::new(file).exists() { + return Err(AppError::NotFound(file.clone())); + } + } + + let destination_dir = Self::resolve_destination(&input_files, &options, &preferences)?; + std::fs::create_dir_all(&destination_dir)?; + + let target = target_action_id + .to_lowercase() + .trim_start_matches('.') + .to_string(); + let files = input_files.clone(); + let total_count = files.len(); + let overwrite = options.overwrite_existing; + + let emit = |percent: f64, message: &str, current_file: Option| { + emitter.emit(ProgressEvent { + task_id: task_id.clone(), + percent, + message: message.to_string(), + current_file, + }); + }; + + emit(3.0, "İşlem başlatılıyor...", None); + Self::ensure_not_cancelled(&cancel_flag)?; + + let all_images = files.iter().all(|f| FormatCatalog::is_image(f)); + let any_media = files + .iter() + .any(|f| FormatCatalog::is_video(f) || FormatCatalog::is_audio(f)); + + let image_targets = [ + "png", "jpg", "jpeg", "webp", "avif", "jxl", "jpegxl", "bmp", "tiff", "tif", "ico", + "gif", "pdf", "compress_image", + ]; + let media_targets = [ + "mp4", + "mkv", + "webm", + "mp3", + "wav", + "aac", + "flac", + "ogg", + "compress_video", + "compress_audio", + ]; + + let mut output_paths: Vec = Vec::new(); + + // 1) QR okuma (görsel ve PDF) + if target == "qr_read" { + for (idx, file) in files.iter().enumerate() { + Self::ensure_not_cancelled(&cancel_flag)?; + emit( + Self::step_percent(idx, total_count), + "QR kod okunuyor...", + Some(file.clone()), + ); + let text = Self::read_qr_any(file)?; + let stem = Path::new(file) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("qr"); + let out_txt = ImageEngine::get_unique_path( + &destination_dir.join(format!("{}_QR.txt", stem)), + overwrite, + ); + std::fs::write(&out_txt, text)?; + output_paths.push(out_txt); + } + } + // 2) Arşivden klasöre çıkarma + else if target == "extract_folder" { + for (idx, file) in files.iter().enumerate() { + Self::ensure_not_cancelled(&cancel_flag)?; + emit( + Self::step_percent(idx, total_count), + "Arşiv çıkarılıyor...", + Some(file.clone()), + ); + let f_clone = file.clone(); + // Her arşiv kendi alt klasörüne çıkarılır: kaynak klasörü kirletmez. + let stem = Path::new(file) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("arsiv"); + let extract_dir = ImageEngine::get_unique_path( + &destination_dir.join(format!("{}_Cikarilan", stem)), + false, + ); + let password = options.archive_password.clone(); + let extracted = tokio::task::spawn_blocking(move || { + ArchiveEngine::extract_archive(&f_clone, &extract_dir, password.as_deref()) + }) + .await + .map_err(|e| AppError::Generic(format!("Arşiv iş parçacığı hatası: {}", e)))??; + output_paths.push(extracted); + } + } + // 3) Arşiv oluşturma (ZIP / 7Z / TAR.GZ) + else if matches!(target.as_str(), "zip" | "7z" | "tar_gz") { + emit(20.0, "Arşiv oluşturuluyor...", None); + let (file_name, kind) = match target.as_str() { + "7z" => ("arsiv.7z", "7z"), + "tar_gz" => ("arsiv.tar.gz", "tar_gz"), + _ => ("arsiv.zip", "zip"), + }; + let out_path = ImageEngine::get_unique_path(&destination_dir.join(file_name), overwrite); + let files_clone = files.clone(); + let created = tokio::task::spawn_blocking(move || match kind { + "7z" => ArchiveEngine::create_7z(&files_clone, &out_path), + "tar_gz" => ArchiveEngine::create_tar_gz(&files_clone, &out_path), + _ => ArchiveEngine::create_zip(&files_clone, &out_path), + }) + .await + .map_err(|e| AppError::Generic(format!("Arşiv iş parçacığı hatası: {}", e)))??; + output_paths.push(created); + } + // 4) Yeni klasöre toplama + else if target == "copy_folder" { + emit(20.0, "Dosyalar yeni klasöre kopyalanıyor...", None); + let files_clone = files.clone(); + let dest_clone = destination_dir.clone(); + let created = + tokio::task::spawn_blocking(move || ArchiveEngine::copy_to_folder(&files_clone, &dest_clone)) + .await + .map_err(|e| AppError::Generic(format!("Kopyalama iş parçacığı hatası: {}", e)))??; + output_paths.push(created); + } + // 5) PDF birleştirme (görsel + PDF karışık) + else if target == "pdf_merge" { + emit(20.0, "Belgeler birleştiriliyor...", None); + let out_path = ImageEngine::get_unique_path( + &destination_dir.join("Birlestirilmis_Belge.pdf"), + overwrite, + ); + let files_clone = files.clone(); + let opts = options.clone(); + let merged = tokio::task::spawn_blocking(move || { + PdfEngine::merge(&files_clone, &out_path, &opts) + }) + .await + .map_err(|e| AppError::Generic(format!("PDF iş parçacığı hatası: {}", e)))??; + output_paths.push(merged); + } + // 6) PDF ayırma / sıkıştırma + else if target == "pdf_split" { + for (idx, file) in files.iter().enumerate() { + Self::ensure_not_cancelled(&cancel_flag)?; + if !FormatCatalog::is_pdf(file) { + return Err(AppError::UnsupportedFormat(format!( + "{} PDF değil; sayfalara ayırmak için PDF seçin.", + file + ))); + } + emit( + Self::step_percent(idx, total_count), + "PDF sayfaları ayrılıyor...", + Some(file.clone()), + ); + let f_clone = file.clone(); + let dest_clone = destination_dir.clone(); + let opts = options.clone(); + let splits = tokio::task::spawn_blocking(move || { + PdfEngine::split_pdf(&f_clone, &dest_clone, &opts) + }) + .await + .map_err(|e| AppError::Generic(format!("PDF iş parçacığı hatası: {}", e)))??; + output_paths.extend(splits); + } + } + // 6b) PDF sıkıştırma ve kısıtlama kaldırma + else if target == "pdf_compress" { + for (idx, file) in files.iter().enumerate() { + Self::ensure_not_cancelled(&cancel_flag)?; + if !FormatCatalog::is_pdf(file) { + return Err(AppError::UnsupportedFormat(format!( + "{} PDF değil; sıkıştırmak için PDF seçin.", + file + ))); + } + emit( + Self::step_percent(idx, total_count), + "PDF sıkıştırılıyor...", + Some(file.clone()), + ); + let f_clone = file.clone(); + let stem = Path::new(file) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("belge") + .to_string(); + let out_path = ImageEngine::get_unique_path( + &destination_dir.join(format!("{}_compressed.pdf", stem)), + overwrite, + ); + let opts = options.clone(); + let compressed = tokio::task::spawn_blocking(move || { + PdfEngine::compress_pdf(&f_clone, &out_path, &opts) + }) + .await + .map_err(|e| AppError::Generic(format!("PDF iş parçacığı hatası: {}", e)))??; + output_paths.push(compressed); + } + } + // 7) PDF -> TXT (taranmış sayfalarda OCR) + else if target == "pdf_to_txt" { + for (idx, file) in files.iter().enumerate() { + Self::ensure_not_cancelled(&cancel_flag)?; + emit( + Self::step_percent(idx, total_count), + "PDF metni çıkarılıyor...", + Some(file.clone()), + ); + let f_clone = file.clone(); + let opts = options.clone(); + let out_dir = destination_dir.clone(); + let txt_path = tokio::task::spawn_blocking(move || { + Self::pdf_to_txt(&f_clone, &out_dir, &opts) + }) + .await + .map_err(|e| AppError::Generic(format!("PDF iş parçacığı hatası: {}", e)))??; + output_paths.push(txt_path); + } + } + // 8) PDF -> DOCX (düz metin) ve Denklem DOCX + else if target == "pdf_to_docx" || target == "pdf_to_math_docx" { + for (idx, file) in files.iter().enumerate() { + Self::ensure_not_cancelled(&cancel_flag)?; + emit( + Self::step_percent(idx, total_count), + "Word belgesi oluşturuluyor...", + Some(file.clone()), + ); + if !FormatCatalog::is_pdf(file) { + return Err(AppError::UnsupportedFormat(format!( + "{} PDF değil.", + file + ))); + } + let f_clone = file.clone(); + let dest_clone = destination_dir.clone(); + let opts = options.clone(); + let preserve_equations = target == "pdf_to_math_docx"; + let docx = tokio::task::spawn_blocking(move || { + Self::pdf_to_docx(&f_clone, &dest_clone, &opts, preserve_equations) + }) + .await + .map_err(|e| AppError::Generic(format!("PDF iş parçacığı hatası: {}", e)))??; + output_paths.push(docx); + } + } + // 9) Markdown -> Denklem DOCX + else if target == "docx_math" { + for (idx, file) in files.iter().enumerate() { + Self::ensure_not_cancelled(&cancel_flag)?; + emit( + Self::step_percent(idx, total_count), + "Denklem DOCX dönüştürülüyor...", + Some(file.clone()), + ); + let f_clone = file.clone(); + let dest_clone = destination_dir.clone(); + let is_pdf = FormatCatalog::is_pdf(file); + let out_docx = tokio::task::spawn_blocking(move || { + if is_pdf { + let opts = ConversionOptions::default(); + Self::pdf_to_docx(&f_clone, &dest_clone, &opts, true) + } else { + MathEngine::convert_to_math_docx(&f_clone, &dest_clone, overwrite).or_else( + |_| { + // Harici denklem motoru yoksa: LaTeX kaynağı korunarak düz DOCX + crate::services::DocumentEngine::convert( + &f_clone, + "docx", + &dest_clone, + overwrite, + ) + }, + ) + } + }) + .await + .map_err(|e| AppError::Generic(format!("Denklem motoru hatası: {}", e)))??; + output_paths.push(out_docx); + } + } + // 10) PDF sayfalarını görsele aktarma + else if matches!(target.as_str(), "pdf_to_images" | "pdf_to_jpg" | "pdf_to_jxl") { + let img_format = match target.as_str() { + "pdf_to_jpg" => "jpg", + "pdf_to_jxl" => "jxl", + _ => "png", + }; + for (idx, file) in files.iter().enumerate() { + Self::ensure_not_cancelled(&cancel_flag)?; + if !FormatCatalog::is_pdf(file) { + return Err(AppError::UnsupportedFormat(format!( + "{} PDF değil.", + file + ))); + } + emit( + Self::step_percent(idx, total_count), + "PDF sayfaları görsele çevriliyor...", + Some(file.clone()), + ); + let f_clone = file.clone(); + let dest_clone = destination_dir.clone(); + let opts = options.clone(); + let images = tokio::task::spawn_blocking(move || { + Self::pdf_pages_to_images(&f_clone, &dest_clone, &opts, img_format) + }) + .await + .map_err(|e| AppError::Generic(format!("PDF iş parçacığı hatası: {}", e)))??; + output_paths.extend(images); + } + } + // 11) Görsel -> TXT / DOCX (OCR) + else if target == "img_to_txt" || target == "img_to_docx" { + let mut pages: Vec = Vec::new(); + for (idx, file) in files.iter().enumerate() { + Self::ensure_not_cancelled(&cancel_flag)?; + emit( + Self::step_percent(idx, total_count), + "OCR metni tanınıyor...", + Some(file.clone()), + ); + let f_clone = file.clone(); + let text = tokio::task::spawn_blocking(move || OcrEngine::recognize_image(&f_clone)) + .await + .map_err(|e| AppError::Generic(format!("OCR iş parçacığı hatası: {}", e)))??; + if !text.trim().is_empty() { + pages.push(text); + } + } + if pages.is_empty() { + return Err(AppError::Engine( + "Seçilen görselde okunabilir bir metin (OCR) bulunamadı.".to_string(), + )); + } + output_paths.push(Self::write_ocr_output( + &files, + &destination_dir, + &pages, + target == "img_to_docx", + overwrite, + )?); + } + // 12) Görsel dönüşümleri (PNG/JPG/WebP/JXL/AVIF/BMP/TIFF/ICO/GIF/PDF/Sıkıştır) + else if all_images && image_targets.contains(&target.as_str()) { + if target == "pdf" || target == "gif" { + if target == "pdf" { + emit(25.0, "Görsellerden PDF oluşturuluyor...", None); + let out_path = ImageEngine::get_unique_path( + &destination_dir.join(if files.len() == 1 { + format!( + "{}.pdf", + Path::new(&files[0]) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("belge") + ) + } else { + "Birlestirilmis_Gorseller.pdf".to_string() + }), + overwrite, + ); + let files_clone = files.clone(); + let opts = options.clone(); + let created = tokio::task::spawn_blocking(move || { + ImageEngine::create_pdf(&files_clone, &out_path, &opts) + }) + .await + .map_err(|e| AppError::Generic(format!("Görsel iş parçacığı hatası: {}", e)))??; + output_paths.push(created); + } else { + // Çoklu görsel -> animasyonlu GIF + emit(25.0, "Animasyonlu GIF oluşturuluyor...", None); + let out_path = ImageEngine::get_unique_path( + &destination_dir.join("animasyon.gif"), + overwrite, + ); + let files_clone = files.clone(); + let created = tokio::task::spawn_blocking(move || { + ImageEngine::create_animated_gif(&files_clone, &out_path, 10) + }) + .await + .map_err(|e| AppError::Generic(format!("Görsel iş parçacığı hatası: {}", e)))??; + output_paths.push(created); + } + } else if files.len() > 1 { + let files_clone = files.clone(); + let target_clone = target.clone(); + let dest_clone = destination_dir.clone(); + let mut opts_clone = options.clone(); + if target_clone == "compress_image" { + opts_clone.image_quality = opts_clone.image_quality.min(80); + } + let emitter_clone = emitter.clone(); + let task_clone = task_id.clone(); + let cancel_clone = cancel_flag.clone(); + let completed = Arc::new(AtomicUsize::new(0)); + + let mut indexed_outputs = tokio::task::spawn_blocking(move || { + files_clone + .par_iter() + .enumerate() + .map(|(idx, file)| { + Self::ensure_not_cancelled(&cancel_clone)?; + let res = if target_clone == "compress_image" { + ImageEngine::compress_image(file, &dest_clone, &opts_clone) + } else { + ImageEngine::convert_single( + file, + &target_clone, + &dest_clone, + &opts_clone, + ) + }?; + let done = completed.fetch_add(1, Ordering::Relaxed) + 1; + emitter_clone.emit(ProgressEvent { + task_id: task_clone.clone(), + percent: Self::step_percent(done, total_count), + message: "Görseller paralel işleniyor...".to_string(), + current_file: Some(file.clone()), + }); + Ok::<(usize, PathBuf), AppError>((idx, res)) + }) + .collect::>>() + }) + .await + .map_err(|e| AppError::Generic(format!("Görsel iş parçacığı hatası: {}", e)))??; + + indexed_outputs.sort_by_key(|(idx, _)| *idx); + output_paths.extend(indexed_outputs.into_iter().map(|(_, p)| p)); + } else { + for (idx, file) in files.iter().enumerate() { + Self::ensure_not_cancelled(&cancel_flag)?; + emit( + Self::step_percent(idx, total_count), + "Görsel işleniyor...", + Some(file.clone()), + ); + let f_clone = file.clone(); + let act_clone = target.clone(); + let dest_clone = destination_dir.clone(); + let mut opts_clone = options.clone(); + if act_clone == "compress_image" { + // "Sıkıştır" küçültme demektir: tam kalite (%100) varsayılanı + // etkisiz kalmasın diye üst sınır uygulanır. + opts_clone.image_quality = opts_clone.image_quality.min(80); + } + let converted = tokio::task::spawn_blocking(move || { + if act_clone == "compress_image" { + ImageEngine::compress_image(&f_clone, &dest_clone, &opts_clone) + } else { + ImageEngine::convert_single(&f_clone, &act_clone, &dest_clone, &opts_clone) + } + }) + .await + .map_err(|e| AppError::Generic(format!("Görsel iş parçacığı hatası: {}", e)))??; + output_paths.push(converted); + } + } + } + // 13) Video ve ses dönüşümleri + else if any_media || media_targets.contains(&target.as_str()) { + let is_audio_target = matches!( + target.as_str(), + "mp3" | "wav" | "aac" | "flac" | "ogg" | "compress_audio" + ); + if files.len() > 1 && is_audio_target { + let files_clone = files.clone(); + let target_clone = target.clone(); + let dest_clone = destination_dir.clone(); + let emitter_clone = emitter.clone(); + let task_clone = task_id.clone(); + let cancel_clone = cancel_flag.clone(); + let mut opts_clone = options.clone(); + if target_clone == "compress_audio" { + let bitrate = opts_clone.audio_bitrate_kbps.unwrap_or(192).min(160); + opts_clone.audio_bitrate_kbps = Some(bitrate); + } + let completed = Arc::new(AtomicUsize::new(0)); + + let mut indexed_outputs = tokio::task::spawn_blocking(move || { + files_clone + .par_iter() + .enumerate() + .map(|(idx, file)| { + Self::ensure_not_cancelled(&cancel_clone)?; + let res = MediaEngine::convert_media( + &emitter_clone, + file, + &target_clone, + &dest_clone, + &opts_clone, + &task_clone, + &cancel_clone, + )?; + let done = completed.fetch_add(1, Ordering::Relaxed) + 1; + emitter_clone.emit(ProgressEvent { + task_id: task_clone.clone(), + percent: Self::step_percent(done, total_count), + message: "Ses dosyaları paralel dönüştürülüyor...".to_string(), + current_file: Some(file.clone()), + }); + Ok::<(usize, PathBuf), AppError>((idx, res)) + }) + .collect::>>() + }) + .await + .map_err(|e| AppError::Generic(format!("Ses iş parçacığı hatası: {}", e)))??; + + indexed_outputs.sort_by_key(|(idx, _)| *idx); + output_paths.extend(indexed_outputs.into_iter().map(|(_, p)| p)); + } else { + for (idx, file) in files.iter().enumerate() { + Self::ensure_not_cancelled(&cancel_flag)?; + emit( + Self::step_percent(idx, total_count), + "Medya dönüştürülüyor...", + Some(file.clone()), + ); + let emitter_clone = emitter.clone(); + let f_clone = file.clone(); + let act_clone = target.clone(); + let dest_clone = destination_dir.clone(); + let mut opts_clone = options.clone(); + if act_clone == "compress_video" { + // Sıkıştırma, tam kalite (CRF 18) varsayılanında boyut küçültmez. + let crf = opts_clone.video_crf.unwrap_or(23).max(26); + opts_clone.video_crf = Some(crf); + } else if act_clone == "compress_audio" { + let bitrate = opts_clone.audio_bitrate_kbps.unwrap_or(192).min(160); + opts_clone.audio_bitrate_kbps = Some(bitrate); + } + let task_clone = task_id.clone(); + let cancel_clone = cancel_flag.clone(); + let converted = tokio::task::spawn_blocking(move || { + MediaEngine::convert_media( + &emitter_clone, + &f_clone, + &act_clone, + &dest_clone, + &opts_clone, + &task_clone, + &cancel_clone, + ) + }) + .await + .map_err(|e| AppError::Generic(format!("Medya iş parçacığı hatası: {}", e)))??; + output_paths.push(converted); + } + } + } + // 14) Ofis / belge dönüşümleri + else if target == "pdf" + || target == "docx" + || target == "txt" + || target == "html" + || files.iter().all(|f| FormatCatalog::is_document(f)) + { + if files.len() > 1 && files.iter().all(|f| !FormatCatalog::is_pdf(f)) { + let files_clone = files.clone(); + let target_clone = target.clone(); + let dest_clone = destination_dir.clone(); + let emitter_clone = emitter.clone(); + let task_clone = task_id.clone(); + let cancel_clone = cancel_flag.clone(); + let completed = Arc::new(AtomicUsize::new(0)); + + let mut indexed_outputs = tokio::task::spawn_blocking(move || { + files_clone + .par_iter() + .enumerate() + .map(|(idx, file)| { + Self::ensure_not_cancelled(&cancel_clone)?; + let res = Self::convert_single_document( + file, + &target_clone, + &dest_clone, + overwrite, + )?; + let done = completed.fetch_add(1, Ordering::Relaxed) + 1; + emitter_clone.emit(ProgressEvent { + task_id: task_clone.clone(), + percent: Self::step_percent(done, total_count), + message: "Belgeler paralel dönüştürülüyor...".to_string(), + current_file: Some(file.clone()), + }); + Ok::<(usize, PathBuf), AppError>((idx, res)) + }) + .collect::>>() + }) + .await + .map_err(|e| AppError::Generic(format!("Belge iş parçacığı hatası: {}", e)))??; + + indexed_outputs.sort_by_key(|(idx, _)| *idx); + output_paths.extend(indexed_outputs.into_iter().map(|(_, p)| p)); + } else { + for (idx, file) in files.iter().enumerate() { + Self::ensure_not_cancelled(&cancel_flag)?; + if FormatCatalog::is_pdf(file) && target == "docx" { + emit( + Self::step_percent(idx, total_count), + "Word belgesi oluşturuluyor...", + Some(file.clone()), + ); + let f_clone = file.clone(); + let dest_clone = destination_dir.clone(); + let opts = options.clone(); + let docx = tokio::task::spawn_blocking(move || { + Self::pdf_to_docx(&f_clone, &dest_clone, &opts, false) + }) + .await + .map_err(|e| AppError::Generic(format!("PDF iş parçacığı hatası: {}", e)))??; + output_paths.push(docx); + continue; + } + + emit( + Self::step_percent(idx, total_count), + "Belge dönüştürülüyor...", + Some(file.clone()), + ); + let f_clone = file.clone(); + let act_clone = target.clone(); + let dest_clone = destination_dir.clone(); + let converted = tokio::task::spawn_blocking(move || { + Self::convert_single_document(&f_clone, &act_clone, &dest_clone, overwrite) + }) + .await + .map_err(|e| AppError::Generic(format!("Belge motoru hatası: {}", e)))??; + output_paths.push(converted); + } + } + } + // 15) Bilinmeyen kombinasyon: güvenli yedek olarak ZIP + else { + emit(20.0, "Arşiv oluşturuluyor...", None); + let out_path = + ImageEngine::get_unique_path(&destination_dir.join("arsiv.zip"), overwrite); + let files_clone = files.clone(); + let created = tokio::task::spawn_blocking(move || { + ArchiveEngine::create_zip(&files_clone, &out_path) + }) + .await + .map_err(|e| AppError::Generic(format!("Arşiv iş parçacığı hatası: {}", e)))??; + output_paths.push(created); + } + + if output_paths.is_empty() { + return Err(AppError::Generic( + "Dönüştürme tamamlandı ancak çıktı dosyası üretilemedi.".to_string(), + )); + } + + emit(100.0, "Tamamlandı!", None); + + let output_strings: Vec = output_paths + .into_iter() + .map(|p| p.to_string_lossy().to_string()) + .collect(); + + Ok(ConversionResult { + success: true, + output_files: output_strings, + error_message: None, + duration_ms: start_time.elapsed().as_millis() as u64, + }) + } + + // ------------------------------------------------------------- helpers + fn convert_single_document( + file: &str, + target: &str, + destination_dir: &Path, + overwrite: bool, + ) -> AppResult { + let is_markdown = FormatCatalog::is_markdown(file); + if is_markdown && target == "docx" { + if let Ok(path) = MathEngine::convert_to_math_docx(file, destination_dir, overwrite) { + return Ok(path); + } + } + + let ext = FormatCatalog::normalize_extension(file); + if matches!( + ext.as_str(), + "docx" | "odt" | "xlsx" | "xls" | "pptx" | "rtf" | "html" + ) { + if let Ok(path) = crate::services::OfficeEngine::convert(file, target, destination_dir) + { + return Ok(path); + } + } + + crate::services::DocumentEngine::convert(file, target, destination_dir, overwrite) + } + + fn ensure_not_cancelled(cancel_flag: &Arc) -> AppResult<()> { + if cancel_flag.load(Ordering::Relaxed) { + Err(AppError::Cancelled) + } else { + Ok(()) + } + } + + fn step_percent(idx: usize, total: usize) -> f64 { + if total == 0 { + 10.0 + } else { + (idx as f64 / total as f64) * 85.0 + 10.0 + } + } + + pub fn read_qr_any(file: &str) -> AppResult { + if FormatCatalog::is_pdf(file) { + // 1) WinRT (Windows.Data.Pdf) ile sayfaları rasterleştirip QR ara + if PdfTools::available() { + let temp_dir = + std::env::temp_dir().join(format!("ld_qr_pages_{}", uuid::Uuid::new_v4())); + let rendered = PdfTools::render_pages(file, None, &temp_dir, 200, "png"); + if let Ok(paths) = rendered { + for path in paths { + let decoded = QrEngine::read_qr_from_image(&path.to_string_lossy()); + if let Ok(text) = decoded { + let _ = std::fs::remove_dir_all(&temp_dir); + return Ok(text); + } + } + } + let _ = std::fs::remove_dir_all(&temp_dir); + } + // 2) Gömülü bitmap'lerde QR ara + let page_count = PdfEngine::page_count(file)?; + for page in 1..=page_count as u32 { + if let Ok(images) = PdfEngine::extract_page_images(file, page) { + for img in images { + if let Ok(text) = QrEngine::read_qr_from_dynamic_image(&img) { + return Ok(text); + } + } + } + } + Err(AppError::Generic( + "PDF içinde QR kod bulunamadı.".to_string(), + )) + } else { + QrEngine::read_qr_from_image(file) + } + } + + fn write_ocr_output( + files: &[String], + destination_dir: &Path, + pages: &[String], + as_docx: bool, + overwrite: bool, + ) -> AppResult { + let base_name = if files.len() == 1 { + format!( + "{}_OCR", + Path::new(&files[0]) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("belge") + ) + } else { + "Birlestirilmis_OCR".to_string() + }; + + if as_docx { + let path = ImageEngine::get_unique_path( + &destination_dir.join(format!("{}.docx", base_name)), + overwrite, + ); + DocxWriter::create_from_pages(&path, pages)?; + Ok(path) + } else { + let path = ImageEngine::get_unique_path( + &destination_dir.join(format!("{}.txt", base_name)), + overwrite, + ); + std::fs::write(&path, pages.join("\n\n---\n\n"))?; + Ok(path) + } + } + + fn pdf_to_txt( + input: &str, + destination_dir: &Path, + options: &ConversionOptions, + ) -> AppResult { + let mut text = String::new(); + let mut empty_pages: Vec = Vec::new(); + let mut found_text = false; + + // 1) Dahili saf Rust PDF metin çözücü + if let Ok(pages) = crate::services::pdf_text::extract_pages(input) { + for (index, page) in pages.iter().enumerate() { + let page_num = (index + 1) as u32; + let cleaned = page.trim().to_string(); + if cleaned.is_empty() { + empty_pages.push(page_num); + } else { + found_text = true; + } + text.push_str(&format!("--- Sayfa {} ---\n{}\n\n", page_num, cleaned)); + } + } + + // 2) Yedek: lopdf metin çıkarma + if text.is_empty() { + let (pages, empties) = PdfEngine::extract_text(input, options)?; + empty_pages = empties; + for (page_num, content) in pages { + if !content.trim().is_empty() { + found_text = true; + } + text.push_str(&format!("--- Sayfa {} ---\n{}\n\n", page_num, content)); + } + } + + // 4) Metin katmanı boş sayfalarda OCR + for page in empty_pages { + if let Ok(ocr) = Self::ocr_pdf_page(input, page) { + if !ocr.trim().is_empty() { + text.push_str(&format!("--- Sayfa {} (OCR) ---\n{}\n\n", page, ocr)); + found_text = true; + } + } + } + + if !found_text { + return Err(AppError::Pdf( + "PDF içinde okunabilir metin bulunamadı (taranmış sayfalar için OCR gerekli)." + .to_string(), + )); + } + + let stem = Path::new(input) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("belge"); + let out = ImageEngine::get_unique_path( + &destination_dir.join(format!("{}.txt", stem)), + options.overwrite_existing, + ); + std::fs::write(&out, text)?; + Ok(out) + } + + fn pdf_page_texts(input: &str, options: &ConversionOptions) -> AppResult> { + let mut pages: Vec<(u32, String)> = Vec::new(); + let mut empty_pages: Vec = Vec::new(); + + if let Ok(extracted) = crate::services::pdf_text::extract_pages(input) { + let total = extracted.len(); + let selected = PdfEngine::parse_page_range(options.pdf_page_range.as_deref(), total); + for (index, content) in extracted.into_iter().enumerate() { + let page_num = (index + 1) as u32; + if !selected.contains(&(page_num as usize)) { + continue; + } + if content.trim().is_empty() { + empty_pages.push(page_num); + } + pages.push((page_num, content)); + } + } + if pages.is_empty() { + let (extracted, empties) = PdfEngine::extract_text(input, options)?; + pages = extracted; + empty_pages = empties; + } + + let mut texts = Vec::new(); + for (page_num, content) in pages { + let page_text = if empty_pages.contains(&page_num) { + Self::ocr_pdf_page(input, page_num).unwrap_or_default() + } else { + content + }; + if !page_text.trim().is_empty() { + texts.push(page_text); + } + } + Ok(texts) + } + + fn ocr_pdf_page(input: &str, page: u32) -> AppResult { + // 1) WinRT (Windows.Data.Pdf) ile yüksek çözünürlüklü sayfa görüntüsü + if PdfTools::available() { + let temp_dir = + std::env::temp_dir().join(format!("ld_pdf_ocr_render_{}", uuid::Uuid::new_v4())); + let page_arg = page.to_string(); + if let Ok(paths) = + PdfTools::render_pages(input, Some(&page_arg), &temp_dir, 300, "png") + { + for path in paths { + let result = OcrEngine::recognize_image(&path.to_string_lossy()); + if let Ok(text) = result { + if !text.trim().is_empty() { + let _ = std::fs::remove_dir_all(&temp_dir); + return Ok(text); + } + } + } + } + let _ = std::fs::remove_dir_all(&temp_dir); + } + + if let Ok(images) = PdfEngine::extract_page_images(input, page) { + for img in images { + let temp = std::env::temp_dir().join(format!( + "ld_pdf_ocr_{}.png", + uuid::Uuid::new_v4() + )); + if img.save_with_format(&temp, image::ImageFormat::Png).is_ok() { + let result = OcrEngine::recognize_image(&temp.to_string_lossy()); + let _ = std::fs::remove_file(&temp); + if let Ok(text) = result { + if !text.trim().is_empty() { + return Ok(text); + } + } + } + } + } + + let temp_dir = std::env::temp_dir().join(format!("ld_pdf_render_{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&temp_dir)?; + let opts = ConversionOptions::default(); + let result = match Self::render_text_page_with_gdi( + input, + page, + &std::env::temp_dir(), + "png", + &opts, + ) { + Some(png) => { + let text = OcrEngine::recognize_image(&png.to_string_lossy()); + let _ = std::fs::remove_file(&png); + text + } + None => Err(AppError::Engine( + "Bu PDF sayfası metin içermiyor ve gömülü görüntü bulunamadı; OCR uygulanamadı." + .to_string(), + )), + }; + let _ = std::fs::remove_dir_all(&temp_dir); + result + } + + /// PDF sayfası metnini GDI ile yeniden çizip görsele aktarır (harici motor gerekmez). + fn render_text_page_with_gdi( + input: &str, + page: u32, + destination_dir: &Path, + img_format: &str, + options: &ConversionOptions, + ) -> Option { + #[cfg(windows)] + { + let pages = crate::services::pdf_text::extract_pages(input).ok()?; + let text = pages.get(page as usize - 1)?.clone(); + if text.trim().is_empty() { + return None; + } + let images = + crate::services::gdi_render::render_text_pages(&text, 26, 1240, 1754, 90).ok()?; + let first = image::DynamicImage::ImageRgb8(images.into_iter().next()?); + let stem = Path::new(input).file_stem()?.to_str()?.to_string(); + let out = ImageEngine::get_unique_path( + &destination_dir.join(format!( + "{}_sayfa_{}.{}", + stem, + page, + Self::image_ext(img_format) + )), + false, + ); + if img_format == "png" { + first + .save_with_format(&out, image::ImageFormat::Png) + .ok()?; + Some(out) + } else { + let temp = std::env::temp_dir().join(format!( + "ld_gdi_{}.png", + uuid::Uuid::new_v4() + )); + first + .save_with_format(&temp, image::ImageFormat::Png) + .ok()?; + let converted = ImageEngine::convert_single( + &temp.to_string_lossy(), + img_format, + destination_dir, + options, + ) + .ok(); + let _ = std::fs::remove_file(&temp); + let converted = converted?; + if converted != out { + std::fs::rename(&converted, &out).ok()?; + } + Some(out) + } + } + #[cfg(not(windows))] + { + let _ = (input, page, destination_dir, img_format, options); + None + } + } + + fn pdf_to_docx( + input: &str, + destination_dir: &Path, + options: &ConversionOptions, + preserve_equations: bool, + ) -> AppResult { + let stem = Path::new(input) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("belge"); + let out = ImageEngine::get_unique_path( + &destination_dir.join(format!("{}.docx", stem)), + options.overwrite_existing, + ); + + // 1) Endüstriyel düzeye yükseltilmiş %100 Saf Rust PDF Yorumlayıcı ve Düzen Motoru + // (Sayfa Düzeni, 2 Sütun, Tablolar, Görseller ve Geometrik Matematik OMML) + if let Ok(res) = crate::services::pdf_parser::convert_pdf_to_docx(input, &out, preserve_equations) { + if res.exists() { + return Ok(res); + } + } + + // 2) Denklem korumalı ikincil dönüşüm: dahili saf Rust OMML motoru + if preserve_equations { + if let Ok(path) = MathEngine::convert_to_math_docx(input, destination_dir, true) { + if path.exists() { + if path != out { + std::fs::rename(&path, &out)?; + } + return Ok(out); + } + } + } + + // 3) Güvenilir metin tabanlı dönüşüm (taranmış sayfalarda OCR) + let page_texts = Self::pdf_page_texts(input, options)?; + + if page_texts.is_empty() { + return Err(AppError::Pdf( + "PDF içinde Word belgesine aktarılacak metin bulunamadı.".to_string(), + )); + } + + DocxWriter::create_from_pages(&out, &page_texts)?; + Ok(out) + } + + fn pdf_pages_to_images( + input: &str, + destination_dir: &Path, + options: &ConversionOptions, + img_format: &str, + ) -> AppResult> { + let page_count = PdfEngine::page_count(input)?; + let stem = Path::new(input) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("belge"); + let selected = PdfEngine::parse_page_range(options.pdf_page_range.as_deref(), page_count); + + // 1) WinRT (Windows.Data.Pdf) ile sayfaları gerçek görüntü olarak rasterleştir + if PdfTools::available() { + let temp_dir = + std::env::temp_dir().join(format!("ld_pdf_render_{}", uuid::Uuid::new_v4())); + let rendered = PdfTools::render_pages( + input, + options.pdf_page_range.as_deref(), + &temp_dir, + 200, + "png", + ); + if let Ok(paths) = rendered { + let mut outputs = Vec::new(); + for (index, png) in paths.iter().enumerate() { + let page = Self::page_from_render_name(png).unwrap_or(index as u32 + 1); + let out = ImageEngine::get_unique_path( + &destination_dir.join(format!( + "{}_sayfa_{}.{}", + stem, + page, + Self::image_ext(img_format) + )), + false, + ); + if img_format == "png" { + if std::fs::rename(png, &out).is_err() { + std::fs::copy(png, &out)?; + } + } else { + let converted = ImageEngine::convert_single( + &png.to_string_lossy(), + img_format, + destination_dir, + options, + )?; + if converted != out { + std::fs::rename(&converted, &out)?; + } + } + outputs.push(out); + } + let _ = std::fs::remove_dir_all(&temp_dir); + if !outputs.is_empty() { + return Ok(outputs); + } + } else { + let _ = std::fs::remove_dir_all(&temp_dir); + } + } + + // 2) Yedek: gömülü bitmap'ler / metin tabanlı GDI çizimi + let (_, empty_pages) = + PdfEngine::extract_text(input, &ConversionOptions::default()).unwrap_or_default(); + let mut outputs = Vec::new(); + + for page in selected { + let scanned = empty_pages.contains(&(page as u32)); + + if scanned { + // Taranmış sayfa: gömülü bitmap'i doğrudan dışa aktar + let embedded = PdfEngine::extract_page_images(input, page as u32).unwrap_or_default(); + if !embedded.is_empty() { + for (index, img) in embedded.into_iter().enumerate() { + let out = ImageEngine::get_unique_path( + &destination_dir.join(format!( + "{}_Sayfa_{:02}_Gorsel{:02}.{}", + stem, + page, + index + 1, + Self::image_ext(img_format) + )), + false, + ); + Self::save_dynamic_image(img, &out, img_format, options)?; + outputs.push(out); + } + continue; + } + } + + // Metin/vektör sayfa: sayfa metnini GDI ile yeniden çiz + match Self::render_text_page_with_gdi( + input, + page as u32, + destination_dir, + img_format, + options, + ) { + Some(rendered) => outputs.push(rendered), + None => { + return Err(AppError::Engine(format!( + "PDF sayfası {} görsele çevrilemedi: sayfada metin ve gömülü görüntü bulunamadı \ + (WinRT Windows.Data.Pdf da başarısız oldu).", + page + ))) + } + } + } + + Ok(outputs) + } + + fn page_from_render_name(path: &Path) -> Option { + path.file_stem() + .and_then(|s| s.to_str()) + .and_then(|stem| stem.rsplit('_').next()) + .and_then(|num| num.parse::().ok()) + } + + fn image_ext(format: &str) -> &'static str { + match format { + "jpg" | "jpeg" => "jpg", + "jxl" => "jxl", + _ => "png", + } + } + + fn save_dynamic_image( + img: image::DynamicImage, + output_path: &Path, + format: &str, + options: &ConversionOptions, + ) -> AppResult<()> { + match format { + "jpg" | "jpeg" => { + let rgb = img.to_rgb8(); + let file = std::fs::File::create(output_path)?; + let mut writer = std::io::BufWriter::new(file); + let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality( + &mut writer, + options.image_quality.clamp(10, 98), + ); + encoder.encode( + rgb.as_raw(), + rgb.width(), + rgb.height(), + image::ExtendedColorType::Rgb8, + )?; + Ok(()) + } + _ => { + img.save_with_format(output_path, image::ImageFormat::Png)?; + Ok(()) + } + } + } + + fn resolve_destination( + files: &[String], + options: &ConversionOptions, + preferences: &AppPreferences, + ) -> AppResult { + if let Some(ref dest) = options.destination_folder { + if !dest.trim().is_empty() { + let path = PathBuf::from(dest); + std::fs::create_dir_all(&path)?; + return Ok(path); + } + } + + match preferences.output_directory_mode { + OutputDirectoryMode::Desktop => dirs::desktop_dir().ok_or_else(|| { + AppError::NotFound("Masaüstü dizini tespit edilemedi.".to_string()) + }), + OutputDirectoryMode::Custom => { + if !preferences.custom_output_directory.trim().is_empty() { + let path = PathBuf::from(&preferences.custom_output_directory); + std::fs::create_dir_all(&path)?; + Ok(path) + } else { + Self::fallback_source_dir(files) + } + } + OutputDirectoryMode::SameAsSource => Self::fallback_source_dir(files), + } + } + + fn fallback_source_dir(files: &[String]) -> AppResult { + if let Some(first) = files.first() { + let p = Path::new(first); + if p.is_dir() { + return Ok(p.parent().unwrap_or(p).to_path_buf()); + } + if let Some(parent) = p.parent() { + return Ok(parent.to_path_buf()); + } + } + dirs::desktop_dir().ok_or_else(|| AppError::NotFound("Hedef klasör belirlenemedi.".to_string())) + } +} diff --git a/src-tauri/src/services/document_engine.rs b/src-tauri/src/services/document_engine.rs new file mode 100644 index 0000000..9c6465c --- /dev/null +++ b/src-tauri/src/services/document_engine.rs @@ -0,0 +1,532 @@ +//! Harici program gerektirmeyen belge motoru. +//! +//! - DOCX/ODT/PPTX/XLSX/RTF/HTML/EPUB/TXT/MD → düz metin +//! - Metin → PDF (GDI ile sayfa görüntüsü) / DOCX / TXT / HTML +//! +//! Tüm ofis belgesi ve metin dönüşümleri bu motorla yapılır (harici program yok). + +use std::io::Read; +use std::path::{Path, PathBuf}; + +use crate::error::{AppError, AppResult}; +use crate::services::docx_writer::DocxWriter; +use crate::services::image_engine::ImageEngine; +use crate::services::pdf_engine::PdfEngine; + +pub struct DocumentEngine; + +impl DocumentEngine { + /// Belge türüne göre düz metin çıkarır. + pub fn extract_text(path: &str) -> AppResult { + let p = Path::new(path); + if !p.exists() { + return Err(AppError::NotFound(path.to_string())); + } + let ext = p + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_lowercase(); + + let text = match ext.as_str() { + "txt" | "md" | "markdown" | "csv" | "log" => { + let bytes = std::fs::read(p)?; + decode_text(&bytes) + } + "html" | "htm" | "xhtml" => { + let bytes = std::fs::read(p)?; + strip_html(&decode_text(&bytes)) + } + "docx" => { + let xml = read_zip_entry(p, "word/document.xml")?; + strip_word_xml(&xml) + } + "odt" => { + let xml = read_zip_entry(p, "content.xml")?; + strip_odf_xml(&xml) + } + "pptx" => { + let mut buffers = Vec::new(); + for (name, data) in zip_entries(p, "ppt/slides/slide")? { + if name.ends_with(".xml") { + buffers.push(strip_drawingml_xml(&decode_text(&data))); + } + } + buffers.join("\n\n---\n\n") + } + "xlsx" => read_xlsx(p)?, + "rtf" => { + let bytes = std::fs::read(p)?; + strip_rtf(&decode_text(&bytes)) + } + "epub" => { + let mut buffers = Vec::new(); + for (name, data) in zip_entries(p, "")? { + let lower = name.to_lowercase(); + if lower.ends_with(".xhtml") || lower.ends_with(".html") || lower.ends_with(".htm") { + buffers.push(strip_html(&decode_text(&data))); + } + } + buffers.join("\n\n---\n\n") + } + other => { + return Err(AppError::UnsupportedFormat(format!( + ".{} uzantısı dahili belge motoruyla okunamıyor", + other + ))) + } + }; + + Ok(cleanup(&text)) + } + + /// Hedef biçime dahili yolla dönüştürür (harici program gerektirmez). + pub fn convert( + input: &str, + target: &str, + destination_dir: &Path, + overwrite: bool, + ) -> AppResult { + let ext = Path::new(input) + .extension() + .and_then(|s| s.to_str()) + .map(|s| s.to_ascii_lowercase()) + .unwrap_or_default(); + + if matches!(ext.as_str(), "html" | "htm") + && matches!(target, "pdf" | "docx" | "html" | "txt") + { + return crate::services::office_engine::OfficeEngine::convert( + input, + target, + destination_dir, + ); + } + + let stem = Path::new(input) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("belge"); + let text = Self::extract_text(input)?; + + match target { + "txt" => { + let out = ImageEngine::get_unique_path( + &destination_dir.join(format!("{}.txt", stem)), + overwrite, + ); + std::fs::write(&out, &text)?; + Ok(out) + } + "docx" => { + let out = ImageEngine::get_unique_path( + &destination_dir.join(format!("{}.docx", stem)), + overwrite, + ); + let mut pages = Vec::new(); + for chunk in text.split('\u{000C}') { + pages.push(chunk.to_string()); + } + DocxWriter::create_from_pages(&out, &pages)?; + Ok(out) + } + "html" => { + let out = ImageEngine::get_unique_path( + &destination_dir.join(format!("{}.html", stem)), + overwrite, + ); + let mut html = String::from( + "", + ); + for line in text.lines() { + if line.trim().is_empty() { + continue; + } + html.push_str("

"); + html.push_str(&escape_html(line)); + html.push_str("

\n"); + } + html.push_str(""); + std::fs::write(&out, html)?; + Ok(out) + } + "pdf" => { + let out = ImageEngine::get_unique_path( + &destination_dir.join(format!("{}.pdf", stem)), + overwrite, + ); + Self::text_to_pdf(&text, &out)?; + Ok(out) + } + other => Err(AppError::UnsupportedFormat(format!( + "dahili motor '{}' hedefini desteklemiyor", + other + ))), + } + } + + /// Düz metni A4 sayfalara yerleştirip PDF üretir (görüntü tabanlı, harici araç yok). + pub fn text_to_pdf(text: &str, output_path: &Path) -> AppResult<()> { + #[cfg(windows)] + { + let pages = crate::services::gdi_render::render_text_pages(text, 26, 1240, 1754, 90)?; + if pages.is_empty() { + return Err(AppError::Generic("PDF için metin üretilemedi".to_string())); + } + let images: Vec = pages + .into_iter() + .map(image::DynamicImage::ImageRgb8) + .collect(); + PdfEngine::images_to_pdf(&images, output_path, 82)?; + Ok(()) + } + #[cfg(not(windows))] + { + let _ = (text, output_path); + Err(AppError::Engine( + "Dahili metin->PDF motoru yalnız Windows'ta destekleniyor.".to_string(), + )) + } + } + + /// PDF içindeki metni sayfalara ayırır (harici motor gerektirmez). + pub fn pdf_page_texts(path: &str) -> AppResult> { + crate::services::pdf_text::extract_pages(path) + } +} + +// ------------------------------------------------------------------ helpers +fn decode_text(bytes: &[u8]) -> String { + // UTF-16 BOM desteği + if bytes.len() >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE { + let units: Vec = bytes[2..] + .as_chunks::<2>() + .0 + .iter() + .map(|pair| u16::from_le_bytes(*pair)) + .collect(); + return String::from_utf16_lossy(&units); + } + String::from_utf8_lossy(bytes).to_string() +} + +fn read_zip_entry(path: &Path, name: &str) -> AppResult { + let file = std::fs::File::open(path)?; + let mut archive = zip::ZipArchive::new(std::io::BufReader::new(file)) + .map_err(|e| AppError::Generic(format!("Belge paketi açılamadı: {}", e)))?; + let mut entry = archive + .by_name(name) + .map_err(|_| AppError::Generic(format!("Belge içinde '{}' bulunamadı", name)))?; + let mut buffer = Vec::new(); + entry.read_to_end(&mut buffer)?; + Ok(decode_text(&buffer)) +} + +/// Arşiv içindeki belirli ön ek ile başlayan dosyaları (ad, içerik) olarak döner. +fn zip_entries(path: &Path, prefix: &str) -> AppResult)>> { + let file = std::fs::File::open(path)?; + let mut archive = zip::ZipArchive::new(std::io::BufReader::new(file)) + .map_err(|e| AppError::Generic(format!("Belge paketi açılamadı: {}", e)))?; + let mut result = Vec::new(); + for index in 0..archive.len() { + let mut entry = match archive.by_index(index) { + Ok(e) => e, + Err(_) => continue, + }; + let name = entry.name().to_string(); + if !name.starts_with(prefix) { + continue; + } + let mut buffer = Vec::new(); + if entry.read_to_end(&mut buffer).is_ok() { + result.push((name, buffer)); + } + } + result.sort_by_key(|entry| natural_key(&entry.0)); + Ok(result) +} + +/// "slide2.xml" < "slide10.xml" sıralaması için sayı-duyarlı anahtar. +fn natural_key(name: &str) -> Vec { + let mut key = Vec::new(); + let mut current = String::new(); + for ch in name.chars() { + if ch.is_ascii_digit() { + current.push(ch); + } else if !current.is_empty() { + key.push(current.parse().unwrap_or(0)); + current.clear(); + } + } + if !current.is_empty() { + key.push(current.parse().unwrap_or(0)); + } + key +} + +fn strip_word_xml(xml: &str) -> String { + let mut text = xml + .replace("", "\n") + .replace("", "\n") + .replace("", "\n") + .replace("", "\t") + .replace("", "\t") + .replace("", "\n") + .replace("", "\t"); + text = remove_tags(&text); + unescape_xml(&text) +} + +fn strip_odf_xml(xml: &str) -> String { + let mut text = xml + .replace("", "\n") + .replace("", "\n") + .replace("", "\t") + .replace("", "\n") + .replace("", "\t") + .replace("", "\n"); + text = remove_tags(&text); + unescape_xml(&text) +} + +fn strip_drawingml_xml(xml: &str) -> String { + let mut text = xml.replace("", "\n").replace("", "\n"); + text = remove_tags(&text); + unescape_xml(&text) +} + +fn read_xlsx(path: &Path) -> AppResult { + let shared: Vec = match read_zip_entry(path, "xl/sharedStrings.xml") { + Ok(xml) => extract_all(&xml, "si", "t"), + Err(_) => Vec::new(), + }; + + let mut sheets = Vec::new(); + for (name, data) in zip_entries(path, "xl/worksheets/sheet")? { + if !name.ends_with(".xml") { + continue; + } + let xml = decode_text(&data); + let mut sheet_text = String::new(); + for row in xml.split(" Option { + let open = format!("<{}", tag); + let start = xml.find(&open)?; + let after_open = xml[start..].find('>')? + start + 1; + let close = format!("", tag); + let end = xml[after_open..].find(&close)? + after_open; + Some(xml[after_open..end].to_string()) +} + +fn extract_all(xml: &str, group_tag: &str, value_tag: &str) -> Vec { + let mut result = Vec::new(); + let open = format!("<{}", group_tag); + let close = format!("", group_tag); + for part in xml.split(&open).skip(1) { + let body = match part.split(&close).next() { + Some(b) => b, + None => continue, + }; + let value = extract_first(body, value_tag).unwrap_or_default(); + result.push(unescape_xml(&value)); + } + result +} + +fn strip_html(html: &str) -> String { + let mut lower = html.to_lowercase(); + for tag in [ + "').map(|i| start + i + 1) + } else { + let closing = format!("').map(|j| start + i + j + 1)) + }; + match end { + Some(end) => { + lower.replace_range(start..end, ""); + } + None => break, + } + } + } + + let mut text = lower + .replace("
", "\n") + .replace("
", "\n") + .replace("
", "\n") + .replace("

", "\n") + .replace("", "\n") + .replace("", "\n") + .replace("", "\n") + .replace("", "\n") + .replace("", "\n") + .replace("", "\n") + .replace("
  • ", "• ") + .replace("", "\n") + .replace("", "\t") + .replace("", "\t"); + text = remove_tags(&text); + unescape_xml(&text) +} + +fn remove_tags(input: &str) -> String { + let mut output = String::with_capacity(input.len()); + let mut inside = false; + for ch in input.chars() { + match ch { + '<' => inside = true, + '>' => inside = false, + _ if !inside => output.push(ch), + _ => {} + } + } + output +} + +fn unescape_xml(input: &str) -> String { + input + .replace("<", "<") + .replace(">", ">") + .replace(""", "\"") + .replace("'", "'") + .replace(" ", " ") + .replace("", " ") + .replace("&", "&") +} + +fn strip_rtf(input: &str) -> String { + let mut output = String::with_capacity(input.len()); + let mut chars = input.chars().peekable(); + + while let Some(ch) = chars.next() { + match ch { + '{' | '}' => {} + '\\' => { + let mut word = String::new(); + while let Some(&next) = chars.peek() { + if next.is_ascii_alphabetic() { + word.push(next); + chars.next(); + } else { + break; + } + } + // Parametreleri atla + let mut parameter = String::new(); + while let Some(&next) = chars.peek() { + if next == '-' || next.is_ascii_digit() { + parameter.push(next); + chars.next(); + } else { + break; + } + } + if chars.peek() == Some(&' ') { + chars.next(); + } + + match word.as_str() { + "par" | "line" => output.push('\n'), + "tab" => output.push('\t'), + "cell" | "row" => output.push('\t'), + "amp" => output.push('&'), + "lt" => output.push('<'), + "gt" => output.push('>'), + "quote" => output.push('"'), + "u" => { + if let Ok(code) = parameter.parse::() { + if let Some(c) = char::from_u32(code as u32) { + output.push(c); + } + } + } + "fonttbl" | "colortbl" | "stylesheet" | "info" | "picw" | "pich" => {} + _ => { + if word.len() == 1 { + // Escaped karakter (\\, \{, \}) + if let Some(c) = word.chars().next() { + output.push(c); + } + } + } + } + } + '\'' => { + // \'hh biçiminde onaltılık karakter (CP1254 yaklaşımı: Latin-1) + let mut hex = String::new(); + for _ in 0..2 { + if let Some(c) = chars.next() { + hex.push(c); + } + } + if let Ok(value) = u8::from_str_radix(&hex, 16) { + output.push(value as char); + } + } + '\r' | '\n' => {} + _ => output.push(ch), + } + } + + output +} + +fn cleanup(text: &str) -> String { + let mut lines: Vec = Vec::new(); + let mut blank_count = 0; + for line in text.replace("\r\n", "\n").split('\n') { + let trimmed = line.trim_end(); + if trimmed.trim().is_empty() { + blank_count += 1; + if blank_count > 1 { + continue; + } + lines.push(String::new()); + } else { + blank_count = 0; + lines.push(trimmed.to_string()); + } + } + lines.join("\n").trim().to_string() +} + +fn escape_html(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") +} diff --git a/src-tauri/src/services/docx_writer.rs b/src-tauri/src/services/docx_writer.rs new file mode 100644 index 0000000..e82242b --- /dev/null +++ b/src-tauri/src/services/docx_writer.rs @@ -0,0 +1,445 @@ +//! Biçim koruyan DOCX yazıcı: resim, birleşik hücreli tablo, liste, hizalama, alt/üst simge. + +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::Path; + +use zip::write::SimpleFileOptions; +use zip::ZipWriter; + +use crate::error::{AppError, AppResult}; +use crate::services::office_model::{ + Align, Block, Cell, Document, ImageBlock, ImageFormat, ListKind, Paragraph, Table, VertAlign, +}; + +pub struct DocxWriter; + +impl DocxWriter { + /// Eski düz metin API'si (PDF OCR vb. için korunur). + pub fn create_from_pages(output_path: &Path, pages: &[String]) -> AppResult<()> { + let mut body = String::new(); + for (page_idx, page) in pages.iter().enumerate() { + for (line_idx, line) in page.replace("\r\n", "\n").split('\n').enumerate() { + if page_idx > 0 && line_idx == 0 { + body.push_str(""); + } + body.push_str(""); + if !line.trim().is_empty() { + body.push_str(""); + body.push_str(&escape(line)); + body.push_str(""); + } + body.push_str(""); + } + } + write_package(output_path, &body, "", &[]) + } + + pub fn create_from_document(output_path: &Path, document: &Document) -> AppResult<()> { + let mut body = String::new(); + let mut media: Vec<(String, Vec)> = Vec::new(); + let mut image_count = 0usize; + let mut numbering = NumberingState::default(); + + for block in &document.blocks { + match block { + Block::Paragraph(paragraph) => { + body.push_str(¶graph_xml(paragraph, &mut numbering)); + } + Block::Table(table) => body.push_str(&table_xml(table, &mut numbering)), + Block::Image(image) => { + image_count += 1; + body.push_str(&image_paragraph_xml(image, image_count, &mut media)); + } + Block::PageBreak => { + body.push_str(""); + } + } + } + + if !document.header.is_empty() { + body.push_str(¶graph_xml( + &Paragraph { + style: Default::default(), + runs: document.header.iter().flat_map(|p| p.runs.clone()).collect(), + }, + &mut numbering, + )); + } + + let numbering_xml = numbering.xml(); + write_package(output_path, &body, &numbering_xml, &media) + } +} + +#[derive(Default)] +struct NumberingState { + next_id: usize, +} + +impl NumberingState { + fn xml(&self) -> String { + if self.next_id == 0 { + return String::new(); + } + let mut xml = String::from( + "", + ); + for index in 0..self.next_id { + xml.push_str(&format!( + "", + index + )); + xml.push_str(&format!( + "", + index + 1 + )); + } + xml.push_str(""); + xml + } + + fn next(&mut self) -> usize { + self.next_id += 1; + self.next_id + } +} + +fn paragraph_xml(paragraph: &Paragraph, numbering: &mut NumberingState) -> String { + let mut xml = String::from(""); + let mut properties = String::new(); + + if let Some(level) = paragraph.style.heading { + let clamped = level.clamp(1, 6); + properties.push_str(&format!( + "", + clamped, + clamped.saturating_sub(1) + )); + } + if let Some(list) = paragraph.style.list { + let num_id = numbering.next(); + properties.push_str(&format!( + "", + paragraph.style.level.min(8), + num_id + )); + if list == ListKind::Bullet { + properties.push_str(""); + } + } + let align = match paragraph.style.align { + Align::Center => Some("center"), + Align::Right => Some("right"), + Align::Justify => Some("both"), + Align::Left => None, + }; + if let Some(align) = align { + properties.push_str(&format!("", align)); + } + + // Paragraf boşlukları (w:spacing): Aşırı boşlukları önle, gövdede tam 1.08 satır aralığı + if let Some(level) = paragraph.style.heading { + match level { + 1 => properties.push_str(""), + 2 => properties.push_str(""), + _ => properties.push_str(""), + } + } else if paragraph.style.space_before_pt > 0.0 || paragraph.style.space_after_pt > 0.0 { + properties.push_str(&format!( + "", + (paragraph.style.space_before_pt * 20.0).round() as i32, + (paragraph.style.space_after_pt * 20.0).round() as i32 + )); + } else if paragraph.style.is_display_math { + properties.push_str(""); + } else { + // Gövde paragraflarında standart akıcı boşluk + properties.push_str(""); + } + + if paragraph.style.indent_left_pt > 0.0 { + properties.push_str(&format!( + "", + (paragraph.style.indent_left_pt * 20.0).round() as i32 + )); + } + if !properties.is_empty() { + xml.push_str(&format!("{}", properties)); + } + + for run in ¶graph.runs { + if let Some(omml) = &run.omml { + let trimmed = omml.trim(); + if paragraph.style.is_display_math { + if trimmed.starts_with("{}", trimmed)); + } else { + xml.push_str(&format!( + "{}", + trimmed + )); + } + } else if trimmed.starts_with("{}", trimmed)); + } + continue; + } + + if run.text.is_empty() { + continue; + } + let mut run_properties = String::new(); + if run.bold || paragraph.style.heading.is_some() { + run_properties.push_str(""); + } + if run.italic { + run_properties.push_str(""); + } + if run.underline { + run_properties.push_str(""); + } + if run.strike { + run_properties.push_str(""); + } + if let Some(size) = run.size_pt { + let half_pt = (size * 2.0).round() as i32; + run_properties.push_str(&format!("")); + } + if let Some(color) = run.color { + run_properties.push_str(&format!( + "", + color[0], color[1], color[2] + )); + } + if let Some(font) = &run.font { + run_properties.push_str(&format!( + "", + escape(font) + )); + } + if let Some(align) = run.vert_align { + run_properties.push_str(match align { + VertAlign::Subscript => "", + VertAlign::Superscript => "", + }); + } + xml.push_str(""); + if !run_properties.is_empty() { + xml.push_str(&format!("{}", run_properties)); + } + xml.push_str(""); + xml.push_str(&escape(&run.text)); + xml.push_str(""); + } + + xml.push_str(""); + xml +} + +fn table_xml(table: &Table, numbering: &mut NumberingState) -> String { + let columns = table + .rows + .iter() + .map(|row| row.iter().map(|cell| cell.colspan.max(1) as usize).sum::()) + .max() + .unwrap_or(1); + + let mut xml = String::from( + "", + ); + for edge in ["top", "left", "bottom", "right", "insideH", "insideV"] { + xml.push_str(&format!( + "", + edge + )); + } + xml.push_str(""); + + let widths = if table.widths.len() == columns { + table.widths.clone() + } else { + vec![1.0; columns] + }; + let total: f32 = widths.iter().sum(); + for width in &widths { + let twips = ((width / total.max(0.0001)) * 9000.0).max(200.0) as i32; + xml.push_str(&format!("", twips)); + } + xml.push_str(""); + + for row in &table.rows { + xml.push_str(""); + for cell in row { + xml.push_str(&cell_xml(cell, numbering)); + } + xml.push_str(""); + } + xml.push_str(""); + xml +} + +fn cell_xml(cell: &Cell, numbering: &mut NumberingState) -> String { + let mut xml = String::from(""); + if cell.colspan > 1 { + xml.push_str(&format!("", cell.colspan)); + } + if cell.rowspan > 1 { + xml.push_str(""); + } + if let Some(shade) = cell.shade { + xml.push_str(&format!( + "", + shade[0], shade[1], shade[2] + )); + } + let align = match cell.align { + Align::Center => Some("center"), + Align::Right => Some("right"), + Align::Justify => Some("both"), + Align::Left => None, + }; + if let Some(align) = align { + xml.push_str(&format!("", align)); + } + xml.push_str(""); + + if cell.paragraphs.is_empty() { + xml.push_str(""); + } + for paragraph in &cell.paragraphs { + xml.push_str(¶graph_xml(paragraph, numbering)); + } + xml.push_str(""); + xml +} + +fn image_paragraph_xml(image: &ImageBlock, index: usize, media: &mut Vec<(String, Vec)>) -> String { + let extension = match image.format { + ImageFormat::Other => "bin", + other => other.extension(), + }; + let file_name = format!("image{}.{}", index, extension); + media.push((file_name.clone(), image.data.clone())); + + let width = if image.width_pt > 0.0 { image.width_pt } else { 320.0 }; + let height = if image.height_pt > 0.0 { image.height_pt } else { 240.0 }; + let cx = (width * 12700.0) as i64; + let cy = (height * 12700.0) as i64; + + format!( + "", + cx = cx, + cy = cy, + index = index, + file_name = file_name + ) +} + +fn write_package( + output_path: &Path, + body: &str, + numbering: &str, + media: &[(String, Vec)], +) -> AppResult<()> { + let document_xml = format!( + r#" +{}"#, + body + ); + + let mut defaults = String::new(); + for extension in ["png", "jpg", "jpeg", "gif", "webp", "bmp"] { + let mime = match extension { + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "gif" => "image/gif", + "webp" => "image/webp", + _ => "image/bmp", + }; + defaults.push_str(&format!( + "", + extension, mime + )); + } + + let numbering_override = if numbering.is_empty() { + "" + } else { + r#""# + }; + + let content_types = format!( + r#" +{defaults}{numbering_override}"# + ); + + let rels = r#" +"#; + + let mut document_rels = String::from( + r#" +"#, + ); + if !numbering.is_empty() { + document_rels.push_str( + r#""#, + ); + } + for (index, (name, _)) in media.iter().enumerate() { + document_rels.push_str(&format!( + "", + index + 1, + name + )); + } + document_rels.push_str(""); + + let styles_xml = r#" +"#; + + let settings_xml = r#" +"#; + + if let Some(parent) = output_path.parent() { + std::fs::create_dir_all(parent)?; + } + let file = File::create(output_path)?; + let mut zip = ZipWriter::new(BufWriter::new(file)); + let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + + let mut entries: Vec<(String, Vec)> = vec![ + ("[Content_Types].xml".to_string(), content_types.into_bytes()), + ("_rels/.rels".to_string(), rels.as_bytes().to_vec()), + ("word/document.xml".to_string(), document_xml.into_bytes()), + ("word/styles.xml".to_string(), styles_xml.as_bytes().to_vec()), + ("word/settings.xml".to_string(), settings_xml.as_bytes().to_vec()), + ("word/_rels/document.xml.rels".to_string(), document_rels.into_bytes()), + ]; + if !numbering.is_empty() { + entries.push(("word/numbering.xml".to_string(), numbering.as_bytes().to_vec())); + } + for (name, bytes) in media { + entries.push((format!("word/media/{}", name), bytes.clone())); + } + + for (name, bytes) in entries { + zip.start_file(name, options) + .map_err(|e| AppError::Generic(format!("DOCX paketi oluşturulamadı: {}", e)))?; + zip.write_all(&bytes)?; + } + zip.finish() + .map_err(|e| AppError::Generic(format!("DOCX dosyası tamamlanamadı: {}", e)))?; + Ok(()) +} + +fn escape(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} diff --git a/src-tauri/src/services/engine_resolver.rs b/src-tauri/src/services/engine_resolver.rs new file mode 100644 index 0000000..a3116ee --- /dev/null +++ b/src-tauri/src/services/engine_resolver.rs @@ -0,0 +1,287 @@ +use std::env; +use std::path::{Path, PathBuf}; +use std::sync::{OnceLock, RwLock}; + +#[derive(Debug, Clone, Default)] +struct CustomPaths { + ffmpeg: Option, + pandoc: Option, + seven_zip: Option, +} + +static CUSTOM_PATHS: OnceLock> = OnceLock::new(); + +fn custom_paths() -> &'static RwLock { + CUSTOM_PATHS.get_or_init(|| RwLock::new(CustomPaths::default())) +} + +/// Ayarlar ekranından girilen motor yollarını kaydeder (uygulama yeniden başlatmadan geçerli olur). +pub fn set_custom_paths(ffmpeg: &str, pandoc: &str, seven_zip: &str) { + let mut guard = match custom_paths().write() { + Ok(guard) => guard, + Err(poisoned) => poisoned.into_inner(), + }; + let clean = |value: &str| { + let trimmed = value.trim(); + if trimmed.is_empty() { + None + } else { + Some(trimmed.to_string()) + } + }; + *guard = CustomPaths { + ffmpeg: clean(ffmpeg), + pandoc: clean(pandoc), + seven_zip: clean(seven_zip), + }; +} + +fn saved_path(pick: impl Fn(&CustomPaths) -> Option) -> Option { + let guard = match custom_paths().read() { + Ok(guard) => guard, + Err(poisoned) => poisoned.into_inner(), + }; + pick(&guard).filter(|value| Path::new(value).exists()) +} + +#[derive(Debug, Clone, serde::Serialize)] +pub struct EngineStatus { + pub ffmpeg_path: Option, + pub pandoc_path: Option, + pub seven_zip_path: Option, +} + +pub struct EngineResolver; + +impl EngineResolver { + pub fn resolve_all( + custom_ffmpeg: Option<&str>, + custom_pandoc: Option<&str>, + custom_seven_zip: Option<&str>, + ) -> EngineStatus { + EngineStatus { + ffmpeg_path: Self::resolve_ffmpeg(custom_ffmpeg), + pandoc_path: Self::resolve_pandoc(custom_pandoc), + seven_zip_path: Self::resolve_7zip(custom_seven_zip), + } + } + + pub fn resolve_ffmpeg(custom: Option<&str>) -> Option { + if let Some(value) = custom { + if !value.trim().is_empty() && Path::new(value).exists() { + return Some(value.to_string()); + } + } + if let Some(path) = saved_path(|c| c.ffmpeg.clone()) { + return Some(path); + } + + let local_app = dirs::data_local_dir(); + let mut candidates = Vec::new(); + if let Some(ref la) = local_app { + candidates.push(la.join("LDConverter").join("tools").join("ffmpeg.exe")); + candidates.push(la.join("ffmpeg").join("bin").join("ffmpeg.exe")); + } + candidates.push(PathBuf::from("tools/ffmpeg.exe")); + candidates.push(PathBuf::from("ffmpeg.exe")); + + if let Ok(exe) = env::current_exe() { + if let Some(parent) = exe.parent() { + candidates.push(parent.join("tools").join("ffmpeg.exe")); + candidates.push(parent.join("ffmpeg.exe")); + } + } + + for candidate in candidates { + if candidate.exists() { + return Some(candidate.to_string_lossy().to_string()); + } + } + Self::find_in_path("ffmpeg.exe") + } + + pub fn resolve_pandoc(custom: Option<&str>) -> Option { + if let Some(value) = custom { + if !value.trim().is_empty() && Path::new(value).exists() { + return Some(value.to_string()); + } + } + if let Some(path) = saved_path(|c| c.pandoc.clone()) { + return Some(path); + } + + let local_app = dirs::data_local_dir(); + let mut candidates = Vec::new(); + if let Some(ref la) = local_app { + candidates.push(la.join("Pandoc").join("pandoc.exe")); + candidates.push(la.join("Programs").join("Pandoc").join("pandoc.exe")); + } + candidates.push(PathBuf::from("C:\\Program Files\\Pandoc\\pandoc.exe")); + candidates.push(PathBuf::from("C:\\Program Files (x86)\\Pandoc\\pandoc.exe")); + candidates.push(PathBuf::from("tools/pandoc.exe")); + + if let Ok(exe) = env::current_exe() { + if let Some(parent) = exe.parent() { + candidates.push(parent.join("tools").join("pandoc.exe")); + candidates.push(parent.join("pandoc.exe")); + } + } + + for candidate in candidates { + if candidate.exists() { + return Some(candidate.to_string_lossy().to_string()); + } + } + Self::find_in_path("pandoc.exe") + } + + pub fn resolve_7zip(custom: Option<&str>) -> Option { + if let Some(value) = custom { + if !value.trim().is_empty() && Path::new(value).exists() { + return Some(value.to_string()); + } + } + if let Some(path) = saved_path(|c| c.seven_zip.clone()) { + return Some(path); + } + + let mut candidates = vec![ + PathBuf::from("C:\\Program Files\\7-Zip\\7z.exe"), + PathBuf::from("C:\\Program Files (x86)\\7-Zip\\7z.exe"), + PathBuf::from("tools/7z.exe"), + ]; + if let Some(la) = dirs::data_local_dir() { + candidates.push(la.join("LDConverter").join("tools").join("7z.exe")); + } + if let Ok(exe) = env::current_exe() { + if let Some(parent) = exe.parent() { + candidates.push(parent.join("tools").join("7z.exe")); + candidates.push(parent.join("7z.exe")); + } + } + + for candidate in candidates { + if candidate.exists() { + return Some(candidate.to_string_lossy().to_string()); + } + } + Self::find_in_path("7z.exe") + } + + /// Tesseract varsa OCR için tercih edilir; yoksa Windows yerleşik OCR kullanılır. + pub fn resolve_tesseract() -> Option { + let mut candidates = vec![ + PathBuf::from("C:\\Program Files\\Tesseract-OCR\\tesseract.exe"), + PathBuf::from("C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe"), + ]; + if let Some(la) = dirs::data_local_dir() { + candidates.push(la.join("LDConverter").join("tools").join("tesseract").join("tesseract.exe")); + candidates.push(la.join("Programs").join("Tesseract-OCR").join("tesseract.exe")); + } + if let Ok(exe) = env::current_exe() { + if let Some(parent) = exe.parent() { + candidates.push(parent.join("tools").join("tesseract").join("tesseract.exe")); + candidates.push(parent.join("tesseract.exe")); + } + } + + for candidate in candidates { + if candidate.exists() { + return Some(candidate.to_string_lossy().to_string()); + } + } + Self::find_in_path("tesseract.exe") + } + + /// FFmpeg build'inde JPEG XL kodlayıcı+kod çözücü (libjxl) var mı? + /// Yoksa JXL seçenekleri kullanıcıya hiç gösterilmez. + pub fn ffmpeg_supports_jxl() -> bool { + static CACHE: OnceLock = OnceLock::new(); + *CACHE.get_or_init(|| { + let Some(ffmpeg) = Self::resolve_ffmpeg(None) else { + return false; + }; + let mut has_encoder = false; + let mut has_decoder = false; + + for (flag, target) in [("-encoders", &mut has_encoder), ("-decoders", &mut has_decoder)] { + let mut cmd = std::process::Command::new(&ffmpeg); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x08000000); + } + if let Ok(out) = cmd.arg("-hide_banner").arg(flag).output() { + let text = String::from_utf8_lossy(&out.stdout).to_lowercase(); + if text.contains("jxl") || text.contains("jpegxl") { + *target = true; + } + } + } + + has_encoder && has_decoder + }) + } + + /// JPEG XL ikililerini (cjxl.exe / djxl.exe) paket içinden veya PATH'ten bulur. + fn resolve_jxl_tool(binary: &str) -> Option { + let mut candidates = vec![ + PathBuf::from("tools").join(binary), + PathBuf::from("../tools").join(binary), + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("tools") + .join(binary), + ]; + if let Some(la) = dirs::data_local_dir() { + candidates.push(la.join("LDConverter").join("tools").join(binary)); + } + if let Ok(exe) = env::current_exe() { + if let Some(parent) = exe.parent() { + candidates.push(parent.join("tools").join(binary)); + candidates.push(parent.join("resources").join("tools").join(binary)); + } + } + + candidates + .into_iter() + .find(|candidate| candidate.is_file()) + .map(|candidate| { + candidate + .canonicalize() + .unwrap_or(candidate) + .to_string_lossy() + .to_string() + }) + .or_else(|| Self::find_in_path(binary)) + } + + pub fn resolve_jxl_encoder() -> Option { + Self::resolve_jxl_tool("cjxl.exe") + } + + pub fn resolve_jxl_decoder() -> Option { + Self::resolve_jxl_tool("djxl.exe") + } + + /// JXL dönüşümü mümkün mü: gömülü cjxl/djxl ya da libjxl'li bir FFmpeg. + pub fn jxl_available() -> bool { + static CACHE: OnceLock = OnceLock::new(); + *CACHE.get_or_init(|| { + (Self::resolve_jxl_encoder().is_some() && Self::resolve_jxl_decoder().is_some()) + || Self::ffmpeg_supports_jxl() + }) + } + + fn find_in_path(binary: &str) -> Option { + if let Ok(path_var) = env::var("PATH") { + for dir in env::split_paths(&path_var) { + let candidate = dir.join(binary); + if candidate.is_file() { + return Some(candidate.to_string_lossy().to_string()); + } + } + } + None + } +} diff --git a/src-tauri/src/services/engine_updater.rs b/src-tauri/src/services/engine_updater.rs new file mode 100644 index 0000000..9e4a51a --- /dev/null +++ b/src-tauri/src/services/engine_updater.rs @@ -0,0 +1,315 @@ +//! Açılışta motorları denetler; eksik veya eski sürümleri resmî kaynaktan indirip +//! `%LOCALAPPDATA%\LDConverter\tools` altına kurar. Kurulum arka planda yapılır, +//! arayüz `engine-update` olaylarıyla bilgilendirilir. + +use std::fs; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::thread; +use std::time::Duration; + +use tauri::{AppHandle, Emitter}; + +use crate::logging; +use crate::services::EngineResolver; + +const FFMPEG_REQUIRED: (u32, u32) = (7, 1); +const PANDOC_REQUIRED: (u32, u32) = (3, 0); +const FFMPEG_URL: &str = + "https://github.com/GyanD/codexffmpeg/releases/download/7.1/ffmpeg-7.1-essentials_build.zip"; +const SEVENZIP_URL: &str = "https://www.7-zip.org/a/7zr.exe"; + +pub fn tools_dir() -> PathBuf { + dirs::data_local_dir() + .unwrap_or_else(|| PathBuf::from(".")) + .join("LDConverter") + .join("tools") +} + +fn command(path: &Path) -> Command { + let mut cmd = Command::new(path); + cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW + } + cmd +} + +fn version_output(path: &Path, args: &[&str]) -> Option { + let output = command(path).args(args).output().ok()?; + if !output.status.success() { + return None; + } + Some(String::from_utf8_lossy(&output.stdout).to_string()) +} + +fn parse_version(text: &str) -> Option<(u32, u32)> { + text.split_whitespace().find_map(|token| { + let cleaned: String = token + .chars() + .take_while(|c| c.is_ascii_digit() || *c == '.') + .collect(); + let cleaned = cleaned.trim_end_matches('.'); + if cleaned.is_empty() { + return None; + } + let mut parts = cleaned.split('.'); + let major: u32 = parts.next()?.parse().ok()?; + let minor: u32 = parts.next().and_then(|part| part.parse().ok()).unwrap_or(0); + Some((major, minor)) + }) +} + +fn is_older(current: (u32, u32), required: (u32, u32)) -> bool { + current < required +} + +fn download(url: &str, destination: &Path) -> Result<(), String> { + if let Some(parent) = destination.parent() { + fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + + let script = format!( + "$ProgressPreference='SilentlyContinue'; [Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -Uri '{}' -OutFile '{}' -UseBasicParsing", + url, + destination.display() + ); + + let mut cmd = Command::new("powershell.exe"); + cmd.args([ + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-Command", + &script, + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x08000000); + } + + let output = cmd.output().map_err(|e| e.to_string())?; + if !output.status.success() { + return Err(String::from_utf8_lossy(&output.stderr).to_string()); + } + if !destination.exists() || fs::metadata(destination).map(|m| m.len()).unwrap_or(0) == 0 { + return Err("indirilen dosya boş".to_string()); + } + Ok(()) +} + +/// ZIP arşivinden yalnızca istenen dosya adlarını hedef klasöre çıkarır (düzleştirir). +fn extract_named(zip_path: &Path, destination: &Path, names: &[&str]) -> Result, String> { + let file = fs::File::open(zip_path).map_err(|e| e.to_string())?; + let mut archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; + let mut extracted = Vec::new(); + + for index in 0..archive.len() { + let mut entry = archive.by_index(index).map_err(|e| e.to_string())?; + if entry.is_dir() { + continue; + } + let entry_name = entry.name().replace('\\', "/"); + let file_name = entry_name.rsplit('/').next().unwrap_or(""); + if !names.iter().any(|wanted| wanted.eq_ignore_ascii_case(file_name)) { + continue; + } + + let target = destination.join(file_name); + let mut buffer = Vec::new(); + entry.read_to_end(&mut buffer).map_err(|e| e.to_string())?; + let mut out = fs::File::create(&target).map_err(|e| e.to_string())?; + out.write_all(&buffer).map_err(|e| e.to_string())?; + extracted.push(target); + } + + if extracted.is_empty() { + return Err("arşivde beklenen dosya bulunamadı".to_string()); + } + Ok(extracted) +} + +fn emit(app: &AppHandle, engine: &str, status: &str, message: &str) { + logging::info(&format!("Motor güncellemesi [{}] {}: {}", engine, status, message)); + let _ = app.emit( + "engine-update", + serde_json::json!({ "engine": engine, "status": status, "message": message }), + ); +} + +fn ensure_ffmpeg(app: &AppHandle) { + let tools = tools_dir(); + let target = tools.join("ffmpeg.exe"); + + if let Some(existing) = EngineResolver::resolve_ffmpeg(None) { + let version = version_output(Path::new(&existing), &["-version"]) + .as_deref() + .and_then(parse_version); + if version.map(|v| !is_older(v, FFMPEG_REQUIRED)).unwrap_or(false) { + return; + } + emit(app, "ffmpeg", "updating", "Eski sürüm bulundu, güncelleniyor…"); + } else { + emit(app, "ffmpeg", "installing", "FFmpeg indiriliyor…"); + } + + let zip_path = tools.join("_ffmpeg.zip"); + if let Err(err) = download(FFMPEG_URL, &zip_path) { + emit(app, "ffmpeg", "error", &format!("indirilemedi: {}", err)); + return; + } + match extract_named(&zip_path, &tools, &["ffmpeg.exe", "ffprobe.exe"]) { + Ok(files) => { + let _ = fs::remove_file(&zip_path); + let ok = files.iter().any(|path| path.ends_with("ffmpeg.exe")); + if ok && target.exists() { + emit(app, "ffmpeg", "ready", "FFmpeg güncellendi"); + } else { + emit(app, "ffmpeg", "error", "arşiv çıkarılamadı"); + } + } + Err(err) => emit(app, "ffmpeg", "error", &format!("arşiv hatası: {}", err)), + } +} + +fn ensure_pandoc(app: &AppHandle) { + let tools = tools_dir(); + + if let Some(existing) = EngineResolver::resolve_pandoc(None) { + let version = version_output(Path::new(&existing), &["--version"]) + .as_deref() + .and_then(parse_version); + if version.map(|v| !is_older(v, PANDOC_REQUIRED)).unwrap_or(false) { + return; + } + emit(app, "pandoc", "updating", "Eski sürüm bulundu, güncelleniyor…"); + } else { + emit(app, "pandoc", "installing", "Pandoc indiriliyor…"); + } + + // GitHub API'den son sürümün ZIP bağlantısını bul + let api = "https://api.github.com/repos/jgm/pandoc/releases/latest"; + let json_path = tools.join("_pandoc.json"); + if let Err(err) = download(api, &json_path) { + emit(app, "pandoc", "error", &format!("sürüm bilgisi alınamadı: {}", err)); + return; + } + let json = fs::read_to_string(&json_path).unwrap_or_default(); + let _ = fs::remove_file(&json_path); + + let Some(url) = serde_json::from_str::(&json) + .ok() + .and_then(|value| { + value + .get("assets") + .and_then(|assets| assets.as_array()) + .and_then(|assets| { + assets.iter().find_map(|asset| { + let name = asset.get("name")?.as_str()?; + if name.contains("windows-x86_64") && name.ends_with(".zip") { + asset.get("browser_download_url")?.as_str().map(String::from) + } else { + None + } + }) + }) + }) + else { + emit(app, "pandoc", "error", "Windows ZIP sürümü bulunamadı"); + return; + }; + + let zip_path = tools.join("_pandoc.zip"); + if let Err(err) = download(&url, &zip_path) { + emit(app, "pandoc", "error", &format!("indirilemedi: {}", err)); + return; + } + match extract_named(&zip_path, &tools, &["pandoc.exe"]) { + Ok(_) => { + let _ = fs::remove_file(&zip_path); + emit(app, "pandoc", "ready", "Pandoc güncellendi"); + } + Err(err) => emit(app, "pandoc", "error", &format!("arşiv hatası: {}", err)), + } +} + +fn ensure_seven_zip(app: &AppHandle) { + if EngineResolver::resolve_7zip(None).is_some() { + return; + } + + emit(app, "7zip", "installing", "7-Zip motoru indiriliyor…"); + let target = tools_dir().join("7z.exe"); + match download(SEVENZIP_URL, &target) { + Ok(()) => { + // 7zr.exe konumlandırıldı; resolver araç klasörünü tercih eder. + emit(app, "7zip", "ready", "7-Zip motoru hazır"); + } + Err(err) => emit(app, "7zip", "error", &format!("indirilemedi: {}", err)), + } +} + +/// Uygulama açılışında çağrılır; motorları denetler ve eksik/eski olanları günceller. +pub fn start(app: AppHandle) { + thread::spawn(move || { + // Açılış tamamlansın, arayüz kendini göstersin. + thread::sleep(Duration::from_millis(1500)); + + ensure_ffmpeg(&app); + ensure_pandoc(&app); + ensure_seven_zip(&app); + + let _ = app.emit("engines-ready", ()); + logging::info("Açılış motor denetimi tamamlandı"); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn version_parsing_works() { + assert_eq!(parse_version("ffmpeg version 7.1-full_build"), Some((7, 1))); + assert_eq!(parse_version("pandoc 3.1.9"), Some((3, 1))); + assert_eq!(parse_version("7-Zip 24.09 (x64)"), Some((7, 0))); + assert_eq!(parse_version("sürüm yok"), None); + assert!(is_older((7, 0), (7, 1))); + assert!(!is_older((7, 1), (7, 1))); + } + + #[test] + fn extract_picks_only_requested_files() { + let dir = std::env::temp_dir().join(format!("ld_updater_{}", uuid::Uuid::new_v4())); + fs::create_dir_all(&dir).unwrap(); + let zip_path = dir.join("a.zip"); + + { + let file = fs::File::create(&zip_path).unwrap(); + let mut writer = zip::ZipWriter::new(file); + let options: zip::write::SimpleFileOptions = Default::default(); + + writer.start_file("build/bin/ffmpeg.exe", options).unwrap(); + writer.write_all(b"FAKE-BINARY").unwrap(); + writer.start_file("build/README.txt", options).unwrap(); + writer.write_all(b"okunmamali").unwrap(); + writer.finish().unwrap(); + } + + let extracted = extract_named(&zip_path, &dir, &["ffmpeg.exe"]).unwrap(); + assert_eq!(extracted.len(), 1); + assert!(dir.join("ffmpeg.exe").exists()); + assert!(!dir.join("README.txt").exists()); + assert_eq!(fs::read(dir.join("ffmpeg.exe")).unwrap(), b"FAKE-BINARY"); + + let _ = fs::remove_dir_all(dir); + } +} diff --git a/src-tauri/src/services/gdi_render.rs b/src-tauri/src/services/gdi_render.rs new file mode 100644 index 0000000..2d1d665 --- /dev/null +++ b/src-tauri/src/services/gdi_render.rs @@ -0,0 +1,263 @@ +//! GDI ile metni görüntüye çizer: harici motor olmadan +//! metin tabanlı PDF sayfalarını PNG'ye çevirmek ve belgelerden görüntü PDF üretmek için kullanılır. +//! Yalnız Windows'ta derlenir; diğer platformlarda derleyici bu modülü atlar. + +#[cfg(windows)] +mod windows_impl { + use std::ffi::c_void; + + use windows_sys::Win32::Foundation::{RECT, SIZE}; + use windows_sys::Win32::Graphics::Gdi::{ + CreateCompatibleDC, CreateDIBSection, CreateFontW, CreateSolidBrush, DeleteDC, DeleteObject, + FillRect, GetTextExtentPoint32W, SelectObject, SetBkMode, SetTextColor, TextOutW, + BITMAPINFOHEADER, BI_RGB, CLIP_DEFAULT_PRECIS, DEFAULT_CHARSET, DEFAULT_PITCH, + FW_NORMAL, OUT_DEFAULT_PRECIS, PROOF_QUALITY, TRANSPARENT, + }; + + use crate::error::{AppError, AppResult}; + + const FONT: &str = "Arial"; + + fn wide(text: &str) -> Vec { + text.encode_utf16().chain(std::iter::once(0)).collect() + } + + /// Bir A4 (veya verilen ölçüde) sayfaya metni sığdırır; satırları kendi ölçerek böler. + pub struct TextRenderer { + hdc: *mut c_void, + bitmap: *mut c_void, + old_bitmap: *mut c_void, + font: *mut c_void, + old_font: *mut c_void, + width: i32, + height: i32, + bits: *mut u8, + brush: *mut c_void, + } + + impl TextRenderer { + pub fn new(width: u32, height: u32, font_px: i32) -> AppResult { + unsafe { + let hdc = CreateCompatibleDC(std::ptr::null_mut()); + if hdc.is_null() { + return Err(AppError::Engine("GDI bağlamı oluşturulamadı".to_string())); + } + + let mut info: BITMAPINFOHEADER = std::mem::zeroed(); + info.biSize = std::mem::size_of::() as u32; + info.biWidth = width as i32; + info.biHeight = -(height as i32); // top-down + info.biPlanes = 1; + info.biBitCount = 32; + info.biCompression = BI_RGB; + + let mut bits: *mut c_void = std::ptr::null_mut(); + let bitmap = CreateDIBSection( + hdc, + &info as *const BITMAPINFOHEADER as *const _, + 0, // DIB_RGB_COLORS + &mut bits, + std::ptr::null_mut(), + 0, + ); + if bitmap.is_null() || bits.is_null() { + DeleteDC(hdc); + return Err(AppError::Engine("GDI bitmap oluşturulamadı".to_string())); + } + let old_bitmap = SelectObject(hdc, bitmap); + + let face = wide(FONT); + let font = CreateFontW( + -font_px, + 0, + 0, + 0, + FW_NORMAL as i32, + 0, + 0, + 0, + DEFAULT_CHARSET as u32, + OUT_DEFAULT_PRECIS as u32, + CLIP_DEFAULT_PRECIS as u32, + PROOF_QUALITY as u32, + DEFAULT_PITCH as u32, + face.as_ptr(), + ); + let old_font = if font.is_null() { + std::ptr::null_mut() + } else { + SelectObject(hdc, font) + }; + + SetBkMode(hdc, TRANSPARENT as i32); + SetTextColor(hdc, 0x000000); // siyah + + let brush = CreateSolidBrush(0x00FF_FFFF); // beyaz + + Ok(Self { + hdc, + bitmap, + old_bitmap, + font, + old_font, + width: width as i32, + height: height as i32, + bits: bits as *mut u8, + brush, + }) + } + } + + pub fn width(&self) -> i32 { + self.width + } + + pub fn height(&self) -> i32 { + self.height + } + + fn clear(&self) { + unsafe { + let rect = RECT { + left: 0, + top: 0, + right: self.width, + bottom: self.height, + }; + FillRect(self.hdc, &rect, self.brush); + } + } + + pub fn measure(&self, text: &str) -> i32 { + let utf16 = wide(text); + let mut size = SIZE { cx: 0, cy: 0 }; + unsafe { + GetTextExtentPoint32W( + self.hdc, + utf16.as_ptr(), + utf16.len() as i32 - 1, + &mut size, + ); + } + size.cx + } + + pub fn draw_line(&self, text: &str, x: i32, y: i32) { + let utf16 = wide(text); + unsafe { + TextOutW(self.hdc, x, y, utf16.as_ptr(), utf16.len() as i32 - 1); + } + } + + /// Bitmap'i RGB görüntüye dönüştürür (BGRA -> RGB). + pub fn to_image(&self) -> image::RgbImage { + let mut buffer = image::RgbImage::new(self.width as u32, self.height as u32); + unsafe { + let stride = self.width as usize * 4; + let raw = std::slice::from_raw_parts(self.bits, stride * self.height as usize); + for y in 0..self.height as usize { + for x in 0..self.width as usize { + let offset = y * stride + x * 4; + buffer.put_pixel( + x as u32, + y as u32, + image::Rgb([raw[offset + 2], raw[offset + 1], raw[offset]]), + ); + } + } + } + buffer + } + } + + impl Drop for TextRenderer { + fn drop(&mut self) { + unsafe { + if !self.old_font.is_null() { + SelectObject(self.hdc, self.old_font); + } + if !self.font.is_null() { + DeleteObject(self.font); + } + if !self.old_bitmap.is_null() { + SelectObject(self.hdc, self.old_bitmap); + } + if !self.bitmap.is_null() { + DeleteObject(self.bitmap); + } + if !self.brush.is_null() { + DeleteObject(self.brush); + } + DeleteDC(self.hdc); + } + } + } + + /// Metni A4 sayfalara bölüp her sayfayı görüntü olarak döner (harici araç gerektirmez). + pub fn render_text_pages( + text: &str, + font_px: i32, + width: u32, + height: u32, + margin: i32, + ) -> AppResult> { + let renderer = TextRenderer::new(width, height, font_px)?; + let line_height = (font_px as f64 * 1.42).round() as i32; + let usable_width = width as i32 - margin * 2; + let lines_per_page = ((height as i32 - margin * 2) / line_height).max(1) as usize; + + let mut lines: Vec = Vec::new(); + for raw_line in text.replace("\r\n", "\n").split('\n') { + let mut current = String::new(); + for word in raw_line.split(' ') { + let candidate = if current.is_empty() { + word.to_string() + } else { + format!("{} {}", current, word) + }; + if renderer.measure(&candidate) <= usable_width { + current = candidate; + } else { + if !current.is_empty() { + lines.push(std::mem::take(&mut current)); + } + // Tek kelime satırdan uzunsa karakter bazında böl + if renderer.measure(word) > usable_width { + let mut chunk = String::new(); + for ch in word.chars() { + let candidate = format!("{}{}", chunk, ch); + if renderer.measure(&candidate) > usable_width && !chunk.is_empty() { + lines.push(std::mem::take(&mut chunk)); + } + chunk.push(ch); + } + current = chunk; + } else { + current = word.to_string(); + } + } + } + lines.push(current); + } + + if lines.is_empty() { + lines.push(String::new()); + } + + let mut pages = Vec::new(); + for chunk in lines.chunks(lines_per_page) { + renderer.clear(); + let mut y = margin; + for line in chunk { + renderer.draw_line(line, margin, y); + y += line_height; + } + pages.push(renderer.to_image()); + } + + Ok(pages) + } +} + +#[cfg(windows)] +pub use windows_impl::{render_text_pages, TextRenderer}; diff --git a/src-tauri/src/services/html_pdf.rs b/src-tauri/src/services/html_pdf.rs new file mode 100644 index 0000000..c629f53 --- /dev/null +++ b/src-tauri/src/services/html_pdf.rs @@ -0,0 +1,186 @@ +//! HTML → vektör PDF: Windows'ta yerleşik Edge (Chromium) `--print-to-pdf` ile. +//! +//! Harici program kurulmaz; Edge/WebView2 her Windows 10/11'de hazırdır. +//! GUI, CLI (`--convert`) ve self-test modlarında aynı şekilde çalışır (COM/mesaj +//! döngüsü gerekmez, süreç tabanlı ve deadlock'suz). + +#![allow(dead_code)] + +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use crate::logging; + +const TIMEOUT: Duration = Duration::from_secs(45); + +fn edge_candidates() -> Vec { + let program_files = std::env::var("ProgramFiles").unwrap_or_else(|_| r"C:\Program Files".to_string()); + let program_files_x86 = + std::env::var("ProgramFiles(x86)").unwrap_or_else(|_| r"C:\Program Files (x86)".to_string()); + let local_app = std::env::var("LOCALAPPDATA").unwrap_or_default(); + + // Windows'ta Edge daima vardır; Chromium tabanlı diğer tarayıcılar yedek. + let relative = [ + ("Microsoft", "Edge", "msedge.exe"), + ("Google", "Chrome", "chrome.exe"), + ("BraveSoftware", "Brave-Browser", "brave.exe"), + ("Chromium", "Application", "chrome.exe"), + ]; + + let mut paths = Vec::new(); + for (vendor, product, exe) in relative { + for base in [&program_files_x86, &program_files] { + paths.push( + PathBuf::from(base) + .join(vendor) + .join(product) + .join("Application") + .join(exe), + ); + } + if !local_app.is_empty() { + paths.push( + PathBuf::from(&local_app) + .join(vendor) + .join(product) + .join("Application") + .join(exe), + ); + } + } + paths +} + +pub fn edge_path() -> Option { + edge_candidates().into_iter().find(|path| path.exists()) +} + +fn temp_dir() -> PathBuf { + let dir = dirs::data_local_dir() + .unwrap_or_else(std::env::temp_dir) + .join("LDConverter") + .join("tmp"); + let _ = std::fs::create_dir_all(&dir); + dir +} + +/// Yolu `file:///` URL'sine çevirir (boşluk ve Türkçe karakterleri yüzde-kodlar). +fn file_url(path: &Path) -> String { + let text = path.to_string_lossy().replace('\\', "/"); + let mut encoded = String::from("file:///"); + for byte in text.as_bytes() { + match byte { + b' ' => encoded.push_str("%20"), + b'#' => encoded.push_str("%23"), + b'?' => encoded.push_str("%3F"), + b'%' => encoded.push_str("%25"), + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' | b':' => { + encoded.push(*byte as char) + } + other => encoded.push_str(&format!("%{:02X}", other)), + } + } + encoded +} + +fn run_edge(edge: &Path, arguments: &[String]) -> bool { + let mut command = Command::new(edge); + command + .args(arguments) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x08000000); // CREATE_NO_WINDOW + } + + let Ok(mut child) = command.spawn() else { + return false; + }; + let started = Instant::now(); + loop { + match child.try_wait() { + Ok(Some(_)) => return true, + Ok(None) => { + if started.elapsed() > TIMEOUT { + let _ = child.kill(); + return false; + } + std::thread::sleep(Duration::from_millis(60)); + } + Err(_) => return false, + } + } +} + +/// HTML'i Edge ile vektör PDF'e basar. Başarılıysa yolu döner. +pub fn html_to_pdf(html: &str, stem: &str, output: &Path) -> Option { + let edge = edge_path()?; + let dir = temp_dir(); + let html_path = dir.join(format!("ld_print_{}.html", stem)); + if std::fs::write(&html_path, html.as_bytes()).is_err() { + return None; + } + + let pdf_path = dir.join(format!("ld_print_{}.pdf", stem)); + let _ = std::fs::remove_file(&pdf_path); + let profile = dir.join("edge_profile"); + + let url = file_url(&html_path); + let target = format!("--print-to-pdf={}", pdf_path.display()); + let profile_arg = format!("--user-data-dir={}", profile.display()); + + let attempts: Vec> = vec![ + vec![ + "--headless=new".to_string(), + "--disable-gpu".to_string(), + "--no-first-run".to_string(), + "--no-pdf-header-footer".to_string(), + "--print-to-pdf-no-header".to_string(), + profile_arg.clone(), + target.clone(), + url.clone(), + ], + vec![ + "--headless".to_string(), + "--disable-gpu".to_string(), + "--no-first-run".to_string(), + profile_arg.clone(), + target.clone(), + url.clone(), + ], + ]; + + for arguments in attempts { + let finished = run_edge(&edge, &arguments); + // Edge alt süreçlere geç bitirebilir; dosya oluşana kadar kısa süre bekle. + let wait_started = Instant::now(); + while !pdf_path.exists() && wait_started.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(80)); + } + if pdf_path.exists() { + let bytes = std::fs::read(&pdf_path).unwrap_or_default(); + if bytes.starts_with(b"%PDF") && bytes.len() > 1000 { + let final_path = crate::services::image_engine::ImageEngine::get_unique_path(output, false); + if std::fs::copy(&pdf_path, &final_path).is_ok() { + let _ = std::fs::remove_file(&pdf_path); + let _ = std::fs::remove_file(&html_path); + logging::info(&format!( + "Edge PrintToPdf başarılı ({} bayt, finished={})", + bytes.len(), + finished + )); + return Some(final_path); + } + } + } + } + + logging::warn("Edge PrintToPdf başarısız; dahili PDF yazıcısına düşülecek"); + let _ = std::fs::remove_file(&html_path); + let _ = std::fs::remove_file(&pdf_path); + None +} diff --git a/src-tauri/src/services/image_engine.rs b/src-tauri/src/services/image_engine.rs new file mode 100644 index 0000000..0a5b1f1 --- /dev/null +++ b/src-tauri/src/services/image_engine.rs @@ -0,0 +1,1188 @@ +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::{Path, PathBuf}; + +#[cfg(windows)] +use std::os::windows::process::CommandExt; + +use image::imageops::FilterType; +use image::{DynamicImage, GenericImageView, ImageEncoder, ImageFormat}; + +use crate::error::{AppError, AppResult}; +use crate::models::ConversionOptions; + +/// SVG baytlarını saf Rust (`resvg` + `tiny-skia`) ile bellekte RGBA8 görsele rasterize eder. +/// Küçük vektör çizimlerin net çıkması için en uzun kenarı en az 1024 px ölçeğine büyütür. +pub fn render_svg(bytes: &[u8]) -> Result { + ImageEngine::render_svg_with_options(bytes, None, None, None) +} + +static SYSTEM_FONTS: std::sync::OnceLock> = + std::sync::OnceLock::new(); + +fn get_cached_system_fonts() -> std::sync::Arc { + SYSTEM_FONTS + .get_or_init(|| { + let mut db = resvg::usvg::fontdb::Database::new(); + db.load_system_fonts(); + std::sync::Arc::new(db) + }) + .clone() +} + +pub struct ImageEngine; + +/// Dönüşüm sırasında kullanılan ara dosya; kapsam dışına çıkınca silinir. +struct TempFile { + path: PathBuf, +} + +impl TempFile { + fn new(dir: &Path, stem: &str, ext: &str) -> Self { + Self { + path: dir.join(format!(".{}-{}.tmp.{}", stem, uuid::Uuid::new_v4(), ext)), + } + } +} + +impl Drop for TempFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.path); + } +} + +impl ImageEngine { + /// Alfa kanalı olmayan formatlara (JPG/BMP) yazarken saydam pikselleri + /// beyaz arka plan üzerine birleştirir (siyah zemin sorununu önler). + pub(crate) fn flatten_on_white(img: &DynamicImage) -> image::RgbImage { + let rgba = img.to_rgba8(); + let mut output = image::RgbImage::new(rgba.width(), rgba.height()); + for (x, y, pixel) in rgba.enumerate_pixels() { + let alpha = pixel[3] as u32; + let blend = |channel: u8| -> u8 { + ((channel as u32 * alpha + 255 * (255 - alpha)) / 255) as u8 + }; + output.put_pixel( + x, + y, + image::Rgb([blend(pixel[0]), blend(pixel[1]), blend(pixel[2])]), + ); + } + output + } + + pub fn convert_single( + input_path: &str, + target_format: &str, + output_dir: &Path, + options: &ConversionOptions, + ) -> AppResult { + let input_p = Path::new(input_path); + if !input_p.exists() { + return Err(AppError::NotFound(input_path.to_string())); + } + + let base_name = input_p + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("converted"); + + let ext = target_format.to_lowercase().trim_start_matches('.').to_string(); + let target_ext = match ext.as_str() { + "jpg" | "jpeg" => "jpg", + "png" => "png", + "webp" => "webp", + "bmp" => "bmp", + "tiff" | "tif" => "tiff", + "ico" => "ico", + "gif" => "gif", + "jxl" => "jxl", + "avif" => "avif", + _ => &ext, + }; + + let mut output_path = output_dir.join(format!("{}.{}", base_name, target_ext)); + output_path = Self::get_unique_path(&output_path, options.overwrite_existing); + + let input_ext = input_p + .extension() + .and_then(|e| e.to_str()) + .map(|s| s.to_lowercase()) + .unwrap_or_default(); + + let is_input_svg = input_ext == "svg"; + let mut img = Self::open_any_image(input_p, options)?; + + if !is_input_svg { + img = Self::apply_resize(img, options); + } + + Self::encode_image_to_path( + &img, + target_ext, + &output_path, + output_dir, + base_name, + options.image_quality.clamp(1, 100), + )?; + + Ok(output_path) + } + + /// Herhangi bir görseli (PNG/JPG/WebP/AVIF/SVG/JXL/HEIC/RAW) belleğe yükler. + pub fn open_any_image(input_p: &Path, options: &ConversionOptions) -> AppResult { + if !input_p.exists() { + return Err(AppError::NotFound(input_p.to_string_lossy().to_string())); + } + + let input_ext = input_p + .extension() + .and_then(|e| e.to_str()) + .map(|s| s.to_lowercase()) + .unwrap_or_default(); + + let is_input_svg = input_ext == "svg"; + let is_input_jxl = input_ext == "jxl" || input_ext == "jpegxl"; + let is_wic_preferred = matches!( + input_ext.as_str(), + "heic" | "heif" | "cr2" | "nef" | "arw" | "dng" | "raw" + ); + + let base_name = input_p + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("decoded"); + let work_dir = input_p + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + + let mut img = if is_input_svg { + Self::decode_svg_in_memory(input_p, options)? + } else if is_input_jxl { + let tmp = TempFile::new(work_dir, base_name, "png"); + if Self::decode_jxl(input_p, &tmp.path).is_ok() { + image::open(&tmp.path)? + } else { + Self::decode_with_wic(input_p).map_err(AppError::Engine)? + } + } else if is_wic_preferred { + if let Ok(im) = Self::decode_with_wic(input_p) { + im + } else if let Ok(im) = image::open(input_p) { + im + } else { + let tmp = TempFile::new(work_dir, base_name, "png"); + let decode_opts = ConversionOptions::default(); + Self::convert_via_ffmpeg(&input_p.to_string_lossy(), &tmp.path, "png", &decode_opts)?; + image::open(&tmp.path)? + } + } else { + match image::open(input_p) { + Ok(im) => im, + Err(_) if input_ext == "avif" => { + let tmp = TempFile::new(work_dir, base_name, "png"); + let decode_opts = ConversionOptions::default(); + if Self::convert_via_ffmpeg( + &input_p.to_string_lossy(), + &tmp.path, + "png", + &decode_opts, + ) + .is_ok() + { + image::open(&tmp.path)? + } else { + Self::decode_with_wic(input_p).map_err(AppError::Engine)? + } + } + Err(_) => { + if let Ok(im) = Self::decode_with_wic(input_p) { + im + } else { + let tmp = TempFile::new(work_dir, base_name, "png"); + let decode_opts = ConversionOptions::default(); + Self::convert_via_ffmpeg( + &input_p.to_string_lossy(), + &tmp.path, + "png", + &decode_opts, + )?; + image::open(&tmp.path)? + } + } + } + }; + + if !is_input_svg { + let orientation = std::fs::read(input_p) + .map(|bytes| read_exif_orientation(&bytes)) + .unwrap_or(1); + if orientation != 1 { + img = apply_orientation(img, orientation); + } + } + + Ok(img) + } + + pub fn create_animated_gif( + input_paths: &[String], + output_path: &Path, + fps: u32, + ) -> AppResult { + if input_paths.is_empty() { + return Err(AppError::Generic("Görsel listesi boş".to_string())); + } + + let file = File::create(output_path)?; + let writer = BufWriter::new(file); + let mut encoder = image::codecs::gif::GifEncoder::new(writer); + encoder.set_repeat(image::codecs::gif::Repeat::Infinite)?; + + let delay_ms = (1000.0 / fps.max(1) as f64).round() as u32; + let delay = image::Delay::from_numer_denom_ms(delay_ms, 1); + let default_opts = ConversionOptions::default(); + + for path in input_paths { + let img = Self::open_any_image(Path::new(path), &default_opts)?; + // GIF bellek şişmesini önle: büyük kareleri 960px'e sığdır + let (w, h) = (img.width(), img.height()); + let img = if w > 960 || h > 960 { + img.resize(960, 960, FilterType::Lanczos3) + } else { + img + }; + let rgba = img.to_rgba8(); + let frame = image::Frame::from_parts(rgba, 0, 0, delay); + encoder.encode_frame(frame)?; + } + + Ok(output_path.to_path_buf()) + } + + /// Tek/çoklu görseli tek PDF belgesine dönüştürür (A4 oranlı sayfalar, JPEG gömme). + pub fn create_pdf( + input_paths: &[String], + output_path: &Path, + options: &ConversionOptions, + ) -> AppResult { + crate::services::pdf_engine::PdfEngine::merge(input_paths, output_path, options) + } + + /// Görseli kalitesini optimize ederek veya PNG nicemlemesi (256 renk + Floyd-Steinberg) + /// uygulayarak sıkıştırır (EXIF/GPS verisi atılır). + pub fn compress_image( + input_path: &str, + output_dir: &Path, + options: &ConversionOptions, + ) -> AppResult { + let input_p = Path::new(input_path); + if !input_p.exists() { + return Err(AppError::NotFound(input_path.to_string())); + } + let ext = input_p + .extension() + .and_then(|e| e.to_str()) + .map(|s| s.to_lowercase()) + .unwrap_or_else(|| "jpg".to_string()); + + let base_name = input_p + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("compressed"); + let output_path = Self::get_unique_path( + &output_dir.join(format!("{}.{}", base_name, ext)), + options.overwrite_existing, + ); + + if ext == "svg" { + return Err(AppError::Engine( + "SVG vektör dosyası doğrudan raster sıkıştırmasını desteklemez; PNG, WebP veya AVIF'e dönüştürün." + .to_string(), + )); + } + + let mut img = Self::open_any_image(input_p, options)?; + img = Self::apply_resize(img, options); + + let quality = options.image_quality.clamp(10, 95); + let target_ext = match ext.as_str() { + "jpeg" => "jpg", + "jpegxl" => "jxl", + other => other, + }; + + if target_ext == "png" { + Self::compress_png_quantized(&img, &output_path)?; + } else { + Self::encode_image_to_path(&img, target_ext, &output_path, output_dir, base_name, quality)?; + } + + Ok(output_path) + } + + fn apply_resize(img: DynamicImage, options: &ConversionOptions) -> DynamicImage { + if let (Some(w), Some(h)) = (options.target_width, options.target_height) { + if w > 0 && h > 0 && img.dimensions() != (w, h) { + return img.resize_exact(w, h, FilterType::Lanczos3); + } + } else if let Some(w) = options.target_width { + if w > 0 && img.width() != w { + let (cur_w, cur_h) = img.dimensions(); + if cur_w > 0 { + let h = ((cur_h as f64 / cur_w as f64) * w as f64).round() as u32; + return img.resize(w, h.max(1), FilterType::Lanczos3); + } + } + } + img + } + + fn encode_image_to_path( + img: &DynamicImage, + target_ext: &str, + output_path: &Path, + output_dir: &Path, + base_name: &str, + quality: u8, + ) -> AppResult<()> { + match target_ext { + "png" => { + img.save_with_format(output_path, ImageFormat::Png)?; + } + "jpg" => { + let rgb = Self::flatten_on_white(img); + let file = File::create(output_path)?; + let mut writer = BufWriter::new(file); + let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality( + &mut writer, + quality.clamp(1, 100), + ); + encoder.encode( + rgb.as_raw(), + rgb.width(), + rgb.height(), + image::ExtendedColorType::Rgb8, + )?; + } + "webp" => { + img.save_with_format(output_path, ImageFormat::WebP)?; + } + "avif" => { + Self::encode_avif_in_memory(img, output_path, quality)?; + } + "bmp" => { + Self::flatten_on_white(img).save_with_format(output_path, ImageFormat::Bmp)?; + } + "tiff" => { + img.save_with_format(output_path, ImageFormat::Tiff)?; + } + "gif" => { + img.save_with_format(output_path, ImageFormat::Gif)?; + } + "ico" => { + Self::save_as_ico(img, output_path)?; + } + "jxl" => { + // cjxl doğrudan DynamicImage alamaz: Geçici dosyaya hızlı sıkıştırmasız PNG yazıp kodluyoruz. + let tmp = TempFile::new(output_dir, base_name, "png"); + Self::write_fast_png(&tmp.path, img)?; + Self::encode_jxl(&tmp.path, output_path, quality)?; + } + _ => { + img.save(output_path)?; + } + } + Ok(()) + } + + /// SVG baytlarını `resvg` + `tiny-skia` ile bellekte RGBA8 görsele dönüştürür. + /// İsteğe bağlı kaynak dizini ve hedef boyut alır; hedef boyut belirtilmezse + /// küçük SVG'leri en az 1024 px kenar boyutuna ölçekler. + pub fn render_svg_with_options( + bytes: &[u8], + resources_dir: Option<&Path>, + target_width: Option, + target_height: Option, + ) -> Result { + let mut opt = resvg::usvg::Options { + fontdb: get_cached_system_fonts(), + ..Default::default() + }; + if let Some(dir) = resources_dir { + opt.resources_dir = Some(dir.to_path_buf()); + } + + let tree = resvg::usvg::Tree::from_data(bytes, &opt) + .map_err(|e| format!("SVG ayrıştırılamadı: {}", e))?; + + let orig_w = tree.size().width().max(1.0); + let orig_h = tree.size().height().max(1.0); + let (out_w, out_h) = match (target_width, target_height) { + (Some(tw), Some(th)) if tw > 0 && th > 0 => (tw.clamp(1, 8192), th.clamp(1, 8192)), + (Some(tw), _) if tw > 0 => { + let th = ((orig_h as f64 / orig_w as f64) * tw as f64).round().max(1.0) as u32; + (tw.clamp(1, 8192), th.clamp(1, 8192)) + } + _ => { + let max_edge = orig_w.max(orig_h); + let scale = if max_edge < 1024.0 { 1024.0 / max_edge } else { 1.0 }; + let ow = ((orig_w * scale).round() as u32).clamp(1, 8192); + let oh = ((orig_h * scale).round() as u32).clamp(1, 8192); + (ow, oh) + } + }; + + let mut pixmap = tiny_skia::Pixmap::new(out_w, out_h) + .ok_or_else(|| format!("SVG tuval boyutu oluşturulamadı ({}x{})", out_w, out_h))?; + + let transform = + tiny_skia::Transform::from_scale(out_w as f32 / orig_w, out_h as f32 / orig_h); + resvg::render(&tree, transform, &mut pixmap.as_mut()); + + let mut rgba_bytes = Vec::with_capacity((out_w as usize) * (out_h as usize) * 4); + for pixel in pixmap.pixels() { + let color = pixel.demultiply(); + rgba_bytes.push(color.red()); + rgba_bytes.push(color.green()); + rgba_bytes.push(color.blue()); + rgba_bytes.push(color.alpha()); + } + + let rgba = image::RgbaImage::from_raw(out_w, out_h, rgba_bytes) + .ok_or_else(|| "SVG piksel tamponu geçersiz.".to_string())?; + Ok(DynamicImage::ImageRgba8(rgba)) + } + + /// SVG dosyasını harici bir süreç başlatmadan `resvg` ile bellekte rasterize eder. + fn decode_svg_in_memory(input: &Path, options: &ConversionOptions) -> AppResult { + let bytes = std::fs::read(input)?; + Self::render_svg_with_options( + &bytes, + input.parent(), + options.target_width, + options.target_height, + ) + .map_err(AppError::Engine) + } + + /// Windows Imaging Component (WIC) COM API ile HEIC/HEIF/JXL/RAW vb. görselleri + /// sıfır dış bağımlılıkla RGBA8 olarak belleğe çözer. + #[cfg(windows)] + pub fn decode_with_wic(path: &Path) -> Result { + use windows::Win32::Foundation::GENERIC_READ; + use windows::Win32::Graphics::Imaging::{ + CLSID_WICImagingFactory, GUID_WICPixelFormat32bppRGBA, IWICBitmapSource, + IWICImagingFactory, IWICPalette, WICBitmapDitherTypeNone, WICBitmapPaletteTypeCustom, + WICDecodeMetadataCacheOnDemand, + }; + use windows::Win32::System::Com::{ + CoCreateInstance, CoInitializeEx, CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, + }; + use windows_core::{Interface, HSTRING}; + + unsafe { + let _ = CoInitializeEx(None, COINIT_MULTITHREADED); + + let factory: IWICImagingFactory = + CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER) + .map_err(|e| format!("WIC factory başlatılamadı: {}", e))?; + let wide_path = HSTRING::from(path.as_os_str()); + let decoder = factory + .CreateDecoderFromFilename( + &wide_path, + None, + GENERIC_READ, + WICDecodeMetadataCacheOnDemand, + ) + .map_err(|e| format!("WIC dosyayı açamadı: {}", e))?; + let frame = decoder + .GetFrame(0) + .map_err(|e| format!("WIC kare okunamadı: {}", e))?; + let converter = factory + .CreateFormatConverter() + .map_err(|e| format!("WIC renk dönüştürücü oluşturulamadı: {}", e))?; + let source: IWICBitmapSource = frame + .cast() + .map_err(|e| format!("WIC kaynak arayüzü alınamadı: {}", e))?; + converter + .Initialize( + &source, + &GUID_WICPixelFormat32bppRGBA, + WICBitmapDitherTypeNone, + None::<&IWICPalette>, + 0.0, + WICBitmapPaletteTypeCustom, + ) + .map_err(|e| format!("WIC RGBA dönüşümü başarısız: {}", e))?; + + let mut width = 0u32; + let mut height = 0u32; + converter + .GetSize(&mut width, &mut height) + .map_err(|e| format!("WIC boyut alınamadı: {}", e))?; + if width == 0 || height == 0 { + return Err("WIC görsel boyutları sıfır döndü.".to_string()); + } + + let stride = width + .checked_mul(4) + .ok_or_else(|| "WIC satır genişliği taştı.".to_string())?; + let total_bytes = (stride as usize) + .checked_mul(height as usize) + .ok_or_else(|| "WIC piksel tampon boyutu taştı.".to_string())?; + let mut buffer = vec![0u8; total_bytes]; + converter + .CopyPixels(std::ptr::null(), stride, &mut buffer) + .map_err(|e| format!("WIC piksel kopyalanamadı: {}", e))?; + + let rgba = image::RgbaImage::from_raw(width, height, buffer) + .ok_or_else(|| "WIC piksel tamponu geçersiz.".to_string())?; + Ok(DynamicImage::ImageRgba8(rgba)) + } + } + + #[cfg(not(windows))] + pub fn decode_with_wic(_path: &Path) -> Result { + Err("Windows WIC yalnız Windows üzerinde desteklenir.".to_string()) + } + + /// 256 renk Median-Cut palet + Floyd-Steinberg hata yayılımı (dithering) + uyarlamalı + /// satır filtresi ile 8-bit dizinli PNG üretir ve kayıpsız sıkıştırma ile karşılaştırıp küçük olanı yazar. + fn compress_png_quantized(img: &DynamicImage, output_path: &Path) -> AppResult<()> { + let rgba = img.to_rgba8(); + let (w, h) = (rgba.width() as usize, rgba.height() as usize); + if w == 0 || h == 0 { + img.save_with_format(output_path, ImageFormat::Png)?; + return Ok(()); + } + + let indexed_bytes = encode_quantized_png(&rgba)?; + + // Çok az renkli basit görsellerde kayıpsız Best PNG daha küçükse onu koru. + let mut lossless_bytes = Vec::new(); + { + use image::codecs::png::{CompressionType, FilterType as PngFilter, PngEncoder}; + let encoder = PngEncoder::new_with_quality( + &mut lossless_bytes, + CompressionType::Best, + PngFilter::Adaptive, + ); + encoder.write_image( + rgba.as_raw(), + rgba.width(), + rgba.height(), + image::ExtendedColorType::Rgba8, + )?; + } + + let chosen = if lossless_bytes.len() < indexed_bytes.len() { + lossless_bytes + } else { + indexed_bytes + }; + std::fs::write(output_path, chosen)?; + Ok(()) + } + + /// Ara işlemler için en düşük CPU yüküyle hızlı ve sıkıştırmasız PNG yazar. + fn write_fast_png(path: &Path, img: &DynamicImage) -> AppResult<()> { + use image::codecs::png::{CompressionType, FilterType as PngFilter, PngEncoder}; + let file = File::create(path)?; + let writer = BufWriter::new(file); + let encoder = + PngEncoder::new_with_quality(writer, CompressionType::Fast, PngFilter::NoFilter); + let rgba = img.to_rgba8(); + encoder.write_image( + rgba.as_raw(), + rgba.width(), + rgba.height(), + image::ExtendedColorType::Rgba8, + )?; + Ok(()) + } + + /// Görseli FFmpeg başlatmadan `image` crate'inin dahili `ravif` kodlayıcısıyla AVIF'e yazar. + fn encode_avif_in_memory( + img: &DynamicImage, + output_path: &Path, + quality: u8, + ) -> AppResult<()> { + let rgba = img.to_rgba8(); + let file = File::create(output_path)?; + let writer = BufWriter::new(file); + let encoder = + image::codecs::avif::AvifEncoder::new_with_speed_quality(writer, 8, quality.clamp(1, 100)); + encoder.write_image( + rgba.as_raw(), + rgba.width(), + rgba.height(), + image::ExtendedColorType::Rgba8, + )?; + Ok(()) + } + + fn save_as_ico(img: &DynamicImage, output_path: &Path) -> AppResult<()> { + // Oranı koruyarak 256x256 şeffaf tuvale ortala + let resized = img.resize(256, 256, FilterType::Lanczos3); + let mut canvas = image::RgbaImage::new(256, 256); + let offset_x = (256u32.saturating_sub(resized.width())) / 2; + let offset_y = (256u32.saturating_sub(resized.height())) / 2; + image::imageops::overlay( + &mut canvas, + &resized.to_rgba8(), + offset_x as i64, + offset_y as i64, + ); + image::DynamicImage::ImageRgba8(canvas).save_with_format(output_path, ImageFormat::Ico)?; + Ok(()) + } + + fn convert_via_ffmpeg( + input_path: &str, + output_path: &Path, + target_ext: &str, + options: &ConversionOptions, + ) -> AppResult { + let ffmpeg = crate::services::engine_resolver::EngineResolver::resolve_ffmpeg(None) + .ok_or_else(|| { + AppError::Engine(format!( + "{} formatına dönüştürmek için sistemde FFmpeg kurulu olmalıdır.", + target_ext.to_uppercase() + )) + })?; + + let mut cmd = std::process::Command::new(ffmpeg); + #[cfg(windows)] + cmd.creation_flags(0x08000000); + cmd.arg("-y").arg("-i").arg(input_path); + + if let (Some(w), Some(h)) = (options.target_width, options.target_height) { + if w > 0 && h > 0 { + cmd.arg("-vf").arg(format!("scale={}:{}", w, h)); + } + } else if let Some(w) = options.target_width { + if w > 0 { + cmd.arg("-vf").arg(format!("scale={}:-1", w)); + } + } + + if target_ext == "jpg" || target_ext == "jpeg" { + let q = ((100 - options.image_quality.clamp(1, 100)) as f32 * 0.31).round() as u32; + cmd.arg("-q:v").arg(q.clamp(1, 31).to_string()); + } + + cmd.arg(output_path); + + let status = cmd.status()?; + if status.success() && output_path.exists() { + Ok(output_path.to_path_buf()) + } else { + Err(AppError::Engine(format!( + "FFmpeg {} dönüşümü başarısız oldu.", + target_ext.to_uppercase() + ))) + } + } + + /// Harici bir aracı çalıştırır; başarısızsa stderr'in son satırlarını hataya katar. + fn run_tool(exe: &str, args: &[&str], fail_msg: &str) -> AppResult<()> { + let mut cmd = std::process::Command::new(exe); + #[cfg(windows)] + cmd.creation_flags(0x08000000); + let output = cmd.args(args).output()?; + if output.status.success() { + return Ok(()); + } + let stderr = String::from_utf8_lossy(&output.stderr); + let lines: Vec<&str> = stderr.lines().filter(|l| !l.trim().is_empty()).collect(); + let tail = lines[lines.len().saturating_sub(2)..].join(" "); + Err(AppError::Engine(format!( + "{}: {}", + fail_msg, + if tail.is_empty() { "bilinmeyen hata" } else { &tail } + ))) + } + + /// JXL dosyasını PNG'ye çözer: önce paketlenmiş djxl.exe, yoksa libjxl'li FFmpeg. + fn decode_jxl(input: &Path, png_out: &Path) -> AppResult<()> { + let input_s = input.to_string_lossy().to_string(); + let png_s = png_out.to_string_lossy().to_string(); + + if let Some(djxl) = crate::services::EngineResolver::resolve_jxl_decoder() { + return Self::run_tool( + &djxl, + &[input_s.as_str(), png_s.as_str()], + "JPEG XL çözülemedi", + ); + } + if crate::services::EngineResolver::ffmpeg_supports_jxl() { + if let Some(ffmpeg) = crate::services::EngineResolver::resolve_ffmpeg(None) { + return Self::run_tool( + &ffmpeg, + &["-y", "-i", input_s.as_str(), png_s.as_str()], + "JPEG XL çözülemedi (FFmpeg)", + ); + } + } + Err(AppError::Engine( + "JPEG XL desteği bulunamadı: tools/djxl.exe pakette yok ve FFmpeg'de libjxl yok." + .to_string(), + )) + } + + /// PNG'yi JPEG XL'e kodlar: önce paketlenmiş cjxl.exe, yoksa libjxl'li FFmpeg. + fn encode_jxl(png: &Path, output: &Path, quality: u8) -> AppResult<()> { + let png_s = png.to_string_lossy().to_string(); + let out_s = output.to_string_lossy().to_string(); + + if let Some(cjxl) = crate::services::EngineResolver::resolve_jxl_encoder() { + let q = quality.clamp(1, 100).to_string(); + return Self::run_tool( + &cjxl, + &[png_s.as_str(), out_s.as_str(), "-q", q.as_str()], + "JPEG XL kodlanamadı", + ); + } + if crate::services::EngineResolver::ffmpeg_supports_jxl() { + if let Some(ffmpeg) = crate::services::EngineResolver::resolve_ffmpeg(None) { + return Self::run_tool( + &ffmpeg, + &["-y", "-i", png_s.as_str(), out_s.as_str()], + "JPEG XL kodlanamadı (FFmpeg)", + ); + } + } + Err(AppError::Engine( + "JPEG XL desteği bulunamadı: tools/cjxl.exe pakette yok ve FFmpeg'de libjxl yok." + .to_string(), + )) + } + + pub fn get_unique_path(path: &Path, overwrite: bool) -> PathBuf { + if overwrite || !path.exists() { + return path.to_path_buf(); + } + + let dir = path.parent().unwrap_or_else(|| Path::new("")); + let file_name = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("output"); + let lower = file_name.to_ascii_lowercase(); + + // Bileşik uzantılar (arsiv.tar.gz -> "arsiv (1).tar.gz") doğru numaralansın. + let compound = ["tar.gz", "tar.bz2", "tar.xz"] + .iter() + .find(|suffix| lower.ends_with(&format!(".{}", suffix))) + .copied(); + + let (stem, ext) = match compound { + Some(suffix) => ( + &file_name[..file_name.len() - suffix.len() - 1], + suffix, + ), + None => ( + path.file_stem().and_then(|s| s.to_str()).unwrap_or("output"), + path.extension().and_then(|e| e.to_str()).unwrap_or(""), + ), + }; + + let mut counter = 1; + loop { + let candidate_name = if ext.is_empty() { + format!("{} ({})", stem, counter) + } else { + format!("{} ({}).{}", stem, counter, ext) + }; + let candidate = dir.join(candidate_name); + if !candidate.exists() { + return candidate; + } + counter += 1; + } + } +} + +/// JPEG APP1 (`Exif\0\0`) veya TIFF başlığından EXIF Orientation (0x0112) okur. +pub fn read_exif_orientation(bytes: &[u8]) -> u8 { + let parse_tiff = |tiff: &[u8]| -> Option { + if tiff.len() < 8 { + return None; + } + let le = match &tiff[0..2] { + b"II" => true, + b"MM" => false, + _ => return None, + }; + let u16_at = |o: usize| -> Option { + let s = tiff.get(o..o + 2)?; + Some(if le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) }) + }; + let u32_at = |o: usize| -> Option { + let s = tiff.get(o..o + 4)?; + Some(if le { + u32::from_le_bytes([s[0], s[1], s[2], s[3]]) + } else { + u32::from_be_bytes([s[0], s[1], s[2], s[3]]) + }) + }; + if u16_at(2)? != 42 { + return None; + } + let ifd_off = u32_at(4)? as usize; + let count = u16_at(ifd_off)? as usize; + for i in 0..count.min(64) { + let entry = ifd_off + 2 + i * 12; + if u16_at(entry)? == 0x0112 { + return u16_at(entry + 8).map(|v| v as u8); + } + } + None + }; + + if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") { + return parse_tiff(bytes).unwrap_or(1); + } + if bytes.starts_with(&[0xFF, 0xD8]) { + let mut i = 2; + while i + 4 <= bytes.len() && bytes[i] == 0xFF { + let marker = bytes[i + 1]; + if marker == 0xDA || marker == 0xD9 { + break; + } + let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize; + if len < 2 || i + 2 + len > bytes.len() { + break; + } + if marker == 0xE1 && len >= 14 && &bytes[i + 4..i + 10] == b"Exif\0\0" { + if let Some(orientation) = parse_tiff(&bytes[i + 10..i + 2 + len]) { + return orientation; + } + } + i += 2 + len; + } + } + 1 +} + +/// EXIF yönüne göre döndürme/aynalama uygular. +pub fn apply_orientation(img: image::DynamicImage, orientation: u8) -> image::DynamicImage { + match orientation { + 2 => img.fliph(), + 3 => img.rotate180(), + 4 => img.flipv(), + 5 => img.rotate90().fliph(), + 6 => img.rotate90(), + 7 => img.rotate270().fliph(), + 8 => img.rotate270(), + _ => img, + } +} + +fn build_median_cut_palette(rgba: &image::RgbaImage) -> Vec<[u8; 4]> { + let raw = rgba.as_raw(); + let total_pixels = raw.len() / 4; + if total_pixels == 0 { + return vec![[0, 0, 0, 255]]; + } + + let step = (total_pixels / 24_576).max(1); + let mut samples: Vec<[u8; 4]> = Vec::with_capacity((total_pixels / step).min(24_576) + 1); + let mut idx = 0usize; + while idx < total_pixels { + let off = idx * 4; + if let Some(chunk) = raw.get(off..off + 4) { + samples.push([chunk[0], chunk[1], chunk[2], chunk[3]]); + } + idx += step; + } + + if samples.is_empty() { + return vec![[0, 0, 0, 255]]; + } + + let mut boxes: Vec> = vec![samples]; + while boxes.len() < 256 { + let mut best_box_idx = None; + let mut best_score = 0u64; + let mut best_channel = 0usize; + + for (bi, b) in boxes.iter().enumerate() { + if b.len() < 2 { + continue; + } + let (mut min_c, mut max_c) = ([255u8; 4], [0u8; 4]); + for px in b { + for ch in 0..4 { + if px[ch] < min_c[ch] { + min_c[ch] = px[ch]; + } + if px[ch] > max_c[ch] { + max_c[ch] = px[ch]; + } + } + } + for ch in 0..4 { + let span = (max_c[ch] - min_c[ch]) as u64; + let weight = if ch == 3 { span * 2 } else { span }; + let score = weight * (b.len() as u64); + if span > 0 && score > best_score { + best_score = score; + best_box_idx = Some(bi); + best_channel = ch; + } + } + } + + let Some(bi) = best_box_idx else { + break; + }; + let mut target = boxes.swap_remove(bi); + target.sort_unstable_by_key(|px| px[best_channel]); + let mid = target.len() / 2; + let right = target.split_off(mid); + boxes.push(target); + boxes.push(right); + } + + let mut palette = Vec::with_capacity(boxes.len()); + for b in boxes { + if b.is_empty() { + continue; + } + let mut sum = [0u64; 4]; + for px in &b { + sum[0] += px[0] as u64; + sum[1] += px[1] as u64; + sum[2] += px[2] as u64; + sum[3] += px[3] as u64; + } + let n = b.len() as u64; + palette.push([ + (sum[0] / n) as u8, + (sum[1] / n) as u8, + (sum[2] / n) as u8, + (sum[3] / n) as u8, + ]); + } + if palette.is_empty() { + palette.push([0, 0, 0, 255]); + } + palette +} + +fn nearest_palette_index(palette: &[[u8; 4]], r: i32, g: i32, b: i32, a: i32) -> usize { + let mut best_idx = 0usize; + let mut best_dist = i64::MAX; + for (i, &[pr, pg, pb, pa]) in palette.iter().enumerate() { + let dr = (r - pr as i32) as i64; + let dg = (g - pg as i32) as i64; + let db = (b - pb as i32) as i64; + let da = (a - pa as i32) as i64; + let dist = 2 * dr * dr + 4 * dg * dg + db * db + 3 * da * da; + if dist == 0 { + return i; + } + if dist < best_dist { + best_dist = dist; + best_idx = i; + } + } + best_idx +} + +fn dither_to_indices(rgba: &image::RgbaImage, palette: &[[u8; 4]]) -> Vec { + let (w, h) = (rgba.width() as usize, rgba.height() as usize); + let raw = rgba.as_raw(); + let mut indices = vec![0u8; w * h]; + let mut cur_err = vec![[0i16; 4]; w]; + let mut next_err = vec![[0i16; 4]; w]; + + for y in 0..h { + next_err.fill([0i16; 4]); + for x in 0..w { + let off = (y * w + x) * 4; + let base_px = raw.get(off..off + 4).unwrap_or(&[0, 0, 0, 255]); + let err = cur_err[x]; + let r = (base_px[0] as i32 + err[0] as i32).clamp(0, 255); + let g = (base_px[1] as i32 + err[1] as i32).clamp(0, 255); + let b = (base_px[2] as i32 + err[2] as i32).clamp(0, 255); + let a = (base_px[3] as i32 + err[3] as i32).clamp(0, 255); + + let pi = nearest_palette_index(palette, r, g, b, a); + indices[y * w + x] = pi as u8; + let chosen = palette[pi]; + let diff = [ + r - chosen[0] as i32, + g - chosen[1] as i32, + b - chosen[2] as i32, + a - chosen[3] as i32, + ]; + + for ch in 0..4 { + if x + 1 < w { + cur_err[x + 1][ch] = + cur_err[x + 1][ch].saturating_add(((diff[ch] * 7) / 16) as i16); + } + if y + 1 < h { + if x > 0 { + next_err[x - 1][ch] = + next_err[x - 1][ch].saturating_add(((diff[ch] * 3) / 16) as i16); + } + next_err[x][ch] = + next_err[x][ch].saturating_add(((diff[ch] * 5) / 16) as i16); + if x + 1 < w { + next_err[x + 1][ch] = + next_err[x + 1][ch].saturating_add((diff[ch] / 16) as i16); + } + } + } + } + std::mem::swap(&mut cur_err, &mut next_err); + } + + indices +} + +fn write_png_chunk(out: &mut Vec, tag: &[u8; 4], data: &[u8]) { + out.extend_from_slice(&(data.len() as u32).to_be_bytes()); + out.extend_from_slice(tag); + out.extend_from_slice(data); + let mut hasher = crc32fast::Hasher::new(); + hasher.update(tag); + hasher.update(data); + out.extend_from_slice(&hasher.finalize().to_be_bytes()); +} + +fn encode_quantized_png(rgba: &image::RgbaImage) -> AppResult> { + let palette = build_median_cut_palette(rgba); + let indices = dither_to_indices(rgba, &palette); + let (w, h) = (rgba.width() as usize, rgba.height() as usize); + + let mut filtered = Vec::with_capacity(h * (w + 1)); + let mut prev_row = vec![0u8; w]; + for y in 0..h { + let row = &indices[y * w..(y + 1) * w]; + // None(0), Sub(1), Up(2) filtrelerinden en düşük mutlak toplamlı olanı seç. + let mut best_filter = 0u8; + let mut best_row = Vec::with_capacity(w); + best_row.extend_from_slice(row); + let mut best_score: u64 = row.iter().map(|&b| (b as i8 as i32).unsigned_abs() as u64).sum(); + + let mut sub_row = Vec::with_capacity(w); + let mut sub_score = 0u64; + for (i, &val) in row.iter().enumerate() { + let left = if i > 0 { row[i - 1] } else { 0 }; + let diff = val.wrapping_sub(left); + sub_score += (diff as i8 as i32).unsigned_abs() as u64; + sub_row.push(diff); + } + if sub_score < best_score { + best_score = sub_score; + best_filter = 1; + best_row = sub_row; + } + + let mut up_row = Vec::with_capacity(w); + let mut up_score = 0u64; + for (i, &val) in row.iter().enumerate() { + let diff = val.wrapping_sub(prev_row[i]); + up_score += (diff as i8 as i32).unsigned_abs() as u64; + up_row.push(diff); + } + if up_score < best_score { + best_filter = 2; + best_row = up_row; + } + + filtered.push(best_filter); + filtered.extend_from_slice(&best_row); + prev_row.copy_from_slice(row); + } + + let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + encoder.write_all(&filtered)?; + let idat = encoder.finish()?; + + let mut out = Vec::with_capacity(idat.len() + 1024); + out.extend_from_slice(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); + + let mut ihdr = Vec::with_capacity(13); + ihdr.extend_from_slice(&(w as u32).to_be_bytes()); + ihdr.extend_from_slice(&(h as u32).to_be_bytes()); + ihdr.push(8); // bit depth + ihdr.push(3); // indexed-color + ihdr.push(0); // compression + ihdr.push(0); // filter + ihdr.push(0); // interlace + write_png_chunk(&mut out, b"IHDR", &ihdr); + + let mut plte = Vec::with_capacity(palette.len() * 3); + for c in &palette { + plte.extend_from_slice(&[c[0], c[1], c[2]]); + } + write_png_chunk(&mut out, b"PLTE", &plte); + + if let Some(last_trans) = palette.iter().rposition(|c| c[3] < 255) { + let trns: Vec = palette[..=last_trans].iter().map(|c| c[3]).collect(); + write_png_chunk(&mut out, b"tRNS", &trns); + } + + write_png_chunk(&mut out, b"IDAT", &idat); + write_png_chunk(&mut out, b"IEND", &[]); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn render_svg_scales_small_svg_to_at_least_1024px() -> Result<(), Box> { + let svg = br##""##; + let rendered = render_svg(svg)?; + assert_eq!(rendered.width(), 1024); + assert_eq!(rendered.height(), 512); + Ok(()) + } + + #[test] + fn compress_png_quantized_shrinks_dense_rgba_png() -> Result<(), Box> { + let dir = std::env::temp_dir().join(format!("ld_img_test_{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir)?; + let src = dir.join("dense.png"); + let out_dir = dir.join("out"); + std::fs::create_dir_all(&out_dir)?; + + let rgba = image::RgbaImage::from_fn(256, 256, |x, y| { + image::Rgba([ + ((x.wrapping_mul(3).wrapping_add(y)) % 256) as u8, + ((x.wrapping_add(y.wrapping_mul(5))) % 256) as u8, + ((x ^ y) % 256) as u8, + 255, + ]) + }); + rgba.save(&src)?; + let orig_len = std::fs::metadata(&src)?.len(); + + let opts = ConversionOptions { + overwrite_existing: true, + ..Default::default() + }; + let out_path = ImageEngine::compress_image(&src.to_string_lossy(), &out_dir, &opts)?; + let out_len = std::fs::metadata(&out_path)?.len(); + let reloaded = image::open(&out_path)?; + assert_eq!(reloaded.dimensions(), (256, 256)); + assert!( + out_len < orig_len, + "sıkıştırılmış boyut küçülmeli: {} vs {}", + out_len, + orig_len + ); + + let _ = std::fs::remove_dir_all(&dir); + Ok(()) + } +} diff --git a/src-tauri/src/services/math_engine.rs b/src-tauri/src/services/math_engine.rs new file mode 100644 index 0000000..ed75b9c --- /dev/null +++ b/src-tauri/src/services/math_engine.rs @@ -0,0 +1,657 @@ +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::{Path, PathBuf}; + +use zip::write::SimpleFileOptions; +use zip::ZipWriter; + +use crate::error::{AppError, AppResult}; +use crate::services::image_engine::ImageEngine; +use crate::services::omml::{escape_xml, latex_to_omml}; +use crate::services::pdf_text; + +const WORD_NS: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; +const MATH_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/math"; +const REL_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + +/// Geçici çıktıyı nihai (benzersiz) ada taşır. +fn finalize(temp: &Path, final_path: &Path) -> AppResult { + if temp == final_path { + return Ok(temp.to_path_buf()); + } + std::fs::rename(temp, final_path)?; + Ok(final_path.to_path_buf()) +} + +pub struct MathEngine; + +impl MathEngine { + /// Markdown, TXT veya PDF belgesini %100 saf Rust motoruyla gerçek Word OMML + /// (`` / ``) denklemleri içeren `.docx` dosyasına dönüştürür. + pub fn convert_to_math_docx( + input_path: &str, + output_dir: &Path, + overwrite: bool, + ) -> AppResult { + let input_p = Path::new(input_path); + let base_name = input_p + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("document"); + + let final_path = + ImageEngine::get_unique_path(&output_dir.join(format!("{}.docx", base_name)), overwrite); + let output_path = output_dir.join(format!(".ld_math_{}.docx", uuid::Uuid::new_v4())); + let _ = std::fs::remove_file(&output_path); + + let ext = input_p + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_lowercase(); + + if matches!(ext.as_str(), "md" | "markdown" | "txt") { + let bytes = std::fs::read(input_p)?; + let raw_text = String::from_utf8(bytes.clone()) + .unwrap_or_else(|_| String::from_utf8_lossy(&bytes).into_owned()); + if let Err(err) = convert_markdown_to_omml_docx(&raw_text, &output_path) { + let _ = std::fs::remove_file(&output_path); + return Err(err); + } + if output_path.exists() { + return finalize(&output_path, &final_path); + } + } else if ext == "pdf" { + match pdf_text::extract_structured_markdown(input_path) + .and_then(|md| convert_markdown_to_omml_docx(&md, &output_path)) + { + Ok(()) if output_path.exists() => { + return finalize(&output_path, &final_path); + } + Ok(()) => {} + Err(err) => { + let _ = std::fs::remove_file(&output_path); + return Err(err); + } + } + } else { + let _ = std::fs::remove_file(&output_path); + return Err(AppError::Engine(format!( + "Denklem DOCX dönüşümü '.{}' biçimini desteklemiyor (MD, TXT veya PDF gerekir).", + ext + ))); + } + + let _ = std::fs::remove_file(&output_path); + Err(AppError::Engine( + "Denklem DOCX dönüşümü tamamlanamadı: girdi metin/denklem içermiyor olabilir." + .to_string(), + )) + } +} + +/// Markdown + LaTeX (`$...$`, `$$...$$`, `\(...\)`, `\[...\]`) içeriğini doğrudan saf Rust'ta +/// geçerli Word OMML (``, ``) içeren `.docx` dosyasına dönüştürür. +pub fn convert_markdown_to_omml_docx(markdown: &str, output_path: &Path) -> AppResult<()> { + let cleaned = markdown.trim_start_matches('\u{FEFF}').replace("\r\n", "\n"); + let lines: Vec<&str> = cleaned.split('\n').collect(); + let mut body = String::new(); + let mut i = 0usize; + + while i < lines.len() { + let trimmed = lines[i].trim(); + if trimmed.is_empty() { + i += 1; + continue; + } + + // 1) Fenced kod bloğu (```) + if trimmed.starts_with("```") { + i += 1; + let mut code_lines = Vec::new(); + while i < lines.len() && !lines[i].trim_start().starts_with("```") { + code_lines.push(lines[i]); + i += 1; + } + if i < lines.len() { + i += 1; + } + for cl in code_lines { + body.push_str(&format!( + "{}", + escape_xml(cl) + )); + } + continue; + } + + // 2) Yatay ayraç (--- / *** / ___) + if is_horizontal_rule(trimmed) { + body.push_str(""); + i += 1; + continue; + } + + // 3) Görüntülenen (display) denklem bloğu: $$ ... $$ veya \[ ... \] + if let Some((latex, next_idx)) = try_consume_display_math(&lines, i) { + body.push_str(&build_display_math_paragraph(&latex)); + i = next_idx; + continue; + } + + // 4) Başlık (# .. ######) + if let Some((level, title)) = parse_heading_line(trimmed) { + let style = match level { + 1 => "Heading1", + 2 => "Heading2", + _ => "Heading3", + }; + body.push_str(&format!( + "{}", + style, + render_inline_markdown(title) + )); + i += 1; + continue; + } + + // 5) Alıntı (> ...) + if let Some(quoted) = trimmed.strip_prefix('>') { + body.push_str(&format!( + "{}", + render_inline_markdown(quoted.trim()) + )); + i += 1; + continue; + } + + // 6) Markdown tablo (| a | b |) + if trimmed.starts_with('|') && i + 1 < lines.len() && is_table_separator(lines[i + 1].trim()) + { + let mut tbl_lines = vec![trimmed]; + i += 2; + while i < lines.len() && lines[i].trim().starts_with('|') { + tbl_lines.push(lines[i].trim()); + i += 1; + } + body.push_str(&render_markdown_table(&tbl_lines)); + continue; + } + + // 7) Liste öğeleri (- / * / • / 1.) + if let Some((marker, item_text)) = parse_list_item(trimmed) { + let mut full = item_text.to_string(); + i += 1; + while i < lines.len() { + let next_tr = lines[i].trim(); + if next_tr.is_empty() + || next_tr.starts_with('#') + || next_tr.starts_with("$$") + || next_tr.starts_with("\\[") + || next_tr.starts_with("```") + || parse_list_item(next_tr).is_some() + { + break; + } + full.push(' '); + full.push_str(next_tr); + i += 1; + } + body.push_str(&format!( + "{} {}", + escape_xml(&marker), + render_inline_markdown(full.trim()) + )); + continue; + } + + // 8) Standart paragraf + let mut para_lines = vec![trimmed]; + i += 1; + while i < lines.len() { + let next_tr = lines[i].trim(); + if next_tr.is_empty() + || next_tr.starts_with('#') + || next_tr.starts_with("$$") + || next_tr.starts_with("\\[") + || next_tr.starts_with("```") + || next_tr.starts_with('>') + || is_horizontal_rule(next_tr) + || parse_list_item(next_tr).is_some() + || (next_tr.starts_with('|') + && i + 1 < lines.len() + && is_table_separator(lines[i + 1].trim())) + { + break; + } + para_lines.push(next_tr); + i += 1; + } + let joined = para_lines.join(" "); + body.push_str(&render_paragraph_with_embedded_display_math(&joined)); + } + + if body.is_empty() { + body.push_str(""); + } + + write_omml_docx_package(output_path, &body) +} + +fn try_consume_display_math(lines: &[&str], start: usize) -> Option<(String, usize)> { + let trimmed = lines[start].trim(); + if let Some(after_open) = trimmed.strip_prefix("$$") { + if let Some(end_pos) = after_open.rfind("$$") { + // Tek satırda: $$ ... $$ + let content = after_open[..end_pos].trim(); + if !content.is_empty() { + return Some((content.to_string(), start + 1)); + } + } + let mut buf = Vec::new(); + if !after_open.trim().is_empty() { + buf.push(after_open.trim().to_string()); + } + let mut idx = start + 1; + while idx < lines.len() { + let t = lines[idx].trim(); + if let Some(before_close) = t.strip_suffix("$$") { + if !before_close.trim().is_empty() { + buf.push(before_close.trim().to_string()); + } + return Some((buf.join("\n"), idx + 1)); + } + if t == "$$" { + return Some((buf.join("\n"), idx + 1)); + } + buf.push(lines[idx].to_string()); + idx += 1; + } + if !buf.is_empty() { + return Some((buf.join("\n"), idx)); + } + } else if let Some(after_open) = trimmed.strip_prefix("\\[") { + if let Some(end_pos) = after_open.rfind("\\]") { + let content = after_open[..end_pos].trim(); + if !content.is_empty() { + return Some((content.to_string(), start + 1)); + } + } + let mut buf = Vec::new(); + if !after_open.trim().is_empty() { + buf.push(after_open.trim().to_string()); + } + let mut idx = start + 1; + while idx < lines.len() { + let t = lines[idx].trim(); + if let Some(before_close) = t.strip_suffix("\\]") { + if !before_close.trim().is_empty() { + buf.push(before_close.trim().to_string()); + } + return Some((buf.join("\n"), idx + 1)); + } + buf.push(lines[idx].to_string()); + idx += 1; + } + if !buf.is_empty() { + return Some((buf.join("\n"), idx)); + } + } + None +} + +fn build_display_math_paragraph(latex: &str) -> String { + match latex_to_omml(latex, true) { + Ok(omml) => format!("{}", omml), + Err(_) => format!( + "{}", + escape_xml(latex) + ), + } +} + +fn render_paragraph_with_embedded_display_math(text: &str) -> String { + if !text.contains("$$") && !text.contains("\\[") { + return format!("{}", render_inline_markdown(text)); + } + + let mut out = String::new(); + let mut rest = text; + while !rest.is_empty() { + let next_dollar = rest.find("$$").map(|i| (i, true)); + let next_bracket = rest.find("\\[").map(|i| (i, false)); + let chosen = match (next_dollar, next_bracket) { + (Some(a), Some(b)) => Some(if a.0 <= b.0 { a } else { b }), + (Some(a), None) => Some(a), + (None, Some(b)) => Some(b), + (None, None) => None, + }; + let Some((pos, is_dollar)) = chosen else { + if !rest.trim().is_empty() { + out.push_str(&format!("{}", render_inline_markdown(rest.trim()))); + } + break; + }; + + let before = rest[..pos].trim(); + if !before.is_empty() { + out.push_str(&format!("{}", render_inline_markdown(before))); + } + + let after_open = &rest[pos + 2..]; + let close_tok = if is_dollar { "$$" } else { "\\]" }; + if let Some(end_pos) = after_open.find(close_tok) { + let tex = after_open[..end_pos].trim(); + if !tex.is_empty() { + out.push_str(&build_display_math_paragraph(tex)); + } + rest = after_open[end_pos + 2..].trim_start(); + } else { + out.push_str(&format!( + "{}", + render_inline_markdown(rest[pos..].trim()) + )); + break; + } + } + + if out.is_empty() { + "".to_string() + } else { + out + } +} + +fn render_inline_markdown(text: &str) -> String { + let mut out = String::new(); + let bytes = text.as_bytes(); + let mut i = 0usize; + let mut plain_buf = String::new(); + + let flush_plain = |buf: &mut String, dest: &mut String| { + if !buf.is_empty() { + dest.push_str(&format!( + "{}", + escape_xml(buf) + )); + buf.clear(); + } + }; + + while i < bytes.len() { + // Kaçışlı karakter (\$, \*, \\) + if bytes[i] == b'\\' && i + 1 < bytes.len() { + let next = bytes[i + 1]; + if next == b'(' { + // \( ... \) satır içi LaTeX + if let Some(rel_end) = text[i + 2..].find("\\)") { + let latex = text[i + 2..i + 2 + rel_end].trim(); + flush_plain(&mut plain_buf, &mut out); + push_inline_omml_or_text(&mut out, latex); + i = i + 2 + rel_end + 2; + continue; + } + } + if matches!(next, b'$' | b'*' | b'_' | b'`' | b'\\') { + plain_buf.push(next as char); + i += 2; + continue; + } + } + + // Satır içi LaTeX ($...$) + if bytes[i] == b'$' && !text[i..].starts_with("$$") { + if let Some(end_rel) = find_closing_inline_dollar(&text[i + 1..]) { + let latex = text[i + 1..i + 1 + end_rel].trim(); + if !latex.is_empty() { + flush_plain(&mut plain_buf, &mut out); + push_inline_omml_or_text(&mut out, latex); + i = i + 1 + end_rel + 1; + continue; + } + } + } + + // Satır içi kod (`...`) + if bytes[i] == b'`' { + if let Some(end_rel) = text[i + 1..].find('`') { + let code = &text[i + 1..i + 1 + end_rel]; + flush_plain(&mut plain_buf, &mut out); + out.push_str(&format!( + "{}", + escape_xml(code) + )); + i = i + 1 + end_rel + 1; + continue; + } + } + + // Kalın (**...**) + if text[i..].starts_with("**") { + if let Some(end_rel) = text[i + 2..].find("**") { + if end_rel > 0 { + let bold_text = &text[i + 2..i + 2 + end_rel]; + flush_plain(&mut plain_buf, &mut out); + out.push_str(&format!( + "{}", + escape_xml(bold_text) + )); + i = i + 2 + end_rel + 2; + continue; + } + } + } + + // İtalik (*...*) + if bytes[i] == b'*' && !text[i..].starts_with("**") { + if let Some(end_rel) = text[i + 1..].find('*') { + let candidate = &text[i + 1..i + 1 + end_rel]; + if !candidate.is_empty() + && !candidate.starts_with(' ') + && !candidate.ends_with(' ') + { + flush_plain(&mut plain_buf, &mut out); + out.push_str(&format!( + "{}", + escape_xml(candidate) + )); + i = i + 1 + end_rel + 1; + continue; + } + } + } + + if let Some(ch) = text[i..].chars().next() { + plain_buf.push(ch); + i += ch.len_utf8(); + } else { + break; + } + } + + flush_plain(&mut plain_buf, &mut out); + if out.is_empty() { + "".to_string() + } else { + out + } +} + +fn find_closing_inline_dollar(after_open: &str) -> Option { + let bytes = after_open.as_bytes(); + let mut i = 0usize; + while i < bytes.len() { + if bytes[i] == b'\\' { + i += 2; + continue; + } + if bytes[i] == b'$' { + if i + 1 < bytes.len() && bytes[i + 1] == b'$' { + return None; + } + let inner = &after_open[..i]; + // Para birimi ($100 ve $200) yanlış eşleşmesini önle + let padded = inner.starts_with(' ') && inner.ends_with(' '); + let looks_like_math = inner.contains('\\') + || inner.contains('^') + || inner.contains('_') + || inner.contains('{') + || inner.contains('=') + || inner.contains('+') + || inner.contains('/'); + if !padded || looks_like_math { + return Some(i); + } + return None; + } + i += 1; + } + None +} + +fn push_inline_omml_or_text(out: &mut String, latex: &str) { + match latex_to_omml(latex, false) { + Ok(omml) => out.push_str(&omml), + Err(_) => out.push_str(&format!( + "{}", + escape_xml(latex) + )), + } +} + +fn is_horizontal_rule(trimmed: &str) -> bool { + let stripped: String = trimmed.chars().filter(|c| !c.is_whitespace()).collect(); + stripped.len() >= 3 + && (stripped.chars().all(|c| c == '-') + || stripped.chars().all(|c| c == '*') + || stripped.chars().all(|c| c == '_')) +} + +fn parse_heading_line(trimmed: &str) -> Option<(usize, &str)> { + let hashes = trimmed.bytes().take_while(|&b| b == b'#').count(); + if (1..=6).contains(&hashes) { + let rest = &trimmed[hashes..]; + if rest.starts_with(' ') || rest.starts_with('\t') { + return Some((hashes, rest.trim())); + } + } + None +} + +fn parse_list_item(trimmed: &str) -> Option<(String, &str)> { + for prefix in ["- ", "* ", "+ ", "• "] { + if let Some(rest) = trimmed.strip_prefix(prefix) { + return Some(("•".to_string(), rest.trim())); + } + } + let digits = trimmed.bytes().take_while(|b| b.is_ascii_digit()).count(); + if digits > 0 && digits <= 4 { + let after = &trimmed[digits..]; + if let Some(rest) = after.strip_prefix(". ").or_else(|| after.strip_prefix(") ")) { + return Some((format!("{}.", &trimmed[..digits]), rest.trim())); + } + } + None +} + +fn is_table_separator(trimmed: &str) -> bool { + trimmed.starts_with('|') + && trimmed.contains('-') + && trimmed + .chars() + .all(|c| matches!(c, '|' | '-' | ':' | ' ' | '\t')) +} + +fn render_markdown_table(rows: &[&str]) -> String { + let mut xml = String::from( + "", + ); + for (row_idx, row_line) in rows.iter().enumerate() { + xml.push_str(""); + let trimmed = row_line.trim().trim_matches('|'); + for cell in trimmed.split('|') { + let shade = if row_idx == 0 { + "" + } else { + "" + }; + let cell_runs = render_inline_markdown(cell.trim()); + xml.push_str(&format!( + "{}{}", + shade, cell_runs + )); + } + xml.push_str(""); + } + xml.push_str(""); + xml +} + +fn write_omml_docx_package(output_path: &Path, body: &str) -> AppResult<()> { + if let Some(parent) = output_path.parent() { + std::fs::create_dir_all(parent)?; + } + + let document_xml = format!( + "\n\ + \ + {body}", + w = WORD_NS, + m = MATH_NS, + r = REL_NS, + body = body + ); + + let content_types = r#" +"#; + + let rels = r#" +"#; + + let document_rels = r#" +"#; + + let styles_xml = format!( + "\n\ + \ + \ + \ + \ + \ + \ + \ + ", + w = WORD_NS + ); + + let settings_xml = format!( + "\n\ + \ + \ + ", + w = WORD_NS, + m = MATH_NS + ); + + let file = File::create(output_path)?; + let mut zip = ZipWriter::new(BufWriter::new(file)); + let options = + SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + + for (name, content) in [ + ("[Content_Types].xml", content_types), + ("_rels/.rels", rels), + ("word/_rels/document.xml.rels", document_rels), + ("word/styles.xml", styles_xml.as_str()), + ("word/settings.xml", settings_xml.as_str()), + ("word/document.xml", document_xml.as_str()), + ] { + zip.start_file(name, options) + .map_err(|e| AppError::Generic(format!("DOCX paketleme hatası ({}): {}", name, e)))?; + zip.write_all(content.as_bytes())?; + } + + zip.finish() + .map_err(|e| AppError::Generic(format!("DOCX arşiv kapatılamadı: {}", e)))?; + Ok(()) +} diff --git a/src-tauri/src/services/media_engine.rs b/src-tauri/src/services/media_engine.rs new file mode 100644 index 0000000..f182743 --- /dev/null +++ b/src-tauri/src/services/media_engine.rs @@ -0,0 +1,313 @@ +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, OnceLock}; + +#[cfg(windows)] +use std::os::windows::process::CommandExt; + +use crate::services::progress::ProgressEmitter; + +use crate::error::{AppError, AppResult}; +use crate::models::{ConversionOptions, ProgressEvent}; +use crate::services::engine_resolver::EngineResolver; +use crate::services::image_engine::ImageEngine; + +static HARDWARE_H264_ENCODER: OnceLock> = OnceLock::new(); + +fn detect_hardware_h264_encoder(ffmpeg_path: &Path) -> Option<&'static str> { + *HARDWARE_H264_ENCODER.get_or_init(|| { + for candidate in ["h264_nvenc", "h264_qsv", "h264_amf"] { + let mut cmd = Command::new(ffmpeg_path); + #[cfg(windows)] + cmd.creation_flags(0x08000000); + cmd.args([ + "-hide_banner", + "-f", + "lavfi", + "-i", + "color=c=black:s=64x64:d=0.1", + "-c:v", + candidate, + "-f", + "null", + "-", + ]); + cmd.stdin(Stdio::null()); + cmd.stdout(Stdio::null()); + cmd.stderr(Stdio::null()); + if let Ok(status) = cmd.status() { + if status.success() { + return Some(candidate); + } + } + } + None + }) +} + +pub struct MediaEngine; + +impl MediaEngine { + pub fn convert_media( + emitter: &ProgressEmitter, + input_path: &str, + target_format: &str, + output_dir: &Path, + options: &ConversionOptions, + task_id: &str, + cancel_flag: &Arc, + ) -> AppResult { + let ffmpeg = EngineResolver::resolve_ffmpeg(None).ok_or_else(|| { + AppError::Engine( + "Video/Ses dönüşümü için FFmpeg bulunamadı. Lütfen Ayarlar'dan FFmpeg yolunu belirtin." + .to_string(), + ) + })?; + + let input_p = Path::new(input_path); + let base_name = input_p + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("media"); + + let ext = target_format.to_lowercase().trim_start_matches('.').to_string(); + let target_ext = match ext.as_str() { + "mp4" => "mp4", + "mkv" => "mkv", + "webm" => "webm", + "mp3" => "mp3", + "wav" => "wav", + "aac" => "m4a", + "flac" => "flac", + "ogg" => "ogg", + "gif" => "gif", + "compress_video" => "mp4", + "compress_audio" => "mp3", + _ => &ext, + }; + + let mut output_path = output_dir.join(format!("{}.{}", base_name, target_ext)); + output_path = ImageEngine::get_unique_path(&output_path, options.overwrite_existing); + + let mut cmd = Command::new(&ffmpeg); + #[cfg(windows)] + cmd.creation_flags(0x08000000); + + cmd.arg("-y"); + + // Start time (Trim) + if let Some(ref st) = options.start_time { + if !st.trim().is_empty() { + cmd.arg("-ss").arg(st.trim()); + } + } + + // End time (Trim) + if let Some(ref et) = options.end_time { + if !et.trim().is_empty() { + cmd.arg("-to").arg(et.trim()); + } + } + + cmd.arg("-i").arg(input_path); + + // Mute audio + if options.mute_audio { + cmd.arg("-an"); + } + if options.strip_metadata { + cmd.arg("-map_metadata").arg("-1"); + } + + // Target specific codecs & quality + match ext.as_str() { + "mp4" | "mkv" | "compress_video" => { + cmd.arg("-map").arg("0:v:0"); + if !options.mute_audio { + cmd.arg("-map").arg("0:a?"); + } + + let hw_encoder = detect_hardware_h264_encoder(Path::new(&ffmpeg)); + if let Some(enc) = hw_encoder { + cmd.arg("-c:v").arg(enc); + match enc { + "h264_nvenc" => { + let preset = match ext.as_str() { + "compress_video" => "p4", + _ => "p6", + }; + let qp = match ext.as_str() { + "compress_video" => "28", + _ => &options.video_crf.unwrap_or(23).to_string(), + }; + cmd.arg("-preset").arg(preset); + cmd.arg("-cq").arg(qp); + } + "h264_qsv" => { + let qp = match ext.as_str() { + "compress_video" => "28", + _ => &options.video_crf.unwrap_or(23).to_string(), + }; + cmd.arg("-global_quality").arg(qp); + } + "h264_amf" => { + let qp = match ext.as_str() { + "compress_video" => "28", + _ => &options.video_crf.unwrap_or(23).to_string(), + }; + cmd.arg("-rc").arg("cqp"); + cmd.arg("-qp_i").arg(qp); + cmd.arg("-qp_p").arg(qp); + } + _ => {} + } + } else { + cmd.arg("-c:v").arg("libx264"); + let (crf, preset) = match ext.as_str() { + "compress_video" => (28, "fast"), + _ => ( + options.video_crf.unwrap_or(23), + options.video_preset.as_deref().unwrap_or("medium"), + ), + }; + cmd.arg("-crf").arg(crf.to_string()); + cmd.arg("-preset").arg(preset); + } + + if !options.mute_audio { + cmd.arg("-c:a").arg("aac"); + let br = options.audio_bitrate_kbps.unwrap_or(192); + cmd.arg("-b:a").arg(format!("{}k", br)); + } + } + "webm" => { + cmd.arg("-map").arg("0:v:0"); + if !options.mute_audio { + cmd.arg("-map").arg("0:a?"); + } + cmd.arg("-c:v").arg("libvpx-vp9"); + cmd.arg("-crf").arg("30"); + cmd.arg("-b:v").arg("0"); + if !options.mute_audio { + cmd.arg("-c:a").arg("libopus"); + } + } + "mp3" | "compress_audio" => { + cmd.arg("-vn"); + cmd.arg("-c:a").arg("libmp3lame"); + let br = if ext == "compress_audio" { + 96 + } else { + options.audio_bitrate_kbps.unwrap_or(192) + }; + cmd.arg("-b:a").arg(format!("{}k", br)); + } + "aac" => { + cmd.arg("-vn"); + cmd.arg("-c:a").arg("aac"); + let br = options.audio_bitrate_kbps.unwrap_or(192); + cmd.arg("-b:a").arg(format!("{}k", br)); + } + "wav" => { + cmd.arg("-vn"); + cmd.arg("-c:a").arg("pcm_s16le"); + } + "flac" => { + cmd.arg("-vn"); + cmd.arg("-c:a").arg("flac"); + } + "ogg" => { + cmd.arg("-vn"); + cmd.arg("-c:a").arg("libvorbis"); + } + "gif" => { + cmd.arg("-vf").arg("fps=15,scale=480:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse"); + } + _ => {} + } + + cmd.arg(&output_path); + cmd.stdout(Stdio::null()); + cmd.stderr(Stdio::piped()); + + let mut child = cmd.spawn().map_err(|e| { + AppError::Engine(format!("FFmpeg başlatılamadı: {}", e)) + })?; + + let mut total_duration_secs: Option = None; + + if let Some(stderr) = child.stderr.take() { + let reader = BufReader::new(stderr); + for line in reader.lines().map_while(Result::ok) { + // Check cancellation inside loop + if cancel_flag.load(Ordering::Relaxed) { + let _ = child.kill(); + let _ = child.wait(); + let _ = std::fs::remove_file(&output_path); + return Err(AppError::Cancelled); + } + + // Parse total duration: Duration: 00:01:23.45 + if total_duration_secs.is_none() && line.contains("Duration:") { + if let Some(dur_str) = line.split("Duration:").nth(1) { + if let Some(dur_val) = dur_str.split(',').next() { + total_duration_secs = Self::parse_time_str(dur_val.trim()); + } + } + } + + // Parse current progress: time=00:00:15.20 + if let Some(total) = total_duration_secs { + if line.contains("time=") { + if let Some(time_part) = line.split("time=").nth(1) { + if let Some(t_str) = time_part.split_whitespace().next() { + if let Some(cur_secs) = Self::parse_time_str(t_str) { + let percent = (cur_secs / total * 100.0).clamp(1.0, 99.0); + emitter.emit(ProgressEvent { + task_id: task_id.to_string(), + percent, + message: format!("FFmpeg işleniyor (%{:.0})", percent), + current_file: Some(base_name.to_string()), + }); + } + } + } + } + } + } + } + + if cancel_flag.load(Ordering::Relaxed) { + let _ = child.kill(); + let _ = child.wait(); + let _ = std::fs::remove_file(&output_path); + return Err(AppError::Cancelled); + } + + let status = child.wait()?; + if status.success() && output_path.exists() { + Ok(output_path) + } else { + let _ = child.kill(); + let _ = std::fs::remove_file(&output_path); + Err(AppError::Engine(format!( + "FFmpeg dönüşümü başarısız oldu: {}", + input_p.file_name().and_then(|n| n.to_str()).unwrap_or("") + ))) + } + } + + fn parse_time_str(t: &str) -> Option { + let parts: Vec<&str> = t.split(':').collect(); + if parts.len() == 3 { + let hours = parts[0].parse::().ok()?; + let mins = parts[1].parse::().ok()?; + let secs = parts[2].parse::().ok()?; + Some(hours * 3600.0 + mins * 60.0 + secs) + } else { + None + } + } +} diff --git a/src-tauri/src/services/mod.rs b/src-tauri/src/services/mod.rs new file mode 100644 index 0000000..144118a --- /dev/null +++ b/src-tauri/src/services/mod.rs @@ -0,0 +1,45 @@ +pub mod archive_engine; +pub mod dispatcher; +pub mod document_engine; +pub mod docx_writer; +pub mod engine_resolver; +pub mod engine_updater; +pub mod autostart; +pub mod shell_menu; +pub mod gdi_render; +pub mod image_engine; +pub mod math_engine; +pub mod omml; +pub use omml as omml_engine; +pub mod html_pdf; +pub mod office_engine; +pub mod office_zip; +pub mod office_readers; +pub mod office_docx; +pub mod office_model; +pub mod pdf_images; +pub mod pdf_writer; +pub mod media_engine; +pub mod ocr_engine; +pub mod pdf_engine; +pub mod pdf_parser; +pub mod pdf_text; +pub use pdf_text as pdf_math_reader; +pub mod pdf_tools; +pub mod progress; +pub mod qr_engine; + +pub use archive_engine::ArchiveEngine; +pub use dispatcher::ConversionDispatcher; +pub use document_engine::DocumentEngine; +pub use docx_writer::DocxWriter; +pub use engine_resolver::EngineResolver; +pub use image_engine::ImageEngine; +pub use math_engine::MathEngine; +pub use office_engine::OfficeEngine; +pub use media_engine::MediaEngine; +pub use ocr_engine::OcrEngine; +pub use pdf_engine::PdfEngine; +pub use pdf_tools::PdfTools; +pub use progress::ProgressEmitter; +pub use qr_engine::QrEngine; diff --git a/src-tauri/src/services/ocr_engine.rs b/src-tauri/src/services/ocr_engine.rs new file mode 100644 index 0000000..56e6d6d --- /dev/null +++ b/src-tauri/src/services/ocr_engine.rs @@ -0,0 +1,199 @@ +use std::path::Path; +use std::process::Command; + +#[cfg(windows)] +use std::os::windows::process::CommandExt; + +use crate::error::{AppError, AppResult}; +use crate::services::engine_resolver::EngineResolver; + +/// Çevrimdışı OCR: önce Tesseract CLI, yoksa Windows 10/11 yerleşik WinRT OCR motoru. +pub struct OcrEngine; + +impl OcrEngine { + pub fn recognize_image(image_path: &str) -> AppResult { + if !Path::new(image_path).exists() { + return Err(AppError::NotFound(image_path.to_string())); + } + + let prepared = Self::prepare_image(image_path)?; + + if let Some(text) = Self::run_tesseract(&prepared) { + let _ = std::fs::remove_file(&prepared); + return Ok(text); + } + + #[cfg(windows)] + { + let outcome = match Self::run_windows_ocr(&prepared) { + Ok(text) => Ok(text), + Err(reason) => Err(AppError::Engine(format!( + "OCR motoru çalıştırılamadı (Tesseract yok, Windows OCR başarısız: {}). \ + Windows Ayarlar > Zaman ve Dil > Dil'den OCR dil paketini ekleyin.", + reason + ))), + }; + let _ = std::fs::remove_file(&prepared); + outcome + } + + #[cfg(not(windows))] + { + let _ = std::fs::remove_file(&prepared); + Err(AppError::Engine( + "OCR motoru bulunamadı. Lütfen Tesseract kurun.".to_string(), + )) + } + } + + /// OCR doğruluğu için görseli opak beyaz zeminli PNG'ye hazırlar, küçük görselleri büyütür. + fn prepare_image(image_path: &str) -> AppResult { + let img = image::open(image_path)?; + let mut rgba = img.to_rgba8(); + for px in rgba.pixels_mut() { + let a = px[3] as u32; + if a < 255 { + for c in 0..3 { + px[c] = ((px[c] as u32 * a + 255 * (255 - a)) / 255) as u8; + } + px[3] = 255; + } + } + let mut prepared = image::DynamicImage::ImageRgba8(rgba); + + let (w, h) = (prepared.width(), prepared.height()); + if w < 600 && h < 600 { + prepared = prepared.resize_exact(w * 2, h * 2, image::imageops::FilterType::Lanczos3); + } + + let path = std::env::temp_dir().join(format!("ld_ocr_{}.png", uuid::Uuid::new_v4())); + prepared.save_with_format(&path, image::ImageFormat::Png)?; + Ok(path.to_string_lossy().to_string()) + } + + fn run_tesseract(png_path: &str) -> Option { + let tess = EngineResolver::resolve_tesseract()?; + + for lang in [Some("tur+eng"), None] { + let mut cmd = Command::new(&tess); + #[cfg(windows)] + cmd.creation_flags(0x08000000); + cmd.arg(png_path).arg("stdout"); + if let Some(l) = lang { + cmd.arg("-l").arg(l); + } + cmd.arg("--oem").arg("1"); + if let Ok(out) = cmd.output() { + if out.status.success() { + let text = String::from_utf8_lossy(&out.stdout).trim().to_string(); + if !text.is_empty() { + return Some(text); + } + } + } + } + None + } + + #[cfg(windows)] + fn run_windows_ocr(png_path: &str) -> Result { + let escaped = png_path.replace('\'', "''"); + let script = format!( + r#" +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 +Add-Type -AssemblyName System.Runtime.WindowsRuntime +$null = [Windows.Storage.StorageFile, Windows.Storage, ContentType = WindowsRuntime] +$null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime] +$null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime] +$null = [Windows.Globalization.Language, Windows.Foundation, ContentType = WindowsRuntime] + +$asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object {{ $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' }})[0] +function Await($WinRtTask, $ResultType) {{ + $asTask = $asTaskGeneric.MakeGenericMethod($ResultType) + $netTask = $asTask.Invoke($null, @($WinRtTask)) + $netTask.Wait(-1) | Out-Null + $netTask.Result +}} + +$file = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync('{path}')) ([Windows.Storage.StorageFile]) +$stream = Await ($file.OpenAsync([Windows.Storage.FileAccessMode]::Read)) ([Windows.Storage.Streams.IRandomAccessStream]) +$decoder = Await ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) ([Windows.Graphics.Imaging.BitmapDecoder]) +$bitmap = Await ($decoder.GetSoftwareBitmapAsync()) ([Windows.Graphics.Imaging.SoftwareBitmap]) + +$engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages() +if ($null -eq $engine) {{ + $lang = New-Object Windows.Globalization.Language('tr-TR') + if ([Windows.Media.Ocr.OcrEngine]::IsLanguageSupported($lang)) {{ $engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromLanguage($lang) }} +}} +if ($null -eq $engine) {{ + $langEn = New-Object Windows.Globalization.Language('en-US') + $engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromLanguage($langEn) +}} +if ($null -ne $engine) {{ + $result = Await ($engine.RecognizeAsync($bitmap)) ([Windows.Media.Ocr.OcrResult]) + foreach ($line in $result.Lines) {{ Write-Output $line.Text }} +}} +$stream.Dispose() +"#, + path = escaped + ); + + let ps = std::env::var("SystemRoot") + .map(|r| format!("{}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", r)) + .unwrap_or_else(|_| "powershell.exe".to_string()); + if !Path::new(&ps).exists() { + return Err("powershell.exe bulunamadı".to_string()); + } + + let encoded = base64_utf16le(&script); + let mut cmd = Command::new(&ps); + cmd.creation_flags(0x08000000); + cmd.arg("-NoProfile") + .arg("-NonInteractive") + .arg("-ExecutionPolicy") + .arg("Bypass") + .arg("-EncodedCommand") + .arg(encoded); + + let out = cmd + .output() + .map_err(|e| format!("PowerShell çalıştırılamadı: {}", e))?; + + let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string(); + if !out.status.success() { + let stderr = String::from_utf8_lossy(&out.stderr) + .replace("_x000D_", " ") + .replace(['\r', '\n'], " "); + let detail: String = stderr.chars().take(400).collect(); + return Err(format!( + "PowerShell çıkış kodu {}: {}", + out.status.code().unwrap_or(-1), + detail.trim() + )); + } + + if stdout.is_empty() { + Err("OCR metin üretmedi (dil paketi eksik olabilir)".to_string()) + } else { + Ok(stdout) + } + } +} + +#[cfg(windows)] +fn base64_utf16le(text: &str) -> String { + const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let bytes: Vec = text.encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let b0 = chunk[0] as u32; + let b1 = *chunk.get(1).unwrap_or(&0) as u32; + let b2 = *chunk.get(2).unwrap_or(&0) as u32; + let n = (b0 << 16) | (b1 << 8) | b2; + out.push(TABLE[(n >> 18) as usize & 63] as char); + out.push(TABLE[(n >> 12) as usize & 63] as char); + out.push(if chunk.len() > 1 { TABLE[(n >> 6) as usize & 63] as char } else { '=' }); + out.push(if chunk.len() > 2 { TABLE[n as usize & 63] as char } else { '=' }); + } + out +} diff --git a/src-tauri/src/services/office_docx.rs b/src-tauri/src/services/office_docx.rs new file mode 100644 index 0000000..8ffd512 --- /dev/null +++ b/src-tauri/src/services/office_docx.rs @@ -0,0 +1,614 @@ +//! DOCX okuyucu: paragraf, liste, tablo (birleşik hücre), görsel, köprü, üst/alt bilgi. + +use std::collections::HashMap; +use std::path::Path; + +use roxmltree::Node; + +use crate::error::{AppError, AppResult}; +use crate::services::office_model::*; +use crate::services::office_zip::Package; + +const EMU_PER_PT: f32 = 12700.0; + +struct Context { + rels: HashMap, // id -> (type, target) + numbering: HashMap<(String, u8), ListKind>, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum VMerge { + None, + Restart, + Continue, +} + +struct RawCell { + col: usize, + #[allow(dead_code)] + span: usize, + vmerge: VMerge, + cell: Cell, +} + +pub fn read_docx(path: &Path) -> AppResult { + let mut package = Package::open(path)?; + let xml = package + .read_string("word/document.xml") + .ok_or_else(|| AppError::NotFound("word/document.xml yok".to_string()))?; + + let rels = parse_rels(&mut package, "word/_rels/document.xml.rels"); + let numbering = parse_numbering(&mut package); + let context = Context { rels, numbering }; + + let mut blocks = Vec::new(); + if let Ok(document) = roxmltree::Document::parse(&xml) { + if let Some(body) = document + .descendants() + .find(|node| node.is_element() && node.tag_name().name() == "body") + { + parse_blocks(body, &context, &mut package, &mut blocks); + } + } + + // Görsel baytlarını paketten oku (push_image yalnızca hedef yolu saklar). + for block in &mut blocks { + if let Block::Image(image) = block { + let target = String::from_utf8_lossy(&image.data).to_string(); + let cleaned = target.trim_start_matches('/').trim_start_matches("./"); + let candidates = [ + format!("word/{}", cleaned), + cleaned.to_string(), + format!("word/media/{}", cleaned.rsplit('/').next().unwrap_or(cleaned)), + ]; + let mut found = None; + for candidate in candidates { + if let Some(bytes) = package.read(&candidate) { + found = Some(bytes); + break; + } + } + if found.is_none() { + let file_name = cleaned.rsplit('/').next().unwrap_or(cleaned); + for name in package.names() { + if name.ends_with(file_name) { + if let Some(bytes) = package.read(&name) { + found = Some(bytes); + break; + } + } + } + } + match found { + Some(bytes) => { + image.format = ImageFormat::from_bytes(&bytes); + image.data = bytes; + } + None => { + crate::logging::warn(&format!("DOCX görseli okunamadı: {}", target)); + } + } + } + } + + let mut result = Document { + blocks, + header: Vec::new(), + footer: Vec::new(), + }; + + for (id, (kind, target)) in &context.rels { + let _ = id; + if kind.ends_with("/header") || kind.ends_with("/footer") { + if let Some(part) = package.read_string(&format!("word/{}", target.trim_start_matches('/'))) { + let mut paragraphs = Vec::new(); + if let Ok(document) = roxmltree::Document::parse(&part) { + if let Some(root) = document.root_element().children().find(|node| node.is_element()) { + collect_paragraphs(root, &context, &mut paragraphs); + } + } + if kind.ends_with("/header") && result.header.is_empty() { + result.header = paragraphs; + } else if kind.ends_with("/footer") && result.footer.is_empty() { + result.footer = paragraphs; + } + } + } + } + + Ok(result) +} + +fn parse_rels(package: &mut Package, name: &str) -> HashMap { + let mut map = HashMap::new(); + let Some(xml) = package.read_string(name) else { + return map; + }; + let Ok(document) = roxmltree::Document::parse(&xml) else { + return map; + }; + for node in document.descendants().filter(|node| node.tag_name().name() == "Relationship") { + let id = attribute(&node, "Id").unwrap_or_default(); + let kind = attribute(&node, "Type").unwrap_or_default(); + let target = attribute(&node, "Target").unwrap_or_default(); + if !id.is_empty() && !target.is_empty() { + map.insert(id, (kind, target)); + } + } + map +} + +fn parse_numbering(package: &mut Package) -> HashMap<(String, u8), ListKind> { + let mut map = HashMap::new(); + let Some(xml) = package.read_string("word/numbering.xml") else { + return map; + }; + let Ok(document) = roxmltree::Document::parse(&xml) else { + return map; + }; + + // abstractNumId -> (ilvl -> numFmt) + let mut abstract_formats: HashMap> = HashMap::new(); + for node in document.descendants().filter(|node| node.tag_name().name() == "abstractNum") { + let id = attribute(&node, "abstractNumId").unwrap_or_default(); + let mut levels = HashMap::new(); + for level in node.children().filter(|child| child.tag_name().name() == "lvl") { + let ilvl = attribute(&level, "ilvl") + .and_then(|value| value.parse::().ok()) + .unwrap_or(0); + let format = level + .children() + .find(|child| child.tag_name().name() == "numFmt") + .and_then(|child| attribute(&child, "val")) + .unwrap_or_default(); + levels.insert(ilvl, format); + } + abstract_formats.insert(id, levels); + } + + for node in document.descendants().filter(|node| node.tag_name().name() == "num") { + let num_id = attribute(&node, "numId").unwrap_or_default(); + let abstract_id = node + .children() + .find(|child| child.tag_name().name() == "abstractNumId") + .and_then(|child| attribute(&child, "val")) + .unwrap_or_default(); + if let Some(levels) = abstract_formats.get(&abstract_id) { + for (level, format) in levels { + let kind = if format.eq_ignore_ascii_case("bullet") { + ListKind::Bullet + } else { + ListKind::Numbered + }; + map.insert((num_id.clone(), *level), kind); + } + } + } + map +} + +fn attribute(node: &Node, name: &str) -> Option { + node.attributes() + .find(|attribute| attribute.name() == name) + .map(|attribute| attribute.value().to_string()) +} + +fn child<'a, 'input>(node: Node<'a, 'input>, name: &str) -> Option> { + node.children() + .find(|child| child.is_element() && child.tag_name().name() == name) +} + +fn parse_blocks( + parent: Node, + context: &Context, + package: &mut Package, + blocks: &mut Vec, +) { + for node in parent.children().filter(|child| child.is_element()) { + match node.tag_name().name() { + "p" => { + let (paragraph, images) = parse_paragraph(node, context); + if !paragraph.is_empty() || !images.is_empty() { + if !paragraph.is_empty() { + blocks.push(Block::Paragraph(paragraph)); + } + blocks.extend(images.into_iter().map(Block::Image)); + } + } + "tbl" => blocks.push(Block::Table(parse_table(node, context, package))), + _ => {} + } + } +} + +fn collect_paragraphs(parent: Node, context: &Context, paragraphs: &mut Vec) { + for node in parent.children().filter(|child| child.is_element()) { + if node.tag_name().name() == "p" { + let (paragraph, _) = parse_paragraph(node, context); + if !paragraph.is_empty() { + paragraphs.push(paragraph); + } + } + } +} + +fn parse_paragraph(node: Node, context: &Context) -> (Paragraph, Vec) { + let mut paragraph = Paragraph::default(); + let mut images = Vec::new(); + + if let Some(properties) = child(node, "pPr") { + if let Some(style) = child(properties, "pStyle").and_then(|item| attribute(&item, "val")) { + paragraph.style.heading = heading_level(&style); + // Word'ün hazır liste stilleri numaralandırmayı stil üzerinden tanımlar. + let lower = style.to_ascii_lowercase(); + if paragraph.style.heading.is_none() { + if lower.contains("list number") || lower.contains("listnumber") || lower == "listparagraph" { + paragraph.style.list = Some(ListKind::Numbered); + } else if lower.contains("list bullet") || lower.contains("listbullet") { + paragraph.style.list = Some(ListKind::Bullet); + } + } + } + if let Some(outline) = child(properties, "outlineLvl").and_then(|item| attribute(&item, "val")) { + if paragraph.style.heading.is_none() { + if let Ok(level) = outline.parse::() { + paragraph.style.heading = Some(level.saturating_add(1)); + } + } + } + if let Some(align) = child(properties, "jc").and_then(|item| attribute(&item, "val")) { + paragraph.style.align = parse_align(&align); + } + if let Some(spacing) = child(properties, "spacing") { + if let Some(before) = attribute(&spacing, "before").and_then(|value| value.parse::().ok()) { + paragraph.style.space_before_pt = before / 20.0; + } + if let Some(after) = attribute(&spacing, "after").and_then(|value| value.parse::().ok()) { + paragraph.style.space_after_pt = after / 20.0; + } + } + if let Some(numbering) = child(properties, "numPr") { + let level = child(numbering, "ilvl") + .and_then(|item| attribute(&item, "val")) + .and_then(|value| value.parse::().ok()) + .unwrap_or(0); + let num_id = child(numbering, "numId") + .and_then(|item| attribute(&item, "val")) + .unwrap_or_default(); + paragraph.style.level = level; + paragraph.style.list = context + .numbering + .get(&(num_id, level)) + .copied() + .or(Some(ListKind::Bullet)); + } + } + + collect_runs(node, context, None, &mut paragraph.runs, &mut images); + (paragraph, images) +} + +fn heading_level(style: &str) -> Option { + let lower = style.to_ascii_lowercase(); + if lower.contains("title") { + return Some(1); + } + if lower == "subtitle" { + return Some(2); + } + lower + .strip_prefix("heading") + .and_then(|rest| rest.trim().parse::().ok()) + .map(|level| level.clamp(1, 6)) +} + +fn parse_align(value: &str) -> Align { + match value { + "center" => Align::Center, + "right" | "end" => Align::Right, + "both" | "justify" => Align::Justify, + _ => Align::Left, + } +} + +fn collect_runs( + parent: Node, + context: &Context, + link: Option, + runs: &mut Vec, + images: &mut Vec, +) { + for node in parent.children().filter(|child| child.is_element()) { + match node.tag_name().name() { + "r" => { + let mut run = Run::plain(String::new()); + if let Some(properties) = child(node, "rPr") { + parse_run_properties(properties, &mut run); + } + run.link = link.clone(); + let mut text = String::new(); + collect_run_text(node, &mut text); + if !text.is_empty() { + run.text = text; + runs.push(run); + } + collect_drawing_images(node, &context.rels, images); + } + "hyperlink" => { + let target = attribute(&node, "id") + .and_then(|id| context.rels.get(&id).map(|(_, target)| target.clone())) + .or_else(|| attribute(&node, "anchor")); + collect_runs(node, context, target.or(link.clone()), runs, images); + } + "ins" | "smartTag" | "sdt" | "sdtContent" | "fldSimple" => { + collect_runs(node, context, link.clone(), runs, images); + } + _ => {} + } + } +} + +fn collect_run_text(parent: Node, text: &mut String) { + for node in parent.children() { + if node.is_text() { + text.push_str(node.text().unwrap_or_default()); + continue; + } + if !node.is_element() { + continue; + } + match node.tag_name().name() { + "t" => text.push_str(node.text().unwrap_or_default()), + "tab" => text.push('\t'), + "br" | "cr" => text.push('\n'), + _ => {} + } + } +} + +fn flag(properties: Node, name: &str) -> bool { + properties + .children() + .filter(|child| child.tag_name().name() == name) + .any(|child| { + attribute(&child, "val") + .map(|value| value != "0" && value != "false") + .unwrap_or(true) + }) +} + +fn parse_run_properties(properties: Node, run: &mut Run) { + for property in properties.children().filter(|child| child.is_element()) { + match property.tag_name().name() { + "b" => run.bold = flag(properties, "b"), + "i" => run.italic = flag(properties, "i"), + "u" => { + run.underline = attribute(&property, "val") + .map(|value| value != "none") + .unwrap_or(true) + } + "strike" | "dstrike" => run.strike = flag(properties, "strike") || flag(properties, "dstrike"), + "sz" => { + if let Some(value) = attribute(&property, "val").and_then(|value| value.parse::().ok()) { + run.size_pt = Some(value / 2.0); + } + } + "color" => { + if let Some(value) = attribute(&property, "val") { + run.color = parse_hex_color(&value); + } + } + "rFonts" => run.font = attribute(&property, "ascii"), + "vertAlign" => { + run.vert_align = match attribute(&property, "val").as_deref() { + Some("subscript") => Some(VertAlign::Subscript), + Some("superscript") => Some(VertAlign::Superscript), + _ => None, + } + } + "highlight" => { + if let Some(value) = attribute(&property, "val") { + run.color = parse_highlight(&value).or(run.color); + } + } + _ => {} + } + } +} + +fn parse_hex_color(value: &str) -> Option<[u8; 3]> { + let cleaned = value.trim_start_matches('#'); + if cleaned.len() != 6 || cleaned.eq_ignore_ascii_case("auto") { + return None; + } + Some([ + u8::from_str_radix(&cleaned[0..2], 16).ok()?, + u8::from_str_radix(&cleaned[2..4], 16).ok()?, + u8::from_str_radix(&cleaned[4..6], 16).ok()?, + ]) +} + +fn parse_highlight(value: &str) -> Option<[u8; 3]> { + let color = match value { + "yellow" => [0xFF, 0xFF, 0x00], + "green" => [0x00, 0xFF, 0x00], + "cyan" => [0x00, 0xFF, 0xFF], + "magenta" => [0xFF, 0x00, 0xFF], + "red" => [0xFF, 0x00, 0x00], + "blue" => [0x00, 0x00, 0xFF], + "darkBlue" => [0x00, 0x00, 0x80], + "darkRed" => [0x80, 0x00, 0x00], + "darkGreen" => [0x00, 0x80, 0x00], + "gray" | "lightGray" => [0xC0, 0xC0, 0xC0], + _ => return None, + }; + Some(color) +} + +fn collect_drawing_images(node: Node, rels: &HashMap, images: &mut Vec) { + for descendant in node.descendants().filter(|item| item.is_element()) { + match descendant.tag_name().name() { + "blip" => { + if let Some(id) = attribute(&descendant, "embed") { + push_image(&id, descendant, rels, images); + } + } + "imagedata" => { + if let Some(id) = attribute(&descendant, "id") { + push_image(&id, descendant, rels, images); + } + } + _ => {} + } + } +} + +fn push_image( + id: &str, + node: Node, + rels: &HashMap, + images: &mut Vec, +) { + let Some((kind, target)) = rels.get(id) else { + return; + }; + if !kind.contains("image") { + return; + } + // Görsel baytları `parse_blocks` sırasında paketten okunamıyorsa rels hedefi taşınır. + let extension = target.rsplit('.').next().unwrap_or(""); + let format = ImageFormat::from_extension(extension); + let anchor = node + .ancestors() + .find(|item| item.has_tag_name("drawing") || item.has_tag_name("pict")); + let extent = anchor.and_then(|item| { + item.descendants() + .find(|item| item.has_tag_name("extent")) + }); + let (width_pt, height_pt) = extent + .map(|item| { + let cx = attribute(&item, "cx").and_then(|value| value.parse::().ok()).unwrap_or(0.0); + let cy = attribute(&item, "cy").and_then(|value| value.parse::().ok()).unwrap_or(0.0); + (cx / EMU_PER_PT, cy / EMU_PER_PT) + }) + .unwrap_or((0.0, 0.0)); + + images.push(ImageBlock { + // Bytes `Document` üretilirken doldurulur (paket erişimi burada yok). + data: target.as_bytes().to_vec(), + format, + width_pt, + height_pt, + alt: None, + }); +} + +fn parse_table(node: Node, context: &Context, _package: &mut Package) -> Table { + let mut widths = Vec::new(); + if let Some(grid) = child(node, "tblGrid") { + for column in grid.children().filter(|item| item.tag_name().name() == "gridCol") { + let width = attribute(&column, "w") + .and_then(|value| value.parse::().ok()) + .unwrap_or(1.0); + widths.push(width); + } + } + + let mut raw_rows: Vec> = Vec::new(); + for row in node.children().filter(|item| item.tag_name().name() == "tr") { + let mut col = 0usize; + let mut cells = Vec::new(); + for cell in row.children().filter(|item| item.tag_name().name() == "tc") { + let properties = child(cell, "tcPr"); + let span = properties + .and_then(|item| child(item, "gridSpan")) + .and_then(|item| attribute(&item, "val").and_then(|value| value.parse::().ok())) + .unwrap_or(1) + .max(1); + + let mut vmerge = VMerge::None; + let mut shade = None; + let mut align = Align::Left; + if let Some(properties) = properties { + if let Some(merge) = child(properties, "vMerge") { + vmerge = match attribute(&merge, "val").as_deref() { + Some("restart") => VMerge::Restart, + _ => VMerge::Continue, + }; + } + if let Some(shading) = child(properties, "shd") { + shade = attribute(&shading, "fill").and_then(|value| parse_hex_color(&value)); + } + if let Some(jc) = child(properties, "jc") { + if let Some(value) = attribute(&jc, "val") { + align = parse_align(&value); + } + } + } + + let mut paragraphs = Vec::new(); + collect_paragraphs(cell, context, &mut paragraphs); + if paragraphs.is_empty() { + paragraphs.push(Paragraph::default()); + } + + cells.push(RawCell { + col, + span, + vmerge, + cell: Cell { + colspan: span as u32, + rowspan: 1, + shade, + align, + paragraphs, + }, + }); + col += span; + } + raw_rows.push(cells); + } + + // Dikey birleşmeleri hesapla: restart hücresi için aşağıdaki continue sayısı. + let mut rowspans: Vec<(usize, usize, u32)> = Vec::new(); + for (row_index, cells) in raw_rows.iter().enumerate() { + for (cell_index, raw) in cells.iter().enumerate() { + if raw.vmerge != VMerge::Restart { + continue; + } + let mut rowspan = 1usize; + for next_row in raw_rows.iter().skip(row_index + 1) { + let covered = next_row + .iter() + .any(|candidate| candidate.col == raw.col && candidate.vmerge == VMerge::Continue); + if covered { + rowspan += 1; + } else { + break; + } + } + rowspans.push((row_index, cell_index, rowspan as u32)); + } + } + for (row_index, cell_index, rowspan) in rowspans { + raw_rows[row_index][cell_index].cell.rowspan = rowspan; + } + + let mut rows: Vec> = Vec::new(); + for cells in raw_rows { + let mut row = Vec::new(); + for raw in cells { + if raw.vmerge == VMerge::Continue { + continue; + } + row.push(raw.cell); + } + rows.push(row); + } + + Table { + widths, + rows, + header_rows: 1, + } +} diff --git a/src-tauri/src/services/office_engine.rs b/src-tauri/src/services/office_engine.rs new file mode 100644 index 0000000..8193019 --- /dev/null +++ b/src-tauri/src/services/office_engine.rs @@ -0,0 +1,288 @@ +//! Biçim koruyan, harici program gerektirmeyen ofis dönüştürme motoru. + +use std::path::{Path, PathBuf}; + +use crate::error::{AppError, AppResult}; +use crate::services::docx_writer::DocxWriter; +use crate::services::image_engine::ImageEngine; +use crate::services::office_model::{read_document, Align, Block, Document, ListKind, Paragraph}; +use crate::services::pdf_writer; + +pub struct OfficeEngine; + +impl OfficeEngine { + pub fn convert(input_path: &str, target: &str, output_dir: &Path) -> AppResult { + let input = Path::new(input_path); + let document = read_document(input)?; + if document.is_empty() { + return Err(AppError::Generic("Belge boş.".to_string())); + } + + let stem = input + .file_stem() + .and_then(|value| value.to_str()) + .unwrap_or("belge"); + + match target { + "docx" => { + let path = + ImageEngine::get_unique_path(&output_dir.join(format!("{}.docx", stem)), false); + DocxWriter::create_from_document(&path, &document)?; + Ok(path) + } + "pdf" => { + let target = ImageEngine::get_unique_path(&output_dir.join(format!("{}.pdf", stem)), false); + pdf_writer::write_pdf(&document, &target) + } + "html" => { + let path = + ImageEngine::get_unique_path(&output_dir.join(format!("{}.html", stem)), false); + std::fs::write(&path, to_html(&document))?; + Ok(path) + } + "txt" => { + let path = + ImageEngine::get_unique_path(&output_dir.join(format!("{}.txt", stem)), false); + std::fs::write(&path, document.plain_text())?; + Ok(path) + } + other => Err(AppError::UnsupportedFormat(format!( + "Ofis motoru '{}' hedefini desteklemiyor.", + other + ))), + } + } +} + +fn escape(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} + +fn inline_html(paragraph: &Paragraph) -> String { + let mut html = String::new(); + for run in ¶graph.runs { + let mut text = escape(&run.text).replace('\t', " ").replace('\n', "
    "); + if text.is_empty() { + continue; + } + if run.bold { + text = format!("{}", text); + } + if run.italic { + text = format!("{}", text); + } + if run.underline { + text = format!("{}", text); + } + if run.strike { + text = format!("{}", text); + } + if let Some(align) = run.vert_align { + use crate::services::office_model::VertAlign; + text = match align { + VertAlign::Subscript => format!("{}", text), + VertAlign::Superscript => format!("{}", text), + }; + } + if let Some(color) = run.color { + text = format!( + "{}", + color[0], color[1], color[2], text + ); + } + if let Some(link) = &run.link { + text = format!("{}", escape(link), text); + } + html.push_str(&text); + } + html +} + +pub fn to_html(document: &Document) -> String { + to_html_with(document, false) +} + +pub fn to_html_with(document: &Document, landscape: bool) -> String { + let page_rule = if landscape { + "@page{size:A4 landscape;margin:14mm 12mm}" + } else { + "@page{size:A4;margin:18mm 16mm}" + }; + + let mut html = String::from(""); + html.push_str("LD Converter"); + + if !document.header.is_empty() { + html.push_str("
    "); + for paragraph in &document.header { + html.push_str(&format!("

    {}

    ", inline_html(paragraph))); + } + html.push_str("
    "); + } + + let mut list_state: Option<(ListKind, u8)> = None; + + let close_list = |html: &mut String, state: &mut Option<(ListKind, u8)>| { + if let Some((kind, _)) = state.take() { + html.push_str(match kind { + ListKind::Bullet => "", + ListKind::Numbered => "", + }); + } + }; + + for block in &document.blocks { + match block { + Block::Paragraph(paragraph) => { + if let Some(list) = paragraph.style.list { + let level = paragraph.style.level; + match list_state { + Some((kind, current)) if kind == list && current == level => {} + _ => { + close_list(&mut html, &mut list_state); + html.push_str(match list { + ListKind::Bullet => "
      ", + ListKind::Numbered => "
        ", + }); + list_state = Some((list, level)); + } + } + html.push_str(&format!("
      1. {}
      2. ", inline_html(paragraph))); + continue; + } + close_list(&mut html, &mut list_state); + + let align = match paragraph.style.align { + Align::Center => " style=\"text-align:center\"", + Align::Right => " style=\"text-align:right\"", + Align::Justify => " style=\"text-align:justify\"", + Align::Left => "", + }; + let content = inline_html(paragraph); + match paragraph.style.heading { + Some(level) => { + let level = level.clamp(1, 6); + html.push_str(&format!("{2}", level, align, content)); + } + None => html.push_str(&format!("{}

        ", align, content)), + } + } + Block::Table(table) => { + close_list(&mut html, &mut list_state); + html.push_str(""); + let columns = table.rows.iter().map(|row| row.len()).max().unwrap_or(0); + if !table.widths.is_empty() && table.widths.len() == columns { + html.push_str(""); + let total: f32 = table.widths.iter().sum(); + for width in &table.widths { + let percent = (width / total.max(0.0001)) * 100.0; + html.push_str(&format!("", percent)); + } + html.push_str(""); + } + for (row_index, row) in table.rows.iter().enumerate() { + html.push_str(""); + for cell in row { + let tag = if row_index < table.header_rows.max(1) { "th" } else { "td" }; + let mut attributes = String::new(); + if cell.colspan > 1 { + attributes.push_str(&format!(" colspan=\"{}\"", cell.colspan)); + } + if cell.rowspan > 1 { + attributes.push_str(&format!(" rowspan=\"{}\"", cell.rowspan)); + } + let mut styles = String::new(); + if let Some(shade) = cell.shade { + styles.push_str(&format!( + "background:#{:02x}{:02x}{:02x};", + shade[0], shade[1], shade[2] + )); + } + match cell.align { + Align::Center => styles.push_str("text-align:center;"), + Align::Right => styles.push_str("text-align:right;"), + Align::Justify => styles.push_str("text-align:justify;"), + Align::Left => {} + } + if !styles.is_empty() { + attributes.push_str(&format!(" style=\"{}\"", styles)); + } + html.push_str(&format!("<{}{}>", tag, attributes)); + for (index, paragraph) in cell.paragraphs.iter().enumerate() { + if index > 0 { + html.push_str("
        "); + } + html.push_str(&inline_html(paragraph)); + } + html.push_str(&format!("", tag)); + } + html.push_str(""); + } + html.push_str("
        "); + } + Block::Image(image) => { + close_list(&mut html, &mut list_state); + let encoded = encode_base64(&image.data); + let mut style = String::new(); + if image.width_pt > 0.0 { + style.push_str(&format!("width:{:.0}px;", image.width_pt * 1.333)); + } + html.push_str(&format!( + "

        \"{}\"

        ", + image.format.mime(), + encoded, + escape(image.alt.as_deref().unwrap_or("")), + style + )); + } + Block::PageBreak => { + close_list(&mut html, &mut list_state); + html.push_str("
        "); + } + } + } + + close_list(&mut html, &mut list_state); + html.push_str(""); + html +} + +fn encode_base64(bytes: &[u8]) -> String { + const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut output = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let byte0 = chunk[0] as u32; + let byte1 = chunk.get(1).copied().unwrap_or(0) as u32; + let byte2 = chunk.get(2).copied().unwrap_or(0) as u32; + let combined = (byte0 << 16) | (byte1 << 8) | byte2; + output.push(TABLE[(combined >> 18) as usize & 63] as char); + output.push(TABLE[(combined >> 12) as usize & 63] as char); + output.push(if chunk.len() > 1 { + TABLE[(combined >> 6) as usize & 63] as char + } else { + '=' + }); + output.push(if chunk.len() > 2 { + TABLE[combined as usize & 63] as char + } else { + '=' + }); + } + output +} diff --git a/src-tauri/src/services/office_model.rs b/src-tauri/src/services/office_model.rs new file mode 100644 index 0000000..551c63c --- /dev/null +++ b/src-tauri/src/services/office_model.rs @@ -0,0 +1,267 @@ +//! Zengin belge modeli: paragraf, liste, tablo (birleşik hücreli), görsel, köprü. +//! +//! DOCX / ODT / XLSX / PPTX / RTF okuyucuları bu modeli doldurur; DOCX/HTML/PDF +//! yazıcıları bu modelden üretir. + +use std::path::Path; + +use crate::error::AppResult; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Align { + #[default] + Left, + Center, + Right, + Justify, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VertAlign { + Subscript, + Superscript, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ListKind { + Bullet, + Numbered, +} + +#[derive(Debug, Clone, Default)] +pub struct Paragraph { + pub style: ParagraphStyle, + pub runs: Vec, +} + +#[derive(Debug, Clone, Default)] +pub struct ParagraphStyle { + pub heading: Option, + pub list: Option, + /// Liste seviyesi (0 tabanlı). + pub level: u8, + pub align: Align, + pub space_before_pt: f32, + pub space_after_pt: f32, + pub indent_left_pt: f32, + pub is_display_math: bool, +} + +impl Paragraph { + pub fn text(&self) -> String { + self.runs.iter().map(|run| run.text.as_str()).collect() + } + + pub fn is_empty(&self) -> bool { + self.runs.iter().all(|run| run.text.trim().is_empty()) + } +} + +#[derive(Debug, Clone)] +pub struct Run { + pub text: String, + pub bold: bool, + pub italic: bool, + pub underline: bool, + pub strike: bool, + pub size_pt: Option, + pub color: Option<[u8; 3]>, + pub font: Option, + pub vert_align: Option, + pub link: Option, + pub omml: Option, +} + +impl Run { + pub fn plain(text: impl Into) -> Self { + Self { + text: text.into(), + bold: false, + italic: false, + underline: false, + strike: false, + size_pt: None, + color: None, + font: None, + vert_align: None, + link: None, + omml: None, + } + } + + pub fn math(omml_xml: impl Into) -> Self { + Self { + text: String::new(), + bold: false, + italic: false, + underline: false, + strike: false, + size_pt: None, + color: None, + font: None, + vert_align: None, + link: None, + omml: Some(omml_xml.into()), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ImageFormat { + Png, + Jpeg, + Gif, + Webp, + Bmp, + Other, +} + +impl ImageFormat { + pub fn from_extension(extension: &str) -> Self { + match extension.to_ascii_lowercase().as_str() { + "png" => ImageFormat::Png, + "jpg" | "jpeg" => ImageFormat::Jpeg, + "gif" => ImageFormat::Gif, + "webp" => ImageFormat::Webp, + "bmp" => ImageFormat::Bmp, + _ => ImageFormat::Other, + } + } + + pub fn from_bytes(bytes: &[u8]) -> Self { + if bytes.starts_with(&[0x89, b'P', b'N', b'G']) { + ImageFormat::Png + } else if bytes.starts_with(&[0xFF, 0xD8]) { + ImageFormat::Jpeg + } else if bytes.starts_with(b"GIF8") { + ImageFormat::Gif + } else if bytes.len() > 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + ImageFormat::Webp + } else if bytes.starts_with(b"BM") { + ImageFormat::Bmp + } else { + ImageFormat::Other + } + } + + pub fn mime(self) -> &'static str { + match self { + ImageFormat::Png => "image/png", + ImageFormat::Jpeg => "image/jpeg", + ImageFormat::Gif => "image/gif", + ImageFormat::Webp => "image/webp", + ImageFormat::Bmp => "image/bmp", + ImageFormat::Other => "application/octet-stream", + } + } + + pub fn extension(self) -> &'static str { + match self { + ImageFormat::Png => "png", + ImageFormat::Jpeg => "jpg", + ImageFormat::Gif => "gif", + ImageFormat::Webp => "webp", + ImageFormat::Bmp => "bmp", + ImageFormat::Other => "bin", + } + } +} + +#[derive(Debug, Clone)] +pub struct ImageBlock { + pub data: Vec, + pub format: ImageFormat, + /// Nokta (pt) cinsinden hedef boyut; 0 ise görselin kendi boyutu kullanılır. + pub width_pt: f32, + pub height_pt: f32, + pub alt: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct Cell { + pub colspan: u32, + pub rowspan: u32, + pub shade: Option<[u8; 3]>, + pub align: Align, + pub paragraphs: Vec, +} + +impl Cell { + pub fn text(&self) -> String { + self.paragraphs + .iter() + .map(Paragraph::text) + .collect::>() + .join("\n") + } +} + +#[derive(Debug, Clone, Default)] +pub struct Table { + /// Sütun genişlik oranları (toplamı 1.0'a normalize edilir); boşsa eşit dağıtılır. + pub widths: Vec, + pub rows: Vec>, + pub header_rows: usize, +} + +#[derive(Debug, Clone)] +pub enum Block { + Paragraph(Paragraph), + Table(Table), + Image(ImageBlock), + PageBreak, +} + +#[derive(Debug, Clone, Default)] +pub struct Document { + pub blocks: Vec, + pub header: Vec, + pub footer: Vec, +} + +impl Document { + pub fn is_empty(&self) -> bool { + self.blocks.is_empty() + } + + pub fn plain_text(&self) -> String { + let mut text = String::new(); + for block in &self.blocks { + match block { + Block::Paragraph(paragraph) => text.push_str(¶graph.text()), + Block::Table(table) => { + for row in &table.rows { + let cells: Vec = row.iter().map(Cell::text).collect(); + text.push_str(&cells.join("\t")); + text.push('\n'); + } + text.push('\n'); + continue; + } + Block::Image(_) => text.push_str("[görsel]"), + Block::PageBreak => text.push_str("\n\n"), + } + text.push('\n'); + } + text.trim_end().to_string() + } +} + +/// Belgeyi okur (uzantıya göre doğru okuyucu). +pub fn read_document(path: &Path) -> AppResult { + let extension = path + .extension() + .and_then(|value| value.to_str()) + .unwrap_or("") + .to_ascii_lowercase(); + + match extension.as_str() { + "docx" => crate::services::office_docx::read_docx(path), + "odt" => crate::services::office_readers::read_odt(path), + "xlsx" | "xls" => crate::services::office_readers::read_xlsx(path), + "pptx" => crate::services::office_readers::read_pptx(path), + "rtf" => crate::services::office_readers::read_rtf(path), + "html" | "htm" => crate::services::office_readers::read_html(path), + _ => crate::services::office_readers::read_text(path), + } +} diff --git a/src-tauri/src/services/office_readers.rs b/src-tauri/src/services/office_readers.rs new file mode 100644 index 0000000..f4f8eca --- /dev/null +++ b/src-tauri/src/services/office_readers.rs @@ -0,0 +1,1651 @@ +//! DOCX dışındaki ofis biçimleri için okuyucular: ODT, XLSX, PPTX, RTF, HTML, TXT. + +use std::collections::HashMap; +use std::path::Path; + +use roxmltree::Node; + +use crate::error::{AppError, AppResult}; +use crate::services::office_model::*; +use crate::services::office_zip::Package; + +fn attribute(node: &Node, name: &str) -> Option { + node.attributes() + .find(|attribute| attribute.name() == name) + .map(|attribute| attribute.value().to_string()) +} + +fn heading_level(value: &str) -> Option { + let digits: String = value.chars().filter(|character| character.is_ascii_digit()).collect(); + digits.parse::().ok().map(|level| level.clamp(1, 6)) +} + +// ------------------------------------------------------------------- HTML + +#[derive(Clone, Default)] +struct HtmlInlineStyle { + bold: bool, + italic: bool, + underline: bool, + strike: bool, + vert_align: Option, + color: Option<[u8; 3]>, + size_pt: Option, + link: Option, +} + +enum HtmlContainer { + Heading { + level: u8, + align: Align, + }, + Paragraph { + align: Align, + list: Option, + level: u8, + }, + TableCell { + is_header: bool, + colspan: u32, + rowspan: u32, + shade: Option<[u8; 3]>, + align: Align, + paragraphs: Vec, + }, +} + +pub fn read_html(path: &Path) -> AppResult { + let bytes = std::fs::read(path)?; + let html = String::from_utf8_lossy(&bytes).to_string(); + let base_dir = path.parent().unwrap_or_else(|| Path::new(".")); + Ok(Document { + blocks: parse_html_to_blocks(&html, base_dir), + ..Default::default() + }) +} + +/// Zengin HTML içeriğini biçim korumalı AST bloklarına (`Paragraph`, `Table`, `Image`, `PageBreak`) çevirir. +pub fn parse_html_to_blocks(html: &str, base_dir: &Path) -> Vec { + let cleaned = strip_ignored_html_sections(html); + let bytes = cleaned.as_bytes(); + let len = bytes.len(); + let mut cursor = 0usize; + + let mut blocks: Vec = Vec::new(); + let mut style_stack: Vec<(String, HtmlInlineStyle)> = Vec::new(); + let mut list_stack: Vec = Vec::new(); + let mut current_runs: Vec = Vec::new(); + let mut current_style: Option = None; + + let mut in_table = false; + let mut table_rows: Vec> = Vec::new(); + let mut table_row: Vec = Vec::new(); + let mut table_header_rows = 0usize; + let mut current_cell: Option = None; + let mut current_cell_runs: Vec = Vec::new(); + + let flush_inline_into_para = + |runs: &mut Vec, p_style: ParagraphStyle| -> Option { + let mut merged: Vec = Vec::new(); + for r in runs.drain(..) { + if r.text.is_empty() { + continue; + } + merged.push(r); + } + if merged.iter().all(|r| r.text.trim().is_empty()) { + return None; + } + Some(Paragraph { + style: p_style, + runs: merged, + }) + }; + + let flush_paragraph = |runs: &mut Vec, + container: &mut Option, + out_blocks: &mut Vec| { + let p_style = match container.take() { + Some(HtmlContainer::Heading { level, align }) => ParagraphStyle { + heading: Some(level), + align, + space_before_pt: if level == 1 { 8.0 } else { 5.0 }, + space_after_pt: 3.0, + ..Default::default() + }, + Some(HtmlContainer::Paragraph { align, list, level }) => ParagraphStyle { + align, + list, + level, + space_after_pt: 3.0, + ..Default::default() + }, + _ => ParagraphStyle::default(), + }; + if let Some(p) = flush_inline_into_para(runs, p_style) { + out_blocks.push(Block::Paragraph(p)); + } + }; + + let flush_cell_runs = |cell_runs: &mut Vec, cell: &mut Option| { + let align = match cell { + Some(HtmlContainer::TableCell { align, .. }) => *align, + _ => Align::Left, + }; + if let Some(p) = flush_inline_into_para( + cell_runs, + ParagraphStyle { + align, + ..Default::default() + }, + ) { + if let Some(HtmlContainer::TableCell { paragraphs, .. }) = cell { + paragraphs.push(p); + } + } + }; + + let active_inline = |stack: &[(String, HtmlInlineStyle)]| -> HtmlInlineStyle { + stack + .last() + .map(|(_, s)| s.clone()) + .unwrap_or_default() + }; + + let push_text = |text: String, + stack: &[(String, HtmlInlineStyle)], + in_cell: bool, + cell_runs: &mut Vec, + para_runs: &mut Vec| { + if text.is_empty() { + return; + } + let st = active_inline(stack); + let run = Run { + text, + bold: st.bold, + italic: st.italic, + underline: st.underline || st.link.is_some(), + strike: st.strike, + size_pt: st.size_pt, + color: st.color.or_else(|| { + if st.link.is_some() { + Some([18, 92, 196]) + } else { + None + } + }), + font: None, + vert_align: st.vert_align, + link: st.link, + omml: None, + }; + if in_cell { + cell_runs.push(run); + } else { + para_runs.push(run); + } + }; + + while cursor < len { + let rest = &cleaned[cursor..]; + let Some(rel_open) = rest.find('<') else { + let decoded = collapse_html_ws(&unescape(rest)); + if !decoded.trim().is_empty() || (!current_runs.is_empty() && decoded == " ") { + push_text( + decoded, + &style_stack, + current_cell.is_some(), + &mut current_cell_runs, + &mut current_runs, + ); + } + break; + }; + + if rel_open > 0 { + let raw_text = &rest[..rel_open]; + let decoded = collapse_html_ws(&unescape(raw_text)); + if !decoded.is_empty() + && (!decoded.trim().is_empty() + || !current_runs.is_empty() + || !current_cell_runs.is_empty()) + { + push_text( + decoded, + &style_stack, + current_cell.is_some(), + &mut current_cell_runs, + &mut current_runs, + ); + } + } + + let tag_start = cursor + rel_open; + let Some(rel_close) = cleaned[tag_start..].find('>') else { + break; + }; + let tag_end = tag_start + rel_close; + let raw_tag = cleaned[tag_start + 1..tag_end].trim(); + cursor = tag_end + 1; + + if raw_tag.is_empty() || raw_tag.starts_with('!') || raw_tag.starts_with('?') { + continue; + } + + let self_closing = raw_tag.ends_with('/'); + let inner = raw_tag.trim_end_matches('/').trim(); + let is_closing = inner.starts_with('/'); + let tag_body = inner.trim_start_matches('/').trim(); + let name = tag_body + .split(|c: char| c.is_whitespace()) + .next() + .unwrap_or("") + .to_ascii_lowercase(); + + if name.is_empty() { + continue; + } + + if is_closing { + match name.as_str() { + "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "p" | "div" | "blockquote" + | "section" | "article" | "header" | "footer" | "li" => { + if current_cell.is_some() { + flush_cell_runs(&mut current_cell_runs, &mut current_cell); + } else { + flush_paragraph(&mut current_runs, &mut current_style, &mut blocks); + } + } + "ul" | "ol" => { + flush_paragraph(&mut current_runs, &mut current_style, &mut blocks); + list_stack.pop(); + } + "td" | "th" => { + flush_cell_runs(&mut current_cell_runs, &mut current_cell); + if let Some(HtmlContainer::TableCell { + is_header, + colspan, + rowspan, + shade, + align, + mut paragraphs, + }) = current_cell.take() + { + if is_header { + for p in &mut paragraphs { + for r in &mut p.runs { + r.bold = true; + } + } + } + table_row.push(Cell { + colspan, + rowspan, + shade, + align, + paragraphs, + }); + } + } + "tr" => { + if current_cell.is_some() { + flush_cell_runs(&mut current_cell_runs, &mut current_cell); + if let Some(HtmlContainer::TableCell { + colspan, + rowspan, + shade, + align, + paragraphs, + .. + }) = current_cell.take() + { + table_row.push(Cell { + colspan, + rowspan, + shade, + align, + paragraphs, + }); + } + } + if !table_row.is_empty() { + if table_row.iter().all(|c| c.shade.is_some()) && table_rows.is_empty() { + table_header_rows = 1; + } + table_rows.push(std::mem::take(&mut table_row)); + } + } + "table" => { + if !table_row.is_empty() { + table_rows.push(std::mem::take(&mut table_row)); + } + if !table_rows.is_empty() { + blocks.push(Block::Table(Table { + widths: Vec::new(), + rows: std::mem::take(&mut table_rows), + header_rows: table_header_rows, + })); + } + table_header_rows = 0; + in_table = false; + } + _ => { + if let Some(pos) = style_stack.iter().rposition(|(t, _)| t == &name) { + style_stack.truncate(pos); + } + } + } + continue; + } + + let css = attribute_from_tag(tag_body, "style").unwrap_or_default(); + if css_has_page_break(&css) { + flush_paragraph(&mut current_runs, &mut current_style, &mut blocks); + blocks.push(Block::PageBreak); + } + + match name.as_str() { + "br" => { + push_text( + "\n".to_string(), + &style_stack, + current_cell.is_some(), + &mut current_cell_runs, + &mut current_runs, + ); + } + "hr" => { + flush_paragraph(&mut current_runs, &mut current_style, &mut blocks); + blocks.push(Block::Paragraph(Paragraph { + style: ParagraphStyle::default(), + runs: vec![Run::plain(" ")], + })); + } + "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => { + flush_paragraph(&mut current_runs, &mut current_style, &mut blocks); + let level = name[1..].parse::().unwrap_or(1).clamp(1, 6); + let align = parse_html_align(tag_body, &css); + current_style = Some(HtmlContainer::Heading { level, align }); + } + "p" | "div" | "blockquote" | "section" | "article" | "header" | "footer" => { + if current_cell.is_some() { + flush_cell_runs(&mut current_cell_runs, &mut current_cell); + } else { + flush_paragraph(&mut current_runs, &mut current_style, &mut blocks); + let align = parse_html_align(tag_body, &css); + current_style = Some(HtmlContainer::Paragraph { + align, + list: None, + level: 0, + }); + } + } + "ul" => { + flush_paragraph(&mut current_runs, &mut current_style, &mut blocks); + list_stack.push(ListKind::Bullet); + } + "ol" => { + flush_paragraph(&mut current_runs, &mut current_style, &mut blocks); + list_stack.push(ListKind::Numbered); + } + "li" => { + flush_paragraph(&mut current_runs, &mut current_style, &mut blocks); + let kind = list_stack.last().copied().unwrap_or(ListKind::Bullet); + let level = list_stack.len().saturating_sub(1) as u8; + let align = parse_html_align(tag_body, &css); + current_style = Some(HtmlContainer::Paragraph { + align, + list: Some(kind), + level, + }); + } + "table" => { + flush_paragraph(&mut current_runs, &mut current_style, &mut blocks); + in_table = true; + table_rows.clear(); + table_row.clear(); + table_header_rows = 0; + } + "tr" => { + if in_table { + table_row.clear(); + } + } + "th" | "td" => { + if !in_table { + in_table = true; + table_rows.clear(); + table_row.clear(); + } + let is_header = name == "th"; + let colspan = attribute_from_tag(tag_body, "colspan") + .and_then(|v| v.parse::().ok()) + .unwrap_or(1) + .max(1); + let rowspan = attribute_from_tag(tag_body, "rowspan") + .and_then(|v| v.parse::().ok()) + .unwrap_or(1) + .max(1); + let align = parse_html_align(tag_body, &css); + let shade = parse_css_prop(&css, "background-color") + .or_else(|| parse_css_prop(&css, "background")) + .or_else(|| attribute_from_tag(tag_body, "bgcolor")) + .and_then(|c| parse_css_color(&c)) + .or(if is_header { Some([235, 241, 248]) } else { None }); + current_cell_runs.clear(); + current_cell = Some(HtmlContainer::TableCell { + is_header, + colspan, + rowspan, + shade, + align, + paragraphs: Vec::new(), + }); + } + "img" => { + if let Some(img_block) = parse_html_img_tag(tag_body, base_dir) { + if current_cell.is_none() { + flush_paragraph(&mut current_runs, &mut current_style, &mut blocks); + blocks.push(Block::Image(img_block)); + } else if let Some(alt_text) = img_block.alt { + if !alt_text.is_empty() { + push_text( + alt_text, + &style_stack, + true, + &mut current_cell_runs, + &mut current_runs, + ); + } + } + } + } + "b" | "strong" | "i" | "em" | "u" | "ins" | "s" | "strike" | "del" | "sub" + | "sup" | "a" | "span" | "font" | "code" + if !self_closing => + { + let mut st = active_inline(&style_stack); + match name.as_str() { + "b" | "strong" => st.bold = true, + "i" | "em" => st.italic = true, + "u" | "ins" => st.underline = true, + "s" | "strike" | "del" => st.strike = true, + "sub" => st.vert_align = Some(VertAlign::Subscript), + "sup" => st.vert_align = Some(VertAlign::Superscript), + "a" => { + if let Some(href) = attribute_from_tag(tag_body, "href") { + if !href.trim().is_empty() { + st.link = Some(unescape(href.trim())); + st.underline = true; + if st.color.is_none() { + st.color = Some([18, 92, 196]); + } + } + } + } + "font" => { + if let Some(c) = attribute_from_tag(tag_body, "color") + .and_then(|v| parse_css_color(&v)) + { + st.color = Some(c); + } + } + _ => {} + } + apply_inline_css(&css, &mut st); + style_stack.push((name, st)); + } + _ => {} + } + } + + flush_cell_runs(&mut current_cell_runs, &mut current_cell); + if !table_row.is_empty() { + table_rows.push(table_row); + } + if !table_rows.is_empty() { + blocks.push(Block::Table(Table { + widths: Vec::new(), + rows: table_rows, + header_rows: table_header_rows, + })); + } + flush_paragraph(&mut current_runs, &mut current_style, &mut blocks); + + blocks +} + +fn strip_ignored_html_sections(html: &str) -> String { + let mut current = html.to_string(); + // HTML yorumları + while let Some(start) = current.find("") { + let end = start + 4 + rel_end + 3; + current.replace_range(start..end, ""); + } else { + current.truncate(start); + break; + } + } + for tag in ["script", "style", "head"] { + let open_pat = format!("<{}", tag); + let close_pat = format!("", tag); + loop { + let lower = current.to_ascii_lowercase(); + let Some(start) = lower.find(&open_pat) else { break }; + let after = lower[start..].find('>'); + let search_from = after.map(|o| start + o + 1).unwrap_or(start); + if let Some(rel_close) = lower[search_from..].find(&close_pat) { + let end = search_from + rel_close + close_pat.len(); + current.replace_range(start..end, ""); + } else { + break; + } + } + } + current +} + +fn collapse_html_ws(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut prev_ws = false; + for ch in text.chars() { + if ch.is_whitespace() { + if !prev_ws { + out.push(' '); + prev_ws = true; + } + } else { + out.push(ch); + prev_ws = false; + } + } + out +} + +fn parse_html_img_tag(tag: &str, base_dir: &Path) -> Option { + let source = attribute_from_tag(tag, "src")?; + let source_trimmed = unescape(source.trim()); + let alt = attribute_from_tag(tag, "alt").map(|s| unescape(s.trim())); + + let is_svg_src = source_trimmed + .to_ascii_lowercase() + .starts_with("data:image/svg+xml") + || source_trimmed.to_ascii_lowercase().ends_with(".svg"); + + let mut data = if source_trimmed.to_ascii_lowercase().starts_with("data:") { + read_data_uri_flexible(&source_trimmed)? + } else { + let candidate = Path::new(&source_trimmed); + if candidate.is_absolute() { + std::fs::read(candidate).ok()? + } else { + std::fs::read(base_dir.join(candidate)).ok()? + } + }; + + let looks_like_svg = is_svg_src + || std::str::from_utf8(&data) + .map(|s| { + let trimmed = s.trim_start(); + trimmed.starts_with(" 0.0 && h > 0.0 => (w, h), + (Some(w), None) if w > 0.0 => (w, w * (nat_h / nat_w)), + (None, Some(h)) if h > 0.0 => (h * (nat_w / nat_h), h), + _ => (nat_w * 0.75, nat_h * 0.75), + }; + if w_pt > max_w_pt { + let scale = max_w_pt / w_pt; + w_pt *= scale; + h_pt *= scale; + } + + Some(ImageBlock { + data, + format, + width_pt: w_pt, + height_pt: h_pt, + alt, + }) +} + +fn read_data_uri_flexible(uri: &str) -> Option> { + if let Some(bytes) = read_data_uri(uri) { + return Some(bytes); + } + let comma = uri.find(',')?; + let payload = &uri[comma + 1..]; + Some(percent_decode(payload).into_bytes()) +} + +fn percent_decode(input: &str) -> String { + let bytes = input.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() { + if let Ok(hex) = std::str::from_utf8(&bytes[i + 1..i + 3]) { + if let Ok(val) = u8::from_str_radix(hex, 16) { + out.push(val); + i += 3; + continue; + } + } + } + out.push(bytes[i]); + i += 1; + } + String::from_utf8_lossy(&out).to_string() +} + +fn parse_html_align(tag: &str, css: &str) -> Align { + let val = parse_css_prop(css, "text-align") + .or_else(|| attribute_from_tag(tag, "align")) + .unwrap_or_default() + .to_ascii_lowercase(); + match val.trim() { + "center" => Align::Center, + "right" | "end" => Align::Right, + "justify" => Align::Justify, + _ => Align::Left, + } +} + +fn css_has_page_break(css: &str) -> bool { + parse_css_prop(css, "page-break-before") + .or_else(|| parse_css_prop(css, "break-before")) + .map(|v| v.eq_ignore_ascii_case("always") || v.eq_ignore_ascii_case("page")) + .unwrap_or(false) +} + +fn parse_css_prop(css: &str, key: &str) -> Option { + for decl in css.split(';') { + let Some((k, v)) = decl.split_once(':') else { continue }; + if k.trim().eq_ignore_ascii_case(key) { + return Some(v.trim().to_string()); + } + } + None +} + +fn apply_inline_css(css: &str, st: &mut HtmlInlineStyle) { + if let Some(c) = parse_css_prop(css, "color").and_then(|v| parse_css_color(&v)) { + st.color = Some(c); + } + if let Some(sz) = parse_css_prop(css, "font-size").and_then(|v| { + let lower = v.trim().to_ascii_lowercase(); + if let Some(pt) = lower.strip_suffix("pt") { + pt.trim().parse::().ok() + } else if let Some(px) = lower.strip_suffix("px") { + px.trim().parse::().ok().map(|p| p * 0.75) + } else { + None + } + }) { + st.size_pt = Some(sz.clamp(6.0, 72.0)); + } + if let Some(w) = parse_css_prop(css, "font-weight") { + let lw = w.trim().to_ascii_lowercase(); + if lw == "bold" || lw == "bolder" || lw.parse::().is_ok_and(|n| n >= 600) { + st.bold = true; + } + } + if let Some(fs) = parse_css_prop(css, "font-style") { + if fs.trim().eq_ignore_ascii_case("italic") || fs.trim().eq_ignore_ascii_case("oblique") { + st.italic = true; + } + } + if let Some(td) = parse_css_prop(css, "text-decoration") { + let ltd = td.to_ascii_lowercase(); + if ltd.contains("underline") { + st.underline = true; + } + if ltd.contains("line-through") { + st.strike = true; + } + } +} + +fn parse_css_color(raw: &str) -> Option<[u8; 3]> { + let val = raw.trim().to_ascii_lowercase(); + if let Some(hex) = val.strip_prefix('#') { + if hex.len() == 6 { + return Some([ + u8::from_str_radix(&hex[0..2], 16).ok()?, + u8::from_str_radix(&hex[2..4], 16).ok()?, + u8::from_str_radix(&hex[4..6], 16).ok()?, + ]); + } else if hex.len() == 3 { + let mut rgb = [0u8; 3]; + for (i, ch) in hex.chars().enumerate() { + let d = ch.to_digit(16)? as u8; + rgb[i] = d * 17; + } + return Some(rgb); + } + } + if let Some(inner) = val.strip_prefix("rgb(").and_then(|s| s.strip_suffix(')')) { + let parts: Vec = inner + .split(',') + .filter_map(|p| p.trim().parse::().ok()) + .collect(); + if parts.len() == 3 { + return Some([parts[0], parts[1], parts[2]]); + } + } + match val.as_str() { + "black" => Some([0, 0, 0]), + "white" => Some([255, 255, 255]), + "red" => Some([200, 30, 30]), + "green" => Some([22, 130, 60]), + "blue" => Some([25, 95, 200]), + "navy" => Some([15, 45, 110]), + "gray" | "grey" => Some([110, 118, 130]), + "orange" => Some([215, 110, 20]), + "purple" => Some([120, 45, 175]), + "teal" => Some([13, 130, 130]), + _ => None, + } +} + +fn attribute_from_tag(tag: &str, name: &str) -> Option { + let lower = tag.to_ascii_lowercase(); + let bytes = lower.as_bytes(); + let pat = format!("{}=", name); + let mut search = 0usize; + while let Some(rel) = lower[search..].find(&pat) { + let idx = search + rel; + let boundary_ok = idx == 0 || bytes[idx - 1].is_ascii_whitespace(); + if !boundary_ok { + search = idx + pat.len(); + continue; + } + let rest = &tag[idx + pat.len()..]; + let trimmed = rest.trim_start(); + let quote = trimmed.chars().next()?; + if quote == '"' || quote == '\'' { + let body = &trimmed[1..]; + return body.find(quote).map(|end| body[..end].to_string()); + } else { + return Some( + trimmed + .split_whitespace() + .next() + .unwrap_or("") + .trim_matches('/') + .to_string(), + ); + } + } + None +} + +fn unescape(text: &str) -> String { + let basic = text + .replace(" ", " ") + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace(""", "\"") + .replace("'", "'") + .replace("'", "'") + .replace("–", "-") + .replace("—", "—") + .replace("…", "..."); + if !basic.contains("&#") { + return basic; + } + let mut out = String::with_capacity(basic.len()); + let mut rest = basic.as_str(); + while let Some(pos) = rest.find("&#") { + out.push_str(&rest[..pos]); + let after = &rest[pos + 2..]; + if let Some(semi) = after.find(';') { + let code = &after[..semi]; + let parsed = if let Some(hex) = code.strip_prefix('x').or_else(|| code.strip_prefix('X')) { + u32::from_str_radix(hex, 16).ok().and_then(char::from_u32) + } else { + code.parse::().ok().and_then(char::from_u32) + }; + if let Some(ch) = parsed { + out.push(ch); + rest = &after[semi + 1..]; + continue; + } + } + out.push_str("&#"); + rest = after; + } + out.push_str(rest); + out +} + +fn read_data_uri(uri: &str) -> Option> { + let marker = ";base64,"; + let index = uri.find(marker)?; + let encoded = &uri[index + marker.len()..]; + decode_base64(encoded) +} + +pub fn decode_base64(input: &str) -> Option> { + const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut lookup = [255u8; 256]; + for (index, byte) in TABLE.iter().enumerate() { + lookup[*byte as usize] = index as u8; + } + + let mut output = Vec::new(); + let mut buffer = 0u32; + let mut bits = 0u8; + for byte in input.bytes() { + if byte == b'=' { + break; + } + let value = lookup[byte as usize]; + if value == 255 { + continue; + } + buffer = (buffer << 6) | value as u32; + bits += 6; + if bits >= 8 { + bits -= 8; + output.push((buffer >> bits) as u8); + } + } + Some(output) +} + +// ------------------------------------------------------------------- TXT + +pub fn read_text(path: &Path) -> AppResult { + let text = std::fs::read_to_string(path) + .or_else(|_| std::fs::read(path).map(|bytes| String::from_utf8_lossy(&bytes).to_string()))?; + let mut blocks = Vec::new(); + for line in text.replace("\r\n", "\n").split('\n') { + if line.trim().is_empty() { + continue; + } + blocks.push(Block::Paragraph(Paragraph { + style: ParagraphStyle::default(), + runs: vec![Run::plain(line.to_string())], + })); + } + Ok(Document { + blocks, + ..Default::default() + }) +} + +// ------------------------------------------------------------------- ODT + +pub fn read_odt(path: &Path) -> AppResult { + let mut package = Package::open(path)?; + let xml = package + .read_string("content.xml") + .ok_or_else(|| AppError::NotFound("content.xml yok".to_string()))?; + let styles = parse_odt_styles(&mut package); + + let mut document = Document::default(); + let Ok(parsed) = roxmltree::Document::parse(&xml) else { + return Ok(document); + }; + let Some(text_root) = parsed + .descendants() + .find(|node| node.tag_name().name() == "text") + else { + return Ok(document); + }; + + parse_odt_nodes(text_root, &styles, &mut package, &mut document.blocks); + Ok(document) +} + +#[derive(Default, Clone)] +struct OdtStyle { + bold: bool, + italic: bool, + color: Option<[u8; 3]>, + size: Option, +} + +fn parse_odt_styles(package: &mut Package) -> HashMap { + let mut styles = HashMap::new(); + for name in ["styles.xml", "content.xml"] { + let Some(xml) = package.read_string(name) else { continue }; + let Ok(parsed) = roxmltree::Document::parse(&xml) else { continue }; + for style in parsed.descendants().filter(|node| node.tag_name().name() == "style") { + let Some(style_name) = attribute(&style, "name") else { continue }; + let mut entry = OdtStyle::default(); + for properties in style.descendants().filter(|node| node.tag_name().name() == "text-properties") { + if attribute(&properties, "font-weight") + .map(|value| value.eq_ignore_ascii_case("bold") || value == "700" || value == "800" || value == "900") + .unwrap_or(false) + { + entry.bold = true; + } + if attribute(&properties, "font-style") + .map(|value| value.eq_ignore_ascii_case("italic")) + .unwrap_or(false) + { + entry.italic = true; + } + if let Some(color) = attribute(&properties, "color").and_then(|value| parse_color(&value)) { + entry.color = Some(color); + } + if let Some(size) = attribute(&properties, "font-size").and_then(|value| parse_pt(&value)) { + entry.size = Some(size); + } + } + styles.insert(style_name, entry); + } + } + styles +} + +fn parse_color(value: &str) -> Option<[u8; 3]> { + let cleaned = value.trim_start_matches('#'); + if cleaned.len() != 6 { + return None; + } + Some([ + u8::from_str_radix(&cleaned[0..2], 16).ok()?, + u8::from_str_radix(&cleaned[2..4], 16).ok()?, + u8::from_str_radix(&cleaned[4..6], 16).ok()?, + ]) +} + +fn parse_pt(value: &str) -> Option { + value + .trim_end_matches("pt") + .trim_end_matches("px") + .parse::() + .ok() +} + +fn parse_odt_nodes( + parent: Node, + styles: &HashMap, + package: &mut Package, + blocks: &mut Vec, +) { + for node in parent.children().filter(|child| child.is_element()) { + match node.tag_name().name() { + "h" => { + let level = attribute(&node, "outline-level") + .and_then(|value| heading_level(&value)) + .unwrap_or(1); + let mut paragraph = Paragraph { + style: ParagraphStyle { + heading: Some(level), + ..Default::default() + }, + runs: Vec::new(), + }; + collect_odt_runs(node, styles, &mut paragraph.runs); + if !paragraph.is_empty() { + blocks.push(Block::Paragraph(paragraph)); + } + } + "p" => { + let mut paragraph = Paragraph::default(); + if let Some(style_name) = attribute(&node, "style-name") { + if let Some(style) = styles.get(&style_name) { + paragraph.runs.push(Run { + bold: style.bold, + italic: style.italic, + color: style.color, + size_pt: style.size, + ..Run::plain("") + }); + let base = paragraph.runs.pop().unwrap_or_else(|| Run::plain("")); + let mut runs = Vec::new(); + collect_odt_runs(node, styles, &mut runs); + paragraph.runs = runs + .into_iter() + .map(|mut run| { + run.bold |= base.bold; + run.italic |= base.italic; + run.color = run.color.or(base.color); + run.size_pt = run.size_pt.or(base.size_pt); + run + }) + .collect(); + if !paragraph.is_empty() { + blocks.push(Block::Paragraph(paragraph)); + } + continue; + } + } + collect_odt_runs(node, styles, &mut paragraph.runs); + if !paragraph.is_empty() { + blocks.push(Block::Paragraph(paragraph)); + } + } + "list" => { + for item in node.children().filter(|child| child.tag_name().name() == "list-item") { + for child in item.children().filter(|child| child.is_element()) { + if child.tag_name().name() == "p" { + let mut paragraph = Paragraph { + style: ParagraphStyle { + list: Some(ListKind::Bullet), + ..Default::default() + }, + runs: Vec::new(), + }; + collect_odt_runs(child, styles, &mut paragraph.runs); + if !paragraph.is_empty() { + blocks.push(Block::Paragraph(paragraph)); + } + } + } + } + } + "table" => blocks.push(Block::Table(parse_odt_table(node, styles))), + "frame" | "image" => { + if let Some(href) = attribute(&node, "href") { + let target = href.trim_start_matches("./"); + if let Some(bytes) = package.read(&format!("Pictures/{}", target)) { + let format = ImageFormat::from_bytes(&bytes); + blocks.push(Block::Image(ImageBlock { + data: bytes, + format, + width_pt: 0.0, + height_pt: 0.0, + alt: None, + })); + } + } + } + _ => parse_odt_nodes(node, styles, package, blocks), + } + } +} + +fn collect_odt_runs(parent: Node, styles: &HashMap, runs: &mut Vec) { + for node in parent.children() { + if node.is_text() { + let text = node.text().unwrap_or_default(); + if !text.is_empty() { + runs.push(Run::plain(text)); + } + continue; + } + if !node.is_element() { + continue; + } + match node.tag_name().name() { + "span" => { + let style = attribute(&node, "style-name") + .and_then(|name| styles.get(&name).cloned()) + .unwrap_or_default(); + let mut child_runs = Vec::new(); + collect_odt_runs(node, styles, &mut child_runs); + for mut run in child_runs { + run.bold |= style.bold; + run.italic |= style.italic; + run.color = run.color.or(style.color); + run.size_pt = run.size_pt.or(style.size); + runs.push(run); + } + } + "s" => { + let count = attribute(&node, "c").and_then(|value| value.parse::().ok()).unwrap_or(1); + runs.push(Run::plain(" ".repeat(count))); + } + "tab" => runs.push(Run::plain("\t")), + "line-break" => runs.push(Run::plain("\n")), + _ => collect_odt_runs(node, styles, runs), + } + } +} + +fn parse_odt_table(node: Node, styles: &HashMap) -> Table { + let mut rows: Vec> = Vec::new(); + for row in node.children().filter(|child| child.tag_name().name() == "table-row") { + let mut cells = Vec::new(); + for cell in row + .children() + .filter(|child| child.tag_name().name() == "table-cell" || child.tag_name().name() == "covered-table-cell") + { + let covered = cell.tag_name().name() == "covered-table-cell"; + if covered { + continue; + } + let colspan = attribute(&cell, "number-columns-spanned") + .and_then(|value| value.parse::().ok()) + .unwrap_or(1); + let rowspan = attribute(&cell, "number-rows-spanned") + .and_then(|value| value.parse::().ok()) + .unwrap_or(1); + let shade = attribute(&cell, "background-color").and_then(|value| parse_color(&value)); + let mut paragraphs = Vec::new(); + for child in cell.children().filter(|child| child.is_element()) { + if child.tag_name().name() == "p" { + let mut paragraph = Paragraph::default(); + collect_odt_runs(child, styles, &mut paragraph.runs); + if !paragraph.is_empty() { + paragraphs.push(paragraph); + } + } + } + if paragraphs.is_empty() { + paragraphs.push(Paragraph::default()); + } + cells.push(Cell { + colspan, + rowspan, + shade, + align: Align::Left, + paragraphs, + }); + } + rows.push(cells); + } + + Table { + widths: Vec::new(), + rows, + header_rows: 1, + } +} + +// ------------------------------------------------------------------- XLSX + +pub fn read_xlsx(path: &Path) -> AppResult { + let mut package = Package::open(path)?; + let shared = package + .read_string("xl/sharedStrings.xml") + .map(|xml| { + let mut values = Vec::new(); + if let Ok(parsed) = roxmltree::Document::parse(&xml) { + for item in parsed.descendants().filter(|node| node.tag_name().name() == "si") { + let text: String = item + .descendants() + .filter(|node| node.tag_name().name() == "t") + .filter_map(|node| node.text()) + .collect(); + values.push(text); + } + } + values + }) + .unwrap_or_default(); + + let sheet_names = parse_sheet_names(&mut package); + let mut document = Document::default(); + + let mut index = 0usize; + loop { + index += 1; + let Some(xml) = package.read_string(&format!("xl/worksheets/sheet{}.xml", index)) else { + break; + }; + let Some(table) = parse_sheet(&xml, &shared) else { + continue; + }; + + let name = sheet_names + .get(index - 1) + .cloned() + .unwrap_or_else(|| format!("Sayfa {}", index)); + + document.blocks.push(Block::Paragraph(Paragraph { + style: ParagraphStyle { + heading: Some(2), + ..Default::default() + }, + runs: vec![Run::plain(name)], + })); + document.blocks.push(Block::Table(table)); + } + + Ok(document) +} + +fn parse_sheet_names(package: &mut Package) -> Vec { + let Some(xml) = package.read_string("xl/workbook.xml") else { + return Vec::new(); + }; + let Ok(parsed) = roxmltree::Document::parse(&xml) else { + return Vec::new(); + }; + parsed + .descendants() + .filter(|node| node.tag_name().name() == "sheet") + .filter_map(|node| attribute(&node, "name")) + .collect() +} + +fn parse_sheet(xml: &str, shared: &[String]) -> Option { + let parsed = roxmltree::Document::parse(xml).ok()?; + let mut rows: Vec> = Vec::new(); + let mut merges: Vec<(usize, usize, usize, usize)> = Vec::new(); // (row, col, rowspan, colspan) + + if let Some(merge_cells) = parsed + .descendants() + .find(|node| node.tag_name().name() == "mergeCells") + { + for merge in merge_cells.children().filter(|node| node.tag_name().name() == "mergeCell") { + if let Some(reference) = attribute(&merge, "ref") { + if let Some((start, end)) = reference.split_once(':') { + if let (Some((r1, c1)), Some((r2, c2))) = (parse_cell_ref(start), parse_cell_ref(end)) { + merges.push((r1, c1, r2.saturating_sub(r1) + 1, c2.saturating_sub(c1) + 1)); + } + } + } + } + } + + for row_node in parsed.descendants().filter(|node| node.tag_name().name() == "row") { + let row_index = attribute(&row_node, "r") + .and_then(|value| value.parse::().ok()) + .unwrap_or(rows.len() + 1) + .saturating_sub(1); + let mut row: Vec = Vec::new(); + + for cell in row_node.children().filter(|node| node.tag_name().name() == "c") { + let reference = attribute(&cell, "r").unwrap_or_default(); + let (_, column) = parse_cell_ref(&reference).unwrap_or((row_index, row.len())); + while row.len() < column { + row.push(empty_cell()); + } + + let cell_type = attribute(&cell, "t").unwrap_or_default(); + let raw = cell + .children() + .find(|node| node.tag_name().name() == "v") + .and_then(|node| node.text()) + .unwrap_or_default() + .to_string(); + let value = match cell_type.as_str() { + "s" => raw + .parse::() + .ok() + .and_then(|index| shared.get(index).cloned()) + .unwrap_or_default(), + "inlineStr" => cell + .descendants() + .filter(|node| node.tag_name().name() == "t") + .filter_map(|node| node.text()) + .collect(), + _ => raw, + }; + + row.push(Cell { + colspan: 1, + rowspan: 1, + shade: None, + align: Align::Left, + paragraphs: vec![Paragraph { + style: ParagraphStyle::default(), + runs: vec![Run::plain(value)], + }], + }); + } + + while rows.len() < row_index { + rows.push(Vec::new()); + } + rows.push(row); + } + + // Birleşik hücreleri uygula: kapsanan hücreleri boşalt, boyutları ata. + for (row, column, rowspan, colspan) in merges { + if row >= rows.len() || column >= rows[row].len() { + continue; + } + rows[row][column].rowspan = rowspan as u32; + rows[row][column].colspan = colspan as u32; + } + + if rows.is_empty() { + return None; + } + let columns = rows.iter().map(Vec::len).max().unwrap_or(1); + for row in &mut rows { + while row.len() < columns { + row.push(empty_cell()); + } + } + + Some(Table { + widths: vec![1.0; columns], + rows, + header_rows: 1, + }) +} + +fn empty_cell() -> Cell { + Cell { + colspan: 1, + rowspan: 1, + shade: None, + align: Align::Left, + paragraphs: vec![Paragraph::default()], + } +} + +fn parse_cell_ref(reference: &str) -> Option<(usize, usize)> { + let letters: String = reference + .chars() + .take_while(|character| character.is_ascii_alphabetic()) + .collect(); + if letters.is_empty() { + return None; + } + let digits: String = reference + .chars() + .skip_while(|character| character.is_ascii_alphabetic()) + .take_while(|character| character.is_ascii_digit()) + .collect(); + let mut column = 0usize; + for character in letters.chars() { + column = column * 26 + (character.to_ascii_uppercase() as usize - 'A' as usize + 1); + } + let row = digits.parse::().ok()?; + Some((row.saturating_sub(1), column.saturating_sub(1))) +} + +// ------------------------------------------------------------------- PPTX + +pub fn read_pptx(path: &Path) -> AppResult { + let mut package = Package::open(path)?; + let media: Vec<(String, Vec)> = package + .names() + .into_iter() + .filter(|name| name.starts_with("ppt/media/")) + .filter_map(|name| package.read(&name).map(|bytes| (name, bytes))) + .collect(); + let media_map: HashMap> = media + .into_iter() + .map(|(name, bytes)| (name.rsplit('/').next().unwrap_or(&name).to_string(), bytes)) + .collect(); + + let mut slides: Vec = package + .names() + .into_iter() + .filter(|name| name.starts_with("ppt/slides/slide") && name.ends_with(".xml")) + .collect(); + slides.sort_by_key(|name| slide_number(name)); + + let mut document = Document::default(); + for (index, slide) in slides.iter().enumerate() { + if index > 0 { + document.blocks.push(Block::PageBreak); + } + let Some(xml) = package.read_string(slide) else { continue }; + let Ok(parsed) = roxmltree::Document::parse(&xml) else { + continue; + }; + + let rels = package + .read_string(&format!("{}rels", slide.replace("ppt/slides/", "ppt/slides/_rels/"))) + .map(|xml| parse_pptx_rels(&xml)) + .unwrap_or_default(); + + for paragraph in parsed.descendants().filter(|node| node.tag_name().name() == "p") { + let mut runs = Vec::new(); + for run in paragraph.descendants().filter(|node| node.tag_name().name() == "r") { + let text: String = run + .descendants() + .filter(|node| node.tag_name().name() == "t") + .filter_map(|node| node.text()) + .collect(); + if text.is_empty() { + continue; + } + let properties = run + .children() + .find(|node| node.tag_name().name() == "rPr"); + let mut styled = Run::plain(text); + if let Some(properties) = properties { + styled.bold = attribute(&properties, "b").map(|v| v == "1").unwrap_or(false); + styled.italic = attribute(&properties, "i").map(|v| v == "1").unwrap_or(false); + } + runs.push(styled); + } + let text: String = runs.iter().map(|run| run.text.as_str()).collect(); + if !text.trim().is_empty() { + let paragraph = Paragraph { + style: ParagraphStyle::default(), + runs, + }; + document.blocks.push(Block::Paragraph(paragraph)); + } + } + + for blip in parsed.descendants().filter(|node| node.tag_name().name() == "blip") { + if let Some(id) = attribute(&blip, "embed") { + if let Some(target) = rels.get(&id) { + let name = target.rsplit('/').next().unwrap_or(target); + if let Some(bytes) = media_map.get(name) { + document.blocks.push(Block::Image(ImageBlock { + data: bytes.clone(), + format: ImageFormat::from_bytes(bytes), + width_pt: 320.0, + height_pt: 180.0, + alt: None, + })); + } + } + } + } + } + + Ok(document) +} + +fn slide_number(name: &str) -> usize { + name.rsplit('/') + .next() + .and_then(|file| file.trim_start_matches("slide").trim_end_matches(".xml").parse::().ok()) + .unwrap_or(0) +} + +fn parse_pptx_rels(xml: &str) -> HashMap { + let mut map = HashMap::new(); + if let Ok(parsed) = roxmltree::Document::parse(xml) { + for node in parsed.descendants().filter(|node| node.tag_name().name() == "Relationship") { + if let (Some(id), Some(target)) = (attribute(&node, "Id"), attribute(&node, "Target")) { + map.insert(id, target); + } + } + } + map +} + +// ------------------------------------------------------------------- RTF + +pub fn read_rtf(path: &Path) -> AppResult { + let bytes = std::fs::read(path)?; + let text = String::from_utf8_lossy(&bytes).to_string(); + Ok(Document { + blocks: parse_rtf(&text), + ..Default::default() + }) +} + +fn parse_rtf(input: &str) -> Vec { + let mut blocks = Vec::new(); + let mut current = Paragraph::default(); + let mut bold = false; + let mut italic = false; + let mut underline = false; + + let characters: Vec = input.chars().collect(); + let mut index = 0usize; + while index < characters.len() { + let character = characters[index]; + match character { + '\\' => { + index += 1; + if index >= characters.len() { + break; + } + let next = characters[index]; + match next { + 'b' => bold = true, + 'i' => italic = true, + 'U' => underline = true, + 'p' => { + if !current.is_empty() { + blocks.push(Block::Paragraph(std::mem::take(&mut current))); + } + } + 'u' => { + // \uNNNN? — bir sonraki sayı unicode değeridir. + let mut digits = String::new(); + index += 1; + while index < characters.len() && characters[index].is_ascii_digit() { + digits.push(characters[index]); + index += 1; + } + if let Ok(code) = digits.parse::() { + let code = if code < 0 { code + 65536 } else { code }; + if let Some(decoded) = char::from_u32(code as u32) { + current.runs.push(Run { + text: decoded.to_string(), + bold, + italic, + underline, + ..Run::plain("") + }); + } + } + continue; + } + '\\' | '{' | '}' => current.runs.push(Run { + text: next.to_string(), + bold, + italic, + underline, + ..Run::plain("") + }), + '0' => { + bold = false; + italic = false; + underline = false; + } + ' ' => {} + _ => { + // Kontrol kelimesini atla. + while index < characters.len() + && (characters[index].is_ascii_alphabetic() || characters[index] == '-') + { + index += 1; + } + while index < characters.len() && characters[index].is_ascii_digit() { + index += 1; + } + if index < characters.len() && characters[index] == ' ' { + continue; + } + continue; + } + } + } + '{' | '}' => {} + '\r' | '\n' => {} + other => current.runs.push(Run { + text: other.to_string(), + bold, + italic, + underline, + ..Run::plain("") + }), + } + index += 1; + } + + if !current.is_empty() { + blocks.push(Block::Paragraph(current)); + } + blocks +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn read_html_parses_headings_links_tables_and_images() -> Result<(), Box> { + let dir = std::env::temp_dir().join(format!("ld_html_test_{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir)?; + let html_path = dir.join("test.html"); + let tiny_png_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; + let html = format!( + "\ +

        Rapor Başlığı

        \ +

        Bağlantı: Örnek

        \ +
        AB
        12
        \ +

        \"piksel\"/

        \ + ", + tiny_png_b64 + ); + std::fs::write(&html_path, html)?; + + let doc = read_html(&html_path)?; + let has_heading = doc.blocks.iter().any(|b| match b { + Block::Paragraph(p) => { + p.style.heading == Some(1) + && p.runs + .iter() + .map(|r| r.text.as_str()) + .collect::() + .contains("Rapor Başlığı") + } + _ => false, + }); + let has_link = doc.blocks.iter().any(|b| match b { + Block::Paragraph(p) => p + .runs + .iter() + .any(|r| r.link.as_deref() == Some("https://example.com")), + _ => false, + }); + let has_table = doc.blocks.iter().any(|b| match b { + Block::Table(t) => t.rows.len() == 2 && t.rows[0].len() == 2, + _ => false, + }); + let has_image = doc + .blocks + .iter() + .any(|b| matches!(b, Block::Image(img) if !img.data.is_empty())); + + assert!(has_heading, "h1 başlığı okunmalı"); + assert!(has_link, "köprü bağlantısı korunmalı"); + assert!(has_table, "2x2 tablo ayrıştırılmalı"); + assert!(has_image, "data URI PNG görüntüsü çözülmeli"); + + let _ = std::fs::remove_dir_all(&dir); + Ok(()) + } +} diff --git a/src-tauri/src/services/office_zip.rs b/src-tauri/src/services/office_zip.rs new file mode 100644 index 0000000..ce5b9e1 --- /dev/null +++ b/src-tauri/src/services/office_zip.rs @@ -0,0 +1,47 @@ +//! ZIP tabanlı ofis paketleri (DOCX/ODT/XLSX/PPTX) için ortak okuyucu. + +use std::fs::File; +use std::io::Read; +use std::path::Path; + +use zip::ZipArchive; + +use crate::error::{AppError, AppResult}; + +pub struct Package { + archive: ZipArchive, +} + +impl Package { + pub fn open(path: &Path) -> AppResult { + let file = File::open(path)?; + let archive = ZipArchive::new(file) + .map_err(|e| AppError::Archive(format!("Paket açılamadı: {}", e)))?; + Ok(Self { archive }) + } + + pub fn read(&mut self, name: &str) -> Option> { + let mut entry = self.archive.by_name(name).ok()?; + let mut buffer = Vec::new(); + entry.read_to_end(&mut buffer).ok()?; + Some(buffer) + } + + pub fn read_string(&mut self, name: &str) -> Option { + self.read(name) + .map(|bytes| String::from_utf8_lossy(&bytes).to_string()) + } + + pub fn names(&self) -> Vec { + (0..self.archive.len()) + .filter_map(|index| self.archive.name_for_index(index).map(String::from)) + .collect() + } +} + +/// Resim uzantısına göre MIME/format tespiti zaten `ImageFormat` içinde. +pub fn read_xml_attributes(node: roxmltree::Node, name: &str) -> Option { + node.attributes() + .find(|attribute| attribute.name() == name) + .map(|attribute| attribute.value().to_string()) +} diff --git a/src-tauri/src/services/omml.rs b/src-tauri/src/services/omml.rs new file mode 100644 index 0000000..93e06d9 --- /dev/null +++ b/src-tauri/src/services/omml.rs @@ -0,0 +1,1625 @@ +//! Saf Rust LaTeX -> MathML -> Word OMML (``) dönüştürücü motor. +//! +//! Microsoft'un `MML2OMML.XSL` kurallarını harici Python / XSLT / Pandoc süreci +//! başlatmadan doğrudan bellek içinde uygular. + +use std::collections::HashMap; +use std::sync::OnceLock; + +use roxmltree::Node; + +use crate::error::{AppError, AppResult}; + +const UNIMATH_SYMBOLS: &str = include_str!("../../../tools/unimathsymbols.txt"); + +fn unimath_map() -> &'static HashMap { + static TABLE: OnceLock> = OnceLock::new(); + TABLE.get_or_init(|| { + let mut map = HashMap::with_capacity(2048); + for line in UNIMATH_SYMBOLS.lines() { + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed.starts_with('#') { + continue; + } + let parts: Vec<&str> = line.split('^').collect(); + let Some(hex_cp) = parts.first().map(|s| s.trim()) else { + continue; + }; + let Ok(cp) = u32::from_str_radix(hex_cp, 16) else { + continue; + }; + let Some(ch) = char::from_u32(cp) else { + continue; + }; + let ch_str = ch.to_string(); + let category = parts.get(5).map(|s| s.trim()).unwrap_or(""); + let tag = if category == "mathalpha" { "mi" } else { "mo" }; + + for idx in [2usize, 3usize] { + if let Some(cmd_raw) = parts.get(idx).map(|s| s.trim()) { + if let Some(cmd) = cmd_raw.strip_prefix('\\') { + if !cmd.is_empty() + && !cmd.contains('{') + && !cmd.contains(' ') + && !map.contains_key(cmd) + { + map.insert(cmd.to_string(), (tag, ch_str.clone())); + } + } + } + } + } + map + }) +} + +const OMML_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/math"; + +/// N-ary (büyük işleç) karakter listesi — MML2OMML.XSL `isNaryOper` ile birebir uyumlu. +fn is_nary_char(ch: &str) -> bool { + matches!( + ch.trim(), + "∫" | "∬" | "∭" | "∮" | "∯" | "∰" | "∱" | "∲" | "∳" | "∩" | "∪" | "∏" | "∐" | "∑" + | "⋀" | "⋁" | "⋂" | "⋃" | "⨁" | "⨂" | "⨀" | "⨄" | "⨆" + ) +} + +/// Standart matematik fonksiyon isimleri (düz/dik font ile yazılır). +fn is_known_function(name: &str) -> bool { + matches!( + name.trim(), + "sin" | "cos" | "tan" | "cot" | "sec" | "csc" + | "arcsin" | "arccos" | "arctan" + | "sinh" | "cosh" | "tanh" | "coth" + | "log" | "ln" | "lg" | "exp" + | "lim" | "limsup" | "liminf" | "sup" | "inf" + | "max" | "min" | "arg" | "det" | "dim" | "gcd" | "hom" | "ker" | "Pr" | "deg" + ) +} + +/// Non-combining aksan karakterlerini OMML `` +/// birleştirici (combining) karşılıklarına dönüştürür (`MML2OMML.XSL` `ToUpperCombining`). +fn to_combining_accent(ch: &str) -> Option<&'static str> { + match ch.trim() { + "^" | "ˆ" | "\u{0302}" => Some("\u{0302}"), // hat / circumflex + "~" | "˜" | "\u{0303}" => Some("\u{0303}"), // tilde + "." | "˙" | "\u{0307}" => Some("\u{0307}"), // dot + "¨" | ".." | "\u{0308}" => Some("\u{0308}"), // ddot / diaeresis + "˘" | "\u{0306}" => Some("\u{0306}"), // breve + "ˇ" | "\u{030C}" => Some("\u{030C}"), // check / caron + "´" | "\u{0301}" => Some("\u{0301}"), // acute + "`" | "\u{0300}" => Some("\u{0300}"), // grave + "→" | "⟶" | "\u{20D7}" => Some("\u{20D7}"), // vec (right arrow) + "←" | "\u{20D6}" => Some("\u{20D6}"), // left arrow + "↔" | "\u{20E1}" => Some("\u{20E1}"), // overleftrightarrow + _ => None, + } +} + +fn is_overbar_char(ch: &str) -> bool { + matches!(ch.trim(), "¯" | "‾" | "\u{0304}" | "\u{0305}" | "─" | "-") +} + +fn is_underbar_char(ch: &str) -> bool { + matches!(ch.trim(), "_" | "\u{0332}" | "\u{0333}" | "‾") +} + +fn is_group_brace_char(ch: &str) -> bool { + matches!(ch.trim(), "⏟" | "⏞" | "︸" | "︷" | "⎵" | "⎴") +} + +/// LaTeX metnini `latex2mathml` / OMML uyumlu hale getirir. +pub fn preprocess_latex(raw: &str) -> String { + let mut s = raw.trim().to_string(); + if ((s.starts_with("$$") && s.ends_with("$$")) + || (s.starts_with("\\[") && s.ends_with("\\]")) + || (s.starts_with("\\(") && s.ends_with("\\)"))) + && s.len() >= 4 + { + s = s[2..s.len() - 2].trim().to_string(); + } else if s.starts_with('$') && s.ends_with('$') && s.len() >= 2 { + s = s[1..s.len() - 1].trim().to_string(); + } + + // Yaygın LaTeX eşanlamlılarını normalize et + s = s + .replace("\\dfrac", "\\frac") + .replace("\\tfrac", "\\frac") + .replace("\\cfrac", "\\frac") + .replace("\\dbinom", "\\binom") + .replace("\\tbinom", "\\binom") + .replace("\\implies", "\\Rightarrow") + .replace("\\iff", "\\Leftrightarrow") + .replace("\\gets", "\\leftarrow") + .replace("\\leqslant", "\\le") + .replace("\\geqslant", "\\ge") + .replace("\\ne ", "\\neq ") + .replace("\\,", "\\;"); + s +} + +/// LaTeX formülünü doğrudan geçerli Word OMML (`` veya ``) XML'ine çevirir. +pub fn latex_to_omml(latex: &str, is_display: bool) -> AppResult { + let cleaned = preprocess_latex(latex); + if cleaned.is_empty() { + return Err(AppError::Engine("Boş LaTeX formülü".to_string())); + } + + let mathml = latex_to_mathml_with_fallback(&cleaned, is_display)?; + mathml_to_omml(&mathml, is_display) +} + +/// LaTeX -> Presentation MathML dönüşümü. +/// Önce genişletilmiş LaTeX özelliklerini (`\underbrace`, `\overbrace`, `\ddot`, `\sqrt[n]`, +/// `\binom`, `\begin{pmatrix|bmatrix|...}`) güvenli şekilde destekler; `latex2mathml` +/// başarısız olursa yerleşik dayanıklı parser devreye girer. +pub fn latex_to_mathml_with_fallback(latex: &str, is_display: bool) -> AppResult { + let needs_custom_parser = contains_extended_latex(latex); + if !needs_custom_parser { + let style = if is_display { + latex2mathml::DisplayStyle::Block + } else { + latex2mathml::DisplayStyle::Inline + }; + if let Ok(mml) = latex2mathml::latex_to_mathml(latex, style) { + if roxmltree::Document::parse(&mml).is_ok() { + return Ok(mml); + } + } + } + + // Genişletilmiş yapılar veya latex2mathml yedeği için kendi recursive-descent LaTeX->MathML motorumuz + let inner = parse_latex_to_mathml_nodes(latex); + let display_attr = if is_display { " display=\"block\"" } else { "" }; + let mml = format!( + "{}", + display_attr, inner + ); + if roxmltree::Document::parse(&mml).is_ok() { + return Ok(mml); + } + + // Son güvenlik: metni mtext içine al + Ok(format!( + "{}", + display_attr, + escape_xml(latex) + )) +} + +fn contains_extended_latex(latex: &str) -> bool { + if latex.contains('_') && latex.contains('^') { + return true; + } + [ + "\\underbrace", + "\\overbrace", + "\\ddot", + "\\dot", + "\\widehat", + "\\widetilde", + "\\overline", + "\\underline", + "\\binom", + "\\begin{", + "\\operatorname", + "\\overset", + "\\underset", + "\\sqrt[", + "\\text{", + "\\textbf{", + "\\textit{", + "\\mathrm{", + "\\mathbf{", + ] + .iter() + .any(|kw| latex.contains(kw)) +} + +/// MathML XML metnini Word OOXML OMML (`` veya ``) çıktısına dönüştürür. +pub fn mathml_to_omml(mathml: &str, is_display: bool) -> AppResult { + let doc = roxmltree::Document::parse(mathml) + .map_err(|e| AppError::Engine(format!("MathML ayrıştırılamadı: {}", e)))?; + + let root = doc.root_element(); + let display_attr = attr(&root, "display").unwrap_or_default(); + let use_para = is_display || display_attr.eq_ignore_ascii_case("block"); + + let children: Vec = element_children(root); + let inner = convert_node_sequence(&children); + + let omath = format!("{}", OMML_NS, inner); + if use_para { + Ok(format!( + "{}", + OMML_NS, omath + )) + } else { + Ok(omath) + } +} + +fn element_children<'a, 'input>(node: Node<'a, 'input>) -> Vec> { + node.children().filter(|c| c.is_element()).collect() +} + +fn attr<'a>(node: &Node<'a, '_>, name: &str) -> Option<&'a str> { + node.attributes() + .find(|a| a.name() == name) + .map(|a| a.value()) +} + +fn tag_name<'a>(node: &Node<'a, '_>) -> &'a str { + node.tag_name().name() +} + +fn collect_plain_text(node: Node) -> String { + let mut out = String::new(); + for desc in node.descendants() { + if desc.is_text() { + if let Some(t) = desc.text() { + out.push_str(t); + } + } + } + out +} + +/// Bir düğüm grubunu (kardeş eleman listesi) sırayla OMML'e dönüştürür. +/// N-ary operatörler, kesir/parantez ayraçları ve birleşik run'lar burada ele alınır. +fn convert_node_sequence(nodes: &[Node]) -> String { + if nodes.is_empty() { + return String::new(); + } + + // Doğrusal kesir (A/B) kontrolü + if nodes.len() == 3 + && tag_name(&nodes[1]) == "mo" + && collect_plain_text(nodes[1]).trim() == "/" + { + return format!( + "{}{}", + convert_single_node(nodes[0]), + convert_single_node(nodes[2]) + ); + } + + let mut out = String::new(); + let mut i = 0usize; + while i < nodes.len() { + let node = nodes[i]; + let name = tag_name(&node); + + // N-ary operatörü içeren script düğümü mü? + if matches!( + name, + "msub" | "msup" | "msubsup" | "munder" | "mover" | "munderover" + ) { + if let Some(nary_char) = extract_nary_operator(node) { + let (omml_nary, consumed) = convert_nary_node(node, &nary_char, &nodes[i + 1..]); + out.push_str(&omml_nary); + i += 1 + consumed; + continue; + } + } + + // Çıplak N-ary operatörü (∫ veya ∑) varsa: sadece tek ya da m:nary + // (alt/üst sınırı olmayan n-ary için MML2OMML'de veya Word'de doğrudan karakter/nary kullanılabilir; + // burada tekil varsa normal run olarak veya nary olarak çıkarılır) + + // içinde açılış/kapanış ayracı olan yapı mı? (örn: ( ... ) veya [ ... ] veya | ... |) + // Not: Açılış ayracı stretchy ve karşılığında kapanış ayracı varsa üretiriz + if name == "mo" && is_stretchy_open(node) { + if let Some((close_idx, open_ch, close_ch)) = find_matching_delimiter(nodes, i) { + if close_idx > i { + let inner_nodes = &nodes[i + 1..close_idx]; + let inner_omml = convert_node_sequence(inner_nodes); + out.push_str(&build_delim_omml(&open_ch, &close_ch, ",", &[inner_omml])); + i = close_idx + 1; + continue; + } + } + } + + out.push_str(&convert_single_node(node)); + i += 1; + } + + out +} + +fn is_stretchy_open(node: Node) -> bool { + let txt = collect_plain_text(node).trim().to_string(); + let stretchy = attr(&node, "stretchy").unwrap_or("true"); + if stretchy.eq_ignore_ascii_case("false") { + return false; + } + matches!(txt.as_str(), "(" | "[" | "{" | "|" | "‖" | "⟨" | "⌊" | "⌈") +} + +fn matching_close_delimiter(open: &str) -> Option<&'static str> { + match open { + "(" => Some(")"), + "[" => Some("]"), + "{" => Some("}"), + "|" => Some("|"), + "‖" => Some("‖"), + "⟨" => Some("⟩"), + "⌊" => Some("⌋"), + "⌈" => Some("⌉"), + _ => None, + } +} + +fn find_matching_delimiter(nodes: &[Node], start_idx: usize) -> Option<(usize, String, String)> { + let open_ch = collect_plain_text(nodes[start_idx]).trim().to_string(); + let expected_close = matching_close_delimiter(&open_ch)?; + // İçeride yalnızca mtable veya yüksek yapı (mfrac/mroot/munder/mover) varsa ya da + // açıkça stretchy delim ise oluştur; basit (x+1) gibi küçük ifadelerde de Word'de mükemmeldir. + let mut depth = 0i32; + for (idx, n) in nodes.iter().enumerate().skip(start_idx) { + if tag_name(n) == "mo" { + let t = collect_plain_text(*n); + let trimmed = t.trim(); + if open_ch == expected_close { + if idx == start_idx { + depth = 1; + } else if trimmed == expected_close { + return Some((idx, open_ch, expected_close.to_string())); + } + } else if trimmed == open_ch { + depth += 1; + } else if trimmed == expected_close { + depth -= 1; + if depth == 0 { + return Some((idx, open_ch, expected_close.to_string())); + } + } + } + } + None +} + +fn build_delim_omml(open: &str, close: &str, sep: &str, elements: &[String]) -> String { + let mut dpr = String::new(); + if open != "(" { + dpr.push_str(&format!("", escape_xml(open))); + } + if sep != "|" && !sep.is_empty() { + dpr.push_str(&format!("", escape_xml(sep))); + } + if close != ")" { + dpr.push_str(&format!("", escape_xml(close))); + } + let dpr_xml = if dpr.is_empty() { + String::new() + } else { + format!("{}", dpr) + }; + let mut bodies = String::new(); + if elements.is_empty() { + bodies.push_str(""); + } else { + for el in elements { + bodies.push_str(&format!("{}", el)); + } + } + format!("{}{}", dpr_xml, bodies) +} + +/// Düğümün birinci çocuğu N-ary operatörü mü kontrol eder. +fn extract_nary_operator(node: Node) -> Option { + let children = element_children(node); + let first = *children.first()?; + if first_is_accent_parent(node) { + return None; + } + let op = extract_pure_mo_text(first)?; + if is_nary_char(&op) { + Some(op) + } else { + None + } +} + +fn first_is_accent_parent(node: Node) -> bool { + let name = tag_name(&node); + if name == "munder" { + return attr(&node, "accentunder") + .map(|v| v.eq_ignore_ascii_case("true")) + .unwrap_or(false); + } + if name == "mover" { + return attr(&node, "accent") + .map(|v| v.eq_ignore_ascii_case("true")) + .unwrap_or(false); + } + false +} + +fn extract_pure_mo_text(node: Node) -> Option { + match tag_name(&node) { + "mo" => { + let t = collect_plain_text(node).trim().to_string(); + if t.is_empty() { + None + } else { + Some(t) + } + } + "mrow" | "mstyle" => { + let children = element_children(node); + if children.len() == 1 { + extract_pure_mo_text(children[0]) + } else { + None + } + } + _ => None, + } +} + +fn is_nary_boundary_operator(node: Node) -> bool { + if tag_name(&node) != "mo" { + return false; + } + let txt = collect_plain_text(node); + matches!( + txt.trim(), + "=" | "≠" | "<" | ">" | "≤" | "≥" | "≈" | "≡" | "∝" | "∈" | "∉" | "⊂" | "⊃" + | "⇒" | "⇔" | "→" | "←" | "↔" | "+" | "-" | "−" | "±" | "∓" | "," | ";" | ")" | "]" | "}" + ) +} + +/// N-ary düğümünü (``) üretir ve sağındaki gövde (``) için kaç kardeş düğüm +/// tüketildiğini döndürür. +fn convert_nary_node(node: Node, chr: &str, following: &[Node]) -> (String, usize) { + let name = tag_name(&node); + let children = element_children(node); + let lim_loc = match name { + "munder" | "mover" | "munderover" => "undOvr", + _ => "subSup", + }; + + let (sub_omml, sup_omml, sub_hide, sup_hide) = match name { + "msub" | "munder" => { + let s = children + .get(1) + .map(|n| convert_single_node(*n)) + .unwrap_or_default(); + (s, String::new(), "off", "on") + } + "msup" | "mover" => { + let p = children + .get(1) + .map(|n| convert_single_node(*n)) + .unwrap_or_default(); + (String::new(), p, "on", "off") + } + "msubsup" | "munderover" => { + let s = children + .get(1) + .map(|n| convert_single_node(*n)) + .unwrap_or_default(); + let p = children + .get(2) + .map(|n| convert_single_node(*n)) + .unwrap_or_default(); + (s, p, "off", "off") + } + _ => (String::new(), String::new(), "on", "on"), + }; + + let grow = if matches!( + chr, + "∫" | "∮" | "∯" | "∲" | "∳" | "∩" | "∪" | "∏" | "∑" | "⋀" | "⋁" | "⋂" | "⋃" + ) { + "1" + } else { + "0" + }; + + // Takip eden kardeş düğümleri analiz et: + // Eğer ilk kardeş veya ise MML2OMML.XSL gibi doğrudan onu tüket. + // Aksi halde bir sınır operatörüne (=, +, -, vb.) kadar olan gövde terimlerini tüket. + let (body_omml, consumed) = if following.is_empty() { + (String::new(), 0) + } else if matches!(tag_name(&following[0]), "mrow" | "mstyle") { + (convert_single_node(following[0]), 1) + } else { + let mut take = 0usize; + while take < following.len() { + let sib = following[take]; + if is_nary_boundary_operator(sib) { + break; + } + take += 1; + } + if take == 0 { + (String::new(), 0) + } else { + (convert_node_sequence(&following[..take]), take) + } + }; + + let xml = format!( + "\ + \ + \ + \ + \ + \ + \ + \ + {sub_omml}\ + {sup_omml}\ + {body_omml}\ + ", + chr = escape_xml(chr), + lim_loc = lim_loc, + grow = grow, + sub_hide = sub_hide, + sup_hide = sup_hide, + sub_omml = sub_omml, + sup_omml = sup_omml, + body_omml = body_omml, + ); + + (xml, consumed) +} + +fn convert_single_node(node: Node) -> String { + let name = tag_name(&node); + let children = element_children(node); + + match name { + "math" | "mrow" | "mstyle" | "mpadded" | "merror" | "maction" => { + // Eğer mrow: a / b değil ve + // başında açılış sonunda kapanış ayracı varsa (veya tek bir matris/kesir sarmalıyorsa) + if name == "mrow" && children.len() >= 2 { + let first_op = if tag_name(&children[0]) == "mo" { + Some(collect_plain_text(children[0]).trim().to_string()) + } else { + None + }; + let last_op = if tag_name(&children[children.len() - 1]) == "mo" { + Some(collect_plain_text(children[children.len() - 1]).trim().to_string()) + } else { + None + }; + if let (Some(open), Some(close)) = (first_op, last_op) { + if matching_close_delimiter(&open) == Some(close.as_str()) + && is_stretchy_open(children[0]) + { + let mid = convert_node_sequence(&children[1..children.len() - 1]); + return build_delim_omml(&open, &close, ",", &[mid]); + } + } + } + convert_node_sequence(&children) + } + + "mfrac" => { + let num = children + .first() + .map(|n| convert_single_node(*n)) + .unwrap_or_default(); + let den = children + .get(1) + .map(|n| convert_single_node(*n)) + .unwrap_or_default(); + let thickness = attr(&node, "linethickness").unwrap_or(""); + let bevelled = attr(&node, "bevelled").unwrap_or(""); + let frac_type = if thickness == "0" || thickness == "0px" || thickness == "0pt" { + "noBar" + } else if bevelled.eq_ignore_ascii_case("true") { + "skw" + } else { + "bar" + }; + format!( + "{}{}", + frac_type, num, den + ) + } + + "msqrt" => { + let inner = convert_node_sequence(&children); + format!( + "{}", + inner + ) + } + + "mroot" => { + let base = children + .first() + .map(|n| convert_single_node(*n)) + .unwrap_or_default(); + let deg = children + .get(1) + .map(|n| convert_single_node(*n)) + .unwrap_or_default(); + format!( + "{}{}", + deg, base + ) + } + + "menclose" => { + let notation = attr(&node, "notation").unwrap_or("box").to_ascii_lowercase(); + let inner = convert_node_sequence(&children); + if notation == "radical" { + format!( + "{}", + inner + ) + } else { + let mut pr = String::new(); + if notation.contains("horizontalstrike") { + pr.push_str(""); + } + if notation.contains("verticalstrike") { + pr.push_str(""); + } + if pr.is_empty() { + format!("{}", inner) + } else { + format!( + "{}{}", + pr, inner + ) + } + } + } + + "msub" => { + if let Some(nary) = extract_nary_operator(node) { + return convert_nary_node(node, &nary, &[]).0; + } + let base = children.first().map(|n| convert_single_node(*n)).unwrap_or_default(); + let sub = children.get(1).map(|n| convert_single_node(*n)).unwrap_or_default(); + format!("{}{}", base, sub) + } + + "msup" => { + if let Some(nary) = extract_nary_operator(node) { + return convert_nary_node(node, &nary, &[]).0; + } + let base = children.first().map(|n| convert_single_node(*n)).unwrap_or_default(); + let sup = children.get(1).map(|n| convert_single_node(*n)).unwrap_or_default(); + format!("{}{}", base, sup) + } + + "msubsup" => { + if let Some(nary) = extract_nary_operator(node) { + return convert_nary_node(node, &nary, &[]).0; + } + let base = children.first().map(|n| convert_single_node(*n)).unwrap_or_default(); + let sub = children.get(1).map(|n| convert_single_node(*n)).unwrap_or_default(); + let sup = children.get(2).map(|n| convert_single_node(*n)).unwrap_or_default(); + format!( + "{}{}{}", + base, sub, sup + ) + } + + "munder" => convert_munder(node, &children), + "mover" => convert_mover(node, &children), + "munderover" => { + if let Some(nary) = extract_nary_operator(node) { + return convert_nary_node(node, &nary, &[]).0; + } + let base = children.first().map(|n| convert_single_node(*n)).unwrap_or_default(); + let under = children.get(1).map(|n| convert_single_node(*n)).unwrap_or_default(); + let over = children.get(2).map(|n| convert_single_node(*n)).unwrap_or_default(); + format!( + "{}{}{}", + base, under, over + ) + } + + "mfenced" => { + let open = attr(&node, "open").unwrap_or("("); + let close = attr(&node, "close").unwrap_or(")"); + let sep = attr(&node, "separators").unwrap_or(","); + let first_sep = sep.chars().next().map(|c| c.to_string()).unwrap_or_else(|| ",".to_string()); + let elems: Vec = children.iter().map(|c| convert_single_node(*c)).collect(); + build_delim_omml(open, close, &first_sep, &elems) + } + + "mtable" => convert_mtable(node, &children), + "mtr" | "mtd" => convert_node_sequence(&children), + + "mphantom" => { + let inner = convert_node_sequence(&children); + format!( + "{}", + inner + ) + } + + "mspace" => " ".to_string(), + + "mi" | "mn" | "mo" | "mtext" | "ms" => convert_token(node, name), + + "mmultiscripts" => convert_mmultiscripts(&children), + + _ => convert_node_sequence(&children), + } +} + +fn convert_munder(node: Node, children: &[Node]) -> String { + if let Some(nary) = extract_nary_operator(node) { + return convert_nary_node(node, &nary, &[]).0; + } + + let first = children.first().copied(); + let second = children.get(1).copied(); + + // 1) Alt çizgi () + if let (Some(base), Some(op_node)) = (first, second) { + if let Some(op) = extract_pure_mo_text(op_node) { + if is_underbar_char(&op) { + return format!( + "{}", + convert_single_node(base) + ); + } + // 2) Alt süslü parantez (underbrace) -> + if is_group_brace_char(&op) { + // İçinde bir munder(base, ⏟) yapısı olabilir: dışta etiket varsa limLow içinde sarılır + return format!( + "{}", + escape_xml(&op), + convert_single_node(base) + ); + } + } + // Özel durum: A⏟lbl + if tag_name(&base) == "munder" { + let inner_children = element_children(base); + if inner_children.len() == 2 { + if let Some(op) = extract_pure_mo_text(inner_children[1]) { + if is_group_brace_char(&op) { + let group_xml = format!( + "{}", + escape_xml(&op), + convert_single_node(inner_children[0]) + ); + return format!( + "{}{}", + group_xml, + convert_single_node(op_node) + ); + } + } + } + } + } + + let base_omml = first.map(convert_single_node).unwrap_or_default(); + let lim_omml = second.map(convert_single_node).unwrap_or_default(); + format!( + "{}{}", + base_omml, lim_omml + ) +} + +fn convert_mover(node: Node, children: &[Node]) -> String { + if let Some(nary) = extract_nary_operator(node) { + return convert_nary_node(node, &nary, &[]).0; + } + + let first = children.first().copied(); + let second = children.get(1).copied(); + + if let (Some(base), Some(op_node)) = (first, second) { + let op_text = extract_pure_mo_text(op_node) + .unwrap_or_else(|| collect_plain_text(op_node).trim().to_string()); + // 1) Üst çizgi () + if is_overbar_char(&op_text) { + return format!( + "{}", + convert_single_node(base) + ); + } + // 2) Aksan () — \hat, \dot, \ddot, \tilde, \vec + if let Some(comb) = to_combining_accent(&op_text) { + return format!( + "{}", + escape_xml(comb), + convert_single_node(base) + ); + } + // 3) Üst süslü parantez (overbrace) -> + if is_group_brace_char(&op_text) { + return format!( + "{}", + escape_xml(&op_text), + convert_single_node(base) + ); + } + // Dışta etiket sarmalayan overbrace: A⏞lbl + if tag_name(&base) == "mover" { + let inner_children = element_children(base); + if inner_children.len() == 2 { + if let Some(op) = extract_pure_mo_text(inner_children[1]) { + if is_group_brace_char(&op) { + let group_xml = format!( + "{}", + escape_xml(&op), + convert_single_node(inner_children[0]) + ); + return format!( + "{}{}", + group_xml, + convert_single_node(op_node) + ); + } + } + } + } + } + + let base_omml = first.map(convert_single_node).unwrap_or_default(); + let lim_omml = second.map(convert_single_node).unwrap_or_default(); + format!( + "{}{}", + base_omml, lim_omml + ) +} + +fn convert_mtable(_node: Node, children: &[Node]) -> String { + let mut rows: Vec> = Vec::new(); + let mut max_cols = 1usize; + + for row_node in children { + let rname = tag_name(row_node); + if rname == "mtr" || rname == "mlabeledtr" { + let cells = element_children(*row_node); + let skip = usize::from(rname == "mlabeledtr"); + let mut row_cells = Vec::new(); + for cell in cells.into_iter().skip(skip) { + row_cells.push(convert_single_node(cell)); + } + max_cols = max_cols.max(row_cells.len()); + rows.push(row_cells); + } else { + rows.push(vec![convert_single_node(*row_node)]); + } + } + + let mut out = format!( + "", + max_cols + ); + + for row in rows { + out.push_str(""); + for cell in &row { + out.push_str(&format!("{}", cell)); + } + for _ in row.len()..max_cols { + out.push_str(""); + } + out.push_str(""); + } + + out.push_str(""); + out +} + +fn convert_mmultiscripts(children: &[Node]) -> String { + if children.is_empty() { + return String::new(); + } + let base = convert_single_node(children[0]); + let prescript_pos = children + .iter() + .position(|c| tag_name(c) == "mprescripts"); + + let post_end = prescript_pos.unwrap_or(children.len()); + let mut post_sub = String::new(); + let mut post_sup = String::new(); + let mut idx = 1usize; + while idx < post_end { + if tag_name(&children[idx]) != "none" { + post_sub.push_str(&convert_single_node(children[idx])); + } + if idx + 1 < post_end && tag_name(&children[idx + 1]) != "none" { + post_sup.push_str(&convert_single_node(children[idx + 1])); + } + idx += 2; + } + + let post_omml = match (!post_sub.is_empty(), !post_sup.is_empty()) { + (true, true) => format!( + "{}{}{}", + base, post_sub, post_sup + ), + (true, false) => format!("{}{}", base, post_sub), + (false, true) => format!("{}{}", base, post_sup), + (false, false) => base, + }; + + if let Some(pos) = prescript_pos { + let mut pre_sub = String::new(); + let mut pre_sup = String::new(); + let mut p = pos + 1; + while p < children.len() { + if tag_name(&children[p]) != "none" { + pre_sub.push_str(&convert_single_node(children[p])); + } + if p + 1 < children.len() && tag_name(&children[p + 1]) != "none" { + pre_sup.push_str(&convert_single_node(children[p + 1])); + } + p += 2; + } + if !pre_sub.is_empty() || !pre_sup.is_empty() { + return format!( + "{}{}{}", + post_omml, pre_sub, pre_sup + ); + } + } + + post_omml +} + +fn convert_token(node: Node, tag: &str) -> String { + let mut text = collect_plain_text(node) + .replace(['\u{2062}', '\u{200B}'], "") // görünmez çarpma ve sıfır genişlikli boşluk + .replace('\u{00A0}', " "); + + if tag == "ms" { + let lq = attr(&node, "lquote").unwrap_or("\""); + let rq = attr(&node, "rquote").unwrap_or("\""); + text = format!("{}{}{}", lq, text, rq); + } + + if text.is_empty() { + return String::new(); + } + + let mathvariant = attr(&node, "mathvariant").unwrap_or(""); + let is_plain_style = match tag { + "mtext" | "ms" => true, + "mn" | "mo" => true, + "mi" => { + mathvariant == "normal" + || text.chars().count() > 1 + || is_known_function(&text) + } + _ => false, + }; + + let mut rpr = String::new(); + if tag == "mtext" || tag == "ms" { + rpr.push_str(""); + } + match mathvariant { + "bold" => rpr.push_str(""), + "bold-italic" => rpr.push_str(""), + "script" => rpr.push_str(""), + "double-struck" => rpr.push_str(""), + "fraktur" => rpr.push_str(""), + "sans-serif" => rpr.push_str(""), + "normal" if tag != "mtext" && tag != "ms" => rpr.push_str(""), + _ => { + if is_plain_style && tag != "mtext" && tag != "ms" { + rpr.push_str(""); + } + } + } + + let rpr_xml = if rpr.is_empty() { + String::new() + } else { + format!("{}", rpr) + }; + + let space_attr = if text.starts_with(' ') || text.ends_with(' ') { + " xml:space=\"preserve\"" + } else { + "" + }; + + format!( + "{}{}", + rpr_xml, + space_attr, + escape_xml(&text) + ) +} + +pub fn escape_xml(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for ch in s.chars() { + match ch { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + other => out.push(other), + } + } + out +} + +// =========================================================================== +// Yerleşik Genişletilmiş LaTeX -> Presentation MathML Parser (Fallback + Ek Makrolar) +// =========================================================================== + +struct LatexParser<'a> { + chars: Vec, + pos: usize, + _marker: std::marker::PhantomData<&'a str>, +} + +fn parse_latex_to_mathml_nodes(input: &str) -> String { + let mut parser = LatexParser { + chars: input.chars().collect(), + pos: 0, + _marker: std::marker::PhantomData, + }; + parser.parse_sequence(None) +} + +impl<'a> LatexParser<'a> { + fn peek(&self) -> Option { + self.chars.get(self.pos).copied() + } + + fn next(&mut self) -> Option { + let ch = self.chars.get(self.pos).copied()?; + self.pos += 1; + Some(ch) + } + + fn skip_whitespace(&mut self) { + while let Some(c) = self.peek() { + if c.is_whitespace() { + self.pos += 1; + } else { + break; + } + } + } + + fn starts_with_str(&self, target: &str) -> bool { + let target_chars: Vec = target.chars().collect(); + if self.pos + target_chars.len() > self.chars.len() { + return false; + } + self.chars[self.pos..self.pos + target_chars.len()] == target_chars[..] + } + + fn read_command_name(&mut self) -> String { + let mut name = String::new(); + while let Some(c) = self.peek() { + if c.is_ascii_alphabetic() { + name.push(c); + self.pos += 1; + } else { + break; + } + } + if name.is_empty() { + if let Some(c) = self.next() { + name.push(c); + } + } + name + } + + fn read_group_raw(&mut self) -> String { + self.skip_whitespace(); + if self.peek() == Some('{') { + self.pos += 1; + let mut out = String::new(); + let mut depth = 1usize; + while let Some(c) = self.next() { + if c == '{' { + depth += 1; + out.push(c); + } else if c == '}' { + depth -= 1; + if depth == 0 { + return out; + } + out.push(c); + } else if c == '\\' { + out.push(c); + if let Some(esc) = self.next() { + out.push(esc); + } + } else { + out.push(c); + } + } + out + } else if self.peek() == Some('\\') { + self.pos += 1; + format!("\\{}", self.read_command_name()) + } else { + self.next().map(|c| c.to_string()).unwrap_or_default() + } + } + + fn read_optional_bracket_raw(&mut self) -> Option { + self.skip_whitespace(); + if self.peek() != Some('[') { + return None; + } + self.pos += 1; + let mut out = String::new(); + let mut depth = 0usize; + while let Some(c) = self.next() { + if c == '{' { + depth += 1; + out.push(c); + } else if c == '}' { + depth = depth.saturating_sub(1); + out.push(c); + } else if c == ']' && depth == 0 { + return Some(out); + } else { + out.push(c); + } + } + Some(out) + } + + fn parse_group_as_mrow(&mut self) -> String { + let raw = self.read_group_raw(); + let inner = parse_latex_to_mathml_nodes(&raw); + if inner.is_empty() { + "".to_string() + } else { + format!("{}", inner) + } + } + + fn parse_sequence(&mut self, stop_at: Option<&str>) -> String { + let mut items: Vec = Vec::new(); + loop { + self.skip_whitespace(); + if let Some(stop) = stop_at { + if self.starts_with_str(stop) { + break; + } + } + let Some(ch) = self.peek() else { + break; + }; + if ch == '}' { + if stop_at.is_none() { + self.pos += 1; + } + break; + } + if ch == '&' || self.starts_with_str("\\\\") { + break; + } + if ch == '^' || ch == '_' { + // Tek başına kalmış script -> boş baz ile birleştir + let last_base = items.pop().unwrap_or_else(|| "".to_string()); + let combined = self.parse_scripts(last_base); + items.push(combined); + continue; + } + let atom = self.parse_atom(); + if !atom.is_empty() { + let with_scripts = self.parse_scripts(atom); + items.push(with_scripts); + } + } + items.join("") + } + + fn parse_scripts(&mut self, base: String) -> String { + let mut sub: Option = None; + let mut sup: Option = None; + loop { + self.skip_whitespace(); + match self.peek() { + Some('_') => { + self.pos += 1; + sub = Some(self.parse_group_as_mrow()); + } + Some('^') => { + self.pos += 1; + sup = Some(self.parse_group_as_mrow()); + } + _ => break, + } + } + + let is_underover = base.contains(">∑<") + || base.contains(">∏<") + || base.contains(">lim<"); + + match (sub, sup) { + (Some(s), Some(p)) => { + if is_underover { + format!("{}{}{}", base, s, p) + } else { + format!("{}{}{}", base, s, p) + } + } + (Some(s), None) => { + if is_underover || base.contains("⏟") { + format!("{}{}", base, s) + } else { + format!("{}{}", base, s) + } + } + (None, Some(p)) => { + if is_underover || base.contains("⏞") { + format!("{}{}", base, p) + } else { + format!("{}{}", base, p) + } + } + (None, None) => base, + } + } + + fn parse_atom(&mut self) -> String { + self.skip_whitespace(); + let Some(ch) = self.peek() else { + return String::new(); + }; + + if ch == '{' { + return self.parse_group_as_mrow(); + } + + if ch == '\\' { + self.pos += 1; + let cmd = self.read_command_name(); + return self.parse_command(&cmd); + } + + if ch.is_ascii_digit() { + let mut num = String::new(); + while let Some(d) = self.peek() { + if d.is_ascii_digit() || d == '.' { + num.push(d); + self.pos += 1; + } else { + break; + } + } + return format!("{}", escape_xml(&num)); + } + + if ch.is_alphabetic() { + self.pos += 1; + return format!("{}", escape_xml(&ch.to_string())); + } + + self.pos += 1; + let mapped = match ch { + '-' => "−".to_string(), + '*' => "⋅".to_string(), + other => other.to_string(), + }; + format!("{}", escape_xml(&mapped)) + } + + fn parse_command(&mut self, cmd: &str) -> String { + match cmd { + "frac" | "dfrac" | "tfrac" | "cfrac" => { + let num = self.parse_group_as_mrow(); + let den = self.parse_group_as_mrow(); + format!("{}{}", num, den) + } + "binom" | "dbinom" | "tbinom" => { + let num = self.parse_group_as_mrow(); + let den = self.parse_group_as_mrow(); + format!( + "{}{}", + num, den + ) + } + "sqrt" => { + let opt = self.read_optional_bracket_raw(); + let body = self.parse_group_as_mrow(); + if let Some(deg) = opt { + let deg_mml = parse_latex_to_mathml_nodes(°); + format!("{}{}", body, deg_mml) + } else { + format!("{}", body) + } + } + "dot" => format!("{}\u{0307}", self.parse_group_as_mrow()), + "ddot" => format!("{}\u{0308}", self.parse_group_as_mrow()), + "hat" | "widehat" => format!("{}\u{0302}", self.parse_group_as_mrow()), + "tilde" | "widetilde" => format!("{}\u{0303}", self.parse_group_as_mrow()), + "bar" | "overline" => format!("{}\u{0305}", self.parse_group_as_mrow()), + "underline" => format!("{}\u{0332}", self.parse_group_as_mrow()), + "vec" => format!("{}\u{20D7}", self.parse_group_as_mrow()), + "underbrace" => { + let body = self.parse_group_as_mrow(); + format!("{}⏟", body) + } + "overbrace" => { + let body = self.parse_group_as_mrow(); + format!("{}⏞", body) + } + "underset" => { + let under = self.parse_group_as_mrow(); + let base = self.parse_group_as_mrow(); + format!("{}{}", base, under) + } + "overset" => { + let over = self.parse_group_as_mrow(); + let base = self.parse_group_as_mrow(); + format!("{}{}", base, over) + } + "text" | "textbf" | "textit" => { + let txt = self.read_group_raw(); + format!("{}", escape_xml(&txt)) + } + "mathrm" | "operatorname" => { + let txt = self.read_group_raw(); + format!("{}", escape_xml(&txt)) + } + "mathbf" | "boldsymbol" => { + let txt = self.read_group_raw(); + format!("{}", escape_xml(&txt)) + } + "mathbb" => { + let txt = self.read_group_raw(); + format!("{}", escape_xml(&txt)) + } + "mathcal" => { + let txt = self.read_group_raw(); + format!("{}", escape_xml(&txt)) + } + "left" => self.parse_left_right(), + "begin" => self.parse_environment(), + "," | ";" | ":" | " " | "quad" | "qquad" => { + "".to_string() + } + "!" => String::new(), + "{" => "{".to_string(), + "}" => "}".to_string(), + "|" => "‖".to_string(), + other => { + if let Some(sym) = latex_symbol_to_mathml(other) { + sym + } else if is_known_function(other) { + format!("{}", escape_xml(other)) + } else { + format!("{}", escape_xml(other)) + } + } + } + } + + fn read_delimiter(&mut self) -> String { + self.skip_whitespace(); + let Some(c) = self.next() else { + return String::new(); + }; + if c == '\\' { + let cmd = self.read_command_name(); + return match cmd.as_str() { + "{" => "{".to_string(), + "}" => "}".to_string(), + "|" => "‖".to_string(), + "langle" => "⟨".to_string(), + "rangle" => "⟩".to_string(), + "lfloor" => "⌊".to_string(), + "rfloor" => "⌋".to_string(), + "lceil" => "⌈".to_string(), + "rceil" => "⌉".to_string(), + _ => String::new(), + }; + } + if c == '.' { + String::new() + } else { + c.to_string() + } + } + + fn parse_left_right(&mut self) -> String { + let open = self.read_delimiter(); + let body = self.parse_sequence(Some("\\right")); + if self.starts_with_str("\\right") { + self.pos += "\\right".chars().count(); + } + let close = self.read_delimiter(); + format!( + "{}", + escape_xml(&open), + escape_xml(&close), + body + ) + } + + fn parse_environment(&mut self) -> String { + let env = self.read_group_raw(); + let end_marker = format!("\\end{{{}}}", env); + + let mut rows_xml = String::new(); + loop { + let mut cells_xml = String::new(); + loop { + let cell = self.parse_sequence(Some(&end_marker)); + cells_xml.push_str(&format!("{}", cell)); + self.skip_whitespace(); + if self.peek() == Some('&') { + self.pos += 1; + continue; + } + break; + } + rows_xml.push_str(&format!("{}", cells_xml)); + self.skip_whitespace(); + if self.starts_with_str("\\\\") { + self.pos += 2; + continue; + } + if self.starts_with_str(&end_marker) { + self.pos += end_marker.chars().count(); + break; + } + if self.peek().is_none() { + break; + } + } + + let table = format!("{}", rows_xml); + match env.trim() { + "pmatrix" => format!("{}", table), + "bmatrix" => format!("{}", table), + "Bmatrix" => format!("{}", table), + "vmatrix" => format!("{}", table), + "Vmatrix" => format!("{}", table), + "cases" => format!("{}", table), + _ => table, + } + } +} + +fn latex_symbol_to_mathml(cmd: &str) -> Option { + let (tag, ch) = match cmd { + // Büyük işleçler (N-ary) + "sum" => ("mo", "∑"), + "prod" => ("mo", "∏"), + "coprod" => ("mo", "∐"), + "int" => ("mo", "∫"), + "iint" => ("mo", "∬"), + "iiint" => ("mo", "∭"), + "oint" => ("mo", "∮"), + "bigcup" => ("mo", "⋃"), + "bigcap" => ("mo", "⋂"), + "bigvee" => ("mo", "⋁"), + "bigwedge" => ("mo", "⋀"), + "bigoplus" => ("mo", "⨁"), + "bigotimes" => ("mo", "⨂"), + + // Küçük Yunan harfleri + "alpha" => ("mi", "α"), + "beta" => ("mi", "β"), + "gamma" => ("mi", "γ"), + "delta" => ("mi", "δ"), + "epsilon" => ("mi", "ϵ"), + "varepsilon" => ("mi", "ε"), + "zeta" => ("mi", "ζ"), + "eta" => ("mi", "η"), + "theta" => ("mi", "θ"), + "vartheta" => ("mi", "ϑ"), + "iota" => ("mi", "ι"), + "kappa" => ("mi", "κ"), + "lambda" => ("mi", "λ"), + "mu" => ("mi", "μ"), + "nu" => ("mi", "ν"), + "xi" => ("mi", "ξ"), + "pi" => ("mi", "π"), + "varpi" => ("mi", "ϖ"), + "rho" => ("mi", "ρ"), + "varrho" => ("mi", "ϱ"), + "sigma" => ("mi", "σ"), + "varsigma" => ("mi", "ς"), + "tau" => ("mi", "τ"), + "upsilon" => ("mi", "υ"), + "phi" => ("mi", "ϕ"), + "varphi" => ("mi", "φ"), + "chi" => ("mi", "χ"), + "psi" => ("mi", "ψ"), + "omega" => ("mi", "ω"), + + // Büyük Yunan harfleri + "Gamma" => ("mi", "Γ"), + "Delta" => ("mi", "Δ"), + "Theta" => ("mi", "Θ"), + "Lambda" => ("mi", "Λ"), + "Xi" => ("mi", "Ξ"), + "Pi" => ("mi", "Π"), + "Sigma" => ("mi", "Σ"), + "Upsilon" => ("mi", "Υ"), + "Phi" => ("mi", "Φ"), + "Psi" => ("mi", "Ψ"), + "Omega" => ("mi", "Ω"), + + // Matematik sembolleri ve operatörler + "infty" => ("mi", "∞"), + "partial" => ("mi", "∂"), + "nabla" => ("mo", "∇"), + "hbar" => ("mi", "ℏ"), + "ell" => ("mi", "ℓ"), + "Re" => ("mi", "ℜ"), + "Im" => ("mi", "ℑ"), + "wp" => ("mi", "℘"), + "aleph" => ("mi", "ℵ"), + "emptyset" | "varnothing" => ("mi", "∅"), + "forall" => ("mo", "∀"), + "exists" => ("mo", "∃"), + "nexists" => ("mo", "∄"), + "in" => ("mo", "∈"), + "notin" => ("mo", "∉"), + "ni" => ("mo", "∋"), + "subset" => ("mo", "⊂"), + "supset" => ("mo", "⊃"), + "subseteq" => ("mo", "⊆"), + "supseteq" => ("mo", "⊇"), + "cup" => ("mo", "∪"), + "cap" => ("mo", "∩"), + "setminus" => ("mo", "∖"), + "cdot" => ("mo", "⋅"), + "times" => ("mo", "×"), + "div" => ("mo", "÷"), + "pm" => ("mo", "±"), + "mp" => ("mo", "∓"), + "circ" => ("mo", "∘"), + "bullet" => ("mo", "∙"), + "oplus" => ("mo", "⊕"), + "otimes" => ("mo", "⊗"), + "le" | "leq" => ("mo", "≤"), + "ge" | "geq" => ("mo", "≥"), + "ne" | "neq" => ("mo", "≠"), + "approx" => ("mo", "≈"), + "equiv" => ("mo", "≡"), + "sim" => ("mo", "∼"), + "simeq" => ("mo", "≃"), + "cong" => ("mo", "≅"), + "propto" => ("mo", "∝"), + "ll" => ("mo", "≪"), + "gg" => ("mo", "≫"), + "perp" => ("mo", "⊥"), + "parallel" => ("mo", "∥"), + "angle" => ("mo", "∠"), + "rightarrow" | "to" => ("mo", "→"), + "leftarrow" => ("mo", "←"), + "leftrightarrow" => ("mo", "↔"), + "Rightarrow" => ("mo", "⇒"), + "Leftarrow" => ("mo", "⇐"), + "Leftrightarrow" => ("mo", "⇔"), + "mapsto" => ("mo", "↦"), + "cdots" => ("mo", "⋯"), + "dots" | "ldots" => ("mo", "…"), + "vdots" => ("mo", "⋮"), + "ddots" => ("mo", "⋱"), + "prime" => ("mo", "′"), + "langle" => ("mo", "⟨"), + "rangle" => ("mo", "⟩"), + "lceil" => ("mo", "⌈"), + "rceil" => ("mo", "⌉"), + "lfloor" => ("mo", "⌊"), + "rfloor" => ("mo", "⌋"), + _ => { + if let Some((tag, ch)) = unimath_map().get(cmd) { + return Some(format!("<{}>{}", tag, escape_xml(ch), tag)); + } + return None; + } + }; + Some(format!("<{}>{}", tag, escape_xml(ch), tag)) +} diff --git a/src-tauri/src/services/pdf_engine.rs b/src-tauri/src/services/pdf_engine.rs new file mode 100644 index 0000000..eb30aed --- /dev/null +++ b/src-tauri/src/services/pdf_engine.rs @@ -0,0 +1,859 @@ +use std::path::{Path, PathBuf}; + +use lopdf::{dictionary, Document, Object, ObjectId, Stream}; + +use crate::error::{AppError, AppResult}; +use crate::models::ConversionOptions; + +/// Sayfa numarası + metin çiftleri. +pub type PageText = Vec<(u32, String)>; + +/// (sayfalar, metin katmanı boş sayfa numaraları) +pub type ExtractedText = (PageText, Vec); + +pub struct PdfEngine; + +impl PdfEngine { + fn load(path: &str) -> AppResult { + Document::load(path).map_err(|e| { + let msg = e.to_string(); + if msg.to_lowercase().contains("encrypt") || msg.to_lowercase().contains("password") { + AppError::Pdf(format!( + "'{}' PDF dosyası şifre korumalı. Şifreli PDF'ler desteklenmiyor.", + Path::new(path) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or(path) + )) + } else { + AppError::Pdf(format!("PDF yüklenemedi ({}): {}", path, msg)) + } + }) + } + + // ---------------------------------------------------------------- merge + pub fn merge( + input_paths: &[String], + output_path: &Path, + options: &ConversionOptions, + ) -> AppResult { + if input_paths.is_empty() { + return Err(AppError::Pdf("Birleştirilecek dosya listesi boş".to_string())); + } + + let rotate_deg = Self::normalize_rotation(options.pdf_rotate_degrees.unwrap_or(0) as i64); + let mut document = Document::with_version("1.5"); + let pages_id = document.new_object_id(); + let catalog_id = document.new_object_id(); + let mut page_ids: Vec = Vec::new(); + let mut max_id: u32 = 1; + + for path in input_paths { + if crate::catalog::FormatCatalog::is_image(path) { + let page_id = Self::append_image_page(&mut document, pages_id, path, rotate_deg, options)?; + page_ids.push(page_id); + } else if crate::catalog::FormatCatalog::is_pdf(path) { + let mut doc = Self::load(path)?; + doc.renumber_objects_with(max_id); + max_id = doc.max_id + 1; + + let total_pages = doc.get_pages().len(); + let selected = Self::parse_page_range(options.pdf_page_range.as_deref(), total_pages); + let mut page_infos = Vec::new(); + + { + let pages = doc.get_pages(); + for (page_num, page_id) in &pages { + if !selected.contains(&(*page_num as usize)) { + continue; + } + if let Ok(Object::Dictionary(dict)) = doc.get_object(*page_id) { + let resources = dict + .get(b"Resources") + .ok() + .cloned() + .or_else(|| Self::inherited(&doc, dict, b"Resources")); + let media_box = dict + .get(b"MediaBox") + .ok() + .cloned() + .or_else(|| Self::inherited(&doc, dict, b"MediaBox")); + let current_rotate = dict + .get(b"Rotate") + .ok() + .and_then(|o| o.as_i64().ok()) + .unwrap_or(0); + page_infos.push((*page_id, resources, media_box, current_rotate)); + } + } + } + + for (page_id, resources, media_box, current_rotate) in page_infos { + if let Ok(Object::Dictionary(dict)) = doc.get_object_mut(page_id) { + dict.set("Parent", Object::Reference(pages_id)); + if let Some(res) = resources { + dict.set("Resources", res); + } + if let Some(mb) = media_box { + dict.set("MediaBox", mb); + } + let new_rotate = Self::normalize_rotation(current_rotate + rotate_deg); + if new_rotate != 0 { + dict.set("Rotate", Object::Integer(new_rotate)); + } + } + page_ids.push(page_id); + } + + for (obj_id, obj) in std::mem::take(&mut doc.objects) { + match obj.type_name().unwrap_or("") { + "Catalog" | "Pages" | "Outlines" | "Outline" => {} + _ => { + Self::put(&mut document, obj_id, obj); + max_id = max_id.max(obj_id.0); + } + } + } + document.max_id = document.max_id.max(max_id); + } else { + return Err(AppError::Pdf(format!( + "Desteklenmeyen birleştirme girdisi: {}", + Path::new(path) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or(path) + ))); + } + } + + if page_ids.is_empty() { + return Err(AppError::Pdf( + "Birleştirilecek geçerli bir PDF sayfası veya görsel bulunamadı.".to_string(), + )); + } + + let kids: Vec = page_ids.iter().map(|&id| Object::Reference(id)).collect(); + document.objects.insert( + pages_id, + Object::Dictionary(dictionary! { + "Type" => "Pages", + "Kids" => Object::Array(kids), + "Count" => page_ids.len() as i64, + }), + ); + document.objects.insert( + catalog_id, + Object::Dictionary(dictionary! { + "Type" => "Catalog", + "Pages" => Object::Reference(pages_id), + }), + ); + document.trailer.set("Root", Object::Reference(catalog_id)); + + if let Some(parent) = output_path.parent() { + std::fs::create_dir_all(parent)?; + } + document + .save(output_path) + .map_err(|e| AppError::Pdf(format!("Birleştirilmiş PDF kaydedilemedi: {}", e)))?; + + Ok(output_path.to_path_buf()) + } + + // ------------------------------------------------------------ image pages + fn append_image_page( + document: &mut Document, + pages_id: ObjectId, + image_path: &str, + rotate_deg: i64, + options: &ConversionOptions, + ) -> AppResult { + let mut img = crate::services::image_engine::ImageEngine::open_any_image( + Path::new(image_path), + options, + )?; + let is_svg = Path::new(image_path) + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|s| s.eq_ignore_ascii_case("svg")); + if !is_svg { + if let Some(w) = options.target_width { + if w > 0 && img.width() != w { + let (cw, ch) = (img.width().max(1), img.height().max(1)); + let h = ((ch as f64 / cw as f64) * w as f64).round().max(1.0) as u32; + img = img.resize(w, h.max(1), image::imageops::FilterType::Lanczos3); + } + } + } + + let rgb = crate::services::image_engine::ImageEngine::flatten_on_white(&img); + Self::append_image_object( + document, + pages_id, + &rgb, + rotate_deg, + options.image_quality.clamp(10, 98), + ) + } + + /// Bellekteki RGB görüntüyü tek sayfalık PDF sayfası olarak ekler. + fn append_image_object( + document: &mut Document, + pages_id: ObjectId, + rgb: &image::RgbImage, + rotate_deg: i64, + quality: u8, + ) -> AppResult { + // JPEG olarak kodla (DCTDecode ile doğrudan gömülür, sayfa boyutu küçük kalır) + let mut jpeg: Vec = Vec::new(); + { + let mut encoder = + image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, quality); + encoder + .encode( + rgb.as_raw(), + rgb.width(), + rgb.height(), + image::ExtendedColorType::Rgb8, + ) + .map_err(|e| AppError::Pdf(format!("Görsel JPEG olarak kodlanamadı: {}", e)))?; + } + + let (img_w, img_h) = (rgb.width().max(1), rgb.height().max(1)); + let landscape = img_w > img_h; + let page_w = if landscape { 842.0 } else { 595.0 }; + let page_h = page_w * img_h as f64 / img_w as f64; + let page_h = page_h.max(100.0); + + let image_stream = Stream::new( + dictionary! { + "Type" => "XObject", + "Subtype" => "Image", + "Width" => img_w as i64, + "Height" => img_h as i64, + "ColorSpace" => "DeviceRGB", + "BitsPerComponent" => 8i64, + "Filter" => "DCTDecode", + }, + jpeg, + ); + let image_id = document.add_object(Object::Stream(image_stream)); + + let content = format!("q {} 0 0 {} 0 0 cm /Im0 Do Q", page_w, page_h); + let content_id = document.add_object(Stream::new( + lopdf::Dictionary::new(), + content.into_bytes(), + )); + + let mut xobjects = lopdf::Dictionary::new(); + xobjects.set("Im0", Object::Reference(image_id)); + let mut resources = lopdf::Dictionary::new(); + resources.set("XObject", Object::Dictionary(xobjects)); + + let mut page = dictionary! { + "Type" => "Page", + "Parent" => Object::Reference(pages_id), + "MediaBox" => Object::Array(vec![ + Object::Real(0.0), + Object::Real(0.0), + Object::Real(page_w as f32), + Object::Real(page_h as f32), + ]), + "Resources" => Object::Dictionary(resources), + "Contents" => Object::Reference(content_id), + }; + if rotate_deg != 0 { + page.set("Rotate", Object::Integer(rotate_deg)); + } + + Ok(document.add_object(Object::Dictionary(page))) + } + + /// Bellekteki görüntülerden çok sayfalı PDF üretir (her görüntü bir sayfa). + pub fn images_to_pdf( + images: &[image::DynamicImage], + output_path: &Path, + quality: u8, + ) -> AppResult { + if images.is_empty() { + return Err(AppError::Pdf("PDF için görüntü listesi boş".to_string())); + } + + let mut document = Document::with_version("1.5"); + let pages_id = document.new_object_id(); + let catalog_id = document.new_object_id(); + let mut page_ids = Vec::new(); + + for img in images { + let rgb = img.to_rgb8(); + page_ids.push(Self::append_image_object( + &mut document, + pages_id, + &rgb, + 0, + quality, + )?); + } + + let kids: Vec = page_ids.iter().map(|&id| Object::Reference(id)).collect(); + document.objects.insert( + pages_id, + Object::Dictionary(dictionary! { + "Type" => "Pages", + "Kids" => Object::Array(kids), + "Count" => page_ids.len() as i64, + }), + ); + document.objects.insert( + catalog_id, + Object::Dictionary(dictionary! { + "Type" => "Catalog", + "Pages" => Object::Reference(pages_id), + }), + ); + document.trailer.set("Root", Object::Reference(catalog_id)); + + if let Some(parent) = output_path.parent() { + std::fs::create_dir_all(parent)?; + } + document + .save(output_path) + .map_err(|e| AppError::Pdf(format!("PDF kaydedilemedi: {}", e)))?; + Ok(output_path.to_path_buf()) + } + + // ---------------------------------------------------------------- rotate + pub fn rotate_pdf( + input_path: &str, + output_path: &Path, + degrees: i32, + ) -> AppResult { + let mut doc = Self::load(input_path)?; + let degrees = Self::normalize_rotation(degrees as i64); + + let pages: Vec = doc.get_pages().values().cloned().collect(); + for page_id in pages { + if let Ok(Object::Dictionary(dict)) = doc.get_object_mut(page_id) { + let current = dict + .get(b"Rotate") + .ok() + .and_then(|o| o.as_i64().ok()) + .unwrap_or(0); + let new_rotate = Self::normalize_rotation(current + degrees); + dict.set("Rotate", Object::Integer(new_rotate)); + } + } + + doc.save(output_path) + .map_err(|e| AppError::Pdf(format!("Döndürülmüş PDF kaydedilemedi: {}", e)))?; + + Ok(output_path.to_path_buf()) + } + + // ----------------------------------------------------------------- split + pub fn split_pdf( + input_path: &str, + output_dir: &Path, + options: &ConversionOptions, + ) -> AppResult> { + let doc = Self::load(input_path)?; + + let pages = doc.get_pages(); + let total_pages = pages.len(); + let stem = Path::new(input_path) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("document"); + let rotate_deg = Self::normalize_rotation(options.pdf_rotate_degrees.unwrap_or(0) as i64); + + let selected_pages = Self::parse_page_range(options.pdf_page_range.as_deref(), total_pages); + let mut outputs = Vec::new(); + + for page_num in selected_pages { + if page_num == 0 || page_num > total_pages { + continue; + } + let mut single_doc = doc.clone(); + let all_pages = single_doc.get_pages(); + let pages_to_delete: Vec = all_pages + .keys() + .filter(|&&p| p != page_num as u32) + .cloned() + .collect(); + + single_doc.delete_pages(&pages_to_delete); + + if rotate_deg != 0 { + let ids: Vec = single_doc.get_pages().values().cloned().collect(); + for page_id in ids { + if let Ok(Object::Dictionary(dict)) = single_doc.get_object_mut(page_id) { + let current = dict + .get(b"Rotate") + .ok() + .and_then(|o| o.as_i64().ok()) + .unwrap_or(0); + dict.set( + "Rotate", + Object::Integer(Self::normalize_rotation(current + rotate_deg)), + ); + } + } + } + + let out_file = Self::unique_path( + &output_dir.join(format!("{}_sayfa_{}.pdf", stem, page_num)), + ); + single_doc + .save(&out_file) + .map_err(|e| AppError::Pdf(format!("Sayfa kaydedilemedi: {}", e)))?; + outputs.push(out_file); + } + + Ok(outputs) + } + + // ----------------------------------------------------------- text / OCR + /// Sayfa numarası + metin çiftleri ve metin katmanı boş olan (taranmış) sayfalar. + pub fn extract_text( + input_path: &str, + options: &ConversionOptions, + ) -> AppResult { + let doc = Self::load(input_path)?; + let total_pages = doc.get_pages().len(); + let selected = Self::parse_page_range(options.pdf_page_range.as_deref(), total_pages); + + let mut pages = Vec::new(); + let mut empty_pages = Vec::new(); + + for page_num in selected { + if page_num == 0 || page_num > total_pages { + continue; + } + let page_text = doc + .extract_text(&[page_num as u32]) + .map_err(|e| AppError::Pdf(format!("Sayfa {} metni okunamadı: {}", page_num, e)))?; + let cleaned = page_text.trim().to_string(); + if cleaned.is_empty() { + empty_pages.push(page_num as u32); + } + pages.push((page_num as u32, cleaned)); + } + + Ok((pages, empty_pages)) + } + + // --------------------------------------------------------- embedded images + /// PDF sayfası içindeki gömülü bitmap'leri çözer (taranmış PDF'ler için hızlı yol). + pub fn extract_page_images(input_path: &str, page_num: u32) -> AppResult> { + let doc = Self::load(input_path)?; + let pages = doc.get_pages(); + let page_id = *pages + .get(&page_num) + .ok_or_else(|| AppError::Pdf(format!("Sayfa {} bulunamadı", page_num)))?; + + let dict = match doc.get_object(page_id) { + Ok(Object::Dictionary(d)) => d, + _ => return Ok(Vec::new()), + }; + + let resources = match dict + .get(b"Resources") + .ok() + .cloned() + .or_else(|| Self::inherited(&doc, dict, b"Resources")) + { + Some(Object::Dictionary(d)) => d, + _ => return Ok(Vec::new()), + }; + + let xobjects = match resources.get(b"XObject").ok().and_then(|o| o.as_dict().ok()) { + Some(d) => d.clone(), + None => return Ok(Vec::new()), + }; + + let mut images = Vec::new(); + for (_name, value) in xobjects.iter() { + let obj_id = match value.as_reference() { + Ok(id) => id, + Err(_) => continue, + }; + let stream = match doc.get_object(obj_id) { + Ok(Object::Stream(s)) => s, + _ => continue, + }; + if let Ok(decoded) = Self::decode_image_stream(stream) { + images.push(decoded); + } + } + + Ok(images) + } + + fn decode_image_stream(stream: &Stream) -> AppResult { + let filter = stream + .dict + .get(b"Filter") + .ok() + .map(|o| match o { + Object::Name(n) => String::from_utf8_lossy(n).to_string(), + Object::Array(a) => a + .iter() + .filter_map(|i| i.as_name().ok()) + .map(|n| String::from_utf8_lossy(n).to_string()) + .collect::>() + .join(","), + _ => String::new(), + }) + .unwrap_or_default(); + + if filter.contains("DCTDecode") { + return image::load_from_memory(&stream.content) + .map_err(|e| AppError::Pdf(format!("JPEG görsel çözülemedi: {}", e))); + } + if filter.contains("JPXDecode") || filter.contains("JBIG2Decode") { + return Err(AppError::Pdf( + "JPX/JBIG2 görselleri desteklenmiyor".to_string(), + )); + } + + let data = match stream.decompressed_content() { + Ok(data) => data, + // Sıkıştırılmamış görsellerde filtre yok; ham içerik geçerlidir. + Err(_) => stream.content.clone(), + }; + + let width = stream + .dict + .get(b"Width") + .ok() + .and_then(|o| o.as_i64().ok()) + .unwrap_or(0) as u32; + let height = stream + .dict + .get(b"Height") + .ok() + .and_then(|o| o.as_i64().ok()) + .unwrap_or(0) as u32; + if width == 0 || height == 0 { + return Err(AppError::Pdf("Görsel boyutları eksik".to_string())); + } + + let bits = stream + .dict + .get(b"BitsPerComponent") + .ok() + .and_then(|o| o.as_i64().ok()) + .unwrap_or(8); + if bits != 8 { + return Err(AppError::Pdf( + "8-bit olmayan görseller desteklenmiyor".to_string(), + )); + } + + let color_space = stream + .dict + .get(b"ColorSpace") + .ok() + .map(|o| match o { + Object::Name(n) => String::from_utf8_lossy(n).to_string(), + _ => String::new(), + }) + .unwrap_or_default(); + + let expected = width as usize * height as usize; + match color_space.as_str() { + "DeviceRGB" | "RGB" => { + if data.len() < expected * 3 { + return Err(AppError::Pdf("Görsel verisi eksik".to_string())); + } + let buf = image::RgbImage::from_raw(width, height, data[..expected * 3].to_vec()) + .ok_or_else(|| AppError::Pdf("RGB görsel oluşturulamadı".to_string()))?; + Ok(image::DynamicImage::ImageRgb8(buf)) + } + "DeviceGray" | "G" => { + if data.len() < expected { + return Err(AppError::Pdf("Görsel verisi eksik".to_string())); + } + let buf = image::GrayImage::from_raw(width, height, data[..expected].to_vec()) + .ok_or_else(|| AppError::Pdf("Gri görsel oluşturulamadı".to_string()))?; + Ok(image::DynamicImage::ImageLuma8(buf)) + } + _ => Err(AppError::Pdf(format!( + "Desteklenmeyen renk uzayı: {}", + color_space + ))), + } + } + /// Basit, metin katmanlı bir PDF üretir (tanılama/test amaçlı; harici araç gerekmez). + pub fn write_simple_text_pdf(text: &str, output: &Path) -> AppResult { + let escaped = text + .replace('\\', "\\\\") + .replace('(', "\\(") + .replace(')', "\\)"); + let content = format!("BT /F1 24 Tf 72 720 Td ({}) Tj ET", escaped); + + let objects = [ + "<< /Type /Catalog /Pages 2 0 R >>".to_string(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>".to_string(), + format!("<< /Length {} >>\nstream\n{}\nendstream", content.len(), content), + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_string(), + ]; + + let mut document = String::from("%PDF-1.4\n"); + let mut offsets = Vec::with_capacity(objects.len()); + for (index, object) in objects.iter().enumerate() { + offsets.push(document.len()); + document.push_str(&format!("{} 0 obj\n{}\nendobj\n", index + 1, object)); + } + let xref_position = document.len(); + document.push_str(&format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1)); + for offset in offsets { + document.push_str(&format!("{:010} 00000 n \n", offset)); + } + document.push_str(&format!( + "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n", + objects.len() + 1, + xref_position + )); + + if let Some(parent) = output.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(output, document)?; + Ok(output.to_path_buf()) + } + + /// PDF içindeki yüksek çözünürlüklü görüntü akışlarını yeniden ölçekleyip JPEG (quality ~75) + /// olarak sıkıştırır, varsa boş parolalı yazdırma/kopyalama kısıtlamasını (`/Encrypt`) kaldırır + /// ve kullanılmayan PDF nesnelerini temizler (`prune_objects` + `compress`). + pub fn compress_pdf( + input_path: &str, + output_path: &Path, + options: &ConversionOptions, + ) -> AppResult { + let mut doc = Document::load(input_path) + .map_err(|e| AppError::Pdf(format!("PDF sıkıştırma için yüklenemedi: {}", e)))?; + + // Boş sahip şifreli yazdırma / kopyalama kısıtlaması varsa temizle + doc.trailer.remove(b"Encrypt"); + + let quality = options.image_quality.clamp(40, 80).min(75); + let candidate_ids: Vec = doc + .objects + .iter() + .filter_map(|(id, obj)| match obj { + Object::Stream(stream) => { + let is_image = stream + .dict + .get(b"Subtype") + .ok() + .and_then(|o| o.as_name().ok()) + .is_some_and(|n| n == b"Image"); + if is_image && stream.content.len() > 4096 { + Some(*id) + } else { + None + } + } + _ => None, + }) + .collect(); + + for obj_id in candidate_ids { + let decoded = match doc.get_object(obj_id) { + Ok(Object::Stream(stream)) => Self::decode_image_stream(stream).ok(), + _ => None, + }; + let Some(mut img) = decoded else { + continue; + }; + + if img.width() > 1600 || img.height() > 1600 { + img = img.resize(1600, 1600, image::imageops::FilterType::Lanczos3); + } + let rgb = crate::services::image_engine::ImageEngine::flatten_on_white(&img); + let mut jpeg_bytes = Vec::new(); + let mut encoder = + image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg_bytes, quality); + if encoder + .encode( + rgb.as_raw(), + rgb.width(), + rgb.height(), + image::ExtendedColorType::Rgb8, + ) + .is_err() + { + continue; + } + + if let Ok(Object::Stream(ref mut stream)) = doc.get_object_mut(obj_id) { + if jpeg_bytes.len() + 128 < stream.content.len() { + let jpeg_len = jpeg_bytes.len(); + stream.content = jpeg_bytes; + stream.allows_compression = false; + stream.dict.set("Filter", Object::Name(b"DCTDecode".to_vec())); + stream + .dict + .set("ColorSpace", Object::Name(b"DeviceRGB".to_vec())); + stream.dict.set("Width", Object::Integer(rgb.width() as i64)); + stream + .dict + .set("Height", Object::Integer(rgb.height() as i64)); + stream.dict.set("BitsPerComponent", Object::Integer(8)); + stream.dict.set("Length", Object::Integer(jpeg_len as i64)); + stream.dict.remove(b"DecodeParms"); + stream.dict.remove(b"SMask"); + } + } + } + + doc.prune_objects(); + doc.delete_zero_length_streams(); + doc.compress(); + doc.save(output_path) + .map_err(|e| AppError::Pdf(format!("Sıkıştırılmış PDF kaydedilemedi: {}", e)))?; + + Ok(output_path.to_path_buf()) + } + + pub fn parse_page_range(range_str: Option<&str>, total: usize) -> Vec { + let all_pages: Vec = (1..=total).collect(); + let spec = match range_str { + Some(s) if !s.trim().is_empty() => s.trim(), + _ => return all_pages, + }; + + let lowered = spec.to_lowercase(); + if matches!(lowered.as_str(), "all" | "tümü" | "tumu" | "hepsi" | "*") { + return all_pages; + } + + let mut pages: Vec = Vec::new(); + for part in spec.split([',', ';']) { + let token = part.trim(); + if token.is_empty() { + continue; + } + if let Some((start, end)) = token.split_once('-') { + if let (Ok(mut a), Ok(mut b)) = + (start.trim().parse::(), end.trim().parse::()) + { + if a > b { + std::mem::swap(&mut a, &mut b); + } + if a > total || b < 1 { + continue; + } + a = a.max(1); + b = b.min(total); + for page in a..=b { + if !pages.contains(&page) { + pages.push(page); + } + } + } + } else if let Ok(num) = token.parse::() { + if num >= 1 && num <= total && !pages.contains(&num) { + pages.push(num); + } + } + } + + if pages.is_empty() { + all_pages + } else { + pages + } + } + + fn normalize_rotation(degrees: i64) -> i64 { + degrees.rem_euclid(360) + } + + fn put(doc: &mut Document, id: ObjectId, obj: Object) { + doc.objects.insert(id, obj); + if id.0 > doc.max_id { + doc.max_id = id.0; + } + } + + fn inherited(doc: &Document, dict: &lopdf::Dictionary, key: &[u8]) -> Option { + if let Ok(value) = dict.get(key) { + return Some(value.clone()); + } + let mut parent = dict.get(b"Parent").ok().and_then(|p| p.as_reference().ok()); + let mut guard = 0; + while let Some(parent_id) = parent { + if guard > 32 { + break; + } + match doc.get_object(parent_id) { + Ok(Object::Dictionary(parent_dict)) => { + if let Ok(value) = parent_dict.get(key) { + return Some(value.clone()); + } + parent = parent_dict + .get(b"Parent") + .ok() + .and_then(|p| p.as_reference().ok()); + } + _ => break, + } + guard += 1; + } + None + } + + pub fn unique_path(path: &Path) -> PathBuf { + crate::services::image_engine::ImageEngine::get_unique_path(path, false) + } + + pub fn page_count(input_path: &str) -> AppResult { + Ok(Self::load(input_path)?.get_pages().len()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compress_pdf_preserves_pages_and_removes_encrypt() -> Result<(), Box> { + let dir = std::env::temp_dir().join(format!("ld_pdf_test_{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir)?; + + let img_path = dir.join("sample.png"); + let img = image::RgbImage::from_fn(400, 300, |x, y| { + image::Rgb([(x % 255) as u8, (y % 255) as u8, ((x + y) % 255) as u8]) + }); + img.save(&img_path)?; + + let merged_pdf = dir.join("merged.pdf"); + PdfEngine::merge( + &[img_path.to_string_lossy().to_string()], + &merged_pdf, + &ConversionOptions::default(), + )?; + + // Yapay /Encrypt belirteci ekle ve sıkıştırıcının temizlediğini doğrula. + let mut doc = Document::load(&merged_pdf)?; + doc.trailer.set("Encrypt", Object::Null); + doc.save(&merged_pdf)?; + + let out_pdf = dir.join("compressed.pdf"); + let opts = ConversionOptions { + image_quality: 70, + ..Default::default() + }; + PdfEngine::compress_pdf(&merged_pdf.to_string_lossy(), &out_pdf, &opts)?; + + assert_eq!(PdfEngine::page_count(&out_pdf.to_string_lossy())?, 1); + let compressed_doc = Document::load(&out_pdf)?; + assert!(compressed_doc.trailer.get(b"Encrypt").is_err()); + + let _ = std::fs::remove_dir_all(&dir); + Ok(()) + } +} diff --git a/src-tauri/src/services/pdf_images.rs b/src-tauri/src/services/pdf_images.rs new file mode 100644 index 0000000..1f10a81 --- /dev/null +++ b/src-tauri/src/services/pdf_images.rs @@ -0,0 +1,291 @@ +//! printpdf çıktısına gerçek PDF görsel XObject'leri, tıklanabilir köprüler (/Subtype /Link) +//! ve PDF Yer İşaretleri (/Outlines) enjekte eder (saf Rust, `lopdf`). + +use lopdf::{Dictionary, Document, Object, Stream, StringFormat}; + +pub struct Placement { + pub page: u32, + pub x_mm: f32, + pub y_mm: f32, + pub width_mm: f32, + pub height_mm: f32, + pub bytes: Vec, +} + +#[derive(Clone, Debug)] +pub struct LinkAnnotation { + pub page: u32, + pub x_mm: f32, + pub y_mm: f32, + pub width_mm: f32, + pub height_mm: f32, + pub url: String, +} + +#[derive(Clone, Debug)] +pub struct OutlineEntry { + pub title: String, + pub level: u8, + pub page: u32, + pub y_mm: f32, +} + +fn mm_to_pt(value: f32) -> f32 { + value / 25.4 * 72.0 +} + +fn encode_jpeg(bytes: &[u8]) -> Option<(Vec, u32, u32)> { + let decoded = image::load_from_memory(bytes).ok()?; + let rgb = crate::services::image_engine::ImageEngine::flatten_on_white(&decoded); + let (width, height) = rgb.dimensions(); + let mut output = Vec::new(); + let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut output, 88); + encoder.encode_image(&rgb).ok()?; + Some((output, width, height)) +} + +fn pdf_text_string(text: &str) -> Object { + if text.is_ascii() { + Object::String(text.as_bytes().to_vec(), StringFormat::Literal) + } else { + let mut utf16be = Vec::with_capacity(2 + text.len() * 2); + utf16be.extend_from_slice(&[0xFE, 0xFF]); + for unit in text.encode_utf16() { + utf16be.extend_from_slice(&unit.to_be_bytes()); + } + Object::String(utf16be, StringFormat::Hexadecimal) + } +} + +fn resolve_dict(document: &Document, object: Option<&Object>) -> Dictionary { + match object { + Some(Object::Dictionary(dict)) => dict.clone(), + Some(Object::Reference(id)) => document + .get_object(*id) + .ok() + .and_then(|object| object.as_dict().ok()) + .cloned() + .unwrap_or_default(), + _ => Dictionary::new(), + } +} + +fn page_resources(document: &Document, page_id: lopdf::ObjectId) -> Dictionary { + let mut current = page_id; + for _ in 0..8 { + let Some(dict) = document + .get_object(current) + .ok() + .and_then(|object| object.as_dict().ok()) + else { + break; + }; + if let Ok(resources) = dict.get(b"Resources") { + return resolve_dict(document, Some(resources)); + } + match dict.get(b"Parent") { + Ok(Object::Reference(parent)) => current = *parent, + _ => break, + } + } + Dictionary::new() +} + +pub fn inject(pdf: &[u8], placements: &[Placement]) -> Vec { + inject_corporate(pdf, placements, &[], &[]) +} + +pub fn inject_corporate( + pdf: &[u8], + placements: &[Placement], + links: &[LinkAnnotation], + outlines: &[OutlineEntry], +) -> Vec { + if placements.is_empty() && links.is_empty() && outlines.is_empty() { + return pdf.to_vec(); + } + let Ok(mut document) = Document::load_mem(pdf) else { + return pdf.to_vec(); + }; + let pages = document.get_pages(); + + for (index, placement) in placements.iter().enumerate() { + let Some(page_id) = pages.get(&placement.page).copied() else { + continue; + }; + let Some((jpeg, width, height)) = encode_jpeg(&placement.bytes) else { + continue; + }; + + let mut image_dict = Dictionary::new(); + image_dict.set("Type", Object::Name(b"XObject".to_vec())); + image_dict.set("Subtype", Object::Name(b"Image".to_vec())); + image_dict.set("Width", Object::Integer(width as i64)); + image_dict.set("Height", Object::Integer(height as i64)); + image_dict.set("ColorSpace", Object::Name(b"DeviceRGB".to_vec())); + image_dict.set("BitsPerComponent", Object::Integer(8)); + image_dict.set("Filter", Object::Name(b"DCTDecode".to_vec())); + + let mut stream = Stream::new(image_dict, jpeg); + stream.allows_compression = false; + let image_id = document.add_object(stream); + + let name = format!("LdIm{}", index); + + // Kaynakları (miras dahil) klonla, XObject'i ekle, sayfaya doğrudan yaz. + let mut resources = page_resources(&document, page_id); + let mut xobjects = resolve_dict(&document, resources.get(b"XObject").ok()); + xobjects.set(name.clone(), Object::Reference(image_id)); + resources.set("XObject", Object::Dictionary(xobjects)); + + if let Ok(page) = document.get_object_mut(page_id) { + if let Ok(dict) = page.as_dict_mut() { + dict.set("Resources", Object::Dictionary(resources)); + } + } + + let width_pt = mm_to_pt(placement.width_mm); + let height_pt = mm_to_pt(placement.height_mm); + let x_pt = mm_to_pt(placement.x_mm); + let y_pt = mm_to_pt(placement.y_mm); + let content = format!( + "q {} 0 0 {} {} {} cm /{} Do Q\n", + width_pt, height_pt, x_pt, y_pt, name + ); + + let content_id = document.add_object(Stream::new(Dictionary::new(), content.into_bytes())); + if let Ok(page) = document.get_object_mut(page_id) { + if let Ok(dict) = page.as_dict_mut() { + match dict.get_mut(b"Contents") { + Ok(Object::Reference(existing)) => { + let existing = *existing; + dict.set( + "Contents", + Object::Array(vec![ + Object::Reference(existing), + Object::Reference(content_id), + ]), + ); + } + Ok(Object::Array(array)) => array.push(Object::Reference(content_id)), + _ => dict.set("Contents", Object::Reference(content_id)), + } + } + } + } + + // Tıklanabilir URI bağlantıları (/Subtype /Link) + for link in links { + let Some(page_id) = pages.get(&link.page).copied() else { + continue; + }; + let x1 = mm_to_pt(link.x_mm); + let y1 = mm_to_pt(link.y_mm); + let x2 = mm_to_pt(link.x_mm + link.width_mm.max(1.0)); + let y2 = mm_to_pt(link.y_mm + link.height_mm.max(2.0)); + + let mut action_dict = Dictionary::new(); + action_dict.set("Type", Object::Name(b"Action".to_vec())); + action_dict.set("S", Object::Name(b"URI".to_vec())); + action_dict.set( + "URI", + Object::String(link.url.as_bytes().to_vec(), StringFormat::Literal), + ); + + let mut annot_dict = Dictionary::new(); + annot_dict.set("Type", Object::Name(b"Annot".to_vec())); + annot_dict.set("Subtype", Object::Name(b"Link".to_vec())); + annot_dict.set( + "Rect", + Object::Array(vec![x1.into(), y1.into(), x2.into(), y2.into()]), + ); + annot_dict.set( + "Border", + Object::Array(vec![Object::Integer(0), Object::Integer(0), Object::Integer(0)]), + ); + annot_dict.set("A", Object::Dictionary(action_dict)); + + let annot_id = document.add_object(Object::Dictionary(annot_dict)); + if let Ok(page) = document.get_object_mut(page_id) { + if let Ok(dict) = page.as_dict_mut() { + match dict.get_mut(b"Annots") { + Ok(Object::Array(arr)) => arr.push(Object::Reference(annot_id)), + _ => dict.set("Annots", Object::Array(vec![Object::Reference(annot_id)])), + } + } + } + } + + // Başlıklardan otomatik İçindekiler / Yer İşaretleri (/Outlines) + let valid_outlines: Vec<&OutlineEntry> = outlines + .iter() + .filter(|entry| !entry.title.trim().is_empty() && pages.contains_key(&entry.page)) + .collect(); + + if !valid_outlines.is_empty() { + let outlines_id = document.new_object_id(); + let item_ids: Vec = (0..valid_outlines.len()) + .map(|_| document.new_object_id()) + .collect(); + + for (i, entry) in valid_outlines.iter().enumerate() { + let Some(&page_id) = pages.get(&entry.page) else { + continue; + }; + let prefix = match entry.level { + 2 => " ", + 3 => " ", + _ => "", + }; + let title = format!("{}{}", prefix, entry.title.trim()); + let mut item = Dictionary::new(); + item.set("Title", pdf_text_string(&title)); + item.set("Parent", Object::Reference(outlines_id)); + if i > 0 { + item.set("Prev", Object::Reference(item_ids[i - 1])); + } + if i + 1 < item_ids.len() { + item.set("Next", Object::Reference(item_ids[i + 1])); + } + item.set( + "Dest", + Object::Array(vec![ + Object::Reference(page_id), + Object::Name(b"XYZ".to_vec()), + Object::Integer(0), + Object::Real(mm_to_pt(entry.y_mm)), + Object::Null, + ]), + ); + document + .objects + .insert(item_ids[i], Object::Dictionary(item)); + } + + if let (Some(&first_id), Some(&last_id)) = (item_ids.first(), item_ids.last()) { + let mut outlines_dict = Dictionary::new(); + outlines_dict.set("Type", Object::Name(b"Outlines".to_vec())); + outlines_dict.set("First", Object::Reference(first_id)); + outlines_dict.set("Last", Object::Reference(last_id)); + outlines_dict.set("Count", Object::Integer(item_ids.len() as i64)); + document + .objects + .insert(outlines_id, Object::Dictionary(outlines_dict)); + + if let Ok(Object::Reference(root_id)) = document.trailer.get(b"Root").cloned() { + if let Ok(root_obj) = document.get_object_mut(root_id) { + if let Ok(root_dict) = root_obj.as_dict_mut() { + root_dict.set("Outlines", Object::Reference(outlines_id)); + root_dict.set("PageMode", Object::Name(b"UseOutlines".to_vec())); + } + } + } + } + } + + let mut output = Vec::new(); + if document.save_to(&mut output).is_err() { + return pdf.to_vec(); + } + output +} diff --git a/src-tauri/src/services/pdf_parser/content_stream.rs b/src-tauri/src/services/pdf_parser/content_stream.rs new file mode 100644 index 0000000..0c0bda9 --- /dev/null +++ b/src-tauri/src/services/pdf_parser/content_stream.rs @@ -0,0 +1,657 @@ +//! PDF İçerik Akışı Yorumlayıcı (Content Stream Interpreter). +//! +//! Grafik Durum Makinesi (`q`/`Q`/`cm`), Metin Durumu (`BT`/`ET`/`Tf`/`Tm`/`Td`/`TJ`), +//! Vektör Çizim Yolları (`m`/`l`/`re`/`S`/`f`/`B`) ve Form XObject özyinelemeli çözümünü yönetir. + +use lopdf::{Document, Object}; +use lopdf::content::Content; + +use super::matrix::{AffineMatrix, GraphicsState, PageBox}; +use super::font_resolver::{FontResolver, ParsedFont}; +use super::image_extractor::{ExtractedImage, ImageExtractor}; + +#[derive(Debug, Clone)] +pub struct PdfChar { + pub unicode: String, + pub x: f64, + pub y: f64, + pub width: f64, + pub height: f64, + pub font_size: f64, + pub font_name: String, + pub is_math: bool, + pub is_bold: bool, + pub is_italic: bool, + pub color: [u8; 3], +} + +#[derive(Debug, Clone)] +pub struct VectorLine { + pub x1: f64, + pub y1: f64, + pub x2: f64, + pub y2: f64, + pub is_horizontal: bool, + pub thickness: f64, + pub color: [u8; 3], +} + +#[derive(Debug, Clone)] +pub struct FilledRect { + pub x: f64, + pub y: f64, + pub width: f64, + pub height: f64, + pub color: [u8; 3], +} + +pub struct ContentStreamInterpreter<'a> { + doc: &'a Document, + page_box: &'a PageBox, + font_resolver: &'a mut FontResolver, + fonts: std::collections::HashMap, ParsedFont>, + xobjects: std::collections::HashMap, lopdf::Object>, + state_stack: Vec, + current_state: GraphicsState, + pub chars: Vec, + pub lines: Vec, + pub filled_rects: Vec, + pub images: Vec, + current_subpath: Vec<(f64, f64)>, +} + +impl<'a> ContentStreamInterpreter<'a> { + pub fn new( + doc: &'a Document, + page_box: &'a PageBox, + font_resolver: &'a mut FontResolver, + resources: Option<&'a lopdf::Dictionary>, + ) -> Self { + let mut interp = Self { + doc, + page_box, + font_resolver, + fonts: std::collections::HashMap::new(), + xobjects: std::collections::HashMap::new(), + state_stack: Vec::new(), + current_state: GraphicsState::default(), + chars: Vec::new(), + lines: Vec::new(), + filled_rects: Vec::new(), + images: Vec::new(), + current_subpath: Vec::new(), + }; + + if let Some(res) = resources { + interp.load_resources(res); + } + + interp + } + + pub fn load_resources(&mut self, res: &lopdf::Dictionary) { + // Fontları yükle + if let Ok(font_dict_obj) = res.get(b"Font") { + if let Some(font_dict) = resolve_dict(self.doc, font_dict_obj) { + for (name, obj) in font_dict.iter() { + let parsed = self.font_resolver.resolve(self.doc, obj); + self.fonts.insert(name.clone(), parsed); + } + } + } + + // XObject sözlüğünü yükle + if let Ok(xobj_dict_obj) = res.get(b"XObject") { + if let Some(xobj_dict) = resolve_dict(self.doc, xobj_dict_obj) { + for (name, obj) in xobj_dict.iter() { + self.xobjects.insert(name.clone(), obj.clone()); + } + } + } + } + + pub fn interpret_stream(&mut self, content_bytes: &[u8]) { + let content = match Content::decode(content_bytes) { + Ok(c) => c, + Err(_) => return, + }; + + for op in content.operations { + self.execute_op(&op.operator, &op.operands); + } + } + + fn execute_op(&mut self, operator: &str, operands: &[Object]) { + match operator { + // Grafik Durum Yığını + "q" => { + self.state_stack.push(self.current_state.clone()); + } + "Q" => { + if let Some(prev) = self.state_stack.pop() { + self.current_state = prev; + } + } + "cm" => { + if operands.len() >= 6 { + let m = parse_matrix_operands(operands); + self.current_state.ctm = m.multiply(&self.current_state.ctm); + } + } + + // Metin Durumu + "BT" => { + self.current_state.reset_text_matrices(); + } + "ET" => { + self.current_state.reset_text_matrices(); + } + "Tf" => { + if let Some(name_obj) = operands.first() { + if let Ok(name) = name_obj.as_name() { + self.current_state.font_name = String::from_utf8_lossy(name).to_string(); + } + } + if let Some(size_obj) = operands.get(1) { + if let Some(size) = to_f64(size_obj) { + self.current_state.font_size = size; + } + } + } + "TL" => { + if let Some(l) = operands.first().and_then(to_f64) { + self.current_state.leading = l; + } + } + "Tr" => { + if let Some(r) = operands.first().and_then(|o| o.as_i64().ok()) { + self.current_state.render_mode = r as u8; + } + } + "Ts" => { + if let Some(s) = operands.first().and_then(to_f64) { + self.current_state.text_rise = s; + } + } + "Tz" => { + if let Some(z) = operands.first().and_then(to_f64) { + self.current_state.horizontal_scaling = z; + } + } + "Tc" => { + if let Some(c) = operands.first().and_then(to_f64) { + self.current_state.char_spacing = c; + } + } + "Tw" => { + if let Some(w) = operands.first().and_then(to_f64) { + self.current_state.word_spacing = w; + } + } + "Td" => { + if operands.len() >= 2 { + let tx = to_f64(&operands[0]).unwrap_or(0.0); + let ty = to_f64(&operands[1]).unwrap_or(0.0); + let trans = AffineMatrix::new(1.0, 0.0, 0.0, 1.0, tx, ty); + self.current_state.text_line_matrix = trans.multiply(&self.current_state.text_line_matrix); + self.current_state.text_matrix = self.current_state.text_line_matrix; + } + } + "TD" => { + if operands.len() >= 2 { + let tx = to_f64(&operands[0]).unwrap_or(0.0); + let ty = to_f64(&operands[1]).unwrap_or(0.0); + self.current_state.leading = -ty; + let trans = AffineMatrix::new(1.0, 0.0, 0.0, 1.0, tx, ty); + self.current_state.text_line_matrix = trans.multiply(&self.current_state.text_line_matrix); + self.current_state.text_matrix = self.current_state.text_line_matrix; + } + } + "Tm" => { + if operands.len() >= 6 { + let m = parse_matrix_operands(operands); + self.current_state.text_matrix = m; + self.current_state.text_line_matrix = m; + } + } + "T*" => { + let ty = -self.current_state.leading; + let trans = AffineMatrix::new(1.0, 0.0, 0.0, 1.0, 0.0, ty); + self.current_state.text_line_matrix = trans.multiply(&self.current_state.text_line_matrix); + self.current_state.text_matrix = self.current_state.text_line_matrix; + } + + // Metin Gösterimi + "Tj" => { + if let Some(str_obj) = operands.first() { + self.show_text_object(str_obj); + } + } + "'" => { + self.execute_op("T*", &[]); + if let Some(str_obj) = operands.first() { + self.show_text_object(str_obj); + } + } + "\"" => { + if operands.len() >= 3 { + if let Some(w) = to_f64(&operands[0]) { + self.current_state.word_spacing = w; + } + if let Some(c) = to_f64(&operands[1]) { + self.current_state.char_spacing = c; + } + self.execute_op("T*", &[]); + self.show_text_object(&operands[2]); + } + } + "TJ" => { + if let Some(arr_obj) = operands.first() { + if let Ok(arr) = arr_obj.as_array() { + self.show_text_array(arr); + } + } + } + + // Renkler + "rg" => { + if operands.len() >= 3 { + let r = (to_f64(&operands[0]).unwrap_or(0.0) * 255.0).round().clamp(0.0, 255.0) as u8; + let g = (to_f64(&operands[1]).unwrap_or(0.0) * 255.0).round().clamp(0.0, 255.0) as u8; + let b = (to_f64(&operands[2]).unwrap_or(0.0) * 255.0).round().clamp(0.0, 255.0) as u8; + self.current_state.fill_color = [r, g, b]; + } + } + "RG" => { + if operands.len() >= 3 { + let r = (to_f64(&operands[0]).unwrap_or(0.0) * 255.0).round().clamp(0.0, 255.0) as u8; + let g = (to_f64(&operands[1]).unwrap_or(0.0) * 255.0).round().clamp(0.0, 255.0) as u8; + let b = (to_f64(&operands[2]).unwrap_or(0.0) * 255.0).round().clamp(0.0, 255.0) as u8; + self.current_state.stroke_color = [r, g, b]; + } + } + "g" => { + if let Some(gray) = operands.first().and_then(to_f64) { + let val = (gray * 255.0).round().clamp(0.0, 255.0) as u8; + self.current_state.fill_color = [val, val, val]; + } + } + "G" => { + if let Some(gray) = operands.first().and_then(to_f64) { + let val = (gray * 255.0).round().clamp(0.0, 255.0) as u8; + self.current_state.stroke_color = [val, val, val]; + } + } + "w" => { + if let Some(lw) = operands.first().and_then(to_f64) { + self.current_state.line_width = lw; + } + } + + // Vektör Çizim Yolları + "m" => { + if operands.len() >= 2 { + let x = to_f64(&operands[0]).unwrap_or(0.0); + let y = to_f64(&operands[1]).unwrap_or(0.0); + let pt = self.current_state.ctm.transform_point(x, y); + self.current_state.current_point = Some(pt); + self.current_subpath = vec![pt]; + } + } + "l" => { + if operands.len() >= 2 { + let x = to_f64(&operands[0]).unwrap_or(0.0); + let y = to_f64(&operands[1]).unwrap_or(0.0); + let pt = self.current_state.ctm.transform_point(x, y); + self.current_subpath.push(pt); + self.current_state.current_point = Some(pt); + } + } + "re" => { + if operands.len() >= 4 { + let rx = to_f64(&operands[0]).unwrap_or(0.0); + let ry = to_f64(&operands[1]).unwrap_or(0.0); + let rw = to_f64(&operands[2]).unwrap_or(0.0); + let rh = to_f64(&operands[3]).unwrap_or(0.0); + + let p0 = self.current_state.ctm.transform_point(rx, ry); + let p1 = self.current_state.ctm.transform_point(rx + rw, ry); + let p2 = self.current_state.ctm.transform_point(rx + rw, ry + rh); + let p3 = self.current_state.ctm.transform_point(rx, ry + rh); + + self.current_subpath = vec![p0, p1, p2, p3, p0]; + } + } + "h" => { + if let Some(&first) = self.current_subpath.first() { + self.current_subpath.push(first); + } + } + "S" | "s" => { + self.paint_stroke(); + self.current_subpath.clear(); + } + "f" | "F" | "f*" => { + self.paint_fill(); + self.current_subpath.clear(); + } + "B" | "b" | "B*" | "b*" => { + self.paint_fill(); + self.paint_stroke(); + self.current_subpath.clear(); + } + "n" => { + self.current_subpath.clear(); + } + + // XObject Çağrısı (Görsel veya Form) + "Do" => { + if let Some(name_obj) = operands.first() { + if let Ok(name) = name_obj.as_name() { + self.handle_xobject(name); + } + } + } + + _ => {} + } + } + + fn paint_stroke(&mut self) { + if self.current_subpath.len() < 2 { + return; + } + + // Çizgi parçalarını tara + for i in 0..self.current_subpath.len() - 1 { + let (x1_raw, y1_raw) = self.current_subpath[i]; + let (x2_raw, y2_raw) = self.current_subpath[i + 1]; + + let (p1_x, p1_y) = self.page_box.to_top_left_point(x1_raw, y1_raw); + let (p2_x, p2_y) = self.page_box.to_top_left_point(x2_raw, y2_raw); + + let is_h = (p1_y - p2_y).abs() <= 1.5; + let is_v = (p1_x - p2_x).abs() <= 1.5; + + if is_h || is_v { + self.lines.push(VectorLine { + x1: p1_x.min(p2_x), + y1: p1_y.min(p2_y), + x2: p1_x.max(p2_x), + y2: p1_y.max(p2_y), + is_horizontal: is_h, + thickness: self.current_state.line_width.max(0.5), + color: self.current_state.stroke_color, + }); + } + } + } + + fn paint_fill(&mut self) { + if self.current_subpath.len() < 3 { + return; + } + + let mut min_x = f64::MAX; + let mut max_x = f64::MIN; + let mut min_y = f64::MAX; + let mut max_y = f64::MIN; + + for &(x, y) in &self.current_subpath { + let (px, py) = self.page_box.to_top_left_point(x, y); + min_x = min_x.min(px); + max_x = max_x.max(px); + min_y = min_y.min(py); + max_y = max_y.max(py); + } + + let w = (max_x - min_x).abs(); + let h = (max_y - min_y).abs(); + + if w > 0.0 && h > 0.0 { + // İnce çizgi kontrolü (< 3.0 pt): kesir veya tablo çizgisi olarak kaydet + if h <= 3.0 || w <= 3.0 { + self.lines.push(VectorLine { + x1: min_x, + y1: min_y, + x2: max_x, + y2: max_y, + is_horizontal: w >= h, + thickness: h.min(w).max(0.5), + color: self.current_state.fill_color, + }); + } else { + // Dolgulu dikdörtgen: tablo hücresi arkaplanı veya vurgu kutusu + self.filled_rects.push(FilledRect { + x: min_x, + y: min_y, + width: w, + height: h, + color: self.current_state.fill_color, + }); + } + } + } + + fn handle_xobject(&mut self, name: &[u8]) { + let xobj_ref = match self.xobjects.get(name) { + Some(obj) => obj.clone(), + None => return, + }; + + let stream = match resolve_stream(self.doc, &xobj_ref) { + Some(s) => s, + None => return, + }; + + let subtype = stream.dict.get(b"Subtype").ok().and_then(|o| o.as_name().ok()).unwrap_or(b""); + + if subtype == b"Image" { + if let Some(img) = ImageExtractor::extract(self.doc, stream, &self.current_state.ctm, self.page_box) { + self.images.push(img); + } + } else if subtype == b"Form" { + // Form XObject: özyinelemeli değerlendirme + let form_matrix = stream + .dict + .get(b"Matrix") + .ok() + .and_then(|o| o.as_array().ok()) + .map(|arr| parse_matrix_operands(arr)) + .unwrap_or_else(AffineMatrix::identity); + + let old_ctm = self.current_state.ctm; + self.current_state.ctm = form_matrix.multiply(&old_ctm); + + let content_bytes = stream + .decompressed_content() + .unwrap_or_else(|_| stream.content.clone()); + if !content_bytes.is_empty() { + self.state_stack.push(self.current_state.clone()); + self.interpret_stream(&content_bytes); + self.current_state = self.state_stack.pop().unwrap_or(self.current_state.clone()); + } + + self.current_state.ctm = old_ctm; + } + } + + fn show_text_object(&mut self, obj: &Object) { + let bytes = match obj { + Object::String(b, _) => b.clone(), + _ => return, + }; + + let font_key = self.current_state.font_name.as_bytes(); + let font = self.fonts.get(font_key).cloned().unwrap_or_default(); + + self.emit_text_bytes(&bytes, &font); + } + + fn show_text_array(&mut self, arr: &[Object]) { + let font_key = self.current_state.font_name.as_bytes(); + let font = self.fonts.get(font_key).cloned().unwrap_or_default(); + + for item in arr { + if let Some(shift) = to_f64(item) { + // TJ kerning kaydırması: dx = -(shift / 1000) * font_size * (h_scale / 100) + let fs = self.current_state.font_size; + let h_scale = self.current_state.horizontal_scaling / 100.0; + let dx = -(shift / 1000.0) * fs * h_scale; + let trans = AffineMatrix::new(1.0, 0.0, 0.0, 1.0, dx, 0.0); + self.current_state.text_matrix = trans.multiply(&self.current_state.text_matrix); + } else if let Ok(bytes) = item.as_str() { + self.emit_text_bytes(bytes, &font); + } + } + } + + fn emit_text_bytes(&mut self, bytes: &[u8], font: &ParsedFont) { + let h_scale = self.current_state.horizontal_scaling / 100.0; + let c_space = self.current_state.char_spacing; + let w_space = self.current_state.word_spacing; + + // Gerçek sayfa üzerindeki efektif font boyutu ve X/Y matris ölçekleri + let tm_scale_y = (self.current_state.text_matrix.c.powi(2) + self.current_state.text_matrix.d.powi(2)).sqrt(); + let ctm_scale_y = (self.current_state.ctm.c.powi(2) + self.current_state.ctm.d.powi(2)).sqrt(); + let mut effective_font_size = (self.current_state.font_size * tm_scale_y * ctm_scale_y).abs(); + if effective_font_size < 0.5 { + effective_font_size = self.current_state.font_size.abs().max(1.0); + } + + let tm_scale_x = (self.current_state.text_matrix.a.powi(2) + self.current_state.text_matrix.b.powi(2)).sqrt(); + let ctm_scale_x = (self.current_state.ctm.a.powi(2) + self.current_state.ctm.b.powi(2)).sqrt(); + let mut effective_scale_x = (tm_scale_x * ctm_scale_x).abs(); + if effective_scale_x < 0.001 { + effective_scale_x = (tm_scale_y * ctm_scale_y).max(1.0); + } + + let is_bold_font = font.is_bold || self.current_state.render_mode == 2; + + let codes: Vec = if font.is_two_byte { + bytes + .chunks(2) + .map(|chunk| { + if chunk.len() == 2 { + ((chunk[0] as u32) << 8) | (chunk[1] as u32) + } else { + chunk[0] as u32 + } + }) + .collect() + } else { + bytes.iter().map(|&b| b as u32).collect() + }; + + for code in codes { + let (decoded_str, glyph_w, is_math) = font.decode_char(code); + + // Metin dönüşüm matrisi x CTM + let trm = self.current_state.text_matrix.multiply(&self.current_state.ctm); + let (x_pt, y_pt) = trm.transform_point(0.0, self.current_state.text_rise); + let (norm_x, norm_y) = self.page_box.to_top_left_point(x_pt, y_pt); + + // Glif genişliği eksik veya sıfırsa karakter duyarlı oransal fallback genişliği uygula + let fallback_w = if decoded_str == " " { + effective_font_size * 0.28 + } else if matches!(decoded_str.as_str(), "i" | "l" | "ı" | "İ" | "I" | "." | "," | ":" | ";" | "'" | "!" | "|" | "(" | ")") { + effective_font_size * 0.26 + } else if matches!(decoded_str.as_str(), "m" | "w" | "M" | "W" | "@") { + effective_font_size * 0.78 + } else { + effective_font_size * 0.52 + }; + + let base_char_width_pt = if glyph_w > 0.0 { + (glyph_w / 1000.0) * (self.current_state.font_size.abs() * effective_scale_x).max(0.5) * h_scale + } else { + fallback_w * h_scale + }; + + // Harf aralıklı (Tc > 0) başlıklarda kelimenin parçalanmaması için makul Tc payını genişliğe kat + let tc_padding = if c_space > 0.0 { + c_space.min(self.current_state.font_size.abs() * 0.25) * effective_scale_x * h_scale + } else { + 0.0 + }; + let char_width_pt = base_char_width_pt + tc_padding; + + let char_y = norm_y - effective_font_size; // Sol-üst köşe hizalaması + let mut is_duplicate_shadow = false; + + // Sahte Kalın (Fake Bold / Shadow glyph) tespiti ve tekilleştirme: + // Aynı karakter 0.05..0.6 pt gibi mikro farkla üst üste basılmışsa önceki karakteri kalın yap ve kopyayı yut + if !decoded_str.trim().is_empty() { + if let Some(prev) = self.chars.last_mut() { + if prev.unicode == decoded_str + && (norm_x - prev.x).abs() <= (effective_font_size * 0.15).max(0.6) + && (char_y - prev.y).abs() <= (effective_font_size * 0.15).max(0.6) + { + prev.is_bold = true; + is_duplicate_shadow = true; + } + } + } + + if !is_duplicate_shadow && !decoded_str.is_empty() { + self.chars.push(PdfChar { + unicode: decoded_str.clone(), + x: norm_x, + y: char_y, + width: char_width_pt.max(1.0), + height: effective_font_size, + font_size: effective_font_size, + font_name: font.name.clone(), + is_math, + is_bold: is_bold_font, + is_italic: font.is_italic, + color: self.current_state.fill_color, + }); + } + + // Metin matrisinde x ilerlemesi (Tc ve boşluklarda Tw dahil) + let word_gap = if code == 32 || decoded_str == " " { w_space } else { 0.0 }; + let text_advance_x = if glyph_w > 0.0 { + (glyph_w / 1000.0) * self.current_state.font_size + c_space + word_gap + } else { + (fallback_w / effective_scale_x.max(0.001)) + c_space + word_gap + }; + let trans = AffineMatrix::new(1.0, 0.0, 0.0, 1.0, text_advance_x * h_scale, 0.0); + self.current_state.text_matrix = trans.multiply(&self.current_state.text_matrix); + } + } +} + +fn parse_matrix_operands(ops: &[Object]) -> AffineMatrix { + let a = ops.first().and_then(to_f64).unwrap_or(1.0); + let b = ops.get(1).and_then(to_f64).unwrap_or(0.0); + let c = ops.get(2).and_then(to_f64).unwrap_or(0.0); + let d = ops.get(3).and_then(to_f64).unwrap_or(1.0); + let e = ops.get(4).and_then(to_f64).unwrap_or(0.0); + let f = ops.get(5).and_then(to_f64).unwrap_or(0.0); + AffineMatrix::new(a, b, c, d, e, f) +} + +fn to_f64(obj: &Object) -> Option { + match obj { + Object::Real(f) => Some(*f as f64), + Object::Integer(i) => Some(*i as f64), + _ => None, + } +} + +fn resolve_dict<'a>(doc: &'a Document, obj: &'a Object) -> Option<&'a lopdf::Dictionary> { + match obj { + Object::Reference(id) => doc.get_object(*id).ok().and_then(|o| o.as_dict().ok()), + Object::Dictionary(d) => Some(d), + _ => None, + } +} + +fn resolve_stream<'a>(doc: &'a Document, obj: &'a Object) -> Option<&'a lopdf::Stream> { + match obj { + Object::Reference(id) => doc.get_object(*id).ok().and_then(|o| o.as_stream().ok()), + Object::Stream(s) => Some(s), + _ => None, + } +} diff --git a/src-tauri/src/services/pdf_parser/font_resolver.rs b/src-tauri/src/services/pdf_parser/font_resolver.rs new file mode 100644 index 0000000..ca579de --- /dev/null +++ b/src-tauri/src/services/pdf_parser/font_resolver.rs @@ -0,0 +1,650 @@ +//! 5-Kademeli Font ve Glif Çözücü (5-Tier Font & Glyph Resolver). +//! +//! Tier 1: `/ToUnicode` CMap (vekil çiftleri, NFC normalizasyon, Türkçe birleştirici aksanlar) +//! Tier 2: `/Encoding` + `/Differences` + Tam Adobe Glyph List (AGL) +//! Tier 3: Gömülü TrueType / OpenType font ayrıştırma (`ttf-parser`) +//! Tier 4: TeX Computer Modern / Math tabloları (`CMMI`, `CMSY`, `CMEX`, `Symbol`) +//! Tier 5: Glif genişlikleri (`/Widths`, `/W`, `hmtx`) + +use std::collections::HashMap; +use lopdf::{Document, Object, ObjectId}; +use unicode_normalization::UnicodeNormalization; + +use super::tex_font_maps::*; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum BaseEncoding { + #[default] + WinAnsi, + MacRoman, + Standard, + Symbol, + Identity, +} + +#[derive(Debug, Clone)] +pub struct ParsedFont { + pub name: String, + pub is_two_byte: bool, + pub is_math_font: bool, + pub is_italic: bool, + pub is_bold: bool, + pub to_unicode_map: HashMap, + pub encoding_map: HashMap, + pub widths: HashMap, + pub default_width: f64, + pub ttf_data: Option>, +} + +impl Default for ParsedFont { + fn default() -> Self { + Self { + name: String::new(), + is_two_byte: false, + is_math_font: false, + is_italic: false, + is_bold: false, + to_unicode_map: HashMap::new(), + encoding_map: HashMap::new(), + widths: HashMap::new(), + default_width: 0.0, + ttf_data: None, + } + } +} + +impl ParsedFont { + /// Karakter kodunu (1-byte veya 2-byte) 5 kademeli çözücüden geçirerek + /// Unicode dizesine ve genişliğine dönüştürür. + pub fn decode_char(&self, code: u32) -> (String, f64, bool) { + let width = self.glyph_width(code); + + // Tier 1: /ToUnicode CMap + if let Some(text) = self.to_unicode_map.get(&code) { + let normalized = normalize_turkish_and_nfc(text); + return (normalized, width, self.is_math_font); + } + + // Tier 4: TeX / LaTeX Math Fonts + let name_upper = self.name.to_ascii_uppercase(); + if name_upper.contains("CMMI") { + if let Some(ch) = tex_cmmi_to_unicode(code as u8) { + return (ch.to_string(), width, true); + } + } else if name_upper.contains("CMSY") { + if let Some(ch) = tex_cmsy_to_unicode(code as u8) { + return (ch.to_string(), width, true); + } + } else if name_upper.contains("CMEX") { + if let Some(ch) = tex_cmex_to_unicode(code as u8) { + return (ch.to_string(), width, true); + } + } else if name_upper.contains("SYMBOL") { + if let Some(ch) = symbol_font_to_unicode(code as u8) { + return (ch.to_string(), width, true); + } + } + + // Tier 2: /Encoding + /Differences + AGL + if let Some(text) = self.encoding_map.get(&code) { + let normalized = normalize_turkish_and_nfc(text); + return (normalized, width, self.is_math_font); + } + + // Tier 3: Gömülü TrueType cmap / post ayrıştırma + if let Some(ttf) = &self.ttf_data { + if let Ok(face) = ttf_parser::Face::parse(ttf, 0) { + if let Some(subtable) = face.tables().cmap { + for st in subtable.subtables { + if let Some(glyph_id) = st.glyph_index(code) { + if let Some(ch) = char::from_u32(code) { + if !ch.is_control() { + return (ch.to_string(), width, self.is_math_font); + } + } + if glyph_id.0 > 0 { + if let Some(ch) = char::from_u32(glyph_id.0 as u32) { + return (ch.to_string(), width, self.is_math_font); + } + } + } + } + } + } + } + + // Son yedek: Standart WinAnsi / ASCII + if code < 256 { + if let Some(ch) = decode_winansi_fallback(code as u8) { + return (ch.to_string(), width, self.is_math_font); + } + } + + if let Some(ch) = char::from_u32(code) { + if !ch.is_control() { + return (ch.to_string(), width, self.is_math_font); + } + } + + (String::new(), width, self.is_math_font) + } + + pub fn glyph_width(&self, code: u32) -> f64 { + if let Some(&w) = self.widths.get(&code) { + return w; + } + // Gömülü TrueType font varsa hmtx'ten tam glif genişliğini çek: + if let Some(ttf) = &self.ttf_data { + if let Ok(face) = ttf_parser::Face::parse(ttf, 0) { + let upem = face.units_per_em() as f64; + if upem > 0.0 { + let gid = char::from_u32(code) + .and_then(|ch| face.glyph_index(ch)) + .or_else(|| { + if self.is_two_byte { + u16::try_from(code).ok().map(ttf_parser::GlyphId) + } else { + None + } + }); + if let Some(glyph_id) = gid { + if let Some(advance) = face.glyph_hor_advance(glyph_id) { + return (advance as f64 / upem) * 1000.0; + } + } + } + } + } + self.default_width + } +} + +/// Türkçe birleştirici aksanları (combining diacritics) ve NFC normalizasyonunu uygular. +fn normalize_turkish_and_nfc(s: &str) -> String { + let mut text = s.to_string(); + // Yaygın PDF birleştirici aksan kalıpları: + text = text.replace("c\u{0327}", "ç") + .replace("C\u{0327}", "Ç") + .replace("s\u{0327}", "ş") + .replace("S\u{0327}", "Ş") + .replace("g\u{0306}", "ğ") + .replace("G\u{0306}", "Ğ") + .replace("u\u{0308}", "ü") + .replace("U\u{0308}", "Ü") + .replace("o\u{0308}", "ö") + .replace("O\u{0308}", "Ö") + .replace("i\u{0307}", "i") + .replace("I\u{0307}", "İ"); + + // Standart Unicode NFC Canonical Composition + text.nfc().collect::() +} + +fn decode_winansi_fallback(b: u8) -> Option { + match b { + 0x20..=0x7E => Some(b as char), + 0x80 => Some('€'), + 0x82 => Some('‚'), + 0x83 => Some('ƒ'), + 0x84 => Some('„'), + 0x85 => Some('…'), + 0x86 => Some('†'), + 0x87 => Some('‡'), + 0x88 => Some('ˆ'), + 0x89 => Some('‰'), + 0x8A => Some('Š'), + 0x8B => Some('‹'), + 0x8C => Some('Œ'), + 0x8E => Some('Ž'), + 0x91 => Some('‘'), + 0x92 => Some('’'), + 0x93 => Some('“'), + 0x94 => Some('”'), + 0x95 => Some('•'), + 0x96 => Some('–'), + 0x97 => Some('—'), + 0x98 => Some('˜'), + 0x99 => Some('™'), + 0x9A => Some('š'), + 0x9B => Some('›'), + 0x9C => Some('œ'), + 0x9E => Some('ž'), + 0x9F => Some('Ÿ'), + 0xA0..=0xFF => Some(b as char), + _ => None, + } +} + +pub struct FontResolver { + cache: HashMap, +} + +impl Default for FontResolver { + fn default() -> Self { + Self::new() + } +} + +impl FontResolver { + pub fn new() -> Self { + Self { + cache: HashMap::new(), + } + } + + pub fn resolve(&mut self, doc: &Document, font_obj: &Object) -> ParsedFont { + if let Ok(id) = font_obj.as_reference() { + if let Some(f) = self.cache.get(&id) { + return f.clone(); + } + } + + let dict = match resolve_dict(doc, font_obj) { + Some(d) => d, + None => return ParsedFont::default(), + }; + + let parsed = self.parse_font_dict(doc, dict); + + if let Ok(id) = font_obj.as_reference() { + self.cache.insert(id, parsed.clone()); + } + parsed + } + + fn parse_font_dict(&mut self, doc: &Document, dict: &lopdf::Dictionary) -> ParsedFont { + let mut font = ParsedFont::default(); + + let base_font_name = dict + .get(b"BaseFont") + .ok() + .and_then(|obj| resolve_object(doc, obj).as_name().ok()) + .map(|n| String::from_utf8_lossy(n).to_string()) + .unwrap_or_default(); + + font.name = base_font_name.clone(); + + let subtype = dict + .get(b"Subtype") + .ok() + .and_then(|obj| resolve_object(doc, obj).as_name().ok()) + .map(|n| String::from_utf8_lossy(n).to_string()) + .unwrap_or_default(); + + font.is_two_byte = subtype == "Type0"; + + apply_font_name_flags(&base_font_name, &mut font); + + // FontDescriptor üzerinden ek kalınlık, italik ve gömülü font okuma + apply_font_descriptor(doc, dict, &mut font); + + // 1) /ToUnicode CMap Okuma + if let Ok(to_uni_obj) = dict.get(b"ToUnicode") { + let to_uni = resolve_object(doc, to_uni_obj); + if let Ok(stream) = to_uni.as_stream() { + let decompressed = stream + .decompressed_content() + .unwrap_or_else(|_| stream.content.clone()); + let cmap_str = String::from_utf8_lossy(&decompressed); + font.to_unicode_map = parse_tounicode_cmap(&cmap_str); + } + } + + // 2) /Encoding ve /Differences Okuma + if let Ok(enc_obj) = dict.get(b"Encoding") { + let enc = resolve_object(doc, enc_obj); + if let Ok(name) = enc.as_name() { + let base_enc = match name { + b"MacRomanEncoding" => BaseEncoding::MacRoman, + b"StandardEncoding" => BaseEncoding::Standard, + _ => BaseEncoding::WinAnsi, + }; + font.encoding_map = build_base_encoding_map(base_enc); + } else if let Ok(enc_dict) = enc.as_dict() { + let base_enc = if let Ok(base_name) = enc_dict.get(b"BaseEncoding").and_then(|o| resolve_object(doc, o).as_name()) { + match base_name { + b"MacRomanEncoding" => BaseEncoding::MacRoman, + b"StandardEncoding" => BaseEncoding::Standard, + _ => BaseEncoding::WinAnsi, + } + } else { + BaseEncoding::WinAnsi + }; + font.encoding_map = build_base_encoding_map(base_enc); + + if let Ok(diff_obj) = enc_dict.get(b"Differences") { + let diff = resolve_object(doc, diff_obj); + if let Ok(arr) = diff.as_array() { + apply_differences(arr, &mut font.encoding_map); + } + } + } + } else { + font.encoding_map = build_base_encoding_map(BaseEncoding::WinAnsi); + } + + // 4) /Widths & /W Okuma + if let Ok(widths_obj) = dict.get(b"Widths") { + let first_char = dict.get(b"FirstChar").ok().and_then(|o| resolve_object(doc, o).as_i64().ok()).unwrap_or(0) as u32; + let w_obj = resolve_object(doc, widths_obj); + if let Ok(arr) = w_obj.as_array() { + for (idx, item) in arr.iter().enumerate() { + if let Some(w) = to_f64(resolve_object(doc, item)) { + font.widths.insert(first_char + idx as u32, w); + } + } + } + } + + // Type0 / DescendantFonts (CIDFont): BaseFont, FontDescriptor, DW ve W dizisi + if let Ok(descendants_obj) = dict.get(b"DescendantFonts") { + let desc = resolve_object(doc, descendants_obj); + if let Ok(arr) = desc.as_array() { + if let Some(first_desc) = arr.first() { + let cid_dict = resolve_dict(doc, first_desc); + if let Some(cid_d) = cid_dict { + if let Ok(cid_base_name) = cid_d.get(b"BaseFont").and_then(|o| resolve_object(doc, o).as_name()) { + let cid_name = String::from_utf8_lossy(cid_base_name); + if font.name.is_empty() { + font.name = cid_name.to_string(); + } + apply_font_name_flags(&cid_name, &mut font); + } + apply_font_descriptor(doc, cid_d, &mut font); + + if let Ok(dw_obj) = cid_d.get(b"DW") { + if let Some(dw) = to_f64(resolve_object(doc, dw_obj)) { + if dw > 0.0 { + font.default_width = dw; + } + } + } + if let Ok(w_obj) = cid_d.get(b"W") { + let w_arr = resolve_object(doc, w_obj); + if let Ok(items) = w_arr.as_array() { + parse_cid_w_array(doc, items, &mut font.widths); + } + } + } + } + } + } + + font + } +} + +fn apply_font_name_flags(font_name: &str, font: &mut ParsedFont) { + let name_upper = font_name.to_ascii_uppercase(); + if name_upper.contains("CMMI") + || name_upper.contains("CMSY") + || name_upper.contains("CMEX") + || name_upper.contains("MATH") + || name_upper.contains("SYMBOL") + || name_upper.contains("MTEXTRA") + || name_upper.contains("EUEX") + || name_upper.contains("MSAM") + || name_upper.contains("MSBM") + { + font.is_math_font = true; + } + + if name_upper.contains("ITALIC") || name_upper.contains("OBLIQUE") || name_upper.contains("CMMI") { + font.is_italic = true; + } + + if name_upper.contains("BOLD") + || name_upper.contains("BD") + || name_upper.contains("MED") + || name_upper.contains("BLACK") + || name_upper.contains("HEAVY") + || name_upper.contains("CMBX") + || name_upper.contains("RB") + { + font.is_bold = true; + } +} + +fn apply_font_descriptor(doc: &Document, dict: &lopdf::Dictionary, font: &mut ParsedFont) { + let Ok(desc_obj) = dict.get(b"FontDescriptor") else { + return; + }; + let desc = resolve_object(doc, desc_obj); + let Ok(desc_dict) = desc.as_dict() else { + return; + }; + + if let Ok(weight) = desc_dict.get(b"FontWeight").and_then(|o| resolve_object(doc, o).as_i64()) { + if weight >= 600 { + font.is_bold = true; + } + } + if let Ok(flags) = desc_dict.get(b"Flags").and_then(|o| resolve_object(doc, o).as_i64()) { + if (flags & (1 << 6)) != 0 { + font.is_italic = true; + } + if (flags & (1 << 18)) != 0 { + font.is_bold = true; + } + } + if let Ok(font_name) = desc_dict.get(b"FontName").and_then(|o| resolve_object(doc, o).as_name()) { + let desc_name = String::from_utf8_lossy(font_name); + apply_font_name_flags(&desc_name, font); + } + + if font.ttf_data.is_none() { + for file_key in [&b"FontFile2"[..], &b"FontFile3"[..], &b"FontFile"[..]].iter() { + if let Ok(file_obj) = desc_dict.get(file_key) { + let f_obj = resolve_object(doc, file_obj); + if let Ok(stream) = f_obj.as_stream() { + let decomp = stream + .decompressed_content() + .unwrap_or_else(|_| stream.content.clone()); + if !decomp.is_empty() { + font.ttf_data = Some(decomp.to_vec()); + break; + } + } + } + } + } +} + +fn resolve_object<'a>(doc: &'a Document, object: &'a Object) -> &'a Object { + match object { + Object::Reference(id) => doc.get_object(*id).unwrap_or(object), + _ => object, + } +} + +fn resolve_dict<'a>(doc: &'a Document, object: &'a Object) -> Option<&'a lopdf::Dictionary> { + match resolve_object(doc, object) { + Object::Dictionary(dict) => Some(dict), + Object::Stream(stream) => Some(&stream.dict), + _ => None, + } +} + +fn to_f64(obj: &Object) -> Option { + match obj { + Object::Real(f) => Some(*f as f64), + Object::Integer(i) => Some(*i as f64), + _ => None, + } +} + +fn parse_cid_w_array(doc: &Document, items: &[Object], widths: &mut HashMap) { + let mut i = 0; + while i < items.len() { + let Some(first_code) = resolve_object(doc, &items[i]).as_i64().map(|v| v as u32).ok() else { + i += 1; + continue; + }; + i += 1; + if i >= items.len() { + break; + } + + let second = resolve_object(doc, &items[i]); + if let Ok(arr) = second.as_array() { + for (idx, w_obj) in arr.iter().enumerate() { + if let Some(w) = to_f64(resolve_object(doc, w_obj)) { + widths.insert(first_code + idx as u32, w); + } + } + i += 1; + } else if let Ok(last_code) = second.as_i64().map(|v| v as u32) { + i += 1; + if i < items.len() { + if let Some(w) = to_f64(resolve_object(doc, &items[i])) { + for code in first_code..=last_code { + widths.insert(code, w); + } + } + i += 1; + } + } else { + i += 1; + } + } +} + +fn build_base_encoding_map(enc: BaseEncoding) -> HashMap { + let mut map = HashMap::with_capacity(256); + for b in 0u8..=255 { + let ch = match enc { + BaseEncoding::WinAnsi => decode_winansi_fallback(b), + _ => if (32..=126).contains(&b) { Some(b as char) } else { None }, + }; + if let Some(c) = ch { + map.insert(b as u32, c.to_string()); + } + } + map +} + +fn apply_differences(items: &[Object], map: &mut HashMap) { + let mut current_code = 0u32; + for item in items { + if let Ok(code) = item.as_i64() { + current_code = code as u32; + } else if let Ok(name_bytes) = item.as_name() { + let name = String::from_utf8_lossy(name_bytes); + if let Some(s) = agl_glyph_name_to_unicode(&name) { + map.insert(current_code, s); + } + current_code += 1; + } + } +} + +/// `/ToUnicode` CMap akışını ayrıştırır. +fn parse_tounicode_cmap(cmap: &str) -> HashMap { + let mut map = HashMap::new(); + let lines: Vec<&str> = cmap.lines().collect(); + + let mut in_bfchar = false; + let mut in_bfrange = false; + + for line in lines { + let trimmed = line.trim(); + if trimmed.contains("beginbfchar") { + in_bfchar = true; + in_bfrange = false; + continue; + } + if trimmed.contains("endbfchar") { + in_bfchar = false; + continue; + } + if trimmed.contains("beginbfrange") { + in_bfrange = true; + in_bfchar = false; + continue; + } + if trimmed.contains("endbfrange") { + in_bfrange = false; + continue; + } + + if in_bfchar { + let parts: Vec<&str> = trimmed.split_whitespace().collect(); + if parts.len() >= 2 { + if let (Some(code), Some(text)) = (parse_hex_code(parts[0]), parse_hex_unicode(parts[1])) { + map.insert(code, text); + } + } + } else if in_bfrange { + let parts: Vec<&str> = trimmed.split_whitespace().collect(); + if parts.len() >= 3 { + if let (Some(start), Some(end)) = (parse_hex_code(parts[0]), parse_hex_code(parts[1])) { + if parts[2].starts_with('<') { + if let Some(base_str) = parse_hex_unicode(parts[2]) { + let mut base_chars: Vec = base_str.chars().map(|c| c as u32).collect(); + for (offset, code) in (start..=end).enumerate() { + if let Some(last) = base_chars.last_mut() { + let c_code = *last + offset as u32; + if let Some(ch) = char::from_u32(c_code) { + map.insert(code, ch.to_string()); + } + } + } + } + } else if parts[2].starts_with('[') { + // Dizi biçimi [<0001> <0002> ...] + let inner = trimmed.trim_start_matches(|c| c != '[').trim_matches(|c| c == '[' || c == ']'); + let tokens: Vec<&str> = inner.split_whitespace().collect(); + for (idx, tok) in tokens.iter().enumerate() { + let code = start + idx as u32; + if code <= end { + if let Some(text) = parse_hex_unicode(tok) { + map.insert(code, text); + } + } + } + } + } + } + } + } + + map +} + +fn parse_hex_code(token: &str) -> Option { + let clean = token.trim_matches(|c| c == '<' || c == '>'); + u32::from_str_radix(clean, 16).ok() +} + +fn parse_hex_unicode(token: &str) -> Option { + let clean = token.trim_matches(|c| c == '<' || c == '>'); + if clean.is_empty() { + return None; + } + // 4'erli hex grupları (UTF-16BE) veya 2'şerli (ASCII/Latin1) + if clean.len() % 4 == 0 { + let mut u16_units = Vec::new(); + for chunk in clean.as_bytes().chunks(4) { + if let Ok(s) = std::str::from_utf8(chunk) { + if let Ok(val) = u16::from_str_radix(s, 16) { + u16_units.push(val); + } + } + } + if let Ok(text) = String::from_utf16(&u16_units) { + return Some(text); + } + } else if clean.len() % 2 == 0 { + let mut u8_units = Vec::new(); + for chunk in clean.as_bytes().chunks(2) { + if let Ok(s) = std::str::from_utf8(chunk) { + if let Ok(val) = u8::from_str_radix(s, 16) { + u8_units.push(val); + } + } + } + return Some(String::from_utf8_lossy(&u8_units).to_string()); + } + + None +} diff --git a/src-tauri/src/services/pdf_parser/image_extractor.rs b/src-tauri/src/services/pdf_parser/image_extractor.rs new file mode 100644 index 0000000..77b43cd --- /dev/null +++ b/src-tauri/src/services/pdf_parser/image_extractor.rs @@ -0,0 +1,340 @@ +//! PDF Görüntü Çıkarıcı (Image XObject Extractor). +//! +//! `/Filter /DCTDecode` (JPEG) ve `/Filter /FlateDecode` (PNG/zlib, PNG Predictor 10..15, +//! Indexed renk uzayı ve `/SMask` şeffaflık maskesi) akışlarını saf Rust ile çözerek +//! Word belgesine doğrudan eklenebilir EMU / pt koordinatlı görsellere dönüştürür. + +use std::io::Cursor; +use lopdf::{Document, Object}; +use image::{ColorType, ImageEncoder}; + +use crate::services::office_model::{ImageBlock, ImageFormat}; +use super::matrix::{AffineMatrix, PageBox}; + +#[derive(Debug, Clone)] +pub struct ExtractedImage { + pub data: Vec, + pub format: ImageFormat, + pub x_pt: f64, + pub y_pt: f64, + pub width_pt: f64, + pub height_pt: f64, +} + +impl ExtractedImage { + pub fn to_office_image(&self) -> ImageBlock { + ImageBlock { + data: self.data.clone(), + format: self.format, + width_pt: self.width_pt.max(10.0) as f32, + height_pt: self.height_pt.max(10.0) as f32, + alt: Some("PDF Image".to_string()), + } + } +} + +pub struct ImageExtractor; + +impl ImageExtractor { + /// Bir Image XObject akışını ve CTM matrisini çözerek `ExtractedImage` üretir. + pub fn extract( + doc: &Document, + stream: &lopdf::Stream, + ctm: &AffineMatrix, + page_box: &PageBox, + ) -> Option { + let dict = &stream.dict; + + // Subtype /Image doğrulaması + let is_image = dict + .get(b"Subtype") + .ok() + .and_then(|o| o.as_name().ok()) + .map(|n| n == b"Image") + .unwrap_or(false); + + if !is_image { + return None; + } + + let width = dict.get(b"Width").ok().and_then(|o| o.as_i64().ok())? as u32; + let height = dict.get(b"Height").ok().and_then(|o| o.as_i64().ok())? as u32; + if width == 0 || height == 0 { + return None; + } + + // CTM koordinat hesaplaması: PDF'te birim kare [0,0] -> [1,1] dönüştürülür + let (p0_x, p0_y) = ctm.transform_point(0.0, 0.0); + let (p1_x, p1_y) = ctm.transform_point(1.0, 0.0); + let (p2_x, p2_y) = ctm.transform_point(0.0, 1.0); + let (p3_x, p3_y) = ctm.transform_point(1.0, 1.0); + + let min_x = p0_x.min(p1_x).min(p2_x).min(p3_x); + let max_x = p0_x.max(p1_x).max(p2_x).max(p3_x); + let min_y = p0_y.min(p1_y).min(p2_y).min(p3_y); + let max_y = p0_y.max(p1_y).max(p2_y).max(p3_y); + + let (tl_x, tl_y) = page_box.to_top_left_point(min_x, max_y); + let w_pt = (max_x - min_x).abs(); + let h_pt = (max_y - min_y).abs(); + + // Filtre kontrolü + let filter = dict.get(b"Filter").ok().and_then(|o| match o { + Object::Name(name) => Some(vec![name.clone()]), + Object::Array(arr) => { + let names: Vec> = arr.iter().filter_map(|item| item.as_name().ok().map(|n| n.to_vec())).collect(); + Some(names) + } + _ => None, + }); + + // 1) Doğrudan JPEG (/DCTDecode) + if let Some(filters) = &filter { + if filters.iter().any(|f| f == b"DCTDecode") { + return Some(ExtractedImage { + data: stream.content.clone(), + format: ImageFormat::Jpeg, + x_pt: tl_x, + y_pt: tl_y, + width_pt: w_pt, + height_pt: h_pt, + }); + } + } + + // 2) FlateDecode veya ham akış çözümü + let decompressed = stream.decompressed_content().ok()?; + let bpc = dict.get(b"BitsPerComponent").ok().and_then(|o| o.as_i64().ok()).unwrap_or(8) as u32; + + let color_space = dict.get(b"ColorSpace").ok(); + let smask_stream = dict.get(b"SMask").ok().and_then(|sm_obj| match sm_obj { + Object::Reference(id) => doc.get_object(*id).ok().and_then(|o| o.as_stream().ok()), + _ => None, + }); + + let smask_bytes = smask_stream.and_then(|s| s.decompressed_content().ok()); + + let raw_pixels = decode_pixels(&decompressed, dict, width, height, bpc, color_space)?; + + // SMask varsa RGBA'ya birleştir + let (final_bytes, format) = if let Some(mask) = smask_bytes { + let rgba = apply_smask(&raw_pixels, &mask, width, height); + let mut out = Vec::new(); + let encoder = image::codecs::png::PngEncoder::new(Cursor::new(&mut out)); + if encoder.write_image(&rgba, width, height, ColorType::Rgba8.into()).is_ok() { + (out, ImageFormat::Png) + } else { + (rgba, ImageFormat::Png) + } + } else { + let mut out = Vec::new(); + let encoder = image::codecs::png::PngEncoder::new(Cursor::new(&mut out)); + let color_type = if raw_pixels.len() == (width * height * 4) as usize { + ColorType::Rgba8 + } else if raw_pixels.len() == (width * height * 3) as usize { + ColorType::Rgb8 + } else { + ColorType::L8 + }; + if encoder.write_image(&raw_pixels, width, height, color_type.into()).is_ok() { + (out, ImageFormat::Png) + } else { + (raw_pixels, ImageFormat::Png) + } + }; + + Some(ExtractedImage { + data: final_bytes, + format, + x_pt: tl_x, + y_pt: tl_y, + width_pt: w_pt, + height_pt: h_pt, + }) + } +} + +fn decode_pixels( + raw: &[u8], + dict: &lopdf::Dictionary, + width: u32, + height: u32, + bpc: u32, + cs_obj: Option<&Object>, +) -> Option> { + // PNG Predictor kontrolü + let decomp = if let Ok(dp) = dict.get(b"DecodeParms").and_then(|o| o.as_dict()) { + let predictor = dp.get(b"Predictor").ok().and_then(|o| o.as_i64().ok()).unwrap_or(1); + let colors = dp.get(b"Colors").ok().and_then(|o| o.as_i64().ok()).unwrap_or(1) as usize; + let bits = dp.get(b"BitsPerComponent").ok().and_then(|o| o.as_i64().ok()).unwrap_or(8) as usize; + let columns = dp.get(b"Columns").ok().and_then(|o| o.as_i64().ok()).unwrap_or(width as i64) as usize; + + if (10..=15).contains(&predictor) { + unfilter_png_predictor(raw, columns, colors, bits)? + } else { + raw.to_vec() + } + } else { + raw.to_vec() + }; + + // Renk uzayı belirleme + let is_rgb = match cs_obj { + Some(Object::Name(n)) => n == b"DeviceRGB", + Some(Object::Array(arr)) => { + if let Some(first) = arr.first().and_then(|o| o.as_name().ok()) { + if first == b"Indexed" { + return decode_indexed_palette(&decomp, arr, width, height); + } + } + false + } + _ => false, + }; + + if is_rgb && bpc == 8 { + let expected = (width * height * 3) as usize; + if decomp.len() >= expected { + return Some(decomp[..expected].to_vec()); + } + } + + if bpc == 8 && decomp.len() >= (width * height) as usize { + // Grayscale -> RGB + let mut rgb = Vec::with_capacity((width * height * 3) as usize); + for &gray in &decomp[..(width * height) as usize] { + rgb.push(gray); + rgb.push(gray); + rgb.push(gray); + } + return Some(rgb); + } + + if bpc == 1 { + // 1-bit monochrome bitmap + let mut rgb = Vec::with_capacity((width * height * 3) as usize); + let row_bytes = width.div_ceil(8) as usize; + for y in 0..height as usize { + for x in 0..width as usize { + let byte_idx = y * row_bytes + (x / 8); + let bit_idx = 7 - (x % 8); + let bit = if byte_idx < decomp.len() { + (decomp[byte_idx] >> bit_idx) & 1 + } else { + 0 + }; + let val = if bit == 1 { 255u8 } else { 0u8 }; + rgb.push(val); + rgb.push(val); + rgb.push(val); + } + } + return Some(rgb); + } + + Some(decomp) +} + +fn unfilter_png_predictor(data: &[u8], columns: usize, colors: usize, bits: usize) -> Option> { + let bytes_per_pixel = (colors * bits).div_ceil(8); + let bytes_per_row = (columns * colors * bits).div_ceil(8); + let stride = bytes_per_row + 1; // +1 filtre baytı için + + let num_rows = data.len() / stride; + let mut out = Vec::with_capacity(num_rows * bytes_per_row); + let mut prev_row = vec![0u8; bytes_per_row]; + + for row_idx in 0..num_rows { + let offset = row_idx * stride; + let filter_type = data[offset]; + let row_in = &data[offset + 1..offset + 1 + bytes_per_row]; + let mut row_out = vec![0u8; bytes_per_row]; + + for i in 0..bytes_per_row { + let left = if i >= bytes_per_pixel { row_out[i - bytes_per_pixel] } else { 0 }; + let up = prev_row[i]; + let up_left = if i >= bytes_per_pixel { prev_row[i - bytes_per_pixel] } else { 0 }; + + let val = match filter_type { + 0 => row_in[i], + 1 => row_in[i].wrapping_add(left), + 2 => row_in[i].wrapping_add(up), + 3 => row_in[i].wrapping_add(((left as u16 + up as u16) / 2) as u8), + 4 => row_in[i].wrapping_add(paeth_predictor(left, up, up_left)), + _ => row_in[i], + }; + row_out[i] = val; + } + + prev_row = row_out.clone(); + out.extend_from_slice(&row_out); + } + + Some(out) +} + +fn paeth_predictor(a: u8, b: u8, c: u8) -> u8 { + let p = a as i32 + b as i32 - c as i32; + let pa = (p - a as i32).abs(); + let pb = (p - b as i32).abs(); + let pc = (p - c as i32).abs(); + + if pa <= pb && pa <= pc { + a + } else if pb <= pc { + b + } else { + c + } +} + +fn decode_indexed_palette( + indices: &[u8], + cs_arr: &[Object], + width: u32, + height: u32, +) -> Option> { + // [/Indexed, Base, Hival, Lookup] + let lookup_data = match cs_arr.get(3) { + Some(Object::String(bytes, _)) => bytes.clone(), + Some(Object::Stream(stream)) => stream.decompressed_content().ok()?.to_vec(), + _ => return None, + }; + + let mut rgb = Vec::with_capacity((width * height * 3) as usize); + let total_pixels = (width * height) as usize; + + for &idx in indices.iter().take(total_pixels) { + let palette_offset = (idx as usize) * 3; + if palette_offset + 2 < lookup_data.len() { + rgb.push(lookup_data[palette_offset]); + rgb.push(lookup_data[palette_offset + 1]); + rgb.push(lookup_data[palette_offset + 2]); + } else { + rgb.push(0); + rgb.push(0); + rgb.push(0); + } + } + + Some(rgb) +} + +fn apply_smask(rgb: &[u8], mask: &[u8], width: u32, height: u32) -> Vec { + let total_pixels = (width * height) as usize; + let mut rgba = Vec::with_capacity(total_pixels * 4); + + for i in 0..total_pixels { + let r = rgb.get(i * 3).copied().unwrap_or(0); + let g = rgb.get(i * 3 + 1).copied().unwrap_or(0); + let b = rgb.get(i * 3 + 2).copied().unwrap_or(0); + let a = mask.get(i).copied().unwrap_or(255); + + rgba.push(r); + rgba.push(g); + rgba.push(b); + rgba.push(a); + } + + rgba +} diff --git a/src-tauri/src/services/pdf_parser/layout_analyzer.rs b/src-tauri/src/services/pdf_parser/layout_analyzer.rs new file mode 100644 index 0000000..29d25dd --- /dev/null +++ b/src-tauri/src/services/pdf_parser/layout_analyzer.rs @@ -0,0 +1,1294 @@ +//! Sayfa Düzeni (Layout), Sütunlar, Tablolar ve Paragraflar (`pdf2docx` Seviyesi). +//! +//! 2 Aşamalı Satır Kümeleme + X-Sıralaması Sonrası Sahte Kalın Tekilleştirme, +//! Efektif Font Boyutu & Başlık Tespiti, Oransal Kelime Boşluğu, Akıllı Paragraf +//! Birleştirme, 3 Seviyeli Kesir Kümeleme ve Satır İçi / Blok Matematik Ayrımı. + +use super::content_stream::{FilledRect, PdfChar, VectorLine}; +use super::image_extractor::ExtractedImage; +use super::math_reconstructor::{is_math_symbol, is_prose_word, MathReconstructor}; +use super::matrix::PageBox; +use super::table_reconstructor::TableReconstructor; +use crate::services::office_model::{ + Align, Block, Document, ListKind, Paragraph, ParagraphStyle, Run, +}; + +pub struct PageContent { + pub page_box: PageBox, + pub chars: Vec, + pub lines: Vec, + pub filled_rects: Vec, + pub images: Vec, +} + +pub struct LayoutAnalyzer; + +impl LayoutAnalyzer { + /// Birden fazla sayfayı analiz ederek akıcı ve eksiksiz bir `Document` oluşturur. + pub fn analyze_document(pages: Vec, preserve_math: bool) -> Document { + let mut document = Document::default(); + let body_median_size = estimate_body_font_size(&pages); + + let mut prev_page_ended_section = false; + + for (page_idx, page) in pages.into_iter().enumerate() { + // Yarım boş sayfaları önle: Sadece önceki sayfa kasıtlı bir bölüm sonuysa + // (alt %35'i tamamen boşsa veya çok az içerik varsa) sayfa sonu koy. + if page_idx > 0 && prev_page_ended_section { + document.blocks.push(Block::PageBreak); + } + + let page_h = page.page_box.height(); + let mut max_content_y = page + .chars + .iter() + .filter(|c| { + // Altbilgideki izole sayfa numaralarını sayfa doluluğundan hariç tut + !(c.y > page_h - 25.0 + && (c.unicode.trim().is_empty() + || c.unicode.trim().chars().all(|ch| ch.is_ascii_digit()))) + }) + .map(|c| c.y + c.height) + .fold(0.0, f64::max); + + for img in &page.images { + max_content_y = max_content_y.max(img.y_pt + img.height_pt); + } + + let char_count = page.chars.len(); + prev_page_ended_section = (char_count < 40 && page.images.is_empty()) + || (page_h > 200.0 && max_content_y < page_h * 0.65); + + let page_blocks = Self::analyze_page(page, body_median_size, preserve_math); + document.blocks.extend(page_blocks); + } + + document + } + + /// Tek bir sayfanın düzenini çözümler: Tablolar, Görseller, 2-Sütun Düzeni, Paragraflar ve Matematik. + pub fn analyze_page( + page: PageContent, + body_font_size: f64, + preserve_math: bool, + ) -> Vec { + let mut blocks = Vec::new(); + + // 1) Tabloları çıkar ve tüketilen karakterleri kaydet + let mut consumed_chars = Vec::new(); + let tables = TableReconstructor::extract_tables( + &page.lines, + &page.filled_rects, + &page.chars, + &page.images, + &mut consumed_chars, + ); + + consumed_chars.sort_unstable(); + consumed_chars.dedup(); + + // Tüketilen karakterleri sayfadan kaldır + let mut unconsumed_chars: Vec = page + .chars + .into_iter() + .enumerate() + .filter(|(idx, _)| !consumed_chars.contains(idx)) + .map(|(_, c)| c) + .collect(); + + // 2) Üstbilgi ve Altbilgi filtreleme (uç kenarlardaki izole sayfa numaraları) + let page_h = page.page_box.height(); + unconsumed_chars.retain(|c| { + if c.y < 25.0 || c.y > page_h - 25.0 { + let trimmed = c.unicode.trim(); + if trimmed.chars().all(|ch| ch.is_ascii_digit()) || trimmed.is_empty() { + return false; + } + } + true + }); + + // 3) Görselleri Blok olarak ekle + for img in &page.images { + blocks.push(Block::Image(img.to_office_image())); + } + + // 4) Tabloları ekle + for table in tables { + blocks.push(Block::Table(table)); + } + + // 5) Çok Sütunlu (2-Sütun) Akademik Düzen Tespiti (Vertical Gutter) + let page_w = page.page_box.width(); + let gutter = find_vertical_gutter(&unconsumed_chars, page_w); + + let lines = if let Some((gutter_left, _gutter_right)) = gutter { + let mut col1 = Vec::new(); + let mut col2 = Vec::new(); + for c in unconsumed_chars { + if c.x < gutter_left { + col1.push(c); + } else { + col2.push(c); + } + } + let mut all_lines = cluster_chars_into_lines(col1); + all_lines.extend(cluster_chars_into_lines(col2)); + all_lines + } else { + cluster_chars_into_lines(unconsumed_chars) + }; + + // 6) Satırları Paragraflara Grupla, Başlıkları ve Matematik Bloklarını Çözümle + let paragraph_blocks = build_paragraphs(lines, &page.lines, body_font_size, preserve_math); + blocks.extend(paragraph_blocks); + + blocks + } +} + +/// Tüm belgedeki gövde metninin dinamik Medyan (Ortanca) font boyutunu hesaplar. +fn estimate_body_font_size(pages: &[PageContent]) -> f64 { + let mut sizes = Vec::new(); + for p in pages { + for c in &p.chars { + if c.unicode.chars().any(|ch| ch.is_alphabetic()) { + sizes.push(c.font_size); + } + } + } + if sizes.is_empty() { + return 11.0; + } + sizes.sort_by(|a, b| a.total_cmp(b)); + sizes[sizes.len() / 2] +} + +/// Sayfa ortasındaki düşey beyaz boşluk oluğunu (vertical whitespace gutter) arar. +/// Tek sütunlu kısa satırlı belgeleri yanlışlıkla 2 sütuna bölmemek için her iki tarafta da yeterli metin arar. +fn find_vertical_gutter(chars: &[PdfChar], page_width: f64) -> Option<(f64, f64)> { + if chars.len() < 60 { + return None; + } + let mid_start = page_width * 0.43; + let mid_end = page_width * 0.57; + + let mut left_count = 0usize; + let mut mid_count = 0usize; + let mut right_count = 0usize; + + for c in chars { + if c.x < mid_start { + left_count += 1; + } else if c.x <= mid_end { + mid_count += 1; + } else { + right_count += 1; + } + } + + let min_col = (chars.len() / 6).max(20); + if left_count >= min_col && right_count >= min_col && mid_count < (chars.len() / 40).max(2) { + return Some((mid_start, mid_end)); + } + + None +} + +/// 2 Aşamalı Satır Kümeleme + X Sıralaması Sonrası Sahte Kalın Tekilleştirme: +/// a) Karakterleri yalnızca Y koordinatına göre (total order) sırala. +/// b) Farkı <= 0.45 * max(line_sz, ch_sz) olanları aynı TextLine içine topla (son satırlardan geriye tarayarak). +/// c) Her satırın içini SADECE X KOORDİNATINA GÖRE soldan sağa sırala. +/// d) X sıralamasından sonra yan yana düşen sahte kalın (fake bold) gölge glifleri tekilleştir ve bold işaretle. +fn cluster_chars_into_lines(mut chars: Vec) -> Vec> { + if chars.is_empty() { + return Vec::new(); + } + + // Aşama a: Yalnızca Y koordinatına göre (üstten alta) katı sıralama + chars.sort_by(|a, b| a.y.total_cmp(&b.y)); + + // Aşama b: Toleranslı tarama ile satır kümelerini (TextLine) oluştur + let mut lines: Vec> = Vec::new(); + + for ch in chars { + let mut matched_idx = None; + for idx in (0..lines.len()).rev() { + let line = &lines[idx]; + let line_y = line.iter().map(|c| c.y).sum::() / line.len() as f64; + let line_base_y = line.iter().map(|c| c.y + c.height).sum::() / line.len() as f64; + let line_sz = line.iter().map(|c| c.font_size).sum::() / line.len() as f64; + let tol = (0.45 * line_sz.max(ch.font_size)).max(3.0); + if (ch.y - line_y).abs() <= tol || ((ch.y + ch.height) - line_base_y).abs() <= tol { + matched_idx = Some(idx); + break; + } + if ch.y - line_y > tol * 3.0 { + break; + } + } + if let Some(idx) = matched_idx { + lines[idx].push(ch); + } else { + lines.push(vec![ch]); + } + } + + // Aşama c ve d: Her satırın içini SADECE X koordinatına göre sırala ve gölge glifleri tekilleştir + for line in &mut lines { + line.sort_by(|a, b| a.x.total_cmp(&b.x)); + + let mut deduped: Vec = Vec::with_capacity(line.len()); + for ch in line.drain(..) { + if !ch.unicode.trim().is_empty() { + if let Some(prev) = deduped.last_mut() { + let max_fs = prev.font_size.max(ch.font_size); + if prev.unicode == ch.unicode + && (ch.x - prev.x).abs() <= (max_fs * 0.15).max(0.6) + && (ch.y - prev.y).abs() <= (max_fs * 0.15).max(0.6) + { + prev.is_bold = true; + continue; + } + } + } + deduped.push(ch); + } + *line = deduped; + } + + // Boş satır kalmışsa temizle ve satırları ortalama Y'ye göre sırala + lines.retain(|l| !l.is_empty()); + lines.sort_by(|a, b| { + let ya = a.iter().map(|c| c.y).sum::() / a.len() as f64; + let yb = b.iter().map(|c| c.y).sum::() / b.len() as f64; + ya.total_cmp(&yb) + }); + + lines +} + +/// Başlık deseni kontrolü (Bölüm, Konu, 1., 1.1, I., vb.) +fn starts_with_heading_pattern(text: &str) -> bool { + let t = text.trim(); + let upper = t.to_uppercase(); + + if upper.starts_with("BÖLÜM") + || upper.starts_with("BOLUM") + || upper.starts_with("CHAPTER") + || upper.starts_with("SECTION") + || upper.starts_with("KONU") + || upper.starts_with("TANIM") + || upper.starts_with("ÖRNEK") + || upper.starts_with("ORNEK") + || upper.starts_with("GİRİŞ") + || upper.starts_with("GIRIS") + || upper.starts_with("SONUÇ") + || upper.starts_with("SONUC") + || upper.starts_with("ÖZET") + || upper.starts_with("OZET") + || upper.starts_with("KAYNAKLAR") + || upper.starts_with("KAYNAKÇA") + || upper.starts_with("TEOREM") + || upper.starts_with("İSPAT") + || upper.starts_with("ISPAT") + || upper.starts_with("NOT") + { + return true; + } + + let mut parts = t.splitn(2, ' '); + if let Some(prefix) = parts.next() { + let p = prefix.trim_end_matches('.'); + if !p.is_empty() { + let is_num_seq = p + .split('.') + .all(|seg| !seg.is_empty() && seg.chars().all(|ch| ch.is_ascii_digit())); + if is_num_seq && (prefix.ends_with('.') || prefix.contains('.')) { + return true; + } + if prefix.ends_with('.') && p.chars().all(|ch| matches!(ch, 'I' | 'V' | 'X' | 'i' | 'v' | 'x')) { + return true; + } + } + } + + false +} + +fn starts_with_list_marker(text: &str) -> bool { + let t = text.trim_start(); + if t.starts_with('•') || t.starts_with("- ") || t.starts_with("* ") { + return true; + } + let bytes = t.as_bytes(); + let digit_count = bytes.iter().take_while(|b| b.is_ascii_digit()).count(); + if (1..=3).contains(&digit_count) { + let rest = &t[digit_count..]; + if rest.starts_with(". ") || rest.starts_with(") ") { + return true; + } + } + let mut chars = t.chars(); + if let (Some(first), Some(')'), Some(' ')) = (chars.next(), chars.next(), chars.next()) { + if first.is_alphabetic() { + return true; + } + } + false +} + +/// Dinamik Başlık Tespiti (Heading 1, 2, 3) +fn detect_heading(line: &[PdfChar], body_median_size: f64, is_isolated: bool) -> Option { + if line.is_empty() { + return None; + } + let (raw_text, _) = assemble_line_text_and_runs(line); + let trimmed = raw_text.trim(); + if trimmed.is_empty() || trimmed.len() > 100 { + return None; + } + if trimmed.starts_with('•') || trimmed.starts_with("- ") || trimmed.starts_with("* ") { + return None; + } + + let alpha_chars: Vec<&PdfChar> = line + .iter() + .filter(|c| c.unicode.chars().any(|ch| ch.is_alphabetic())) + .collect(); + if alpha_chars.is_empty() { + return None; + } + let line_fs = alpha_chars.iter().map(|c| c.font_size).sum::() / alpha_chars.len() as f64; + let bold_alpha = alpha_chars.iter().filter(|c| c.is_bold).count(); + let line_is_bold = bold_alpha > 0 && bold_alpha * 2 >= alpha_chars.len(); + let has_prefix = starts_with_heading_pattern(trimmed); + + if line_fs >= body_median_size * 1.45 { + Some(1) + } else if line_fs >= body_median_size * 1.20 { + Some(2) + } else if (line_fs >= body_median_size * 1.08 && (line_is_bold || has_prefix || is_isolated)) + || (line_is_bold && has_prefix) + { + Some(3) + } else { + None + } +} + +/// Bir satırdaki karakterleri oransal boşluk ve biçim özellikleriyle (Run) birleştirir. +fn assemble_line_text_and_runs(line: &[PdfChar]) -> (String, Vec) { + if line.is_empty() { + return (String::new(), Vec::new()); + } + + let avg_char_w = line.iter().map(|c| c.width).sum::() / line.len() as f64; + let mut full_text = String::new(); + let mut runs: Vec = Vec::new(); + + let mut current_run_text = String::new(); + let mut current_bold = line[0].is_bold; + let mut current_italic = line[0].is_italic; + let mut current_fs = line[0].font_size; + let mut current_color = line[0].color; + let mut prev_char: Option<&PdfChar> = None; + + for c in line { + let mut space_to_insert = None; + + if let Some(prev) = prev_char { + let prev_x1 = prev.x + prev.width; + let gap = c.x - prev_x1; + let fs = prev.font_size.max(c.font_size); + + let space_threshold = (fs * 0.16).min(avg_char_w * 0.32).max(1.2); + let tab_threshold = fs * 2.2; + + let already_has_space = full_text.ends_with(' ') || full_text.ends_with('\t') || c.unicode.starts_with(' '); + + if !already_has_space { + if gap > tab_threshold { + space_to_insert = Some("\t"); + } else if gap > space_threshold { + space_to_insert = Some(" "); + } + } + } + + if let Some(sp) = space_to_insert { + full_text.push_str(sp); + current_run_text.push_str(sp); + } + + let style_changed = c.is_bold != current_bold + || c.is_italic != current_italic + || (c.font_size - current_fs).abs() >= 1.5 + || c.color != current_color; + + if style_changed && !current_run_text.is_empty() { + runs.push(Run { + text: current_run_text.clone(), + bold: current_bold, + italic: current_italic, + size_pt: Some(current_fs as f32), + color: if current_color != [0, 0, 0] { Some(current_color) } else { None }, + ..Run::plain("") + }); + current_run_text.clear(); + current_bold = c.is_bold; + current_italic = c.is_italic; + current_fs = c.font_size; + current_color = c.color; + } + + if c.unicode == " " { + if !full_text.ends_with(' ') && !full_text.ends_with('\t') { + full_text.push(' '); + current_run_text.push(' '); + } + } else { + full_text.push_str(&c.unicode); + current_run_text.push_str(&c.unicode); + } + + prev_char = Some(c); + } + + if !current_run_text.is_empty() { + runs.push(Run { + text: current_run_text, + bold: current_bold, + italic: current_italic, + size_pt: Some(current_fs as f32), + color: if current_color != [0, 0, 0] { Some(current_color) } else { None }, + ..Run::plain("") + }); + } + + (full_text, runs) +} + +#[derive(Clone)] +struct WordToken { + chars: Vec, + preceding_space: String, + is_math_token: bool, + overlaps_fraction: bool, + is_punctuation: bool, +} + +impl WordToken { + fn text(&self) -> String { + self.chars.iter().map(|c| c.unicode.as_str()).collect() + } +} + +fn dominant_line_font_size(line: &[PdfChar]) -> f64 { + if line.is_empty() { + return 11.0; + } + let mut fs_list: Vec = line.iter().map(|c| c.font_size).collect(); + fs_list.sort_by(|a, b| a.total_cmp(b)); + fs_list[fs_list.len() / 2] +} + +fn active_fraction_indices(line: &[PdfChar], vector_lines: &[VectorLine], line_fs: f64) -> Vec { + let mut active = Vec::new(); + let min_y = line.iter().map(|c| c.y).fold(f64::MAX, f64::min); + let max_y = line.iter().map(|c| c.y + c.height).fold(f64::MIN, f64::max); + + for (idx, vl) in vector_lines.iter().enumerate() { + if vl.is_horizontal && vl.thickness <= 3.0 && (vl.x2 - vl.x1) >= 6.0 { + if vl.y1 < min_y - line_fs || vl.y1 > max_y + line_fs { + continue; + } + let has_above = line.iter().any(|c| { + let mx = c.x + c.width * 0.5; + mx >= vl.x1 - 8.0 + && mx <= vl.x2 + 8.0 + && c.y + c.height <= vl.y1 + 5.0 + && c.y >= vl.y1 - line_fs * 1.8 + }); + let has_below = line.iter().any(|c| { + let mx = c.x + c.width * 0.5; + mx >= vl.x1 - 8.0 + && mx <= vl.x2 + 8.0 + && c.y >= vl.y1 - 5.0 + && c.y + c.height <= vl.y1 + line_fs * 1.8 + }); + if has_above && has_below { + active.push(idx); + } + } + } + active +} + +fn char_fraction_bar(c: &PdfChar, vector_lines: &[VectorLine], active_bars: &[usize], line_fs: f64) -> Option { + let mx = c.x + c.width * 0.5; + for &idx in active_bars { + let vl = &vector_lines[idx]; + if mx >= vl.x1 - 5.0 + && mx <= vl.x2 + 5.0 + && (c.y + c.height * 0.5 - vl.y1).abs() <= line_fs * 1.8 + { + return Some(idx); + } + } + None +} + +fn looks_like_math_func(trimmed: &str) -> bool { + let Some(open_idx) = trimmed.find('(') else { + return false; + }; + let Some(close_idx) = trimmed.rfind(')') else { + return false; + }; + if close_idx <= open_idx { + return false; + } + let fn_name = trimmed[..open_idx].trim(); + let args = trimmed[open_idx + 1..close_idx].trim(); + if fn_name.is_empty() || args.is_empty() { + return false; + } + let valid_fn = matches!( + fn_name.to_lowercase().as_str(), + "sin" | "cos" | "tan" | "cot" | "sec" | "csc" | "log" | "ln" | "exp" | "lim" | "det" | "min" | "max" + ) || (fn_name.chars().count() <= 2 && fn_name.chars().all(|ch| ch.is_ascii_alphabetic())); + let valid_args = !args.split([',', '+', '-', ' ']) + .any(is_prose_word); + valid_fn && valid_args +} + +fn token_has_prose(trimmed: &str) -> bool { + if looks_like_math_func(trimmed) { + return false; + } + trimmed + .split(|c: char| !c.is_alphabetic()) + .any(is_prose_word) +} + +fn has_inline_math_candidate(line: &[PdfChar], vector_lines: &[VectorLine]) -> bool { + let line_fs = dominant_line_font_size(line); + if !active_fraction_indices(line, vector_lines, line_fs).is_empty() { + return true; + } + line.iter().any(|c| { + let t = c.unicode.trim(); + c.is_math + || (is_math_symbol(&c.unicode) && t != "-") + || t == "^" + || t == "_" + || (!t.is_empty() && c.font_size <= line_fs * 0.85) + || (t.chars().count() == 1 + && c.is_italic + && t.chars().all(|ch| ch.is_ascii_alphabetic())) + }) +} + +/// Kelime bazlı Satır İçi (Inline) Matematik ayrımı: +/// Türkçe kelimeler ve aralarındaki boşluklar %100 korunur; sadece formül ifadeleri +/// ve bitişik operatör/kesir/simge grupları `` içine sarılır. +fn extract_inline_math_runs(line: &[PdfChar], vector_lines: &[VectorLine]) -> Vec { + if line.is_empty() { + return Vec::new(); + } + if !has_inline_math_candidate(line, vector_lines) { + return assemble_line_text_and_runs(line).1; + } + + let line_fs = dominant_line_font_size(line); + let active_bars = active_fraction_indices(line, vector_lines, line_fs); + + let mut sorted = line.to_vec(); + sorted.sort_by(|a, b| a.x.total_cmp(&b.x).then_with(|| a.y.total_cmp(&b.y))); + + let avg_char_w = sorted.iter().map(|c| c.width).sum::() / sorted.len().max(1) as f64; + + // 1) Gerçek koordinat boşluklarına göre WordToken'lara böl (alt/üst simgeler ve kesirler aynı token'da kalır) + let mut tokens: Vec = Vec::new(); + let mut cur_chars: Vec = Vec::new(); + let mut cur_frac: Option = None; + let mut cur_max_x1 = 0.0f64; + let mut cur_last_fs = line_fs; + let mut pending_space = String::new(); + let mut token_space = String::new(); + + for c in sorted { + if c.unicode == " " { + if pending_space.is_empty() { + pending_space = " ".to_string(); + } + continue; + } + + let frac = char_fraction_bar(&c, vector_lines, &active_bars, line_fs); + let same_fraction = frac.is_some() && frac == cur_frac; + + if !cur_chars.is_empty() { + let gap = c.x - cur_max_x1; + let fs = cur_last_fs.max(c.font_size); + let space_threshold = (fs * 0.16).min(avg_char_w * 0.32).max(1.2); + let tab_threshold = fs * 2.2; + + let is_script_char = c.font_size <= line_fs * 0.85; + let split_by_gap = if same_fraction { + false + } else if is_script_char { + gap > space_threshold * 1.5 + } else { + gap > space_threshold + }; + + if !pending_space.is_empty() || split_by_gap { + tokens.push(WordToken { + chars: std::mem::take(&mut cur_chars), + preceding_space: std::mem::take(&mut token_space), + is_math_token: false, + overlaps_fraction: cur_frac.is_some(), + is_punctuation: false, + }); + token_space = if gap > tab_threshold { + "\t".to_string() + } else if !pending_space.is_empty() { + pending_space.clone() + } else { + " ".to_string() + }; + pending_space.clear(); + cur_frac = None; + cur_max_x1 = 0.0; + } + } else if !pending_space.is_empty() { + token_space = std::mem::take(&mut pending_space); + } + + cur_max_x1 = cur_max_x1.max(c.x + c.width); + cur_last_fs = c.font_size; + if cur_frac.is_none() { + cur_frac = frac; + } + cur_chars.push(c); + } + + if !cur_chars.is_empty() { + tokens.push(WordToken { + chars: cur_chars, + preceding_space: token_space, + is_math_token: false, + overlaps_fraction: cur_frac.is_some(), + is_punctuation: false, + }); + } + + // Cümle sonu noktalama işaretini (",", ";", ":", ".") matematik tokenından ayır (ör. "mc^2." -> "mc^2" + ".") + let mut split_tokens = Vec::with_capacity(tokens.len()); + for mut tok in tokens { + let should_detach_punct = if tok.chars.len() >= 2 && !tok.overlaps_fraction { + if let Some(last) = tok.chars.last() { + let u = last.unicode.trim(); + matches!(u, "," | ";" | ":") + || (u == "." && !tok.chars[..tok.chars.len() - 1].iter().all(|c| c.unicode.trim().chars().all(|ch| ch.is_ascii_digit()))) + } else { + false + } + } else { + false + }; + + if should_detach_punct { + if let Some(punct) = tok.chars.pop() { + split_tokens.push(tok); + split_tokens.push(WordToken { + chars: vec![punct], + preceding_space: String::new(), + is_math_token: false, + overlaps_fraction: false, + is_punctuation: true, + }); + continue; + } + } + split_tokens.push(tok); + } + let mut tokens = split_tokens; + + // 2) Çekirdek matematik tokenlarını belirle + let mut is_operator = vec![false; tokens.len()]; + let mut has_prose = vec![false; tokens.len()]; + + for (i, tok) in tokens.iter_mut().enumerate() { + let txt = tok.text(); + let trimmed = txt.trim(); + let prose = token_has_prose(trimmed); + has_prose[i] = prose; + + if matches!(trimmed, "," | ";" | ":" | ".") { + tok.is_punctuation = true; + continue; + } + + if matches!( + trimmed, + "=" | "+" | "−" | "×" | "÷" | "≠" | "≤" | "≥" | "<" | ">" | "≈" | "≡" | "→" | "±" | "∓" + ) { + is_operator[i] = true; + tok.is_math_token = true; + continue; + } + + if prose { + continue; + } + + let baseline_y = tok.chars[0].y + tok.chars[0].height; + let has_math_char = tok.chars.iter().any(|c| { + let u = c.unicode.trim(); + c.is_math || (is_math_symbol(&c.unicode) && u != "-") || u == "^" || u == "_" + }); + let has_script = tok.chars.len() >= 2 + && tok.chars.iter().any(|c| { + !c.unicode.trim().is_empty() + && (c.font_size <= line_fs * 0.85 + || (c.y + c.height - baseline_y).abs() >= line_fs * 0.15) + }); + let is_single_italic_var = trimmed.chars().count() == 1 + && tok.chars.len() == 1 + && tok.chars[0].is_italic + && trimmed.chars().all(|ch| ch.is_ascii_alphabetic()); + + if tok.overlaps_fraction + || has_math_char + || has_script + || looks_like_math_func(trimmed) + || is_single_italic_var + { + tok.is_math_token = true; + } + } + + // 3) Komşu yayılımı: matematik operatörüne bitişik tek harfli değişken ve sayıları gruba kat + for _pass in 0..2 { + for i in 0..tokens.len() { + let tok_txt = tokens[i].text(); + let tok_trimmed = tok_txt.trim(); + let carries_operator = is_operator[i] + || (tokens[i].is_math_token + && tok_trimmed + .chars() + .any(|ch| matches!(ch, '=' | '+' | '−' | '×' | '÷' | '<' | '>' | '≤' | '≥' | '≠'))); + + if carries_operator { + if i > 0 && !has_prose[i - 1] && !tokens[i - 1].is_punctuation { + let prev_txt = tokens[i - 1].text(); + let pt = prev_txt.trim(); + if pt.chars().count() <= 4 && !pt.is_empty() { + tokens[i - 1].is_math_token = true; + } + } + if i + 1 < tokens.len() && !has_prose[i + 1] && !tokens[i + 1].is_punctuation { + let next_txt = tokens[i + 1].text(); + let nt = next_txt.trim(); + if nt.chars().count() <= 4 && !nt.is_empty() { + tokens[i + 1].is_math_token = true; + } + } + } + + // Bağımsız ASCII '-' yalnızca komşularından biri matematik olup diğeri nesir değilse matematik sayılır + if tok_trimmed == "-" && !tokens[i].is_math_token { + let left_math = i > 0 && tokens[i - 1].is_math_token; + let right_math = i + 1 < tokens.len() && tokens[i + 1].is_math_token; + let left_prose = i > 0 && has_prose[i - 1]; + let right_prose = i + 1 < tokens.len() && has_prose[i + 1]; + if (left_math && !right_prose) || (right_math && !left_prose) { + tokens[i].is_math_token = true; + is_operator[i] = true; + } + } + } + } + + // Eğer hiç matematik token'ı çıkmadıysa düz satır run'larına geri dön + if !tokens.iter().any(|t| t.is_math_token) { + return assemble_line_text_and_runs(line).1; + } + + // 4) Bitişik nesir ve matematik tokenlarını sırayla Run'lara dönüştür, boşlukları %100 koru + let mut runs: Vec = Vec::new(); + let mut idx = 0; + + while idx < tokens.len() { + if !tokens[idx].is_math_token { + // Normal Türkçe nesir grubu + let mut end = idx + 1; + while end < tokens.len() && !tokens[end].is_math_token { + end += 1; + } + let mut group_chars: Vec = Vec::new(); + let leading_sp = tokens[idx].preceding_space.clone(); + if !leading_sp.is_empty() { + if let Some(prev_run) = runs.last_mut() { + if prev_run.omml.is_none() { + if !prev_run.text.ends_with(' ') { + prev_run.text.push_str(&leading_sp); + } + } else { + // Önceki run inline olduğu için boşluğu sonraki metin run'ının başına koy + let anchor = &tokens[idx].chars[0]; + group_chars.push(PdfChar { + unicode: leading_sp.clone(), + x: anchor.x - 2.0, + y: anchor.y, + width: 1.0, + height: anchor.height, + font_size: anchor.font_size, + font_name: anchor.font_name.clone(), + is_math: false, + is_bold: anchor.is_bold, + is_italic: anchor.is_italic, + color: anchor.color, + }); + } + } + } + + for (offset, tok) in tokens[idx..end].iter().enumerate() { + if offset > 0 && !tok.preceding_space.is_empty() { + let prev_end_x = group_chars.last().map(|c| c.x + c.width).unwrap_or(0.0); + let anchor = &tok.chars[0]; + let gap_end = (anchor.x - 0.5).max(prev_end_x + 0.5); + group_chars.push(PdfChar { + unicode: tok.preceding_space.clone(), + x: gap_end, + y: anchor.y, + width: (anchor.x - gap_end).max(0.5), + height: anchor.height, + font_size: anchor.font_size, + font_name: anchor.font_name.clone(), + is_math: false, + is_bold: anchor.is_bold, + is_italic: anchor.is_italic, + color: anchor.color, + }); + } + group_chars.extend(tok.chars.clone()); + } + + // Eğer assemble_line_text_and_runs içinde karakterlerin arası genişse çift boşluk çıkmaması için doğrudan run üret + runs.extend(assemble_word_group_runs(&group_chars)); + idx = end; + } else { + // Bitişik satır içi matematik grubu -> tek bir + let mut end = idx + 1; + while end < tokens.len() && tokens[end].is_math_token { + end += 1; + } + + let leading_sp = &tokens[idx].preceding_space; + if !leading_sp.is_empty() { + if let Some(prev_run) = runs.last_mut() { + if prev_run.omml.is_none() { + if !prev_run.text.ends_with(' ') && !prev_run.text.ends_with('\t') { + prev_run.text.push_str(leading_sp); + } + } else { + runs.push(Run::plain(leading_sp)); + } + } + } + + let mut math_chars: Vec = Vec::new(); + for tok in &tokens[idx..end] { + math_chars.extend(tok.chars.clone()); + } + + let min_x = math_chars.iter().map(|c| c.x).fold(f64::MAX, f64::min); + let max_x = math_chars.iter().map(|c| c.x + c.width).fold(f64::MIN, f64::max); + let relevant_vlines: Vec = active_bars + .iter() + .map(|&bar_idx| vector_lines[bar_idx].clone()) + .filter(|vl| vl.x2 >= min_x - 8.0 && vl.x1 <= max_x + 8.0) + .collect(); + + if let Some(omml) = MathReconstructor::reconstruct_math(&math_chars, &relevant_vlines) { + runs.push(Run::math(omml)); + } else { + runs.extend(assemble_word_group_runs(&math_chars)); + } + + idx = end; + } + } + + runs +} + +/// Önceden boşluk karakterleri yerleştirilmiş bir nesir kelime grubundan stil uyumlu Run'lar üretir. +fn assemble_word_group_runs(chars: &[PdfChar]) -> Vec { + if chars.is_empty() { + return Vec::new(); + } + let mut runs: Vec = Vec::new(); + let mut text = String::new(); + let mut bold = chars[0].is_bold; + let mut italic = chars[0].is_italic; + let mut fs = chars[0].font_size; + let mut color = chars[0].color; + + for c in chars { + if !c.unicode.trim().is_empty() { + let changed = c.is_bold != bold + || c.is_italic != italic + || (c.font_size - fs).abs() >= 1.5 + || c.color != color; + if changed && !text.is_empty() { + runs.push(Run { + text: std::mem::take(&mut text), + bold, + italic, + size_pt: Some(fs as f32), + color: if color != [0, 0, 0] { Some(color) } else { None }, + ..Run::plain("") + }); + bold = c.is_bold; + italic = c.is_italic; + fs = c.font_size; + color = c.color; + } + } + text.push_str(&c.unicode); + } + + if !text.is_empty() { + runs.push(Run { + text, + bold, + italic, + size_pt: Some(fs as f32), + color: if color != [0, 0, 0] { Some(color) } else { None }, + ..Run::plain("") + }); + } + runs +} + +/// Satırları Paragraflara Grupla: 3-Seviyeli Kesir Kümeleme, Başlık, Blok Denklem ve Akıllı Paragraf Birleştirme +fn build_paragraphs( + raw_lines: Vec>, + vector_lines: &[VectorLine], + body_font_size: f64, + preserve_math: bool, +) -> Vec { + if raw_lines.is_empty() { + return Vec::new(); + } + + // 3-seviyeli kesir satırı birleştirme: + // Yatay kesir çizgisi (vl) etrafında dikey merkezi [vl.y1 - max_fs * 1.6, vl.y1 + max_fs * 1.6] + // aralığına düşen ilgili satırları (pay, orta denklem satırı ve payda) tek satır kümesinde topla. + let mut lines: Vec> = Vec::with_capacity(raw_lines.len()); + let mut consumed = vec![false; raw_lines.len()]; + + for i in 0..raw_lines.len() { + if consumed[i] { + continue; + } + + if preserve_math { + let line_i = &raw_lines[i]; + let max_fs = line_i.iter().map(|c| c.font_size).fold(10.0, f64::max); + + // Bu satırın hemen altında bir yatay kesir çizgisi (vinculum) var mı? + let matching_vl = vector_lines.iter().find(|vl| { + if !vl.is_horizontal || vl.thickness > 3.0 || (vl.x2 - vl.x1) < 6.0 { + return false; + } + let line_is_above = line_i.iter().any(|c| { + let mx = c.x + c.width * 0.5; + mx >= vl.x1 - 8.0 + && mx <= vl.x2 + 8.0 + && c.y + c.height <= vl.y1 + 5.0 + && vl.y1 - (c.y + c.height * 0.5) <= max_fs * 1.6 + }); + if !line_is_above { + return false; + } + // Aynı kesir çizgisinin altında da (payda) satır bulunmalı + raw_lines.iter().enumerate().skip(i + 1).any(|(j, lj)| { + !consumed[j] + && lj.iter().any(|c| { + let mx = c.x + c.width * 0.5; + mx >= vl.x1 - 8.0 + && mx <= vl.x2 + 8.0 + && c.y >= vl.y1 - 5.0 + && (c.y + c.height * 0.5) - vl.y1 <= max_fs * 1.6 + }) + }) + }); + + if let Some(vl) = matching_vl { + let band_min = vl.y1 - max_fs * 1.6; + let band_max = vl.y1 + max_fs * 1.6; + let mut combined = Vec::new(); + + for (j, lj) in raw_lines.iter().enumerate().skip(i) { + if consumed[j] { + continue; + } + let center_y = lj.iter().map(|c| c.y + c.height * 0.5).sum::() / lj.len().max(1) as f64; + if center_y < band_min || center_y > band_max { + continue; + } + let overlaps_vl = lj.iter().any(|c| { + let mx = c.x + c.width * 0.5; + mx >= vl.x1 - 8.0 && mx <= vl.x2 + 8.0 + }); + let is_mid_baseline = (center_y - vl.y1).abs() <= max_fs * 0.85; + if overlaps_vl || is_mid_baseline { + combined.extend(lj.clone()); + consumed[j] = true; + } + } + + if !combined.is_empty() { + lines.push(combined); + continue; + } + } + } + + consumed[i] = true; + lines.push(raw_lines[i].clone()); + } + + let mut blocks = Vec::new(); + let mut current_paragraph_lines: Vec> = Vec::new(); + + for (i, line) in lines.iter().enumerate() { + let is_isolated = { + let prev_gap = if i > 0 { + let prev_bot = lines[i - 1].iter().map(|c| c.y + c.height).fold(0.0, f64::max); + let cur_top = line.iter().map(|c| c.y).fold(f64::MAX, f64::min); + cur_top - prev_bot + } else { + 20.0 + }; + let next_gap = if i + 1 < lines.len() { + let cur_bot = line.iter().map(|c| c.y + c.height).fold(0.0, f64::max); + let next_top = lines[i + 1].iter().map(|c| c.y).fold(f64::MAX, f64::min); + next_top - cur_bot + } else { + 20.0 + }; + prev_gap > 12.0 && next_gap > 12.0 + }; + + // 1) Blok denklem kontrolü + if preserve_math && MathReconstructor::is_display_math(line, vector_lines) { + if !current_paragraph_lines.is_empty() { + blocks.push(assemble_merged_paragraph(¤t_paragraph_lines, preserve_math, vector_lines)); + current_paragraph_lines.clear(); + } + + if let Some(omml_xml) = MathReconstructor::reconstruct_math(line, vector_lines) { + blocks.push(Block::Paragraph(Paragraph { + style: ParagraphStyle { + align: Align::Center, + is_display_math: true, + space_before_pt: 4.0, + space_after_pt: 4.0, + ..Default::default() + }, + runs: vec![Run::math(omml_xml)], + })); + } + continue; + } + + // 2) Başlık kontrolü + let heading_level = detect_heading(line, body_font_size, is_isolated); + + if let Some(level) = heading_level { + if !current_paragraph_lines.is_empty() { + blocks.push(assemble_merged_paragraph(¤t_paragraph_lines, preserve_math, vector_lines)); + current_paragraph_lines.clear(); + } + + let (heading_text, mut heading_runs) = assemble_line_text_and_runs(line); + let heading_sz = match level { + 1 => 18.0, + 2 => 14.0, + _ => 12.0, + }; + for r in &mut heading_runs { + r.bold = true; + r.size_pt = Some(heading_sz); + } + blocks.push(Block::Paragraph(Paragraph { + style: ParagraphStyle { + heading: Some(level), + ..Default::default() + }, + runs: if heading_runs.is_empty() { + vec![Run { + text: heading_text, + bold: true, + size_pt: Some(heading_sz), + ..Run::plain("") + }] + } else { + heading_runs + }, + })); + continue; + } + + // 3) Liste işareti kontrolü (•, -, *, 1., a)) + let (line_text, _) = assemble_line_text_and_runs(line); + let is_list_item = starts_with_list_marker(&line_text); + + if is_list_item { + if !current_paragraph_lines.is_empty() { + blocks.push(assemble_merged_paragraph(¤t_paragraph_lines, preserve_math, vector_lines)); + current_paragraph_lines.clear(); + } + current_paragraph_lines.push(line.clone()); + continue; + } + + // 4) Normal gövde satırı: önceki satırla birleşme kontrolü + if current_paragraph_lines.is_empty() { + current_paragraph_lines.push(line.clone()); + } else { + let prev_line = current_paragraph_lines.last().unwrap(); + let prev_bot = prev_line.iter().map(|c| c.y + c.height).fold(0.0, f64::max); + let cur_top = line.iter().map(|c| c.y).fold(f64::MAX, f64::min); + let line_gap = cur_top - prev_bot; + let line_height = prev_line.iter().map(|c| c.height).sum::() / prev_line.len().max(1) as f64; + + let prev_fs = prev_line.iter().map(|c| c.font_size).sum::() / prev_line.len().max(1) as f64; + let cur_fs = line.iter().map(|c| c.font_size).sum::() / line.len().max(1) as f64; + let fs_diff = (prev_fs - cur_fs).abs(); + + // Kural: line_gap <= 0.65 * line_height ve font farkı < 1.0 pt ise AYNI PARAGRAFTIR + if line_gap <= (line_height * 0.65).max(4.0) && fs_diff < 1.0 { + current_paragraph_lines.push(line.clone()); + } else { + blocks.push(assemble_merged_paragraph(¤t_paragraph_lines, preserve_math, vector_lines)); + current_paragraph_lines = vec![line.clone()]; + } + } + } + + if !current_paragraph_lines.is_empty() { + blocks.push(assemble_merged_paragraph(¤t_paragraph_lines, preserve_math, vector_lines)); + } + + blocks +} + +/// Birden fazla satırı akıllı Türkçe tireleme ve satır içi matematik korumasıyla tek bir paragrafa birleştirir. +fn assemble_merged_paragraph( + lines: &[Vec], + preserve_math: bool, + vector_lines: &[VectorLine], +) -> Block { + let mut paragraph_runs: Vec = Vec::new(); + + for (l_idx, line) in lines.iter().enumerate() { + let (line_text, mut line_runs) = assemble_line_text_and_runs(line); + + let is_last_line = l_idx == lines.len() - 1; + let mut ends_with_hyphen = false; + + if !is_last_line && line_text.trim_end().ends_with('-') { + ends_with_hyphen = true; + if let Some(last_r) = line_runs.last_mut() { + if let Some(pos) = last_r.text.rfind('-') { + if last_r.text[pos + 1..].trim().is_empty() { + last_r.text.truncate(pos); + } + } + } + } + + if preserve_math && has_inline_math_candidate(line, vector_lines) { + let mut math_line = line.clone(); + if ends_with_hyphen { + if let Some(last_c) = math_line.last() { + if last_c.unicode.trim() == "-" { + math_line.pop(); + } + } + } + line_runs = extract_inline_math_runs(&math_line, vector_lines); + } + + if !is_last_line && !ends_with_hyphen { + if let Some(last_r) = line_runs.last_mut() { + if last_r.omml.is_some() { + line_runs.push(Run::plain(" ")); + } else if !last_r.text.ends_with(' ') && !last_r.text.ends_with('\t') { + last_r.text.push(' '); + } + } + } + + paragraph_runs.extend(line_runs); + } + + // Aynı biçime sahip bitişik metin run'larını tekilleştirerek temiz DOCX XML üret + let mut compacted_runs: Vec = Vec::with_capacity(paragraph_runs.len()); + for run in paragraph_runs { + if run.omml.is_none() && run.text.is_empty() { + continue; + } + if let Some(prev) = compacted_runs.last_mut() { + let can_merge = prev.omml.is_none() + && run.omml.is_none() + && prev.bold == run.bold + && prev.italic == run.italic + && prev.underline == run.underline + && prev.strike == run.strike + && prev.color == run.color + && prev.font == run.font + && prev.vert_align == run.vert_align + && prev.link == run.link + && prev + .size_pt + .zip(run.size_pt) + .map(|(a, b)| (a - b).abs() < 0.5) + .unwrap_or(prev.size_pt == run.size_pt); + if can_merge { + prev.text.push_str(&run.text); + continue; + } + } + compacted_runs.push(run); + } + + let first_text = compacted_runs.first().map(|r| r.text.as_str()).unwrap_or(""); + let trimmed = first_text.trim_start(); + let mut style = ParagraphStyle::default(); + + if trimmed.starts_with('•') || trimmed.starts_with("- ") || trimmed.starts_with("* ") { + style.list = Some(ListKind::Bullet); + if let Some(first_r) = compacted_runs.first_mut() { + first_r.text = first_r + .text + .trim_start() + .trim_start_matches(['•', '-', '*', ' ']) + .to_string(); + } + } + + Block::Paragraph(Paragraph { + style, + runs: compacted_runs, + }) +} diff --git a/src-tauri/src/services/pdf_parser/math_reconstructor.rs b/src-tauri/src/services/pdf_parser/math_reconstructor.rs new file mode 100644 index 0000000..3fab5c0 --- /dev/null +++ b/src-tauri/src/services/pdf_parser/math_reconstructor.rs @@ -0,0 +1,529 @@ +//! Geometrik Matematik Rekonstrüksiyon Motoru (2D Spatial Math to OMML ``). +//! +//! 2B uzaysal koordinatları (x, y, w, h) ve vektör çizgilerini (vinculum) analiz ederek; +//! Kesirleri (``), Kökleri (``), N-ary işleçleri (``: ∑, ∏, ∫), +//! Alt/Üst simgeleri (``, ``, ``), Ayraçları (``), +//! Matrisleri (``) ve Aksanları (``) yerli Microsoft Office OMML XML'ine dönüştürür. + +use super::content_stream::{PdfChar, VectorLine}; +use crate::services::omml::escape_xml; + +#[derive(Debug, Clone)] +pub enum MathNode { + Text(String, bool), // (metin, is_italic) + Fraction { + num: Vec, + den: Vec, + }, + Radical { + degree: Option>, + expr: Vec, + }, + Nary { + operator: String, + sub: Option>, + sup: Option>, + expr: Vec, + }, + SubSup { + base: Vec, + sub: Option>, + sup: Option>, + }, + Delimiter { + open: char, + close: char, + content: Vec, + }, + Accent { + accent_char: char, + base: Vec, + }, +} + +impl MathNode { + /// MathNode AST'sini doğrudan Word OMML XML (``) dizesine dönüştürür. + pub fn to_omml(&self) -> String { + match self { + MathNode::Text(text, is_italic) => { + let rpr = if *is_italic { + "" + } else { + "" + }; + format!("{rpr}{}", escape_xml(text)) + } + MathNode::Fraction { num, den } => { + let num_xml = nodes_to_omml(num); + let den_xml = nodes_to_omml(den); + format!("{num_xml}{den_xml}") + } + MathNode::Radical { degree, expr } => { + let expr_xml = nodes_to_omml(expr); + if let Some(deg) = degree { + let deg_xml = nodes_to_omml(deg); + format!("{deg_xml}{expr_xml}") + } else { + format!("{expr_xml}") + } + } + MathNode::Nary { operator, sub, sup, expr } => { + let pr = format!("", escape_xml(operator)); + let sub_xml = sub.as_ref().map(|s| nodes_to_omml(s)).unwrap_or_default(); + let sup_xml = sup.as_ref().map(|s| nodes_to_omml(s)).unwrap_or_default(); + let expr_xml = nodes_to_omml(expr); + format!("{pr}{sub_xml}{sup_xml}{expr_xml}") + } + MathNode::SubSup { base, sub, sup } => { + let base_xml = nodes_to_omml(base); + match (sub, sup) { + (Some(s), Some(u)) => { + let sub_xml = nodes_to_omml(s); + let sup_xml = nodes_to_omml(u); + format!("{base_xml}{sub_xml}{sup_xml}") + } + (Some(s), None) => { + let sub_xml = nodes_to_omml(s); + format!("{base_xml}{sub_xml}") + } + (None, Some(u)) => { + let sup_xml = nodes_to_omml(u); + format!("{base_xml}{sup_xml}") + } + (None, None) => base_xml, + } + } + MathNode::Delimiter { open, close, content } => { + let content_xml = nodes_to_omml(content); + format!( + "{content_xml}", + open, close + ) + } + MathNode::Accent { accent_char, base } => { + let base_xml = nodes_to_omml(base); + format!( + "{base_xml}", + accent_char + ) + } + } + } +} + +pub fn nodes_to_omml(nodes: &[MathNode]) -> String { + let mut out = String::new(); + for node in nodes { + out.push_str(&node.to_omml()); + } + out +} + +pub struct MathReconstructor; + +impl MathReconstructor { + /// Bir satırın tek başına bağımsız blok denklem (Display Math: ) olup olmadığını belirler. + /// Türkçe nesir cümlelerin ("Burada x ve y için...") blok denklem sanılmasını engeller. + pub fn is_display_math(chars: &[PdfChar], lines: &[VectorLine]) -> bool { + if chars.is_empty() { + return false; + } + + let words_text = join_chars_with_gaps(chars); + let words: Vec<&str> = words_text.split_whitespace().collect(); + let prose_word_count = words.iter().filter(|w| is_prose_word(w)).count(); + + // Cümle/paragraf içinde Türkçe/İngilizce nesir kelimeleri varsa blok denklem olamaz! + if prose_word_count >= 1 { + return false; + } + + // 1) Yatay kesir çizgisi var mı? + for line in lines { + if line.is_horizontal && line.thickness <= 3.0 && (line.x2 - line.x1) >= 6.0 { + let has_above = chars.iter().any(|c| c.y + c.height <= line.y1 + 4.0 && c.x >= line.x1 - 6.0 && c.x <= line.x2 + 6.0); + let has_below = chars.iter().any(|c| c.y >= line.y1 - 4.0 && c.x >= line.x1 - 6.0 && c.x <= line.x2 + 6.0); + if has_above && has_below { + return true; + } + } + } + + // 2) Matematik sembolleri veya fontları (yalnız kısa çizgi '-' hariç) + let mut math_count = 0; + let mut non_space_len = 0usize; + for c in chars { + if !c.unicode.trim().is_empty() { + non_space_len += 1; + if c.is_math || (is_math_symbol(&c.unicode) && c.unicode.trim() != "-") { + math_count += 1; + } + } + } + + let denom = non_space_len.max(chars.len()).max(1) as f64; + let math_ratio = math_count as f64 / denom; + if math_ratio >= 0.40 { + return true; + } + + // Tek başına belirgin bir büyük işleç veya kök var mı? + if chars.iter().any(|c| matches!(c.unicode.as_str(), "∑" | "∏" | "∫" | "∮" | "√" | "∂" | "∇" | "±" | "≤" | "≥" | "≠")) { + return true; + } + + false + } + + /// Geriye dönük uyumluluk: is_display_math ile eşdeğerdir. + pub fn is_math_zone(chars: &[PdfChar], lines: &[VectorLine]) -> bool { + Self::is_display_math(chars, lines) + } + + /// Verilen karakterleri ve çizgileri 2B uzayda analiz edip eksiksiz `` dizesi üretir. + pub fn reconstruct_math(chars: &[PdfChar], lines: &[VectorLine]) -> Option { + if chars.is_empty() { + return None; + } + + let nodes = Self::build_ast(chars, lines); + if nodes.is_empty() { + return None; + } + + let inner_xml = nodes_to_omml(&nodes); + Some(format!("{inner_xml}")) + } + + fn build_ast(chars: &[PdfChar], lines: &[VectorLine]) -> Vec { + let mut remaining_chars = chars.to_vec(); + // x koordinatına göre sırala (katı total order) + remaining_chars.sort_by(|a, b| a.x.total_cmp(&b.x)); + + // 1) Yatay kesir çizgilerinden kesir düğümlerini (vl.x1 konumu ile) çıkar + let mut fractions: Vec<(f64, MathNode)> = Vec::new(); + for line in lines { + if line.is_horizontal && line.thickness <= 3.0 && (line.x2 - line.x1) >= 6.0 { + let margin = 5.0; + let mut num_indices = Vec::new(); + let mut den_indices = Vec::new(); + for (idx, c) in remaining_chars.iter().enumerate() { + let mid_x = c.x + c.width * 0.5; + if mid_x >= line.x1 - margin && mid_x <= line.x2 + margin { + if c.y + c.height <= line.y1 + 4.0 && c.y >= line.y1 - 45.0 { + num_indices.push(idx); + } else if c.y >= line.y1 - 4.0 && c.y <= line.y1 + 45.0 { + den_indices.push(idx); + } + } + } + + if !num_indices.is_empty() && !den_indices.is_empty() { + let num_chars: Vec = num_indices.iter().map(|&i| remaining_chars[i].clone()).collect(); + let den_chars: Vec = den_indices.iter().map(|&i| remaining_chars[i].clone()).collect(); + + let mut used = vec![false; remaining_chars.len()]; + for idx in num_indices.into_iter().chain(den_indices) { + used[idx] = true; + } + let mut next_remaining = Vec::with_capacity(remaining_chars.len()); + for (idx, ch) in remaining_chars.into_iter().enumerate() { + if !used[idx] { + next_remaining.push(ch); + } + } + remaining_chars = next_remaining; + + let num_ast = Self::build_linear_ast(&num_chars); + let den_ast = Self::build_linear_ast(&den_chars); + + fractions.push(( + line.x1, + MathNode::Fraction { + num: num_ast, + den: den_ast, + }, + )); + } + } + } + + fractions.sort_by(|(ax, _), (bx, _)| ax.total_cmp(bx)); + + // 2) Kesirleri ve kalan karakterleri soldan sağa gerçek X sırasıyla birleştir + let mut nodes = Vec::new(); + for (frac_x, frac_node) in fractions { + let split_idx = remaining_chars + .iter() + .position(|c| (c.x + c.width * 0.5) >= frac_x) + .unwrap_or(remaining_chars.len()); + if split_idx > 0 { + let left_chars: Vec = remaining_chars.drain(..split_idx).collect(); + nodes.extend(Self::build_linear_ast(&left_chars)); + } + nodes.push(frac_node); + } + + if !remaining_chars.is_empty() { + nodes.extend(Self::build_linear_ast(&remaining_chars)); + } + + nodes + } + + fn build_linear_ast(chars: &[PdfChar]) -> Vec { + if chars.is_empty() { + return Vec::new(); + } + + let mut sorted = chars.to_vec(); + sorted.sort_by(|a, b| a.x.total_cmp(&b.x)); + + let avg_font_size = sorted.iter().map(|c| c.font_size).sum::() / sorted.len() as f64; + let mut nodes: Vec = Vec::new(); + let mut last_base_char: Option = None; + let mut idx = 0; + + while idx < sorted.len() { + let c = &sorted[idx]; + + // 1) Kök (Radical: √) + if c.unicode == "√" { + idx += 1; + let mut expr_chars = Vec::new(); + let radical_x = c.x; + let radical_w = c.width; + + while idx < sorted.len() { + let next = &sorted[idx]; + // Kökün sağında ve dikey olarak yakın olanları al + if next.x < radical_x + radical_w + 120.0 && (next.y - c.y).abs() <= avg_font_size * 1.5 { + expr_chars.push(next.clone()); + idx += 1; + } else { + break; + } + } + + let expr_ast = Self::build_linear_ast(&expr_chars); + nodes.push(MathNode::Radical { + degree: None, + expr: expr_ast, + }); + last_base_char = None; + continue; + } + + // 2) N-ary Operatörleri (∑, ∏, ∫, ∮) + if matches!(c.unicode.as_str(), "∑" | "∏" | "∫" | "∮") { + let op = c.unicode.clone(); + let op_x = c.x; + let op_y = c.y; + let op_fs = c.font_size; + idx += 1; + + let mut sub_chars = Vec::new(); + let mut sup_chars = Vec::new(); + + while idx < sorted.len() { + let next = &sorted[idx]; + // Alt sınır: op_y'nin altında ve yatayda operatörle örtüşen + if next.y > op_y + op_fs * 0.4 && next.x >= op_x - 5.0 && next.x <= op_x + op_fs * 1.2 { + sub_chars.push(next.clone()); + idx += 1; + } else if next.y < op_y - op_fs * 0.2 && next.x >= op_x - 5.0 && next.x <= op_x + op_fs * 1.2 { + // Üst sınır: op_y'nin üstünde + sup_chars.push(next.clone()); + idx += 1; + } else { + break; + } + } + + let sub = if sub_chars.is_empty() { None } else { Some(Self::build_linear_ast(&sub_chars)) }; + let sup = if sup_chars.is_empty() { None } else { Some(Self::build_linear_ast(&sup_chars)) }; + + nodes.push(MathNode::Nary { + operator: op, + sub, + sup, + expr: Vec::new(), + }); + last_base_char = None; + continue; + } + + // 3) Metin içi açık '^' ve '_' karakterleri ile Alt / Üst Simge + if (c.unicode == "^" || c.unicode == "_") && !nodes.is_empty() && idx + 1 < sorted.len() { + let is_sup = c.unicode == "^"; + idx += 1; + let mut script_chars = Vec::new(); + if sorted[idx].unicode == "{" { + idx += 1; + while idx < sorted.len() && sorted[idx].unicode != "}" { + script_chars.push(sorted[idx].clone()); + idx += 1; + } + if idx < sorted.len() && sorted[idx].unicode == "}" { + idx += 1; + } + } else { + while idx < sorted.len() { + let sc = &sorted[idx]; + if sc.unicode.trim().is_empty() + || matches!(sc.unicode.as_str(), "=" | "+" | "-" | "−" | "," | ";" | "<" | ">" | "(" | ")") + { + break; + } + script_chars.push(sc.clone()); + idx += 1; + } + } + if !script_chars.is_empty() { + let script_ast = Self::build_linear_ast(&script_chars); + attach_script(&mut nodes, script_ast, is_sup); + } + continue; + } + + // 4) Geometrik Alt / Üst Simge (önceki taban karaktere göre Y hizası ve boyut karşılaştırması) + if let Some(ref base) = last_base_char { + let is_non_rel_or_space = !c.unicode.trim().is_empty() + && !matches!( + c.unicode.as_str(), + "=" | "≠" | "≤" | "≥" | "<" | ">" | "→" | "←" | "↔" | "⇒" | "⇔" | "," | ";" + ); + if is_non_rel_or_space { + let base_bottom = base.y + base.height; + let cur_bottom = c.y + c.height; + let is_small = c.font_size <= base.font_size * 0.85; + let in_active_script = matches!(nodes.last(), Some(MathNode::SubSup { .. })); + let is_binary_op = matches!(c.unicode.as_str(), "+" | "-" | "−" | "×" | "÷" | "/"); + + if !is_binary_op || (in_active_script && is_small) { + let is_sup = cur_bottom < base_bottom - base.font_size * 0.15 + || (is_small && c.y < base.y + base.height * 0.35); + let is_sub = !is_sup + && (cur_bottom > base_bottom + base.font_size * 0.12 || is_small); + + if is_sup || is_sub { + let script_node = MathNode::Text(c.unicode.clone(), c.is_italic); + attach_script(&mut nodes, vec![script_node], is_sup); + idx += 1; + continue; + } + } + } + } + + // Standart Matematik Metni / Harfi + if !c.unicode.trim().is_empty() { + last_base_char = Some(c.clone()); + } else { + last_base_char = None; + } + nodes.push(MathNode::Text(c.unicode.clone(), c.is_italic)); + idx += 1; + } + + nodes + } +} + +fn attach_script(nodes: &mut Vec, script: Vec, is_sup: bool) { + if let Some(MathNode::SubSup { sub, sup, .. }) = nodes.last_mut() { + if is_sup { + if let Some(existing) = sup { + existing.extend(script); + return; + } + *sup = Some(script); + return; + } else { + if let Some(existing) = sub { + existing.extend(script); + return; + } + *sub = Some(script); + return; + } + } + + if let Some(prev_base) = nodes.pop() { + if is_sup { + nodes.push(MathNode::SubSup { + base: vec![prev_base], + sub: None, + sup: Some(script), + }); + } else { + nodes.push(MathNode::SubSup { + base: vec![prev_base], + sub: Some(script), + sup: None, + }); + } + } +} + +fn join_chars_with_gaps(chars: &[PdfChar]) -> String { + let mut sorted = chars.to_vec(); + sorted.sort_by(|a, b| a.x.total_cmp(&b.x)); + let avg_w = sorted.iter().map(|c| c.width).sum::() / sorted.len().max(1) as f64; + let mut out = String::new(); + let mut prev: Option<&PdfChar> = None; + for c in &sorted { + if let Some(p) = prev { + let gap = c.x - (p.x + p.width); + let fs = p.font_size.max(c.font_size); + let thresh = (fs * 0.16).min(avg_w * 0.32).max(1.2); + if gap > thresh && !out.ends_with(' ') && !c.unicode.starts_with(' ') { + out.push(' '); + } + } + out.push_str(&c.unicode); + prev = Some(c); + } + out +} + +pub fn is_math_symbol(s: &str) -> bool { + matches!( + s.trim(), + "+" | "−" | "-" | "×" | "÷" | "=" | "≠" | "<" | ">" | "≤" | "≥" | "±" | "∓" | "≈" | "≡" + | "∞" | "∝" | "√" | "∫" | "∑" | "∏" | "∂" | "∇" | "∈" | "∉" | "∋" | "⊂" | "⊃" + | "⊆" | "⊇" | "∩" | "∪" | "∧" | "∨" | "¬" | "∀" | "∃" | "→" | "←" | "↔" + | "⇒" | "⇐" | "⇔" | "α" | "β" | "γ" | "δ" | "ε" | "θ" | "λ" | "μ" | "π" | "σ" + | "ω" | "Δ" | "Σ" | "Ω" | "Φ" + ) +} + +pub fn is_prose_word(w: &str) -> bool { + let lower = w.to_lowercase(); + let trimmed = lower.trim_matches(|c: char| !c.is_alphabetic()); + if trimmed.is_empty() { + return false; + } + // Matematik fonksiyon isimleri nesir sayılmaz + if matches!( + trimmed, + "sin" | "cos" | "tan" | "cot" | "sec" | "csc" | "log" | "ln" | "exp" | "lim" | "det" | "min" | "max" | "sup" | "inf" | "arg" | "dim" | "deg" + ) { + return false; + } + // Sık kullanılan kısa Türkçe ve İngilizce nesir kelimeleri + if matches!( + trimmed, + "ve" | "ile" | "icin" | "için" | "olan" | "bir" | "bu" | "de" | "da" | "ise" | "gore" | "göre" + | "her" | "tum" | "tüm" | "yani" | "burada" | "elde" | "edilir" | "değeri" | "degeri" | "olur" + | "the" | "and" | "for" | "with" | "from" | "that" | "this" | "where" | "then" + ) { + return true; + } + // 3 harften uzun tüm alfabetik kelimeler doğal dil nesir kelimesidir + trimmed.chars().count() >= 3 +} + +pub fn is_math_char(c: &PdfChar) -> bool { + c.is_math || is_math_symbol(&c.unicode) +} diff --git a/src-tauri/src/services/pdf_parser/matrix.rs b/src-tauri/src/services/pdf_parser/matrix.rs new file mode 100644 index 0000000..6bf92b6 --- /dev/null +++ b/src-tauri/src/services/pdf_parser/matrix.rs @@ -0,0 +1,235 @@ +//! PDF Koordinat Sistemi, Affine Dönüşüm Matrisi ve Grafik Durum Makinesi. +//! +//! PDF standart koordinat sistemi (sol-alt tabanlı) ile Word / DOCX / ekran +//! koordinat sistemi (sol-üst tabanlı) arasındaki dönüşümleri, MediaBox/CropBox/Rotate +//! normalizasyonunu ve iç içe geçmiş grafik durum yığınını (`q` / `Q`) yönetir. + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct AffineMatrix { + pub a: f64, + pub b: f64, + pub c: f64, + pub d: f64, + pub e: f64, + pub f: f64, +} + +impl Default for AffineMatrix { + fn default() -> Self { + Self::identity() + } +} + +impl AffineMatrix { + pub const fn new(a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) -> Self { + Self { a, b, c, d, e, f } + } + + pub const fn identity() -> Self { + Self { + a: 1.0, + b: 0.0, + c: 0.0, + d: 1.0, + e: 0.0, + f: 0.0, + } + } + + pub fn from_slice(s: &[f64]) -> Self { + if s.len() >= 6 { + Self::new(s[0], s[1], s[2], s[3], s[4], s[5]) + } else { + Self::identity() + } + } + + pub fn to_array(&self) -> [f64; 6] { + [self.a, self.b, self.c, self.d, self.e, self.f] + } + + /// İki afin matrisi çarpar: (self x other). + /// PDF spesifikasyonuna göre: CTM_new = M x CTM_old + pub fn multiply(&self, other: &Self) -> Self { + Self { + a: self.a * other.a + self.b * other.c, + b: self.a * other.b + self.b * other.d, + c: self.c * other.a + self.d * other.c, + d: self.c * other.b + self.d * other.d, + e: self.e * other.a + self.f * other.c + other.e, + f: self.e * other.b + self.f * other.d + other.f, + } + } + + /// Noktayı dönüştürür: [x', y', 1] = [x, y, 1] x M + pub fn transform_point(&self, x: f64, y: f64) -> (f64, f64) { + let x_prime = self.a * x + self.c * y + self.e; + let y_prime = self.b * x + self.d * y + self.f; + (x_prime, y_prime) + } + + /// Vektörü dönüştürür (öteleme e ve f hariç): + pub fn transform_vector(&self, dx: f64, dy: f64) -> (f64, f64) { + let dx_prime = self.a * dx + self.c * dy; + let dy_prime = self.b * dx + self.d * dy; + (dx_prime, dy_prime) + } + + pub fn scale_x(&self) -> f64 { + (self.a * self.a + self.b * self.b).sqrt() + } + + pub fn scale_y(&self) -> f64 { + (self.c * self.c + self.d * self.d).sqrt() + } + + pub fn rotation_rad(&self) -> f64 { + self.b.atan2(self.a) + } + + pub fn inverse(&self) -> Option { + let det = self.a * self.d - self.b * self.c; + if det.abs() < 1e-12 { + return None; + } + let inv_det = 1.0 / det; + Some(Self { + a: self.d * inv_det, + b: -self.b * inv_det, + c: -self.c * inv_det, + d: self.a * inv_det, + e: (self.c * self.f - self.d * self.e) * inv_det, + f: (self.b * self.e - self.a * self.f) * inv_det, + }) + } +} + +/// Sayfa sınır kutusu ve yönlendirme bilgisi. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct PageBox { + pub min_x: f64, + pub min_y: f64, + pub max_x: f64, + pub max_y: f64, + pub rotation: i32, +} + +impl Default for PageBox { + fn default() -> Self { + Self { + min_x: 0.0, + min_y: 0.0, + max_x: 595.28, // Standart A4 Genişliği (pt) + max_y: 841.89, // Standart A4 Yüksekliği (pt) + rotation: 0, + } + } +} + +impl PageBox { + pub fn new(coords: [f64; 4], rotation: i32) -> Self { + let min_x = coords[0].min(coords[2]); + let max_x = coords[0].max(coords[2]); + let min_y = coords[1].min(coords[3]); + let max_y = coords[1].max(coords[3]); + let rot = rotation.rem_euclid(360); + Self { + min_x, + min_y, + max_x, + max_y, + rotation: rot, + } + } + + pub fn width(&self) -> f64 { + if self.rotation == 90 || self.rotation == 270 { + (self.max_y - self.min_y).abs() + } else { + (self.max_x - self.min_x).abs() + } + } + + pub fn height(&self) -> f64 { + if self.rotation == 90 || self.rotation == 270 { + (self.max_x - self.min_x).abs() + } else { + (self.max_y - self.min_y).abs() + } + } + + /// PDF'in sol-alt koordinatını sayfanın sol-üst (ekran/docx) koordinatına çevirir. + pub fn to_top_left_point(&self, x: f64, y: f64) -> (f64, f64) { + match self.rotation { + 90 => { + let norm_x = y - self.min_y; + let norm_y = x - self.min_x; + (norm_x, norm_y) + } + 180 => { + let norm_x = self.max_x - x; + let norm_y = y - self.min_y; + (norm_x, norm_y) + } + 270 => { + let norm_x = self.max_y - y; + let norm_y = self.max_x - x; + (norm_x, norm_y) + } + _ => { + let norm_x = x - self.min_x; + let norm_y = self.max_y - y; + (norm_x, norm_y) + } + } + } +} + +/// PDF Grafik Durumu (Graphics State). +#[derive(Debug, Clone)] +pub struct GraphicsState { + pub ctm: AffineMatrix, + pub text_matrix: AffineMatrix, + pub text_line_matrix: AffineMatrix, + pub font_name: String, + pub font_size: f64, + pub char_spacing: f64, + pub word_spacing: f64, + pub horizontal_scaling: f64, // Yüzde (varsayılan 100.0) + pub leading: f64, + pub text_rise: f64, + pub render_mode: u8, + pub stroke_color: [u8; 3], + pub fill_color: [u8; 3], + pub line_width: f64, + pub current_point: Option<(f64, f64)>, +} + +impl Default for GraphicsState { + fn default() -> Self { + Self { + ctm: AffineMatrix::identity(), + text_matrix: AffineMatrix::identity(), + text_line_matrix: AffineMatrix::identity(), + font_name: String::new(), + font_size: 10.0, + char_spacing: 0.0, + word_spacing: 0.0, + horizontal_scaling: 100.0, + leading: 0.0, + text_rise: 0.0, + render_mode: 0, + stroke_color: [0, 0, 0], + fill_color: [0, 0, 0], + line_width: 1.0, + current_point: None, + } + } +} + +impl GraphicsState { + pub fn reset_text_matrices(&mut self) { + self.text_matrix = AffineMatrix::identity(); + self.text_line_matrix = AffineMatrix::identity(); + } +} diff --git a/src-tauri/src/services/pdf_parser/mod.rs b/src-tauri/src/services/pdf_parser/mod.rs new file mode 100644 index 0000000..6e8244b --- /dev/null +++ b/src-tauri/src/services/pdf_parser/mod.rs @@ -0,0 +1,249 @@ +//! Endüstriyel Düzeyde %100 Saf Rust PDF Yorumlayıcı, Sayfa Düzeni ve Matematik (OMML) Motoru. +//! +//! PyMuPDF (`fitz`), `pdf2docx` ve Math OMML standartlarıyla birebir uyumlu; +//! harici Python, C/C++ ve PDFium bağımlılığı olmadan sıfır kalite kaybıyla çalışır. + +pub mod matrix; +pub mod tex_font_maps; +pub mod font_resolver; +pub mod image_extractor; +pub mod content_stream; +pub mod math_reconstructor; +pub mod table_reconstructor; +pub mod layout_analyzer; + +use std::path::{Path, PathBuf}; +use lopdf::{Document as LopdfDoc, Object, ObjectId}; + +use crate::error::{AppError, AppResult}; +use crate::services::docx_writer::DocxWriter; +use crate::services::office_model::Document as OfficeDoc; +use self::matrix::PageBox; +use self::font_resolver::FontResolver; +use self::content_stream::ContentStreamInterpreter; +use self::layout_analyzer::{LayoutAnalyzer, PageContent}; + +/// PDF dosyasını yüksek çözünürlüklü Saf Rust motoruyla ayrıştırıp DOCX dosyasına dönüştürür. +pub fn convert_pdf_to_docx( + input_path: &str, + output_path: &Path, + preserve_math: bool, +) -> AppResult { + let lopdf_doc = LopdfDoc::load(input_path) + .map_err(|e| AppError::Pdf(format!("PDF dosyası yüklenemedi: {}", e)))?; + + let office_doc = convert_pdf_to_document(&lopdf_doc, input_path, preserve_math)?; + + DocxWriter::create_from_document(output_path, &office_doc)?; + Ok(output_path.to_path_buf()) +} + +/// PDF belgesini iç model olan `office_model::Document` yapısına dönüştürür. +pub fn convert_pdf_to_document( + doc: &LopdfDoc, + input_path: &str, + preserve_math: bool, +) -> AppResult { + let pages_dict = doc.get_pages(); + if pages_dict.is_empty() { + return Err(AppError::Pdf("PDF içinde sayfa bulunamadı.".to_string())); + } + + let mut page_ids: Vec<(u32, ObjectId)> = pages_dict.into_iter().collect(); + page_ids.sort_by_key(|(p_num, _)| *p_num); + + let mut font_resolver = FontResolver::new(); + let mut page_contents = Vec::with_capacity(page_ids.len()); + + for (_page_num, page_id) in page_ids { + let page_box = get_page_box(doc, page_id); + let resources = get_page_resources(doc, page_id); + + let mut interpreter = ContentStreamInterpreter::new(doc, &page_box, &mut font_resolver, resources); + + let content_bytes = get_page_content_bytes(doc, page_id); + interpreter.interpret_stream(&content_bytes); + + page_contents.push(PageContent { + page_box, + chars: interpreter.chars, + lines: interpreter.lines, + filled_rects: interpreter.filled_rects, + images: interpreter.images, + }); + } + + // Taranmış (scanned) PDF kontrolü: sayfada hiç metin glifi yoksa + let total_chars: usize = page_contents.iter().map(|p| p.chars.len()).sum(); + if total_chars == 0 { + // Otomatik WinRT OCR fallback + if let Ok(ocr_doc) = run_ocr_fallback(input_path) { + return Ok(ocr_doc); + } + } + + let office_doc = LayoutAnalyzer::analyze_document(page_contents, preserve_math); + Ok(office_doc) +} + +fn get_page_content_bytes(doc: &LopdfDoc, page_id: ObjectId) -> Vec { + let mut bytes = Vec::new(); + if let Ok(page_dict) = doc.get_object(page_id).and_then(|o| o.as_dict()) { + if let Ok(contents) = page_dict.get(b"Contents") { + collect_stream_bytes(doc, contents, &mut bytes); + } + } + bytes +} + +fn collect_stream_bytes(doc: &LopdfDoc, obj: &Object, buffer: &mut Vec) { + match obj { + Object::Reference(id) => { + if let Ok(target) = doc.get_object(*id) { + collect_stream_bytes(doc, target, buffer); + } + } + Object::Stream(stream) => { + let data = stream + .decompressed_content() + .unwrap_or_else(|_| stream.content.clone()); + buffer.extend_from_slice(&data); + buffer.push(b'\n'); + } + Object::Array(arr) => { + for item in arr { + collect_stream_bytes(doc, item, buffer); + } + } + _ => {} + } +} + +fn get_page_box(doc: &LopdfDoc, page_id: ObjectId) -> PageBox { + let mut media_box = [0.0, 0.0, 595.28, 841.89]; + let mut rotation = 0i32; + + if let Ok(page_dict) = doc.get_object(page_id).and_then(|o| o.as_dict()) { + if let Some(arr) = get_inherited_box(doc, page_dict, b"CropBox").or_else(|| get_inherited_box(doc, page_dict, b"MediaBox")) { + media_box = arr; + } + if let Some(rot) = get_inherited_i64(doc, page_dict, b"Rotate") { + rotation = rot as i32; + } + } + + PageBox::new(media_box, rotation) +} + +fn get_page_resources(doc: &LopdfDoc, page_id: ObjectId) -> Option<&lopdf::Dictionary> { + let page_dict = doc.get_object(page_id).ok()?.as_dict().ok()?; + get_inherited_dict(doc, page_dict, b"Resources") +} + +fn get_inherited_box(doc: &LopdfDoc, dict: &lopdf::Dictionary, key: &[u8]) -> Option<[f64; 4]> { + if let Ok(obj) = dict.get(key) { + let resolved = resolve_object(doc, obj); + if let Ok(arr) = resolved.as_array() { + if arr.len() >= 4 { + let x1 = to_f64(&arr[0])?; + let y1 = to_f64(&arr[1])?; + let x2 = to_f64(&arr[2])?; + let y2 = to_f64(&arr[3])?; + return Some([x1, y1, x2, y2]); + } + } + } + if let Ok(parent_obj) = dict.get(b"Parent") { + if let Some(parent_dict) = resolve_dict(doc, parent_obj) { + return get_inherited_box(doc, parent_dict, key); + } + } + None +} + +fn get_inherited_i64(doc: &LopdfDoc, dict: &lopdf::Dictionary, key: &[u8]) -> Option { + if let Ok(obj) = dict.get(key) { + if let Ok(val) = resolve_object(doc, obj).as_i64() { + return Some(val); + } + } + if let Ok(parent_obj) = dict.get(b"Parent") { + if let Some(parent_dict) = resolve_dict(doc, parent_obj) { + return get_inherited_i64(doc, parent_dict, key); + } + } + None +} + +fn get_inherited_dict<'a>(doc: &'a LopdfDoc, dict: &'a lopdf::Dictionary, key: &[u8]) -> Option<&'a lopdf::Dictionary> { + if let Ok(obj) = dict.get(key) { + if let Some(d) = resolve_dict(doc, obj) { + return Some(d); + } + } + if let Ok(parent_obj) = dict.get(b"Parent") { + if let Some(parent_dict) = resolve_dict(doc, parent_obj) { + return get_inherited_dict(doc, parent_dict, key); + } + } + None +} + +fn resolve_object<'a>(doc: &'a LopdfDoc, obj: &'a Object) -> &'a Object { + match obj { + Object::Reference(id) => doc.get_object(*id).unwrap_or(obj), + _ => obj, + } +} + +fn resolve_dict<'a>(doc: &'a LopdfDoc, obj: &'a Object) -> Option<&'a lopdf::Dictionary> { + match resolve_object(doc, obj) { + Object::Dictionary(d) => Some(d), + Object::Stream(s) => Some(&s.dict), + _ => None, + } +} + +fn to_f64(obj: &Object) -> Option { + match obj { + Object::Real(f) => Some(*f as f64), + Object::Integer(i) => Some(*i as f64), + _ => None, + } +} + +fn run_ocr_fallback(input_path: &str) -> AppResult { + let temp_dir = std::env::temp_dir().join(format!("ld_ocr_pdf_{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&temp_dir)?; + + let rendered_pages = crate::services::pdf_tools::PdfTools::render_pages( + input_path, + None, + &temp_dir, + 200, + "png", + )?; + + let mut doc = OfficeDoc::default(); + for (idx, page_path) in rendered_pages.iter().enumerate() { + if idx > 0 { + doc.blocks.push(crate::services::office_model::Block::PageBreak); + } + if let Ok(text) = crate::services::ocr_engine::OcrEngine::recognize_image(&page_path.to_string_lossy()) { + for line in text.lines() { + let trimmed = line.trim(); + if !trimmed.is_empty() { + doc.blocks.push(crate::services::office_model::Block::Paragraph( + crate::services::office_model::Paragraph { + style: Default::default(), + runs: vec![crate::services::office_model::Run::plain(trimmed)], + }, + )); + } + } + } + let _ = std::fs::remove_file(page_path); + } + let _ = std::fs::remove_dir_all(&temp_dir); + Ok(doc) +} diff --git a/src-tauri/src/services/pdf_parser/table_reconstructor.rs b/src-tauri/src/services/pdf_parser/table_reconstructor.rs new file mode 100644 index 0000000..cb128ce --- /dev/null +++ b/src-tauri/src/services/pdf_parser/table_reconstructor.rs @@ -0,0 +1,211 @@ +//! PDF Tablo Rekonstrüksiyon Motoru (Table Reconstructor). +//! +//! Çerçeveli (Bordered) ve Çerçevesiz / Akademik (Booktabs) tabloları, +//! birleşik hücreleri (`gridSpan` / `vMerge`), hücre arkaplan dolgularını (`w:shd`) +//! ve hücre içi zengin içerikleri (metin, görsel, denklem) Word tablosuna dönüştürür. + +use super::content_stream::{FilledRect, PdfChar, VectorLine}; +use super::image_extractor::ExtractedImage; +use crate::services::office_model::{Align, Cell, Paragraph, ParagraphStyle, Run, Table}; + +pub struct TableReconstructor; + +impl TableReconstructor { + /// Sayfadaki çizgileri, dolguları, metinleri ve görselleri analiz ederek tabloları bulur + /// ve tüketilen öğelerin indekslerini döndürür. + pub fn extract_tables( + lines: &[VectorLine], + filled_rects: &[FilledRect], + chars: &[PdfChar], + _images: &[ExtractedImage], + consumed_char_indices: &mut Vec, + ) -> Vec { + let mut tables = Vec::new(); + + // 1) Yatay ve dikey çizgileri topla + let mut h_lines: Vec = lines.iter().filter(|l| l.is_horizontal).cloned().collect(); + let mut v_lines: Vec = lines.iter().filter(|l| !l.is_horizontal).cloned().collect(); + + if h_lines.len() < 2 || v_lines.len() < 2 { + return tables; + } + + // Çizgileri sırala + h_lines.sort_by(|a, b| a.y1.total_cmp(&b.y1)); + v_lines.sort_by(|a, b| a.x1.total_cmp(&b.x1)); + + // Yatay kesişim koordinatları (Y ekseni) ve dikey kesişim koordinatları (X ekseni) + let y_coords = cluster_coords(&h_lines.iter().map(|l| l.y1).collect::>(), 4.0); + let x_coords = cluster_coords(&v_lines.iter().map(|l| l.x1).collect::>(), 4.0); + + if y_coords.len() < 2 || x_coords.len() < 2 { + return tables; + } + + // En az 2 satır ve 2 sütunluk bir ızgara oluştur + let num_rows = y_coords.len() - 1; + let num_cols = x_coords.len() - 1; + + // Geçerli bir tablo mu kontrolü (ızgara alanında metin veya dolgu var mı?) + let table_min_x = *x_coords.first().unwrap(); + let table_max_x = *x_coords.last().unwrap(); + let table_min_y = *y_coords.first().unwrap(); + let table_max_y = *y_coords.last().unwrap(); + + let table_chars_count = chars + .iter() + .filter(|c| c.x >= table_min_x - 2.0 && c.x <= table_max_x + 2.0 && c.y >= table_min_y - 2.0 && c.y <= table_max_y + 2.0) + .count(); + + if table_chars_count == 0 { + return tables; + } + + // Sütun genişlik oranları + let total_w = table_max_x - table_min_x; + let mut widths = Vec::with_capacity(num_cols); + for col in 0..num_cols { + let col_w = x_coords[col + 1] - x_coords[col]; + widths.push((col_w / total_w) as f32); + } + + let mut rows = Vec::with_capacity(num_rows); + + for r in 0..num_rows { + let y1 = y_coords[r]; + let y2 = y_coords[r + 1]; + let mut row_cells = Vec::with_capacity(num_cols); + + for c in 0..num_cols { + let x1 = x_coords[c]; + let x2 = x_coords[c + 1]; + + // Hücreye ait arkaplan rengi var mı? (Hücre merkezini kapsayan dolgulu dikdörtgen) + let center_x = (x1 + x2) / 2.0; + let center_y = (y1 + y2) / 2.0; + let cell_shade = filled_rects + .iter() + .find(|rect| { + rect.x <= center_x + && rect.x + rect.width >= center_x + && rect.y <= center_y + && rect.y + rect.height >= center_y + }) + .map(|rect| rect.color); + + // Hücreye ait karakterleri topla + let mut cell_chars = Vec::new(); + for (idx, ch) in chars.iter().enumerate() { + if ch.x >= x1 - 1.0 && ch.x <= x2 + 1.0 && ch.y >= y1 - 1.0 && ch.y <= y2 + 1.0 { + cell_chars.push(ch.clone()); + consumed_char_indices.push(idx); + } + } + + // Karakterleri satırlara ve paragraflara dönüştür + let paragraphs = build_cell_paragraphs(&cell_chars); + + row_cells.push(Cell { + colspan: 1, + rowspan: 1, + shade: cell_shade, + align: Align::Left, + paragraphs, + }); + } + + rows.push(row_cells); + } + + tables.push(Table { + widths, + rows, + header_rows: 1, + }); + + tables + } +} + +fn cluster_coords(coords: &[f64], tolerance: f64) -> Vec { + if coords.is_empty() { + return Vec::new(); + } + let mut sorted = coords.to_vec(); + sorted.sort_by(|a, b| a.total_cmp(b)); + + let mut clusters = Vec::new(); + let mut current_cluster = vec![sorted[0]]; + + for &c in &sorted[1..] { + let last = *current_cluster.last().unwrap(); + if (c - last).abs() <= tolerance { + current_cluster.push(c); + } else { + let avg = current_cluster.iter().sum::() / current_cluster.len() as f64; + clusters.push(avg); + current_cluster = vec![c]; + } + } + + if !current_cluster.is_empty() { + let avg = current_cluster.iter().sum::() / current_cluster.len() as f64; + clusters.push(avg); + } + + clusters +} + +fn build_cell_paragraphs(chars: &[PdfChar]) -> Vec { + if chars.is_empty() { + return vec![Paragraph::default()]; + } + + let mut sorted = chars.to_vec(); + sorted.sort_by(|a, b| a.y.total_cmp(&b.y).then_with(|| a.x.total_cmp(&b.x))); + + // Hücre içi satırları grupla + let mut cell_lines: Vec> = Vec::new(); + for ch in sorted { + if let Some(last_line) = cell_lines.last_mut() { + let line_y = last_line.iter().map(|c| c.y).sum::() / last_line.len() as f64; + let line_sz = last_line.iter().map(|c| c.font_size).sum::() / last_line.len() as f64; + let tol = (line_sz.max(ch.font_size) * 0.45).max(3.0); + if (ch.y - line_y).abs() <= tol { + last_line.push(ch); + continue; + } + } + cell_lines.push(vec![ch]); + } + + for line in &mut cell_lines { + line.sort_by(|a, b| a.x.total_cmp(&b.x)); + } + + let mut runs = Vec::new(); + for (l_idx, line) in cell_lines.iter().enumerate() { + if l_idx > 0 { + runs.push(Run::plain("\n")); + } + let mut line_text = String::new(); + let mut last_char: Option<&PdfChar> = None; + for c in line { + if let Some(prev) = last_char { + if c.x > prev.x + prev.width + 1.8 { + line_text.push(' '); + } + } + line_text.push_str(&c.unicode); + last_char = Some(c); + } + if !line_text.trim().is_empty() { + runs.push(Run::plain(line_text.trim())); + } + } + + vec![Paragraph { + style: ParagraphStyle::default(), + runs, + }] +} diff --git a/src-tauri/src/services/pdf_parser/tex_font_maps.rs b/src-tauri/src/services/pdf_parser/tex_font_maps.rs new file mode 100644 index 0000000..55f794b --- /dev/null +++ b/src-tauri/src/services/pdf_parser/tex_font_maps.rs @@ -0,0 +1,506 @@ +//! TeX / LaTeX Matematik Font Eşleme Tabloları ve Adobe Glyph List (AGL). +//! +//! Akademik makalelerde ve teknik PDF'lerde `/ToUnicode` tablosu bulunmadığında +//! devreye giren Tier 4 TeX Computer Modern (`CMMI`, `CMSY`, `CMEX`, `CMR`, +//! `MSAM`, `MSBM`, `Symbol`) ve Tier 2 AGL adlandırma eşlemelerini sağlar. + +use std::collections::HashMap; +use std::sync::OnceLock; + +/// TeX Computer Modern Math Italic (`CMMI`) karakter kodlarını Unicode'a çevirir. +pub fn tex_cmmi_to_unicode(code: u8) -> Option { + match code { + // Büyük Yunan Harfleri + 0x00 => Some('Γ'), + 0x01 => Some('Δ'), + 0x02 => Some('Θ'), + 0x03 => Some('Λ'), + 0x04 => Some('Ξ'), + 0x05 => Some('Π'), + 0x06 => Some('Σ'), + 0x07 => Some('Υ'), + 0x08 => Some('Φ'), + 0x09 => Some('Ψ'), + 0x0A => Some('Ω'), + + // Küçük Yunan Harfleri + 0x0B => Some('α'), + 0x0C => Some('β'), + 0x0D => Some('γ'), + 0x0E => Some('δ'), + 0x0F => Some('ϵ'), + 0x10 => Some('ζ'), + 0x11 => Some('η'), + 0x12 => Some('θ'), + 0x13 => Some('ι'), + 0x14 => Some('κ'), + 0x15 => Some('λ'), + 0x16 => Some('μ'), + 0x17 => Some('ν'), + 0x18 => Some('ξ'), + 0x19 => Some('π'), + 0x1A => Some('ρ'), + 0x1B => Some('σ'), + 0x1C => Some('τ'), + 0x1D => Some('υ'), + 0x1E => Some('ϕ'), + 0x1F => Some('χ'), + 0x20 => Some('ψ'), + 0x21 => Some('ω'), + 0x22 => Some('ε'), + 0x23 => Some('ϑ'), + 0x24 => Some('ϖ'), + 0x25 => Some('ϱ'), + 0x26 => Some('ς'), + 0x27 => Some('φ'), + + // Özel Semboller & Oklar + 0x28 => Some('↼'), + 0x29 => Some('↽'), + 0x2A => Some('⇀'), + 0x2B => Some('⇁'), + 0x3A => Some(','), + 0x3B => Some('.'), + 0x3C => Some('<'), + 0x3D => Some('/'), + 0x3E => Some('>'), + 0x3F => Some('⋆'), + 0x40 => Some('∂'), // Kısmi türev \partial + + // Rakamlar + 0x30..=0x39 => Some((b'0' + (code - 0x30)) as char), + + // İtalik Latin Harfleri (A-Z, a-z) + 0x41..=0x5A => Some((b'A' + (code - 0x41)) as char), + 0x61..=0x7A => Some((b'a' + (code - 0x61)) as char), + + 0x7B => Some('ℓ'), // \ell + 0x7C => Some('℘'), // \wp + 0x7D => Some('ℜ'), + 0x7E => Some('ℑ'), + _ => None, + } +} + +/// TeX Computer Modern Math Symbols (`CMSY`) karakter kodlarını Unicode'a çevirir. +pub fn tex_cmsy_to_unicode(code: u8) -> Option { + match code { + 0x00 => Some('−'), // \minus + 0x01 => Some('⋅'), // \cdot + 0x02 => Some('×'), // \times + 0x03 => Some('*'), // \ast + 0x04 => Some('÷'), // \div + 0x05 => Some('⋄'), // \diamond + 0x06 => Some('±'), // \pm + 0x07 => Some('∓'), // \mp + 0x08 => Some('⊕'), // \oplus + 0x09 => Some('⊖'), // \ominus + 0x0A => Some('⊗'), // \otimes + 0x0B => Some('⊘'), // \oslash + 0x0C => Some('⊙'), // \odot + 0x0D => Some('◯'), // \bigcirc + 0x0E => Some('∘'), // \circ + 0x0F => Some('∙'), // \bullet + 0x10 => Some('≍'), // \asymp + 0x11 => Some('≡'), // \equiv + 0x12 => Some('⊆'), // \subseteq + 0x13 => Some('⊇'), // \supseteq + 0x14 => Some('≤'), // \leq + 0x15 => Some('≥'), // \geq + 0x16 => Some('≼'), // \preceq + 0x17 => Some('≽'), // \succeq + 0x18 => Some('∼'), // \sim + 0x19 => Some('≈'), // \approx + 0x1A => Some('⊂'), // \subset + 0x1B => Some('⊃'), // \supset + 0x1C => Some('≪'), // \ll + 0x1D => Some('≫'), // \gg + 0x1E => Some('≺'), // \prec + 0x1F => Some('≻'), // \succ + + 0x20 => Some('←'), // \leftarrow + 0x21 => Some('→'), // \rightarrow + 0x22 => Some('↑'), // \uparrow + 0x23 => Some('↓'), // \downarrow + 0x24 => Some('↔'), // \leftrightarrow + 0x25 => Some('↗'), // \nearrow + 0x26 => Some('↘'), // \searrow + 0x27 => Some('≃'), // \simeq + 0x28 => Some('⇐'), // \Leftarrow + 0x29 => Some('⇒'), // \Rightarrow + 0x2A => Some('⇑'), // \Uparrow + 0x2B => Some('⇓'), // \Downarrow + 0x2C => Some('⇔'), // \Leftrightarrow + 0x2D => Some('↖'), // \nwarrow + 0x2E => Some('↙'), // \swarrow + 0x2F => Some('∝'), // \propto + + 0x30 => Some('′'), // \prime + 0x31 => Some('∞'), // \infty + 0x32 => Some('∈'), // \in + 0x33 => Some('∋'), // \ni + 0x34 => Some('△'), // \triangle + 0x35 => Some('▽'), // \triangledown + 0x36 => Some('∇'), // \nabla + 0x37 => Some('⊥'), // \bot + 0x38 => Some('∀'), // \forall + 0x39 => Some('∃'), // \exists + 0x3A => Some('¬'), // \neg + 0x3B => Some('∅'), // \emptyset + 0x3C => Some('ℜ'), // \Re + 0x3D => Some('ℑ'), // \Im + 0x3E => Some('⊤'), // \top + 0x3F => Some('ℵ'), // \aleph + + // Kaligrafi Harfler \mathcal{A}..\mathcal{Z} -> Standart A-Z + 0x41..=0x5A => Some((b'A' + (code - 0x41)) as char), + + 0x5B => Some('∪'), // \cup + 0x5C => Some('∩'), // \cap + 0x5D => Some('⊎'), // \uplus + 0x5E => Some('∧'), // \wedge + 0x5F => Some('∨'), // \vee + 0x60 => Some('⊢'), // \vdash + 0x61 => Some('⊣'), // \dashv + 0x62 => Some('⌊'), // \lfloor + 0x63 => Some('⌋'), // \rfloor + 0x64 => Some('⌈'), // \lceil + 0x65 => Some('⌉'), // \rceil + 0x66 => Some('{'), + 0x67 => Some('}'), + 0x68 => Some('⟨'), // \langle + 0x69 => Some('⟩'), // \rangle + 0x6A => Some('|'), + 0x6B => Some('∥'), // \parallel + 0x6C => Some('↕'), + 0x6D => Some('⇕'), + 0x6E => Some('∖'), // \backslash + 0x6F => Some('≀'), // \wr + 0x72 => Some('∇'), + _ => None, + } +} + +/// TeX Computer Modern Math Extension (`CMEX`) karakter kodlarını Unicode'a çevirir. +pub fn tex_cmex_to_unicode(code: u8) -> Option { + match code { + 0x48 | 0x50 => Some('∑'), // \sum + 0x51 => Some('∏'), // \prod + 0x52 => Some('∐'), // \coprod + 0x58 => Some('∫'), // \int + 0x59 => Some('∮'), // \oint + 0x5A => Some('⋂'), // \bigcap + 0x5B => Some('⋃'), // \bigcup + 0x5C => Some('⨄'), // \biguplus + 0x5D => Some('⨅'), // \bigsqcap + 0x5E => Some('⨆'), // \bigsqcup + 0x5F => Some('⋁'), // \bigvee + 0x60 => Some('⋀'), // \bigwedge + 0x70 | 0x71 => Some('√'), // \sqrt + _ => None, + } +} + +/// Standart Adobe Symbol font karakter kodlarını Unicode'a çevirir. +pub fn symbol_font_to_unicode(code: u8) -> Option { + match code { + 0x20 => Some(' '), + 0x21 => Some('!'), + 0x22 => Some('∀'), + 0x23 => Some('#'), + 0x24 => Some('∃'), + 0x25 => Some('%'), + 0x26 => Some('&'), + 0x27 => Some('∍'), + 0x28 => Some('('), + 0x29 => Some(')'), + 0x2A => Some('∗'), + 0x2B => Some('+'), + 0x2C => Some(','), + 0x2D => Some('−'), + 0x2E => Some('.'), + 0x2F => Some('/'), + + 0x30..=0x39 => Some((b'0' + (code - 0x30)) as char), + 0x3A => Some(':'), + 0x3B => Some(';'), + 0x3C => Some('<'), + 0x3D => Some('='), + 0x3E => Some('>'), + 0x3F => Some('?'), + 0x40 => Some('≅'), + + // Büyük Yunan Harfleri + 0x41 => Some('Α'), + 0x42 => Some('Β'), + 0x43 => Some('Χ'), + 0x44 => Some('Δ'), + 0x45 => Some('Ε'), + 0x46 => Some('Φ'), + 0x47 => Some('Γ'), + 0x48 => Some('Η'), + 0x49 => Some('Ι'), + 0x4A => Some('ϑ'), + 0x4B => Some('Κ'), + 0x4C => Some('Λ'), + 0x4D => Some('Μ'), + 0x4E => Some('Ν'), + 0x4F => Some('Ο'), + 0x50 => Some('Π'), + 0x51 => Some('Θ'), + 0x52 => Some('Ρ'), + 0x53 => Some('Σ'), + 0x54 => Some('Τ'), + 0x55 => Some('Υ'), + 0x56 => Some('ς'), + 0x57 => Some('Ω'), + 0x58 => Some('Ξ'), + 0x59 => Some('Ψ'), + 0x5A => Some('Ζ'), + + 0x5B => Some('['), + 0x5C => Some('∴'), + 0x5D => Some(']'), + 0x5E => Some('⊥'), + 0x5F => Some('_'), + + // Küçük Yunan Harfleri + 0x61 => Some('α'), + 0x62 => Some('β'), + 0x63 => Some('χ'), + 0x64 => Some('δ'), + 0x65 => Some('ε'), + 0x66 => Some('ϕ'), + 0x67 => Some('γ'), + 0x68 => Some('η'), + 0x69 => Some('ι'), + 0x6A => Some('φ'), + 0x6B => Some('κ'), + 0x6C => Some('λ'), + 0x6D => Some('μ'), + 0x6E => Some('ν'), + 0x6F => Some('ο'), + 0x70 => Some('π'), + 0x71 => Some('θ'), + 0x72 => Some('ρ'), + 0x73 => Some('σ'), + 0x74 => Some('τ'), + 0x75 => Some('υ'), + 0x76 => Some('ϖ'), + 0x77 => Some('ω'), + 0x78 => Some('ξ'), + 0x79 => Some('ψ'), + 0x7A => Some('ζ'), + 0x7B => Some('{'), + 0x7C => Some('|'), + 0x7D => Some('}'), + 0x7E => Some('∼'), + + // Genişletilmiş Matematiksel Semboller + 0xA3 => Some('≤'), + 0xB1 => Some('±'), + 0xB3 => Some('≥'), + 0xB4 => Some('×'), + 0xB8 => Some('÷'), + 0xB9 => Some('≠'), + 0xBA => Some('≡'), + 0xBB => Some('≈'), + 0xBC => Some('…'), + 0xC4 => Some('⊗'), + 0xC5 => Some('⊕'), + 0xC6 => Some('∅'), + 0xC7 => Some('∩'), + 0xC8 => Some('∪'), + 0xC9 => Some('⊃'), + 0xCA => Some('⊇'), + 0xCB => Some('⊄'), + 0xCC => Some('⊂'), + 0xCD => Some('⊆'), + 0xCE => Some('∈'), + 0xCF => Some('∉'), + 0xD0 => Some('∠'), + 0xD1 => Some('∇'), + 0xD2 => Some('®'), + 0xD3 => Some('©'), + 0xD4 => Some('™'), + 0xD5 => Some('∏'), + 0xD6 => Some('√'), + 0xD7 => Some('⋅'), + 0xD8 => Some('¬'), + 0xD9 => Some('∧'), + 0xDA => Some('∨'), + 0xDB => Some('⇔'), + 0xDC => Some('⇐'), + 0xDD => Some('⇑'), + 0xDE => Some('⇒'), + 0xDF => Some('⇓'), + 0xE0 => Some('⋄'), + 0xE1 => Some('⟨'), + 0xE5 => Some('∑'), + 0xF1 => Some('⟩'), + 0xF2 => Some('∫'), + _ => None, + } +} + +/// Adobe Glyph List (AGL) adından Unicode dizesine çözümler. +pub fn agl_glyph_name_to_unicode(name: &str) -> Option { + static AGL_MAP: OnceLock> = OnceLock::new(); + let map = AGL_MAP.get_or_init(|| { + let mut m = HashMap::with_capacity(512); + + // Türkçe Glif Adları + m.insert("dotlessi", "ı"); + m.insert("Idotaccent", "İ"); + m.insert("gbreve", "ğ"); + m.insert("Gbreve", "Ğ"); + m.insert("scedilla", "ş"); + m.insert("Scedilla", "Ş"); + m.insert("ccedilla", "ç"); + m.insert("Ccedilla", "Ç"); + m.insert("odieresis", "ö"); + m.insert("Odieresis", "Ö"); + m.insert("udieresis", "ü"); + m.insert("Udieresis", "Ü"); + + // Temel Matematik & Mantık Glifleri + m.insert("plus", "+"); + m.insert("minus", "−"); + m.insert("multiply", "×"); + m.insert("divide", "÷"); + m.insert("equal", "="); + m.insert("notequal", "≠"); + m.insert("lessequal", "≤"); + m.insert("greaterequal", "≥"); + m.insert("plusminus", "±"); + m.insert("minusplus", "∓"); + m.insert("approxequal", "≈"); + m.insert("equivalence", "≡"); + m.insert("proportional", "∝"); + m.insert("infinity", "∞"); + m.insert("radical", "√"); + m.insert("radicalex", ""); + m.insert("integral", "∫"); + m.insert("contourintegral", "∮"); + m.insert("summation", "∑"); + m.insert("product", "∏"); + m.insert("coproduct", "∐"); + m.insert("partialdiff", "∂"); + m.insert("gradient", "∇"); + m.insert("emptyset", "∅"); + m.insert("element", "∈"); + m.insert("notelement", "∉"); + m.insert("suchthat", "∋"); + m.insert("intersection", "∩"); + m.insert("union", "∪"); + m.insert("logicaland", "∧"); + m.insert("logicalor", "∨"); + m.insert("logicalnot", "¬"); + m.insert("universal", "∀"); + m.insert("existential", "∃"); + m.insert("arrowleft", "←"); + m.insert("arrowright", "→"); + m.insert("arrowup", "↑"); + m.insert("arrowdown", "↓"); + m.insert("arrowboth", "↔"); + m.insert("arrowdblleft", "⇐"); + m.insert("arrowdblright", "⇒"); + m.insert("arrowdblboth", "⇔"); + m.insert("angle", "∠"); + m.insert("perpendicular", "⊥"); + m.insert("parallel", "∥"); + m.insert("prime", "′"); + m.insert("second", "″"); + + // Yunan Glifleri (İsim bazlı) + m.insert("alpha", "α"); + m.insert("beta", "β"); + m.insert("gamma", "γ"); + m.insert("delta", "δ"); + m.insert("epsilon", "ε"); + m.insert("zeta", "ζ"); + m.insert("eta", "η"); + m.insert("theta", "θ"); + m.insert("iota", "ι"); + m.insert("kappa", "κ"); + m.insert("lambda", "λ"); + m.insert("mu", "μ"); + m.insert("nu", "ν"); + m.insert("xi", "ξ"); + m.insert("pi", "π"); + m.insert("rho", "ρ"); + m.insert("sigma", "σ"); + m.insert("tau", "τ"); + m.insert("upsilon", "υ"); + m.insert("phi", "φ"); + m.insert("chi", "χ"); + m.insert("psi", "ψ"); + m.insert("omega", "ω"); + + m.insert("Alpha", "Α"); + m.insert("Beta", "Β"); + m.insert("Gamma", "Γ"); + m.insert("Delta", "Δ"); + m.insert("Epsilon", "Ε"); + m.insert("Zeta", "Ζ"); + m.insert("Eta", "Η"); + m.insert("Theta", "Θ"); + m.insert("Iota", "Ι"); + m.insert("Kappa", "Κ"); + m.insert("Lambda", "Λ"); + m.insert("Mu", "Μ"); + m.insert("Nu", "Ν"); + m.insert("Xi", "Ξ"); + m.insert("Pi", "Π"); + m.insert("Rho", "Ρ"); + m.insert("Sigma", "Σ"); + m.insert("Tau", "Τ"); + m.insert("Upsilon", "Υ"); + m.insert("Phi", "Φ"); + m.insert("Chi", "Χ"); + m.insert("Psi", "Ψ"); + m.insert("Omega", "Ω"); + + // Ligatürler ve Tipografi + m.insert("ff", "ff"); + m.insert("fi", "fi"); + m.insert("fl", "fl"); + m.insert("ffi", "ffi"); + m.insert("ffl", "ffl"); + m.insert("endash", "–"); + m.insert("emdash", "—"); + m.insert("quoteleft", "‘"); + m.insert("quoteright", "’"); + m.insert("quotedblleft", "“"); + m.insert("quotedblright", "”"); + m.insert("bullet", "•"); + m.insert("ellipsis", "…"); + + m + }); + + if let Some(&s) = map.get(name) { + return Some(s.to_string()); + } + + // "uniXXXX" veya "uXXXX" standardı: + if let Some(stripped) = name.strip_prefix("uni") { + if stripped.len() == 4 { + if let Ok(cp) = u32::from_str_radix(stripped, 16) { + if let Some(ch) = char::from_u32(cp) { + return Some(ch.to_string()); + } + } + } + } else if let Some(stripped) = name.strip_prefix('u') { + if stripped.len() == 4 { + if let Ok(cp) = u32::from_str_radix(stripped, 16) { + if let Some(ch) = char::from_u32(cp) { + return Some(ch.to_string()); + } + } + } + } + + None +} diff --git a/src-tauri/src/services/pdf_text.rs b/src-tauri/src/services/pdf_text.rs new file mode 100644 index 0000000..69c78e2 --- /dev/null +++ b/src-tauri/src/services/pdf_text.rs @@ -0,0 +1,2843 @@ +//! Harici araç gerektirmeyen saf Rust PDF metin, CMap, encoding ve koordinatlı denklem çıkarıcısı. +//! +//! `ToUnicode` CMap (UTF-16BE vekil çiftleri dahil), `/Encoding` + `/Differences`, +//! font genişlikleri (`/Widths`, `/W`, `/DW`), CTM/metin matrisleri ve yatay kesir +//! çizgilerini (`re`, `m`/`l`) çözerek hem düz metin hem de LaTeX matematik içeren +//! yapılandırılmış Markdown üretir. + +use std::collections::HashMap; + +use lopdf::{Document, Object, ObjectId}; +use rayon::prelude::*; + +use crate::error::{AppError, AppResult}; + +/// Sayfaların düz metnini okuma sırasıyla çıkarır. +pub fn extract_pages(path: &str) -> AppResult> { + let doc = Document::load(path) + .map_err(|e| AppError::Pdf(format!("PDF yüklenemedi: {}", e)))?; + + let pages: Vec<(u32, ObjectId)> = doc.get_pages().into_iter().collect(); + let result = pages + .par_iter() + .map(|(_, page_id)| extract_page_text(&doc, *page_id).unwrap_or_default()) + .collect(); + Ok(result) +} + +/// PDF'ten çok sütunlu okuma sırası, başlıklar, Türkçe metin ve `$...$` / `$$...$$` +/// LaTeX denklemlerini koruyarak yapılandırılmış Markdown üretir. +pub fn extract_structured_markdown(path: &str) -> AppResult { + let doc = Document::load(path) + .map_err(|e| AppError::Pdf(format!("PDF yüklenemedi: {}", e)))?; + + let pages: Vec<(u32, ObjectId)> = doc.get_pages().into_iter().collect(); + if pages.is_empty() { + return Err(AppError::Pdf("PDF içinde sayfa bulunamadı.".into())); + } + + let page_layouts: Vec<_> = pages + .par_iter() + .map(|(_, page_id)| extract_page_layout(&doc, *page_id).unwrap_or_default()) + .collect(); + + let body_size = estimate_body_font_size(&page_layouts); + let mut sections: Vec = Vec::new(); + for layout in &page_layouts { + let md = build_page_markdown(layout, body_size); + if !md.trim().is_empty() { + sections.push(md); + } + } + + if sections.is_empty() { + let plain: Vec = pages + .par_iter() + .map(|(_, page_id)| extract_page_text(&doc, *page_id).unwrap_or_default()) + .collect(); + let plain_joined = plain.join("\n\n"); + if plain_joined.trim().is_empty() { + return Err(AppError::Pdf( + "PDF'ten çıkarılabilir metin/denklem bulunamadı (taranmış görüntü olabilir).".into(), + )); + } + return Ok(normalize(&plain_joined)); + } + + Ok(normalize(§ions.join("\n\n"))) +} + +// --------------------------------------------------------------------------- +// Font & Karakter Kod Çözücü +// --------------------------------------------------------------------------- + +#[derive(Clone, Default)] +struct FontDecoder { + map: HashMap, + two_byte: bool, + widths: HashMap, + default_width: f64, + is_italic: bool, + is_math_font: bool, + encoding_kind: BaseEncoding, +} + +#[derive(Clone, Copy, PartialEq, Eq, Default)] +enum BaseEncoding { + #[default] + WinAnsi, + MacRoman, + Standard, + Symbol, + Identity, +} + +impl FontDecoder { + fn decode_tokens(&self, bytes: &[u8]) -> Vec<(u32, String, f64)> { + let mut out = Vec::new(); + if self.two_byte { + for chunk in bytes.chunks(2) { + let code = if chunk.len() == 2 { + u32::from_be_bytes([0, 0, chunk[0], chunk[1]]) + } else { + chunk[0] as u32 + }; + let text = self.decode_code(code); + let width = self.width_for(code, &text); + out.push((code, text, width)); + } + } else { + for &b in bytes { + let code = b as u32; + let text = self.decode_code(code); + let width = self.width_for(code, &text); + out.push((code, text, width)); + } + } + out + } + + fn decode_code(&self, code: u32) -> String { + if let Some(value) = self.map.get(&code) { + if !value.is_empty() { + return value.clone(); + } + } + if code <= 255 { + let b = code as u8; + match self.encoding_kind { + BaseEncoding::Symbol => { + if let Some(sym) = decode_symbol_byte(b) { + return sym.to_string(); + } + } + BaseEncoding::MacRoman => { + if let Some(mac) = decode_macroman_byte(b) { + return mac.to_string(); + } + } + BaseEncoding::Standard => { + if let Some(std_ch) = decode_standard_byte(b) { + return std_ch.to_string(); + } + } + BaseEncoding::WinAnsi | BaseEncoding::Identity => { + if let Some(wa) = decode_winansi_byte(b) { + return wa.to_string(); + } + } + } + } + if let Some(c) = char::from_u32(code) { + if !c.is_control() || c == '\t' { + return c.to_string(); + } + } + String::new() + } + + fn width_for(&self, code: u32, decoded: &str) -> f64 { + if let Some(&w) = self.widths.get(&code) { + if w > 0.0 { + return w; + } + } + if self.default_width > 0.0 { + return self.default_width; + } + estimate_glyph_width(decoded) + } +} + +fn estimate_glyph_width(s: &str) -> f64 { + let ch = match s.chars().next() { + Some(c) => c, + None => return 500.0, + }; + match ch { + ' ' => 278.0, + 'i' | 'l' | 'ı' | 'I' | '.' | ',' | ':' | ';' | '!' | '|' | '\'' => 278.0, + 'f' | 'j' | 'r' | 't' | '(' | ')' | '[' | ']' | '{' | '}' => 333.0, + 'm' | 'w' | 'M' | 'W' | '∑' | '∏' | '∫' | '≈' | '≠' | '≤' | '≥' => 778.0, + c if c.is_ascii_uppercase() => 667.0, + _ => 520.0, + } +} + +fn resolve_dict<'a>(doc: &'a Document, object: &'a Object) -> Option<&'a lopdf::Dictionary> { + match object { + Object::Dictionary(d) => Some(d), + Object::Reference(id) => match doc.get_object(*id) { + Ok(Object::Dictionary(d)) => Some(d), + Ok(Object::Stream(s)) => Some(&s.dict), + _ => None, + }, + _ => None, + } +} + +fn resolve_object<'a>(doc: &'a Document, object: &'a Object) -> &'a Object { + let mut current = object; + let mut guard = 0; + while let Object::Reference(id) = current { + if guard > 16 { + break; + } + match doc.get_object(*id) { + Ok(next) => current = next, + Err(_) => break, + } + guard += 1; + } + current +} + +fn inherited_dict<'a>( + doc: &'a Document, + dict: &'a lopdf::Dictionary, + key: &[u8], +) -> Option<&'a lopdf::Dictionary> { + if let Ok(value) = dict.get(key) { + if let Some(found) = resolve_dict(doc, value) { + return Some(found); + } + } + let mut parent = dict.get(b"Parent").ok().and_then(|p| p.as_reference().ok()); + let mut guard = 0; + while let Some(parent_id) = parent { + if guard > 32 { + break; + } + match doc.get_object(parent_id) { + Ok(Object::Dictionary(parent_dict)) => { + if let Ok(value) = parent_dict.get(key) { + if let Some(found) = resolve_dict(doc, value) { + return Some(found); + } + } + parent = parent_dict + .get(b"Parent") + .ok() + .and_then(|p| p.as_reference().ok()); + } + _ => break, + } + guard += 1; + } + None +} + +fn inherited_box(doc: &Document, dict: &lopdf::Dictionary, key: &[u8]) -> Option<[f64; 4]> { + if let Ok(val) = dict.get(key) { + if let Some(b) = object_to_box(doc, val) { + return Some(b); + } + } + let mut parent = dict.get(b"Parent").ok().and_then(|p| p.as_reference().ok()); + let mut guard = 0; + while let Some(parent_id) = parent { + if guard > 32 { + break; + } + match doc.get_object(parent_id) { + Ok(Object::Dictionary(parent_dict)) => { + if let Ok(val) = parent_dict.get(key) { + if let Some(b) = object_to_box(doc, val) { + return Some(b); + } + } + parent = parent_dict + .get(b"Parent") + .ok() + .and_then(|p| p.as_reference().ok()); + } + _ => break, + } + guard += 1; + } + None +} + +fn object_to_box(doc: &Document, obj: &Object) -> Option<[f64; 4]> { + if let Object::Array(arr) = resolve_object(doc, obj) { + if arr.len() >= 4 { + let mut vals = [0.0; 4]; + for (i, item) in arr.iter().take(4).enumerate() { + vals[i] = object_to_f64(item).unwrap_or(0.0); + } + return Some(vals); + } + } + None +} + +fn object_to_f64(obj: &Object) -> Option { + match obj { + Object::Integer(v) => Some(*v as f64), + Object::Real(v) => Some(*v as f64), + _ => None, + } +} + +fn collect_stream(doc: &Document, id: ObjectId, buffer: &mut Vec) { + if let Ok(Object::Stream(stream)) = doc.get_object(id) { + match stream.decompressed_content() { + Ok(data) => buffer.extend_from_slice(&data), + Err(_) => buffer.extend_from_slice(&stream.content), + } + } +} + +fn collect_object_stream(doc: &Document, obj: &Object, buffer: &mut Vec) { + match obj { + Object::Reference(id) => collect_stream(doc, *id, buffer), + Object::Stream(stream) => match stream.decompressed_content() { + Ok(data) => buffer.extend_from_slice(&data), + Err(_) => buffer.extend_from_slice(&stream.content), + }, + _ => {} + } +} + +fn build_decoders( + doc: &Document, + resources: &lopdf::Dictionary, +) -> HashMap, FontDecoder> { + let mut decoders = HashMap::new(); + let fonts = match resources.get(b"Font").ok().and_then(|o| resolve_dict(doc, o)) { + Some(d) => d, + None => return decoders, + }; + + for (name, value) in fonts.iter() { + let font_dict = match resolve_dict(doc, value) { + Some(d) => d, + None => continue, + }; + decoders.insert(name.clone(), build_single_decoder(doc, font_dict)); + } + + decoders +} + +fn build_single_decoder(doc: &Document, font_dict: &lopdf::Dictionary) -> FontDecoder { + let subtype = font_dict + .get(b"Subtype") + .ok() + .and_then(|o| o.as_name().ok()) + .map(|n| String::from_utf8_lossy(n).to_string()) + .unwrap_or_default(); + + let base_font = font_dict + .get(b"BaseFont") + .ok() + .and_then(|o| o.as_name().ok()) + .map(|n| String::from_utf8_lossy(n).to_string()) + .unwrap_or_default(); + + let base_upper = base_font.to_uppercase(); + let is_math_font = base_upper.contains("SYMBOL") + || base_upper.contains("CMMI") + || base_upper.contains("CMSY") + || base_upper.contains("CMEX") + || base_upper.contains("MATH") + || base_upper.contains("STIX") + || base_upper.contains("CAMBRIA") && base_upper.contains("MATH") + || base_upper.contains("MSAM") + || base_upper.contains("MSBM"); + + let mut is_italic = base_upper.contains("ITALIC") + || base_upper.contains("OBLIQUE") + || base_upper.contains("CMMI"); + + if let Some(desc) = resolve_font_descriptor(doc, font_dict) { + if let Ok(flags) = desc.get(b"Flags").and_then(|o| o.as_i64()) { + if (flags & (1 << 6)) != 0 { + is_italic = true; + } + } + } + + let mut encoding_kind = if base_upper == "SYMBOL" || base_upper.ends_with("+SYMBOL") { + BaseEncoding::Symbol + } else if subtype == "Type0" { + BaseEncoding::Identity + } else { + BaseEncoding::WinAnsi + }; + + let mut map: HashMap = HashMap::new(); + + // 1. /Encoding sözlüğü veya adı + /Differences + if let Ok(enc_obj) = font_dict.get(b"Encoding") { + match resolve_object(doc, enc_obj) { + Object::Name(enc_name) => { + encoding_kind = encoding_from_name(enc_name, encoding_kind); + } + Object::Dictionary(enc_dict) => { + if let Ok(base_obj) = enc_dict.get(b"BaseEncoding") { + if let Ok(base_name) = base_obj.as_name() { + encoding_kind = encoding_from_name(base_name, encoding_kind); + } + } + if let Ok(diff_obj) = enc_dict.get(b"Differences") { + if let Object::Array(items) = resolve_object(doc, diff_obj) { + apply_encoding_differences(items, &mut map); + } + } + } + _ => {} + } + } + + // 2. ToUnicode CMap (öncelikli: önceki varsayılan eşleşmelerin üstüne yazar) + if let Ok(to_unicode) = font_dict.get(b"ToUnicode") { + let mut buffer = Vec::new(); + collect_object_stream(doc, to_unicode, &mut buffer); + if !buffer.is_empty() { + let cmap = String::from_utf8_lossy(&buffer); + for (code, uni) in parse_tounicode(&cmap) { + map.insert(code, uni); + } + } + } + + // 3. Genişlik tabloları (/Widths veya Type0 /DescendantFonts /W + /DW) + let mut widths = HashMap::new(); + let mut default_width = 0.0; + if subtype == "Type0" { + read_cid_widths(doc, font_dict, &mut widths, &mut default_width); + } else { + read_simple_widths(doc, font_dict, &mut widths); + } + + FontDecoder { + map, + two_byte: subtype == "Type0", + widths, + default_width, + is_italic, + is_math_font, + encoding_kind, + } +} + +fn resolve_font_descriptor<'a>( + doc: &'a Document, + font_dict: &'a lopdf::Dictionary, +) -> Option<&'a lopdf::Dictionary> { + if let Ok(fd) = font_dict.get(b"FontDescriptor") { + if let Some(d) = resolve_dict(doc, fd) { + return Some(d); + } + } + if let Ok(desc_arr) = font_dict.get(b"DescendantFonts") { + if let Object::Array(arr) = resolve_object(doc, desc_arr) { + if let Some(first) = arr.first().and_then(|o| resolve_dict(doc, o)) { + if let Ok(fd) = first.get(b"FontDescriptor") { + return resolve_dict(doc, fd); + } + } + } + } + None +} + +fn encoding_from_name(name: &[u8], fallback: BaseEncoding) -> BaseEncoding { + match name { + b"WinAnsiEncoding" => BaseEncoding::WinAnsi, + b"MacRomanEncoding" => BaseEncoding::MacRoman, + b"StandardEncoding" => BaseEncoding::Standard, + b"SymbolEncoding" => BaseEncoding::Symbol, + b"Identity-H" | b"Identity-V" => BaseEncoding::Identity, + _ => fallback, + } +} + +fn apply_encoding_differences(items: &[Object], map: &mut HashMap) { + let mut current_code: u32 = 0; + for item in items { + match item { + Object::Integer(n) => { + if *n >= 0 { + current_code = *n as u32; + } + } + Object::Name(glyph_bytes) => { + let glyph = String::from_utf8_lossy(glyph_bytes); + if let Some(uni) = glyph_name_to_unicode(&glyph) { + map.insert(current_code, uni); + } + current_code = current_code.saturating_add(1); + } + _ => {} + } + } +} + +fn read_simple_widths( + doc: &Document, + font_dict: &lopdf::Dictionary, + widths: &mut HashMap, +) { + let first_char = font_dict + .get(b"FirstChar") + .ok() + .and_then(|o| o.as_i64().ok()) + .unwrap_or(0) + .max(0) as u32; + let Ok(w_obj) = font_dict.get(b"Widths") else { + return; + }; + if let Object::Array(arr) = resolve_object(doc, w_obj) { + for (idx, item) in arr.iter().enumerate() { + if let Some(w) = object_to_f64(resolve_object(doc, item)) { + widths.insert(first_char + idx as u32, w); + } + } + } +} + +fn read_cid_widths( + doc: &Document, + font_dict: &lopdf::Dictionary, + widths: &mut HashMap, + default_width: &mut f64, +) { + let Ok(desc_arr) = font_dict.get(b"DescendantFonts") else { + return; + }; + let Object::Array(arr) = resolve_object(doc, desc_arr) else { + return; + }; + let Some(cid_font) = arr.first().and_then(|o| resolve_dict(doc, o)) else { + return; + }; + if let Ok(dw_obj) = cid_font.get(b"DW") { + if let Some(dw) = object_to_f64(resolve_object(doc, dw_obj)) { + *default_width = dw; + } + } + let Ok(w_obj) = cid_font.get(b"W") else { + return; + }; + let Object::Array(w_arr) = resolve_object(doc, w_obj) else { + return; + }; + + let mut i = 0; + while i < w_arr.len() { + let Some(first_cid) = resolve_object(doc, &w_arr[i]).as_i64().ok() else { + i += 1; + continue; + }; + if i + 1 >= w_arr.len() { + break; + } + match resolve_object(doc, &w_arr[i + 1]) { + Object::Array(sub_arr) => { + for (offset, entry) in sub_arr.iter().enumerate() { + if let Some(w) = object_to_f64(resolve_object(doc, entry)) { + widths.insert((first_cid as u32).saturating_add(offset as u32), w); + } + } + i += 2; + } + next => { + if let (Some(last_cid), Some(w)) = ( + next.as_i64().ok(), + w_arr + .get(i + 2) + .and_then(|o| object_to_f64(resolve_object(doc, o))), + ) { + let lo = first_cid.max(0) as u32; + let hi = (last_cid.max(first_cid) as u32).min(lo.saturating_add(4096)); + for cid in lo..=hi { + widths.insert(cid, w); + } + i += 3; + } else { + i += 1; + } + } + } + } +} + +fn hex_value(token: &str) -> Option { + let cleaned: String = token + .trim() + .trim_start_matches('<') + .trim_end_matches('>') + .chars() + .filter(|c| c.is_ascii_hexdigit()) + .collect(); + if cleaned.is_empty() { + return None; + } + u32::from_str_radix(&cleaned, 16).ok() +} + +/// PDF CMap `<...>` hedef dizgesini UTF-16BE vekil çiftlerini (surrogate pairs) koruyarak çözer. +fn hex_to_string(token: &str) -> String { + let cleaned: String = token + .trim() + .trim_start_matches('<') + .trim_end_matches('>') + .chars() + .filter(|c| c.is_ascii_hexdigit()) + .collect(); + if cleaned.is_empty() { + return String::new(); + } + let bytes: Vec = cleaned + .as_bytes() + .chunks(2) + .filter_map(|pair| { + if pair.len() == 2 { + std::str::from_utf8(pair) + .ok() + .and_then(|s| u8::from_str_radix(s, 16).ok()) + } else { + std::str::from_utf8(pair) + .ok() + .and_then(|s| u8::from_str_radix(&format!("{}0", s), 16).ok()) + } + }) + .collect(); + + if bytes.len() == 1 { + return (bytes[0] as char).to_string(); + } + + let units: Vec = bytes + .chunks(2) + .map(|chunk| { + if chunk.len() == 2 { + u16::from_be_bytes([chunk[0], chunk[1]]) + } else { + chunk[0] as u16 + } + }) + .collect(); + + String::from_utf16_lossy(&units) +} + +#[derive(Debug, Clone)] +enum CMapToken { + Hex(String), + Array(Vec), +} + +fn tokenize_cmap_section(body: &str) -> Vec { + let mut tokens = Vec::new(); + let bytes = body.as_bytes(); + let mut i = 0; + + while i < bytes.len() { + match bytes[i] { + b'<' => { + i += 1; + let start = i; + while i < bytes.len() && bytes[i] != b'>' { + i += 1; + } + tokens.push(CMapToken::Hex(body[start..i].to_string())); + if i < bytes.len() { + i += 1; + } + } + b'[' => { + i += 1; + let mut inner = Vec::new(); + while i < bytes.len() && bytes[i] != b']' { + if bytes[i] == b'<' { + i += 1; + let start = i; + while i < bytes.len() && bytes[i] != b'>' { + i += 1; + } + inner.push(body[start..i].to_string()); + if i < bytes.len() { + i += 1; + } + } else { + i += 1; + } + } + tokens.push(CMapToken::Array(inner)); + if i < bytes.len() { + i += 1; + } + } + _ => i += 1, + } + } + tokens +} + +fn parse_tounicode(cmap: &str) -> HashMap { + let mut map = HashMap::new(); + + for block in cmap.split("beginbfchar").skip(1) { + let body = block.split("endbfchar").next().unwrap_or(""); + let tokens = tokenize_cmap_section(body); + let mut i = 0; + while i + 1 < tokens.len() { + if let (CMapToken::Hex(src), CMapToken::Hex(dst)) = (&tokens[i], &tokens[i + 1]) { + if let Some(code) = hex_value(src) { + map.insert(code, hex_to_string(dst)); + } + i += 2; + } else { + i += 1; + } + } + } + + for block in cmap.split("beginbfrange").skip(1) { + let body = block.split("endbfrange").next().unwrap_or(""); + let tokens = tokenize_cmap_section(body); + let mut i = 0; + while i + 2 < tokens.len() { + let (low, high) = match (&tokens[i], &tokens[i + 1]) { + (CMapToken::Hex(l), CMapToken::Hex(h)) => match (hex_value(l), hex_value(h)) { + (Some(lo), Some(hi)) => (lo, hi), + _ => { + i += 1; + continue; + } + }, + _ => { + i += 1; + continue; + } + }; + + match &tokens[i + 2] { + CMapToken::Array(items) => { + for (offset, dst) in items.iter().enumerate() { + let code = low.saturating_add(offset as u32); + if code <= high { + map.insert(code, hex_to_string(dst)); + } + } + i += 3; + } + CMapToken::Hex(start_hex) => { + let base = hex_to_string(start_hex); + let mut chars: Vec = base.chars().collect(); + if chars.is_empty() { + chars.push(' '); + } + let last_index = chars.len() - 1; + let last_value = chars[last_index] as u32; + for code in low..=high.min(low.saturating_add(65535)) { + let offset = code - low; + let mut value = chars.clone(); + if let Some(c) = char::from_u32(last_value + offset) { + value[last_index] = c; + } + map.insert(code, value.into_iter().collect()); + } + i += 3; + } + } + } + } + + map +} + +fn decode_winansi_byte(b: u8) -> Option { + if (0x20..=0x7E).contains(&b) || b >= 0xA0 { + return Some(b as char); + } + match b { + 0x80 => Some('€'), + 0x82 => Some('‚'), + 0x83 => Some('ƒ'), + 0x84 => Some('„'), + 0x85 => Some('…'), + 0x86 => Some('†'), + 0x87 => Some('‡'), + 0x88 => Some('ˆ'), + 0x89 => Some('‰'), + 0x8A => Some('Š'), + 0x8B => Some('‹'), + 0x8C => Some('Œ'), + 0x8E => Some('Ž'), + 0x91 => Some('‘'), + 0x92 => Some('’'), + 0x93 => Some('“'), + 0x94 => Some('”'), + 0x95 => Some('•'), + 0x96 => Some('–'), + 0x97 => Some('—'), + 0x98 => Some('˜'), + 0x99 => Some('™'), + 0x9A => Some('š'), + 0x9B => Some('›'), + 0x9C => Some('œ'), + 0x9E => Some('ž'), + 0x9F => Some('Ÿ'), + _ => None, + } +} + +fn decode_macroman_byte(b: u8) -> Option { + if (0x20..=0x7E).contains(&b) { + return Some(b as char); + } + match b { + 0x80 => Some('Ä'), + 0x81 => Some('Å'), + 0x82 => Some('Ç'), + 0x83 => Some('É'), + 0x84 => Some('Ñ'), + 0x85 => Some('Ö'), + 0x86 => Some('Ü'), + 0x87 => Some('á'), + 0x88 => Some('à'), + 0x89 => Some('â'), + 0x8A => Some('ä'), + 0x8B => Some('ã'), + 0x8C => Some('å'), + 0x8D => Some('ç'), + 0x8E => Some('é'), + 0x8F => Some('è'), + 0x90 => Some('ê'), + 0x91 => Some('ë'), + 0x92 => Some('í'), + 0x93 => Some('ì'), + 0x94 => Some('î'), + 0x95 => Some('ï'), + 0x96 => Some('ñ'), + 0x97 => Some('ó'), + 0x98 => Some('ò'), + 0x99 => Some('ô'), + 0x9A => Some('ö'), + 0x9B => Some('õ'), + 0x9C => Some('ú'), + 0x9D => Some('ù'), + 0x9E => Some('û'), + 0x9F => Some('ü'), + 0xA5 => Some('•'), + 0xD0 => Some('–'), + 0xD1 => Some('—'), + 0xD2 => Some('“'), + 0xD3 => Some('”'), + 0xD4 => Some('‘'), + 0xD5 => Some('’'), + _ => None, + } +} + +fn decode_standard_byte(b: u8) -> Option { + if (0x20..=0x7E).contains(&b) { + return Some(b as char); + } + match b { + 0xB1 => Some('–'), + 0xD0 => Some('—'), + _ => decode_winansi_byte(b), + } +} + +fn decode_symbol_byte(b: u8) -> Option { + match b { + 0x20 => Some(' '), + 0x22 => Some('∀'), + 0x24 => Some('∃'), + 0x27 => Some('∋'), + 0x2A => Some('∗'), + 0x2D => Some('−'), + 0x3D => Some('='), + 0x40 => Some('≅'), + 0x41 => Some('Α'), + 0x42 => Some('Β'), + 0x43 => Some('Χ'), + 0x44 => Some('Δ'), + 0x45 => Some('Ε'), + 0x46 => Some('Φ'), + 0x47 => Some('Γ'), + 0x48 => Some('Η'), + 0x49 => Some('Ι'), + 0x4B => Some('Κ'), + 0x4C => Some('Λ'), + 0x4D => Some('Μ'), + 0x4E => Some('Ν'), + 0x4F => Some('Ο'), + 0x50 => Some('Π'), + 0x51 => Some('Θ'), + 0x52 => Some('Ρ'), + 0x53 => Some('Σ'), + 0x54 => Some('Τ'), + 0x55 => Some('Υ'), + 0x57 => Some('Ω'), + 0x58 => Some('Ξ'), + 0x59 => Some('Ψ'), + 0x5A => Some('Ζ'), + 0x5C => Some('∴'), + 0x5E => Some('⊥'), + 0x61 => Some('α'), + 0x62 => Some('β'), + 0x63 => Some('χ'), + 0x64 => Some('δ'), + 0x65 => Some('ε'), + 0x66 => Some('φ'), + 0x67 => Some('γ'), + 0x68 => Some('η'), + 0x69 => Some('ι'), + 0x6A => Some('ϕ'), + 0x6B => Some('κ'), + 0x6C => Some('λ'), + 0x6D => Some('μ'), + 0x6E => Some('ν'), + 0x6F => Some('ο'), + 0x70 => Some('π'), + 0x71 => Some('θ'), + 0x72 => Some('ρ'), + 0x73 => Some('σ'), + 0x74 => Some('τ'), + 0x75 => Some('υ'), + 0x76 => Some('ϖ'), + 0x77 => Some('ω'), + 0x78 => Some('ξ'), + 0x79 => Some('ψ'), + 0x7A => Some('ζ'), + 0x7E => Some('∼'), + 0xA3 => Some('≤'), + 0xA5 => Some('∞'), + 0xAB => Some('↔'), + 0xAC => Some('←'), + 0xAD => Some('↑'), + 0xAE => Some('→'), + 0xAF => Some('↓'), + 0xB0 => Some('°'), + 0xB1 => Some('±'), + 0xB2 => Some('″'), + 0xB3 => Some('≥'), + 0xB4 => Some('×'), + 0xB5 => Some('∝'), + 0xB6 => Some('∂'), + 0xB7 => Some('•'), + 0xB8 => Some('÷'), + 0xB9 => Some('≠'), + 0xBA => Some('≡'), + 0xBB => Some('≈'), + 0xBC => Some('…'), + 0xC0 => Some('ℵ'), + 0xC1 => Some('ℑ'), + 0xC2 => Some('ℜ'), + 0xC4 => Some('⊗'), + 0xC5 => Some('⊕'), + 0xC6 => Some('∅'), + 0xC7 => Some('∩'), + 0xC8 => Some('∪'), + 0xC9 => Some('⊃'), + 0xCA => Some('⊇'), + 0xCB => Some('⊄'), + 0xCC => Some('⊂'), + 0xCD => Some('⊆'), + 0xCE => Some('∈'), + 0xCF => Some('∉'), + 0xD0 => Some('∠'), + 0xD1 => Some('∇'), + 0xD5 => Some('∏'), + 0xD6 => Some('√'), + 0xD7 => Some('⋅'), + 0xD8 => Some('¬'), + 0xD9 => Some('∧'), + 0xDA => Some('∨'), + 0xDB => Some('⇔'), + 0xDC => Some('⇐'), + 0xDE => Some('⇒'), + 0xE1 => Some('⟨'), + 0xE5 => Some('∑'), + 0xF1 => Some('⟩'), + 0xF2 => Some('∫'), + _ if (0x21..=0x7E).contains(&b) => Some(b as char), + _ => None, + } +} + +fn glyph_name_to_unicode(name: &str) -> Option { + if let Some(hex) = name.strip_prefix("uni") { + if hex.len() >= 4 && hex.len() % 4 == 0 && hex.chars().all(|c| c.is_ascii_hexdigit()) { + let mut out = String::new(); + for chunk in hex.as_bytes().chunks(4) { + if let Ok(s) = std::str::from_utf8(chunk) { + if let Ok(cp) = u32::from_str_radix(s, 16) { + if let Some(c) = char::from_u32(cp) { + out.push(c); + } + } + } + } + if !out.is_empty() { + return Some(out); + } + } + } + if let Some(hex) = name.strip_prefix('u') { + if (4..=6).contains(&hex.len()) && hex.chars().all(|c| c.is_ascii_hexdigit()) { + if let Ok(cp) = u32::from_str_radix(hex, 16) { + if let Some(c) = char::from_u32(cp) { + return Some(c.to_string()); + } + } + } + } + + let s = match name { + // Türkçe & Latin + "gbreve" => "ğ", + "Gbreve" => "Ğ", + "Idotaccent" => "İ", + "dotlessi" => "ı", + "scedilla" => "ş", + "Scedilla" => "Ş", + "ccedilla" => "ç", + "Ccedilla" => "Ç", + "odiaeresis" => "ö", + "Odiaeresis" => "Ö", + "udiaeresis" => "ü", + "Udiaeresis" => "Ü", + "adiaeresis" => "ä", + "Adiaeresis" => "Ä", + "acircumflex" => "â", + "Acircumflex" => "Â", + "icircumflex" => "î", + "Icircumflex" => "Î", + "ucircumflex" => "û", + "Ucircumflex" => "Û", + "eacute" => "é", + "Eacute" => "É", + "germandbls" => "ß", + "fi" => "fi", + "fl" => "fl", + "ff" => "ff", + "ffi" => "ffi", + "ffl" => "ffl", + // Temel ASCII + "space" | "nbspace" => " ", + "exclam" => "!", + "quotedbl" => "\"", + "numbersign" => "#", + "dollar" => "$", + "percent" => "%", + "ampersand" => "&", + "quotesingle" => "'", + "parenleft" => "(", + "parenright" => ")", + "asterisk" => "*", + "plus" => "+", + "comma" => ",", + "hyphen" => "-", + "period" => ".", + "slash" => "/", + "zero" => "0", + "one" => "1", + "two" => "2", + "three" => "3", + "four" => "4", + "five" => "5", + "six" => "6", + "seven" => "7", + "eight" => "8", + "nine" => "9", + "colon" => ":", + "semicolon" => ";", + "less" => "<", + "equal" => "=", + "greater" => ">", + "question" => "?", + "at" => "@", + "bracketleft" => "[", + "backslash" => "\\", + "bracketright" => "]", + "asciicircum" => "^", + "underscore" => "_", + "grave" => "`", + "braceleft" => "{", + "bar" => "|", + "braceright" => "}", + "asciitilde" => "~", + // Noktalama & tipografi + "endash" => "–", + "emdash" => "—", + "quoteleft" => "‘", + "quoteright" => "’", + "quotedblleft" => "“", + "quotedblright" => "”", + "bullet" => "•", + "ellipsis" => "…", + "trademark" => "™", + "Euro" => "€", + "degree" => "°", + "periodcentered" => "·", + "dagger" => "†", + "daggerdbl" => "‡", + "section" => "§", + "paragraph" => "¶", + // Aksanlar (birleştirici) + "dotaccent" => "\u{0307}", + "dieresis" => "\u{0308}", + "circumflex" => "\u{0302}", + "tilde" => "\u{0303}", + "macron" => "\u{0304}", + "breve" => "\u{0306}", + "caron" => "\u{030C}", + "ring" => "\u{030A}", + // Matematik & Yunan harfleri + "minus" => "−", + "plusminus" => "±", + "multiply" => "×", + "divide" => "÷", + "dotmath" => "⋅", + "integral" => "∫", + "summation" => "∑", + "product" => "∏", + "radical" => "√", + "partialdiff" => "∂", + "infinity" => "∞", + "approxequal" => "≈", + "notequal" => "≠", + "lessequal" => "≤", + "greaterequal" => "≥", + "equivalence" => "≡", + "congruent" => "≅", + "similar" => "∼", + "proportional" => "∝", + "element" => "∈", + "notelement" => "∉", + "intersection" => "∩", + "union" => "∪", + "emptyset" => "∅", + "nabla" => "∇", + "arrowleft" => "←", + "arrowright" => "→", + "arrowboth" => "↔", + "arrowdblright" => "⇒", + "arrowdblboth" => "⇔", + "universal" => "∀", + "existential" => "∃", + "logicaland" => "∧", + "logicalor" => "∨", + "logicalnot" => "¬", + "perpendicular" => "⊥", + "angle" => "∠", + "prime" => "′", + "second" => "″", + "alpha" => "α", + "beta" => "β", + "gamma" => "γ", + "delta" => "δ", + "epsilon" | "epsilon1" => "ε", + "zeta" => "ζ", + "eta" => "η", + "theta" => "θ", + "iota" => "ι", + "kappa" => "κ", + "lambda" => "λ", + "mu" => "μ", + "nu" => "ν", + "xi" => "ξ", + "omicron" => "ο", + "pi" => "π", + "rho" => "ρ", + "sigma" => "σ", + "sigma1" => "ς", + "tau" => "τ", + "upsilon" => "υ", + "phi" | "phi1" => "φ", + "chi" => "χ", + "psi" => "ψ", + "omega" => "ω", + "Gamma" => "Γ", + "Delta" => "Δ", + "Theta" => "Θ", + "Lambda" => "Λ", + "Xi" => "Ξ", + "Pi" => "Π", + "Sigma" => "Σ", + "Upsilon" => "Υ", + "Phi" => "Φ", + "Psi" => "Ψ", + "Omega" => "Ω", + other if other.len() == 1 => other, + _ => return None, + }; + Some(s.to_string()) +} + +// --------------------------------------------------------------------------- +// İçerik Akışı Tarama & Koordinatlı Çıkarım +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +struct PdfChar { + ch: String, + x0: f64, + y0: f64, + x1: f64, + y1: f64, + size: f64, + is_italic: bool, + is_math_font: bool, + is_preformatted_latex: bool, +} + +impl PdfChar { + fn y_center(&self) -> f64 { + (self.y0 + self.y1) * 0.5 + } +} + +#[derive(Debug, Clone)] +struct HBar { + x0: f64, + x1: f64, + y0: f64, + y1: f64, +} + +impl HBar { + fn y_center(&self) -> f64 { + (self.y0 + self.y1) * 0.5 + } + fn width(&self) -> f64 { + self.x1 - self.x0 + } +} + +#[derive(Default)] +struct PageLayout { + width: f64, + chars: Vec, + hbars: Vec, +} + +enum Token { + Number(f64), + String(Vec), + Name(Vec), + ArrayStart, + ArrayEnd, +} + +#[derive(Clone)] +struct GraphicsState { + ctm: [f64; 6], + font_size: f64, + char_space: f64, + word_space: f64, + horiz_scale: f64, + leading: f64, + rise: f64, + line_width: f64, + decoder: FontDecoder, +} + +impl Default for GraphicsState { + fn default() -> Self { + Self { + ctm: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], + font_size: 12.0, + char_space: 0.0, + word_space: 0.0, + horiz_scale: 100.0, + leading: 0.0, + rise: 0.0, + line_width: 1.0, + decoder: FontDecoder::default(), + } + } +} + +struct ContentWalker<'a> { + doc: &'a Document, + resources: Option<&'a lopdf::Dictionary>, + decoders: HashMap, FontDecoder>, + box_x0: f64, + box_y1: f64, + state: GraphicsState, + state_stack: Vec, + tm: [f64; 6], + tlm: [f64; 6], + path_pts: Vec<(f64, f64)>, + path_rects: Vec<[f64; 4]>, + chars: Vec, + hbars: Vec, + form_depth: usize, +} + +fn mul_matrix(m1: [f64; 6], m2: [f64; 6]) -> [f64; 6] { + [ + m2[0] * m1[0] + m2[2] * m1[1], + m2[1] * m1[0] + m2[3] * m1[1], + m2[0] * m1[2] + m2[2] * m1[3], + m2[1] * m1[2] + m2[3] * m1[3], + m2[0] * m1[4] + m2[2] * m1[5] + m2[4], + m2[1] * m1[4] + m2[3] * m1[5] + m2[5], + ] +} + +fn transform_point(m: [f64; 6], x: f64, y: f64) -> (f64, f64) { + (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]) +} + +impl<'a> ContentWalker<'a> { + fn new( + doc: &'a Document, + resources: Option<&'a lopdf::Dictionary>, + page_box: [f64; 4], + ) -> Self { + let decoders = resources + .map(|r| build_decoders(doc, r)) + .unwrap_or_default(); + Self { + doc, + resources, + decoders, + box_x0: page_box[0], + box_y1: page_box[3].max(page_box[1]), + state: GraphicsState::default(), + state_stack: Vec::new(), + tm: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], + tlm: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], + path_pts: Vec::new(), + path_rects: Vec::new(), + chars: Vec::new(), + hbars: Vec::new(), + form_depth: 0, + } + } + + fn walk(&mut self, content: &[u8]) { + let mut operands: Vec = Vec::new(); + let mut index = 0; + + while index < content.len() { + let byte = content[index]; + match byte { + b'%' => { + while index < content.len() && content[index] != b'\n' { + index += 1; + } + } + b'(' => { + let (s, next) = read_literal_string(content, index); + operands.push(Token::String(s)); + index = next; + } + b'<' => { + if content.get(index + 1) == Some(&b'<') { + index += 2; + let mut depth = 1usize; + while index + 1 < content.len() && depth > 0 { + if content[index] == b'<' && content[index + 1] == b'<' { + depth += 1; + index += 2; + } else if content[index] == b'>' && content[index + 1] == b'>' { + depth -= 1; + index += 2; + } else { + index += 1; + } + } + continue; + } + let (hex, next) = read_hex_string(content, index); + operands.push(Token::String(hex)); + index = next; + } + b'[' => { + operands.push(Token::ArrayStart); + index += 1; + } + b']' => { + operands.push(Token::ArrayEnd); + index += 1; + } + b'/' => { + let start = index + 1; + let mut cursor = start; + while cursor < content.len() && !is_delimiter(content[cursor]) { + cursor += 1; + } + operands.push(Token::Name(content[start..cursor].to_vec())); + index = cursor; + } + b'B' if content.get(index + 1) == Some(&b'I') => { + index += 2; + while index + 1 < content.len() + && !(content[index] == b'E' && content[index + 1] == b'I') + { + index += 1; + } + index = (index + 2).min(content.len()); + operands.clear(); + } + _ if byte.is_ascii_whitespace() => index += 1, + _ if byte.is_ascii_digit() || byte == b'-' || byte == b'+' || byte == b'.' => { + let start = index; + let mut cursor = index; + while cursor < content.len() + && (content[cursor].is_ascii_digit() + || matches!(content[cursor], b'-' | b'+' | b'.' | b'e' | b'E')) + { + cursor += 1; + } + let number = String::from_utf8_lossy(&content[start..cursor]) + .parse::() + .unwrap_or(0.0); + operands.push(Token::Number(number)); + index = cursor; + } + _ if byte.is_ascii_alphabetic() + || byte == b'*' + || byte == b'\'' + || byte == b'"' => + { + let start = index; + let mut cursor = index; + while cursor < content.len() + && (content[cursor].is_ascii_alphabetic() + || content[cursor] == b'*' + || content[cursor] == b'\'' + || content[cursor] == b'"') + { + cursor += 1; + } + let op = String::from_utf8_lossy(&content[start..cursor]).to_string(); + self.apply_op(&op, &operands); + operands.clear(); + index = cursor; + } + _ => index += 1, + } + } + } + + fn apply_op(&mut self, op: &str, operands: &[Token]) { + let nums = |min_len: usize| -> Option> { + let v: Vec = operands + .iter() + .filter_map(|t| match t { + Token::Number(n) => Some(*n), + _ => None, + }) + .collect(); + if v.len() >= min_len { + Some(v) + } else { + None + } + }; + + match op { + "q" => { + if self.state_stack.len() < 64 { + self.state_stack.push(self.state.clone()); + } + } + "Q" => { + if let Some(prev) = self.state_stack.pop() { + self.state = prev; + } + } + "cm" => { + if let Some(n) = nums(6) { + let m = [n[0], n[1], n[2], n[3], n[4], n[5]]; + self.state.ctm = mul_matrix(m, self.state.ctm); + } + } + "w" => { + if let Some(n) = nums(1) { + self.state.line_width = n[n.len() - 1].abs().max(0.2); + } + } + "m" | "l" => { + if let Some(n) = nums(2) { + let l = n.len(); + self.path_pts.push((n[l - 2], n[l - 1])); + } + } + "re" => { + if let Some(n) = nums(4) { + let l = n.len(); + self.path_rects.push([n[l - 4], n[l - 3], n[l - 2], n[l - 1]]); + } + } + "S" | "s" | "f" | "F" | "f*" | "B" | "B*" | "b" | "b*" => { + self.commit_hbars(); + } + "n" | "W" | "W*" => { + self.path_pts.clear(); + self.path_rects.clear(); + } + "BT" => { + self.tm = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + self.tlm = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + } + "ET" => {} + "Tf" => { + if let Some(Token::Name(name)) = + operands.iter().find(|t| matches!(t, Token::Name(_))) + { + if let Some(dec) = self.decoders.get(name) { + self.state.decoder = dec.clone(); + } else { + self.state.decoder = FontDecoder::default(); + } + } + if let Some(n) = nums(1) { + self.state.font_size = n[n.len() - 1].abs().max(0.5); + } + } + "Tc" => { + if let Some(n) = nums(1) { + self.state.char_space = n[n.len() - 1]; + } + } + "Tw" => { + if let Some(n) = nums(1) { + self.state.word_space = n[n.len() - 1]; + } + } + "Tz" => { + if let Some(n) = nums(1) { + self.state.horiz_scale = n[n.len() - 1].max(1.0); + } + } + "TL" => { + if let Some(n) = nums(1) { + self.state.leading = n[n.len() - 1]; + } + } + "Ts" => { + if let Some(n) = nums(1) { + self.state.rise = n[n.len() - 1]; + } + } + "Td" => { + if let Some(n) = nums(2) { + let l = n.len(); + self.tlm = mul_matrix([1.0, 0.0, 0.0, 1.0, n[l - 2], n[l - 1]], self.tlm); + self.tm = self.tlm; + } + } + "TD" => { + if let Some(n) = nums(2) { + let l = n.len(); + self.state.leading = -n[l - 1]; + self.tlm = mul_matrix([1.0, 0.0, 0.0, 1.0, n[l - 2], n[l - 1]], self.tlm); + self.tm = self.tlm; + } + } + "Tm" => { + if let Some(n) = nums(6) { + let l = n.len(); + self.tm = [ + n[l - 6], + n[l - 5], + n[l - 4], + n[l - 3], + n[l - 2], + n[l - 1], + ]; + self.tlm = self.tm; + } + } + "T*" => { + self.tlm = mul_matrix([1.0, 0.0, 0.0, 1.0, 0.0, -self.state.leading], self.tlm); + self.tm = self.tlm; + } + "Tj" => { + if let Some(Token::String(bytes)) = + operands.iter().find(|t| matches!(t, Token::String(_))) + { + self.emit_text_bytes(bytes); + } + } + "TJ" => { + let th = self.state.horiz_scale / 100.0; + for token in operands { + match token { + Token::String(bytes) => self.emit_text_bytes(bytes), + Token::Number(adj) => { + let tx = (-adj / 1000.0) * self.state.font_size * th; + self.tm = mul_matrix([1.0, 0.0, 0.0, 1.0, tx, 0.0], self.tm); + } + _ => {} + } + } + } + "'" => { + self.tlm = mul_matrix([1.0, 0.0, 0.0, 1.0, 0.0, -self.state.leading], self.tlm); + self.tm = self.tlm; + if let Some(Token::String(bytes)) = + operands.iter().find(|t| matches!(t, Token::String(_))) + { + self.emit_text_bytes(bytes); + } + } + "\"" => { + if let Some(n) = nums(2) { + self.state.word_space = n[0]; + self.state.char_space = n[1]; + } + self.tlm = mul_matrix([1.0, 0.0, 0.0, 1.0, 0.0, -self.state.leading], self.tlm); + self.tm = self.tlm; + if let Some(Token::String(bytes)) = + operands.iter().find(|t| matches!(t, Token::String(_))) + { + self.emit_text_bytes(bytes); + } + } + "Do" if self.form_depth < 4 => { + if let Some(Token::Name(name)) = + operands.iter().find(|t| matches!(t, Token::Name(_))) + { + self.invoke_xobject(name); + } + } + _ => {} + } + } + + fn commit_hbars(&mut self) { + let ctm = self.state.ctm; + for [rx, ry, rw, rh] in self.path_rects.drain(..) { + let (p0x, p0y) = transform_point(ctm, rx, ry); + let (p1x, p1y) = transform_point(ctm, rx + rw, ry + rh); + let x0 = p0x.min(p1x) - self.box_x0; + let x1 = p0x.max(p1x) - self.box_x0; + let y0 = (self.box_y1 - p0y).min(self.box_y1 - p1y); + let y1 = (self.box_y1 - p0y).max(self.box_y1 - p1y); + if (x1 - x0) >= 4.0 && (y1 - y0) <= 4.0 { + self.hbars.push(HBar { x0, x1, y0, y1 }); + } + } + if self.path_pts.len() >= 2 { + let lw = self.state.line_width * (ctm[1].hypot(ctm[3])).max(1.0); + if lw <= 4.0 { + for pair in self.path_pts.windows(2) { + let (p0x, p0y) = transform_point(ctm, pair[0].0, pair[0].1); + let (p1x, p1y) = transform_point(ctm, pair[1].0, pair[1].1); + let dy = (p0y - p1y).abs(); + let dx = (p1x - p0x).abs(); + if dy <= 1.2 && dx >= 4.0 { + let y_mid = self.box_y1 - (p0y + p1y) * 0.5; + let half = (lw * 0.5).max(0.4); + self.hbars.push(HBar { + x0: p0x.min(p1x) - self.box_x0, + x1: p0x.max(p1x) - self.box_x0, + y0: y_mid - half, + y1: y_mid + half, + }); + } + } + } + } + self.path_pts.clear(); + } + + fn emit_text_bytes(&mut self, bytes: &[u8]) { + let th = self.state.horiz_scale / 100.0; + let tfs = self.state.font_size; + let trise = self.state.rise; + let tokens = self.state.decoder.decode_tokens(bytes); + + for (code, ch_str, width_thousandths) in tokens { + let tx_glyph = (width_thousandths / 1000.0) * tfs * th; + let tc = self.state.char_space * th; + let tw = if !self.state.decoder.two_byte && code == 32 { + self.state.word_space * th + } else { + 0.0 + }; + + let text_space_m = [tfs * th, 0.0, 0.0, tfs, 0.0, trise]; + let trm = mul_matrix(text_space_m, mul_matrix(self.tm, self.state.ctm)); + let (px0, py0) = (trm[4], trm[5]); + let eff_size = trm[1].hypot(trm[3]).max(trm[0].hypot(trm[2])).max(1.0); + let adv_page_x = (tx_glyph / tfs.max(0.5)) * (trm[0].hypot(trm[2])); + let x0 = px0 - self.box_x0; + let x1 = x0 + adv_page_x.max(0.5); + let baseline_y = self.box_y1 - py0; + let y0 = baseline_y - eff_size * 0.80; + let y1 = baseline_y + eff_size * 0.20; + + if !ch_str.is_empty() { + self.chars.push(PdfChar { + ch: ch_str, + x0, + y0, + x1, + y1, + size: eff_size, + is_italic: self.state.decoder.is_italic, + is_math_font: self.state.decoder.is_math_font, + is_preformatted_latex: false, + }); + } + + let step_x = tx_glyph + tc + tw; + self.tm = mul_matrix([1.0, 0.0, 0.0, 1.0, step_x, 0.0], self.tm); + } + } + + fn invoke_xobject(&mut self, name: &[u8]) { + let Some(res) = self.resources else { + return; + }; + let Some(xobjs) = res.get(b"XObject").ok().and_then(|o| resolve_dict(self.doc, o)) else { + return; + }; + let Ok(xobj_ref) = xobjs.get(name) else { + return; + }; + let obj = resolve_object(self.doc, xobj_ref); + let Object::Stream(stream) = obj else { + return; + }; + let is_form = stream + .dict + .get(b"Subtype") + .ok() + .and_then(|o| o.as_name().ok()) + == Some(b"Form"); + if !is_form { + return; + } + let data = match stream.decompressed_content() { + Ok(d) => d, + Err(_) => stream.content.clone(), + }; + + let saved_state = self.state.clone(); + let saved_decoders = self.decoders.clone(); + if let Some(form_res) = stream + .dict + .get(b"Resources") + .ok() + .and_then(|o| resolve_dict(self.doc, o)) + { + for (k, v) in build_decoders(self.doc, form_res) { + self.decoders.insert(k, v); + } + } + if let Ok(mat_obj) = stream.dict.get(b"Matrix") { + if let Object::Array(arr) = resolve_object(self.doc, mat_obj) { + if arr.len() >= 6 { + let mut m = [0.0; 6]; + for (i, item) in arr.iter().take(6).enumerate() { + m[i] = object_to_f64(item).unwrap_or(if i == 0 || i == 3 { 1.0 } else { 0.0 }); + } + self.state.ctm = mul_matrix(m, self.state.ctm); + } + } + } + self.form_depth += 1; + self.walk(&data); + self.form_depth -= 1; + self.decoders = saved_decoders; + self.state = saved_state; + } +} + +fn extract_page_layout(doc: &Document, page_id: ObjectId) -> Result { + let dict = match doc.get_object(page_id) { + Ok(Object::Dictionary(d)) => d, + _ => return Ok(PageLayout::default()), + }; + + let page_box = inherited_box(doc, dict, b"CropBox") + .or_else(|| inherited_box(doc, dict, b"MediaBox")) + .unwrap_or([0.0, 0.0, 612.0, 792.0]); + + let resources = dict + .get(b"Resources") + .ok() + .and_then(|o| resolve_dict(doc, o)) + .or_else(|| inherited_dict(doc, dict, b"Resources")); + + let contents = match dict.get(b"Contents").ok() { + Some(Object::Reference(id)) => { + let mut buffer = Vec::new(); + collect_stream(doc, *id, &mut buffer); + buffer + } + Some(Object::Array(items)) => { + let mut buffer = Vec::new(); + for item in items { + if let Ok(id) = item.as_reference() { + collect_stream(doc, id, &mut buffer); + buffer.push(b'\n'); + } + } + buffer + } + _ => return Ok(PageLayout::default()), + }; + + let mut walker = ContentWalker::new(doc, resources, page_box); + walker.walk(&contents); + Ok(PageLayout { + width: (page_box[2] - page_box[0]).abs().max(200.0), + chars: walker.chars, + hbars: walker.hbars, + }) +} + +fn extract_page_text(doc: &Document, page_id: ObjectId) -> Result { + let layout = extract_page_layout(doc, page_id)?; + if layout.chars.is_empty() { + return Ok(String::new()); + } + let ordered = order_chars_multicolumn(&layout.chars, layout.width); + let rows = group_chars_into_rows(ordered); + let mut lines = Vec::new(); + for row in rows { + let line = row_to_plain_text(&row); + if !line.trim().is_empty() { + lines.push(line); + } + } + Ok(lines.join("\n")) +} + +// --------------------------------------------------------------------------- +// Çok Sütunlu Okuma Sırası, Kesir/Üs/Alt/Kök & LaTeX Yeniden Yapılandırması +// --------------------------------------------------------------------------- + +fn order_chars_multicolumn(chars: &[PdfChar], page_width: f64) -> Vec { + if chars.is_empty() { + return Vec::new(); + } + // Orta sütun boşluğu olup olmadığını kontrol et (klasik iki sütunlu akademik PDF). + let mid = page_width * 0.5; + let gutter_lo = mid - 10.0; + let gutter_hi = mid + 10.0; + + let mut left_count = 0usize; + let mut right_count = 0usize; + let mut span_count = 0usize; + for ch in chars { + if ch.ch.trim().is_empty() { + continue; + } + if ch.x1 <= gutter_lo { + left_count += 1; + } else if ch.x0 >= gutter_hi { + right_count += 1; + } else { + span_count += 1; + } + } + + let is_two_col = left_count >= 40 + && right_count >= 40 + && span_count * 12 < (left_count + right_count); + + if !is_two_col { + return chars.to_vec(); + } + + // Tam genişlikli başlık/bölüm satırlarını (ör. sayfa başı başlık/özet) Y sırasıyla koru. + let mut split_rows = group_chars_into_rows(chars.to_vec()); + let mut min_col_y = f64::MAX; + for r in &split_rows { + let left_present = r.iter().any(|c| c.x1 <= gutter_lo); + let right_present = r.iter().any(|c| c.x0 >= gutter_hi); + let crosses = r.iter().any(|c| c.x0 < gutter_lo && c.x1 > gutter_hi); + if left_present && right_present && !crosses { + let y = r.iter().map(|c| c.y_center()).sum::() / r.len() as f64; + if y < min_col_y { + min_col_y = y; + } + } + } + + let mut top_chars = Vec::new(); + let mut left_chars = Vec::new(); + let mut right_chars = Vec::new(); + for ch in split_rows.drain(..).flatten() { + if ch.y_center() < min_col_y - 2.0 { + top_chars.push(ch); + } else if (ch.x0 + ch.x1) * 0.5 < mid { + left_chars.push(ch); + } else { + right_chars.push(ch); + } + } + + top_chars.extend(left_chars); + top_chars.extend(right_chars); + top_chars +} + +fn group_chars_into_rows(mut chars: Vec) -> Vec> { + if chars.is_empty() { + return Vec::new(); + } + chars.sort_by(|a, b| { + a.y_center() + .total_cmp(&b.y_center()) + .then_with(|| a.x0.total_cmp(&b.x0)) + }); + + let mut rows: Vec> = Vec::new(); + for ch in chars { + if let Some(last_row) = rows.last_mut() { + let row_y = last_row.iter().map(|c| c.y_center()).sum::() / last_row.len() as f64; + let row_sz = last_row.iter().map(|c| c.size).sum::() / last_row.len() as f64; + let tol = (row_sz.max(ch.size) * 0.45).max(3.0); + if (ch.y_center() - row_y).abs() <= tol { + last_row.push(ch); + continue; + } + } + rows.push(vec![ch]); + } + + for row in &mut rows { + row.sort_by(|a, b| a.x0.total_cmp(&b.x0)); + } + rows +} + +fn row_to_plain_text(row: &[PdfChar]) -> String { + let mut out = String::new(); + let mut prev_x1: Option = None; + for ch in row { + if let Some(px1) = prev_x1 { + let gap = ch.x0 - px1; + if gap > (ch.size * 0.24).max(1.8) && !out.ends_with(' ') && !ch.ch.starts_with(' ') { + out.push(' '); + } + } + out.push_str(&ch.ch); + prev_x1 = Some(ch.x1); + } + out +} + +fn estimate_body_font_size(layouts: &[PageLayout]) -> f64 { + let mut buckets: HashMap = HashMap::new(); + for l in layouts { + for c in &l.chars { + if !c.ch.trim().is_empty() { + let key = (c.size * 2.0).round() as i64; + *buckets.entry(key).or_insert(0) += 1; + } + } + } + buckets + .into_iter() + .max_by_key(|&(_, count)| count) + .map(|(k, _)| (k as f64) / 2.0) + .unwrap_or(11.0) + .max(6.0) +} + +fn build_page_markdown(layout: &PageLayout, body_size: f64) -> String { + if layout.chars.is_empty() { + return String::new(); + } + + let mut chars = layout.chars.clone(); + merge_combining_accents(&mut chars); + resolve_fractions_and_bars(&mut chars, &layout.hbars); + + let ordered = order_chars_multicolumn(&chars, layout.width); + let rows = group_chars_into_rows(ordered); + + let mut blocks: Vec<(bool, String)> = Vec::new(); + for row in rows { + let non_space: Vec<&PdfChar> = row.iter().filter(|c| !c.ch.trim().is_empty()).collect(); + if non_space.is_empty() { + continue; + } + + let avg_size = non_space.iter().map(|c| c.size).sum::() / non_space.len() as f64; + let has_pre_latex = non_space.iter().any(|c| c.is_preformatted_latex); + let plain = row_to_plain_text(&row); + let trimmed = plain.trim(); + + // Başlık tespiti + if !has_pre_latex + && avg_size >= body_size * 1.18 + && trimmed.len() <= 140 + && !is_math_heavy_text(&non_space, trimmed) + { + let level = if avg_size >= body_size * 1.45 { "##" } else { "###" }; + blocks.push((false, format!("{} {}", level, trimmed))); + continue; + } + + // Görüntülenen (display) veya satır içi matematik vs düz metin sınıflandırması + if is_display_math_row(&non_space, trimmed) { + let latex = chars_to_latex(&row); + if !latex.trim().is_empty() { + blocks.push((false, format!("$$\n{}\n$$", latex.trim()))); + continue; + } + } + + let prose_with_inline = reconstruct_prose_row_with_inline_math(&row); + blocks.push((true, prose_with_inline)); + } + + // Ardışık normal metin satırlarını mantıklı paragraflar halinde birleştir + let mut out: Vec = Vec::new(); + for (is_prose, text) in blocks { + if !is_prose { + out.push(text); + continue; + } + let is_bullet = text.starts_with("• ") + || text.starts_with("- ") + || text.starts_with("* "); + if is_bullet { + out.push(text); + continue; + } + if let Some(prev) = out.last_mut() { + let prev_is_block = prev.starts_with('#') + || prev.starts_with("$$") + || prev.ends_with("$$"); + let prev_ends_sentence = prev.ends_with('.') + || prev.ends_with('?') + || prev.ends_with('!') + || prev.ends_with(':'); + if !prev_is_block && !prev_ends_sentence && prev.len() < 420 { + if prev.ends_with('-') && !prev.ends_with(" -") { + prev.pop(); + prev.push_str(text.trim()); + } else { + prev.push(' '); + prev.push_str(text.trim()); + } + continue; + } + } + out.push(text); + } + + out.join("\n\n") +} + +/// Tek bir karakterin hemen üzerinde duran aksanları (`˙`, `¨`, `^`, `~`, `¯`, `→`) +/// önceden `\dot{x}` / `\ddot{x}` vb. LaTeX düğümüne birleştirir. +fn merge_combining_accents(chars: &mut Vec) { + let mut consumed = vec![false; chars.len()]; + let mut additions: Vec = Vec::new(); + + for i in 0..chars.len() { + if consumed[i] || chars[i].is_preformatted_latex { + continue; + } + let Some(cmd) = accent_glyph_to_latex(&chars[i].ch) else { + continue; + }; + let acc = &chars[i]; + let acc_cx = (acc.x0 + acc.x1) * 0.5; + let mut best_idx: Option = None; + let mut best_dist = f64::MAX; + + for (j, base) in chars.iter().enumerate() { + if i == j || consumed[j] || base.ch.trim().is_empty() { + continue; + } + if accent_glyph_to_latex(&base.ch).is_some() { + continue; + } + let base_cx = (base.x0 + base.x1) * 0.5; + let dx = (acc_cx - base_cx).abs(); + let dy = base.y0 - acc.y1; + if dx <= base.size * 0.55 && (-base.size * 0.5..=base.size * 0.65).contains(&dy) { + let dist = dx + dy.abs(); + if dist < best_dist { + best_dist = dist; + best_idx = Some(j); + } + } + } + + if let Some(target_idx) = best_idx { + consumed[i] = true; + consumed[target_idx] = true; + let base = &chars[target_idx]; + let inner = normalize_math_char(&base.ch); + additions.push(PdfChar { + ch: format!("{}{{{}}}", cmd, inner), + x0: base.x0.min(acc.x0), + y0: base.y0.min(acc.y0), + x1: base.x1.max(acc.x1), + y1: base.y1.max(acc.y1), + size: base.size, + is_italic: base.is_italic, + is_math_font: true, + is_preformatted_latex: true, + }); + } + } + + if additions.is_empty() { + return; + } + + let mut kept = Vec::with_capacity(chars.len()); + for (idx, c) in chars.drain(..).enumerate() { + if !consumed[idx] { + kept.push(c); + } + } + kept.extend(additions); + *chars = kept; +} + +fn accent_glyph_to_latex(s: &str) -> Option<&'static str> { + match s.trim() { + "˙" | "\u{0307}" | "⋅" => None, // `⋅` çarpım olabilir; yalnızca gerçek aksanları yakala + _ => match s.trim() { + "\u{02D9}" | "\u{0307}" => Some("\\dot"), + "¨" | "\u{0308}" => Some("\\ddot"), + "\u{02C6}" | "\u{0302}" => Some("\\hat"), + "\u{02DC}" | "\u{0303}" => Some("\\tilde"), + "¯" | "\u{0304}" => Some("\\bar"), + _ => None, + }, + } +} + +/// Yatay çizgileri (`HBar`) küçükten büyüğe işleyerek kesirleri (`\frac{num}{den}`), +/// karekökleri (`\sqrt{...}`) ve üst çizgileri (`\overline{...}`) özyinelemeli üretir. +fn resolve_fractions_and_bars(chars: &mut Vec, hbars: &[HBar]) { + if hbars.is_empty() || chars.is_empty() { + return; + } + + let mut sorted_bars = hbars.to_vec(); + sorted_bars.sort_by(|a, b| a.width().total_cmp(&b.width())); + + for bar in sorted_bars { + let bx0 = bar.x0 - 3.5; + let bx1 = bar.x1 + 3.5; + let bar_y = bar.y_center(); + let search_span = (bar.width() * 0.9).clamp(24.0, 70.0); + + let mut num_indices = Vec::new(); + let mut den_indices = Vec::new(); + let mut num_chars = Vec::new(); + let mut den_chars = Vec::new(); + + for (idx, c) in chars.iter().enumerate() { + if c.ch.trim().is_empty() { + continue; + } + let cx = (c.x0 + c.x1) * 0.5; + if cx < bx0 || cx > bx1 { + continue; + } + let cy = c.y_center(); + if cy < bar_y && (bar_y - cy) <= search_span { + num_indices.push(idx); + num_chars.push(c.clone()); + } else if cy > bar_y && (cy - bar_y) <= search_span { + den_indices.push(idx); + den_chars.push(c.clone()); + } + } + + // Durum 1: Gerçek kesir (üstte pay + altta payda var) + if !num_chars.is_empty() && !den_chars.is_empty() { + let num_tex = chars_to_latex(&num_chars); + let den_tex = chars_to_latex(&den_chars); + if !num_tex.trim().is_empty() && !den_tex.trim().is_empty() { + let mut remove_set: Vec = num_indices; + remove_set.extend(den_indices); + let replaced = combine_bounds_as_latex( + chars, + &remove_set, + &bar, + format!("\\frac{{{}}}{{{}}}", num_tex.trim(), den_tex.trim()), + ); + chars.push(replaced); + continue; + } + } + + // Durum 2: Yalnızca çizginin altında karakter var -> solunda `√` varsa `\sqrt{...}`, yoksa `\overline{...}` + if num_chars.is_empty() && !den_chars.is_empty() { + let max_dy = den_chars + .iter() + .map(|c| c.y0 - bar.y1) + .fold(0.0_f64, f64::max); + let avg_sz = + den_chars.iter().map(|c| c.size).sum::() / den_chars.len().max(1) as f64; + if max_dy <= avg_sz * 1.15 { + let rad_idx = chars.iter().enumerate().find_map(|(idx, c)| { + if c.ch.trim() == "√" + && c.x1 <= bar.x0 + 8.0 + && (bar.x0 - c.x1).abs() <= avg_sz * 1.5 + && c.y0 <= bar.y1 + avg_sz * 0.5 + && c.y1 >= bar.y1 + { + Some(idx) + } else { + None + } + }); + + let inner = chars_to_latex(&den_chars); + if let Some(ri) = rad_idx { + let mut remove_set = den_indices; + remove_set.push(ri); + let replaced = combine_bounds_as_latex( + chars, + &remove_set, + &bar, + format!("\\sqrt{{{}}}", inner.trim()), + ); + chars.push(replaced); + } else if den_chars.len() <= 8 { + let replaced = combine_bounds_as_latex( + chars, + &den_indices, + &bar, + if den_chars.len() == 1 { + format!("\\bar{{{}}}", inner.trim()) + } else { + format!("\\overline{{{}}}", inner.trim()) + }, + ); + chars.push(replaced); + } + } + } + } +} + +fn combine_bounds_as_latex( + chars: &mut Vec, + remove_indices: &[usize], + bar: &HBar, + latex: String, +) -> PdfChar { + let mut x0 = bar.x0; + let mut x1 = bar.x1; + let mut y0 = bar.y0; + let mut y1 = bar.y1; + let mut max_size = 10.0_f64; + + let mut sorted = remove_indices.to_vec(); + sorted.sort_unstable(); + sorted.dedup(); + for &idx in sorted.iter().rev() { + let c = chars.remove(idx); + x0 = x0.min(c.x0); + x1 = x1.max(c.x1); + y0 = y0.min(c.y0); + y1 = y1.max(c.y1); + max_size = max_size.max(c.size); + } + + PdfChar { + ch: latex, + x0, + y0, + x1, + y1, + size: max_size, + is_italic: false, + is_math_font: true, + is_preformatted_latex: true, + } +} + +/// Karakter kümesini (satır veya kesir pay/paydası) üs `^{...}` / alt `_{...}` ve +/// matematik sembol haritasıyla LaTeX'e dönüştürür. +fn chars_to_latex(input: &[PdfChar]) -> String { + let mut chars: Vec = input + .iter() + .filter(|c| !c.ch.is_empty() && !matches!(c.ch.trim(), "⏟" | "⏞" | "︸" | "︷")) + .cloned() + .collect(); + if chars.is_empty() { + return String::new(); + } + chars.sort_by(|a, b| a.x0.total_cmp(&b.x0)); + + // Referans normal boyut & baseline Y hesapla + let mut sizes: Vec = chars + .iter() + .filter(|c| !c.is_preformatted_latex && !c.ch.trim().is_empty()) + .map(|c| c.size) + .collect(); + if sizes.is_empty() { + sizes = chars.iter().map(|c| c.size).collect(); + } + sizes.sort_by(|a, b| a.total_cmp(b)); + let base_size = sizes[sizes.len() * 3 / 4].max(5.0); + + let mut base_ys: Vec = chars + .iter() + .filter(|c| !c.ch.trim().is_empty() && c.size >= base_size * 0.85) + .map(|c| c.y_center()) + .collect(); + if base_ys.is_empty() { + base_ys = chars.iter().map(|c| c.y_center()).collect(); + } + base_ys.sort_by(|a, b| a.total_cmp(b)); + let base_y = base_ys[base_ys.len() / 2]; + + #[derive(Clone, Copy, PartialEq, Eq)] + enum ScriptKind { + Normal, + Super, + Sub, + } + + let raw_classify = |c: &PdfChar| -> ScriptKind { + if c.is_preformatted_latex || c.ch.trim().is_empty() { + return ScriptKind::Normal; + } + let dy = c.y_center() - base_y; + let is_small = c.size < base_size * 0.84; + if (is_small && dy < -base_size * 0.12) || dy < -base_size * 0.28 { + ScriptKind::Super + } else if (is_small && dy > base_size * 0.12) || dy > base_size * 0.28 { + ScriptKind::Sub + } else { + ScriptKind::Normal + } + }; + + let mut kinds: Vec = chars.iter().map(raw_classify).collect(); + // İki aynı tür script arasındaki küçük bağlaçları (`+`, `-`, `,`, `/`) ve boşlukları script ile birleştir. + for idx in 1..kinds.len().saturating_sub(1) { + if kinds[idx] == ScriptKind::Normal + && (chars[idx].ch.trim().is_empty() + || (chars[idx].size < base_size * 0.88 + && matches!(chars[idx].ch.trim(), "+" | "-" | "−" | "," | "/"))) + { + let prev = kinds[idx - 1]; + let next_non_ws = (idx + 1..kinds.len()) + .find(|&k| !chars[k].ch.trim().is_empty()) + .map(|k| kinds[k]) + .unwrap_or(ScriptKind::Normal); + if prev != ScriptKind::Normal && prev == next_non_ws { + kinds[idx] = prev; + } + } + } + + let mut out = String::new(); + let mut i = 0; + while i < chars.len() { + let kind = kinds[i]; + if kind == ScriptKind::Normal { + if chars[i].ch.trim() == "√" && i + 1 < chars.len() && !chars[i + 1].is_preformatted_latex { + // Bare `√x` (yatay çizgisiz karekök) + let next_tex = normalize_math_char(&chars[i + 1].ch); + out.push_str(&format!("\\sqrt{{{}}}", next_tex.trim())); + i += 2; + continue; + } + if chars[i].is_preformatted_latex { + push_latex_token(&mut out, &chars[i].ch); + } else { + let tok = normalize_math_char(&chars[i].ch); + if tok == " " { + if !out.ends_with(' ') && !out.is_empty() { + out.push(' '); + } + } else { + push_latex_token(&mut out, &tok); + } + } + i += 1; + } else { + let mut sub_run = Vec::new(); + let mut sup_run = Vec::new(); + while i < chars.len() && kinds[i] != ScriptKind::Normal { + if !chars[i].ch.trim().is_empty() { + match kinds[i] { + ScriptKind::Sub => sub_run.push(chars[i].clone()), + ScriptKind::Super => sup_run.push(chars[i].clone()), + ScriptKind::Normal => break, + } + } + i += 1; + } + if !sub_run.is_empty() { + let sub_str = chars_to_plain_math(&sub_run); + out.push_str(&format!("_{{{}}}", sub_str.trim())); + } + if !sup_run.is_empty() { + let sup_str = chars_to_plain_math(&sup_run); + out.push_str(&format!("^{{{}}}", sup_str.trim())); + } + } + } + + collapse_known_functions(out.trim()) +} + +fn chars_to_plain_math(chars: &[PdfChar]) -> String { + let mut out = String::new(); + for c in chars { + if c.is_preformatted_latex { + push_latex_token(&mut out, &c.ch); + } else { + let tok = normalize_math_char(&c.ch); + push_latex_token(&mut out, &tok); + } + } + out +} + +fn push_latex_token(out: &mut String, tok: &str) { + if tok.starts_with('\\') && out.ends_with(|c: char| c.is_ascii_alphanumeric()) { + out.push(' '); + } + let needs_space_after_cmd = out + .rsplit_once('\\') + .map(|(_, tail)| !tail.is_empty() && tail.chars().all(|c| c.is_ascii_alphabetic())) + .unwrap_or(false); + if needs_space_after_cmd && tok.starts_with(|c: char| c.is_ascii_alphanumeric()) { + out.push(' '); + } + out.push_str(tok); +} + +fn normalize_math_char(s: &str) -> String { + let mut out = String::new(); + for ch in s.chars() { + if let Some(mapped) = unicode_math_to_latex(ch) { + push_latex_token(&mut out, mapped); + } else if let Some(ascii) = unicode_math_alpha_to_ascii(ch) { + out.push(ascii); + } else { + out.push(ch); + } + } + out +} + +fn unicode_math_to_latex(ch: char) -> Option<&'static str> { + let s = match ch { + '−' => "-", + '×' => "\\times", + '÷' => "\\div", + '±' => "\\pm", + '∓' => "\\mp", + '⋅' | '·' => "\\cdot", + '∗' => "*", + '≤' => "\\le", + '≥' => "\\ge", + '≠' => "\\ne", + '≈' => "\\approx", + '≡' => "\\equiv", + '≅' => "\\cong", + '∼' => "\\sim", + '∝' => "\\propto", + '∞' => "\\infty", + '∂' => "\\partial", + '∇' => "\\nabla", + '∑' => "\\sum", + '∏' => "\\prod", + '∫' => "\\int", + '∬' => "\\iint", + '∮' => "\\oint", + '∈' => "\\in", + '∉' => "\\notin", + '⊂' => "\\subset", + '⊆' => "\\subseteq", + '⊃' => "\\supset", + '⊇' => "\\supseteq", + '∩' => "\\cap", + '∪' => "\\cup", + '∅' => "\\emptyset", + '∀' => "\\forall", + '∃' => "\\exists", + '∧' => "\\land", + '∨' => "\\lor", + '¬' => "\\neg", + '←' => "\\leftarrow", + '→' => "\\to", + '↔' => "\\leftrightarrow", + '⇒' => "\\Rightarrow", + '⇐' => "\\Leftarrow", + '⇔' => "\\Leftrightarrow", + '⊥' => "\\perp", + '∠' => "\\angle", + '°' => "^\\circ", + 'α' => "\\alpha", + 'β' => "\\beta", + 'γ' => "\\gamma", + 'δ' => "\\delta", + 'ε' | 'ϵ' => "\\epsilon", + 'ζ' => "\\zeta", + 'η' => "\\eta", + 'θ' | 'ϑ' => "\\theta", + 'ι' => "\\iota", + 'κ' => "\\kappa", + 'λ' => "\\lambda", + 'μ' => "\\mu", + 'ν' => "\\nu", + 'ξ' => "\\xi", + 'π' | 'ϖ' => "\\pi", + 'ρ' | 'ϱ' => "\\rho", + 'σ' | 'ς' => "\\sigma", + 'τ' => "\\tau", + 'υ' => "\\upsilon", + 'φ' | 'ϕ' => "\\phi", + 'χ' => "\\chi", + 'ψ' => "\\psi", + 'ω' => "\\omega", + 'Γ' => "\\Gamma", + 'Δ' => "\\Delta", + 'Θ' => "\\Theta", + 'Λ' => "\\Lambda", + 'Ξ' => "\\Xi", + 'Π' => "\\Pi", + 'Σ' => "\\Sigma", + 'Υ' => "\\Upsilon", + 'Φ' => "\\Phi", + 'Ψ' => "\\Psi", + 'Ω' => "\\Omega", + '′' => "'", + '″' => "''", + _ => return None, + }; + Some(s) +} + +fn unicode_math_alpha_to_ascii(ch: char) -> Option { + let cp = ch as u32; + let map_range = |start: u32, count: u32, base: u8| -> Option { + if (start..start + count).contains(&cp) { + Some((base + (cp - start) as u8) as char) + } else { + None + } + }; + map_range(0x1D400, 26, b'A') + .or_else(|| map_range(0x1D41A, 26, b'a')) + .or_else(|| map_range(0x1D434, 26, b'A')) + .or_else(|| map_range(0x1D44E, 26, b'a')) + .or_else(|| map_range(0x1D468, 26, b'A')) + .or_else(|| map_range(0x1D482, 26, b'a')) + .or_else(|| map_range(0x1D7CE, 10, b'0')) + .or(if ch == 'ℎ' { Some('h') } else { None }) +} + +fn collapse_known_functions(s: &str) -> String { + let mut out = s.to_string(); + for func in [ + "sin", "cos", "tan", "cot", "sec", "csc", "arcsin", "arccos", "arctan", "sinh", "cosh", + "tanh", "log", "ln", "exp", "lim", "max", "min", "sup", "inf", "det", + ] { + let target = format!("\\{}", func); + if out.contains(func) && !out.contains(&target) { + out = out.replace(&format!("{} (", func), &format!("\\{}(", func)); + } + } + out +} + +fn is_math_symbol_str(s: &str) -> bool { + s.chars().any(|ch| { + unicode_math_to_latex(ch).is_some() + || unicode_math_alpha_to_ascii(ch).is_some() + || matches!(ch, '=' | '+' | '−' | '√' | '^' | '_') + }) +} + +fn is_math_heavy_text(non_space: &[&PdfChar], trimmed: &str) -> bool { + if non_space.iter().any(|c| c.is_preformatted_latex) { + return true; + } + let math_count = non_space + .iter() + .filter(|c| c.is_math_font || is_math_symbol_str(&c.ch)) + .count(); + math_count * 3 >= non_space.len().max(1) || trimmed.contains("\\frac") +} + +fn is_display_math_row(non_space: &[&PdfChar], trimmed: &str) -> bool { + if non_space.is_empty() { + return false; + } + let word_count = trimmed + .split_whitespace() + .filter(|w| w.chars().filter(|c| c.is_alphabetic()).count() >= 3) + .count(); + let has_pre_latex = non_space.iter().any(|c| c.is_preformatted_latex); + let math_chars = non_space + .iter() + .filter(|c| c.is_math_font || c.is_italic || is_math_symbol_str(&c.ch)) + .count(); + let has_eq_or_op = non_space + .iter() + .any(|c| matches!(c.ch.as_str(), "=" | "+" | "−" | "∑" | "∫" | "∏" | "√") || c.is_preformatted_latex); + + if has_pre_latex && word_count <= 2 { + return true; + } + has_eq_or_op && word_count <= 2 && math_chars * 2 >= non_space.len() +} + +fn reconstruct_prose_row_with_inline_math(row: &[PdfChar]) -> String { + let mut base_ys: Vec = row + .iter() + .filter(|c| !c.ch.trim().is_empty() && !c.is_preformatted_latex) + .map(|c| c.y_center()) + .collect(); + if base_ys.is_empty() { + return format!("${}$", chars_to_latex(row)); + } + base_ys.sort_by(|a, b| a.total_cmp(b)); + let row_y = base_ys[base_ys.len() / 2]; + + // 1) Karakterleri boşluk ve X-boşluğuna göre gerçek kelimelere böl (asla boşluk üstünden yapıştırma). + let mut words: Vec> = Vec::new(); + let mut prev_x1: Option = None; + for c in row { + if c.ch.trim().is_empty() { + prev_x1 = None; + continue; + } + let gap = prev_x1.map(|px1| c.x0 - px1).unwrap_or(0.0); + if words.is_empty() || gap > (c.size * 0.25).max(1.8) { + words.push(vec![c.clone()]); + } else if let Some(last) = words.last_mut() { + last.push(c.clone()); + } + prev_x1 = Some(c.x1); + } + + if words.is_empty() { + return String::new(); + } + + let is_word_math = |w: &[PdfChar]| -> bool { + let plain: String = w.iter().map(|c| c.ch.as_str()).collect(); + let trimmed = plain.trim(); + if trimmed.is_empty() || matches!(trimmed, "•" | "-" | "–" | "—") { + return false; + } + let has_turkish_word_char = trimmed.chars().any(|ch| { + matches!( + ch, + 'ğ' | 'Ğ' | 'ı' | 'İ' | 'ş' | 'Ş' | 'ç' | 'Ç' | 'ö' | 'Ö' | 'ü' | 'Ü' + ) + }); + let has_pre_latex = w.iter().any(|c| c.is_preformatted_latex); + let alpha_run_len = trimmed + .chars() + .filter(|ch| ch.is_alphabetic() && unicode_math_to_latex(*ch).is_none()) + .count(); + + if has_turkish_word_char || (!has_pre_latex && alpha_run_len >= 4 && !trimmed.contains('=')) { + return false; + } + + let has_script = w.iter().any(|c| { + !c.is_preformatted_latex + && c.ch.chars().any(|ch| ch.is_alphanumeric()) + && (c.y_center() - row_y).abs() > c.size * 0.22 + && c.size < w.iter().map(|x| x.size).fold(0.0_f64, f64::max).max(c.size) * 1.05 + }); + let has_sym = w + .iter() + .any(|c| c.is_math_font || is_math_symbol_str(&c.ch)); + let single_math_token = trimmed.len() <= 2 + && w.iter() + .all(|c| c.is_italic || is_math_symbol_str(&c.ch)); + + has_pre_latex || has_script || has_sym || single_math_token + }; + + // 2) Ardışık matematik kelimelerini birleştir, düzyazı kelimelerini saf UTF-8 bırak. + let mut grouped: Vec<(bool, Vec)> = Vec::new(); + for w in words { + let math_flag = is_word_math(&w); + if let Some((prev_math, buf)) = grouped.last_mut() { + if *prev_math == math_flag { + if let Some(last_c) = buf.last() { + // Boşluk karakteri simülasyonu (chars_to_latex'te aralık korumak için) + buf.push(PdfChar { + ch: " ".to_string(), + x0: last_c.x1, + y0: last_c.y0, + x1: w[0].x0, + y1: last_c.y1, + size: last_c.size, + is_italic: false, + is_math_font: false, + is_preformatted_latex: false, + }); + } + buf.extend(w); + continue; + } + } + grouped.push((math_flag, w)); + } + + let mut result = String::new(); + for (is_math, seg) in grouped { + let piece = if is_math { + let latex = chars_to_latex(&seg); + let trimmed = latex.trim(); + if trimmed.is_empty() { + String::new() + } else { + format!("${}$", trimmed) + } + } else { + row_to_plain_text(&seg) + }; + let p_trim = piece.trim(); + if !p_trim.is_empty() { + if !result.is_empty() + && !p_trim.starts_with(&[',', '.', ';', ':', ')', ']', '!'][..]) + { + result.push(' '); + } + result.push_str(p_trim); + } + } + + result +} + +fn is_delimiter(byte: u8) -> bool { + byte.is_ascii_whitespace() || matches!(byte, b'/' | b'[' | b']' | b'<' | b'>' | b'(' | b')') +} + +fn read_literal_string(content: &[u8], start: usize) -> (Vec, usize) { + let mut out = Vec::new(); + let mut index = start + 1; + let mut depth = 1; + while index < content.len() { + let byte = content[index]; + match byte { + b'\\' => { + index += 1; + if index >= content.len() { + break; + } + let escaped = content[index]; + let value = match escaped { + b'n' => b'\n', + b'r' => b'\r', + b't' => b'\t', + b'b' => 0x08, + b'f' => 0x0C, + b'(' => b'(', + b')' => b')', + b'\\' => b'\\', + b'0'..=b'7' => { + let mut digits = String::new(); + digits.push(escaped as char); + while digits.len() < 3 + && index + 1 < content.len() + && (b'0'..=b'7').contains(&content[index + 1]) + { + index += 1; + digits.push(content[index] as char); + } + u8::from_str_radix(&digits, 8).unwrap_or(b'?') + } + other => other, + }; + out.push(value); + } + b'(' => { + depth += 1; + out.push(byte); + } + b')' => { + depth -= 1; + if depth == 0 { + return (out, index + 1); + } + out.push(byte); + } + _ => out.push(byte), + } + index += 1; + } + (out, index) +} + +fn read_hex_string(content: &[u8], start: usize) -> (Vec, usize) { + let mut out = Vec::new(); + let mut index = start + 1; + let mut digits = String::new(); + while index < content.len() && content[index] != b'>' { + let byte = content[index]; + if byte.is_ascii_hexdigit() { + digits.push(byte as char); + if digits.len() == 2 { + if let Ok(value) = u8::from_str_radix(&digits, 16) { + out.push(value); + } + digits.clear(); + } + } + index += 1; + } + if digits.len() == 1 { + if let Ok(value) = u8::from_str_radix(&format!("{}0", digits), 16) { + out.push(value); + } + } + (out, (index + 1).min(content.len())) +} + +/// Yardımcı: metin içindeki boşlukları düzenler. +pub fn normalize(text: &str) -> String { + let mut lines: Vec = Vec::new(); + for line in text.lines() { + let trimmed = line.trim_end(); + if trimmed.trim().is_empty() { + if lines.last().map(|l: &String| l.is_empty()).unwrap_or(true) { + continue; + } + lines.push(String::new()); + } else { + lines.push(trimmed.to_string()); + } + } + lines.join("\n").trim().to_string() +} diff --git a/src-tauri/src/services/pdf_tools.rs b/src-tauri/src/services/pdf_tools.rs new file mode 100644 index 0000000..c41a376 --- /dev/null +++ b/src-tauri/src/services/pdf_tools.rs @@ -0,0 +1,170 @@ +use std::path::{Path, PathBuf}; + +use crate::error::{AppError, AppResult}; + +/// Yerleşik Windows (`Windows.Data.Pdf`) WinRT PDF sayfa rasterleştirme motoru. +pub struct PdfTools; + +impl PdfTools { + pub fn available() -> bool { + cfg!(windows) + } + + /// PDF sayfalarını belirtilen DPI ile görüntüye çevirir (`Windows.Data.Pdf` WinRT API). + pub fn render_pages( + pdf_path: &str, + page_range: Option<&str>, + out_dir: &Path, + dpi: u32, + format: &str, + ) -> AppResult> { + #[cfg(windows)] + { + let paths = Self::render_pages_winrt(pdf_path, page_range, out_dir, dpi, format)?; + if paths.is_empty() { + return Err(AppError::Pdf( + "PDF sayfası görseli üretilemedi.".to_string(), + )); + } + Ok(paths) + } + #[cfg(not(windows))] + { + let _ = (pdf_path, page_range, out_dir, dpi, format); + Err(AppError::Engine( + "WinRT PDF görüntüleme yalnızca Windows üzerinde desteklenir.".to_string(), + )) + } + } + + #[cfg(windows)] + fn render_pages_winrt( + pdf_path: &str, + page_range: Option<&str>, + out_dir: &Path, + dpi: u32, + format: &str, + ) -> AppResult> { + use windows::Data::Pdf::{PdfDocument, PdfPageRenderOptions}; + use windows::Storage::StorageFile; + use windows::Storage::Streams::{DataReader, InMemoryRandomAccessStream}; + use windows::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED}; + use windows_core::HSTRING; + + let _ = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }; + + let abs = std::fs::canonicalize(pdf_path)?; + let abs_str = abs.to_string_lossy(); + let clean_path = abs_str.strip_prefix(r"\\?\").unwrap_or(&abs_str); + let hpath = HSTRING::from(clean_path); + + let file = StorageFile::GetFileFromPathAsync(&hpath) + .and_then(|op| op.join()) + .map_err(|e| AppError::Pdf(format!("WinRT PDF dosyayı açamadı: {}", e)))?; + let pdf_doc = PdfDocument::LoadFromFileAsync(&file) + .and_then(|op| op.join()) + .map_err(|e| AppError::Pdf(format!("WinRT PDF yüklenemedi: {}", e)))?; + + let total_pages = pdf_doc + .PageCount() + .map_err(|e| AppError::Pdf(format!("WinRT sayfa sayısı alınamadı: {}", e)))? + as usize; + if total_pages == 0 { + return Err(AppError::Pdf("PDF belgesinde sayfa bulunamadı.".to_string())); + } + + std::fs::create_dir_all(out_dir)?; + let stem = Path::new(pdf_path) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("sayfa"); + let selected = + crate::services::pdf_engine::PdfEngine::parse_page_range(page_range, total_pages); + let scale = (dpi.max(72) as f64) / 96.0; + let fmt_lower = format.to_ascii_lowercase(); + let mut out_paths = Vec::with_capacity(selected.len()); + + for page_num in selected { + let page = pdf_doc + .GetPage((page_num as u32).saturating_sub(1)) + .map_err(|e| AppError::Pdf(format!("Sayfa {} açılamadı: {}", page_num, e)))?; + let size = page + .Size() + .map_err(|e| AppError::Pdf(format!("Sayfa {} boyutu okunamadı: {}", page_num, e)))?; + + let dest_w = ((size.Width as f64 * scale).round() as u32).clamp(1, 8192); + let dest_h = ((size.Height as f64 * scale).round() as u32).clamp(1, 8192); + + let opts = PdfPageRenderOptions::new() + .map_err(|e| AppError::Pdf(format!("WinRT render seçenekleri hatası: {}", e)))?; + let _ = opts.SetDestinationWidth(dest_w); + let _ = opts.SetDestinationHeight(dest_h); + + let stream = InMemoryRandomAccessStream::new() + .map_err(|e| AppError::Pdf(format!("WinRT bellek akışı hatası: {}", e)))?; + page.RenderWithOptionsToStreamAsync(&stream, &opts) + .and_then(|act| act.join()) + .map_err(|e| AppError::Pdf(format!("Sayfa {} rasterleştirilemedi: {}", page_num, e)))?; + + let stream_size = stream + .Size() + .map_err(|e| AppError::Pdf(format!("Akış boyutu alınamadı: {}", e)))?; + let byte_len = u32::try_from(stream_size) + .map_err(|_| AppError::Pdf("Sayfa görsel akışı çok büyük.".to_string()))?; + let _ = stream.Seek(0); + let input_stream = stream + .GetInputStreamAt(0) + .map_err(|e| AppError::Pdf(format!("Akış okuyucu açılamadı: {}", e)))?; + let reader = DataReader::CreateDataReader(&input_stream) + .map_err(|e| AppError::Pdf(format!("DataReader oluşturulamadı: {}", e)))?; + reader + .LoadAsync(byte_len) + .and_then(|op| op.join()) + .map_err(|e| AppError::Pdf(format!("Görsel verisi yüklenemedi: {}", e)))?; + + let mut png_bytes = vec![0u8; byte_len as usize]; + reader + .ReadBytes(&mut png_bytes) + .map_err(|e| AppError::Pdf(format!("Görsel baytları okunamadı: {}", e)))?; + + let _ = reader.Close(); + let _ = input_stream.Close(); + let _ = stream.Close(); + let _ = page.Close(); + + let target_path = out_dir.join(format!("{}_page_{:03}.{}", stem, page_num, fmt_lower)); + if fmt_lower == "png" { + std::fs::write(&target_path, &png_bytes)?; + out_paths.push(target_path); + } else { + let img = image::load_from_memory(&png_bytes).map_err(|e| { + AppError::Pdf(format!("WinRT PNG tamponu çözülemedi: {}", e)) + })?; + if fmt_lower == "jpg" || fmt_lower == "jpeg" { + let rgb = crate::services::image_engine::ImageEngine::flatten_on_white(&img); + rgb.save_with_format(&target_path, image::ImageFormat::Jpeg)?; + } else if fmt_lower == "jxl" { + let tmp_png = out_dir.join(format!(".tmp_winrt_{}.png", page_num)); + std::fs::write(&tmp_png, &png_bytes)?; + let converted = crate::services::image_engine::ImageEngine::convert_single( + &tmp_png.to_string_lossy(), + "jxl", + out_dir, + &crate::models::ConversionOptions::default(), + )?; + let _ = std::fs::remove_file(&tmp_png); + if converted != target_path { + let _ = std::fs::rename(&converted, &target_path); + } + } else { + img.save(&target_path)?; + } + out_paths.push(target_path); + } + } + + drop(pdf_doc); + drop(file); + Ok(out_paths) + } +} diff --git a/src-tauri/src/services/pdf_writer.rs b/src-tauri/src/services/pdf_writer.rs new file mode 100644 index 0000000..ec19b8b --- /dev/null +++ b/src-tauri/src/services/pdf_writer.rs @@ -0,0 +1,787 @@ +//! Biçim koruyan vektör PDF yazıcı (resim, birleşik hücreli tablo, liste, hizalama). + +use std::path::{Path, PathBuf}; + +use printpdf::{ + Mm, Op, ParsedFont, PdfDocument, PdfFontHandle, PdfPage, PdfSaveOptions, Point, Pt, Rgb, + TextItem, +}; + +use crate::error::{AppError, AppResult}; +use crate::services::image_engine::ImageEngine; +use crate::services::pdf_images::{self, LinkAnnotation, OutlineEntry, Placement}; +use crate::services::office_model::{Align, Block, Document, Paragraph, Table}; + +const PAGE_WIDTH_MM: f32 = 210.0; +const PAGE_HEIGHT_MM: f32 = 297.0; +const MARGIN_MM: f32 = 18.0; +const BODY_SIZE: f32 = 11.0; +const MM_PER_PT: f32 = 25.4 / 72.0; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Style { + Regular, + Bold, + Italic, + BoldItalic, +} + +impl Style { + fn index(self) -> usize { + match self { + Style::Regular => 0, + Style::Bold => 1, + Style::Italic => 2, + Style::BoldItalic => 3, + } + } + + fn from_flags(bold: bool, italic: bool) -> Self { + match (bold, italic) { + (true, true) => Style::BoldItalic, + (true, false) => Style::Bold, + (false, true) => Style::Italic, + (false, false) => Style::Regular, + } + } +} + +fn font_file(style: Style) -> &'static [&'static str] { + match style { + Style::Regular => &["segoeui.ttf", "arial.ttf"], + Style::Bold => &["segoeuib.ttf", "arialbd.ttf"], + Style::Italic => &["segoeuii.ttf", "ariali.ttf"], + Style::BoldItalic => &["segoeuiz.ttf", "arialbi.ttf"], + } +} + +fn fonts_dir() -> PathBuf { + std::env::var("WINDIR") + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from(r"C:\Windows")) + .join("Fonts") +} + +fn load_face_from_disk(style: Style) -> Option> { + let dir = fonts_dir(); + font_file(style) + .iter() + .find_map(|name| std::fs::read(dir.join(name)).ok()) +} + +static CACHED_FONTS: std::sync::OnceLock<[Option>; 4]> = std::sync::OnceLock::new(); + +fn load_face(style: Style) -> Option> { + let cache = CACHED_FONTS.get_or_init(|| { + [ + load_face_from_disk(Style::Regular), + load_face_from_disk(Style::Bold), + load_face_from_disk(Style::Italic), + load_face_from_disk(Style::BoldItalic), + ] + }); + cache[style.index()].clone() +} + +#[derive(Clone)] +struct FontMetrics { + units_per_em: f32, + ascii_widths: [f32; 128], +} + +impl Default for FontMetrics { + fn default() -> Self { + Self { + units_per_em: 1000.0, + ascii_widths: [0.52; 128], + } + } +} + +impl FontMetrics { + fn from_bytes(font: &[u8]) -> Option { + let face = ttf_parser::Face::parse(font, 0).ok()?; + let units = face.units_per_em() as f32; + let mut ascii_widths = [0.0f32; 128]; + for (i, w) in ascii_widths.iter_mut().enumerate() { + let ch = i as u8 as char; + if let Some(id) = face.glyph_index(ch) { + if let Some(adv) = face.glyph_hor_advance(id) { + *w = adv as f32 / units; + continue; + } + } + *w = 0.52; + } + Some(Self { + units_per_em: units, + ascii_widths, + }) + } + + fn measure_text(&self, text: &str, size_pt: f32, font: &[u8]) -> f32 { + let mut width = 0.0f32; + let mut face_cached: Option = None; + for c in text.chars() { + let code = c as u32; + if code < 128 { + width += self.ascii_widths[code as usize] * size_pt; + } else { + if face_cached.is_none() { + face_cached = ttf_parser::Face::parse(font, 0).ok(); + } + if let Some(ref face) = face_cached { + if let Some(id) = face.glyph_index(c) { + if let Some(advance) = face.glyph_hor_advance(id) { + width += (advance as f32 / self.units_per_em) * size_pt; + continue; + } + } + } + width += size_pt * 0.52; + } + } + width + } +} + +fn measure(text: &str, size_pt: f32, faces: &Faces, style: Style) -> f32 { + let index = style.index(); + let font_bytes = faces.data(style); + if let Some(ref metrics) = faces.metrics[index] { + metrics.measure_text(text, size_pt, font_bytes) + } else { + text.chars().count() as f32 * size_pt * 0.52 + } +} + +#[derive(Clone)] +struct Span { + text: String, + style: Style, + size: f32, + color: Option<[u8; 3]>, + underline: bool, + link: Option, +} + +struct Faces { + bytes: [Vec; 4], + handles: [Option; 4], + parsed: [Option; 4], + used: [bool; 4], + metrics: [Option; 4], +} + +impl Faces { + fn collect(document: &Document) -> [bool; 4] { + let mut used = [false; 4]; + used[Style::Regular.index()] = true; + for block in &document.blocks { + match block { + Block::Paragraph(paragraph) => { + if paragraph.style.heading.is_some() { + used[Style::Bold.index()] = true; + } + for run in ¶graph.runs { + used[Style::from_flags(run.bold, run.italic).index()] = true; + } + } + Block::Table(table) => { + for row in &table.rows { + for cell in row { + for paragraph in &cell.paragraphs { + if paragraph.style.heading.is_some() { + used[Style::Bold.index()] = true; + } + for run in ¶graph.runs { + used[Style::from_flags(run.bold, run.italic).index()] = true; + } + } + } + } + } + _ => {} + } + } + used + } + + fn load(document: &Document) -> AppResult { + let used = Self::collect(document); + let mut bytes: [Vec; 4] = Default::default(); + let mut parsed: [Option; 4] = Default::default(); + let mut metrics: [Option; 4] = Default::default(); + + for style in [Style::Regular, Style::Bold, Style::Italic, Style::BoldItalic] { + if !used[style.index()] { + continue; + } + let Some(data) = load_face(style).or_else(|| load_face(Style::Regular)) else { + return Err(AppError::Engine( + "PDF için sistem yazı tipi bulunamadı (segoeui/arial).".to_string(), + )); + }; + parsed[style.index()] = ParsedFont::from_bytes(&data, 0, &mut Vec::new()); + metrics[style.index()] = FontMetrics::from_bytes(&data); + bytes[style.index()] = data; + } + + Ok(Self { + bytes, + handles: Default::default(), + parsed, + used, + metrics, + }) + } + + fn data(&self, style: Style) -> &[u8] { + let index = style.index(); + if self.bytes[index].is_empty() { + &self.bytes[Style::Regular.index()] + } else { + &self.bytes[index] + } + } + + fn handle(&self, style: Style) -> Option { + let index = style.index(); + self.handles[index] + .clone() + .or_else(|| self.handles[Style::Regular.index()].clone()) + } +} + +fn color_of(color: Option<[u8; 3]>) -> printpdf::Color { + let [r, g, b] = color.unwrap_or([20, 24, 30]); + printpdf::Color::Rgb(Rgb { + r: r as f32 / 255.0, + g: g as f32 / 255.0, + b: b as f32 / 255.0, + icc_profile: None, + }) +} + +fn paragraph_spans(paragraph: &Paragraph, prefix_override: Option) -> (Vec, f32) { + let (base_style, base_size) = match paragraph.style.heading { + Some(1) => (Style::Bold, 20.0), + Some(2) => (Style::Bold, 16.0), + Some(3) => (Style::Bold, 14.0), + Some(_) => (Style::Bold, 13.0), + None => (Style::Regular, BODY_SIZE), + }; + let heading = paragraph.style.heading.is_some(); + + let mut spans = Vec::new(); + if let Some(prefix) = prefix_override { + spans.push(Span { + text: prefix, + style: base_style, + size: base_size, + color: None, + underline: false, + link: None, + }); + } else if paragraph.style.list.is_some() { + spans.push(Span { + text: "• ".to_string(), + style: Style::Regular, + size: base_size, + color: None, + underline: false, + link: None, + }); + } + + for run in ¶graph.runs { + let style = if heading { + Style::Bold + } else { + Style::from_flags(run.bold, run.italic) + }; + let color = run.color.or_else(|| { + if run.link.is_some() { + Some([18, 92, 196]) + } else { + None + } + }); + spans.push(Span { + text: run.text.clone(), + style, + size: run.size_pt.unwrap_or(base_size), + color, + underline: run.underline || run.link.is_some(), + link: run.link.clone(), + }); + } + (spans, base_size) +} + +fn wrap(spans: &[Span], max_width_pt: f32, faces: &Faces) -> Vec> { + let mut lines: Vec> = Vec::new(); + let mut current: Vec = Vec::new(); + let mut width = 0.0; + + for span in spans { + let mut word = String::new(); + let mut pieces: Vec<(String, bool)> = Vec::new(); + for character in span.text.chars() { + if character == '\n' { + pieces.push((std::mem::take(&mut word), false)); + pieces.push(("\n".to_string(), true)); + continue; + } + word.push(character); + if character == ' ' { + pieces.push((std::mem::take(&mut word), true)); + } + } + if !word.is_empty() { + pieces.push((word, false)); + } + + for (piece, is_space) in pieces { + if piece == "\n" { + lines.push(std::mem::take(&mut current)); + width = 0.0; + continue; + } + let advance = measure(&piece, span.size, faces, span.style); + if width + advance > max_width_pt && !current.is_empty() && !(is_space && piece.trim().is_empty()) { + lines.push(std::mem::take(&mut current)); + width = 0.0; + } + if is_space && piece.trim().is_empty() && current.is_empty() { + continue; + } + current.push(Span { + text: piece, + style: span.style, + size: span.size, + color: span.color, + underline: span.underline, + link: span.link.clone(), + }); + width += advance; + } + } + if !current.is_empty() { + lines.push(current); + } + if lines.is_empty() { + lines.push(Vec::new()); + } + lines +} + +struct Page { + ops: Vec, + y: f32, +} + +impl Page { + fn new() -> Self { + Self { + ops: Vec::new(), + y: PAGE_HEIGHT_MM - MARGIN_MM, + } + } + + #[allow(clippy::too_many_arguments)] + fn text(&mut self, text: &str, style: Style, size: f32, color: Option<[u8; 3]>, x: f32, y: f32, faces: &Faces) { + let Some(handle) = faces.handle(style) else { return }; + self.ops.push(Op::StartTextSection); + self.ops.push(Op::SetTextCursor { + pos: Point::new(Mm(x), Mm(y)), + }); + self.ops.push(Op::SetFont { font: handle, size: Pt(size) }); + self.ops.push(Op::SetFillColor { col: color_of(color) }); + self.ops.push(Op::ShowText { + items: vec![TextItem::Text(text.to_string())], + }); + self.ops.push(Op::EndTextSection); + } + + fn underline_rule(&mut self, x_mm: f32, baseline_mm: f32, width_mm: f32, size_pt: f32, color: Option<[u8; 3]>) { + if width_mm <= 0.1 { + return; + } + let rule_y_mm = baseline_mm - (size_pt * 0.12 * MM_PER_PT); + self.ops.push(Op::SetFillColor { col: color_of(color) }); + self.ops.push(Op::DrawRectangle { + rectangle: printpdf::Rect { + x: Pt(x_mm / MM_PER_PT), + y: Pt(rule_y_mm / MM_PER_PT), + width: Pt(width_mm / MM_PER_PT), + height: Pt(0.55), + mode: Some(printpdf::PaintMode::Fill), + winding_order: Some(printpdf::WindingOrder::NonZero), + }, + }); + } +} + +pub fn write_pdf(document: &Document, output: &Path) -> AppResult { + if document.is_empty() { + return Err(AppError::Pdf("Belgede yazılacak içerik yok.".to_string())); + } + + let mut faces = Faces::load(document)?; + let mut pdf = PdfDocument::new("LD Converter"); + for style in [Style::Regular, Style::Bold, Style::Italic, Style::BoldItalic] { + if faces.used[style.index()] { + if let Some(font) = &faces.parsed[style.index()] { + let handle = PdfFontHandle::External(pdf.add_font(font)); + faces.handles[style.index()] = Some(handle); + } + } + } + + // Görsel yerleşimleri, tıklanabilir köprüler ve yer işaretleri lopdf ile eklenecek. + let mut placements: Vec = Vec::new(); + let mut links: Vec = Vec::new(); + let mut outlines: Vec = Vec::new(); + + let content_width_pt = (PAGE_WIDTH_MM - 2.0 * MARGIN_MM) / MM_PER_PT; + let mut pages: Vec> = Vec::new(); + let mut page = Page::new(); + + let flush = |pages: &mut Vec>, page: &mut Page| { + pages.push(std::mem::take(&mut page.ops)); + page.y = PAGE_HEIGHT_MM - MARGIN_MM; + }; + + let mut list_counters: std::collections::HashMap = std::collections::HashMap::new(); + + for block in document.blocks.iter() { + let is_list = matches!(block, Block::Paragraph(paragraph) if paragraph.style.list.is_some()); + if !is_list { + list_counters.clear(); + } + + match block { + Block::Paragraph(paragraph) => { + let prefix = match paragraph.style.list { + Some(crate::services::office_model::ListKind::Numbered) => { + let level = paragraph.style.level; + let counter = list_counters.entry(level).or_insert(0); + *counter += 1; + Some(format!("{}. ", counter)) + } + _ => None, + }; + let (spans, base_size) = paragraph_spans(paragraph, prefix); + if spans.iter().all(|span| span.text.trim().is_empty()) { + page.y -= base_size * 0.6 * MM_PER_PT; + continue; + } + + let indent = if paragraph.style.list.is_some() { + 5.0 + (paragraph.style.level as f32) * 4.0 + } else { + 0.0 + }; + page.y -= paragraph.style.space_before_pt * MM_PER_PT + + if paragraph.style.heading.is_some() { 4.0 } else { 0.8 }; + + let lines = wrap(&spans, content_width_pt - indent / MM_PER_PT, &faces); + let mut recorded_outline = false; + + for line in lines { + let max_size = line.iter().map(|span| span.size).fold(base_size, f32::max); + let height = max_size * 1.38 * MM_PER_PT; + if page.y - height < MARGIN_MM { + flush(&mut pages, &mut page); + } + if !recorded_outline { + if let Some(level) = paragraph.style.heading { + if (1..=3).contains(&level) { + let title = paragraph.text(); + if !title.trim().is_empty() { + outlines.push(OutlineEntry { + title, + level, + page: pages.len() as u32 + 1, + y_mm: page.y, + }); + } + } + } + recorded_outline = true; + } + + page.y -= height; + let baseline = page.y + height * 0.26; + + let mut x = MARGIN_MM + indent; + let line_width: f32 = line + .iter() + .map(|span| measure(&span.text, span.size, &faces, span.style) * MM_PER_PT) + .sum(); + match paragraph.style.align { + Align::Center => x = MARGIN_MM + (PAGE_WIDTH_MM - 2.0 * MARGIN_MM - line_width) / 2.0, + Align::Right => x = PAGE_WIDTH_MM - MARGIN_MM - line_width, + _ => {} + } + + for span in &line { + if span.text.is_empty() { + continue; + } + let w_mm = measure(&span.text, span.size, &faces, span.style) * MM_PER_PT; + page.text(&span.text, span.style, span.size, span.color, x, baseline, &faces); + if span.underline || span.link.is_some() { + page.underline_rule(x, baseline, w_mm, span.size, span.color); + } + if let Some(url) = &span.link { + links.push(LinkAnnotation { + page: pages.len() as u32 + 1, + x_mm: x, + y_mm: baseline - (span.size * 0.25 * MM_PER_PT), + width_mm: w_mm, + height_mm: span.size * 1.2 * MM_PER_PT, + url: url.clone(), + }); + } + x += w_mm; + } + } + page.y -= 1.4; + } + Block::Table(table) => { + render_table(table, &mut page, &mut pages, &faces, &mut links, &flush); + } + Block::Image(image) => { + let width_pt = if image.width_pt > 0.0 { image.width_pt } else { 320.0 }; + let height_pt = if image.height_pt > 0.0 { image.height_pt } else { 200.0 }; + let width_mm = width_pt * MM_PER_PT; + let height_mm = height_pt * MM_PER_PT; + + if page.y - height_mm < MARGIN_MM { + flush(&mut pages, &mut page); + } + page.y -= height_mm; + placements.push(Placement { + page: pages.len() as u32 + 1, + x_mm: MARGIN_MM, + y_mm: page.y, + width_mm, + height_mm, + bytes: image.data.clone(), + }); + page.y -= 2.0; + } + Block::PageBreak => { + flush(&mut pages, &mut page); + } + } + } + + if !page.ops.is_empty() { + pages.push(page.ops); + } + if pages.is_empty() { + pages.push(Vec::new()); + } + + // Birden fazla sayfa varsa alt ortaya otomatik "1 / N" sayfa numarası bas. + let total_pages = pages.len(); + if total_pages > 1 { + if let Some(regular_handle) = faces.handle(Style::Regular) { + for (idx, ops) in pages.iter_mut().enumerate() { + let label = format!("{} / {}", idx + 1, total_pages); + let label_w_mm = measure(&label, 9.0, &faces, Style::Regular) * MM_PER_PT; + let x_mm = (PAGE_WIDTH_MM - label_w_mm) / 2.0; + ops.push(Op::StartTextSection); + ops.push(Op::SetTextCursor { + pos: Point::new(Mm(x_mm), Mm(9.5)), + }); + ops.push(Op::SetFont { + font: regular_handle.clone(), + size: Pt(9.0), + }); + ops.push(Op::SetFillColor { + col: color_of(Some([110, 118, 130])), + }); + ops.push(Op::ShowText { + items: vec![TextItem::Text(label)], + }); + ops.push(Op::EndTextSection); + } + } + } + + let pdf_pages: Vec = pages + .into_iter() + .map(|ops| PdfPage::new(Mm(PAGE_WIDTH_MM), Mm(PAGE_HEIGHT_MM), ops)) + .collect(); + let bytes = pdf + .with_pages(pdf_pages) + .save(&PdfSaveOptions::default(), &mut Vec::new()); + let bytes = pdf_images::inject_corporate(&bytes, &placements, &links, &outlines); + + let final_path = ImageEngine::get_unique_path(output, false); + std::fs::write(&final_path, bytes)?; + Ok(final_path) +} + +#[allow(clippy::too_many_arguments)] +fn render_table( + table: &Table, + page: &mut Page, + pages: &mut Vec>, + faces: &Faces, + links: &mut Vec, + flush: &impl Fn(&mut Vec>, &mut Page), +) { + let columns = table + .rows + .iter() + .map(|row| row.iter().map(|cell| cell.colspan.max(1) as usize).sum::()) + .max() + .unwrap_or(1) + .max(1); + + let widths: Vec = if table.widths.len() == columns { + table.widths.clone() + } else { + vec![1.0; columns] + }; + let total: f32 = widths.iter().sum(); + let column_mm: Vec = widths + .iter() + .map(|width| (width / total.max(0.0001)) * (PAGE_WIDTH_MM - 2.0 * MARGIN_MM)) + .collect(); + + for row in &table.rows { + let mut col_cursor = 0usize; + let text_lines: Vec = row + .iter() + .map(|cell| { + let span_cols = cell.colspan.max(1) as usize; + let width: f32 = (0..span_cols) + .map(|offset| column_mm.get(col_cursor + offset).copied().unwrap_or(0.0)) + .sum(); + col_cursor += span_cols; + let span_width = (width - 2.0).max(6.0) / MM_PER_PT; + let mut total_lines = 0usize; + for paragraph in &cell.paragraphs { + let (spans, _) = paragraph_spans(paragraph, None); + total_lines += wrap(&spans, span_width, faces).len().max(1); + } + total_lines + }) + .collect(); + + let line_height = 4.2f32; + let row_height = text_lines.iter().copied().max().unwrap_or(1) as f32 * line_height + 2.2; + if page.y - row_height < MARGIN_MM { + flush(pages, page); + } + + let top = page.y; + page.y -= row_height; + let bottom = page.y; + let cur_page_num = pages.len() as u32 + 1; + + let mut column = 0usize; + for (cell_index, cell) in row.iter().enumerate() { + let width_mm: f32 = (0..cell.colspan.max(1) as usize) + .map(|offset| column_mm.get(column + offset).copied().unwrap_or(0.0)) + .sum(); + let x = MARGIN_MM + column_mm.iter().take(column).sum::() + 1.0; + + if let Some(shade) = cell.shade { + let [r, g, b] = shade; + page.ops.push(Op::SetFillColor { + col: printpdf::Color::Rgb(Rgb { + r: r as f32 / 255.0, + g: g as f32 / 255.0, + b: b as f32 / 255.0, + icc_profile: None, + }), + }); + page.ops.push(Op::DrawRectangle { + rectangle: printpdf::Rect { + x: Pt((x - 0.6) / MM_PER_PT), + y: Pt(bottom / MM_PER_PT), + width: Pt(width_mm / MM_PER_PT), + height: Pt(row_height / MM_PER_PT), + mode: Some(printpdf::PaintMode::Fill), + winding_order: Some(printpdf::WindingOrder::NonZero), + }, + }); + } + + let mut y = top - 3.6; + for paragraph in &cell.paragraphs { + let (spans, _) = paragraph_spans(paragraph, None); + let max_width = (width_mm - 2.0).max(6.0) / MM_PER_PT; + for line in wrap(&spans, max_width, faces) { + let line_width: f32 = line + .iter() + .map(|item| measure(&item.text, item.size.min(9.0), faces, item.style) * MM_PER_PT) + .sum(); + let start = match cell.align { + Align::Center => x + (width_mm - 1.0 - line_width) / 2.0, + Align::Right => x + width_mm - 1.0 - line_width, + _ => x, + }; + let mut offset = 0.0f32; + for span in &line { + let span_w = measure(&span.text, 9.0, faces, span.style) * MM_PER_PT; + page.text( + &span.text, + span.style, + 9.0, + span.color, + start + offset, + y, + faces, + ); + if span.underline || span.link.is_some() { + page.underline_rule(start + offset, y, span_w, 9.0, span.color); + } + if let Some(url) = &span.link { + links.push(LinkAnnotation { + page: cur_page_num, + x_mm: start + offset, + y_mm: y - (9.0 * 0.25 * MM_PER_PT), + width_mm: span_w, + height_mm: 9.0 * 1.2 * MM_PER_PT, + url: url.clone(), + }); + } + offset += span_w; + } + y -= line_height; + } + } + + page.ops.push(Op::SetOutlineColor { + col: printpdf::Color::Rgb(Rgb { + r: 0.6, + g: 0.65, + b: 0.7, + icc_profile: None, + }), + }); + page.ops.push(Op::SetOutlineThickness { pt: Pt(0.5) }); + page.ops.push(Op::DrawRectangle { + rectangle: printpdf::Rect { + x: Pt(x / MM_PER_PT), + y: Pt(bottom / MM_PER_PT), + width: Pt(width_mm / MM_PER_PT), + height: Pt(row_height / MM_PER_PT), + mode: Some(printpdf::PaintMode::Stroke), + winding_order: Some(printpdf::WindingOrder::NonZero), + }, + }); + + let _ = cell_index; + column += cell.colspan.max(1) as usize; + } + } +} diff --git a/src-tauri/src/services/progress.rs b/src-tauri/src/services/progress.rs new file mode 100644 index 0000000..c0de792 --- /dev/null +++ b/src-tauri/src/services/progress.rs @@ -0,0 +1,19 @@ +use tauri::{AppHandle, Emitter}; + +use crate::models::ProgressEvent; + +/// İlerleme olaylarını yayınlar. Testlerde `None` ile sessiz çalışır. +#[derive(Clone)] +pub struct ProgressEmitter(pub Option); + +impl ProgressEmitter { + pub fn emit(&self, event: ProgressEvent) { + if let Some(handle) = &self.0 { + let _ = handle.emit("conversion-progress", event); + } + } + + pub fn silent() -> Self { + Self(None) + } +} diff --git a/src-tauri/src/services/qr_engine.rs b/src-tauri/src/services/qr_engine.rs new file mode 100644 index 0000000..1655a53 --- /dev/null +++ b/src-tauri/src/services/qr_engine.rs @@ -0,0 +1,50 @@ +use std::path::Path; + +use rqrr::PreparedImage; + +use crate::error::{AppError, AppResult}; + +pub struct QrEngine; + +impl QrEngine { + pub fn read_qr_from_image(image_path: &str) -> AppResult { + let p = Path::new(image_path); + if !p.exists() { + return Err(AppError::NotFound(image_path.to_string())); + } + + let img = image::open(p)?; + Self::read_qr_from_dynamic_image(&img) + } + + pub fn read_qr_from_dynamic_image(img: &image::DynamicImage) -> AppResult { + let gray = img.to_luma8(); + let mut prepared = PreparedImage::prepare(gray); + let grids = prepared.detect_grids(); + + if grids.is_empty() { + return Err(AppError::Generic( + "Görsel içerisinde geçerli bir QR kod tespit edilemedi.".to_string(), + )); + } + + let mut contents = Vec::new(); + for grid in grids { + let mut bytes = Vec::new(); + if grid.decode_to(&mut bytes).is_ok() { + let content = String::from_utf8_lossy(&bytes).to_string(); + if !content.is_empty() { + contents.push(content); + } + } + } + + if contents.is_empty() { + Err(AppError::Generic( + "QR kod bulundu ancak içeriği çözümlenemedi.".to_string(), + )) + } else { + Ok(contents.join("\n\n")) + } + } +} diff --git a/src-tauri/src/services/shell_menu.rs b/src-tauri/src/services/shell_menu.rs new file mode 100644 index 0000000..0ac64c5 --- /dev/null +++ b/src-tauri/src/services/shell_menu.rs @@ -0,0 +1,232 @@ +//! Explorer sağ tık menüsü: "LD Converter ile Dönüştür" + hedef format alt menüsü. +//! +//! Menü, kayıt defterine (HKCU, yönetici gerekmez) statik fiiller olarak yazılır. +//! Her giriş `ld-converter.exe --convert "%1"` çağırır. + +use std::fs; +use std::path::PathBuf; +use std::process::{Command, Stdio}; + +use crate::logging; + +const MENU_VERSION: &str = "4"; + +struct Entry { + label: &'static str, + action: &'static str, +} + +const PDF: &[Entry] = &[ + Entry { label: "DOCX Yap", action: "pdf_to_docx" }, + Entry { label: "Denklem DOCX Yap", action: "pdf_to_math_docx" }, + Entry { label: "Metin Çıkar (TXT)", action: "pdf_to_txt" }, + Entry { label: "Sayfaları PNG Yap", action: "pdf_to_images" }, + Entry { label: "Sayfaları JPG Yap", action: "pdf_to_jpg" }, + Entry { label: "PDF Sıkıştır", action: "pdf_compress" }, + Entry { label: "Sayfaları Ayır", action: "pdf_split" }, + Entry { label: "ZIP Arşivi", action: "zip" }, +]; + +const DOCUMENTS: &[Entry] = &[ + Entry { label: "PDF Yap", action: "pdf" }, + Entry { label: "DOCX Yap", action: "docx" }, + Entry { label: "Düz Metin (TXT)", action: "txt" }, + Entry { label: "HTML Yap", action: "html" }, + Entry { label: "ZIP Arşivi", action: "zip" }, +]; + +const IMAGES: &[Entry] = &[ + Entry { label: "PNG Yap", action: "png" }, + Entry { label: "JPG Yap", action: "jpg" }, + Entry { label: "WebP Yap", action: "webp" }, + Entry { label: "PDF Yap", action: "pdf" }, + Entry { label: "ICO Yap", action: "ico" }, + Entry { label: "TIFF Yap", action: "tiff" }, + Entry { label: "BMP Yap", action: "bmp" }, + Entry { label: "AVIF Yap", action: "avif" }, + Entry { label: "GIF Yap", action: "gif" }, + Entry { label: "Sıkıştır", action: "compress_image" }, + Entry { label: "OCR → TXT", action: "img_to_txt" }, + Entry { label: "OCR → DOCX", action: "img_to_docx" }, +]; + +const VIDEO: &[Entry] = &[ + Entry { label: "MP4 Yap", action: "mp4" }, + Entry { label: "MKV Yap", action: "mkv" }, + Entry { label: "WebM Yap", action: "webm" }, + Entry { label: "GIF Yap", action: "gif" }, + Entry { label: "Sesi MP3 Yap", action: "mp3" }, + Entry { label: "Video Sıkıştır", action: "compress_video" }, +]; + +const AUDIO: &[Entry] = &[ + Entry { label: "MP3 Yap", action: "mp3" }, + Entry { label: "WAV Yap", action: "wav" }, + Entry { label: "AAC / M4A Yap", action: "aac" }, + Entry { label: "FLAC Yap", action: "flac" }, +]; + +const ARCHIVES: &[Entry] = &[ + Entry { label: "ZIP Arşivi", action: "zip" }, + Entry { label: "7Z Arşivi", action: "7z" }, + Entry { label: "TAR.GZ Yap", action: "tar_gz" }, +]; + +fn entries_for(extension: &str) -> Option<&'static [Entry]> { + match extension { + "pdf" => Some(PDF), + "docx" | "doc" | "odt" | "rtf" | "txt" | "md" | "markdown" | "html" | "htm" | "epub" + | "pptx" | "xlsx" | "csv" => Some(DOCUMENTS), + "png" | "jpg" | "jpeg" | "webp" | "avif" | "jxl" | "bmp" | "tiff" | "tif" | "gif" + | "ico" | "svg" | "heic" | "heif" | "cr2" | "nef" | "arw" => Some(IMAGES), + "mp4" | "mkv" | "avi" | "mov" | "webm" | "flv" | "wmv" => Some(VIDEO), + "mp3" | "wav" | "aac" | "m4a" | "flac" | "ogg" | "opus" => Some(AUDIO), + "zip" | "7z" | "rar" | "tar" | "gz" | "tar.gz" => Some(ARCHIVES), + _ => None, + } +} + +/// .reg dosyası için dizge kaçışı. +fn escape(value: &str) -> String { + value.replace('\\', "\\\\").replace('"', "\\\"") +} + +fn submenu_key(extension: &str) -> String { + format!("LDConverter.{}", extension.replace('.', "_")) +} + +fn write_submenu(reg: &mut String, base: &str, extension: &str, entries: &[Entry], exe: &str) { + let key = submenu_key(extension); + + reg.push_str(&format!( + "[{}\\shell\\LDConverter]\n\"MUIVerb\"=\"LD Converter ile Dönüştür\"\n\"Icon\"=\"{}\"\n\"SubCommands\"=\"\"\n\"ExtendedSubCommandsKey\"=\"{}\"\n\n", + base, + escape(exe), + key + )); + + for (index, entry) in entries.iter().enumerate() { + let sub = format!("{}\\shell\\{:02}", key, index + 1); + reg.push_str(&format!( + "[HKEY_CURRENT_USER\\Software\\Classes\\{}]\n\"MUIVerb\"=\"{}\"\n\n", + sub, + escape(entry.label) + )); + reg.push_str(&format!( + "[HKEY_CURRENT_USER\\Software\\Classes\\{}\\command]\n@=\"\\\"{}\\\" --convert {} \\\"%1\\\"\"\n\n", + sub, + escape(exe), + entry.action + )); + } +} + +fn marker_path() -> Option { + dirs::data_local_dir().map(|dir| dir.join("LDConverter").join("shell_menu.txt")) +} + +fn write_registry(exe: &str) -> bool { + let mut reg = String::from("Windows Registry Editor Version 5.00\n\n"); + + // Bilinen uzantılar için hedefe özel alt menüler + let extensions = [ + "pdf", "docx", "doc", "odt", "rtf", "txt", "md", "html", "htm", "epub", "pptx", "xlsx", + "csv", "png", "jpg", "jpeg", "webp", "avif", "jxl", "bmp", "tiff", "tif", "gif", "ico", + "svg", "heic", "heif", "cr2", "nef", "arw", + "mp4", "mkv", "avi", "mov", "webm", "flv", "wmv", "mp3", "wav", "aac", "m4a", "flac", + "ogg", "opus", "zip", "7z", "rar", "tar", "gz", + ]; + + for extension in extensions { + let Some(entries) = entries_for(extension) else { continue }; + let base = format!( + "HKEY_CURRENT_USER\\Software\\Classes\\SystemFileAssociations\\.{}", + extension + ); + write_submenu(&mut reg, &base, extension, entries, exe); + } + + // Tüm dosyalar için genel alt menü (bilinmeyen uzantılar) + let common: &[Entry] = &[ + Entry { label: "PDF Yap", action: "pdf" }, + Entry { label: "DOCX Yap", action: "docx" }, + Entry { label: "PNG Yap", action: "png" }, + Entry { label: "JPG Yap", action: "jpg" }, + Entry { label: "MP3 Yap", action: "mp3" }, + Entry { label: "MP4 Yap", action: "mp4" }, + Entry { label: "ZIP Arşivi", action: "zip" }, + ]; + write_submenu( + &mut reg, + "HKEY_CURRENT_USER\\Software\\Classes\\*", + "any", + common, + exe, + ); + + let Some(marker) = marker_path() else { return false }; + if let Some(parent) = marker.parent() { + let _ = fs::create_dir_all(parent); + } + let reg_path = marker.with_file_name("ld_menu.reg"); + + // reg.exe .reg dosyasını UTF-16LE (BOM'lu) bekler; Türkçe karakterler için şart. + let mut bytes = vec![0xFF, 0xFE]; + for unit in reg.encode_utf16() { + bytes.extend_from_slice(&unit.to_le_bytes()); + } + if fs::write(®_path, bytes).is_err() { + return false; + } + + let mut command = Command::new("reg.exe"); + command + .args(["import", ®_path.to_string_lossy()]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x08000000); + } + + let result = command.output(); + let _ = fs::remove_file(®_path); + + match result { + Ok(output) if output.status.success() => true, + Ok(output) => { + let stderr = String::from_utf8_lossy(&output.stderr); + logging::warn(&format!( + "Menü içe aktarma hatası (kod {:?}): {}", + output.status.code(), + stderr.trim() + )); + false + } + Err(err) => { + logging::warn(&format!("reg.exe çalıştırılamadı: {}", err)); + false + } + } +} + +/// Menüyü kurar (yalnızca sürüm/yol değiştiyse yeniden yazar). +pub fn install(exe: &str) { + let Some(marker) = marker_path() else { return }; + let expected = format!("{}\n{}", MENU_VERSION, exe); + + if let Ok(current) = fs::read_to_string(&marker) { + if current.trim() == expected.trim() { + return; + } + } + + if write_registry(exe) { + let _ = fs::write(&marker, &expected); + logging::info("Explorer sağ tık menüsü kuruldu"); + } else { + logging::warn("Explorer sağ tık menüsü kurulamadı"); + } +} diff --git a/src-tauri/src/state/mod.rs b/src-tauri/src/state/mod.rs new file mode 100644 index 0000000..02da3d7 --- /dev/null +++ b/src-tauri/src/state/mod.rs @@ -0,0 +1,122 @@ +use std::collections::HashMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; +use std::sync::Arc; +use tokio::sync::RwLock; + +use crate::logging; +use crate::models::{AppPreferences, HistoryEntry}; + +pub struct AppState { + pub preferences: Arc>, + pub history: Arc>>, + pub active_cancellations: Arc>>>, +} + +impl AppState { + pub fn new() -> Self { + let mut prefs = Self::load_preferences().unwrap_or_default(); + + // Ayar şeması yükseltmesi: 2.7.0 öncesi dosyalarda kalite varsayılanı %90 idi. + // Tam kalite yeni varsayılan olduğu için eski dosyalar bir kez güncellenir. + if prefs.settings_version < 2 { + prefs.default_image_quality = 100; + prefs.settings_version = 2; + AppState::save_preferences_to_disk(&prefs); + logging::info("Ayar şeması 2'ye yükseltildi (tam kalite varsayılanları)"); + } + + let hist = Self::load_history().unwrap_or_default(); + + crate::services::engine_resolver::set_custom_paths( + &prefs.custom_ffmpeg_path, + &prefs.custom_pandoc_path, + &prefs.custom_seven_zip_path, + ); + + Self { + preferences: Arc::new(RwLock::new(prefs)), + history: Arc::new(RwLock::new(hist)), + active_cancellations: Arc::new(RwLock::new(HashMap::new())), + } + } + + fn config_dir() -> Option { + dirs::data_local_dir().map(|dir| dir.join("LDConverter")) + } + + /// Bozuk JSON dosyasını yedekleyip varsayılan değerlerle devam eder (self-healing). + fn read_json_or_heal( + path: &Path, + label: &str, + ) -> Option { + if !path.exists() { + return None; + } + match fs::read_to_string(path) { + Ok(text) => match serde_json::from_str::(&text) { + Ok(value) => Some(value), + Err(err) => { + let backup = path.with_extension("corrupt.json"); + let _ = fs::rename(path, &backup); + logging::warn(&format!( + "{} dosyası bozuk ({}); yedeklendi: {}", + label, + err, + backup.display() + )); + Some(T::default()) + } + }, + Err(err) => { + logging::error(&format!("{} okunamadı: {}", label, err)); + None + } + } + } + + pub fn load_preferences() -> Option { + let path = Self::config_dir()?.join("preferences.json"); + Self::read_json_or_heal(&path, "preferences.json") + } + + fn write_json_atomic(path: &Path, data: &str) -> Option<()> { + let dir = path.parent()?; + fs::create_dir_all(dir).ok()?; + let temp_path = path.with_extension("tmp"); + fs::write(&temp_path, data).ok()?; + fs::rename(&temp_path, path).ok() + } + + pub fn save_preferences_to_disk(prefs: &AppPreferences) -> Option<()> { + let path = Self::config_dir()?.join("preferences.json"); + let data = serde_json::to_string_pretty(prefs).ok()?; + let result = Self::write_json_atomic(&path, &data); + if result.is_none() { + logging::error("preferences.json yazılamadı (ayarlar kalıcı olmayabilir)"); + } + result + } + + pub fn load_history() -> Option> { + let path = Self::config_dir()?.join("history.json"); + Self::read_json_or_heal(&path, "history.json") + } + + pub fn save_history_to_disk(history: &[HistoryEntry]) -> Option<()> { + let path = Self::config_dir()?.join("history.json"); + let data = serde_json::to_string_pretty(history).ok()?; + let result = Self::write_json_atomic(&path, &data); + if result.is_none() { + logging::error("history.json yazılamadı (geçmiş kalıcı olmayabilir)"); + } + result + } +} + +impl Default for AppState { + fn default() -> Self { + Self::new() + } +} diff --git a/src-tauri/src/utils/mod.rs b/src-tauri/src/utils/mod.rs new file mode 100644 index 0000000..359561b --- /dev/null +++ b/src-tauri/src/utils/mod.rs @@ -0,0 +1,75 @@ +//! Küçük, bağımsız yardımcı fonksiyonlar (dosya boyutu, kullanıcıya gösterilecek etiketler). + +use std::path::Path; + +use walkdir::WalkDir; + +/// Bir dosya veya klasörün toplam boyutunu bayt cinsinden döner (okunamayan girdiler atlanır). +pub fn total_size(path: &str) -> u64 { + let target = Path::new(path); + let metadata = match std::fs::metadata(target) { + Ok(metadata) => metadata, + Err(_) => return 0, + }; + + if metadata.is_file() { + return metadata.len(); + } + + WalkDir::new(target) + .into_iter() + .flatten() + .filter_map(|entry| entry.metadata().ok()) + .filter(|entry| entry.is_file()) + .map(|entry| entry.len()) + .sum() +} + +/// Windows mesaj penceresi (hata ise kırmızı ikon). +#[cfg(windows)] +pub fn message_box(title: &str, text: &str, is_error: bool) { + use windows_sys::Win32::UI::WindowsAndMessaging::{ + MessageBoxW, MB_ICONERROR, MB_ICONINFORMATION, MB_OK, MB_SETFOREGROUND, + }; + + let wide = |value: &str| -> Vec { value.encode_utf16().chain(std::iter::once(0)).collect() }; + let text_wide = wide(text); + let title_wide = wide(title); + let icon = if is_error { MB_ICONERROR } else { MB_ICONINFORMATION }; + unsafe { + MessageBoxW( + std::ptr::null_mut(), + text_wide.as_ptr(), + title_wide.as_ptr(), + MB_OK | icon | MB_SETFOREGROUND, + ); + } +} + +#[cfg(not(windows))] +pub fn message_box(title: &str, text: &str, _is_error: bool) { + eprintln!("{}: {}", title, text); +} + +/// Geçmiş ekranında gösterilen kısa eylem etiketi. +pub fn friendly_action_label(action: &str) -> String { + match action { + "pdf_to_images" => "PNG".to_string(), + "pdf_to_jpg" => "JPG".to_string(), + "pdf_to_jxl" => "JXL".to_string(), + "pdf_to_txt" => "TXT".to_string(), + "pdf_to_docx" => "DOCX".to_string(), + "pdf_to_math_docx" | "docx_math" => "DENKLEM DOCX".to_string(), + "img_to_txt" => "OCR TXT".to_string(), + "img_to_docx" => "OCR DOCX".to_string(), + "pdf_merge" => "PDF BİRLEŞTİR".to_string(), + "pdf_split" => "PDF AYIR".to_string(), + "extract_folder" => "KLASÖRE ÇIKAR".to_string(), + "copy_folder" => "KLASÖRE TOPLA".to_string(), + "compress_image" | "compress_video" | "compress_audio" => "SIKIŞTIR".to_string(), + "qr_read" => "QR OKU".to_string(), + "tar_gz" => "TAR.GZ".to_string(), + "jxl" => "JPEG XL".to_string(), + other => other.to_uppercase(), + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json new file mode 100644 index 0000000..999d801 --- /dev/null +++ b/src-tauri/tauri.conf.json @@ -0,0 +1,58 @@ +{ + "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", + "productName": "LD Converter", + "version": "3.6.4", + "identifier": "com.lildosto.ldconverter", + "build": { + "frontendDist": "../dist-ui", + "devUrl": "http://localhost:5173", + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run build" + }, + "app": { + "windows": [ + { + "label": "main", + "title": "LD Converter", + "width": 940, + "height": 640, + "minWidth": 780, + "minHeight": 540, + "center": true, + "resizable": true, + "fullscreen": false, + "decorations": false, + "transparent": true, + "shadow": true, + "dragDropEnabled": true + } + ], + "security": { + "csp": null + } + }, + "bundle": { + "active": true, + "createUpdaterArtifacts": true, + "targets": "all", + "icon": [ + "icons/32x32.png", + "icons/128x128.png", + "icons/128x128@2x.png", + "icons/icon.icns", + "icons/icon.ico" + ], + "resources": { + "../tools/cjxl.exe": "tools/cjxl.exe", + "../tools/djxl.exe": "tools/djxl.exe" + } + }, + "plugins": { + "updater": { + "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDAzNEUwNEE1OEFCNEU1NDQKUldSRTViU0twUVJPQSt5M2xPRDNPSGZENE9EOXM4NDcwd0RSamIwbFNGRGNoRmUvbm5CUWdiNFMK", + "endpoints": [ + "https://ttmadethat.shop/updates/ld-converter/latest.json" + ] + } + } +} diff --git a/src-tauri/tests/conversion_tests.rs b/src-tauri/tests/conversion_tests.rs new file mode 100644 index 0000000..752038f --- /dev/null +++ b/src-tauri/tests/conversion_tests.rs @@ -0,0 +1,952 @@ +//! Uçtan uca dönüşüm testleri: gerçek dosyalar üretip motorları çalıştırır. +//! Harici araç (FFmpeg, 7-Zip, OCR) yoksa ilgili test sessizce atlanır. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::atomic::AtomicBool; +use std::sync::Arc; + +use app_lib::models::{AppPreferences, ConversionOptions}; +use app_lib::services::{ + ArchiveEngine, ConversionDispatcher, EngineResolver, ImageEngine, OcrEngine, PdfEngine, + ProgressEmitter, +}; + +#[cfg(windows)] +use std::os::windows::process::CommandExt; + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ld_it_{}_{}", tag, uuid::Uuid::new_v4())); + fs::create_dir_all(&dir).unwrap(); + dir +} + +fn create_image(path: &Path, width: u32, height: u32) { + let img = image::RgbImage::from_fn(width, height, |x, y| { + image::Rgb([(x % 255) as u8, (y % 255) as u8, 90]) + }); + img.save(path).unwrap(); +} + +fn run_capture(program: &str, args: &[&str]) -> bool { + let mut cmd = Command::new(program); + #[cfg(windows)] + cmd.creation_flags(0x08000000); + cmd.args(args) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .map(|s| s.success()) + .unwrap_or(false) +} + +/// Harici araç gerektirmeyen, metin katmanlı test PDF'i üretir. +fn create_text_pdf(dir: &Path, file_stem: &str, marker: &str) -> Option { + let path = dir.join(format!("{}.pdf", file_stem)); + PdfEngine::write_simple_text_pdf(marker, &path).ok()?; + Some(path) +} + +fn dispatcher_call(files: Vec, action: &str, options: ConversionOptions) -> Result { + let runtime = tokio::runtime::Runtime::new().unwrap(); + runtime.block_on(async move { + ConversionDispatcher::execute_task( + ProgressEmitter::silent(), + files, + action.to_string(), + options, + AppPreferences::default(), + Arc::new(AtomicBool::new(false)), + uuid::Uuid::new_v4().to_string(), + ) + .await + .map_err(|e| e.to_string()) + }) +} + +#[test] +fn image_formats_all_convert() { + let dir = temp_dir("img_formats"); + let src = dir.join("kaynak.png"); + create_image(&src, 320, 200); + + let opts = ConversionOptions::default(); + for target in ["jpg", "webp", "bmp", "tiff", "ico", "gif", "png"] { + let out = ImageEngine::convert_single(&src.to_string_lossy(), target, &dir, &opts) + .unwrap_or_else(|e| panic!("{} dönüşümü başarısız: {}", target, e)); + assert!(out.exists(), "{} çıktısı yok", target); + assert!(fs::metadata(&out).unwrap().len() > 0, "{} çıktısı boş", target); + } + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn image_to_pdf_merge_split_roundtrip() { + let dir = temp_dir("pdf_flow"); + let a = dir.join("a.png"); + let b = dir.join("b.png"); + create_image(&a, 200, 300); + create_image(&b, 400, 200); + + let pdf1 = dir.join("tek.pdf"); + PdfEngine::merge(&[a.to_string_lossy().to_string()], &pdf1, &ConversionOptions::default()) + .unwrap(); + assert_eq!(PdfEngine::page_count(&pdf1.to_string_lossy()).unwrap(), 1); + + let pdf2 = dir.join("birlestirilmis.pdf"); + PdfEngine::merge( + &[ + pdf1.to_string_lossy().to_string(), + b.to_string_lossy().to_string(), + ], + &pdf2, + &ConversionOptions::default(), + ) + .unwrap(); + assert_eq!( + PdfEngine::page_count(&pdf2.to_string_lossy()).unwrap(), + 2, + "PDF + görsel birleştirme 2 sayfa olmalı" + ); + + // Ayırma: her sayfa ayrı dosya + let split = PdfEngine::split_pdf( + &pdf2.to_string_lossy(), + &dir, + &ConversionOptions::default(), + ) + .unwrap(); + assert_eq!(split.len(), 2); + for page in &split { + assert!(page.exists()); + assert_eq!(PdfEngine::page_count(&page.to_string_lossy()).unwrap(), 1); + } + + // Sayfa aralığı: sadece 2. sayfa + let opts = ConversionOptions { + pdf_page_range: Some("2".to_string()), + ..Default::default() + }; + let split_range = PdfEngine::split_pdf(&pdf2.to_string_lossy(), &dir, &opts).unwrap(); + assert_eq!(split_range.len(), 1); + assert!(split_range[0] + .file_name() + .unwrap() + .to_string_lossy() + .contains("sayfa_2")); + + // Döndürme uygulanır ve geçerli PDF kalır + let rotated_dir = dir.join("rotated"); + fs::create_dir_all(&rotated_dir).unwrap(); + let rotated_opts = ConversionOptions { + pdf_rotate_degrees: Some(90), + ..Default::default() + }; + let rotated = PdfEngine::merge( + &[pdf1.to_string_lossy().to_string()], + &rotated_dir.join("donmus.pdf"), + &rotated_opts, + ) + .unwrap(); + assert!(rotated.exists()); + assert_eq!(PdfEngine::page_count(&rotated.to_string_lossy()).unwrap(), 1); + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn pdf_math_docx_runs_bundled_engine() { + let dir = temp_dir("pdf_math"); + let Some(pdf) = create_text_pdf(&dir, "matematik", "DENKLEM TESTI") else { + eprintln!("test PDF üretilemedi"); + return; + }; + + let out_dir = dir.join("out"); + fs::create_dir_all(&out_dir).unwrap(); + let started = std::time::Instant::now(); + let result = dispatcher_call( + vec![pdf.to_string_lossy().to_string()], + "docx_math", + ConversionOptions { + destination_folder: Some(out_dir.to_string_lossy().to_string()), + ..Default::default() + }, + ); + eprintln!("PDF_MATH_SURE={:?}", started.elapsed()); + let result = result.expect("PDF -> Denklem DOCX başarısız"); + let docx = PathBuf::from(&result.output_files[0]); + assert!(docx.exists()); + assert!(fs::metadata(&docx).unwrap().len() > 1000); + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn math_engine_direct_on_formula_pdf() { + let dir = temp_dir("math_direct"); + let out_dir = dir.join("out"); + fs::create_dir_all(&out_dir).unwrap(); + let Some(pdf) = create_text_pdf(&dir, "formul", "x^2 + y^2 = z^2") else { + return; + }; + + let result = app_lib::services::MathEngine::convert_to_math_docx( + &pdf.to_string_lossy(), + &out_dir, + true, + ); + eprintln!("MATH_DIRECT={:?}", result); + let docx = result.expect("motor doğrudan çalışmadı"); + let file = fs::File::open(&docx).unwrap(); + let mut archive = zip::ZipArchive::new(file).unwrap(); + let mut xml = String::new(); + { + use std::io::Read; + archive.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap(); + } + eprintln!("DIRECT_OMML={} SIZE={}", xml.matches(" 100); + } + + let _ = fs::remove_dir_all(dir); +} + +/// OCR testi için üzerinde büyük puntolu metin bulunan görsel üretir (Windows GDI dahili yolu). +fn create_text_image(dir: &Path) -> Option { + #[cfg(windows)] + { + let out = dir.join("metin.png"); + let pages = app_lib::services::gdi_render::render_text_pages( + "MERHABA DUNYA\nLD CONVERTER 2026", + 64, + 1000, + 260, + 30, + ) + .ok()?; + let first = pages.into_iter().next()?; + first.save(&out).ok()?; + if out.exists() { + Some(out) + } else { + None + } + } + #[cfg(not(windows))] + { + let _ = dir; + None + } +} + +#[test] +fn ocr_recognizes_rendered_text() { + let dir = temp_dir("ocr_text"); + let Some(png) = create_text_image(&dir) else { + eprintln!("Test görseli üretilemedi (Python/Pillow yok), OCR testi atlandı"); + return; + }; + + match OcrEngine::recognize_image(&png.to_string_lossy()) { + Ok(text) => { + println!("OCR sonucu: {}", text); + let upper = text.to_uppercase(); + assert!( + upper.contains("MERHABA") || upper.contains("CONVERTER") || upper.contains("DUNYA"), + "OCR beklenen metni tanımadı: {:?}", + text + ); + + // OCR -> TXT / DOCX dönüşümü uçtan uca + let out = dir.join("out"); + fs::create_dir_all(&out).unwrap(); + let result = dispatcher_call( + vec![png.to_string_lossy().to_string()], + "img_to_txt", + ConversionOptions { + destination_folder: Some(out.to_string_lossy().to_string()), + ..Default::default() + }, + ) + .unwrap(); + let txt = PathBuf::from(&result.output_files[0]); + assert!(txt.exists()); + assert!(fs::read_to_string(&txt) + .unwrap() + .to_uppercase() + .contains("MERHABA")); + + let result = dispatcher_call( + vec![png.to_string_lossy().to_string()], + "img_to_docx", + ConversionOptions { + destination_folder: Some(out.to_string_lossy().to_string()), + ..Default::default() + }, + ) + .unwrap(); + assert!(PathBuf::from(&result.output_files[0]).exists()); + } + Err(e) => eprintln!("OCR motoru yok, atlandı: {}", e), + } + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn ocr_reports_clear_error_or_text() { + let dir = temp_dir("ocr"); + let src = dir.join("text.png"); + create_image(&src, 400, 200); + + // OCR motoru yoksa hata mesajı anlamlı olmalı, varsa sonuç dönmeli + match OcrEngine::recognize_image(&src.to_string_lossy()) { + Ok(text) => assert!(!text.is_empty()), + Err(err) => { + let msg = err.to_string(); + assert!(msg.contains("OCR"), "beklenmeyen hata: {}", msg); + } + } + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn archives_zip_7z_targz_create_and_extract() { + let dir = temp_dir("archives"); + let source = dir.join("ornek.txt"); + fs::write(&source, "LD Converter arşiv testi").unwrap(); + let inputs = vec![source.to_string_lossy().to_string()]; + + let zip = dir.join("a.zip"); + ArchiveEngine::create_zip(&inputs, &zip).unwrap(); + let zip2 = dir.join("b.zip"); + ArchiveEngine::create_zip(&inputs, &zip2).unwrap(); + assert!(zip.exists() && zip2.exists()); + + let extract_dir = dir.join("zip_out"); + ArchiveEngine::extract_archive(&zip.to_string_lossy(), &extract_dir, None).unwrap(); + assert!(extract_dir.join("ornek.txt").exists()); + + // Saf Rust 7Z oluşturma & çıkarma (harici 7z.exe gerektirmeden her sistemde çalışır) + let seven = dir.join("a.7z"); + ArchiveEngine::create_7z(&inputs, &seven).unwrap(); + assert!(seven.exists()); + let out7 = dir.join("7z_out"); + ArchiveEngine::extract_archive(&seven.to_string_lossy(), &out7, None).unwrap(); + assert_eq!(fs::read_to_string(out7.join("ornek.txt")).unwrap(), "LD Converter arşiv testi"); + + // Klasör yapılı saf Rust 7Z roundtrip testi + let folder = dir.join("alt_klasor"); + fs::create_dir_all(folder.join("ic")).unwrap(); + fs::write(folder.join("ic").join("not.txt"), "7z iç içe").unwrap(); + let folder_7z = dir.join("klasor.7z"); + ArchiveEngine::create_7z(&[folder.to_string_lossy().to_string()], &folder_7z).unwrap(); + let folder_out = dir.join("klasor_7z_out"); + ArchiveEngine::extract_archive(&folder_7z.to_string_lossy(), &folder_out, None).unwrap(); + assert_eq!( + fs::read_to_string(folder_out.join("alt_klasor").join("ic").join("not.txt")).unwrap(), + "7z iç içe" + ); + + if EngineResolver::resolve_7zip(None).is_some() { + let targz = dir.join("a.tar.gz"); + ArchiveEngine::create_tar_gz(&inputs, &targz).unwrap(); + assert!(targz.exists()); + assert!(fs::metadata(&targz).unwrap().len() > 0); + } else { + eprintln!("7-Zip yok, tar.gz testi atlandı"); + } + + // Zip Slip koruması + assert!(ArchiveEngine::extract_archive( + &dir.join("yok.zip").to_string_lossy(), + &dir.join("x"), + None + ) + .is_err()); + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn copy_folder_collects_files() { + let dir = temp_dir("copy_folder"); + let a = dir.join("bir.txt"); + let b = dir.join("iki.png"); + fs::write(&a, "a").unwrap(); + create_image(&b, 32, 32); + + let target = ArchiveEngine::copy_to_folder( + &[a.to_string_lossy().to_string(), b.to_string_lossy().to_string()], + &dir, + ) + .unwrap(); + assert!(target.is_dir()); + assert!(target.join("bir.txt").exists()); + assert!(target.join("iki.png").exists()); + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn builtin_document_engine_without_external_tools() { + use app_lib::services::DocumentEngine; + + let dir = temp_dir("builtin_docs"); + + // TXT -> DOCX -> TXT (Türkçe karakterler korunmalı) + let txt = dir.join("metin.txt"); + fs::write(&txt, "Merhaba dünya\nTürkçe: şğüıİÖÇ\n\nSon paragraf.").unwrap(); + let docx = DocumentEngine::convert(&txt.to_string_lossy(), "docx", &dir, true).unwrap(); + assert!(docx.exists()); + let back = DocumentEngine::extract_text(&docx.to_string_lossy()).unwrap(); + assert!(back.contains("Türkçe"), "metin geri okunamadı: {:?}", back); + assert!(back.contains("şğüıİÖÇ"), "Türkçe karakterler bozuldu: {:?}", back); + + // TXT -> PDF (GDI ile, harici motor yok) + let pdf = DocumentEngine::convert(&txt.to_string_lossy(), "pdf", &dir, true).unwrap(); + assert!(pdf.exists()); + assert!(PdfEngine::page_count(&pdf.to_string_lossy()).unwrap() >= 1); + + // TXT -> HTML + let html = DocumentEngine::convert(&txt.to_string_lossy(), "html", &dir, true).unwrap(); + let html_text = fs::read_to_string(&html).unwrap(); + assert!(html_text.contains("

        ")); + + // Markdown -> DOCX (dahili yedek yol) + let md = dir.join("basit.md"); + fs::write(&md, "# Başlık\n\nMetin $x^2$ formülü.\n").unwrap(); + let md_docx = DocumentEngine::convert(&md.to_string_lossy(), "docx", &dir, true).unwrap(); + assert!(md_docx.exists()); + let md_back = DocumentEngine::extract_text(&md_docx.to_string_lossy()).unwrap(); + assert!(md_back.contains("Başlık")); + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn dispatcher_image_zip_and_cancel() { + let dir = temp_dir("dispatcher_basic"); + let img = dir.join("resim.png"); + create_image(&img, 120, 90); + let out = dir.join("out"); + fs::create_dir_all(&out).unwrap(); + + let result = dispatcher_call( + vec![img.to_string_lossy().to_string()], + "jpg", + ConversionOptions { + destination_folder: Some(out.to_string_lossy().to_string()), + image_quality: 80, + target_width: Some(60), + ..Default::default() + }, + ) + .unwrap(); + let produced = PathBuf::from(&result.output_files[0]); + assert!(produced.exists()); + assert_eq!(produced.extension().unwrap(), "jpg"); + let loaded = image::open(&produced).unwrap(); + assert_eq!(loaded.width(), 60); + + // ZIP + let result = dispatcher_call( + vec![img.to_string_lossy().to_string()], + "zip", + ConversionOptions { + destination_folder: Some(out.to_string_lossy().to_string()), + ..Default::default() + }, + ) + .unwrap(); + assert!(PathBuf::from(&result.output_files[0]).exists()); + + // Görsellerden PDF + let result = dispatcher_call( + vec![img.to_string_lossy().to_string()], + "pdf", + ConversionOptions { + destination_folder: Some(out.to_string_lossy().to_string()), + ..Default::default() + }, + ) + .unwrap(); + let pdf = PathBuf::from(&result.output_files[0]); + assert_eq!(PdfEngine::page_count(&pdf.to_string_lossy()).unwrap(), 1); + + // İptal: bayrak önceden set edilirse Cancelled dönmeli + let runtime = tokio::runtime::Runtime::new().unwrap(); + let flag = Arc::new(AtomicBool::new(true)); + let cancelled = runtime.block_on(async move { + ConversionDispatcher::execute_task( + ProgressEmitter::silent(), + vec![img.to_string_lossy().to_string()], + "jpg".to_string(), + ConversionOptions::default(), + AppPreferences::default(), + flag, + "iptal".to_string(), + ) + .await + }); + let err = match cancelled { + Ok(_) => panic!("iptal edilen işlem hata dönmeli"), + Err(err) => err, + }; + assert!(err.to_string().contains("iptal"), "hata: {}", err); + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn jxl_and_avif_capability_handling() { + let dir = temp_dir("jxl_avif"); + let src = dir.join("kaynak.png"); + create_image(&src, 160, 120); + let opts = ConversionOptions::default(); + + // Saf Rust AVIF kodlama (FFmpeg olmadan daima çalışır) + let avif = ImageEngine::convert_single(&src.to_string_lossy(), "avif", &dir, &opts) + .expect("PNG -> AVIF saf Rust kodlama başarısız"); + assert!(avif.exists()); + assert_eq!(avif.extension().unwrap(), "avif"); + + if EngineResolver::resolve_ffmpeg(None).is_some() { + // AVIF -> PNG geri dönüş (kod çözme yolu FFmpeg gerektirir) + let back = + ImageEngine::convert_single(&avif.to_string_lossy(), "png", &dir, &opts).unwrap(); + assert!(back.exists()); + } + + // JPEG XL: destek varsa üretilmeli, yoksa anlaşılır hata vermeli (sessiz bozuk dosya olmamalı) + match ImageEngine::convert_single(&src.to_string_lossy(), "jxl", &dir, &opts) { + Ok(jxl) => { + assert!(jxl.exists()); + assert_eq!(jxl.extension().unwrap(), "jxl"); + } + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("JXL") || msg.contains("JPEG XL"), + "JXL hatası anlaşılır olmalı: {}", + msg + ); + } + } + + // Katalog: JXL desteklenmiyorsa seçenek hiç gösterilmemeli + let choices = app_lib::catalog::FormatCatalog::get_choices_for_files( + &[src.to_string_lossy().to_string()], + None, + false, + ); + assert!(!choices.iter().any(|c| c.id == "jxl")); + let choices_with_jxl = app_lib::catalog::FormatCatalog::get_choices_for_files( + &[src.to_string_lossy().to_string()], + None, + true, + ); + assert!(choices_with_jxl.iter().any(|c| c.id == "jxl")); + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn dispatcher_extract_and_overwrite_behaviour() { + let dir = temp_dir("dispatcher_archives"); + let out = dir.join("out"); + fs::create_dir_all(&out).unwrap(); + let dest = Some(out.to_string_lossy().to_string()); + + let a = dir.join("bir.txt"); + let b = dir.join("iki.txt"); + fs::write(&a, "bir").unwrap(); + fs::write(&b, "iki").unwrap(); + + // ZIP oluştur (iki dosya) + let zip_result = dispatcher_call( + vec![a.to_string_lossy().to_string(), b.to_string_lossy().to_string()], + "zip", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .unwrap(); + let zip_path = PathBuf::from(&zip_result.output_files[0]); + + // İkinci kez üret: üzerine yazma kapalı olduğu için yeni ad almalı + let zip_again = dispatcher_call( + vec![a.to_string_lossy().to_string(), b.to_string_lossy().to_string()], + "zip", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .unwrap(); + let zip_path2 = PathBuf::from(&zip_again.output_files[0]); + assert_ne!(zip_path, zip_path2, "üzerine yazma kapalıyken yeni dosya adı üretilmeli"); + assert!(zip_path.exists() && zip_path2.exists()); + + // Arşivi alt klasöre çıkar + let extract = dispatcher_call( + vec![zip_path.to_string_lossy().to_string()], + "extract_folder", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .unwrap(); + let extract_dir = PathBuf::from(&extract.output_files[0]); + assert!(extract_dir.is_dir(), "çıkarma klasörü oluşmalı"); + assert!(extract_dir.join("bir.txt").exists()); + assert!(extract_dir.join("iki.txt").exists()); + assert!(extract_dir + .file_name() + .unwrap() + .to_string_lossy() + .contains("Cikarilan")); + + // Saf Rust 7Z yönlendirmesi (harici 7z.exe gerektirmez) + let seven = dispatcher_call( + vec![a.to_string_lossy().to_string()], + "7z", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(PathBuf::from(&seven.output_files[0]).extension().unwrap(), "7z"); + + // TAR.GZ yönlendirmesi + if EngineResolver::resolve_7zip(None).is_some() { + let targz = dispatcher_call( + vec![a.to_string_lossy().to_string()], + "tar_gz", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .unwrap(); + assert!(PathBuf::from(&targz.output_files[0]) + .to_string_lossy() + .ends_with(".tar.gz")); + } + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn media_conversions_with_ffmpeg() { + let Some(ffmpeg) = EngineResolver::resolve_ffmpeg(None) else { + eprintln!("FFmpeg yok, medya testi atlandı"); + return; + }; + let dir = temp_dir("media"); + let wav = dir.join("ton.wav"); + assert!( + run_capture( + &ffmpeg, + &[ + "-y", + "-f", + "lavfi", + "-i", + "sine=frequency=440:duration=1", + "-c:a", + "pcm_s16le", + &wav.to_string_lossy(), + ], + ), + "test WAV üretilemedi" + ); + + let mp4 = dir.join("klip.mp4"); + let has_video = run_capture( + &ffmpeg, + &[ + "-y", + "-f", + "lavfi", + "-i", + "testsrc=size=160x120:rate=10:duration=1", + "-f", + "lavfi", + "-i", + "sine=frequency=440:duration=1", + "-c:v", + "libx264", + "-c:a", + "aac", + "-shortest", + &mp4.to_string_lossy(), + ], + ); + + let out = dir.join("out"); + fs::create_dir_all(&out).unwrap(); + let dest = Some(out.to_string_lossy().to_string()); + + let result = dispatcher_call( + vec![wav.to_string_lossy().to_string()], + "mp3", + ConversionOptions { + destination_folder: dest.clone(), + audio_bitrate_kbps: Some(128), + ..Default::default() + }, + ) + .unwrap(); + let mp3 = PathBuf::from(&result.output_files[0]); + assert!(mp3.exists() && fs::metadata(&mp3).unwrap().len() > 1000); + + let result = dispatcher_call( + vec![wav.to_string_lossy().to_string()], + "compress_audio", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ) + .unwrap(); + let compressed = PathBuf::from(&result.output_files[0]); + assert_eq!(compressed.extension().unwrap(), "mp3"); + assert!(compressed.exists()); + + if has_video { + let result = dispatcher_call( + vec![mp4.to_string_lossy().to_string()], + "mp3", + ConversionOptions { + destination_folder: dest.clone(), + start_time: Some("00:00:00".to_string()), + end_time: Some("00:00:00.5".to_string()), + ..Default::default() + }, + ) + .unwrap(); + assert!(PathBuf::from(&result.output_files[0]).exists()); + + let result = dispatcher_call( + vec![mp4.to_string_lossy().to_string()], + "compress_video", + ConversionOptions { + destination_folder: dest.clone(), + mute_audio: true, + ..Default::default() + }, + ) + .unwrap(); + let compressed_video = PathBuf::from(&result.output_files[0]); + assert_eq!(compressed_video.extension().unwrap(), "mp4"); + assert!(compressed_video.exists()); + } + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn documents_via_builtin_engine() { + let dir = temp_dir("docs"); + let out = dir.join("out"); + fs::create_dir_all(&out).unwrap(); + let dest = Some(out.to_string_lossy().to_string()); + + // TXT -> DOCX (dahili motor, harici program yok) + let txt = dir.join("notlar.txt"); + fs::write(&txt, "Merhaba dunya\nLD Converter").unwrap(); + let result = dispatcher_call( + vec![txt.to_string_lossy().to_string()], + "docx", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ); + match result { + Ok(res) => assert!(PathBuf::from(&res.output_files[0]).exists()), + Err(e) => panic!("TXT->DOCX (dahili) başarısız: {}", e), + } + + // TXT -> PDF (dahili, GDI) + let result = dispatcher_call( + vec![txt.to_string_lossy().to_string()], + "pdf", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ); + match result { + Ok(res) => { + let pdf = PathBuf::from(&res.output_files[0]); + assert!(pdf.exists()); + assert!(PdfEngine::page_count(&pdf.to_string_lossy()).unwrap() >= 1); + } + Err(e) => panic!("TXT->PDF (dahili) başarısız: {}", e), + } + + // Markdown (LaTeX) -> Denklem DOCX (Pandoc / gömülü motor) + let md = dir.join("formul.md"); + fs::write(&md, "# Baslik\n\nDenklem: $x^2 + y^2 = z^2$\n\nMetin.").unwrap(); + let result = dispatcher_call( + vec![md.to_string_lossy().to_string()], + "docx_math", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ); + match result { + Ok(res) => { + let docx = PathBuf::from(&res.output_files[0]); + assert!(docx.exists(), "denklem docx üretilemedi"); + assert!(fs::metadata(&docx).unwrap().len() > 1000); + } + Err(e) => eprintln!("Denklem DOCX motoru yok, atlandı: {}", e), + } + + // Markdown -> PDF (dahili motor) + let result = dispatcher_call( + vec![md.to_string_lossy().to_string()], + "pdf", + ConversionOptions { + destination_folder: dest.clone(), + ..Default::default() + }, + ); + match result { + Ok(res) => { + let pdf = PathBuf::from(&res.output_files[0]); + assert!(pdf.exists()); + assert!(PdfEngine::page_count(&pdf.to_string_lossy()).unwrap() >= 1); + } + Err(e) => panic!("MD->PDF (dahili) başarısız: {}", e), + } + + let _ = fs::remove_dir_all(dir); +} diff --git a/src-tauri/tests/image_quality_tests.rs b/src-tauri/tests/image_quality_tests.rs new file mode 100644 index 0000000..4826584 --- /dev/null +++ b/src-tauri/tests/image_quality_tests.rs @@ -0,0 +1,164 @@ +//! Görsel kalite testleri: alfa -> beyaz arka plan. + +use std::path::PathBuf; + +use image::GenericImageView; + +use app_lib::models::ConversionOptions; +use app_lib::services::ImageEngine; + +fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ld_img_{}_{}", name, uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn transparent_png_becomes_white_in_jpg() { + let dir = temp_dir("alpha"); + let source = dir.join("seffaf.png"); + + // Tamamen saydam (0,0,0,0) 32x32 PNG + let rgba = image::RgbaImage::from_pixel(32, 32, image::Rgba([0, 0, 0, 0])); + rgba.save(&source).unwrap(); + + let output = ImageEngine::convert_single( + &source.to_string_lossy(), + "jpg", + &dir, + &ConversionOptions::default(), + ) + .expect("PNG -> JPG başarısız"); + + let converted = image::open(&output).expect("JPG açılamadı").to_rgb8(); + let pixel = converted.get_pixel(5, 5); + eprintln!("KOSE_PIKSEL={:?}", pixel.0); + assert!( + pixel.0.iter().all(|channel| *channel > 245), + "saydam alan beyaz olmadı: {:?}", + pixel.0 + ); + + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn exif_orientation_6_rotates_dimensions() { + let dir = temp_dir("exif"); + let source = dir.join("dikey.jpg"); + + let image = image::RgbImage::from_pixel(10, 20, image::Rgb([200, 30, 30])); + image.save(&source).unwrap(); + + // SOI'den hemen sonra Orientation=6 (90° CW) APP1 segmenti ekle. + let app1: [u8; 36] = [ + 0xFF, 0xE1, 0x00, 0x22, b'E', b'x', b'i', b'f', 0x00, 0x00, b'I', b'I', 0x2A, 0x00, + 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x12, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]; + let original = std::fs::read(&source).unwrap(); + let mut with_exif = Vec::with_capacity(original.len() + app1.len()); + with_exif.extend_from_slice(&original[..2]); + with_exif.extend_from_slice(&app1); + with_exif.extend_from_slice(&original[2..]); + std::fs::write(&source, &with_exif).unwrap(); + + assert_eq!( + app_lib::services::image_engine::read_exif_orientation(&with_exif), + 6, + "EXIF orientation okunamadı" + ); + + let output = ImageEngine::convert_single( + &source.to_string_lossy(), + "png", + &dir, + &ConversionOptions::default(), + ) + .expect("EXIF yön düzeltmeli dönüşüm başarısız"); + + let converted = image::open(&output).unwrap(); + eprintln!("EXIF_DIMS={:?}", converted.dimensions()); + assert_eq!(converted.dimensions(), (20, 10), "90° döndürme uygulanmadı"); + + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn svg_rasterizes_in_memory_and_encodes_png_jpg_avif() { + let dir = temp_dir("svg_in_mem"); + let source = dir.join("vektor.svg"); + let svg_markup = r##" + +"##; + std::fs::write(&source, svg_markup).unwrap(); + + // 1) SVG -> PNG (ölçekli: target_width=128 -> 128x96) + let scale_opts = ConversionOptions { + target_width: Some(128), + ..Default::default() + }; + let png_out = ImageEngine::convert_single(&source.to_string_lossy(), "png", &dir, &scale_opts) + .expect("SVG -> PNG bellek içi dönüşüm başarısız"); + let png_img = image::open(&png_out).expect("SVG'den üretilen PNG açılamadı"); + assert_eq!(png_img.dimensions(), (128, 96)); + let center = png_img.to_rgba8().get_pixel(64, 48).0; + assert!(center[0] > 180 && center[1] < 60 && center[3] > 240, "merkez kırmızı değil: {:?}", center); + + // 2) SVG -> JPG (saydam köşeler beyaz arka plana oturmalı) + let jpg_out = ImageEngine::convert_single( + &source.to_string_lossy(), + "jpg", + &dir, + &ConversionOptions::default(), + ) + .expect("SVG -> JPG başarısız"); + let jpg_img = image::open(&jpg_out).expect("SVG'den üretilen JPG açılamadı").to_rgb8(); + let corner = jpg_img.get_pixel(2, 2).0; + assert!(corner.iter().all(|c| *c > 245), "SVG -> JPG köşe beyaz değil: {:?}", corner); + + // 3) SVG -> AVIF (FFmpeg olmadan tamamen saf Rust bellek içi) + let avif_out = ImageEngine::convert_single( + &source.to_string_lossy(), + "avif", + &dir, + &ConversionOptions::default(), + ) + .expect("SVG -> AVIF saf Rust dönüşümü başarısız"); + let avif_bytes = std::fs::read(&avif_out).unwrap(); + assert!(avif_bytes.len() > 64, "AVIF çıktısı beklenmedik şekilde küçük"); + assert!( + avif_bytes.windows(8).any(|w| w == b"ftypavif" || w == b"ftypavis"), + "AVIF kutu imzası (ftypavif) bulunamadı" + ); + + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn png_to_avif_runs_in_memory_without_ffmpeg() { + let dir = temp_dir("png_avif_in_mem"); + let source = dir.join("girdi.png"); + + let mut rgba = image::RgbaImage::new(32, 32); + for (x, y, px) in rgba.enumerate_pixels_mut() { + *px = image::Rgba([(x * 8) as u8, (y * 8) as u8, 120, 255]); + } + rgba.save(&source).unwrap(); + + let avif_out = ImageEngine::convert_single( + &source.to_string_lossy(), + "avif", + &dir, + &ConversionOptions::default(), + ) + .expect("PNG -> AVIF saf Rust dönüşümü başarısız"); + let avif_bytes = std::fs::read(&avif_out).unwrap(); + assert!(avif_bytes.len() > 64); + assert!( + avif_bytes.windows(8).any(|w| w == b"ftypavif" || w == b"ftypavis"), + "PNG -> AVIF geçersiz konteyner başlığı" + ); + + let _ = std::fs::remove_dir_all(dir); +} diff --git a/src-tauri/tests/jxl_tests.rs b/src-tauri/tests/jxl_tests.rs new file mode 100644 index 0000000..7dfeae7 --- /dev/null +++ b/src-tauri/tests/jxl_tests.rs @@ -0,0 +1,83 @@ +//! JPEG XL testleri: paketlenmiş cjxl/djxl ile PNG -> JXL -> PNG roundtrip. + +use std::path::PathBuf; + +use app_lib::models::ConversionOptions; +use app_lib::services::{EngineResolver, ImageEngine}; + +fn temp_dir(name: &str) -> PathBuf { + // ponytail: ara dosyalar depo kökündeki temp_out altında tutulur; sandbox'lı ortamda + // çalışma alanı içindeki cjxl/djxl yalnızca çalışma alanına yazabiliyor. + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("temp_out") + .join(format!("ld_jxl_{}_{}", name, uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn png_to_jxl_to_png_roundtrip() { + if !EngineResolver::jxl_available() { + eprintln!("ATLANDI: cjxl/djxl bulunamadı ve FFmpeg'de libjxl yok"); + return; + } + + let dir = temp_dir("roundtrip"); + let png_dir = dir.join("png"); + let jxl_dir = dir.join("jxl"); + let back_dir = dir.join("back"); + for d in [&png_dir, &jxl_dir, &back_dir] { + std::fs::create_dir_all(d).unwrap(); + } + + // 64x48 renk geçişli kaynak görsel + let source = png_dir.join("kaynak.png"); + let mut img = image::RgbImage::new(64, 48); + for (x, y, px) in img.enumerate_pixels_mut() { + *px = image::Rgb([(x * 4) as u8, (y * 5) as u8, ((x + y) * 2) as u8]); + } + image::DynamicImage::ImageRgb8(img) + .save_with_format(&source, image::ImageFormat::Png) + .unwrap(); + + let jxl = ImageEngine::convert_single( + &source.to_string_lossy(), + "jxl", + &jxl_dir, + &ConversionOptions { + image_quality: 90, + ..Default::default() + }, + ) + .expect("PNG -> JXL başarısız"); + + let header = std::fs::read(&jxl).unwrap(); + assert_eq!(&header[..2], &[0xFF, 0x0A], "JXL imzası hatalı"); + assert!(std::fs::metadata(&jxl).unwrap().len() > 100, "JXL çıktısı boş"); + + let back = ImageEngine::convert_single( + &jxl.to_string_lossy(), + "png", + &back_dir, + &ConversionOptions::default(), + ) + .expect("JXL -> PNG başarısız"); + + let decoded = image::open(&back).expect("dönen PNG açılamadı"); + assert_eq!( + (decoded.width(), decoded.height()), + (64, 48), + "boyutlar korunmadı" + ); + + // Kayıpsız olmasa da renkler yakın kalmalı (beyaz/siyah kayması yok). + let px = decoded.to_rgb8().get_pixel(32, 24).0; + assert!( + px.iter().all(|c| *c > 10 && *c < 245), + "piksel beklenmedik: {:?}", + px + ); + + let _ = std::fs::remove_dir_all(dir); +} diff --git a/src-tauri/tests/math_omml_tests.rs b/src-tauri/tests/math_omml_tests.rs new file mode 100644 index 0000000..b72a283 --- /dev/null +++ b/src-tauri/tests/math_omml_tests.rs @@ -0,0 +1,205 @@ +use std::fs; +use std::io::Read; +use std::path::PathBuf; +use std::process::{Command, Stdio}; + +use app_lib::services::{math_engine, omml, pdf_text, MathEngine}; + +#[cfg(windows)] +use std::os::windows::process::CommandExt; + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ld_omml_{}_{}", tag, uuid::Uuid::new_v4())); + fs::create_dir_all(&dir).unwrap(); + dir +} + +fn read_docx_xml(docx_path: &std::path::Path) -> String { + let file = fs::File::open(docx_path).expect("DOCX dosyası açılamadı"); + let mut archive = zip::ZipArchive::new(file).expect("DOCX geçerli bir ZIP arşivi değil"); + let mut doc_xml = String::new(); + archive + .by_name("word/document.xml") + .expect("word/document.xml bulunamadı") + .read_to_string(&mut doc_xml) + .unwrap(); + roxmltree::Document::parse(&doc_xml).expect("word/document.xml geçerli XML değil"); + doc_xml +} + +#[test] +fn omml_complex_formulas_produce_valid_word_elements() { + let cases = [ + ("fraction", r"\frac{a+b}{c-d}", &["", "", ""][..]), + ("sqrt", r"\sqrt{x^2 + 1}", &["", "", "", "3"][..]), + ("integral", r"\int_{0}^{1} x^2 \, dx", &["", "∫", "", ""][..]), + ("summation", r"\sum_{i=1}^{n} a_i", &["", "∑", "", ""][..]), + ("matrix", r"\begin{pmatrix} a & b \\ c & d \end{pmatrix}", &["", "", ""][..]), + ("sub_sup", r"x_i^2 + y_{k}^{n+1}", &["", "", ""][..]), + ("accent_ddot", r"\ddot{u}_i + \hat{x} + \tilde{y}", &["", "", ""][..]), + ("delimiters", r"\left( \frac{x}{y} \right)", &["", ""][..]), + ]; + + for (name, latex, required_tokens) in cases { + let out = omml::latex_to_omml(latex, false) + .unwrap_or_else(|e| panic!("{} formülü OMML'e çevrilemedi: {}", name, e)); + roxmltree::Document::parse(&out) + .unwrap_or_else(|e| panic!("{} için geçersiz OMML XML: {} -> {}", name, e, out)); + assert!(out.contains(" OMML DOCX başarısız"); + + assert!(out_docx.exists()); + let xml = read_docx_xml(&out_docx); + assert!(xml.contains("Öğrenci Değerlendirme Raporu")); + assert!(xml.contains("ğ, Ğ, ı, İ, ş, Ş, ç, Ç, ö, Ö, ü, Ü")); + assert!(xml.contains(""), "OMML kesir () yok"); + assert!(xml.contains(""), "OMML integral/toplam () yok"); + assert!(xml.contains(""), "OMML kök () yok"); + assert!(xml.contains(""), "OMML matris () yok"); + assert!(xml.contains(""), "OMML aksan () yok"); + + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn pure_rust_pdf_math_parity_on_test_pdf() { + let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let workspace_root = manifest_dir.parent().unwrap(); + let test_pdf = workspace_root.join("test.pdf"); + if !test_pdf.exists() { + eprintln!("test.pdf bulunamadı, parite testi atlandı."); + return; + } + + let extracted_md = pdf_text::extract_structured_markdown(&test_pdf.to_string_lossy()) + .expect("test.pdf saf Rust ile çözülemedi"); + eprintln!( + "PURE_RUST_MD_LEN={} SAMPLE=\n{}", + extracted_md.len(), + extracted_md.chars().take(700).collect::() + ); + let eq_preview: Vec<&str> = extracted_md + .lines() + .filter(|l| l.contains("\\frac") || l.contains('$')) + .take(10) + .collect(); + eprintln!("EQ_PREVIEW=\n{}", eq_preview.join("\n")); + assert!( + !extracted_md.trim().is_empty(), + "test.pdf yapılandırılmış Markdown çıktısı boş" + ); + + let dir = temp_dir("pdf_parity"); + let rust_out_dir = dir.join("rust"); + fs::create_dir_all(&rust_out_dir).unwrap(); + let rust_docx = MathEngine::convert_to_math_docx( + &test_pdf.to_string_lossy(), + &rust_out_dir, + true, + ) + .expect("Saf Rust test.pdf -> DOCX başarısız"); + + let rust_xml = read_docx_xml(&rust_docx); + let rust_omath = rust_xml.matches("").count(); + let rust_sub_sup = + rust_xml.matches("={} ={} ={}", + fs::metadata(&rust_docx).unwrap().len(), + rust_omath, + rust_frac, + rust_sub_sup + ); + assert!( + rust_omath > 0, + "test.pdf çıktısında hiç üretilmedi" + ); + + // Eğer diskte referans tools/ld_pdf_math_engine.exe varsa yan yana kıyasla + let py_engine = workspace_root.join("tools").join("ld_pdf_math_engine.exe"); + if py_engine.exists() { + let py_docx = dir.join("python.docx"); + let mut cmd = Command::new(&py_engine); + #[cfg(windows)] + cmd.creation_flags(0x08000000); + cmd.current_dir(py_engine.parent().unwrap()) + .stdin(Stdio::null()) + .arg(&test_pdf) + .arg(&py_docx) + .arg(""); + if let Ok(output) = cmd.output() { + if output.status.success() && py_docx.exists() { + let py_xml = read_docx_xml(&py_docx); + let py_omath = py_xml.matches("").count(); + eprintln!( + "PY_PDF_DOCX size={} ={} ={}", + fs::metadata(&py_docx).unwrap().len(), + py_omath, + py_frac + ); + assert!( + rust_omath >= py_omath.min(1), + "Saf Rust OMML sayısı beklenenden düşük: rust={}, py={}", + rust_omath, + py_omath + ); + } + } + } + + let _ = fs::remove_dir_all(dir); +} diff --git a/src-tauri/tests/office_engine_tests.rs b/src-tauri/tests/office_engine_tests.rs new file mode 100644 index 0000000..6c8932c --- /dev/null +++ b/src-tauri/tests/office_engine_tests.rs @@ -0,0 +1,99 @@ +//! Yeni ofis motoru: zengin AST, DOCX/HTML/PDF çıktıları. + +use std::fs; +use std::path::{Path, PathBuf}; + +use app_lib::services::office_model::Block; +use app_lib::services::OfficeEngine; + +fn fixture() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures_bicim.docx") +} + +fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ld_office_{}_{}", name, uuid::Uuid::new_v4())); + fs::create_dir_all(&dir).unwrap(); + dir +} + +fn document_xml(path: &Path) -> String { + let file = fs::File::open(path).unwrap(); + let mut archive = zip::ZipArchive::new(file).unwrap(); + let mut xml = String::new(); + { + use std::io::Read; + archive.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap(); + } + xml +} + +#[test] +fn docx_reader_captures_structure() { + let document = app_lib::services::office_docx::read_docx(&fixture()).expect("DOCX okunamadı"); + + let mut bold = false; + let mut italic = false; + let mut heading = false; + let mut cells = 0usize; + + for block in &document.blocks { + match block { + Block::Paragraph(paragraph) => { + heading |= paragraph.style.heading.is_some(); + for run in ¶graph.runs { + bold |= run.bold; + italic |= run.italic; + } + } + Block::Table(table) => { + cells += table.rows.iter().map(|row| row.len()).sum::(); + } + _ => {} + } + } + + assert!(heading, "başlık algılanmadı"); + assert!(bold, "kalın run algılanmadı"); + assert!(italic, "italik run algılanmadı"); + assert_eq!(cells, 4, "tablo hücreleri okunamadı"); +} + +#[test] +fn docx_to_docx_keeps_formatting() { + let dir = temp_dir("docx"); + let output = OfficeEngine::convert(&fixture().to_string_lossy(), "docx", &dir) + .expect("DOCX -> DOCX başarısız"); + let xml = document_xml(&output); + assert!(xml.contains(""), "kalın korunmadı"); + assert!(xml.contains(""), "italik korunmadı"); + assert!(xml.contains("Heading1"), "başlık stili korunmadı"); + assert!(xml.contains(""), "tablo korunmadı"); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn docx_to_pdf_is_vector_and_searchable() { + let dir = temp_dir("pdf"); + let output = OfficeEngine::convert(&fixture().to_string_lossy(), "pdf", &dir) + .expect("DOCX -> PDF başarısız"); + let bytes = fs::read(&output).unwrap(); + assert!(bytes.starts_with(b"%PDF")); + let text = app_lib::services::pdf_text::extract_pages(&output.to_string_lossy()) + .expect("PDF metni çıkarılamadı") + .join("\n"); + eprintln!("PDF_TEXT_LEN={}", text.len()); + assert!(text.contains("12345"), "metin katmanı yok"); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn docx_to_html_keeps_semantics() { + let dir = temp_dir("html"); + let output = OfficeEngine::convert(&fixture().to_string_lossy(), "html", &dir) + .expect("DOCX -> HTML başarısız"); + let html = fs::read_to_string(&output).unwrap(); + assert!(html.contains("

        "), "başlık HTML'e girmedi"); + assert!(html.contains(""), "kalın HTML'e girmedi"); + assert!(html.contains("

        "), "tablo HTML'e girmedi"); + let _ = fs::remove_dir_all(dir); +} diff --git a/src-tauri/tests/pdf_to_docx_quality_tests.rs b/src-tauri/tests/pdf_to_docx_quality_tests.rs new file mode 100644 index 0000000..edb737d --- /dev/null +++ b/src-tauri/tests/pdf_to_docx_quality_tests.rs @@ -0,0 +1,616 @@ +//! LD Converter v3.6.0 Saf Rust PDF -> DOCX & Geometrik Matematik Motoru Kalite Testleri. +//! +//! 8 Mimari Katmanın tamamını doğrular: +//! - Afin Matris ve Koordinat Dönüşümleri +//! - 5 Kademeli Font Çözücü & Türkçe/TeX Eşlemeleri +//! - 2B Uzaysal Matematik Rekonstrüksiyonu (OMML , , , ) +//! - Tablo Çözümleme ve Hücre Arkaplanları +//! - Uçtan Uca PDF -> DOCX Dönüşümü ve ZIP/OpenXML Doğrulaması + +use std::fs::File; +use std::io::Read; +use zip::ZipArchive; + +use app_lib::services::pdf_parser::matrix::{AffineMatrix, PageBox}; +use app_lib::services::pdf_parser::tex_font_maps::*; +use app_lib::services::pdf_parser::content_stream::{PdfChar, VectorLine, FilledRect}; +use app_lib::services::pdf_parser::math_reconstructor::MathReconstructor; +use app_lib::services::pdf_parser::table_reconstructor::TableReconstructor; +use app_lib::services::pdf_parser::convert_pdf_to_docx; + +#[test] +fn test_affine_matrix_operations() { + let m = AffineMatrix::new(2.0, 0.0, 0.0, 3.0, 10.0, 20.0); + let (px, py) = m.transform_point(5.0, 5.0); + assert_eq!(px, 20.0); // 2*5 + 10 = 20 + assert_eq!(py, 35.0); // 3*5 + 20 = 35 + + let inv = m.inverse().expect("Matris tersi alınabilir olmalı"); + let (ix, iy) = inv.transform_point(px, py); + assert!((ix - 5.0).abs() < 1e-6); + assert!((iy - 5.0).abs() < 1e-6); +} + +#[test] +fn test_page_box_top_left_normalization() { + // 600x800 pt standart A4 dikey sayfa + let page_box = PageBox::new([0.0, 0.0, 600.0, 800.0], 0); + // Sol-alt orijinli (100, 700) -> Sol-üst orijinli (100, 100) olmalı + let (tx, ty) = page_box.to_top_left_point(100.0, 700.0); + assert_eq!(tx, 100.0); + assert_eq!(ty, 100.0); +} + +#[test] +fn test_turkish_agl_and_tex_cmmi_mappings() { + assert_eq!(agl_glyph_name_to_unicode("gbreve").as_deref(), Some("ğ")); + assert_eq!(agl_glyph_name_to_unicode("Gbreve").as_deref(), Some("Ğ")); + assert_eq!(agl_glyph_name_to_unicode("scedilla").as_deref(), Some("ş")); + assert_eq!(agl_glyph_name_to_unicode("Scedilla").as_deref(), Some("Ş")); + assert_eq!(agl_glyph_name_to_unicode("dotlessi").as_deref(), Some("ı")); + assert_eq!(agl_glyph_name_to_unicode("Idotaccent").as_deref(), Some("İ")); + + // TeX CMMI Yunan karakterleri + assert_eq!(tex_cmmi_to_unicode(0x0B), Some('α')); + assert_eq!(tex_cmmi_to_unicode(0x0C), Some('β')); + assert_eq!(tex_cmmi_to_unicode(0x19), Some('π')); + assert_eq!(tex_cmmi_to_unicode(0x40), Some('∂')); + + // TeX CMSY sembolleri + assert_eq!(tex_cmsy_to_unicode(0x06), Some('±')); + assert_eq!(tex_cmsy_to_unicode(0x14), Some('≤')); + assert_eq!(tex_cmsy_to_unicode(0x15), Some('≥')); + assert_eq!(tex_cmsy_to_unicode(0x31), Some('∞')); +} + +#[test] +fn test_math_reconstruction_fraction() { + // Yatay kesir çizgisi y = 100, x: [50..100] + let line = VectorLine { + x1: 50.0, + y1: 100.0, + x2: 100.0, + y2: 100.0, + is_horizontal: true, + thickness: 1.0, + color: [0, 0, 0], + }; + + // Pay: y = 85 (çizginin üstü) + let char_a = PdfChar { + unicode: "a".to_string(), + x: 65.0, + y: 85.0, + width: 8.0, + height: 10.0, + font_size: 10.0, + font_name: "CMMI10".to_string(), + is_math: true, + is_bold: false, + is_italic: true, + color: [0, 0, 0], + }; + + // Payda: y = 105 (çizginin altı) + let char_b = PdfChar { + unicode: "b".to_string(), + x: 65.0, + y: 105.0, + width: 8.0, + height: 10.0, + font_size: 10.0, + font_name: "CMMI10".to_string(), + is_math: true, + is_bold: false, + is_italic: true, + color: [0, 0, 0], + }; + + let is_math = MathReconstructor::is_math_zone(&[char_a.clone(), char_b.clone()], std::slice::from_ref(&line)); + assert!(is_math, "Kesir çizgisi ve pay/payda matematik bölgesi olarak tanınmalı"); + + let omml = MathReconstructor::reconstruct_math(&[char_a, char_b], &[line]) + .expect("Kesir OMML XML'ine dönüştürülebilmeli"); + + assert!(omml.contains("")); + assert!(omml.contains("")); + assert!(omml.contains("")); + assert!(omml.contains("")); +} + +#[test] +fn test_table_reconstructor_with_shading() { + // 2 satır, 2 sütun çizgileri + let h1 = VectorLine { x1: 50.0, y1: 50.0, x2: 250.0, y2: 50.0, is_horizontal: true, thickness: 1.0, color: [0, 0, 0] }; + let h2 = VectorLine { x1: 50.0, y1: 100.0, x2: 250.0, y2: 100.0, is_horizontal: true, thickness: 1.0, color: [0, 0, 0] }; + let h3 = VectorLine { x1: 50.0, y1: 150.0, x2: 250.0, y2: 150.0, is_horizontal: true, thickness: 1.0, color: [0, 0, 0] }; + + let v1 = VectorLine { x1: 50.0, y1: 50.0, x2: 50.0, y2: 150.0, is_horizontal: false, thickness: 1.0, color: [0, 0, 0] }; + let v2 = VectorLine { x1: 150.0, y1: 50.0, x2: 150.0, y2: 150.0, is_horizontal: false, thickness: 1.0, color: [0, 0, 0] }; + let v3 = VectorLine { x1: 250.0, y1: 50.0, x2: 250.0, y2: 150.0, is_horizontal: false, thickness: 1.0, color: [0, 0, 0] }; + + let fill_header = FilledRect { + x: 50.0, + y: 50.0, + width: 200.0, + height: 50.0, + color: [220, 230, 242], // Açık mavi başlık + }; + + let text_cell1 = PdfChar { + unicode: "Hücre1".to_string(), + x: 60.0, + y: 65.0, + width: 40.0, + height: 10.0, + font_size: 10.0, + font_name: "Arial".to_string(), + is_math: false, + is_bold: true, + is_italic: false, + color: [0, 0, 0], + }; + + let mut consumed = Vec::new(); + let tables = TableReconstructor::extract_tables( + &[h1, h2, h3, v1, v2, v3], + &[fill_header], + &[text_cell1], + &[], + &mut consumed, + ); + + assert_eq!(tables.len(), 1, "1 tablo tespit edilmeli"); + let table = &tables[0]; + assert_eq!(table.rows.len(), 2, "2 satır olmalı"); + assert_eq!(table.rows[0].len(), 2, "2 sütun olmalı"); + assert_eq!(table.rows[0][0].shade, Some([220, 230, 242]), "Başlık hücresi dolgusu korunmalı"); + assert!(consumed.contains(&0), "Tablo içindeki karakterler tüketilmeli"); +} + +#[test] +fn test_end_to_end_pdf_to_docx_with_math() { + let temp_dir = std::env::temp_dir().join(format!("ld_test_{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&temp_dir).expect("Geçici klasör oluşturulmalı"); + + let pdf_path = temp_dir.join("test_sample.pdf"); + let docx_path = temp_dir.join("output_sample.docx"); + + // Dahili Saf Rust PDF motoru ile test belgesi üret + let mut doc = app_lib::services::office_model::Document::default(); + doc.blocks.push(app_lib::services::office_model::Block::Paragraph( + app_lib::services::office_model::Paragraph { + style: Default::default(), + runs: vec![app_lib::services::office_model::Run::plain("Türkçe Metin: LD Converter v3.6.0 Saf Rust Motoru")], + } + )); + doc.blocks.push(app_lib::services::office_model::Block::Paragraph( + app_lib::services::office_model::Paragraph { + style: Default::default(), + runs: vec![app_lib::services::office_model::Run::plain("Denklem: E = mc^2 ve a/b")], + } + )); + + app_lib::services::pdf_writer::write_pdf(&doc, &pdf_path).expect("PDF oluşturulmalı"); + + assert!(pdf_path.exists(), "PDF dosyası mevcut olmalı"); + + let result = convert_pdf_to_docx(&pdf_path.to_string_lossy(), &docx_path, true); + assert!(result.is_ok(), "Dönüşüm başarılı olmalı: {:?}", result.err()); + assert!(docx_path.exists(), "DOCX çıktısı üretilmiş olmalı"); + + // DOCX paketini aç ve içeriği doğrula + let docx_file = File::open(&docx_path).expect("DOCX dosyası açılmalı"); + let mut zip = ZipArchive::new(docx_file).expect("Geçerli bir ZIP/DOCX paketi olmalı"); + + let mut doc_xml = String::new(); + let mut xml_file = zip.by_name("word/document.xml").expect("word/document.xml pakette bulunmalı"); + xml_file.read_to_string(&mut doc_xml).expect("XML okunabilmeli"); + println!("DOC_XML CONTENT:\n{}", doc_xml); + + assert!(doc_xml.contains("xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\""), "Math XML isim alanı bulunmalı"); + assert!(doc_xml.contains("Türkçe Metin: LD Converter"), "Türkçe metin DOCX içine aktarılmış olmalı"); + + let _ = std::fs::remove_dir_all(&temp_dir); +} + +#[test] +fn test_comprehensive_v362_quality_verification() { + use app_lib::services::pdf_parser::layout_analyzer::{LayoutAnalyzer, PageContent}; + use app_lib::services::docx_writer::DocxWriter; + + let page_box = PageBox::new([0.0, 0.0, 600.0, 800.0], 0); + + // 1) Heading 1 (18pt, Kalın) + let mut chars = Vec::new(); + let h1_text = "1. GİRİŞ VE GENEL BAKIŞ"; + let mut cur_x = 50.0; + for ch in h1_text.chars() { + chars.push(PdfChar { + unicode: ch.to_string(), + x: cur_x, + y: 50.0, + width: 10.0, + height: 18.0, + font_size: 18.0, + font_name: "Arial-Bold".to_string(), + is_math: false, + is_bold: true, + is_italic: false, + color: [0, 0, 0], + }); + cur_x += 10.5; + } + + // 2) 5 Satırlık Gövde Paragrafı (11pt, satırlar arası 14pt aralık -> tek bir olmalı) + let body_sentences = [ + "Bu paragrafın birinci satırıdır ve akıcı bir şekilde devam eder.", + "İkinci satırda kelimeler arasında kesinlikle yapışma veya kopma olmaz.", + "Üçüncü satırda Türkçe karakterler ve boşluklar başarıyla korunur.", + "Dördüncü satırda satır sonu birleştirmesi kusursuz çalışır.", + "Beşinci satır ile birlikte bu paragraf tek bir Word paragrafı olmalıdır.", + ]; + + let mut cur_y = 90.0; + for sentence in &body_sentences { + let mut x = 50.0; + for ch in sentence.chars() { + let w = if ch == ' ' { 4.0 } else { 6.5 }; + chars.push(PdfChar { + unicode: ch.to_string(), + x, + y: cur_y, + width: w, + height: 11.0, + font_size: 11.0, + font_name: "Arial".to_string(), + is_math: false, + is_bold: false, + is_italic: false, + color: [0, 0, 0], + }); + x += w + 0.5; + } + cur_y += 14.0; // line_gap = 14.0 - 11.0 = 3.0 pt <= 0.65 * 11.0 (7.15 pt) + } + + // 3) Heading 2 (14pt, Kalın) + cur_y += 20.0; // Paragraf boşluğu + let h2_text = "1.1 Temel Matematiksel Bağıntılar"; + let mut h2_x = 50.0; + for ch in h2_text.chars() { + chars.push(PdfChar { + unicode: ch.to_string(), + x: h2_x, + y: cur_y, + width: 8.0, + height: 14.0, + font_size: 14.0, + font_name: "Arial-Bold".to_string(), + is_math: false, + is_bold: true, + is_italic: false, + color: [0, 0, 0], + }); + h2_x += 8.5; + } + + // 4) Nesir Cümlesi ve Satır İçi Matematik (Burada x ve y için...) + cur_y += 20.0; + let prose_math_sentence = "Burada x ve y için formül geçerlidir."; + let mut pm_x = 50.0; + for ch in prose_math_sentence.chars() { + let is_math_var = ch == 'x' || ch == 'y'; + let w = if ch == ' ' { 4.0 } else { 6.0 }; + chars.push(PdfChar { + unicode: ch.to_string(), + x: pm_x, + y: cur_y, + width: w, + height: 11.0, + font_size: 11.0, + font_name: if is_math_var { "CMMI10".to_string() } else { "Arial".to_string() }, + is_math: is_math_var, + is_bold: false, + is_italic: is_math_var, + color: [0, 0, 0], + }); + pm_x += w + 0.5; + } + + // 5) Blok Kesirli Denklem: a / b + cur_y += 30.0; + let frac_line = VectorLine { + x1: 100.0, + y1: cur_y + 10.0, + x2: 140.0, + y2: cur_y + 10.0, + is_horizontal: true, + thickness: 1.0, + color: [0, 0, 0], + }; + chars.push(PdfChar { + unicode: "a".to_string(), + x: 118.0, + y: cur_y, + width: 8.0, + height: 10.0, + font_size: 10.0, + font_name: "CMMI10".to_string(), + is_math: true, + is_bold: false, + is_italic: true, + color: [0, 0, 0], + }); + chars.push(PdfChar { + unicode: "b".to_string(), + x: 118.0, + y: cur_y + 15.0, + width: 8.0, + height: 10.0, + font_size: 10.0, + font_name: "CMMI10".to_string(), + is_math: true, + is_bold: false, + is_italic: true, + color: [0, 0, 0], + }); + + let page = PageContent { + page_box, + chars, + lines: vec![frac_line], + filled_rects: Vec::new(), + images: Vec::new(), + }; + + let office_doc = LayoutAnalyzer::analyze_document(vec![page], true); + + let temp_dir = std::env::temp_dir().join(format!("ld_test_v362_{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&temp_dir).expect("Geçici klasör"); + let docx_path = temp_dir.join("v362_quality.docx"); + + DocxWriter::create_from_document(&docx_path, &office_doc).expect("DOCX yazılabilmeli"); + + let docx_file = File::open(&docx_path).expect("DOCX dosyası açılmalı"); + let mut zip = ZipArchive::new(docx_file).expect("ZIP arşivi"); + let mut doc_xml = String::new(); + { + let mut xml_file = zip.by_name("word/document.xml").expect("document.xml"); + xml_file.read_to_string(&mut doc_xml).expect("XML okunabilmeli"); + } + + println!("V362 DOCUMENT XML:\n{}", doc_xml); + + // KONTROL 1: Başlık 1 ve Başlık 2 stilleri ile doğru yapısı + assert!(doc_xml.contains(""), "Heading 1 stili bulunmalı"); + assert!(doc_xml.contains(""), "Heading 2 stili bulunmalı"); + assert!(doc_xml.contains(""), "Kalın özelliği içinde olarak bulunmalı"); + let mut styles_xml = String::new(); + zip.by_name("word/styles.xml") + .expect("word/styles.xml bulunmalı") + .read_to_string(&mut styles_xml) + .expect("styles.xml okunabilmeli"); + assert!(styles_xml.contains("w:styleId=\"Heading1\""), "styles.xml içinde Heading1 tanımı olmalı"); + assert!(styles_xml.contains("w:styleId=\"Heading2\""), "styles.xml içinde Heading2 tanımı olmalı"); + + // KONTROL 2: Gövde paragraf boşlukları (1.08 satır aralığı) + assert!(doc_xml.contains("w:spacing w:before=\"0\" w:after=\"100\" w:line=\"260\""), "Gövde paragraflarında makul satır aralığı ve boşluk olmalı"); + + // KONTROL 3: 5 satırlık paragrafın tek bir içinde birleştiği kontrolü + let merged_p_count = doc_xml + .split("") + .filter(|p| { + p.contains("Bu paragrafın birinci satırıdır") + && p.contains("Beşinci satır ile birlikte bu paragraf tek bir Word paragrafı olmalıdır") + }) + .count(); + assert_eq!(merged_p_count, 1, "5 satırlık gövde paragrafı tek bir içinde birleşmeli"); + + // KONTROL 4: Kelimeler arasında yapışma olmamalı + assert!(!doc_xml.contains("Buparagrafın"), "Kelimeler birbirine yapışmamalı"); + assert!(!doc_xml.contains("B u p a r a g r a f"), "Harfler birbirinden ayrılmamalı"); + + // KONTROL 5: Gereksiz sayfa kırılması () olmamalı + assert!(!doc_xml.contains(""), "Tek sayfalı akışta gereksiz sayfa kırılması olmamalı"); + + // KONTROL 6: Kesirli blok denklem ve satır içi matematik + Türkçe kelime korunması + assert!(doc_xml.contains(""), "Kesir formülü () bulunmalı"); + assert!(doc_xml.contains(""), "Matematik XML () bulunmalı"); + assert!(doc_xml.contains("Burada "), "Satır içi matematik öncesi Türkçe kelime korunmalı"); + assert!(doc_xml.contains(" ve "), "Satır içi matematik arası Türkçe bağlaç korunmalı"); + assert!(doc_xml.contains("için formül geçerlidir."), "Satır içi matematik sonrası Türkçe metin korunmalı"); + + let _ = std::fs::remove_dir_all(&temp_dir); +} + +#[test] +fn test_real_multipage_pdf_tm_scale_headings_inline_math_and_no_pagebreak() { + use lopdf::content::{Content, Operation}; + use lopdf::{dictionary, Document, Object, Stream}; + + let temp_dir = std::env::temp_dir().join(format!("ld_real_pdf_{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&temp_dir).expect("Geçici klasör"); + let pdf_path = temp_dir.join("gercek_cok_sayfali.pdf"); + let docx_path = temp_dir.join("gercek_cikti.docx"); + + // Gerçek PDF yapısı üret (/F1 1 Tf ile Tm ölçekleme, sahte kalın, 5 satırlı paragraf, + // %70 üzeri dolu 1. sayfa + 2. sayfada Heading 2, satır içi E = mc^2 ve kesirli denklem) + let mut doc = Document::with_version("1.4"); + let pages_id = doc.new_object_id(); + + let font_regular_id = doc.add_object(dictionary! { + "Type" => "Font", + "Subtype" => "Type1", + "BaseFont" => "Helvetica", + "Encoding" => "WinAnsiEncoding", + }); + let font_bold_id = doc.add_object(dictionary! { + "Type" => "Font", + "Subtype" => "Type1", + "BaseFont" => "Helvetica-Bold", + "Encoding" => "WinAnsiEncoding", + }); + let resources_id = doc.add_object(dictionary! { + "Font" => dictionary! { + "F1" => font_regular_id, + "F2" => font_bold_id, + }, + }); + + let push_text = |ops: &mut Vec, font: &str, tf_sz: i64, tm_scale: i64, x: i64, y: i64, text: &str| { + ops.extend([ + Operation::new("BT", vec![]), + Operation::new("Tf", vec![font.into(), tf_sz.into()]), + Operation::new( + "Tm", + vec![tm_scale.into(), 0.into(), 0.into(), tm_scale.into(), x.into(), y.into()], + ), + Operation::new("Tj", vec![Object::string_literal(text)]), + Operation::new("ET", vec![]), + ]); + }; + + // Sayfa 1: /F1 1 Tf altında Tm [18 0 0 18] başlık + 5 satırlı uzun gövde paragrafı + sayfa alt %75'e inen satırlar + let mut ops1: Vec = Vec::new(); + push_text(&mut ops1, "F2", 1, 18, 50, 760, "1. GIRIS VE AMAC"); + + // 5 satırlı gövde paragrafı (y: 720, 706, 692, 678, 664 -> step 14pt on 10pt font => line_gap=4pt <= 6.5pt) + let para_lines = [ + "Bu belge cok sayfalik PDF donusum kalitesini test etmek icin uretilmistir.", + "Ikinci satir birinci satirin hemen altinda yer alir ve ayri paragraf olmamalidir.", + "Ucuncu satir boyunca kelimeler arasindaki bosluklar duzgun sekilde korunmalidir.", + "Dorduncu satir ile birlikte metin akisi kesintisiz sekilde devam etmektedir.", + "Besinci satir paragraf birlestirme algoritmasinin basarisini dogrulamaktadir.", + ]; + for (idx, line_str) in para_lines.iter().enumerate() { + let y = 720 - (idx as i64) * 14; + push_text(&mut ops1, "F1", 1, 10, 50, y, line_str); + } + + // Sayfa 1'in %70'in uzerinde doldugunu gostermek icin alt bolumde devam eden govde metni (y=180 on 842pt => top_y ~ 662 / 842 = 78.6%) + for row in 0..8 { + let y = 600 - row * 60; + push_text( + &mut ops1, + "F1", + 1, + 10, + 50, + y, + "Akademik govde metni sayfa boyunca duzenli araliklarla ilerlemektedir.", + ); + } + + let content1 = Content { operations: ops1 }.encode().expect("Stream 1 encode"); + let content1_id = doc.add_object(Stream::new(dictionary! {}, content1)); + + // Sayfa 2: 1.1 Temel Kavramlar (14pt baslik), satir ici E = mc^2 ve x_1 + x_2 = b/a kesirli denklem + let mut ops2: Vec = Vec::new(); + push_text(&mut ops2, "F2", 1, 14, 50, 760, "1.1 Temel Kavramlar"); + + // Satir ici matematik iceren normal cumle: "Burada E = mc^2 formulu gecerlidir." + push_text(&mut ops2, "F1", 10, 1, 50, 720, "Burada E = mc"); + push_text(&mut ops2, "F1", 7, 1, 111, 724, "2"); + push_text(&mut ops2, "F1", 10, 1, 117, 720, " formulu gecerlidir."); + + // Blok denklem: x_1 + x_2 = \frac{b}{a} (y_pdf = 660 civari) + // Yatay kesir cizgisi: (160, 663) -> (186, 663) + ops2.extend([ + Operation::new("w", vec![1.0.into()]), + Operation::new("m", vec![160.into(), 663.into()]), + Operation::new("l", vec![186.into(), 663.into()]), + Operation::new("S", vec![]), + ]); + + // Orta denklem: x_1 + x_2 = + push_text(&mut ops2, "F1", 10, 1, 100, 660, "x"); + push_text(&mut ops2, "F1", 7, 1, 106, 657, "1"); + push_text(&mut ops2, "F1", 10, 1, 112, 660, "+ x"); + push_text(&mut ops2, "F1", 7, 1, 128, 657, "2"); + push_text(&mut ops2, "F1", 10, 1, 138, 660, "="); + + // Pay 'b' (y=669) ve Payda 'a' (y=650) + push_text(&mut ops2, "F1", 10, 1, 170, 669, "b"); + push_text(&mut ops2, "F1", 10, 1, 170, 650, "a"); + + let content2 = Content { operations: ops2 }.encode().expect("Stream 2 encode"); + let content2_id = doc.add_object(Stream::new(dictionary! {}, content2)); + + let page1_id = doc.add_object(dictionary! { + "Type" => "Page", + "Parent" => pages_id, + "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()], + "Resources" => resources_id, + "Contents" => content1_id, + }); + let page2_id = doc.add_object(dictionary! { + "Type" => "Page", + "Parent" => pages_id, + "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()], + "Resources" => resources_id, + "Contents" => content2_id, + }); + let pages = dictionary! { + "Type" => "Pages", + "Kids" => vec![page1_id.into(), page2_id.into()], + "Count" => 2, + }; + doc.objects.insert(pages_id, Object::Dictionary(pages)); + let catalog_id = doc.add_object(dictionary! { + "Type" => "Catalog", + "Pages" => pages_id, + }); + doc.trailer.set("Root", catalog_id); + doc.save(&pdf_path).expect("PDF kaydedilmeli"); + + let out = convert_pdf_to_docx(&pdf_path.to_string_lossy(), &docx_path, true) + .expect("Çok sayfalı PDF -> DOCX başarısız"); + assert!(out.exists()); + + let docx_file = File::open(&docx_path).expect("DOCX açılmalı"); + let mut zip = ZipArchive::new(docx_file).expect("ZIP"); + let mut doc_xml = String::new(); + zip.by_name("word/document.xml") + .expect("document.xml") + .read_to_string(&mut doc_xml) + .expect("XML okunmalı"); + + println!("REAL MULTIPAGE DOCUMENT.XML:\n{}", doc_xml); + + // 1) Tm ölçekli başlıklar (/F1 1 Tf + Tm 18/14) doğru algılanıp Heading1 ve Heading2 + almış mı? + assert!(doc_xml.contains(""), "Tm 18pt başlık Heading1 olmalı"); + assert!(doc_xml.contains(""), "Tm 14pt başlık Heading2 olmalı"); + assert!(doc_xml.contains(""), "Başlıklarda bulunmalı"); + assert!(doc_xml.contains("1. GIRIS VE AMAC")); + assert!(doc_xml.contains("1.1 Temel Kavramlar")); + + // 2) 5 satırlı paragraf tek içinde birleşmiş mi? + let merged_count = doc_xml + .split("") + .filter(|p| { + p.contains("Bu belge cok sayfalik PDF donusum kalitesini test etmek icin uretilmistir.") + && p.contains("Besinci satir paragraf birlestirme algoritmasinin basarisini dogrulamaktadir.") + }) + .count(); + assert_eq!(merged_count, 1, "5 satırlık paragraf tek içinde birleşmeli"); + + // 3) Dolu 1. sayfadan 2. sayfaya gereksiz konmamış mı? + assert!(!doc_xml.contains(""), "Dolu sayfadan sonra gereksiz pageBreak basılmamalı"); + + // 4) Satır içi matematik: nesir metni normal , E = mc^2 satır içi () olmuş mu? + assert!(doc_xml.contains("Burada "), "Nesir başlangıcı korunmalı"); + assert!(doc_xml.contains("formulu gecerlidir."), "Nesir devamı korunmalı"); + assert!(doc_xml.contains(""), "mc^2 üst simgesi olmalı"); + + // 5) Blok denklem: x_1 + x_2 = \frac{b}{a} hem hem üretmiş mi ve kesir solda kalmamış mı? + assert!(doc_xml.contains(""), "Blok denklem içinde olmalı"); + assert!(doc_xml.contains(""), "x_1 / x_2 alt simgesi olmalı"); + assert!(doc_xml.contains(""), "b/a kesri olmalı"); + + let x1_pos = doc_xml.find("x").unwrap_or(usize::MAX); + let frac_pos = doc_xml.find("").unwrap_or(0); + assert!(x1_pos < frac_pos, "Kesir x_1 + x_2 = ifadesinin sağına yerleştirilmeli (sol-sağ sırası)"); + + let _ = std::fs::remove_dir_all(&temp_dir); +} diff --git a/src-tauri/tests/unit_tests.rs b/src-tauri/tests/unit_tests.rs new file mode 100644 index 0000000..3e5cfe4 --- /dev/null +++ b/src-tauri/tests/unit_tests.rs @@ -0,0 +1,232 @@ +use std::fs::{self, File}; + +use app_lib::catalog::FormatCatalog; +use app_lib::models::{AppPreferences, ConversionOptions, HistoryEntry, OutputDirectoryMode, ThemeMode}; +use app_lib::services::{ArchiveEngine, ImageEngine}; + +#[test] +fn test_format_catalog_extensions() { + assert_eq!(FormatCatalog::normalize_extension("photo.JPEG"), "jpg"); + assert_eq!(FormatCatalog::normalize_extension("doc.markdown"), "md"); + assert_eq!(FormatCatalog::normalize_extension("graphic.jpegxl"), "jxl"); + assert_eq!(FormatCatalog::normalize_extension("image.PNG"), "png"); + assert_eq!(FormatCatalog::normalize_extension("video.MP4"), "mp4"); + assert_eq!(FormatCatalog::normalize_extension("audio.FLAC"), "flac"); + assert_eq!(FormatCatalog::normalize_extension("archive.TGZ"), "gz"); +} + +#[test] +fn test_format_catalog_classification() { + assert!(FormatCatalog::is_image("test.png")); + assert!(FormatCatalog::is_image("test.jxl")); + assert!(FormatCatalog::is_image("test.webp")); + assert!(!FormatCatalog::is_image("test.pdf")); + + assert!(FormatCatalog::is_video("clip.mp4")); + assert!(FormatCatalog::is_video("movie.mkv")); + assert!(!FormatCatalog::is_video("song.mp3")); + + assert!(FormatCatalog::is_audio("song.mp3")); + assert!(FormatCatalog::is_audio("recording.wav")); + + assert!(FormatCatalog::is_pdf("document.pdf")); + assert!(FormatCatalog::is_markdown("notes.md")); + assert!(FormatCatalog::is_document("notes.md")); + assert!(FormatCatalog::is_document("sheet.xlsx")); + + assert!(FormatCatalog::is_archive("backup.zip")); + assert!(FormatCatalog::is_archive("data.7z")); +} + +#[test] +fn test_format_catalog_choices_markdown_includes_docx_math() { + let files = vec!["formulas.md".to_string()]; + let choices = FormatCatalog::get_choices_for_files(&files, None, true); + assert!(!choices.is_empty()); + assert!(choices.iter().any(|c| c.id == "docx")); + assert!(choices.iter().any(|c| c.id == "docx_math" && c.display_name == "Denklem DOCX")); + assert!(choices.iter().any(|c| c.id == "pdf")); +} + +#[test] +fn test_format_catalog_choices_images() { + let files = vec!["photo.png".to_string()]; + let choices = FormatCatalog::get_choices_for_files(&files, None, true); + assert!(choices.iter().any(|c| c.id == "jpg")); + assert!(choices.iter().any(|c| c.id == "webp")); + assert!(choices.iter().any(|c| c.id == "jxl")); + assert!(choices.iter().any(|c| c.id == "qr_read")); +} + +#[test] +fn test_format_catalog_favorites_filter() { + let files = vec!["photo.png".to_string()]; + let hidden = vec!["bmp".to_string(), "tiff".to_string()]; + let choices = FormatCatalog::get_choices_for_files(&files, Some(&hidden), true); + assert!(!choices.iter().any(|c| c.id == "bmp")); + assert!(!choices.iter().any(|c| c.id == "tiff")); + assert!(choices.iter().any(|c| c.id == "jpg")); +} + +#[test] +fn test_image_engine_conversion_and_resize() { + let temp_dir = std::env::temp_dir().join(format!("ld_test_img_{}", uuid::Uuid::new_v4())); + fs::create_dir_all(&temp_dir).unwrap(); + + let input_path = temp_dir.join("test_input.png"); + // Create a 200x150 colored image + let img = image::RgbImage::from_fn(200, 150, |x, y| { + image::Rgb([(x % 255) as u8, (y % 255) as u8, 128]) + }); + img.save(&input_path).unwrap(); + + let opts = ConversionOptions { + target_width: Some(100), + target_height: Some(75), + image_quality: 85, + ..Default::default() + }; + + // Convert to JPG + let jpg_result = ImageEngine::convert_single( + &input_path.to_string_lossy(), + "jpg", + &temp_dir, + &opts, + ) + .unwrap(); + + assert!(jpg_result.exists()); + assert_eq!(jpg_result.extension().unwrap(), "jpg"); + + let loaded = image::open(&jpg_result).unwrap(); + assert_eq!(loaded.width(), 100); + assert_eq!(loaded.height(), 75); + + // Convert to WebP + let webp_result = ImageEngine::convert_single( + &input_path.to_string_lossy(), + "webp", + &temp_dir, + &opts, + ) + .unwrap(); + assert!(webp_result.exists()); + assert_eq!(webp_result.extension().unwrap(), "webp"); + + let _ = fs::remove_dir_all(temp_dir); +} + +#[test] +fn test_image_unique_path_generation() { + let temp_dir = std::env::temp_dir().join(format!("ld_test_uniq_{}", uuid::Uuid::new_v4())); + fs::create_dir_all(&temp_dir).unwrap(); + + let file1 = temp_dir.join("output.png"); + File::create(&file1).unwrap(); + + let unique = ImageEngine::get_unique_path(&file1, false); + assert_ne!(file1, unique); + assert!(unique.to_string_lossy().contains("output (1).png")); + + let _ = fs::remove_dir_all(temp_dir); +} + +#[test] +fn test_archive_engine_zip_and_slip_security() { + let temp_dir = std::env::temp_dir().join(format!("ld_test_zip_{}", uuid::Uuid::new_v4())); + let extract_dir = temp_dir.join("extracted"); + fs::create_dir_all(&temp_dir).unwrap(); + + let file1 = temp_dir.join("sample.txt"); + fs::write(&file1, "LD Converter Tauri v2 Rust Test").unwrap(); + + let zip_dest = temp_dir.join("test_archive.zip"); + let input_paths = vec![file1.to_string_lossy().to_string()]; + + // 1. Create ZIP + let created = ArchiveEngine::create_zip(&input_paths, &zip_dest).unwrap(); + assert!(created.exists()); + assert!(fs::metadata(&created).unwrap().len() > 0); + + // 2. Extract ZIP + let extracted_path = ArchiveEngine::extract_archive( + &created.to_string_lossy(), + &extract_dir, + None, + ) + .unwrap(); + assert!(extracted_path.exists()); + + let extracted_file = extract_dir.join("sample.txt"); + assert!(extracted_file.exists()); + let content = fs::read_to_string(extracted_file).unwrap(); + assert_eq!(content, "LD Converter Tauri v2 Rust Test"); + + let _ = fs::remove_dir_all(temp_dir); +} + +#[test] +fn test_preferences_serialization() { + let prefs = AppPreferences { + theme: ThemeMode::Dark, + output_directory_mode: OutputDirectoryMode::Desktop, + default_image_quality: 95, + start_with_windows: false, + ..Default::default() + }; + + let json = serde_json::to_string(&prefs).unwrap(); + let deserialized: AppPreferences = serde_json::from_str(&json).unwrap(); + + assert_eq!(deserialized.theme, ThemeMode::Dark); + assert_eq!(deserialized.output_directory_mode, OutputDirectoryMode::Desktop); + assert_eq!(deserialized.default_image_quality, 95); + assert!(deserialized.auto_update_on_startup); + assert!(!deserialized.start_with_windows); + + // Eski preferences.json dosyalarındaki miras alanlar sorunsuz yoksayılmalıdır. + let legacy_json = r#"{ + "enabled": true, + "drag_modifier": "Shift", + "output_directory_mode": "SameAsSource", + "custom_output_directory": "", + "overwrite_existing": false, + "play_sound_effects": true, + "theme": "Dark", + "default_image_quality": 100, + "custom_ffmpeg_path": "", + "custom_pandoc_path": "", + "custom_seven_zip_path": "", + "favorite_format_ids": ["bmp"], + "auto_update_on_startup": true, + "start_with_windows": true, + "settings_version": 2 + }"#; + let legacy_deserialized: AppPreferences = serde_json::from_str(legacy_json).unwrap(); + assert!(legacy_deserialized.start_with_windows); + assert_eq!(legacy_deserialized.default_image_quality, 100); +} + +#[test] +fn test_history_serialization() { + let entry = HistoryEntry { + id: "task-123".to_string(), + title: "test.pdf".to_string(), + format_summary: "DOCX".to_string(), + input_files: vec!["C:/path/test.pdf".to_string()], + output_files: vec!["C:/path/test.docx".to_string()], + original_size_bytes: 1024, + output_size_bytes: 2048, + timestamp: chrono::Utc::now(), + success: true, + error_message: None, + }; + + let json = serde_json::to_string(&entry).unwrap(); + let deserialized: HistoryEntry = serde_json::from_str(&json).unwrap(); + + assert_eq!(deserialized.id, "task-123"); + assert_eq!(deserialized.format_summary, "DOCX"); + assert!(deserialized.success); +} diff --git a/src/App.tsx b/src/App.tsx new file mode 100644 index 0000000..888749b --- /dev/null +++ b/src/App.tsx @@ -0,0 +1,142 @@ +import React, { useEffect, useState } from "react"; +import { getCurrentWindow } from "@tauri-apps/api/window"; +import { listen } from "@tauri-apps/api/event"; +import { AppHeader, type TabId } from "./components/AppHeader"; +import { AppFooter } from "./components/AppFooter"; +import { ConvertView } from "./components/ConvertView"; +import { LibraryView } from "./components/LibraryView"; +import { QuickToolsView } from "./components/QuickToolsView"; +import { SettingsModal } from "./components/SettingsModal"; +import { QrResultModal } from "./components/QrResultModal"; +import { UpdateModal } from "./components/UpdateModal"; +import { UpdateBanner } from "./components/UpdateBanner"; +import { ConversionModal } from "./components/ConversionModal"; +import { Toast } from "./components/Toast"; +import { useAppStore } from "./stores/useAppStore"; +import { tauriApi } from "./lib/tauri"; + +export const App: React.FC = () => { + const { + setActiveModal, + loadPreferences, + loadHistory, + loadEngineStatus, + setSelectedFiles, + addSelectedFiles, + checkForUpdates, + preferences, + } = useAppStore(); + const [tab, setTab] = useState("convert"); + + useEffect(() => { + loadPreferences().then(() => { + checkForUpdates(true).catch(() => {}); + }); + loadHistory(); + loadEngineStatus(); + setSelectedFiles([]); + + let unlistenProgress: (() => void) | null = null; + let unlistenWindowDrop: (() => void) | null = null; + const unlisteners: Array<() => void> = []; + let isMounted = true; + + tauriApi + .onConversionProgress((payload) => { + const state = useAppStore.getState(); + if (!state.isConverting) return; + if (state.currentProgress?.task_id && payload.task_id !== state.currentProgress.task_id) return; + useAppStore.setState({ currentProgress: payload }); + }) + .then((unlisten) => { + if (!isMounted) unlisten(); + else unlistenProgress = unlisten; + }); + + // Ana pencereye sürükle-bırak + getCurrentWindow() + .onDragDropEvent((event) => { + if (event.payload.type === "drop" && event.payload.paths.length > 0) { + void addSelectedFiles(event.payload.paths); + setTab("convert"); + } + }) + .then((unlisten) => { + if (!isMounted) unlisten(); + else unlistenWindowDrop = unlisten; + }) + .catch(() => {}); + + listen("history-changed", () => { + void loadHistory(); + }).then((un) => (isMounted ? unlisteners.push(un) : un())); + + listen<{ engine: string; status: string; message: string }>("engine-update", (event) => { + const { status, message } = event.payload; + if (status === "error") { + useAppStore.getState().setToast({ type: "error", message: `Motor güncellenemedi: ${message}` }); + } else if (status === "installing" || status === "updating") { + useAppStore.getState().setToast({ type: "info", message }); + } else { + void loadEngineStatus(); + } + }).then((un) => (isMounted ? unlisteners.push(un) : un())); + + listen("engines-ready", () => { + void loadEngineStatus(); + }).then((un) => (isMounted ? unlisteners.push(un) : un())); + + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") { + setActiveModal("none"); + } else if (event.ctrlKey && event.key === ",") { + event.preventDefault(); + const current = useAppStore.getState().activeModal; + setActiveModal(current === "settings" ? "none" : "settings"); + } + }; + window.addEventListener("keydown", handleKeyDown); + + return () => { + isMounted = false; + unlistenProgress?.(); + unlistenWindowDrop?.(); + unlisteners.forEach((un) => un()); + window.removeEventListener("keydown", handleKeyDown); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + useEffect(() => { + const theme = preferences?.theme ?? "Dark"; + const media = window.matchMedia("(prefers-color-scheme: light)"); + const apply = () => { + const light = theme === "Light" || (theme === "System" && media.matches); + document.documentElement.dataset.theme = light ? "light" : "dark"; + }; + apply(); + media.addEventListener("change", apply); + return () => media.removeEventListener("change", apply); + }, [preferences?.theme]); + + return ( +
        + + + + {tab === "convert" && } + {tab === "library" && } + {tab === "tools" && } + + + + + + + + +
        + ); +}; + +export default App; diff --git a/src/Donustur.Core/Catalog/FormatCatalog.cs b/src/Donustur.Core/Catalog/FormatCatalog.cs deleted file mode 100644 index 7674444..0000000 --- a/src/Donustur.Core/Catalog/FormatCatalog.cs +++ /dev/null @@ -1,215 +0,0 @@ -using Donustur.Core.Models; - -namespace Donustur.Core.Catalog; - -public static class FormatCatalog -{ - private static readonly HashSet ImageExts = new(StringComparer.OrdinalIgnoreCase) - { - "jpg", "jpeg", "png", "webp", "avif", "bmp", "tiff", "tif", "gif", "ico", "svg", "heic", "heif" - }; - - private static readonly HashSet VideoExts = new(StringComparer.OrdinalIgnoreCase) - { - "mp4", "mkv", "avi", "mov", "webm", "flv", "wmv", "m4v" - }; - - private static readonly HashSet AudioExts = new(StringComparer.OrdinalIgnoreCase) - { - "mp3", "wav", "aac", "m4a", "flac", "ogg", "opus", "wma" - }; - - private static readonly HashSet DocumentExts = new(StringComparer.OrdinalIgnoreCase) - { - "docx", "doc", "pptx", "ppt", "xlsx", "xls", "odt", "rtf", "txt", "md", "html", "htm", "epub" - }; - - private static readonly HashSet ArchiveExts = new(StringComparer.OrdinalIgnoreCase) - { - "zip", "7z", "tar", "gz", "tgz", "rar" - }; - - public static string NormalizeExtension(string path) - { - if (string.IsNullOrWhiteSpace(path)) return string.Empty; - if (Directory.Exists(path)) return "folder"; - - string ext = Path.GetExtension(path).TrimStart('.').ToLowerInvariant(); - return ext switch - { - "jpeg" or "jpe" => "jpg", - "heif" => "heic", - "markdown" => "md", - "tgz" => "gz", - "htm" => "html", - "tif" => "tiff", - _ => ext - }; - } - - public static bool IsDirectory(string path) => !string.IsNullOrWhiteSpace(path) && Directory.Exists(path); - public static bool IsImage(string path) => !IsDirectory(path) && ImageExts.Contains(NormalizeExtension(path)); - public static bool IsVideo(string path) => !IsDirectory(path) && VideoExts.Contains(NormalizeExtension(path)); - public static bool IsAudio(string path) => !IsDirectory(path) && AudioExts.Contains(NormalizeExtension(path)); - public static bool IsDocument(string path) => !IsDirectory(path) && DocumentExts.Contains(NormalizeExtension(path)); - public static bool IsPdf(string path) => !IsDirectory(path) && NormalizeExtension(path) == "pdf"; - public static bool IsArchive(string path) => !IsDirectory(path) && ArchiveExts.Contains(NormalizeExtension(path)); - - /// - /// Gelen dosya listesine göre çark üzerinde gösterilecek en uygun seçenekleri üretir. - /// 6 ila 8 dilim ideal bir çark deneyimi sağlar. - /// - public static IReadOnlyList GetChoicesForFiles(IReadOnlyList filePaths) - { - if (filePaths.Count == 0) - { - return GetDefaultChoices(); - } - - bool anyDirs = filePaths.Any(IsDirectory); - if (anyDirs) - { - return new List - { - new("zip", "ZIP Arşivi Oluştur", "Arşiv", "Archive", "Seçili klasör ve dosyaları ZIP arşivine sıkıştır"), - new("7z", "7Z Arşivi Oluştur", "Arşiv", "Archive", "Ultra sıkıştırma ile 7Z arşivi oluştur"), - new("tar_gz", "TAR.GZ Yap", "Arşiv", "Archive", "Linux uyumlu .tar.gz paketi oluştur"), - new("copy_folder", "Yeni Klasöre Topla", "Dosya", "Folder", "İçeriği yeni bir klasörde organize et") - }; - } - - bool allImages = filePaths.All(IsImage); - bool allVideos = filePaths.All(IsVideo); - bool allAudios = filePaths.All(IsAudio); - bool allPdfs = filePaths.All(IsPdf); - bool allDocs = filePaths.All(IsDocument); - bool allArchives = filePaths.All(IsArchive); - - // Görseller - if (allImages) - { - var list = new List - { - new("png", "PNG", "Görsel", "Image", "Kayıpsız PNG formatına dönüştür"), - new("jpg", "JPG", "Görsel", "Image", "Yüksek uyumlu JPG formatına dönüştür"), - new("webp", "WebP", "Görsel", "Web", "Modern, hafif WebP formatına dönüştür"), - new("avif", "AVIF", "Görsel", "Sparkle", "Yeni nesil ultra sıkıştırılmış AVIF"), - new("pdf", "PDF", "Belge", "Pdf", "Görsellerden PDF belgesi oluştur"), - new("ico", "ICO (İkon)", "Görsel", "Icon", "Windows simgesi (.ico) oluştur") - }; - - if (filePaths.Count == 1) - { - list.Add(new("qr_read", "QR Oku", "Araç", "QrCode", "Görseldeki QR kodu tara ve çöz")); - list.Add(new("compress_image", "Sıkıştır", "Optimizasyon", "Compress", "Kalite kaybı olmadan boyutu küçült")); - } - else - { - list.Add(new("gif", "Animasyonlu GIF", "Görsel", "Sparkle", "Görsellerden hareketli GIF oluştur")); - list.Add(new("zip", "ZIP Arşivi", "Arşiv", "Archive", "Tüm görselleri tek ZIP dosyası yap")); - list.Add(new("compress_image", "Hepsini Sıkıştır", "Optimizasyon", "Compress", "Tüm görselleri optimize et")); - } - return list; - } - - // PDF'ler - if (allPdfs) - { - var list = new List - { - new("pdf_to_images", "Sayfaları PNG Yap", "Görsel", "Image", "PDF sayfalarını yüksek çözünürlüklü PNG'ye aktar"), - new("pdf_to_jpg", "Sayfaları JPG Yap", "Görsel", "Image", "PDF sayfalarını JPG resimleri olarak kaydet"), - new("pdf_to_txt", "Metin Çıkar (TXT)", "Belge", "Text", "PDF içindeki tüm metinleri TXT olarak kaydet"), - new("pdf_to_docx", "DOCX Yap", "Belge", "Document", "Word belgesine (.docx) dönüştür"), - new("qr_read", "QR Oku", "Araç", "QrCode", "PDF sayfalarındaki QR kodları tara") - }; - - if (filePaths.Count > 1) - { - list.Insert(0, new("pdf_merge", "PDF'leri Birleştir", "Belge", "PdfMerge", "Tüm PDF'leri tek bir dosyada birleştir")); - } - else - { - list.Add(new("pdf_split", "Sayfaları Ayır", "Belge", "Split", "Her sayfayı ayrı bir PDF yap")); - } - list.Add(new("zip", "ZIP Arşivi", "Arşiv", "Archive", "PDF'leri ZIP olarak arşivle")); - return list; - } - - // Belgeler (DOCX, PPTX, XLSX, TXT, HTML, MD...) - if (allDocs) - { - return new List - { - new("pdf", "PDF Yap", "Belge", "Pdf", "Ofis belgesini PDF formatına dönüştür"), - new("docx", "DOCX Yap", "Belge", "Document", "Modern Word belgesine çevir"), - new("txt", "Düz Metin (TXT)", "Belge", "Text", "Yalnızca metin içeriğini kaydet"), - new("html", "HTML Web Sayfası", "Belge", "Web", "Web formatında HTML çıktısı al"), - new("zip", "ZIP Paketle", "Arşiv", "Archive", "Belgeleri sıkıştırılmış ZIP yap") - }; - } - - // Videolar - if (allVideos) - { - return new List - { - new("mp4", "MP4 Yap", "Video", "Video", "Evrensel MP4 (H.264 / AAC) dönüştür"), - new("mp3", "Sesi MP3 Yap", "Ses", "Audio", "Videodan sesi ayırıp MP3 olarak kaydet"), - new("gif", "Animasyonlu GIF", "Görsel", "Sparkle", "Videoyu hafif ve canlı GIF yap"), - new("webm", "WebM Yap", "Video", "Web", "Web uyumlu VP9/WebM formatına dönüştür"), - new("mkv", "MKV Yap", "Video", "Video", "Yüksek kaliteli MKV konteyneri"), - new("compress_video", "Video Sıkıştır", "Optimizasyon", "Compress", "Kaliteyi koruyarak dosya boyutunu düşür") - }; - } - - // Sesler - if (allAudios) - { - return new List - { - new("mp3", "MP3 Yap", "Ses", "Audio", "Yüksek uyumlu 192kbps MP3"), - new("wav", "WAV Yap", "Ses", "Audio", "Kayıpsız stüdyo WAV formatı"), - new("aac", "AAC / M4A", "Ses", "Audio", "Modern yüksek kaliteli AAC"), - new("flac", "FLAC Yap", "Ses", "Audio", "Kayıpsız FLAC sıkıştırması"), - new("ogg", "OGG Vorbis", "Ses", "Audio", "Açık kaynak OGG formatı"), - new("compress_audio", "Sesi Sıkıştır", "Optimizasyon", "Compress", "Ses boyutunu küçült") - }; - } - - // Arşivler - if (allArchives) - { - return new List - { - new("extract_folder", "Klasöre Çıkar", "Arşiv", "Unpack", "Arşiv içeriğini klasöre çıkar"), - new("zip", "ZIP Formatına Çevir", "Arşiv", "Archive", "Arşivi standart ZIP yap"), - new("7z", "7Z Formatına Çevir", "Arşiv", "Archive", "Ultra sıkıştırmalı 7-Zip yap"), - new("tar_gz", "TAR.GZ Yap", "Arşiv", "Archive", "Linux uyumlu .tar.gz yap") - }; - } - - // Karışık dosyalar - return new List - { - new("zip", "ZIP Arşivi Oluştur", "Arşiv", "Archive", "Tüm seçili dosyaları ZIP dosyasına topla"), - new("7z", "7Z Arşivi Oluştur", "Arşiv", "Archive", "Ultra sıkıştırma ile 7Z arşivi oluştur"), - new("tar_gz", "TAR.GZ Oluştur", "Arşiv", "Archive", "Dosyaları .tar.gz olarak arşivle"), - new("pdf_merge", "Görsel & PDF Birleştir", "Belge", "PdfMerge", "Desteklenen belgeleri tek PDF yap"), - new("copy_folder", "Yeni Klasöre Topla", "Dosya", "Folder", "Dosyaları organize bir klasöre kopyala") - }; - } - - private static IReadOnlyList GetDefaultChoices() - { - return new List - { - new("png", "PNG", "Görsel", "Image", "PNG dönüştür"), - new("jpg", "JPG", "Görsel", "Image", "JPG dönüştür"), - new("webp", "WebP", "Görsel", "Web", "WebP dönüştür"), - new("pdf", "PDF", "Belge", "Pdf", "PDF oluştur"), - new("mp3", "MP3", "Ses", "Audio", "MP3 ses çıkar"), - new("zip", "ZIP Arşivi", "Arşiv", "Archive", "Dosyaları ZIP arşivine sıkıştır") - }; - } -} diff --git a/src/Donustur.Core/Donustur.Core.csproj b/src/Donustur.Core/Donustur.Core.csproj deleted file mode 100644 index fa71b7a..0000000 --- a/src/Donustur.Core/Donustur.Core.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - - net8.0 - enable - enable - - - diff --git a/src/Donustur.Core/Math/WheelMath.cs b/src/Donustur.Core/Math/WheelMath.cs deleted file mode 100644 index 9fdaeaf..0000000 --- a/src/Donustur.Core/Math/WheelMath.cs +++ /dev/null @@ -1,79 +0,0 @@ -namespace Donustur.Core.Math; - -public readonly record struct WheelPoint(double X, double Y); - -public static class WheelMath -{ - /// - /// Fare koordinatına göre fare imlecinin hangi dilim üzerinde olduğunu hesaplar. - /// Dilimler saat yönünde, üstten (90 derece ofsetle) başlar. - /// Merkezdeki ölü bölgede veya çarkın dışındaysa -1 döner. - /// - public static int GetSegmentIndex( - double centerX, - double centerY, - double mouseX, - double mouseY, - int totalSegments, - double deadZoneRadius = 42, - double outerRadius = 175) - { - if (totalSegments <= 0) return -1; - - double dx = mouseX - centerX; - double dy = mouseY - centerY; - double distance = System.Math.Sqrt(dx * dx + dy * dy); - - if (distance < deadZoneRadius || distance > outerRadius) - return -1; - - // dy aşağı doğru pozitif olduğu için ekran koordinatlarında Math.Atan2(dy, dx) - double angleRad = System.Math.Atan2(dy, dx); - double angleDeg = angleRad * (180.0 / System.Math.PI); - - // Standart matematik: 0 derece sağ, 90 derece alt. - // Biz ilk dilimi tam tepeye (saat 12) ortalamak istiyoruz. - // Saat 12 açısı: -90 derece (veya 270 derece). - // Normalize 0 - 360 - if (angleDeg < 0) angleDeg += 360.0; - - // Tepe noktayı (270°) 0° başlangıcına eşlemek için: - // Saat yönünde: 270° -> 0, 0° -> 90, 90° -> 180, 180° -> 270. - // clockAngle = (angleDeg + 90) % 360 - double clockAngle = (angleDeg + 90.0) % 360.0; - - double segmentAngle = 360.0 / totalSegments; - // İlk dilimi tepeye ortalamak için yarım dilim ofset: - double shifted = (clockAngle + (segmentAngle / 2.0)) % 360.0; - - int index = (int)(shifted / segmentAngle); - if (index < 0) index = 0; - if (index >= totalSegments) index = totalSegments - 1; - - return index; - } - - /// - /// Verilen dilimin merkez açısını (derece cinsinden) hesaplar. - /// 0. dilim saat 12 yönündedir (tepede). - /// - public static double GetSegmentCenterAngle(int segmentIndex, int totalSegments) - { - if (totalSegments <= 0) return 0; - double segmentAngle = 360.0 / totalSegments; - // Saat 12 (270 derece ekran koordinatı) + index * segmentAngle - double angle = -90.0 + (segmentIndex * segmentAngle); - return angle; - } - - /// - /// Açı ve yarıçapa göre çember üzerindeki koordinatı hesaplar. - /// - public static WheelPoint GetPointOnCircle(double centerX, double centerY, double radius, double angleInDegrees) - { - double angleRad = angleInDegrees * (System.Math.PI / 180.0); - double x = centerX + (radius * System.Math.Cos(angleRad)); - double y = centerY + (radius * System.Math.Sin(angleRad)); - return new WheelPoint(x, y); - } -} diff --git a/src/Donustur.Core/Models/AppPreferences.cs b/src/Donustur.Core/Models/AppPreferences.cs deleted file mode 100644 index ed8d26a..0000000 --- a/src/Donustur.Core/Models/AppPreferences.cs +++ /dev/null @@ -1,19 +0,0 @@ -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 string? CustomPandocPath { get; set; } - public int DefaultImageQuality { get; set; } = 85; -} diff --git a/src/Donustur.Core/Models/ConversionOptions.cs b/src/Donustur.Core/Models/ConversionOptions.cs deleted file mode 100644 index e588515..0000000 --- a/src/Donustur.Core/Models/ConversionOptions.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace Donustur.Core.Models; - -/// -/// Dönüştürme işlemleri için yapılandırma seçenekleri. -/// -public sealed class ConversionOptions -{ - public int ImageQuality { get; set; } = 85; - public int? ResizeWidth { get; set; } - public int? ResizeHeight { get; set; } - public bool StripMetadata { get; set; } = false; - public int PdfDpi { get; set; } = 200; - public string? ArchivePassword { get; set; } - public string VideoPreset { get; set; } = "faster"; - public int VideoCrf { get; set; } = 23; - public string AudioBitrate { get; set; } = "192k"; - public string? DestinationFolder { get; set; } - public bool OverwriteExisting { get; set; } = false; - - public static ConversionOptions Default => new(); -} diff --git a/src/Donustur.Core/Models/ConversionTask.cs b/src/Donustur.Core/Models/ConversionTask.cs deleted file mode 100644 index 0a39915..0000000 --- a/src/Donustur.Core/Models/ConversionTask.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace Donustur.Core.Models; - -public enum ConversionTaskStatus -{ - Queued, - Running, - Completed, - Failed, - Cancelled -} - -/// -/// Bir dönüştürme görevinin durum ve çıktı bilgilerini temsil eder. -/// -public sealed class ConversionTask -{ - public string Id { get; init; } = Guid.NewGuid().ToString("N"); - public IReadOnlyList InputFiles { get; init; } = Array.Empty(); - public string TargetActionId { get; init; } = string.Empty; - public string TargetDisplayName { get; init; } = string.Empty; - public ConversionOptions Options { get; init; } = new(); - public ConversionTaskStatus Status { get; set; } = ConversionTaskStatus.Queued; - public double ProgressPercentage { get; set; } - public string? CurrentStatusMessage { get; set; } - public List OutputFiles { get; } = new(); - public DateTime CreatedAt { get; init; } = DateTime.Now; - public DateTime? CompletedAt { get; set; } - public string? ErrorMessage { get; set; } - - public TimeSpan? Duration => CompletedAt.HasValue ? CompletedAt.Value - CreatedAt : null; -} - -public sealed record ConversionResult( - bool Success, - IReadOnlyList OutputFiles, - string? ErrorMessage = null, - TimeSpan? Duration = null -); diff --git a/src/Donustur.Core/Models/ToolChoice.cs b/src/Donustur.Core/Models/ToolChoice.cs deleted file mode 100644 index e9b330c..0000000 --- a/src/Donustur.Core/Models/ToolChoice.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Donustur.Core.Models; - -/// -/// Çark üzerinde veya arayüzde gösterilen dönüştürme/işlem seçeneği. -/// -public sealed record ToolChoice( - string Id, - string DisplayName, - string Category, - string IconKey, - string Description, - bool RequiresOptions = false -); diff --git a/src/Donustur.Core/Services/HistoryStore.cs b/src/Donustur.Core/Services/HistoryStore.cs deleted file mode 100644 index a3aab5d..0000000 --- a/src/Donustur.Core/Services/HistoryStore.cs +++ /dev/null @@ -1,153 +0,0 @@ -using System.Text.Json; - -namespace Donustur.Core.Services; - -public sealed class HistoryEntry -{ - public string Id { get; set; } = Guid.NewGuid().ToString("N"); - public string Title { get; set; } = string.Empty; - public string FormatSummary { get; set; } = string.Empty; - public List InputFiles { get; set; } = new(); - public List OutputFiles { get; set; } = new(); - public long OriginalSizeBytes { get; set; } - public long OutputSizeBytes { get; set; } - public DateTime Timestamp { get; set; } = DateTime.Now; - public bool Success { get; set; } = true; - public string? ErrorMessage { get; set; } -} - -public sealed class HistoryStore -{ - private static readonly JsonSerializerOptions JsonOptions = new() - { - WriteIndented = true, - PropertyNameCaseInsensitive = true - }; - - private readonly string _filePath; - private readonly List _entries = new(); - private readonly object _lock = new(); - - public IReadOnlyList Entries - { - get - { - lock (_lock) - { - return _entries.ToList(); - } - } - } - - public event Action? Changed; - - public HistoryStore(string? customPath = null) - { - if (!string.IsNullOrWhiteSpace(customPath)) - { - _filePath = customPath; - } - else - { - string localData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - string appDir = Path.Combine(localData, "LDConverter"); - Directory.CreateDirectory(appDir); - _filePath = Path.Combine(appDir, "history.json"); - } - - Load(); - } - - private void Load() - { - lock (_lock) - { - _entries.Clear(); - try - { - if (File.Exists(_filePath)) - { - string json = File.ReadAllText(_filePath); - var list = JsonSerializer.Deserialize>(json, JsonOptions); - if (list != null) - { - _entries.AddRange(list); - } - } - } - catch - { - // Silently fallback on empty history - } - } - } - - public void Add(HistoryEntry entry) - { - lock (_lock) - { - _entries.Insert(0, entry); - // En fazla son 100 işlemi sakla - if (_entries.Count > 100) - { - _entries.RemoveRange(100, _entries.Count - 100); - } - } - SaveInternal(); - Changed?.Invoke(); - } - - public void Remove(string id) - { - bool removed; - lock (_lock) - { - removed = _entries.RemoveAll(e => e.Id == id) > 0; - } - if (removed) - { - SaveInternal(); - Changed?.Invoke(); - } - } - - public void Clear() - { - lock (_lock) - { - _entries.Clear(); - } - SaveInternal(); - Changed?.Invoke(); - } - - private void SaveInternal() - { - List snapshot; - lock (_lock) - { - snapshot = _entries.ToList(); - } - - Task.Run(() => - { - try - { - string dir = Path.GetDirectoryName(_filePath)!; - if (!Directory.Exists(dir)) - { - Directory.CreateDirectory(dir); - } - - string json = JsonSerializer.Serialize(snapshot, JsonOptions); - string tmp = _filePath + ".tmp"; - File.WriteAllText(tmp, json); - File.Move(tmp, _filePath, overwrite: true); - } - catch - { - // Silently handle IO errors - } - }); - } -} diff --git a/src/Donustur.Core/Services/PreferencesStore.cs b/src/Donustur.Core/Services/PreferencesStore.cs deleted file mode 100644 index 185429b..0000000 --- a/src/Donustur.Core/Services/PreferencesStore.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System.Text.Json; -using Donustur.Core.Models; - -namespace Donustur.Core.Services; - -public sealed class PreferencesStore -{ - private static readonly JsonSerializerOptions JsonOptions = new() - { - WriteIndented = true, - PropertyNameCaseInsensitive = true - }; - - private readonly string _filePath; - private AppPreferences _current; - - public AppPreferences Current => _current; - - public event Action? Changed; - - public PreferencesStore(string? customPath = null) - { - if (!string.IsNullOrWhiteSpace(customPath)) - { - _filePath = customPath; - } - else - { - string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); - string appDir = Path.Combine(appData, "LDConverter"); - Directory.CreateDirectory(appDir); - _filePath = Path.Combine(appDir, "preferences.json"); - } - - _current = Load(); - } - - private AppPreferences Load() - { - try - { - if (File.Exists(_filePath)) - { - string json = File.ReadAllText(_filePath); - var loaded = JsonSerializer.Deserialize(json, JsonOptions); - if (loaded != null) return loaded; - } - } - catch - { - // Fallback to defaults on error - } - - var defaultPrefs = new AppPreferences(); - Save(defaultPrefs); - return defaultPrefs; - } - - public void Save(AppPreferences preferences) - { - _current = preferences; - Changed?.Invoke(_current); - - Task.Run(() => - { - try - { - string dir = Path.GetDirectoryName(_filePath)!; - if (!Directory.Exists(dir)) - { - Directory.CreateDirectory(dir); - } - - string json = JsonSerializer.Serialize(preferences, JsonOptions); - string tempFile = _filePath + ".tmp"; - File.WriteAllText(tempFile, json); - File.Move(tempFile, _filePath, overwrite: true); - } - catch - { - // Handle error silently - } - }); - } -} diff --git a/src/Donustur.Core/Transactions/ExportTransaction.cs b/src/Donustur.Core/Transactions/ExportTransaction.cs deleted file mode 100644 index 0b38cac..0000000 --- a/src/Donustur.Core/Transactions/ExportTransaction.cs +++ /dev/null @@ -1,118 +0,0 @@ -using Donustur.Core.Utils; - -namespace Donustur.Core.Transactions; - -/// -/// Dönüştürme sırasında hedef klasörün yarım/bozuk dosyalarla kirlenmesini önleyen -/// atomik evreleme (staging) yöneticisi. Farklı disk sürücüleri (C:, D:, USB) arasında -/// klasör hiyerarşisini koruyarak güvenli aktarım yapar. -/// -public sealed class ExportTransaction : IDisposable -{ - private bool _disposed; - public bool IsCommitted { get; private set; } - - public string StagingDirectory { get; } - - public ExportTransaction(string? baseDir = null) - { - string root = string.IsNullOrWhiteSpace(baseDir) - ? Path.Combine(Path.GetTempPath(), "LDConverter") - : baseDir; - - StagingDirectory = Path.Combine(root, "staging_" + Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(StagingDirectory); - } - - /// - /// Staging klasöründeki tüm dosya ve alt klasörleri yapısını koruyarak hedef klasöre taşır. - /// - public List CommitTo(string destinationFolder, bool overwrite = false) - { - if (_disposed) - throw new ObjectDisposedException(nameof(ExportTransaction)); - - if (!Directory.Exists(destinationFolder)) - { - Directory.CreateDirectory(destinationFolder); - } - - var finalPaths = new List(); - - // 1. Üst seviye dosyaları taşı - var topFiles = Directory.GetFiles(StagingDirectory, "*", SearchOption.TopDirectoryOnly); - foreach (var sourceFile in topFiles) - { - string fileName = Path.GetFileName(sourceFile); - string dest = Path.Combine(destinationFolder, fileName); - - if (!overwrite && (File.Exists(dest) || Directory.Exists(dest))) - { - dest = SafePaths.GetUniquePath(destinationFolder, fileName); - } - - File.Move(sourceFile, dest, overwrite: true); - finalPaths.Add(dest); - } - - // 2. Üst seviye klasörleri (örn. arşivden çıkarılan klasörler) alt yapısıyla birlikte taşı - var topDirs = Directory.GetDirectories(StagingDirectory, "*", SearchOption.TopDirectoryOnly); - foreach (var sourceDir in topDirs) - { - string dirName = Path.GetFileName(sourceDir); - string destDir = Path.Combine(destinationFolder, dirName); - - if (!overwrite && (Directory.Exists(destDir) || File.Exists(destDir))) - { - destDir = SafePaths.GetUniquePath(destinationFolder, dirName); - } - - MoveDirectoryCrossVolume(sourceDir, destDir); - finalPaths.Add(destDir); - } - - IsCommitted = true; - return finalPaths; - } - - private static void MoveDirectoryCrossVolume(string sourceDir, string destDir) - { - Directory.CreateDirectory(destDir); - - foreach (var dir in Directory.GetDirectories(sourceDir, "*", SearchOption.AllDirectories)) - { - string relative = Path.GetRelativePath(sourceDir, dir); - Directory.CreateDirectory(Path.Combine(destDir, relative)); - } - - foreach (var file in Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories)) - { - string relative = Path.GetRelativePath(sourceDir, file); - string targetFile = Path.Combine(destDir, relative); - string? targetParent = Path.GetDirectoryName(targetFile); - if (!string.IsNullOrEmpty(targetParent)) - { - Directory.CreateDirectory(targetParent); - } - File.Move(file, targetFile, overwrite: true); - } - } - - public void Dispose() - { - if (_disposed) return; - _disposed = true; - - try - { - if (Directory.Exists(StagingDirectory)) - { - Directory.Delete(StagingDirectory, recursive: true); - } - } - catch - { - // Arka plandaki kilitli dosyalar için sessizce geç - } - } -} diff --git a/src/Donustur.Core/Utils/FileUtils.cs b/src/Donustur.Core/Utils/FileUtils.cs deleted file mode 100644 index 733e887..0000000 --- a/src/Donustur.Core/Utils/FileUtils.cs +++ /dev/null @@ -1,64 +0,0 @@ -namespace Donustur.Core.Utils; - -public static class FileUtils -{ - private static readonly string[] SizeSuffixes = { "B", "KB", "MB", "GB", "TB" }; - - public static string FormatBytes(long bytes) - { - if (bytes < 0) return "-" + FormatBytes(-bytes); - if (bytes == 0) return "0 B"; - - int mag = (int)System.Math.Log(bytes, 1024); - if (mag >= SizeSuffixes.Length) mag = SizeSuffixes.Length - 1; - - decimal adjustedSize = (decimal)bytes / (1L << (mag * 10)); - return string.Format("{0:n1} {1}", adjustedSize, SizeSuffixes[mag]); - } - - public static string FormatPercentChange(long initialBytes, long finalBytes) - { - if (initialBytes <= 0) return "0%"; - double diff = (double)(finalBytes - initialBytes) / initialBytes * 100.0; - if (diff > 0) - return $"+{diff:F1}%"; - return $"{diff:F1}%"; - } - - /// - /// Verilen dosya veya klasör yollarının toplam bayt boyutunu hesaplar. - /// - public static long CalculateTotalBytes(IEnumerable paths) - { - long total = 0; - foreach (var path in paths) - { - try - { - if (File.Exists(path)) - { - total += new FileInfo(path).Length; - } - else if (Directory.Exists(path)) - { - foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) - { - try - { - total += new FileInfo(file).Length; - } - catch - { - // Erişilemeyen alt dosyaları atla - } - } - } - } - catch - { - // Erişilemeyen yolları atla - } - } - return total; - } -} diff --git a/src/Donustur.Core/Utils/SafePaths.cs b/src/Donustur.Core/Utils/SafePaths.cs deleted file mode 100644 index 1badd58..0000000 --- a/src/Donustur.Core/Utils/SafePaths.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace Donustur.Core.Utils; - -public static class SafePaths -{ - public static string EnsureDirectory(string path) - { - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - return path; - } - - public static string GetUniquePath(string directory, string desiredFileName) - { - EnsureDirectory(directory); - string targetPath = Path.Combine(directory, desiredFileName); - if (!File.Exists(targetPath) && !Directory.Exists(targetPath)) - { - return targetPath; - } - - string nameWithoutExt = Path.GetFileNameWithoutExtension(desiredFileName); - string ext = Path.GetExtension(desiredFileName); - int counter = 1; - - do - { - targetPath = Path.Combine(directory, $"{nameWithoutExt} ({counter}){ext}"); - counter++; - } while (File.Exists(targetPath) || Directory.Exists(targetPath)); - - return targetPath; - } -} diff --git a/src/Donustur.Engine/Archives/ArchiveEngine.cs b/src/Donustur.Engine/Archives/ArchiveEngine.cs deleted file mode 100644 index bba9810..0000000 --- a/src/Donustur.Engine/Archives/ArchiveEngine.cs +++ /dev/null @@ -1,522 +0,0 @@ -using System.IO.Compression; -using Donustur.Core.Catalog; -using Donustur.Core.Transactions; -using Donustur.Core.Utils; -using SharpCompress.Archives; -using SharpCompress.Common; -using SharpCompress.Readers; -using SharpCompress.Writers; - -namespace Donustur.Engine.Archives; - -public sealed class ArchiveEngine -{ - public static string? Resolve7ZipPath() - { - string[] candidates = - { - @"C:\Program Files\7-Zip\7z.exe", - @"C:\Program Files (x86)\7-Zip\7z.exe", - @"C:\ProgramData\chocolatey\bin\7z.exe" - }; - - foreach (var c in candidates) - { - if (File.Exists(c)) return c; - } - - string? pathEnv = Environment.GetEnvironmentVariable("PATH"); - if (pathEnv != null) - { - foreach (var segment in pathEnv.Split(Path.PathSeparator)) - { - if (string.IsNullOrWhiteSpace(segment)) continue; - string combined = Path.Combine(segment.Trim(), "7z.exe"); - if (File.Exists(combined)) return combined; - } - } - - return null; - } - - public bool Is7ZipAvailable => Resolve7ZipPath() != null; - - /// - /// Arşiv dosyasını klasöre çıkarır. ZIP, 7Z, TAR, GZ, TGZ, RAR destekler. - /// - public async Task ExtractAsync( - string archivePath, - ExportTransaction transaction, - string? password = null, - IProgress? progress = null, - CancellationToken token = default) - { - string baseName = GetCleanArchiveBaseName(archivePath); - string extractDir = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + "_Cikarilan"); - Directory.CreateDirectory(extractDir); - - await Task.Run(() => - { - ExtractToDirectoryInternal(archivePath, extractDir, password, progress, token); - }, token); - - return extractDir; - } - - private static void ExtractToDirectoryInternal( - string archivePath, - string extractDir, - string? password, - IProgress? progress, - CancellationToken token) - { - string lowerName = Path.GetFileName(archivePath).ToLowerInvariant(); - var readerOptions = new ReaderOptions { Password = password }; - - // .tar.gz / .tgz / .gz akış tabanlı arşivler için ReaderFactory kullan - if (lowerName.EndsWith(".tar.gz") || lowerName.EndsWith(".tgz") || lowerName.EndsWith(".gz")) - { - using var fileStream = File.OpenRead(archivePath); - using var reader = ReaderFactory.OpenReader(fileStream, readerOptions); - while (reader.MoveToNextEntry()) - { - token.ThrowIfCancellationRequested(); - if (!reader.Entry.IsDirectory) - { - reader.WriteEntryToDirectory(extractDir, new ExtractionOptions - { - ExtractFullPath = true, - Overwrite = true - }); - } - } - progress?.Report(100.0); - return; - } - - using var archive = ArchiveFactory.OpenArchive(archivePath, readerOptions); - var entries = archive.Entries.Where(e => !e.IsDirectory).ToList(); - int total = Math.Max(1, entries.Count); - - for (int i = 0; i < entries.Count; i++) - { - token.ThrowIfCancellationRequested(); - var entry = entries[i]; - entry.WriteToDirectory(extractDir, new ExtractionOptions - { - ExtractFullPath = true, - Overwrite = true - }); - - progress?.Report((double)(i + 1) / total * 100.0); - } - } - - /// - /// Verilen dosyaları (veya mevcut arşivlerin içeriğini) ZIP arşivi olarak paketler. - /// - public async Task CreateZipAsync( - IReadOnlyList files, - ExportTransaction transaction, - string? zipName = null, - IProgress? progress = null, - CancellationToken token = default) - { - // Eğer girdilerin tamamı zaten arşivse (örn. .rar veya .7z -> .zip dönüşümü), önce açıp sonra ZIP yap - if (files.Count > 0 && files.All(FormatCatalog.IsArchive)) - { - return await ConvertArchivesToFormatAsync(files, "zip", transaction, progress, token); - } - - string name = string.IsNullOrWhiteSpace(zipName) - ? (files.Count == 1 ? Path.GetFileNameWithoutExtension(files[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) + ".zip" : "Arsiv.zip") - : zipName; - - if (!name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) - { - name += ".zip"; - } - - string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, name); - - await Task.Run(() => - { - using var zipStream = new FileStream(outputPath, FileMode.Create); - using var archive = new ZipArchive(zipStream, ZipArchiveMode.Create); - var usedEntryNames = new HashSet(StringComparer.OrdinalIgnoreCase); - - for (int i = 0; i < files.Count; i++) - { - token.ThrowIfCancellationRequested(); - string file = files[i]; - - if (File.Exists(file)) - { - string entryName = GetUniqueArchiveEntryName(Path.GetFileName(file), usedEntryNames); - archive.CreateEntryFromFile(file, entryName, CompressionLevel.Optimal); - } - else if (Directory.Exists(file)) - { - string dirName = Path.GetFileName(file.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); - AddDirectoryToZip(archive, file, dirName, usedEntryNames); - } - - progress?.Report((double)(i + 1) / files.Count * 100.0); - } - }, token); - - return outputPath; - } - - /// - /// Verilen dosyaları .tar.gz olarak paketler. - /// - public async Task CreateTarGzAsync( - IReadOnlyList files, - ExportTransaction transaction, - string? archiveName = null, - IProgress? progress = null, - CancellationToken token = default) - { - if (files.Count > 0 && files.All(FormatCatalog.IsArchive)) - { - return await ConvertArchivesToFormatAsync(files, "tar_gz", transaction, progress, token); - } - - string baseName = string.IsNullOrWhiteSpace(archiveName) - ? (files.Count == 1 ? GetCleanArchiveBaseName(files[0]) : "Arsiv") - : GetCleanArchiveBaseName(archiveName); - - string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + ".tar.gz"); - - await Task.Run(() => - { - using var stream = File.OpenWrite(outputPath); - var writerOptions = new WriterOptions(CompressionType.GZip) { LeaveStreamOpen = false }; - using var writer = WriterFactory.OpenWriter(stream, ArchiveType.Tar, writerOptions); - - for (int i = 0; i < files.Count; i++) - { - token.ThrowIfCancellationRequested(); - string item = files[i]; - - if (File.Exists(item)) - { - writer.Write(Path.GetFileName(item), item); - } - else if (Directory.Exists(item)) - { - string prefix = Path.GetFileName(item.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); - foreach (var subFile in Directory.GetFiles(item, "*", SearchOption.AllDirectories)) - { - token.ThrowIfCancellationRequested(); - string rel = Path.Combine(prefix, Path.GetRelativePath(item, subFile)).Replace('\\', '/'); - writer.Write(rel, subFile); - } - } - - progress?.Report((double)(i + 1) / files.Count * 100.0); - } - }, token); - - return outputPath; - } - - /// - /// Verilen dosyaları 7-Zip (.7z) olarak paketler. Sistemde 7z.exe varsa kullanır. - /// - public async Task Create7zAsync( - IReadOnlyList files, - ExportTransaction transaction, - string? archiveName = null, - IProgress? progress = null, - CancellationToken token = default) - { - if (files.Count > 0 && files.All(FormatCatalog.IsArchive)) - { - return await ConvertArchivesToFormatAsync(files, "7z", transaction, progress, token); - } - - string? sevenZipExe = Resolve7ZipPath(); - if (sevenZipExe == null) - { - throw new FileNotFoundException( - "7-Zip (7z.exe) sistemde bulunamadı. .7z formatında sıkıştırma için 7-Zip kurulu olmalıdır (veya ZIP / TAR.GZ seçeneğini kullanabilirsiniz)."); - } - - string baseName = string.IsNullOrWhiteSpace(archiveName) - ? (files.Count == 1 ? GetCleanArchiveBaseName(files[0]) : "Arsiv") - : GetCleanArchiveBaseName(archiveName); - - string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + ".7z"); - string quotedFiles = string.Join(" ", files.Select(f => $"\"{f}\"")); - string args = $"a -t7z -mx=7 -y \"{outputPath}\" {quotedFiles}"; - - progress?.Report(25.0); - var result = await ProcessRunner.RunAsync(sevenZipExe, args, token: token); - if (result.ExitCode != 0) - { - throw new InvalidOperationException($"7-Zip arşivleme hatası ({result.ExitCode}): {result.StandardError}"); - } - - progress?.Report(100.0); - return outputPath; - } - - /// - /// Mevcut bir arşivi (RAR, 7Z, ZIP, TAR.GZ) açıp hedef arşiv formatına (ZIP, 7Z, TAR.GZ) dönüştürür. - /// - private async Task ConvertArchivesToFormatAsync( - IReadOnlyList archiveFiles, - string targetFormat, - ExportTransaction transaction, - IProgress? progress, - CancellationToken token) - { - string tempExtractRoot = Path.Combine(Path.GetTempPath(), "Donustur", "repack_" + Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(tempExtractRoot); - - try - { - for (int i = 0; i < archiveFiles.Count; i++) - { - token.ThrowIfCancellationRequested(); - string archivePath = archiveFiles[i]; - string subDir = archiveFiles.Count == 1 - ? tempExtractRoot - : Path.Combine(tempExtractRoot, GetCleanArchiveBaseName(archivePath)); - Directory.CreateDirectory(subDir); - - await Task.Run(() => - { - ExtractToDirectoryInternal(archivePath, subDir, null, null, token); - }, token); - - progress?.Report((double)(i + 1) / archiveFiles.Count * 50.0); - } - - var extractedItems = Directory.GetFileSystemEntries(tempExtractRoot).ToList(); - if (extractedItems.Count == 0) - { - throw new InvalidOperationException("Kaynak arşiv boş olduğu için dönüştürülemedi."); - } - - string baseName = archiveFiles.Count == 1 - ? GetCleanArchiveBaseName(archiveFiles[0]) - : "Donusturulen_Arsiv"; - - return targetFormat switch - { - "7z" => await Create7zFromExtractedAsync(extractedItems, baseName, transaction, progress, token), - "tar_gz" => await CreateTarGzFromExtractedAsync(extractedItems, baseName, transaction, progress, token), - _ => await CreateZipFromExtractedAsync(extractedItems, baseName, transaction, progress, token) - }; - } - finally - { - try - { - if (Directory.Exists(tempExtractRoot)) - { - Directory.Delete(tempExtractRoot, recursive: true); - } - } - catch - { - // Geçici klasör temizleme hatasını yoksay - } - } - } - - private async Task CreateZipFromExtractedAsync( - IReadOnlyList items, - string baseName, - ExportTransaction transaction, - IProgress? progress, - CancellationToken token) - { - string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + ".zip"); - await Task.Run(() => - { - using var zipStream = new FileStream(outputPath, FileMode.Create); - using var archive = new ZipArchive(zipStream, ZipArchiveMode.Create); - var usedNames = new HashSet(StringComparer.OrdinalIgnoreCase); - - for (int i = 0; i < items.Count; i++) - { - token.ThrowIfCancellationRequested(); - string item = items[i]; - if (File.Exists(item)) - { - string entryName = GetUniqueArchiveEntryName(Path.GetFileName(item), usedNames); - archive.CreateEntryFromFile(item, entryName, CompressionLevel.Optimal); - } - else if (Directory.Exists(item)) - { - AddDirectoryToZip(archive, item, Path.GetFileName(item), usedNames); - } - progress?.Report(50.0 + ((double)(i + 1) / items.Count * 50.0)); - } - }, token); - return outputPath; - } - - private async Task CreateTarGzFromExtractedAsync( - IReadOnlyList items, - string baseName, - ExportTransaction transaction, - IProgress? progress, - CancellationToken token) - { - string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + ".tar.gz"); - await Task.Run(() => - { - using var stream = File.OpenWrite(outputPath); - var writerOptions = new WriterOptions(CompressionType.GZip) { LeaveStreamOpen = false }; - using var writer = WriterFactory.OpenWriter(stream, ArchiveType.Tar, writerOptions); - - for (int i = 0; i < items.Count; i++) - { - token.ThrowIfCancellationRequested(); - string item = items[i]; - if (File.Exists(item)) - { - writer.Write(Path.GetFileName(item), item); - } - else if (Directory.Exists(item)) - { - string prefix = Path.GetFileName(item); - foreach (var subFile in Directory.GetFiles(item, "*", SearchOption.AllDirectories)) - { - token.ThrowIfCancellationRequested(); - string rel = Path.Combine(prefix, Path.GetRelativePath(item, subFile)).Replace('\\', '/'); - writer.Write(rel, subFile); - } - } - progress?.Report(50.0 + ((double)(i + 1) / items.Count * 50.0)); - } - }, token); - return outputPath; - } - - private async Task Create7zFromExtractedAsync( - IReadOnlyList items, - string baseName, - ExportTransaction transaction, - IProgress? progress, - CancellationToken token) - { - string? sevenZipExe = Resolve7ZipPath(); - if (sevenZipExe == null) - { - throw new FileNotFoundException("7-Zip (7z.exe) sistemde bulunamadı."); - } - - string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + ".7z"); - string quotedFiles = string.Join(" ", items.Select(f => $"\"{f}\"")); - string args = $"a -t7z -mx=7 -y \"{outputPath}\" {quotedFiles}"; - - var result = await ProcessRunner.RunAsync(sevenZipExe, args, token: token); - if (result.ExitCode != 0) - { - throw new InvalidOperationException($"7-Zip arşivleme hatası ({result.ExitCode}): {result.StandardError}"); - } - progress?.Report(100.0); - return outputPath; - } - - /// - /// Seçili dosya ve klasörleri yeni bir klasör altında toplar. - /// - public async Task CollectToFolderAsync( - IReadOnlyList files, - ExportTransaction transaction, - IProgress? progress = null, - CancellationToken token = default) - { - string folderName = $"Toplanan_Dosyalar_{DateTime.Now:yyyyMMdd_HHmm}"; - string targetFolder = SafePaths.GetUniquePath(transaction.StagingDirectory, folderName); - Directory.CreateDirectory(targetFolder); - - await Task.Run(() => - { - for (int i = 0; i < files.Count; i++) - { - token.ThrowIfCancellationRequested(); - string item = files[i]; - if (File.Exists(item)) - { - string destFile = SafePaths.GetUniquePath(targetFolder, Path.GetFileName(item)); - File.Copy(item, destFile, overwrite: true); - } - else if (Directory.Exists(item)) - { - string dirName = Path.GetFileName(item.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); - string destSubDir = SafePaths.GetUniquePath(targetFolder, dirName); - CopyDirectoryRecursive(item, destSubDir, token); - } - - progress?.Report((double)(i + 1) / files.Count * 100.0); - } - }, token); - - return targetFolder; - } - - private static void CopyDirectoryRecursive(string sourceDir, string destDir, CancellationToken token) - { - Directory.CreateDirectory(destDir); - foreach (var dir in Directory.GetDirectories(sourceDir, "*", SearchOption.AllDirectories)) - { - token.ThrowIfCancellationRequested(); - string rel = Path.GetRelativePath(sourceDir, dir); - Directory.CreateDirectory(Path.Combine(destDir, rel)); - } - foreach (var file in Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories)) - { - token.ThrowIfCancellationRequested(); - string rel = Path.GetRelativePath(sourceDir, file); - File.Copy(file, Path.Combine(destDir, rel), overwrite: true); - } - } - - private static string GetCleanArchiveBaseName(string path) - { - string name = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); - if (name.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase)) - { - return name[..^7]; - } - return Path.GetFileNameWithoutExtension(name); - } - - private static string GetUniqueArchiveEntryName(string desiredName, HashSet usedNames) - { - if (usedNames.Add(desiredName)) return desiredName; - - string nameNoExt = Path.GetFileNameWithoutExtension(desiredName); - string ext = Path.GetExtension(desiredName); - int counter = 1; - string candidate; - do - { - candidate = $"{nameNoExt} ({counter}){ext}"; - counter++; - } while (!usedNames.Add(candidate)); - - return candidate; - } - - private static void AddDirectoryToZip(ZipArchive archive, string sourceDir, string entryPrefix, HashSet usedNames) - { - foreach (var file in Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories)) - { - string relative = Path.GetRelativePath(sourceDir, file); - string entryName = Path.Combine(entryPrefix, relative).Replace('\\', '/'); - if (usedNames.Add(entryName)) - { - archive.CreateEntryFromFile(file, entryName, CompressionLevel.Optimal); - } - } - } -} diff --git a/src/Donustur.Engine/ConversionDispatcher.cs b/src/Donustur.Engine/ConversionDispatcher.cs deleted file mode 100644 index 232f584..0000000 --- a/src/Donustur.Engine/ConversionDispatcher.cs +++ /dev/null @@ -1,348 +0,0 @@ -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, preferences.CustomPandocPath); - _mediaEngine = new MediaEngine(preferences.CustomFfmpegPath); - _historyStore = historyStore; - } - - public async Task ExecuteTaskAsync( - ConversionTask task, - AppPreferences preferences, - IProgress? progress = null, - CancellationToken token = default) - { - return await Task.Run(async () => - { - task.Status = ConversionTaskStatus.Running; - - // Ayarlar ekranından değiştirilmiş olabilecek harici motor yollarını senkronize et - _officeEngine.SetCustomPath(preferences.CustomLibreOfficePath); - _officeEngine.SetCustomPandocPath(preferences.CustomPandocPath); - _mediaEngine.SetCustomPath(preferences.CustomFfmpegPath); - - if (preferences.DefaultImageQuality is >= 10 and <= 100 && task.Options.ImageQuality == 85) - { - task.Options.ImageQuality = preferences.DefaultImageQuality; - } - - string targetAction = task.TargetActionId.ToLowerInvariant().TrimStart('.'); - string destination = ResolveDestinationFolder(task, preferences); - - using var transaction = new ExportTransaction(); - - try - { - var files = task.InputFiles; - if (files.Count == 0) - { - throw new InvalidOperationException("İşlenecek dosya bulunamadı."); - } - - long totalInitialBytes = FileUtils.CalculateTotalBytes(files); - IReadOnlyList generatedStagedFiles; - - // 1. QR İşlemleri (Görsel ve PDF destekli) - if (targetAction == "qr_read") - { - var qrResults = new List(); - var decodedTexts = new List(); - - for (int i = 0; i < files.Count; i++) - { - token.ThrowIfCancellationRequested(); - string f = files[i]; - string? text = _qrEngine.ReadQrCode(f); - if (!string.IsNullOrWhiteSpace(text)) - { - decodedTexts.Add(text); - string txtPath = SafePaths.GetUniquePath( - transaction.StagingDirectory, - Path.GetFileNameWithoutExtension(f) + "_QR.txt"); - await File.WriteAllTextAsync(txtPath, text, token); - qrResults.Add(txtPath); - } - progress?.Report((double)(i + 1) / files.Count * 100.0); - } - - if (qrResults.Count == 0) - { - throw new InvalidOperationException("Seçilen dosyada okunabilir bir QR kod veya barkod bulunamadı."); - } - - task.CurrentStatusMessage = string.Join(" | ", decodedTexts); - generatedStagedFiles = qrResults; - } - // 2. Arşiv Çıkarma - else if (targetAction == "extract_folder") - { - var extractedDirs = new List(); - foreach (var f in files) - { - string dir = await _archiveEngine.ExtractAsync(f, transaction, task.Options.ArchivePassword, progress, token); - extractedDirs.Add(dir); - } - generatedStagedFiles = extractedDirs; - } - // 3. ZIP Paketleme / Arşiv Dönüştürme - else if (targetAction == "zip") - { - string zip = await _archiveEngine.CreateZipAsync(files, transaction, null, progress, token); - generatedStagedFiles = new[] { zip }; - } - // 4. 7Z Paketleme / Arşiv Dönüştürme - else if (targetAction == "7z") - { - string sevenZ = await _archiveEngine.Create7zAsync(files, transaction, null, progress, token); - generatedStagedFiles = new[] { sevenZ }; - } - // 5. TAR.GZ Paketleme / Arşiv Dönüştürme - else if (targetAction == "tar_gz") - { - string tarGz = await _archiveEngine.CreateTarGzAsync(files, transaction, null, progress, token); - generatedStagedFiles = new[] { tarGz }; - } - // 6. Yeni Klasöre Toplama - else if (targetAction == "copy_folder") - { - string folder = await _archiveEngine.CollectToFolderAsync(files, transaction, progress, token); - generatedStagedFiles = new[] { folder }; - } - // 7. PDF veya Görsel Birleştirme - else if (targetAction == "pdf_merge") - { - if (files.All(FormatCatalog.IsImage)) - { - generatedStagedFiles = await _imageEngine.ConvertImagesAsync(files, "pdf", transaction, task.Options, progress, token); - } - else - { - var mergeable = files.Where(f => FormatCatalog.IsPdf(f) || FormatCatalog.IsImage(f)).ToList(); - if (mergeable.Count == 0) - { - throw new InvalidOperationException("PDF olarak birleştirmek için en az bir PDF veya görsel dosyası seçilmelidir."); - } - string merged = await _pdfEngine.MergePdfsAsync(mergeable, transaction, null, progress, token); - generatedStagedFiles = new[] { merged }; - } - } - // 8. PDF Sayfa Ayırma - else if (targetAction == "pdf_split") - { - var splitFiles = new List(); - foreach (var f in files.Where(FormatCatalog.IsPdf)) - { - var pages = await _pdfEngine.SplitPdfAsync(f, transaction, progress, token); - splitFiles.AddRange(pages); - } - generatedStagedFiles = splitFiles; - } - // 9. PDF'den Metin Çıkarma - else if (targetAction == "pdf_to_txt") - { - var txts = new List(); - foreach (var f in files) - { - string txt = await _pdfEngine.ExtractTextAsync(f, transaction, progress, token); - txts.Add(txt); - } - generatedStagedFiles = txts; - } - // 10. PDF'den Word (DOCX) Belgesine Dönüştürme - else if (targetAction == "pdf_to_docx") - { - var docxs = new List(); - foreach (var f in files) - { - string docx = await _pdfEngine.ConvertToDocxAsync(f, transaction, progress, token); - docxs.Add(docx); - } - generatedStagedFiles = docxs; - } - // 11. PDF'den Görsele (PNG veya JPG) Aktarma - else if (targetAction is "pdf_to_images" or "pdf_to_jpg") - { - string imgFormat = targetAction == "pdf_to_jpg" ? "jpg" : "png"; - var imgs = new List(); - foreach (var f in files) - { - var extracted = await _pdfEngine.ExtractImagesAsync(f, transaction, progress, token, imgFormat); - imgs.AddRange(extracted); - } - generatedStagedFiles = imgs; - } - // 12. Görsel İşlemleri (PNG, JPG, WEBP, AVIF, ICO, Çoklu Görsel -> GIF/PDF vb.) - else if (files.All(FormatCatalog.IsImage) && - targetAction is "png" or "jpg" or "webp" or "avif" or "ico" or "bmp" or "tiff" or "gif" or "pdf" or "compress_image") - { - generatedStagedFiles = await _imageEngine.ConvertImagesAsync(files, targetAction, transaction, task.Options, progress, token); - } - // 13. Video ve Ses Dönüşümleri - else if (files.Any(FormatCatalog.IsVideo) || files.Any(FormatCatalog.IsAudio) || - targetAction is "mp4" or "mp3" or "wav" or "aac" or "flac" or "ogg" or "mkv" or "webm" or "compress_video" or "compress_audio") - { - generatedStagedFiles = await _mediaEngine.ConvertMediaAsync(files, targetAction, transaction, task.Options, progress, token); - } - // 14. Ofis Belgeleri (DOCX, PPTX, XLSX, ODT, TXT, MD, HTML vb.) - else if (files.All(FormatCatalog.IsDocument) || targetAction is "docx" or "txt" or "html") - { - generatedStagedFiles = await _officeEngine.ConvertDocumentsAsync(files, targetAction, transaction, progress, token); - } - // 15. Tekil Görsel Yedeği - else if (targetAction is "png" or "jpg" or "webp" or "avif" or "ico" or "compress_image") - { - generatedStagedFiles = await _imageEngine.ConvertImagesAsync(files, targetAction, transaction, task.Options, progress, token); - } - else - { - // Genel ZIP arşivleme yedeği - string zip = await _archiveEngine.CreateZipAsync(files, transaction, null, progress, token); - generatedStagedFiles = new[] { zip }; - } - - // Dosyaları nihai hedef klasöre taşı (Commit) - var finalCommittedPaths = transaction.CommitTo(destination, task.Options.OverwriteExisting); - long totalFinalBytes = FileUtils.CalculateTotalBytes(finalCommittedPaths); - - task.Status = ConversionTaskStatus.Completed; - task.CompletedAt = DateTime.Now; - task.OutputFiles.AddRange(finalCommittedPaths); - - string sourceLabel = files.Count == 1 - ? FormatCatalog.NormalizeExtension(files[0]).ToUpperInvariant() - : $"{files.Count} ÖĞE"; - string targetLabel = FormatFriendlyActionLabel(targetAction); - - _historyStore?.Add(new HistoryEntry - { - Title = files.Count == 1 - ? Path.GetFileName(files[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) - : $"{files.Count} öğe ({Path.GetFileName(files[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))}...)", - FormatSummary = $"{sourceLabel} → {targetLabel}", - InputFiles = files.ToList(), - OutputFiles = finalCommittedPaths.ToList(), - OriginalSizeBytes = totalInitialBytes, - OutputSizeBytes = totalFinalBytes, - Timestamp = DateTime.Now, - Success = true - }); - - return new ConversionResult(true, finalCommittedPaths, null, task.Duration); - } - catch (OperationCanceledException) - { - task.Status = ConversionTaskStatus.Cancelled; - task.CompletedAt = DateTime.Now; - return new ConversionResult(false, Array.Empty(), "İşlem kullanıcı tarafından iptal edildi."); - } - catch (Exception ex) - { - task.Status = ConversionTaskStatus.Failed; - task.CompletedAt = DateTime.Now; - task.ErrorMessage = ex.Message; - - _historyStore?.Add(new HistoryEntry - { - Title = task.InputFiles.Count == 1 - ? Path.GetFileName(task.InputFiles[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) - : $"{task.InputFiles.Count} dosya", - FormatSummary = FormatFriendlyActionLabel(targetAction), - InputFiles = task.InputFiles.ToList(), - OutputFiles = new List(), - Timestamp = DateTime.Now, - Success = false, - ErrorMessage = ex.Message - }); - - return new ConversionResult(false, Array.Empty(), ex.Message, task.Duration); - } - }, token); - } - - private static string FormatFriendlyActionLabel(string action) - { - return action switch - { - "pdf_to_images" => "PNG", - "pdf_to_jpg" => "JPG", - "pdf_to_txt" => "TXT", - "pdf_to_docx" => "DOCX", - "pdf_merge" => "PDF BİRLEŞTİR", - "pdf_split" => "PDF AYIR", - "extract_folder" => "KLASÖRE ÇIKAR", - "copy_folder" => "KLASÖRE TOPLA", - "compress_image" or "compress_video" or "compress_audio" => "SIKIŞTIR", - "qr_read" => "QR OKU", - "tar_gz" => "TAR.GZ", - _ => action.ToUpperInvariant() - }; - } - - public static string ResolveDestinationFolder(ConversionTask task, AppPreferences preferences) - { - if (!string.IsNullOrWhiteSpace(task.Options.DestinationFolder) && Directory.Exists(task.Options.DestinationFolder)) - { - return task.Options.DestinationFolder; - } - - if (preferences.OutputDirectoryMode == "Desktop") - { - return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); - } - - if (preferences.OutputDirectoryMode == "Custom" && - !string.IsNullOrWhiteSpace(preferences.CustomOutputDirectory)) - { - try - { - if (!Directory.Exists(preferences.CustomOutputDirectory)) - { - Directory.CreateDirectory(preferences.CustomOutputDirectory); - } - return preferences.CustomOutputDirectory; - } - catch - { - // Özel klasör oluşturulamazsa kaynak klasöre dön - } - } - - // SameAsSource (Hem dosya hem klasör girdilerini destekler) - if (task.InputFiles.Count > 0) - { - string first = task.InputFiles[0].TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - if (File.Exists(first) || Directory.Exists(first)) - { - string? dir = Path.GetDirectoryName(first); - if (!string.IsNullOrWhiteSpace(dir) && Directory.Exists(dir)) - { - return dir; - } - } - } - - return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); - } -} diff --git a/src/Donustur.Engine/Documents/DocxHelper.cs b/src/Donustur.Engine/Documents/DocxHelper.cs deleted file mode 100644 index 8c5fc4f..0000000 --- a/src/Donustur.Engine/Documents/DocxHelper.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System.IO.Compression; -using System.Security; -using System.Text; -using System.Xml.Linq; - -namespace Donustur.Engine.Documents; - -/// -/// Harici ofis kurulumuna ihtiyaç duymadan standart OpenXML (.docx) dosyaları -/// oluşturmak ve mevcut .docx dosyalarından metin okumak için yerel yardımcı. -/// -public static class DocxHelper -{ - public static void CreateDocxFromPages(string outputPath, IReadOnlyList pages) - { - if (File.Exists(outputPath)) - { - File.Delete(outputPath); - } - - using var fs = new FileStream(outputPath, FileMode.Create, FileAccess.Write); - using var archive = new ZipArchive(fs, ZipArchiveMode.Create); - - // 1. [Content_Types].xml - WriteZipText(archive, "[Content_Types].xml", """ - - - - - - - """); - - // 2. _rels/.rels - WriteZipText(archive, "_rels/.rels", """ - - - - - """); - - // 3. word/document.xml - var sb = new StringBuilder(); - sb.AppendLine(""""""); - sb.AppendLine(""""""); - sb.AppendLine(" "); - - for (int p = 0; p < pages.Count; p++) - { - string pageText = SanitizeXmlChars(pages[p] ?? string.Empty); - string[] lines = pageText.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); - - foreach (var line in lines) - { - string escaped = SecurityElement.Escape(line) ?? string.Empty; - sb.AppendLine(" "); - if (!string.IsNullOrEmpty(escaped)) - { - sb.AppendLine($" {escaped}"); - } - sb.AppendLine(" "); - } - - if (p < pages.Count - 1) - { - sb.AppendLine(" "); - } - } - - sb.AppendLine(" "); - sb.AppendLine(""); - - WriteZipText(archive, "word/document.xml", sb.ToString()); - } - - public static string ExtractTextFromDocx(string docxPath) - { - using var fs = File.OpenRead(docxPath); - using var archive = new ZipArchive(fs, ZipArchiveMode.Read); - var docEntry = archive.GetEntry("word/document.xml"); - if (docEntry == null) - { - throw new InvalidOperationException("Geçerli bir DOCX belgesi değil (word/document.xml bulunamadı)."); - } - - using var entryStream = docEntry.Open(); - var xdoc = XDocument.Load(entryStream); - XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; - - var sb = new StringBuilder(); - foreach (var para in xdoc.Descendants(w + "p")) - { - var paraText = new StringBuilder(); - foreach (var node in para.Descendants()) - { - if (node.Name == w + "t") - { - paraText.Append(node.Value); - } - else if (node.Name == w + "tab") - { - paraText.Append('\t'); - } - else if (node.Name == w + "br") - { - paraText.AppendLine(); - } - } - sb.AppendLine(paraText.ToString()); - } - - return sb.ToString(); - } - - private static void WriteZipText(ZipArchive archive, string entryName, string content) - { - var entry = archive.CreateEntry(entryName, CompressionLevel.Optimal); - using var stream = entry.Open(); - using var writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); - writer.Write(content.Trim()); - } - - private static string SanitizeXmlChars(string input) - { - if (string.IsNullOrEmpty(input)) return string.Empty; - var sb = new StringBuilder(input.Length); - foreach (char c in input) - { - if (c == '\t' || c == '\n' || c == '\r' || (c >= 0x20 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD)) - { - sb.Append(c); - } - } - return sb.ToString(); - } -} diff --git a/src/Donustur.Engine/Documents/OfficeDocumentEngine.cs b/src/Donustur.Engine/Documents/OfficeDocumentEngine.cs deleted file mode 100644 index 5b69cd0..0000000 --- a/src/Donustur.Engine/Documents/OfficeDocumentEngine.cs +++ /dev/null @@ -1,338 +0,0 @@ -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; - private readonly PandocEngine _pandocEngine = new(); - - public OfficeDocumentEngine(string? customPath = null, string? customPandocPath = null) - { - _customPath = customPath; - _pandocEngine.SetCustomPath(customPandocPath); - } - - public void SetCustomPath(string? customPath) - { - _customPath = customPath; - } - - public void SetCustomPandocPath(string? customPandocPath) - { - _pandocEngine.SetCustomPath(customPandocPath); - } - - public PandocEngine Pandoc => _pandocEngine; - - /// - /// LibreOffice soffice.exe yolunu bulur. - /// - public string? ResolveSofficePath() - { - if (!string.IsNullOrWhiteSpace(_customPath) && File.Exists(_customPath)) - { - return _customPath; - } - - string[] standardLocations = - { - @"C:\Program Files\LibreOffice\program\soffice.exe", - @"C:\Program Files (x86)\LibreOffice\program\soffice.exe" - }; - - foreach (var loc in standardLocations) - { - if (File.Exists(loc)) - return loc; - } - - string? pathEnv = Environment.GetEnvironmentVariable("PATH"); - if (pathEnv != null) - { - foreach (var path in pathEnv.Split(Path.PathSeparator)) - { - if (string.IsNullOrWhiteSpace(path)) continue; - string combined = Path.Combine(path.Trim(), "soffice.exe"); - if (File.Exists(combined)) - return combined; - } - } - - return null; - } - - public bool IsAvailable => ResolveSofficePath() != null; - - /// - /// Ofis ve metin belgelerini (DOCX, PPTX, XLSX, ODT, TXT, MD, HTML vb.) PDF veya diğer formatlara dönüştürür. - /// LibreOffice kuruluysa tam sadakatli motoru kullanır; kurulu değilse yerel OpenXML/PDF/HTML motoruna başvurur. - /// - public async Task> ConvertDocumentsAsync( - IReadOnlyList inputFiles, - string targetFormat, - ExportTransaction transaction, - IProgress? progress = null, - CancellationToken token = default) - { - var outputFiles = new List(); - string formatKey = targetFormat.ToLowerInvariant().TrimStart('.'); - string? sofficePath = ResolveSofficePath(); - - for (int i = 0; i < inputFiles.Count; i++) - { - token.ThrowIfCancellationRequested(); - string inputFile = inputFiles[i]; - string sourceExt = FormatCatalog.NormalizeExtension(inputFile); - string baseName = Path.GetFileNameWithoutExtension(inputFile); - - // Kaynak ve hedef uzantı aynıysa doğrudan kopyala - if (string.Equals(sourceExt, formatKey, StringComparison.OrdinalIgnoreCase)) - { - string copyDest = SafePaths.GetUniquePath(transaction.StagingDirectory, baseName + "." + formatKey); - File.Copy(inputFile, copyDest, overwrite: true); - outputFiles.Add(copyDest); - progress?.Report((double)(i + 1) / inputFiles.Count * 100.0); - continue; - } - - string? generatedPath = null; - - // 1. Öncelik: Markdown belgelerinde veya denklem içeren metinlerde Pandoc (XeLaTeX & LaTeX math desteği) - if (sourceExt is "md" or "markdown" && _pandocEngine.IsAvailable) - { - generatedPath = await _pandocEngine.ConvertAsync(inputFile, formatKey, transaction, token); - } - - // 2. Öncelik: LibreOffice kuruluysa izole profil ile çalıştır - if ((generatedPath == null || !File.Exists(generatedPath)) && sofficePath != null) - { - generatedPath = await TryConvertWithLibreOfficeAsync(sofficePath, inputFile, formatKey, transaction, token); - } - - // 3. Pandoc diğer formatlarda da alternatif olarak denenebilir - if ((generatedPath == null || !File.Exists(generatedPath)) && _pandocEngine.IsAvailable) - { - generatedPath = await _pandocEngine.ConvertAsync(inputFile, formatKey, transaction, token); - } - - // 4. 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 && !_pandocEngine.IsAvailable) - { - throw new FileNotFoundException( - $"'{sourceExt.ToUpperInvariant()} → {formatKey.ToUpperInvariant()}' dönüşümü için LibreOffice veya Pandoc gereklidir. " + - "Lütfen LibreOffice ya da Pandoc yükleyin veya Ayarlar ekranından soffice.exe / pandoc.exe yolunu belirtin."); - } - else - { - throw new InvalidOperationException($"Belge dönüştürülemedi: {Path.GetFileName(inputFile)}"); - } - } - - outputFiles.Add(generatedPath); - progress?.Report((double)(i + 1) / inputFiles.Count * 100.0); - } - - return outputFiles; - } - - private static async Task TryConvertWithLibreOfficeAsync( - string sofficePath, - string inputFile, - string formatKey, - ExportTransaction transaction, - CancellationToken token) - { - string tempProfileDir = Path.Combine(Path.GetTempPath(), "Donustur", "lo_profile_" + Guid.NewGuid().ToString("N")); - string tempOutDir = Path.Combine(transaction.StagingDirectory, "lo_work_" + Guid.NewGuid().ToString("N")[..6]); - Directory.CreateDirectory(tempProfileDir); - Directory.CreateDirectory(tempOutDir); - - try - { - string profileUri = new Uri(tempProfileDir).AbsoluteUri; - string filterArg = formatKey == "txt" ? "txt:Text (encoded):UTF8" : formatKey; - string args = $"-env:UserInstallation={profileUri} --headless --norestore --convert-to \"{filterArg}\" --outdir \"{tempOutDir}\" \"{inputFile}\""; - - var result = await ProcessRunner.RunAsync(sofficePath, args, token: token); - if (result.ExitCode != 0) - { - return null; - } - - var generated = Directory.GetFiles(tempOutDir); - if (generated.Length == 0) - { - return null; - } - - string desiredFileName = Path.GetFileNameWithoutExtension(inputFile) + "." + formatKey; - string finalStagedPath = SafePaths.GetUniquePath(transaction.StagingDirectory, desiredFileName); - File.Move(generated[0], finalStagedPath, overwrite: true); - return finalStagedPath; - } - catch - { - return null; - } - finally - { - try { if (Directory.Exists(tempOutDir)) Directory.Delete(tempOutDir, true); } catch { } - try { if (Directory.Exists(tempProfileDir)) Directory.Delete(tempProfileDir, true); } catch { } - } - } - - private static bool CanConvertNatively(string sourceExt, string targetFormat) - { - bool supportedSource = sourceExt is "txt" or "md" or "html" or "docx"; - bool supportedTarget = targetFormat is "txt" or "html" or "docx" or "pdf"; - return supportedSource && supportedTarget; - } - - private static string ConvertNatively(string inputFile, string sourceExt, string targetFormat, ExportTransaction transaction) - { - string baseName = Path.GetFileNameWithoutExtension(inputFile); - string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, $"{baseName}.{targetFormat}"); - - string plainText = ReadDocumentPlainText(inputFile, sourceExt); - - switch (targetFormat) - { - case "txt": - File.WriteAllText(outPath, plainText, Encoding.UTF8); - break; - - case "docx": - DocxHelper.CreateDocxFromPages(outPath, new[] { plainText }); - break; - - case "html": - string html = BuildHtmlFromText(baseName, plainText); - File.WriteAllText(outPath, html, Encoding.UTF8); - break; - - case "pdf": - RenderTextToPdf(plainText, outPath); - break; - - default: - throw new NotSupportedException($"Desteklenmeyen hedef belge formatı: {targetFormat}"); - } - - return outPath; - } - - private static string ReadDocumentPlainText(string inputFile, string sourceExt) - { - if (sourceExt == "docx") - { - return DocxHelper.ExtractTextFromDocx(inputFile); - } - - string raw = File.ReadAllText(inputFile, Encoding.UTF8); - if (sourceExt == "html") - { - string withoutScripts = Regex.Replace(raw, @"<(script|style)[^>]*?>.*?", "", RegexOptions.Singleline | RegexOptions.IgnoreCase); - string withBreaks = Regex.Replace(withoutScripts, @"<(br|p|div|li|tr|h[1-6])[^>]*?>", "\n", RegexOptions.IgnoreCase); - string stripped = Regex.Replace(withBreaks, @"<[^>]+>", ""); - return WebUtility.HtmlDecode(stripped).Trim(); - } - - return raw; - } - - private static string BuildHtmlFromText(string title, string text) - { - var sb = new StringBuilder(); - sb.AppendLine(""); - sb.AppendLine(""); - sb.AppendLine(""); - sb.AppendLine(" "); - sb.AppendLine(" "); - sb.AppendLine($" {WebUtility.HtmlEncode(title)}"); - sb.AppendLine(" "); - sb.AppendLine(" "); - sb.AppendLine(" "); - sb.AppendLine(""); - sb.AppendLine(""); - - string[] lines = text.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); - foreach (var line in lines) - { - sb.AppendLine($"

        {WebUtility.HtmlEncode(line)}

        "); - } - - sb.AppendLine(""); - sb.AppendLine(""); - return sb.ToString(); - } - - private static void RenderTextToPdf(string text, string outputPath) - { - using var document = new PdfDocument(); - var font = new XFont("Arial", 11, XFontStyle.Regular); - - string[] rawLines = (text ?? string.Empty).Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); - var wrappedLines = new List(); - const int maxChars = 90; - - foreach (var raw in rawLines) - { - if (string.IsNullOrEmpty(raw)) - { - wrappedLines.Add(string.Empty); - continue; - } - - string rem = raw; - while (rem.Length > 0) - { - int len = Math.Min(maxChars, rem.Length); - wrappedLines.Add(rem[..len]); - rem = rem[len..]; - } - } - - if (wrappedLines.Count == 0) - { - wrappedLines.Add(string.Empty); - } - - const double margin = 45; - const double lineHeight = 16; - int lineIndex = 0; - - while (lineIndex < wrappedLines.Count) - { - var page = document.AddPage(); - using var gfx = XGraphics.FromPdfPage(page); - double y = margin; - double maxY = page.Height.Point - margin; - - while (lineIndex < wrappedLines.Count && y + lineHeight <= maxY) - { - string line = wrappedLines[lineIndex++]; - if (!string.IsNullOrEmpty(line)) - { - gfx.DrawString(line, font, XBrushes.Black, new XPoint(margin, y + 11)); - } - y += lineHeight; - } - } - - document.Save(outputPath); - } -} diff --git a/src/Donustur.Engine/Documents/PandocEngine.cs b/src/Donustur.Engine/Documents/PandocEngine.cs deleted file mode 100644 index 2b02c4c..0000000 --- a/src/Donustur.Engine/Documents/PandocEngine.cs +++ /dev/null @@ -1,194 +0,0 @@ -using System.Diagnostics; -using Donustur.Core.Transactions; -using Donustur.Core.Utils; - -namespace Donustur.Engine.Documents; - -public sealed class PandocEngine -{ - private string? _customPath; - - public PandocEngine(string? customPath = null) - { - _customPath = customPath; - } - - public void SetCustomPath(string? customPath) - { - _customPath = customPath; - } - - public string? ResolvePandocPath() - { - if (!string.IsNullOrWhiteSpace(_customPath) && File.Exists(_customPath)) - { - return _customPath; - } - - string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - string progFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); - string progFilesX86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); - - string[] candidatePaths = - { - Path.Combine(progFiles, @"Pandoc\pandoc.exe"), - Path.Combine(progFilesX86, @"Pandoc\pandoc.exe"), - Path.Combine(localAppData, @"Pandoc\pandoc.exe"), - Path.Combine(localAppData, @"Programs\Pandoc\pandoc.exe"), - Path.Combine(localAppData, @"Microsoft\WinGet\Links\pandoc.exe") - }; - - foreach (var path in candidatePaths) - { - if (File.Exists(path)) - return path; - } - - // WinGet paket klasörünü dinamik tara - string wingetPackages = Path.Combine(localAppData, @"Microsoft\WinGet\Packages"); - if (Directory.Exists(wingetPackages)) - { - try - { - foreach (var pkgDir in Directory.EnumerateDirectories(wingetPackages)) - { - if (Path.GetFileName(pkgDir).Contains("pandoc", StringComparison.OrdinalIgnoreCase)) - { - string direct = Path.Combine(pkgDir, "pandoc.exe"); - if (File.Exists(direct)) return direct; - - string inBin = Path.Combine(pkgDir, "bin", "pandoc.exe"); - if (File.Exists(inBin)) return inBin; - } - } - } - catch - { - // Erişim hatasında devam et - } - } - - // PATH çevre değişkenlerini Process, User ve Machine seviyelerinde kontrol et - var pathTargets = new[] { EnvironmentVariableTarget.Process, EnvironmentVariableTarget.User, EnvironmentVariableTarget.Machine }; - foreach (var target in pathTargets) - { - try - { - string? pathEnv = Environment.GetEnvironmentVariable("PATH", target); - if (pathEnv != null) - { - foreach (var segment in pathEnv.Split(Path.PathSeparator)) - { - if (string.IsNullOrWhiteSpace(segment)) continue; - string combined = Path.Combine(segment.Trim(), "pandoc.exe"); - if (File.Exists(combined)) - return combined; - } - } - } - catch - { - // Sessizce geç - } - } - - return null; - } - - /// - /// Sistemde xelatex, pdflatex veya alternatif bir pdf-engine motoru olup olmadığını tespit eder. - /// - public string? ResolvePdfEngine() - { - string[] candidates = { "xelatex", "pdflatex", "lualatex", "typst", "weasyprint", "wkhtmltopdf" }; - foreach (var eng in candidates) - { - if (FindExecutableInPath(eng + ".exe") != null) - { - return eng; - } - } - return null; - } - - private static string? FindExecutableInPath(string exeName) - { - var pathTargets = new[] { EnvironmentVariableTarget.Process, EnvironmentVariableTarget.User, EnvironmentVariableTarget.Machine }; - foreach (var target in pathTargets) - { - try - { - string? pathEnv = Environment.GetEnvironmentVariable("PATH", target); - if (pathEnv != null) - { - foreach (var segment in pathEnv.Split(Path.PathSeparator)) - { - if (string.IsNullOrWhiteSpace(segment)) continue; - string combined = Path.Combine(segment.Trim(), exeName); - if (File.Exists(combined)) - return combined; - } - } - } - catch - { - // Sessizce geç - } - } - return null; - } - - public bool IsAvailable => ResolvePandocPath() != null; - - /// - /// Pandoc kullanarak Markdown veya ofis belgesini yüksek sadakatle dönüştürür. - /// Matematik denklemleri ($...$, $$...$$) için xelatex ve standart LaTeX desteği sağlar. - /// - public async Task ConvertAsync( - string inputFile, - string targetFormat, - ExportTransaction transaction, - CancellationToken token = default) - { - string? pandocPath = ResolvePandocPath(); - if (pandocPath == null) return null; - - string formatKey = targetFormat.ToLowerInvariant().TrimStart('.'); - string baseName = Path.GetFileNameWithoutExtension(inputFile); - string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, $"{baseName}.{formatKey}"); - - string arguments; - string? pdfEngine = ResolvePdfEngine(); - - if (formatKey == "pdf") - { - // Kullanıcının paylaştığı kusursuz parametreler: - // pandoc "belge.md" -o "belge.pdf" --pdf-engine=xelatex -V mainfont="Arial" -V geometry:margin=2.5cm - string engineParam = pdfEngine != null ? $"--pdf-engine={pdfEngine}" : ""; - arguments = $"\"{inputFile}\" -o \"{outputPath}\" {engineParam} -V mainfont=\"Arial\" -V geometry:margin=2.5cm".Trim(); - } - else - { - arguments = $"\"{inputFile}\" -o \"{outputPath}\""; - } - - var result = await ProcessRunner.RunAsync(pandocPath, arguments, token: token); - if (result.ExitCode == 0 && File.Exists(outputPath)) - { - return outputPath; - } - - // Eğer xelatex ile denendi ve başarısız olduysa, varsayılan pandoc parametresiyle tekrar dene - if (formatKey == "pdf" && !string.IsNullOrEmpty(pdfEngine)) - { - string fallbackArgs = $"\"{inputFile}\" -o \"{outputPath}\" -V geometry:margin=2.5cm"; - var fallbackResult = await ProcessRunner.RunAsync(pandocPath, fallbackArgs, token: token); - if (fallbackResult.ExitCode == 0 && File.Exists(outputPath)) - { - return outputPath; - } - } - - return null; - } -} diff --git a/src/Donustur.Engine/Documents/PandocInstaller.cs b/src/Donustur.Engine/Documents/PandocInstaller.cs deleted file mode 100644 index 96c5b23..0000000 --- a/src/Donustur.Engine/Documents/PandocInstaller.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System.Diagnostics; -using Donustur.Engine.Media; - -namespace Donustur.Engine.Documents; - -public static class PandocInstaller -{ - private static readonly object LockObj = new(); - private static Task? _activeInstallTask; - - public static bool IsInstalling - { - get - { - lock (LockObj) - { - return _activeInstallTask != null && !_activeInstallTask.IsCompleted; - } - } - } - - /// - /// Pandoc kurulu değilse Windows winget üzerinden sessizce kurar. - /// - public static Task EnsureOrInstallPandocAsync( - PandocEngine pandocEngine, - IProgress? progress = null, - CancellationToken token = default) - { - string? existing = pandocEngine.ResolvePandocPath(); - if (existing != null) - { - return Task.FromResult(existing); - } - - lock (LockObj) - { - if (_activeInstallTask != null && !_activeInstallTask.IsCompleted) - { - return _activeInstallTask; - } - - _activeInstallTask = Task.Run(async () => - { - progress?.Report("Pandoc aranıyor..."); - string? found = pandocEngine.ResolvePandocPath(); - if (found != null) return found; - - string? wingetPath = FfmpegInstaller.ResolveWingetPath(); - if (wingetPath != null) - { - try - { - progress?.Report("Pandoc, Windows Paket Yöneticisi (winget) ile indiriliyor..."); - string args = "install --id JohnMacFarlane.Pandoc --accept-package-agreements --accept-source-agreements --silent"; - - var result = await ProcessRunner.RunAsync(wingetPath, args, outputProgress: progress, token: token); - if (result.ExitCode == 0) - { - found = pandocEngine.ResolvePandocPath(); - if (found != null) - { - progress?.Report($"✓ Pandoc başarıyla kuruldu: {found}"); - return found; - } - } - } - catch (Exception ex) - { - progress?.Report($"✕ Pandoc kurulum hatası: {ex.Message}"); - } - } - - return pandocEngine.ResolvePandocPath(); - }, token); - - return _activeInstallTask; - } - } -} diff --git a/src/Donustur.Engine/Documents/PdfEngine.cs b/src/Donustur.Engine/Documents/PdfEngine.cs deleted file mode 100644 index 9279cf8..0000000 --- a/src/Donustur.Engine/Documents/PdfEngine.cs +++ /dev/null @@ -1,357 +0,0 @@ -using System.Text; -using Donustur.Core.Catalog; -using Donustur.Core.Transactions; -using Donustur.Core.Utils; -using ImageMagick; -using ImageMagick.Drawing; -using PdfSharpCore.Pdf; -using PdfSharpCore.Pdf.IO; -using UglyToad.PdfPig; -using UglyToad.PdfPig.DocumentLayoutAnalysis.TextExtractor; - -namespace Donustur.Engine.Documents; - -public sealed class PdfEngine -{ - /// - /// Çoklu PDF belgelerini (veya PDF + Görsel karışımını) tek bir PDF dosyasında birleştirir. - /// - public async Task MergePdfsAsync( - IReadOnlyList inputFiles, - ExportTransaction transaction, - string? outputName = null, - IProgress? progress = null, - CancellationToken token = default) - { - string name = string.IsNullOrWhiteSpace(outputName) ? "Birlestirilmis_Belge.pdf" : outputName; - if (!name.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)) - { - name += ".pdf"; - } - string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, name); - - await Task.Run(() => - { - using var outputDoc = new PdfSharpCore.Pdf.PdfDocument(); - - for (int i = 0; i < inputFiles.Count; i++) - { - token.ThrowIfCancellationRequested(); - string input = inputFiles[i]; - - if (FormatCatalog.IsPdf(input)) - { - using var inputDoc = PdfReader.Open(input, PdfDocumentOpenMode.Import); - for (int pageIndex = 0; pageIndex < inputDoc.PageCount; pageIndex++) - { - outputDoc.AddPage(inputDoc.Pages[pageIndex]); - } - } - else if (FormatCatalog.IsImage(input)) - { - string tempImgPdf = Path.Combine(Path.GetTempPath(), $"donustur_img_{Guid.NewGuid():N}.pdf"); - try - { - using (var img = new MagickImage(input)) - { - img.AutoOrient(); - img.Write(tempImgPdf, MagickFormat.Pdf); - } - using var imgPdfDoc = PdfReader.Open(tempImgPdf, PdfDocumentOpenMode.Import); - for (int pageIndex = 0; pageIndex < imgPdfDoc.PageCount; pageIndex++) - { - outputDoc.AddPage(imgPdfDoc.Pages[pageIndex]); - } - } - finally - { - if (File.Exists(tempImgPdf)) - { - try { File.Delete(tempImgPdf); } catch { } - } - } - } - - progress?.Report((double)(i + 1) / inputFiles.Count * 100.0); - } - - if (outputDoc.PageCount == 0) - { - throw new InvalidOperationException("Birleştirilecek geçerli bir PDF veya görsel sayfası bulunamadı."); - } - - outputDoc.Save(outputPath); - }, token); - - return outputPath; - } - - /// - /// Bir PDF belgesinin sayfalarını ayrı PDF dosyalarına böler. - /// - public async Task> SplitPdfAsync( - string inputPdf, - ExportTransaction transaction, - IProgress? progress = null, - CancellationToken token = default) - { - var outputPaths = new List(); - string baseName = Path.GetFileNameWithoutExtension(inputPdf); - - await Task.Run(() => - { - using var inputDoc = PdfReader.Open(inputPdf, PdfDocumentOpenMode.Import); - int total = inputDoc.PageCount; - - for (int i = 0; i < total; i++) - { - token.ThrowIfCancellationRequested(); - - using var singleDoc = new PdfSharpCore.Pdf.PdfDocument(); - singleDoc.AddPage(inputDoc.Pages[i]); - - string pageName = $"{baseName}_Sayfa_{i + 1:D2}.pdf"; - string pagePath = SafePaths.GetUniquePath(transaction.StagingDirectory, pageName); - singleDoc.Save(pagePath); - outputPaths.Add(pagePath); - - progress?.Report((double)(i + 1) / total * 100.0); - } - }, token); - - return outputPaths; - } - - /// - /// PDF belgesindeki tüm metinleri çıkarıp .txt dosyası olarak kaydeder. - /// - public async Task ExtractTextAsync( - string inputPdf, - ExportTransaction transaction, - IProgress? progress = null, - CancellationToken token = default) - { - string outName = Path.GetFileNameWithoutExtension(inputPdf) + ".txt"; - string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, outName); - - await Task.Run(() => - { - using var document = UglyToad.PdfPig.PdfDocument.Open(inputPdf); - var sb = new StringBuilder(); - int totalPages = document.NumberOfPages; - - for (int i = 1; i <= totalPages; i++) - { - token.ThrowIfCancellationRequested(); - var page = document.GetPage(i); - string pageText = ExtractPageTextFormatted(page); - - sb.AppendLine($"--- Sayfa {i} ---"); - sb.AppendLine(pageText); - sb.AppendLine(); - - progress?.Report((double)i / totalPages * 100.0); - } - - File.WriteAllText(outPath, sb.ToString(), Encoding.UTF8); - }, token); - - return outPath; - } - - /// - /// PDF belgesini Word (.docx) belgesine dönüştürür. - /// - public async Task ConvertToDocxAsync( - string inputPdf, - ExportTransaction transaction, - IProgress? progress = null, - CancellationToken token = default) - { - string outName = Path.GetFileNameWithoutExtension(inputPdf) + ".docx"; - string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, outName); - - await Task.Run(() => - { - using var document = UglyToad.PdfPig.PdfDocument.Open(inputPdf); - int totalPages = document.NumberOfPages; - var pages = new List(totalPages); - - for (int i = 1; i <= totalPages; i++) - { - token.ThrowIfCancellationRequested(); - var page = document.GetPage(i); - pages.Add(ExtractPageTextFormatted(page)); - progress?.Report((double)i / totalPages * 90.0); - } - - DocxHelper.CreateDocxFromPages(outPath, pages); - progress?.Report(100.0); - }, token); - - return outPath; - } - - /// - /// PDF içindeki görselleri veya sayfaları hedef görsel formatında (png/jpg) dışa aktarır. - /// - public async Task> ExtractImagesAsync( - string inputPdf, - ExportTransaction transaction, - IProgress? progress = null, - CancellationToken token = default, - string targetFormat = "png") - { - var outputs = new List(); - string baseName = Path.GetFileNameWithoutExtension(inputPdf); - bool isJpg = targetFormat.Equals("jpg", StringComparison.OrdinalIgnoreCase) || - targetFormat.Equals("jpeg", StringComparison.OrdinalIgnoreCase) || - targetFormat.Equals("pdf_to_jpg", StringComparison.OrdinalIgnoreCase); - - string ext = isJpg ? ".jpg" : ".png"; - MagickFormat magickFormat = isJpg ? MagickFormat.Jpg : MagickFormat.Png; - - await Task.Run(() => - { - using var document = UglyToad.PdfPig.PdfDocument.Open(inputPdf); - int totalPages = document.NumberOfPages; - int imageIndex = 1; - - for (int i = 1; i <= totalPages; i++) - { - token.ThrowIfCancellationRequested(); - var page = document.GetPage(i); - var images = page.GetImages().ToList(); - int extractedOnPage = 0; - - foreach (var pdfImg in images) - { - try - { - MagickImage? mImg = null; - if (pdfImg.TryGetPng(out byte[]? pngBytes) && pngBytes != null && pngBytes.Length > 0) - { - mImg = new MagickImage(pngBytes); - } - else - { - byte[] rawBytes = pdfImg.RawBytes.ToArray(); - if (rawBytes.Length > 0) - { - mImg = new MagickImage(rawBytes); - } - } - - if (mImg != null) - { - using (mImg) - { - if (isJpg) - { - if (mImg.HasAlpha) - { - mImg.ColorAlpha(MagickColors.White); - } - mImg.Quality = 90; - } - - string imgName = $"{baseName}_Sayfa{i:D2}_Gorsel{imageIndex:D2}{ext}"; - string imgPath = SafePaths.GetUniquePath(transaction.StagingDirectory, imgName); - mImg.Write(imgPath, magickFormat); - outputs.Add(imgPath); - imageIndex++; - extractedOnPage++; - } - } - } - catch - { - // Desteklenmeyen ham görsel akışını atla - } - } - - // Eğer sayfada gömülü bitmap yoksa, sayfa metnini yüksek çözünürlüklü görsel sayfasına işle - if (extractedOnPage == 0) - { - string pageText = ExtractPageTextFormatted(page); - string pageImgName = $"{baseName}_Sayfa_{i:D2}{ext}"; - string pageImgPath = SafePaths.GetUniquePath(transaction.StagingDirectory, pageImgName); - RenderTextPageToImage(pageText, i, totalPages, pageImgPath, magickFormat); - outputs.Add(pageImgPath); - } - - progress?.Report((double)i / totalPages * 100.0); - } - }, token); - - return outputs; - } - - private static string ExtractPageTextFormatted(UglyToad.PdfPig.Content.Page page) - { - try - { - string ordered = ContentOrderTextExtractor.GetText(page); - if (!string.IsNullOrWhiteSpace(ordered)) - { - return ordered; - } - } - catch - { - // Yedek olarak standart page.Text kullan - } - return page.Text ?? string.Empty; - } - - private static void RenderTextPageToImage(string pageText, int pageNumber, int totalPages, string outputPath, MagickFormat format) - { - using var canvas = new MagickImage(MagickColors.White, 1240, 1754); - var drawables = new Drawables() - .Font("Arial") - .FontPointSize(18) - .FillColor(MagickColors.Black); - - string[] rawLines = (pageText ?? string.Empty).Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); - double y = 80; - const int maxCharsPerLine = 95; - - foreach (var rawLine in rawLines) - { - if (y > 1660) break; - - if (string.IsNullOrWhiteSpace(rawLine)) - { - y += 24; - continue; - } - - string remaining = rawLine; - while (remaining.Length > 0 && y <= 1660) - { - string chunk = remaining.Length > maxCharsPerLine - ? remaining[..maxCharsPerLine] - : remaining; - remaining = remaining.Length > maxCharsPerLine - ? remaining[maxCharsPerLine..] - : string.Empty; - - drawables.Text(70, y, chunk); - y += 26; - } - } - - // Sayfa alt bilgisi - drawables - .FontPointSize(14) - .FillColor(new MagickColor("#6B7280")) - .Text(560, 1710, $"Sayfa {pageNumber} / {totalPages}"); - - canvas.Draw(drawables); - if (format == MagickFormat.Jpg) - { - canvas.Quality = 90; - } - canvas.Write(outputPath, format); - } -} diff --git a/src/Donustur.Engine/Donustur.Engine.csproj b/src/Donustur.Engine/Donustur.Engine.csproj deleted file mode 100644 index 3b6d7eb..0000000 --- a/src/Donustur.Engine/Donustur.Engine.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - net8.0 - enable - enable - - - diff --git a/src/Donustur.Engine/Images/ImageMagickEngine.cs b/src/Donustur.Engine/Images/ImageMagickEngine.cs deleted file mode 100644 index 37323e2..0000000 --- a/src/Donustur.Engine/Images/ImageMagickEngine.cs +++ /dev/null @@ -1,177 +0,0 @@ -using ImageMagick; -using Donustur.Core.Models; -using Donustur.Core.Transactions; -using Donustur.Core.Utils; - -namespace Donustur.Engine.Images; - -public sealed class ImageMagickEngine -{ - private static readonly HashSet SupportedImageExtensions = new(StringComparer.OrdinalIgnoreCase) - { - "jpg", "jpeg", "png", "webp", "avif", "bmp", "tiff", "tif", "gif", "ico", "svg", "heic", "heif" - }; - - public bool CanHandle(string extension) - { - return SupportedImageExtensions.Contains(extension.TrimStart('.')); - } - - /// - /// Tek veya çoklu görselleri hedef formata dönüştürür. - /// - public async Task> ConvertImagesAsync( - IReadOnlyList inputFiles, - string targetFormat, - ExportTransaction transaction, - ConversionOptions options, - IProgress? progress = null, - CancellationToken token = default) - { - var outputPaths = new List(); - string formatKey = targetFormat.ToLowerInvariant().TrimStart('.'); - - // Çoklu görsellerden tek PDF oluşturma - if (formatKey == "pdf") - { - string pdfName = inputFiles.Count == 1 - ? Path.GetFileNameWithoutExtension(inputFiles[0]) + ".pdf" - : "Birlestirilmis_Gorseller.pdf"; - - string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, pdfName); - - await Task.Run(() => - { - using var collection = new MagickImageCollection(); - for (int i = 0; i < inputFiles.Count; i++) - { - token.ThrowIfCancellationRequested(); - var image = new MagickImage(inputFiles[i]); - image.AutoOrient(); - collection.Add(image); - progress?.Report((double)(i + 1) / inputFiles.Count * 100.0); - } - collection.Write(outPath, MagickFormat.Pdf); - }, token); - - outputPaths.Add(outPath); - return outputPaths; - } - - // Çoklu görsellerden animasyonlu GIF oluşturma - if (formatKey == "gif" && inputFiles.Count > 1) - { - string gifName = "Animasyon.gif"; - string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, gifName); - - await Task.Run(() => - { - using var collection = new MagickImageCollection(); - for (int i = 0; i < inputFiles.Count; i++) - { - token.ThrowIfCancellationRequested(); - var img = new MagickImage(inputFiles[i]); - img.AutoOrient(); - img.AnimationDelay = 40; // 400ms - collection.Add(img); - progress?.Report((double)(i + 1) / inputFiles.Count * 90.0); - } - collection.Optimize(); - collection.Write(outPath, MagickFormat.Gif); - progress?.Report(100.0); - }, token); - - outputPaths.Add(outPath); - return outputPaths; - } - - // Birebir görsel dönüşümleri - MagickFormat magickFormat = MapFormat(formatKey); - - for (int i = 0; i < inputFiles.Count; i++) - { - token.ThrowIfCancellationRequested(); - string inputPath = inputFiles[i]; - string fileNameWithoutExt = Path.GetFileNameWithoutExtension(inputPath); - string extensionWithDot = formatKey == "compress_image" - ? Path.GetExtension(inputPath) - : "." + formatKey; - - string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, fileNameWithoutExt + extensionWithDot); - - await Task.Run(() => - { - using var image = new MagickImage(inputPath); - image.AutoOrient(); - - if (options.StripMetadata) - { - image.Strip(); - } - - if (options.ResizeWidth.HasValue || options.ResizeHeight.HasValue) - { - var geo = new MagickGeometry((uint)(options.ResizeWidth ?? 0), (uint)(options.ResizeHeight ?? 0)) - { - IgnoreAspectRatio = false - }; - image.Resize(geo); - } - - if (formatKey == "compress_image") - { - image.Quality = (uint)System.Math.Clamp(options.ImageQuality, 10, 95); - image.Strip(); - image.Write(outPath); - } - else if (magickFormat == MagickFormat.Ico) - { - // Oranı koruyarak 256x256 şeffaf tuvale ortala - image.Resize(new MagickGeometry(256, 256) { IgnoreAspectRatio = false }); - image.BackgroundColor = MagickColors.Transparent; - image.Extent(256, 256, Gravity.Center); - image.Write(outPath, MagickFormat.Ico); - } - else - { - if (magickFormat is MagickFormat.Jpg or MagickFormat.Jpeg) - { - // Şeffaf PNG/WebP görseller JPG'ye çevrilirken siyah arka plan oluşmasını önle - if (image.HasAlpha) - { - image.ColorAlpha(MagickColors.White); - } - } - - if (magickFormat is MagickFormat.Jpg or MagickFormat.Jpeg or MagickFormat.WebP or MagickFormat.Avif) - { - image.Quality = (uint)System.Math.Clamp(options.ImageQuality, 10, 100); - } - image.Write(outPath, magickFormat); - } - }, token); - - outputPaths.Add(outPath); - progress?.Report((double)(i + 1) / inputFiles.Count * 100.0); - } - - return outputPaths; - } - - private static MagickFormat MapFormat(string format) - { - return format.ToLowerInvariant() switch - { - "png" => MagickFormat.Png, - "jpg" or "jpeg" => MagickFormat.Jpg, - "webp" => MagickFormat.WebP, - "avif" => MagickFormat.Avif, - "bmp" => MagickFormat.Bmp, - "tiff" or "tif" => MagickFormat.Tiff, - "ico" => MagickFormat.Ico, - "gif" => MagickFormat.Gif, - "pdf" => MagickFormat.Pdf, - _ => MagickFormat.Png - }; - } -} diff --git a/src/Donustur.Engine/Media/FfmpegInstaller.cs b/src/Donustur.Engine/Media/FfmpegInstaller.cs deleted file mode 100644 index d8e9e41..0000000 --- a/src/Donustur.Engine/Media/FfmpegInstaller.cs +++ /dev/null @@ -1,194 +0,0 @@ -using System.Diagnostics; -using System.IO.Compression; -using System.Net.Http; -using Donustur.Core.Utils; - -namespace Donustur.Engine.Media; - -public static class FfmpegInstaller -{ - private static readonly object LockObj = new(); - private static Task? _activeInstallTask; - - public static bool IsInstalling - { - get - { - lock (LockObj) - { - return _activeInstallTask != null && !_activeInstallTask.IsCompleted; - } - } - } - - /// - /// FFmpeg kurulu değilse Windows winget veya doğrudan resmi GitHub kaynağından - /// indirip kurar. Eşzamanlı çağrıları güvenle tek bir kuruluma yönlendirir. - /// - public static Task EnsureOrInstallFfmpegAsync( - MediaEngine mediaEngine, - IProgress? progress = null, - CancellationToken token = default) - { - // 1. Zaten mevcutsa anında döndür - string? existing = mediaEngine.ResolveFfmpegPath(); - if (existing != null) - { - return Task.FromResult(existing); - } - - lock (LockObj) - { - if (_activeInstallTask != null && !_activeInstallTask.IsCompleted) - { - return _activeInstallTask; - } - - _activeInstallTask = Task.Run(() => PerformInstallAsync(mediaEngine, progress, token), token); - return _activeInstallTask; - } - } - - private static async Task PerformInstallAsync( - MediaEngine mediaEngine, - IProgress? progress, - CancellationToken token) - { - progress?.Report("FFmpeg taranıyor..."); - - // 1. Derin tarama - string? found = mediaEngine.ResolveFfmpegPath(); - if (found != null) - { - progress?.Report($"FFmpeg bulundu: {found}"); - return found; - } - - // 2. Yöntem 1: Windows Paket Yöneticisi (winget) - string? wingetPath = ResolveWingetPath(); - if (wingetPath != null) - { - try - { - progress?.Report("FFmpeg, Windows Paket Yöneticisi (winget) ile indiriliyor..."); - string args = "install --id Gyan.FFmpeg.Essentials --accept-package-agreements --accept-source-agreements --silent"; - - var result = await ProcessRunner.RunAsync( - wingetPath, - args, - outputProgress: progress, - token: token); - - if (result.ExitCode == 0) - { - // Çevre değişkenlerini ve winget paket klasörünü yeniden tara - found = mediaEngine.ResolveFfmpegPath(); - if (found != null) - { - progress?.Report($"✓ FFmpeg başarıyla kuruldu: {found}"); - return found; - } - } - } - catch - { - // Winget başarısız olursa doğrudan indirme yöntemine geç - } - } - - // 3. Yöntem 2: Doğrudan resmi GitHub sürümünden taşınabilir FFmpeg indirme - try - { - progress?.Report("FFmpeg resmi sunucudan doğrudan indiriliyor..."); - string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - string toolsDir = Path.Combine(localAppData, "LDConverter", "tools"); - Directory.CreateDirectory(toolsDir); - - string zipPath = Path.Combine(toolsDir, "ffmpeg_download.zip"); - string targetExePath = Path.Combine(toolsDir, "ffmpeg.exe"); - - // GyanD / FFmpeg essentials build doğrudan indirme URL'si - string downloadUrl = "https://github.com/GyanD/codexffmpeg/releases/download/7.1/ffmpeg-7.1-essentials_build.zip"; - - using (var httpClient = new HttpClient { Timeout = TimeSpan.FromMinutes(5) }) - { - httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LDConverter/1.3.0"); - - using var response = await httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead, token); - response.EnsureSuccessStatusCode(); - - long? totalBytes = response.Content.Headers.ContentLength; - await using (var contentStream = await response.Content.ReadAsStreamAsync(token)) - await using (var fileStream = new FileStream(zipPath, FileMode.Create, FileAccess.Write, FileShare.None, 81920, true)) - { - var buffer = new byte[81920]; - long totalRead = 0; - int read; - - while ((read = await contentStream.ReadAsync(buffer, token)) > 0) - { - await fileStream.WriteAsync(buffer.AsMemory(0, read), token); - totalRead += read; - - if (totalBytes.HasValue && totalBytes.Value > 0) - { - double pct = (double)totalRead / totalBytes.Value * 100.0; - progress?.Report($"FFmpeg indiriliyor: %{pct:F0}"); - } - } - } - } - - progress?.Report("FFmpeg paketi açılıyor..."); - using (var archive = ZipFile.OpenRead(zipPath)) - { - var ffmpegEntry = archive.Entries.FirstOrDefault(e => e.Name.Equals("ffmpeg.exe", StringComparison.OrdinalIgnoreCase)); - if (ffmpegEntry != null) - { - ffmpegEntry.ExtractToFile(targetExePath, overwrite: true); - } - } - - try { File.Delete(zipPath); } catch { } - - if (File.Exists(targetExePath)) - { - mediaEngine.SetCustomPath(targetExePath); - progress?.Report($"✓ FFmpeg başarıyla hazırlandı: {targetExePath}"); - return targetExePath; - } - } - catch (Exception ex) - { - progress?.Report($"✕ FFmpeg indirme hatası: {ex.Message}"); - } - - return mediaEngine.ResolveFfmpegPath(); - } - - public static string? ResolveWingetPath() - { - string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - string defaultWinget = Path.Combine(localAppData, @"Microsoft\WindowsApps\winget.exe"); - if (File.Exists(defaultWinget)) - { - return defaultWinget; - } - - string? pathEnv = Environment.GetEnvironmentVariable("PATH"); - if (pathEnv != null) - { - foreach (var segment in pathEnv.Split(Path.PathSeparator)) - { - if (string.IsNullOrWhiteSpace(segment)) continue; - string candidate = Path.Combine(segment.Trim(), "winget.exe"); - if (File.Exists(candidate)) - { - return candidate; - } - } - } - - return null; - } -} diff --git a/src/Donustur.Engine/Media/MediaEngine.cs b/src/Donustur.Engine/Media/MediaEngine.cs deleted file mode 100644 index c85dea1..0000000 --- a/src/Donustur.Engine/Media/MediaEngine.cs +++ /dev/null @@ -1,226 +0,0 @@ -using Donustur.Core.Models; -using Donustur.Core.Transactions; -using Donustur.Core.Utils; - -namespace Donustur.Engine.Media; - -public sealed class MediaEngine -{ - private string? _customPath; - - public MediaEngine(string? customPath = null) - { - _customPath = customPath; - } - - public void SetCustomPath(string? customPath) - { - _customPath = customPath; - } - - /// - /// FFmpeg çalıştırılabilir dosya yolunu bulur. - /// - public string? ResolveFfmpegPath() - { - if (!string.IsNullOrWhiteSpace(_customPath) && File.Exists(_customPath)) - { - return _customPath; - } - - string baseDir = AppContext.BaseDirectory; - string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - - string[] candidatePaths = - { - Path.Combine(localAppData, @"LDConverter\tools\ffmpeg.exe"), - Path.Combine(baseDir, "tools", "ffmpeg.exe"), - Path.Combine(baseDir, "ffmpeg.exe"), - Path.Combine(localAppData, @"Microsoft\WindowsApps\ffmpeg.exe"), - Path.Combine(localAppData, @"Microsoft\WinGet\Links\ffmpeg.exe"), - Path.Combine(userProfile, @"scoop\shims\ffmpeg.exe"), - @"C:\ffmpeg\bin\ffmpeg.exe", - @"C:\ffmpeg\ffmpeg.exe", - @"C:\Program Files\ffmpeg\bin\ffmpeg.exe", - @"C:\Program Files\ffmpeg\ffmpeg.exe", - @"C:\ProgramData\chocolatey\bin\ffmpeg.exe" - }; - - foreach (var path in candidatePaths) - { - if (File.Exists(path)) - return path; - } - - // WinGet paket klasörlerini dinamik ve güvenli (hata fırlatmayan) tara - string wingetPackages = Path.Combine(localAppData, @"Microsoft\WinGet\Packages"); - if (Directory.Exists(wingetPackages)) - { - try - { - foreach (var pkgDir in Directory.EnumerateDirectories(wingetPackages)) - { - string dirName = Path.GetFileName(pkgDir); - if (dirName.Contains("ffmpeg", StringComparison.OrdinalIgnoreCase) || - dirName.Contains("gyan", StringComparison.OrdinalIgnoreCase)) - { - var found = SafeFindFile(pkgDir, "ffmpeg.exe", maxDepth: 4); - if (found != null) - return found; - } - } - } - catch - { - // Erişim hatasında devam et - } - } - - // PATH çevre değişkenlerini Process, User ve Machine seviyelerinde kontrol et - var pathTargets = new[] { EnvironmentVariableTarget.Process, EnvironmentVariableTarget.User, EnvironmentVariableTarget.Machine }; - foreach (var target in pathTargets) - { - try - { - string? pathEnv = Environment.GetEnvironmentVariable("PATH", target); - 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; - } - } - } - catch - { - // Sessizce geç - } - } - - return null; - } - - private static string? SafeFindFile(string rootDir, string targetFileName, int maxDepth) - { - if (!Directory.Exists(rootDir) || maxDepth < 0) return null; - try - { - string direct = Path.Combine(rootDir, targetFileName); - if (File.Exists(direct)) return direct; - - string inBin = Path.Combine(rootDir, "bin", targetFileName); - if (File.Exists(inBin)) return inBin; - - foreach (var subDir in Directory.EnumerateDirectories(rootDir)) - { - var found = SafeFindFile(subDir, targetFileName, maxDepth - 1); - if (found != null) return found; - } - } - catch - { - // Erişim izin hatalarını yut - } - return null; - } - - public bool IsAvailable => ResolveFfmpegPath() != null; - - /// - /// Video veya ses dosyasını hedef formata dönüştürür. - /// FFmpeg eksikse otomatik kurulum dener; bulunamazsa kullanıcıya yol gösterir. - /// - public async Task> ConvertMediaAsync( - IReadOnlyList inputFiles, - string targetFormat, - ExportTransaction transaction, - ConversionOptions options, - IProgress? progress = null, - CancellationToken token = default) - { - string? ffmpegPath = ResolveFfmpegPath(); - if (ffmpegPath == null) - { - // Eksikse son anda otomatik kurulumu tetikle - ffmpegPath = await FfmpegInstaller.EnsureOrInstallFfmpegAsync(this, null, token); - } - - if (ffmpegPath == null) - { - throw new FileNotFoundException( - "FFmpeg bulunamadı ve otomatik indirilemedi. Video & ses dönüştürmeleri için lütfen Ayarlar ekranından FFmpeg indir butonuna tıklayın veya ffmpeg.exe yolunu seçin."); - } - - var outputFiles = new List(); - string formatKey = targetFormat.ToLowerInvariant().TrimStart('.'); - - for (int i = 0; i < inputFiles.Count; i++) - { - token.ThrowIfCancellationRequested(); - string inputFile = inputFiles[i]; - string fileName = Path.GetFileNameWithoutExtension(inputFile); - string outputExt = GetExtensionForFormat(formatKey, inputFile); - string outputPath = SafePaths.GetUniquePath(transaction.StagingDirectory, fileName + outputExt); - - string arguments = BuildArguments(inputFile, outputPath, formatKey, options); - - var result = await ProcessRunner.RunAsync(ffmpegPath, arguments, token: token); - if (result.ExitCode != 0) - { - throw new InvalidOperationException($"FFmpeg dönüştürme hatası ({result.ExitCode}): {result.StandardError}"); - } - - if (File.Exists(outputPath)) - { - outputFiles.Add(outputPath); - } - - progress?.Report((double)(i + 1) / inputFiles.Count * 100.0); - } - - return outputFiles; - } - - private static string GetExtensionForFormat(string formatKey, string inputFile) - { - return formatKey switch - { - "mp4" => ".mp4", - "mkv" => ".mkv", - "webm" => ".webm", - "mp3" => ".mp3", - "wav" => ".wav", - "aac" => ".m4a", - "flac" => ".flac", - "ogg" => ".ogg", - "gif" => ".gif", - // Sıkıştırma işlemlerinde H.264/MP3 kodekleriyle tam uyumluluk için standart konteyner kullan - "compress_video" => ".mp4", - "compress_audio" => ".mp3", - _ => "." + formatKey - }; - } - - private static string BuildArguments(string input, string output, string formatKey, ConversionOptions options) - { - return formatKey switch - { - "mp4" => $"-y -i \"{input}\" -c:v libx264 -preset {options.VideoPreset} -crf {options.VideoCrf} -c:a aac -b:a {options.AudioBitrate} \"{output}\"", - "mkv" => $"-y -i \"{input}\" -c:v libx264 -preset {options.VideoPreset} -crf {options.VideoCrf} -c:a aac \"{output}\"", - "webm" => $"-y -i \"{input}\" -c:v libvpx-vp9 -b:v 0 -crf 30 -c:a libopus \"{output}\"", - "mp3" => $"-y -i \"{input}\" -vn -c:a libmp3lame -b:a {options.AudioBitrate} \"{output}\"", - "wav" => $"-y -i \"{input}\" -vn -c:a pcm_s16le \"{output}\"", - "aac" => $"-y -i \"{input}\" -vn -c:a aac -b:a {options.AudioBitrate} \"{output}\"", - "flac" => $"-y -i \"{input}\" -vn -c:a flac \"{output}\"", - "ogg" => $"-y -i \"{input}\" -vn -c:a libvorbis -q:a 5 \"{output}\"", - "gif" => $"-y -i \"{input}\" -vf \"fps=15,scale=480:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse\" \"{output}\"", - "compress_video" => $"-y -i \"{input}\" -c:v libx264 -crf 28 -preset fast -c:a aac -b:a 128k \"{output}\"", - "compress_audio" => $"-y -i \"{input}\" -vn -c:a libmp3lame -b:a 96k \"{output}\"", - _ => $"-y -i \"{input}\" \"{output}\"" - }; - } -} diff --git a/src/Donustur.Engine/ProcessRunner.cs b/src/Donustur.Engine/ProcessRunner.cs deleted file mode 100644 index 0570eca..0000000 --- a/src/Donustur.Engine/ProcessRunner.cs +++ /dev/null @@ -1,104 +0,0 @@ -using System.Diagnostics; -using System.Text; - -namespace Donustur.Engine; - -public static class ProcessRunner -{ - public sealed record ProcessOutput(int ExitCode, string StandardOutput, string StandardError); - - /// - /// Harici CLI araçlarını (FFmpeg, LibreOffice vb.) UI'ı dondurmadan, - /// CancellationToken ile süreç ağacını sonlandırabilen güvenli çalıştırıcı. - /// - public static async Task RunAsync( - string exePath, - string arguments, - string? workingDirectory = null, - IProgress? outputProgress = null, - CancellationToken token = default) - { - if (!File.Exists(exePath)) - { - throw new FileNotFoundException($"Çalıştırılacak araç bulunamadı: {exePath}"); - } - - var psi = new ProcessStartInfo - { - FileName = exePath, - Arguments = arguments, - WorkingDirectory = workingDirectory ?? Path.GetDirectoryName(exePath) ?? string.Empty, - CreateNoWindow = true, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - StandardOutputEncoding = Encoding.UTF8, - StandardErrorEncoding = Encoding.UTF8 - }; - - using var process = new Process { StartInfo = psi, EnableRaisingEvents = true }; - var stdOut = new StringBuilder(); - var stdErr = new StringBuilder(); - long lastReportTicks = 0; - - void ReportThrottled(string line) - { - if (outputProgress == null) return; - long now = Environment.TickCount64; - if (now - Interlocked.Read(ref lastReportTicks) >= 60) // En fazla ~16 FPS raporlama (WPF Dispatcher koruması) - { - Interlocked.Exchange(ref lastReportTicks, now); - outputProgress.Report(line); - } - } - - process.OutputDataReceived += (_, e) => - { - if (e.Data != null) - { - lock (stdOut) - { - stdOut.AppendLine(e.Data); - } - ReportThrottled(e.Data); - } - }; - - process.ErrorDataReceived += (_, e) => - { - if (e.Data != null) - { - lock (stdErr) - { - stdErr.AppendLine(e.Data); - } - ReportThrottled(e.Data); - } - }; - - process.Start(); - process.BeginOutputReadLine(); - process.BeginErrorReadLine(); - - // CancellationToken ile işlem iptal edilirse süreci ve alt süreçlerini zorla sonlandır - using (token.Register(() => - { - try - { - if (!process.HasExited) - { - process.Kill(entireProcessTree: true); - } - } - catch - { - // Süreç zaten kapanmış olabilir - } - })) - { - await process.WaitForExitAsync(token); - } - - return new ProcessOutput(process.ExitCode, stdOut.ToString(), stdErr.ToString()); - } -} diff --git a/src/Donustur.Engine/Qr/QrEngine.cs b/src/Donustur.Engine/Qr/QrEngine.cs deleted file mode 100644 index 9dfb08e..0000000 --- a/src/Donustur.Engine/Qr/QrEngine.cs +++ /dev/null @@ -1,161 +0,0 @@ -using Donustur.Core.Catalog; -using Donustur.Core.Transactions; -using Donustur.Core.Utils; -using ImageMagick; -using UglyToad.PdfPig; -using ZXing; -using ZXing.Common; -using ZXing.QrCode; - -namespace Donustur.Engine.Qr; - -public sealed class QrEngine -{ - /// - /// Görsel veya PDF dosyasından QR kod(ları) okur ve metnini döner. - /// - public string? ReadQrCode(string filePath) - { - if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath)) - return null; - - if (FormatCatalog.IsPdf(filePath)) - { - return ReadQrFromPdf(filePath); - } - - try - { - using var image = new MagickImage(filePath); - return DecodeFromMagickImage(image); - } - catch - { - return null; - } - } - - private static string? ReadQrFromPdf(string pdfPath) - { - try - { - var foundTexts = new List(); - using var document = PdfDocument.Open(pdfPath); - - for (int i = 1; i <= document.NumberOfPages; i++) - { - var page = document.GetPage(i); - foreach (var pdfImg in page.GetImages()) - { - try - { - MagickImage? mImg = null; - if (pdfImg.TryGetPng(out byte[]? pngBytes) && pngBytes != null && pngBytes.Length > 0) - { - mImg = new MagickImage(pngBytes); - } - else - { - byte[] raw = pdfImg.RawBytes.ToArray(); - if (raw.Length > 0) - { - mImg = new MagickImage(raw); - } - } - - if (mImg != null) - { - using (mImg) - { - string? decoded = DecodeFromMagickImage(mImg); - if (!string.IsNullOrWhiteSpace(decoded) && !foundTexts.Contains(decoded)) - { - foundTexts.Add(decoded); - } - } - } - } - catch - { - // Okunamayan alt görselleri atla - } - } - } - - return foundTexts.Count > 0 ? string.Join(Environment.NewLine + Environment.NewLine, foundTexts) : null; - } - catch - { - return null; - } - } - - private static string? DecodeFromMagickImage(MagickImage image) - { - image.AutoOrient(); - - // Şeffaf arka planlı QR kodların doğru okunması için beyaz zemine oturt - if (image.HasAlpha) - { - image.ColorAlpha(MagickColors.White); - } - - using var pixels = image.GetPixels(); - byte[]? rgb = pixels.ToByteArray(PixelMapping.RGB); - if (rgb == null) return null; - - var luminanceSource = new RGBLuminanceSource( - rgb, - (int)image.Width, - (int)image.Height, - RGBLuminanceSource.BitmapFormat.RGB24); - - var reader = new BarcodeReaderGeneric - { - AutoRotate = true, - Options = new DecodingOptions - { - TryHarder = true, - PossibleFormats = new[] { BarcodeFormat.QR_CODE, BarcodeFormat.DATA_MATRIX, BarcodeFormat.AZTEC, BarcodeFormat.CODE_128, BarcodeFormat.EAN_13 } - } - }; - - var result = reader.Decode(luminanceSource); - return result?.Text; - } - - /// - /// Verilen metinden yüksek çözünürlüklü bir QR kod PNG görseli üretir. - /// - public string GenerateQrCode(string text, ExportTransaction transaction, int size = 600) - { - string outPath = SafePaths.GetUniquePath(transaction.StagingDirectory, "Karekod_" + Guid.NewGuid().ToString("N")[..6] + ".png"); - - var writer = new BarcodeWriterPixelData - { - Format = BarcodeFormat.QR_CODE, - Options = new QrCodeEncodingOptions - { - Width = size, - Height = size, - Margin = 4, - CharacterSet = "UTF-8" - } - }; - - var pixelData = writer.Write(text); - - // PixelDataRenderer varsayılan olarak BGRA32 üretir (B, G, R, A) - var readSettings = new MagickReadSettings - { - Width = (uint)pixelData.Width, - Height = (uint)pixelData.Height, - Format = MagickFormat.Bgra - }; - - using var image = new MagickImage(pixelData.Pixels, readSettings); - image.Write(outPath, MagickFormat.Png); - - return outPath; - } -} diff --git a/src/Donustur.UI/App.xaml b/src/Donustur.UI/App.xaml deleted file mode 100644 index be95b0d..0000000 --- a/src/Donustur.UI/App.xaml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - diff --git a/src/Donustur.UI/App.xaml.cs b/src/Donustur.UI/App.xaml.cs deleted file mode 100644 index d820ba4..0000000 --- a/src/Donustur.UI/App.xaml.cs +++ /dev/null @@ -1,202 +0,0 @@ -using System.IO; -using System.Windows; -using Donustur.Core.Models; -using Donustur.Core.Services; -using Donustur.Engine; -using Donustur.UI.Services; -using Donustur.UI.Windows; - -namespace Donustur.UI; - -public partial class App : Application -{ - private SingleInstance? _singleInstance; - private PreferencesStore? _preferencesStore; - private HistoryStore? _historyStore; - private ConversionDispatcher? _dispatcher; - private GlobalDragController? _dragController; - private TrayHost? _trayHost; - private MainWindow? _mainWindow; - private bool _isExiting; - - protected override void OnStartup(StartupEventArgs e) - { - // 1. Aynı anda iki kez açılmasını senkron olarak engelle - _singleInstance = new SingleInstance(); - if (!_singleInstance.IsPrimaryInstance) - { - SingleInstance.NotifyAndFocusPrimaryInstance(e.Args); - _singleInstance.Dispose(); - Environment.Exit(0); - return; - } - - base.OnStartup(e); - - DispatcherUnhandledException += (_, args) => - { - args.Handled = true; - MessageBox.Show( - $"Beklenmeyen bir hata oluştu:\n{args.Exception.Message}", - "LD Converter", - MessageBoxButton.OK, - MessageBoxImage.Warning); - }; - - TaskScheduler.UnobservedTaskException += (_, args) => - { - args.SetObserved(); - }; - - _singleInstance.StartListening(); - _singleInstance.ShowRequestReceived += BringMainWindowToFront; - _singleInstance.FilesReceived += files => - { - _mainWindow?.SetSelectedFiles(files); - }; - - // Servisleri başlat - _preferencesStore = new PreferencesStore(); - _historyStore = new HistoryStore(); - _dispatcher = new ConversionDispatcher(_preferencesStore.Current, _historyStore); - - // Global sürükleme ve çark kontrolcüsü - _dragController = new GlobalDragController(_preferencesStore, HandleWheelDroppedFiles); - - // Sistem Tepsisi (Tray) - _trayHost = new TrayHost( - _preferencesStore, - openMainWindow: BringMainWindowToFront, - openSettings: OpenSettingsWindow, - exitApp: ExitApplication); - - _preferencesStore.Changed += _ => _trayHost.UpdateStatus(); - - // Ana Pencereyi Oluştur - _mainWindow = new MainWindow( - _preferencesStore, - _historyStore, - _dispatcher, - onExitRequested: ExitApplication); - - // Komut satırı argümanları (Dosya veya klasör ile açılmışsa) - if (e.Args.Length > 0) - { - var validPaths = e.Args.Where(p => File.Exists(p) || Directory.Exists(p)).ToList(); - if (validPaths.Count > 0) - { - _mainWindow.SetSelectedFiles(validPaths); - } - } - - _mainWindow.Show(); - } - - private void BringMainWindowToFront() - { - if (_mainWindow == null) return; - - if (!_mainWindow.IsVisible) - { - _mainWindow.Show(); - } - - if (_mainWindow.WindowState == WindowState.Minimized) - { - _mainWindow.WindowState = WindowState.Normal; - } - - _mainWindow.Topmost = true; - _mainWindow.Activate(); - _mainWindow.Topmost = false; - _mainWindow.Focus(); - } - - private void OpenSettingsWindow() - { - if (_preferencesStore == null) return; - var win = new SettingsWindow(_preferencesStore); - if (_mainWindow != null && _mainWindow.IsVisible) - { - win.Owner = _mainWindow; - } - win.ShowDialog(); - } - - private async void HandleWheelDroppedFiles(ToolChoice choice, IReadOnlyList files) - { - if (_dispatcher == null || _preferencesStore == null || files.Count == 0) return; - - using var cts = new CancellationTokenSource(); - - // Kayan bildirim penceresi oluştur - var toast = new ProgressToastWindow( - $"{choice.DisplayName} Dönüştürülüyor...", - onCancelRequested: () => cts.Cancel()); - toast.Show(); - - var progress = new Progress(val => - { - toast.UpdateProgress(val, $"{choice.DisplayName} işleniyor (%{val:F0})..."); - }); - - var task = new ConversionTask - { - InputFiles = files, - TargetActionId = choice.Id, - TargetDisplayName = choice.DisplayName, - Options = new ConversionOptions - { - ImageQuality = _preferencesStore.Current.DefaultImageQuality - } - }; - - var result = await _dispatcher.ExecuteTaskAsync(task, _preferencesStore.Current, progress, cts.Token); - - if (result.Success) - { - string? decodedQr = choice.Id == "qr_read" ? task.CurrentStatusMessage : null; - toast.SetCompleted(result.OutputFiles, decodedQr); - - if (_preferencesStore.Current.SoundEffectsEnabled) - { - SoundFeedback.PlaySuccess(); - } - - if (_preferencesStore.Current.AutoOpenOutputFolder && result.OutputFiles.Count > 0) - { - DesktopGeometry.RevealInExplorer(result.OutputFiles[0]); - } - } - else - { - toast.SetFailed(result.ErrorMessage ?? "İşlem başarısız oldu."); - } - } - - private void ExitApplication() - { - if (_isExiting) return; - _isExiting = true; - - _dragController?.Dispose(); - _dragController = null; - - _trayHost?.Dispose(); - _trayHost = null; - - _singleInstance?.Dispose(); - _singleInstance = null; - - Shutdown(); - Environment.Exit(0); - } - - protected override void OnExit(ExitEventArgs e) - { - _dragController?.Dispose(); - _trayHost?.Dispose(); - _singleInstance?.Dispose(); - base.OnExit(e); - } -} diff --git a/src/Donustur.UI/AssemblyInfo.cs b/src/Donustur.UI/AssemblyInfo.cs deleted file mode 100644 index cc29e7f..0000000 --- a/src/Donustur.UI/AssemblyInfo.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Windows; - -[assembly:ThemeInfo( - ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located - //(used if a resource is not found in the page, - // or application resource dictionaries) - ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located - //(used if a resource is not found in the page, - // app, or any theme specific resource dictionaries) -)] diff --git a/src/Donustur.UI/Assets/app.ico b/src/Donustur.UI/Assets/app.ico deleted file mode 100644 index e85e5c1..0000000 Binary files a/src/Donustur.UI/Assets/app.ico and /dev/null differ diff --git a/src/Donustur.UI/Controls/RadialWheelControl.cs b/src/Donustur.UI/Controls/RadialWheelControl.cs deleted file mode 100644 index 4bb630f..0000000 --- a/src/Donustur.UI/Controls/RadialWheelControl.cs +++ /dev/null @@ -1,318 +0,0 @@ -using System.Globalization; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Media; -using Donustur.Core.Math; -using Donustur.Core.Models; - -namespace Donustur.UI.Controls; - -public sealed class RadialWheelControl : Control -{ - public static readonly DependencyProperty ChoicesProperty = - DependencyProperty.Register( - nameof(Choices), - typeof(IReadOnlyList), - typeof(RadialWheelControl), - new FrameworkPropertyMetadata(Array.Empty(), FrameworkPropertyMetadataOptions.AffectsRender)); - - public static readonly DependencyProperty HoveredIndexProperty = - DependencyProperty.Register( - nameof(HoveredIndex), - typeof(int), - typeof(RadialWheelControl), - new FrameworkPropertyMetadata(-1, FrameworkPropertyMetadataOptions.AffectsRender, OnHoveredIndexChanged)); - - public static readonly DependencyProperty FileCountProperty = - DependencyProperty.Register( - nameof(FileCount), - typeof(int), - typeof(RadialWheelControl), - new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender)); - - public static readonly DependencyProperty FileSummaryProperty = - DependencyProperty.Register( - nameof(FileSummary), - typeof(string), - typeof(RadialWheelControl), - new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsRender)); - - public IReadOnlyList Choices - { - get => (IReadOnlyList)GetValue(ChoicesProperty); - set => SetValue(ChoicesProperty, value); - } - - public int HoveredIndex - { - get => (int)GetValue(HoveredIndexProperty); - set => SetValue(HoveredIndexProperty, value); - } - - public int FileCount - { - get => (int)GetValue(FileCountProperty); - set => SetValue(FileCountProperty, value); - } - - public string FileSummary - { - get => (string)GetValue(FileSummaryProperty); - set => SetValue(FileSummaryProperty, value); - } - - public event Action? HoverChanged; - - private static void OnHoveredIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - if (d is RadialWheelControl wheel) - { - wheel.HoverChanged?.Invoke((int)e.NewValue); - } - } - - public double OuterRadius { get; set; } = 175.0; - public double InnerRadius { get; set; } = 48.0; - - // --- Performans ve Akışkanlık İçin Dondurulmuş (Frozen) Grafik Nesneleri --- - private static readonly RadialGradientBrush GlowBrush; - private static readonly LinearGradientBrush ActiveSegmentBrush; - private static readonly Pen ActiveSegmentPen; - private static readonly SolidColorBrush DefaultSegmentBrush; - private static readonly Pen DefaultSegmentPen; - - private static readonly RadialGradientBrush HubShadowBrush; - private static readonly SolidColorBrush HubFillBrush; - private static readonly Pen HubBorderPen; - - private static readonly Typeface SegmentTypefaceRegular; - private static readonly Typeface SegmentTypefaceBold; - private static readonly Typeface HubTitleTypeface; - private static readonly Typeface HubSubtitleTypeface; - - private static readonly SolidColorBrush TextWhiteBrush; - private static readonly SolidColorBrush TextNormalBrush; - private static readonly SolidColorBrush TextSubBrush; - - static RadialWheelControl() - { - DefaultStyleKeyProperty.OverrideMetadata( - typeof(RadialWheelControl), - new FrameworkPropertyMetadata(typeof(RadialWheelControl))); - - // Arka plan parlaması (Glow) - GlowBrush = new RadialGradientBrush - { - GradientOrigin = new Point(0.5, 0.5), - Center = new Point(0.5, 0.5), - RadiusX = 0.5, - RadiusY = 0.5 - }; - GlowBrush.GradientStops.Add(new GradientStop(Color.FromArgb(40, 99, 102, 241), 0.3)); - GlowBrush.GradientStops.Add(new GradientStop(Colors.Transparent, 1.0)); - GlowBrush.Freeze(); - - // Aktif dilim fırçası ve kalemi - ActiveSegmentBrush = new LinearGradientBrush( - Color.FromRgb(99, 102, 241), - Color.FromRgb(14, 165, 233), - new Point(0, 0), - new Point(1, 1)); - ActiveSegmentBrush.Freeze(); - - ActiveSegmentPen = new Pen(new SolidColorBrush(Color.FromArgb(220, 255, 255, 255)), 2.0); - ActiveSegmentPen.Brush.Freeze(); - ActiveSegmentPen.Freeze(); - - // Varsayılan dilim fırçası ve kalemi - DefaultSegmentBrush = new SolidColorBrush(Color.FromArgb(200, 24, 27, 36)); - DefaultSegmentBrush.Freeze(); - - DefaultSegmentPen = new Pen(new SolidColorBrush(Color.FromArgb(70, 255, 255, 255)), 1.0); - DefaultSegmentPen.Brush.Freeze(); - DefaultSegmentPen.Freeze(); - - // Merkez gösterge (Hub) - HubShadowBrush = new RadialGradientBrush(); - HubShadowBrush.GradientStops.Add(new GradientStop(Color.FromArgb(160, 0, 0, 0), 0.7)); - HubShadowBrush.GradientStops.Add(new GradientStop(Colors.Transparent, 1.0)); - HubShadowBrush.Freeze(); - - HubFillBrush = new SolidColorBrush(Color.FromRgb(18, 20, 28)); - HubFillBrush.Freeze(); - - HubBorderPen = new Pen(new SolidColorBrush(Color.FromArgb(120, 99, 102, 241)), 2.0); - HubBorderPen.Brush.Freeze(); - HubBorderPen.Freeze(); - - // Tipografiler - SegmentTypefaceRegular = new Typeface(new FontFamily("Segoe UI Variable Display, Segoe UI, Arial"), FontStyles.Normal, FontWeights.SemiBold, FontStretches.Normal); - SegmentTypefaceBold = new Typeface(new FontFamily("Segoe UI Variable Display, Segoe UI, Arial"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); - HubTitleTypeface = new Typeface(new FontFamily("Segoe UI Variable Display, Segoe UI"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); - HubSubtitleTypeface = new Typeface(new FontFamily("Segoe UI Variable Display, Segoe UI"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); - - // Metin fırçaları - TextWhiteBrush = Brushes.White; - TextNormalBrush = new SolidColorBrush(Color.FromRgb(220, 225, 235)); - TextNormalBrush.Freeze(); - TextSubBrush = new SolidColorBrush(Color.FromRgb(156, 163, 175)); - TextSubBrush.Freeze(); - } - - public RadialWheelControl() - { - 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) - 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 = isHovered ? ActiveSegmentBrush : DefaultSegmentBrush; - Pen borderPen = isHovered ? ActiveSegmentPen : DefaultSegmentPen; - - 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 = isHovered ? SegmentTypefaceBold : SegmentTypefaceRegular; - var brush = isHovered ? TextWhiteBrush : TextNormalBrush; - - var ft = new FormattedText( - text, - CultureInfo.CurrentUICulture, - FlowDirection.LeftToRight, - typeface, - isHovered ? 14 : 12.5, - brush, - 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 - dc.DrawEllipse(HubShadowBrush, null, new Point(centerX, centerY), InnerRadius + 6, InnerRadius + 6); - - // Merkez arkaplan - dc.DrawEllipse(HubFillBrush, HubBorderPen, 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 titleFt = new FormattedText( - centerTitle, - CultureInfo.CurrentUICulture, - FlowDirection.LeftToRight, - HubTitleTypeface, - 11.0, - TextWhiteBrush, - 1.0); - - dc.DrawText(titleFt, new Point(centerX - (titleFt.Width / 2.0), centerY - 13)); - - var subFt = new FormattedText( - centerSubtitle, - CultureInfo.CurrentUICulture, - FlowDirection.LeftToRight, - HubSubtitleTypeface, - 9.5, - TextSubBrush, - 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); - geom.Freeze(); // GPU donanım hızlandırma ve sıfır GC tahsisi için dondur - return geom; - } -} diff --git a/src/Donustur.UI/Donustur.UI.csproj b/src/Donustur.UI/Donustur.UI.csproj deleted file mode 100644 index 1562c5a..0000000 --- a/src/Donustur.UI/Donustur.UI.csproj +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - WinExe - net8.0-windows - LDConverter - LD Converter - LD Converter - 1.3.0 - Assets\app.ico - enable - enable - true - true - app.manifest - - $(NoWarn);WFAC010 - - - diff --git a/src/Donustur.UI/GlobalUsings.cs b/src/Donustur.UI/GlobalUsings.cs deleted file mode 100644 index 7985d6f..0000000 --- a/src/Donustur.UI/GlobalUsings.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Conflict resolution aliases for WPF + WinForms coexistence -// WPF types take priority over WinForms throughout the project -global using Application = System.Windows.Application; -global using Point = System.Windows.Point; -global using DragEventArgs = System.Windows.DragEventArgs; -global using Control = System.Windows.Controls.Control; -global using MouseEventArgs = System.Windows.Input.MouseEventArgs; -global using KeyEventArgs = System.Windows.Input.KeyEventArgs; -global using Color = System.Windows.Media.Color; -global using Brushes = System.Windows.Media.Brushes; -global using Brush = System.Windows.Media.Brush; -global using FontFamily = System.Windows.Media.FontFamily; -global using Pen = System.Windows.Media.Pen; -global using Size = System.Windows.Size; -global using Orientation = System.Windows.Controls.Orientation; -global using RadioButton = System.Windows.Controls.RadioButton; -global using Button = System.Windows.Controls.Button; -global using MessageBox = System.Windows.MessageBox; -global using MessageBoxButton = System.Windows.MessageBoxButton; -global using MessageBoxImage = System.Windows.MessageBoxImage; -global using FontStyle = System.Windows.FontStyle; -global using FontStyles = System.Windows.FontStyles; -global using FlowDirection = System.Windows.FlowDirection; -global using DataFormats = System.Windows.DataFormats; -global using DragDropEffects = System.Windows.DragDropEffects; -global using StreamReader = System.IO.StreamReader; -global using StreamWriter = System.IO.StreamWriter; -global using OpenFileDialog = Microsoft.Win32.OpenFileDialog; -global using Clipboard = System.Windows.Clipboard; -global using Cursors = System.Windows.Input.Cursors; -global using HorizontalAlignment = System.Windows.HorizontalAlignment; diff --git a/src/Donustur.UI/MainWindow.xaml b/src/Donustur.UI/MainWindow.xaml deleted file mode 100644 index 48771b5..0000000 --- a/src/Donustur.UI/MainWindow.xaml +++ /dev/null @@ -1,407 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Donustur.UI/Windows/ProgressToastWindow.xaml.cs b/src/Donustur.UI/Windows/ProgressToastWindow.xaml.cs deleted file mode 100644 index 8cfa0f4..0000000 --- a/src/Donustur.UI/Windows/ProgressToastWindow.xaml.cs +++ /dev/null @@ -1,190 +0,0 @@ -using System.IO; -using System.Windows; -using System.Windows.Threading; -using Donustur.UI.Services; - -namespace Donustur.UI.Windows; - -public partial class ProgressToastWindow : Window -{ - private static readonly List ActiveToasts = new(); - - private string? _firstOutputFile; - private string? _copiedPayload; - private bool _isCompletedOrFailed; - private readonly Action? _onCancelRequested; - private readonly DispatcherTimer _autoCloseTimer; - - public ProgressToastWindow(string initialTitle, Action? onCancelRequested = null) - { - InitializeComponent(); - Icon = AppIconProvider.GetWindowIcon(); - TitleText.Text = initialTitle; - _onCancelRequested = onCancelRequested; - - _autoCloseTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5.5) }; - _autoCloseTimer.Tick += (_, _) => Close(); - - Loaded += (_, _) => - { - if (!ActiveToasts.Contains(this)) - { - ActiveToasts.Add(this); - } - RepositionAllToasts(); - }; - - Closed += (_, _) => - { - _autoCloseTimer.Stop(); - ActiveToasts.Remove(this); - RepositionAllToasts(); - }; - } - - private static void RepositionAllToasts() - { - double workAreaRight = SystemParameters.WorkArea.Right; - double workAreaBottom = SystemParameters.WorkArea.Bottom; - - for (int i = 0; i < ActiveToasts.Count; i++) - { - var toast = ActiveToasts[i]; - toast.Left = workAreaRight - toast.Width - 15; - toast.Top = workAreaBottom - ((i + 1) * (toast.Height - 5)) - 10; - } - } - - private static readonly System.Windows.Media.SolidColorBrush CompletedGreenBrush; - - static ProgressToastWindow() - { - CompletedGreenBrush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(16, 185, 129)); - CompletedGreenBrush.Freeze(); - } - - public void UpdateProgress(double percent, string? status = null) - { - if (Dispatcher.HasShutdownStarted || Dispatcher.HasShutdownFinished) return; - - void Apply() - { - ProgressBar.Value = percent; - if (!string.IsNullOrWhiteSpace(status)) - { - StatusText.Text = status; - } - } - - if (Dispatcher.CheckAccess()) - { - Apply(); - } - else - { - Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)Apply); - } - } - - public void SetCompleted(IReadOnlyList outputFiles, string? decodedText = null) - { - if (Dispatcher.HasShutdownStarted || Dispatcher.HasShutdownFinished) return; - - void Apply() - { - _isCompletedOrFailed = true; - ProgressBar.Value = 100; - ProgressBar.Foreground = CompletedGreenBrush; - 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(); - } - - if (Dispatcher.CheckAccess()) - { - Apply(); - } - else - { - Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)Apply); - } - } - - public void SetFailed(string error) - { - if (Dispatcher.HasShutdownStarted || Dispatcher.HasShutdownFinished) return; - - void Apply() - { - _isCompletedOrFailed = true; - TitleText.Text = "✕ İşlem Tamamlanamadı"; - TitleText.Foreground = System.Windows.Media.Brushes.IndianRed; - StatusText.Text = error; - ProgressBar.Visibility = Visibility.Collapsed; - _autoCloseTimer.Start(); - } - - if (Dispatcher.CheckAccess()) - { - Apply(); - } - else - { - Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)Apply); - } - } - - private void OnCloseClick(object sender, RoutedEventArgs e) - { - if (!_isCompletedOrFailed) - { - _onCancelRequested?.Invoke(); - } - Close(); - } - - private void OnCopyTextClick(object sender, RoutedEventArgs e) - { - if (!string.IsNullOrWhiteSpace(_copiedPayload)) - { - try - { - Clipboard.SetText(_copiedPayload); - CopyTextButton.Content = "✓ Kopyalandı"; - } - catch - { - // Pano meşgulse sessizce geç - } - } - } - - private void OnOpenFolderClick(object sender, RoutedEventArgs e) - { - if (!string.IsNullOrWhiteSpace(_firstOutputFile)) - { - DesktopGeometry.RevealInExplorer(_firstOutputFile); - } - Close(); - } -} diff --git a/src/Donustur.UI/Windows/SettingsWindow.xaml b/src/Donustur.UI/Windows/SettingsWindow.xaml deleted file mode 100644 index a3f7930..0000000 --- a/src/Donustur.UI/Windows/SettingsWindow.xaml +++ /dev/null @@ -1,394 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Donustur.UI/Windows/SettingsWindow.xaml.cs b/src/Donustur.UI/Windows/SettingsWindow.xaml.cs deleted file mode 100644 index 0625626..0000000 --- a/src/Donustur.UI/Windows/SettingsWindow.xaml.cs +++ /dev/null @@ -1,344 +0,0 @@ -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; - private string? _customPandocPath; - - 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; - _customPandocPath = prefs.CustomPandocPath; - - 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 (UI thread'i kilitlememesi için arka planda tara) - LibreOfficeStatusText.Text = "ℹ Kontrol ediliyor..."; - FfmpegStatusText.Text = "ℹ Kontrol ediliyor..."; - PandocStatusText.Text = "ℹ Kontrol ediliyor..."; - NativeEnginesStatusText.Text = "✓ Magick.NET, PdfPig ve SharpCompress hazır"; - - Task.Run(() => - { - var officeEngine = new OfficeDocumentEngine(prefs.CustomLibreOfficePath, _customPandocPath); - bool officeAvailable = officeEngine.IsAvailable; - string? sofficePath = officeAvailable ? officeEngine.ResolveSofficePath() : null; - - var mediaEngine = new MediaEngine(prefs.CustomFfmpegPath); - bool mediaAvailable = mediaEngine.IsAvailable; - string? ffmpegPath = mediaAvailable ? mediaEngine.ResolveFfmpegPath() : null; - - var pandocEngine = new PandocEngine(_customPandocPath); - bool pandocAvailable = pandocEngine.IsAvailable; - string? pandocPath = pandocAvailable ? pandocEngine.ResolvePandocPath() : null; - string? pdfEngine = pandocAvailable ? pandocEngine.ResolvePdfEngine() : null; - - string? sevenZip = ArchiveEngine.Resolve7ZipPath(); - - Dispatcher.BeginInvoke(() => - { - if (officeAvailable) - { - LibreOfficeStatusText.Text = $"✓ Hazır ({sofficePath})"; - LibreOfficeStatusText.Foreground = System.Windows.Media.Brushes.LightGreen; - } - else - { - LibreOfficeStatusText.Text = "ℹ Kurulu değil (TXT/DOCX/HTML/PDF yerel motoru aktif; PPTX/XLSX için LibreOffice seçilebilir)"; - LibreOfficeStatusText.Foreground = System.Windows.Media.Brushes.Khaki; - } - - if (mediaAvailable) - { - FfmpegStatusText.Text = $"✓ Hazır ({ffmpegPath})"; - FfmpegStatusText.Foreground = System.Windows.Media.Brushes.LightGreen; - InstallFfmpegBtn.Visibility = Visibility.Collapsed; - } - else - { - FfmpegStatusText.Text = "✕ Bulunamadı (Video & ses dönüşümleri için FFmpeg gereklidir)"; - FfmpegStatusText.Foreground = System.Windows.Media.Brushes.IndianRed; - InstallFfmpegBtn.Visibility = Visibility.Visible; - } - - if (pandocAvailable) - { - string engineInfo = pdfEngine != null ? $" [PDF Motoru: {pdfEngine}]" : ""; - PandocStatusText.Text = $"✓ Hazır ({pandocPath}){engineInfo}"; - PandocStatusText.Foreground = System.Windows.Media.Brushes.LightGreen; - InstallPandocBtn.Visibility = Visibility.Collapsed; - } - else - { - PandocStatusText.Text = "ℹ Kurulu değil (Markdown & LaTeX denklem dönüşümleri için kurabilirsiniz)"; - PandocStatusText.Foreground = System.Windows.Media.Brushes.Khaki; - InstallPandocBtn.Visibility = Visibility.Visible; - } - - NativeEnginesStatusText.Text = sevenZip != null - ? $"✓ Magick.NET, PdfPig, SharpCompress ve 7-Zip ({sevenZip}) hazır" - : "✓ Magick.NET, PdfPig ve SharpCompress hazır (ZIP, TAR.GZ, Görsel, PDF, DOCX, QR)"; - }); - }); - } - - private void OnScaleSliderChanged(object sender, RoutedPropertyChangedEventArgs e) - { - if (ScaleValueLabel != null) - { - ScaleValueLabel.Text = $"{e.NewValue:0.00}x"; - } - } - - private void OnQualitySliderChanged(object sender, RoutedPropertyChangedEventArgs e) - { - if (QualityValueLabel != null) - { - QualityValueLabel.Text = $"%{e.NewValue:F0}"; - } - } - - private void OnOutputModeChanged(object sender, SelectionChangedEventArgs e) - { - if (CustomFolderPanel != null) - { - CustomFolderPanel.Visibility = OutputModeCombo.SelectedIndex == 2 ? Visibility.Visible : Visibility.Collapsed; - } - } - - private void OnBrowseFolderClick(object sender, RoutedEventArgs e) - { - var dlg = new OpenFolderDialog - { - Title = "Dönüştürülen Dosyaların Kaydedileceği Klasörü Seçin" - }; - if (dlg.ShowDialog() == true) - { - CustomFolderText.Text = dlg.FolderName; - } - } - - private void OnBrowseLibreOfficeClick(object sender, RoutedEventArgs e) - { - var dlg = new Microsoft.Win32.OpenFileDialog - { - Filter = "soffice.exe|soffice.exe|Tüm Dosyalar (*.*)|*.*", - Title = "LibreOffice soffice.exe dosyasını seçin" - }; - if (dlg.ShowDialog() == true) - { - var prefs = _preferencesStore.Current; - prefs.CustomLibreOfficePath = dlg.FileName; - _preferencesStore.Save(prefs); - LoadValues(); - } - } - - private void OnBrowseFfmpegClick(object sender, RoutedEventArgs e) - { - var dlg = new Microsoft.Win32.OpenFileDialog - { - Filter = "ffmpeg.exe|ffmpeg.exe|Tüm Dosyalar (*.*)|*.*", - Title = "FFmpeg ffmpeg.exe dosyasını seçin" - }; - if (dlg.ShowDialog() == true) - { - var prefs = _preferencesStore.Current; - prefs.CustomFfmpegPath = dlg.FileName; - _preferencesStore.Save(prefs); - LoadValues(); - } - } - - private async void OnInstallFfmpegClick(object sender, RoutedEventArgs e) - { - InstallFfmpegBtn.IsEnabled = false; - FfmpegStatusText.Text = "📥 FFmpeg indiriliyor ve kuruluyor..."; - FfmpegStatusText.Foreground = System.Windows.Media.Brushes.Khaki; - - var progress = new Progress(msg => - { - Dispatcher.BeginInvoke(() => FfmpegStatusText.Text = msg); - }); - - var mediaEngine = new MediaEngine(_preferencesStore.Current.CustomFfmpegPath); - string? result = await FfmpegInstaller.EnsureOrInstallFfmpegAsync(mediaEngine, progress); - - if (result != null) - { - var prefs = _preferencesStore.Current; - prefs.CustomFfmpegPath = result; - _preferencesStore.Save(prefs); - } - - InstallFfmpegBtn.IsEnabled = true; - LoadValues(); - } - - private void OnBrowsePandocClick(object sender, RoutedEventArgs e) - { - var dlg = new Microsoft.Win32.OpenFileDialog - { - Filter = "pandoc.exe|pandoc.exe|Tüm Dosyalar (*.*)|*.*", - Title = "Pandoc pandoc.exe dosyasını seçin" - }; - if (dlg.ShowDialog() == true) - { - _customPandocPath = dlg.FileName; - var prefs = _preferencesStore.Current; - prefs.CustomPandocPath = dlg.FileName; - _preferencesStore.Save(prefs); - LoadValues(); - } - } - - private async void OnInstallPandocClick(object sender, RoutedEventArgs e) - { - InstallPandocBtn.IsEnabled = false; - PandocStatusText.Text = "📥 Pandoc indiriliyor ve kuruluyor..."; - PandocStatusText.Foreground = System.Windows.Media.Brushes.Khaki; - - var progress = new Progress(msg => - { - Dispatcher.BeginInvoke(() => PandocStatusText.Text = msg); - }); - - var pandocEngine = new PandocEngine(_customPandocPath); - string? result = await PandocInstaller.EnsureOrInstallPandocAsync(pandocEngine, progress); - - if (result != null) - { - _customPandocPath = result; - var prefs = _preferencesStore.Current; - prefs.CustomPandocPath = result; - _preferencesStore.Save(prefs); - } - - InstallPandocBtn.IsEnabled = true; - 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.CustomPandocPath = _customPandocPath; - - prefs.OutputDirectoryMode = OutputModeCombo.SelectedIndex switch - { - 1 => "Desktop", - 2 => "Custom", - _ => "SameAsSource" - }; - prefs.CustomOutputDirectory = CustomFolderText.Text.Trim(); - - _preferencesStore.Save(prefs); - Close(); - } -} diff --git a/src/Donustur.UI/Windows/WheelWindow.xaml b/src/Donustur.UI/Windows/WheelWindow.xaml deleted file mode 100644 index 3252b74..0000000 --- a/src/Donustur.UI/Windows/WheelWindow.xaml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - diff --git a/src/Donustur.UI/Windows/WheelWindow.xaml.cs b/src/Donustur.UI/Windows/WheelWindow.xaml.cs deleted file mode 100644 index aeae4f8..0000000 --- a/src/Donustur.UI/Windows/WheelWindow.xaml.cs +++ /dev/null @@ -1,245 +0,0 @@ -using System.Runtime.InteropServices; -using System.Windows; -using System.Windows.Interop; -using System.Windows.Media; -using System.Windows.Media.Animation; -using Donustur.Core.Catalog; -using Donustur.Core.Math; -using Donustur.Core.Models; -using Donustur.UI.Services; - -namespace Donustur.UI.Windows; - -public partial class WheelWindow : Window -{ - private const int GWL_EXSTYLE = -20; - private const int WS_EX_NOACTIVATE = 0x08000000; - private const int WS_EX_TOOLWINDOW = 0x00000080; - private const int WS_EX_TOPMOST = 0x00000008; - - [DllImport("user32.dll")] - private static extern int GetWindowLong(IntPtr hWnd, int nIndex); - - [DllImport("user32.dll")] - private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); - - private readonly Action> _onDropped; - private readonly bool _soundEnabled; - private readonly double _targetScale; - private IReadOnlyList _activeFiles = Array.Empty(); - private bool _isClosing; - private bool _selectionExecuted; - - public DateTime OpenedAtUtc { get; } = DateTime.UtcNow; - public bool HasValidFileDrag { get; private set; } - - public WheelWindow(Action> onDropped, bool soundEnabled = true, double scale = 1.0) - { - InitializeComponent(); - _onDropped = onDropped; - _soundEnabled = soundEnabled; - _targetScale = Math.Clamp(scale, 0.75, 1.5); - - // Ölçek büyütüldüğünde çarkın pencere sınırlarından kırpılmasını önle - double baseSize = 390.0; - Width = Math.Ceiling(baseSize * _targetScale); - Height = Math.Ceiling(baseSize * _targetScale); - - WheelScale.ScaleX = _targetScale; - WheelScale.ScaleY = _targetScale; - - // Varsayılan seçeneklerle başlat - RadialControl.Choices = FormatCatalog.GetChoicesForFiles(Array.Empty()); - - DragEnter += OnDragEnter; - DragOver += OnDragOver; - DragLeave += OnDragLeave; - Drop += OnDrop; - - Loaded += (_, _) => AnimateOpen(); - } - - protected override void OnSourceInitialized(EventArgs e) - { - base.OnSourceInitialized(e); - - // Pencerenin odağı çalmamasını ve OLE sürüklemeyi bozmamasını sağla - var handle = new WindowInteropHelper(this).Handle; - int exStyle = GetWindowLong(handle, GWL_EXSTYLE); - SetWindowLong(handle, GWL_EXSTYLE, exStyle | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST); - } - - private void AnimateOpen() - { - var scaleAnim = new DoubleAnimation(_targetScale * 0.7, _targetScale, TimeSpan.FromMilliseconds(120)) - { - EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut } - }; - var fadeAnim = new DoubleAnimation(0.0, 1.0, TimeSpan.FromMilliseconds(100)); - - WheelScale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnim); - WheelScale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnim); - RootGrid.BeginAnimation(OpacityProperty, fadeAnim); - } - - public void AnimateClose(Action? onComplete = null) - { - if (_isClosing) return; - _isClosing = true; - - var scaleAnim = new DoubleAnimation(_targetScale, _targetScale * 0.8, TimeSpan.FromMilliseconds(90)); - var fadeAnim = new DoubleAnimation(1.0, 0.0, TimeSpan.FromMilliseconds(90)); - - fadeAnim.Completed += (_, _) => - { - try - { - Close(); - } - catch - { - // Pencere zaten kapanmış olabilir - } - onComplete?.Invoke(); - }; - - WheelScale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnim); - WheelScale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnim); - RootGrid.BeginAnimation(OpacityProperty, fadeAnim); - } - - public void CancelAndClose() - { - _selectionExecuted = true; - RadialControl.HoveredIndex = -1; - AnimateClose(); - } - - public void UpdateMousePosition(Point screenPoint) - { - if (!IsLoaded || _isClosing) return; - try - { - if (PresentationSource.FromVisual(this) == null) return; - var clientPos = PointFromScreen(screenPoint); - UpdateSegmentFromPoint(clientPos); - } - catch - { - // Pencere kapanırken oluşan koordinat dönüşüm hatasını yoksay - } - } - - private void OnDragEnter(object sender, DragEventArgs e) - { - if (e.Data.GetDataPresent(DataFormats.FileDrop)) - { - HasValidFileDrag = true; - e.Effects = DragDropEffects.Copy; - if (e.Data.GetData(DataFormats.FileDrop) is string[] files && files.Length > 0) - { - _activeFiles = files; - RadialControl.FileCount = files.Length; - RadialControl.Choices = FormatCatalog.GetChoicesForFiles(files); - } - } - else - { - e.Effects = DragDropEffects.None; - } - e.Handled = true; - } - - private void OnDragOver(object sender, DragEventArgs e) - { - if (e.Data.GetDataPresent(DataFormats.FileDrop)) - { - HasValidFileDrag = true; - e.Effects = DragDropEffects.Copy; - Point pos = e.GetPosition(this); - UpdateSegmentFromPoint(pos); - } - else - { - e.Effects = DragDropEffects.None; - } - e.Handled = true; - } - - private void OnDragLeave(object sender, DragEventArgs e) - { - if (!_isClosing && !_selectionExecuted) - { - RadialControl.HoveredIndex = -1; - } - } - - private void UpdateSegmentFromPoint(Point pos) - { - if (_isClosing || _selectionExecuted) return; - - double centerX = ActualWidth / 2.0; - double centerY = ActualHeight / 2.0; - if (centerX <= 0 || centerY <= 0) - { - centerX = Width / 2.0; - centerY = Height / 2.0; - } - - int total = RadialControl.Choices?.Count ?? 0; - int newIndex = WheelMath.GetSegmentIndex( - centerX, centerY, - pos.X, pos.Y, - total, - RadialControl.InnerRadius * _targetScale, - RadialControl.OuterRadius * _targetScale); - - if (newIndex != RadialControl.HoveredIndex) - { - RadialControl.HoveredIndex = newIndex; - if (newIndex >= 0 && _soundEnabled) - { - SoundFeedback.PlayTick(); - } - } - } - - private void OnDrop(object sender, DragEventArgs e) - { - if (e.Data.GetDataPresent(DataFormats.FileDrop)) - { - HasValidFileDrag = true; - if (e.Data.GetData(DataFormats.FileDrop) is string[] files && files.Length > 0) - { - _activeFiles = files; - } - } - - Point dropPos = e.GetPosition(this); - UpdateSegmentFromPoint(dropPos); - ExecuteSelectionAndClose(); - e.Handled = true; - } - - public void ExecuteSelectionAndClose() - { - if (_selectionExecuted) return; - _selectionExecuted = true; - - int index = RadialControl.HoveredIndex; - var choices = RadialControl.Choices; - var files = _activeFiles; - - ToolChoice? selected = (index >= 0 && choices != null && index < choices.Count) - ? choices[index] - : null; - - AnimateClose(() => - { - if (selected != null && files.Count > 0) - { - _onDropped(selected, files); - } - }); - } -} diff --git a/src/Donustur.UI/app.manifest b/src/Donustur.UI/app.manifest deleted file mode 100644 index 0f3a1dc..0000000 --- a/src/Donustur.UI/app.manifest +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - true/pm - PerMonitorV2, PerMonitor - - - diff --git a/src/components/AppFooter.tsx b/src/components/AppFooter.tsx new file mode 100644 index 0000000..6c03153 --- /dev/null +++ b/src/components/AppFooter.tsx @@ -0,0 +1,42 @@ +import React, { useEffect, useState } from "react"; +import { Info } from "lucide-react"; +import { getVersion } from "@tauri-apps/api/app"; +import { useAppStore } from "../stores/useAppStore"; + +export const AppFooter: React.FC = () => { + const { engineStatus, availableUpdate, isUpdating, updateProgress, activeModal } = useAppStore(); + const [version, setVersion] = useState(""); + + useEffect(() => { + getVersion().then(setVersion).catch(() => {}); + }, []); + + const engines = [ + ["FFmpeg", engineStatus?.ffmpeg_path], + ["Pandoc", engineStatus?.pandoc_path], + ["7-Zip", engineStatus?.seven_zip_path], + ] as const; + const missing = engines.filter(([, value]) => !value).map(([name]) => name); + + const updateText = isUpdating && updateProgress + ? `Güncelleme indiriliyor: %${updateProgress.percent}` + : availableUpdate + ? `Yeni sürüm v${availableUpdate.version} hazır` + : missing.length > 0 + ? `Motorlar denetleniyor / eksik: ${missing.join(", ")}` + : "Tüm motorlar güncel · açılışta otomatik denetlenir"; + + return ( +
        + + LD Converter v{version || "3.6.4"} +
        + ); +}; diff --git a/src/components/AppHeader.tsx b/src/components/AppHeader.tsx new file mode 100644 index 0000000..1aedeac --- /dev/null +++ b/src/components/AppHeader.tsx @@ -0,0 +1,103 @@ +import React, { useEffect, useState } from "react"; +import { Minus, Square, X, Settings, Sparkles } from "lucide-react"; +import { getVersion } from "@tauri-apps/api/app"; +import { getCurrentWindow } from "@tauri-apps/api/window"; +import { useAppStore } from "../stores/useAppStore"; + +export type TabId = "convert" | "library" | "tools"; + +const TABS: { id: TabId; label: string }[] = [ + { id: "convert", label: "Dönüştür" }, + { id: "library", label: "Kitaplık" }, + { id: "tools", label: "Hızlı Araçlar" }, +]; + +export const AppHeader: React.FC<{ active: TabId; onChange: (tab: TabId) => void }> = ({ + active, + onChange, +}) => { + const { checkForUpdates, isCheckingUpdate } = useAppStore(); + const [version, setVersion] = useState(""); + + useEffect(() => { + getVersion().then(setVersion).catch(() => {}); + }, []); + + const appWindow = getCurrentWindow(); + + return ( +
        +
        + LD Converter +
        +
        LD Converter
        +
        Hızlı Medya & Belge Aracı
        +
        +
        + + + +
        + + + + + +
        + + + +
        +
        + ); +}; diff --git a/src/components/ConversionModal.tsx b/src/components/ConversionModal.tsx new file mode 100644 index 0000000..c7c8a3a --- /dev/null +++ b/src/components/ConversionModal.tsx @@ -0,0 +1,55 @@ +import React from "react"; +import { Loader2, XCircle } from "lucide-react"; +import { useAppStore } from "../stores/useAppStore"; + +export const ConversionModal: React.FC = () => { + const { isConverting, currentProgress, cancelConversion } = useAppStore(); + + if (!isConverting) return null; + + const percent = currentProgress?.percent || 0; + + return ( +
        +
        + {/* Glow ambient background */} +
        +
        + +
        + +
        + +

        + Dönüştürülüyor... +

        + +

        + {currentProgress?.message || "Lütfen bekleyin..."} +

        + + {/* Progress Bar */} +
        +
        +
        + +
        + İlerleme: + %{percent.toFixed(0)} +
        + + {/* Cancel Button */} + +
        +
        + ); +}; diff --git a/src/components/ConvertView.tsx b/src/components/ConvertView.tsx new file mode 100644 index 0000000..f0461f8 --- /dev/null +++ b/src/components/ConvertView.tsx @@ -0,0 +1,247 @@ +import React, { useEffect, useMemo, useState } from "react"; +import { invoke } from "@tauri-apps/api/core"; +import { open } from "@tauri-apps/plugin-dialog"; +import { FileText, FolderOpen, Image as ImageIcon, Music, Plus, Trash2, Video, Archive, Play, X } from "lucide-react"; +import { useAppStore } from "../stores/useAppStore"; + +function formatBytes(bytes: number): string { + if (!bytes) return "0 B"; + const units = ["B", "KB", "MB", "GB"]; + const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1); + const value = bytes / Math.pow(1024, index); + return `${value.toFixed(index === 0 ? 0 : 1)} ${units[index]}`; +} + +function iconFor(path: string) { + const ext = path.split(".").pop()?.toLowerCase() ?? ""; + if (["png", "jpg", "jpeg", "webp", "avif", "jxl", "bmp", "tiff", "gif", "ico", "svg", "heic", "heif", "cr2", "nef", "arw"].includes(ext)) { + return ; + } + if (["mp4", "mkv", "avi", "mov", "webm"].includes(ext)) return