chore: add bilingual documentation, MIT license, and clean repository for Forgejo

This commit is contained in:
LilDosto 2026-11-23 03:44:15 +03:00
parent 0bf0aff8f3
commit 6b484cffe0
201 changed files with 41385 additions and 8615 deletions

40
.gitignore vendored
View file

@ -3,7 +3,21 @@
[Oo]bj/ [Oo]bj/
[Ll]og/ [Ll]og/
[Ll]ogs/ [Ll]ogs/
*.log
*.zip *.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 # Visual Studio / Rider / VS Code caches
.vs/ .vs/
@ -15,3 +29,29 @@
*.sln.docstates *.sln.docstates
TestResults/ TestResults/
*.DotSettings.user *.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.*

View file

@ -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

112
README.md
View file

@ -1,54 +1,98 @@
# LD Converter 🚀 <div align="center">
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) # LD Converter
[![Release](https://img.shields.io/github/v/release/LilDosto/LD-Converter)](https://github.com/LilDosto/LD-Converter/releases)
> **Yeni Nesil, Optimize & Akıcı Dosya Dönüştürme Aracı** **Hızlı, çevrimdışı ve çok formatlı masaüstü dosya dönüştürücü • Fast, offline, multi-format desktop file converter**
> .NET 8, WPF ve modern asenkron mimari ile tasarlanmış yüksek performanslı masaüstü dosya dönüştürücü.
[![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)
</div>
--- ---
## 🌟 Öne Çıkan Özellikler ## 🇹🇷 Türkçe
1. **Sıfır Tıklama (Zero-Click) Çarkı (Radial Wheel):** **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.
- Masaüstünde veya klasörde herhangi bir dosyayı (veya dosya grubunu) sürüklerken **Shift** (veya **Ctrl**) tuşuna basılı tuttuğunuz anda fare imlecinizin etrafında dairesel işlem çarkı açılır.
- Dosyayı istediğiniz dilimin üzerine bırakın; dönüştürme anında başlar.
2. **Dinamik ve Akıllı Format Eşleme:** ### Özellikler
- Görseller (PNG, JPG, WebP, AVIF, BMP, TIFF, GIF, ICO, HEIC)
- Belgeler (DOCX, PPTX, XLSX, ODT, RTF, TXT, HTML, EPUB)
- PDF İşlemleri (Sayfalara ayırma, PDF & Görsel birleştirme, metin çıkarma, DOCX'e çevirme, sayfaları PNG/JPG olarak dışa aktarma)
- Medya (MP4, MKV, AVI, MOV, WebM -> MP3, WAV, AAC, FLAC, OGG, GIF)
- Arşivleme (ZIP, 7Z, TAR.GZ, RAR)
- Karekod (QR Code) okuma ve tek tıklamayla yüksek çözünürlüklü QR üretme.
3. **Atomik Evreleme (ExportTransaction):** - **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.
- 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. - **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):** ### Teknoloji Yığını
- 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.
--- - **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: **Son Kullanıcı:**
`publish/LDConverter.exe` dosyasını çift tıklayarak doğrudan çalıştırabilirsiniz. 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: **Geliştirici (Kaynaktan Derleme):**
```bash ```powershell
dotnet run --project src/Donustur.UI/Donustur.UI.csproj npm install
npm run tauri dev # Geliştirme modunda çalıştır
npm run tauri build # Üretim kurulum paketini derle
``` ```
Rust motor testleri ve tanılama:
### Testleri Çalıştırma: ```powershell
```bash cd src-tauri
dotnet test 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).

13
index.html Normal file
View file

@ -0,0 +1,13 @@
<!doctype html>
<html lang="tr" class="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>LD Converter</title>
<link rel="icon" type="image/x-icon" href="/app.ico" />
</head>
<body class="bg-[#070b12] text-slate-100 antialiased select-none overflow-hidden m-0 p-0 h-screen w-screen">
<div id="root" class="h-full w-full"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

2471
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

52
package.json Normal file
View file

@ -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"
}
}

BIN
public/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 263 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -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": ""
}
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -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
}
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -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')

545
site/ld-converter.html Normal file
View file

@ -0,0 +1,545 @@
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LD Converter — Tauri v2 &amp; Rust ile Yeni Nesil Masaüstü Dönüştürücü | v3.6.4</title>
<meta name="description" content="LD Converter: Tauri v2 ve Rust çekirdeğiyle ultra hızlı masaüstü dosya dönüştürücü. Sürükle-bırak ve Explorer sağ tık desteği, OMML Word matematik formülleri, JPEG XL, WebP, AVIF, PDF araçları ve canlı FFmpeg desteği.">
<link rel="canonical" href="https://ttmadethat.shop/ld-converter">
<meta property="og:title" content="LD Converter — Tauri v2 &amp; Rust ile Ultra Hızlı Dönüştürücü">
<meta property="og:description" content="Sürükle-bırak &amp; Windows sağ tık menüsü, Saf Rust Word denklem motoru (OMML), JPEG XL, PDF/OCR ve FFmpeg araçları tek bir hafif masaüstü uygulamasında.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://ttmadethat.shop/ld-converter">
<meta property="og:image" content="https://ttmadethat.shop/static/downloads/ld-apps/ld-converter-logo.png">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="LD Converter — Tauri v2 &amp; Rust ile Masaüstü Dönüştürücü">
<meta name="twitter:description" content="Tauri v2 + Rust ile ışık hızında dosya dönüştürme. JPEG XL, OMML Matematik DOCX, PDF araçları ve Windows Sağ Tık entegrasyonu.">
<meta name="twitter:image" content="https://ttmadethat.shop/static/downloads/ld-apps/ld-converter-logo.png">
<meta name="theme-color" content="#05080b">
<link rel="icon" type="image/png" href="/static/downloads/ld-apps/ld-converter-logo.png">
<style>
:root {
--bg: #05080b;
--bg2: #070d12;
--panel: rgba(13, 21, 29, .82);
--panel-solid: #0c151d;
--line: rgba(126, 190, 211, .16);
--line2: rgba(126, 190, 211, .28);
--text: #e8f3f7;
--muted: #91aab7;
--cyan: #8fe3f5;
--cyan2: #57c9e8;
--green: #8dffad;
--warn: #ffd27a;
--red: #ff8f9f;
--purple: #c084fc;
--radius: 18px;
--mono: ui-monospace, "Cascadia Code", "SFMono-Regular", Consolas, monospace;
--sans: "Segoe UI Variable Display", "Segoe UI", ui-sans-serif, system-ui, -apple-system, sans-serif;
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
margin: 0; color: var(--text); font-family: var(--sans); line-height: 1.6;
background:
radial-gradient(900px 520px at 82% -8%, rgba(143,227,245,.14), transparent 62%),
radial-gradient(800px 500px at 4% 18%, rgba(141,255,173,.08), transparent 58%),
radial-gradient(700px 450px at 50% 85%, rgba(192,132,252,.06), transparent 60%),
var(--bg);
overflow-x: hidden;
}
body::before {
content: ""; position: fixed; inset: 0; pointer-events: none; z-index: -2;
background-image: linear-gradient(rgba(143,227,245,.035) 1px, transparent 1px), linear-gradient(90deg, rgba(143,227,245,.035) 1px, transparent 1px);
background-size: 54px 54px;
mask-image: linear-gradient(to bottom, #000 0%, transparent 75%);
-webkit-mask-image: linear-gradient(to bottom, #000 0%, transparent 75%);
}
.aurora { position: fixed; inset: 0; pointer-events: none; z-index: -1; overflow: hidden; }
.aurora span { position: absolute; width: 44vw; height: 44vw; border-radius: 50%; filter: blur(90px); opacity: .18; animation: drift 18s ease-in-out infinite alternate; }
.aurora span:nth-child(1) { background: #26c9e4; top: -22vw; right: -10vw; }
.aurora span:nth-child(2) { background: #1aff7a; bottom: -28vw; left: -16vw; animation-delay: -7s; opacity: .1; }
.aurora span:nth-child(3) { background: #a855f7; width: 22vw; height: 22vw; top: 45%; left: 60%; opacity: .08; animation-delay: -12s; }
@keyframes drift { from { transform: translate3d(0,0,0) scale(1); } to { transform: translate3d(-4vw, 4vw, 0) scale(1.12); } }
a { color: inherit; }
.wrap { width: min(1160px, calc(100% - 40px)); margin: 0 auto; }
.mono { font-family: var(--mono); }
.muted { color: var(--muted); }
.kicker { color: var(--cyan); font-family: var(--mono); font-size: 10px; letter-spacing: .18em; text-transform: uppercase; font-weight: 700; display: flex; align-items: center; gap: 8px; }
.kicker::before { content: ""; width: 18px; height: 1px; background: linear-gradient(90deg, var(--cyan), transparent); }
h1, h2, h3 { letter-spacing: -.035em; line-height: 1.06; }
h1 { font-size: clamp(42px, 6.2vw, 78px); margin: 18px 0 16px; font-weight: 850; }
h1 span { display: block; background: linear-gradient(100deg, #f0fbff 10%, var(--cyan) 50%, var(--green)); -webkit-background-clip: text; background-clip: text; color: transparent; }
h2 { font-size: clamp(26px, 3.4vw, 42px); margin: 6px 0 0; font-weight: 820; }
p { margin: 0; }
.nav { position: sticky; top: 0; z-index: 50; backdrop-filter: blur(18px) saturate(140%); background: rgba(5,8,11,.78); border-bottom: 1px solid var(--line); }
.nav-in { min-height: 66px; display: flex; align-items: center; justify-content: space-between; gap: 18px; }
.nav-left { display: flex; align-items: center; gap: 10px; min-width: 0; }
.back {
display: inline-flex; align-items: center; gap: 6px; padding: 7px 12px; border-radius: 10px;
font-size: 12px; font-weight: 700; text-decoration: none; white-space: nowrap;
color: var(--muted); border: 1px solid var(--line); background: rgba(27,32,42,.7);
transition: color .15s ease, border-color .15s ease, background .15s ease;
}
.back:hover { color: var(--cyan); border-color: rgba(143,227,245,.5); background: rgba(143,227,245,.12); }
.back .arrow { font-size: 14px; line-height: 1; }
/* Geniş ekranda KickWatch'taki gibi pencere kenarına yaslan */
@media (min-width: 1360px) {
.back { position: absolute; left: 18px; top: 50%; transform: translateY(-50%); z-index: 2; }
}
@media (max-width: 700px) { .back { padding: 7px 9px; } .back .lbl { display: none; } }
.brand { display: flex; align-items: center; gap: 11px; text-decoration: none; font-weight: 820; }
.brand img { width: 34px; height: 34px; border-radius: 10px; border: 1px solid var(--line2); box-shadow: 0 0 24px rgba(143,227,245,.12); }
.brand small { display: block; font-family: var(--mono); font-size: 9px; color: var(--muted); letter-spacing: .16em; text-transform: uppercase; font-weight: 500; }
.nav-links { display: flex; align-items: center; gap: 4px; }
.nav-links .btn, .actions .btn { flex: 0 0 auto; }
.nav-links a { text-decoration: none; font-size: 12px; color: var(--muted); padding: 8px 10px; border-radius: 8px; }
.nav-links a:hover { color: var(--text); background: rgba(143,227,245,.06); }
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; border: 1px solid transparent; border-radius: 10px; padding: 11px 16px; text-decoration: none; font-size: 12px; font-weight: 780; transition: transform .18s, filter .18s, border-color .18s, background .18s; white-space: nowrap; }
.btn-primary { background: linear-gradient(135deg, #c8f7ff, var(--cyan) 40%, #62d6a0); color: #031014; box-shadow: 0 10px 30px rgba(87,201,232,.16); }
.btn-primary:hover { transform: translateY(-1px); filter: brightness(1.06); }
.btn-ghost { border-color: var(--line2); background: rgba(10,18,24,.7); color: #dcecf2; }
.btn-ghost:hover { border-color: rgba(143,227,245,.55); background: rgba(143,227,245,.06); }
.hero { padding: 68px 0 42px; display: grid; grid-template-columns: 1.05fr .95fr; gap: 44px; align-items: center; }
.eyebrow { display: inline-flex; align-items: center; gap: 8px; border: 1px solid rgba(143,227,245,.25); background: rgba(143,227,245,.06); border-radius: 999px; padding: 6px 11px; font-family: var(--mono); font-size: 9px; letter-spacing: .12em; text-transform: uppercase; color: var(--cyan); }
.pulse { width: 6px; height: 6px; border-radius: 50%; background: var(--green); box-shadow: 0 0 0 0 rgba(141,255,173,.6); animation: pulse 2s infinite; }
@keyframes pulse { 70% { box-shadow: 0 0 0 7px rgba(141,255,173,0); } 100% { box-shadow: 0 0 0 0 rgba(141,255,173,0); } }
.lead { max-width: 620px; color: #b3c9d3; font-size: 16px; margin: 0 0 24px; }
.lead b { color: #e9f8fc; font-weight: 650; }
.actions { display: flex; flex-wrap: wrap; gap: 10px; }
.meta { display: flex; flex-wrap: wrap; gap: 7px; margin-top: 22px; }
.chip { font-family: var(--mono); font-size: 9px; color: #b7ced8; border: 1px solid var(--line); background: rgba(10,20,27,.7); padding: 5px 8px; border-radius: 6px; letter-spacing: .02em; }
.chip.live { color: var(--green); border-color: rgba(141,255,173,.28); }
/* Pure Rust Conversion Engines Showcase */
.engine-stage {
position: relative; border: 1px solid var(--line2); border-radius: 22px; overflow: hidden;
background: linear-gradient(160deg, rgba(14,24,34,.96), rgba(6,12,17,.98));
box-shadow: 0 38px 90px rgba(0,0,0,.55), 0 0 0 1px rgba(143,227,245,.06) inset;
padding: 24px; display: flex; flex-direction: column; justify-content: space-between; gap: 18px;
min-height: 400px;
}
.engine-top { width: 100%; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--line); padding-bottom: 12px; }
.engine-badge { font-family: var(--mono); font-size: 10px; color: var(--cyan); background: rgba(143,227,245,.08); padding: 4px 10px; border-radius: 999px; border: 1px solid rgba(143,227,245,.2); }
.engine-list { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
.engine-item {
border: 1px solid var(--line); border-radius: 12px; padding: 12px;
background: rgba(10,18,26,.85); display: flex; align-items: flex-start; gap: 10px;
transition: border-color .2s, transform .2s, background .2s;
}
.engine-item:hover { border-color: rgba(143,227,245,.45); transform: translateY(-2px); background: rgba(16,30,42,.95); }
.engine-item .ico { font-size: 18px; line-height: 1.2; }
.engine-item b { display: block; font-size: 12px; color: #e8f5fa; font-weight: 740; }
.engine-item span { display: block; font-family: var(--mono); font-size: 10px; color: var(--muted); margin-top: 2px; }
.engine-hud {
width: 100%; border: 1px solid var(--line); border-radius: 12px;
background: rgba(4,9,12,.85); padding: 10px 14px; display: flex; align-items: center; justify-content: space-between;
font-family: var(--mono); font-size: 11px; gap: 10px;
}
.hud-text { color: var(--cyan); }
.hud-stat { color: var(--green); }
/* Visual Metrics */
.stats { display: grid; grid-template-columns: repeat(4,1fr); gap: 1px; border: 1px solid var(--line); border-radius: 14px; overflow: hidden; background: var(--line); margin-top: 20px; }
.stat { background: rgba(7,13,18,.86); padding: 18px; }
.stat b { display: block; font-family: var(--mono); font-size: 24px; color: var(--cyan); letter-spacing: -.04em; }
.stat span { display: block; font-size: 11px; color: var(--muted); margin-top: 4px; }
/* Visual Showcase Cards */
section { padding: 48px 0; }
.section-head { display: flex; align-items: end; justify-content: space-between; gap: 24px; margin-bottom: 24px; }
.section-head p { max-width: 500px; color: var(--muted); font-size: 13px; }
.grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; }
.card {
position: relative; overflow: hidden; border: 1px solid var(--line); border-radius: 16px; padding: 22px;
background: linear-gradient(160deg, rgba(14,24,32,.9), rgba(7,13,18,.92));
transition: transform .22s, border-color .22s, box-shadow .22s;
}
.card:hover { transform: translateY(-4px); border-color: rgba(143,227,245,.4); box-shadow: 0 16px 40px rgba(0,0,0,.35); }
.card .ico { width: 40px; height: 40px; display: grid; place-items: center; border-radius: 12px; border: 1px solid rgba(143,227,245,.2); background: rgba(143,227,245,.07); color: var(--cyan); font-size: 19px; margin-bottom: 14px; }
.card h3 { margin: 0 0 8px; font-size: 15px; font-weight: 760; }
.card p { color: #9ab2bd; font-size: 12.5px; line-height: 1.5; }
.card .visual-tag {
display: inline-flex; align-items: center; gap: 6px; font-family: var(--mono); font-size: 9px;
padding: 4px 8px; border-radius: 6px; margin-top: 14px; border: 1px solid var(--line); background: rgba(5,11,16,.6);
color: var(--cyan);
}
.card.wide { grid-column: span 2; }
.card.spotlight {
background: radial-gradient(circle at 10% 10%, rgba(143,227,245,.14), transparent 60%), linear-gradient(140deg, rgba(16,28,38,.92), rgba(7,13,18,.95));
border-color: rgba(143,227,245,.3);
}
/* Visual Pathways */
.flow-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }
.flow-box {
border: 1px solid var(--line); border-radius: 16px; padding: 22px; background: rgba(8,15,20,.82);
display: flex; flex-direction: column; gap: 14px;
}
.flow-header { display: flex; align-items: center; justify-content: space-between; }
.flow-badge { font-family: var(--mono); font-size: 10px; color: var(--green); border: 1px solid rgba(141,255,173,.3); padding: 4px 8px; border-radius: 6px; background: rgba(141,255,173,.06); }
.flow-pipeline {
display: flex; align-items: center; gap: 8px; font-family: var(--mono); font-size: 11px; flex-wrap: wrap;
background: rgba(4,9,13,.75); padding: 12px 14px; border-radius: 10px; border: 1px solid var(--line);
}
.flow-node { padding: 4px 8px; border-radius: 6px; background: rgba(143,227,245,.12); color: #d6f2fa; border: 1px solid rgba(143,227,245,.2); }
.flow-arrow { color: var(--cyan); font-weight: 700; }
.flow-result { padding: 4px 8px; border-radius: 6px; background: rgba(141,255,173,.14); color: var(--green); border: 1px solid rgba(141,255,173,.3); font-weight: 700; }
/* Interactive Comparison Matrix */
.matrix { width: 100%; border-collapse: collapse; font-size: 12px; border: 1px solid var(--line); border-radius: 14px; overflow: hidden; }
.matrix th, .matrix td { text-align: left; padding: 12px 14px; border-bottom: 1px solid var(--line); }
.matrix th { font-family: var(--mono); color: #7f9aa7; font-size: 10px; letter-spacing: .1em; text-transform: uppercase; background: rgba(143,227,245,.045); }
.matrix td:first-child { color: #d9ecf2; font-weight: 600; }
.matrix tr:last-child td { border-bottom: 0; }
.tag { font-family: var(--mono); font-size: 9.5px; border-radius: 5px; padding: 3px 7px; border: 1px solid; }
.tag.native { color: #9dffb9; border-color: rgba(141,255,173,.3); background: rgba(141,255,173,.08); }
.tag.omml { color: #c084fc; border-color: rgba(192,132,252,.35); background: rgba(192,132,252,.08); }
.tag.stream { color: #8fe3f5; border-color: rgba(143,227,245,.3); background: rgba(143,227,245,.08); }
/* Download & CTA */
.download-card {
border: 1px solid var(--line2); border-radius: 20px; padding: 28px;
background: radial-gradient(600px 240px at 90% 0%, rgba(143,227,245,.14), transparent 60%), rgba(8,15,20,.95);
box-shadow: 0 24px 60px rgba(0,0,0,.4); display: grid; grid-template-columns: 1.2fr .8fr; gap: 24px; align-items: center;
}
.download-card .big { font-size: 28px; font-weight: 850; letter-spacing: -.04em; }
.hash {
margin-top: 12px; border: 1px solid var(--line); border-radius: 8px; background: #050b0f; padding: 9px 12px;
font-family: var(--mono); font-size: 9.5px; color: #87a6b3; word-break: break-all;
}
footer { border-top: 1px solid var(--line); margin-top: 40px; padding: 26px 0 40px; color: #728b98; font-size: 11px; }
footer .wrap { display: flex; justify-content: space-between; gap: 14px; flex-wrap: wrap; }
footer a { color: #a9c4ce; text-decoration: none; }
@media (max-width: 900px) {
.hero { grid-template-columns: 1fr; padding-top: 40px; }
.grid { grid-template-columns: 1fr 1fr; }
.card.wide { grid-column: span 2; }
.flow-grid { grid-template-columns: 1fr; }
.download-card { grid-template-columns: 1fr; }
}
@media (max-width: 640px) {
.grid { grid-template-columns: 1fr; }
.card.wide { grid-column: auto; }
.stats { grid-template-columns: 1fr 1fr; }
.engine-list { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="aurora"><span></span><span></span><span></span></div>
<nav class="nav">
<div class="wrap nav-in">
<div class="nav-left">
<a class="back" href="https://ttmadethat.shop/#ldapps" title="LD Apps sayfasına dön">
<span class="arrow">←</span><span class="lbl">LD Apps</span>
</a>
<a class="brand" href="/">
<img src="/static/downloads/ld-apps/ld-converter-logo.png" alt="LD Converter">
<div>
<span>LD Converter</span>
<small>Tauri v2 · Rust</small>
</div>
</a>
</div>
<div class="nav-links">
<a href="#ozellikler">Özellikler</a>
<a href="#formatlar">Formatlar</a>
<a href="#indir" class="btn btn-primary">⬇️ İndir v3.6.4</a>
</div>
</div>
</nav>
<header class="hero wrap">
<div>
<div class="eyebrow"><span class="pulse"></span>Tauri v2 &amp; Rust 64-Bit Core</div>
<h1>Ultra Hızlı. <span>Sıfır Bloat.</span></h1>
<p class="lead">
Dosyalarını pencereye sürükle-bırak veya Windows Gezgini sağ tık menüsünden dönüştür:
<b>JPEG XL (JXL)</b>, <b>Word Denklem Formülleri (OMML)</b>, <b>PDF &amp; OCR</b>, <b>Canlı FFmpeg Medya</b> ve <b>7-Zip Güvenliği</b> tek bir şık masaüstü uygulamasında buluştu.
</p>
<div class="actions">
<a class="btn btn-primary" href="#indir">🚀 Kuruluma Başla (v3.6.4)</a>
<a class="btn btn-ghost" href="#ozellikler">⚡ Özellikleri Keşfet</a>
</div>
<div class="meta">
<span class="chip live">● Windows 11 / 10 Uyumlu</span>
<span class="chip">Pure Rust Image &amp; Archive Core</span>
<span class="chip">100% Çevrimdışı Çalışır</span>
</div>
</div>
<!-- Pure Rust Conversion Engines Showcase -->
<div class="engine-stage" id="motorlar">
<div class="engine-top">
<span class="kicker">Saf Rust Mimarisi</span>
<span class="engine-badge">Zero-Python · Zero-Bloat</span>
</div>
<div class="engine-list">
<div class="engine-item">
<span class="ico">📐</span>
<div>
<b>OMML Denklem DOCX</b>
<span>PDF &amp; LaTeX → &lt;m:oMath&gt;</span>
</div>
</div>
<div class="engine-item">
<span class="ico">📄</span>
<div>
<b>PDF Düzen Motoru</b>
<span>DOCX, PNG/JPG, Ayır/Birleştir</span>
</div>
</div>
<div class="engine-item">
<span class="ico">✨</span>
<div>
<b>JPEG XL &amp; Modern Görsel</b>
<span>JXL, WebP, AVIF, ICO, GIF</span>
</div>
</div>
<div class="engine-item">
<span class="ico">🎬</span>
<div>
<b>Canlı FFmpeg Medya</b>
<span>MP4, MKV, MP3, Trim &amp; % Takibi</span>
</div>
</div>
<div class="engine-item">
<span class="ico">📦</span>
<div>
<b>Güvenli 7Z / ZIP</b>
<span>Zip Slip Koruması · AES</span>
</div>
</div>
<div class="engine-item">
<span class="ico">🖱️</span>
<div>
<b>Explorer Sağ Tık &amp; OCR</b>
<span>Tek Tık Menü · Çevrimdışı OCR</span>
</div>
</div>
</div>
<div class="engine-hud">
<span class="hud-text">Sürükle-Bırak + Explorer Sağ Tık Menüsü</span>
<span class="hud-stat">● %100 Çevrimdışı</span>
</div>
</div>
</header>
<!-- Visual Key Metrics -->
<section class="wrap">
<div class="stats">
<div class="stat">
<b>&lt; 15 ms</b>
<span>Tauri v2 Başlatma Hızı</span>
</div>
<div class="stat">
<b>100%</b>
<span>OMML Denklem Uyumu</span>
</div>
<div class="stat">
<b>12+</b>
<span>Görsel &amp; Medya Formatı</span>
</div>
<div class="stat">
<b>Sağ Tık</b>
<span>Explorer Menü Entegrasyonu</span>
</div>
</div>
</section>
<!-- Visual Feature Cards -->
<section class="wrap" id="ozellikler">
<div class="section-head">
<div>
<span class="kicker">Öne Çıkan Yetenekler</span>
<h2>Masaüstü Dönüşümünde Standartları Yeniden Belirledik</h2>
</div>
<p>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.</p>
</div>
<div class="grid">
<div class="card spotlight wide">
<div class="ico">📐</div>
<h3>Markdown &amp; PDF'ten Gerçek Word Denklemlerine (OMML)</h3>
<p>
Akademik makaleler, ders notları veya formül dolu dökümanlar artık Word'e resim olarak yapışmıyor. <code>$E = mc^2$</code> gibi LaTeX formülleri doğrudan Microsoft Word'ün yerleşik <code>&lt;m:oMath&gt;</code> denklem motoruna çevrilir; tıklayıp düzenleyebilirsiniz.
</p>
<span class="visual-tag">✓ LaTeX $...$ &amp; $$...$$ &nbsp;→&nbsp; Microsoft Word OMML</span>
</div>
<div class="card">
<div class="ico">✨</div>
<h3>JPEG XL (JXL) Çift Yönlü Motor</h3>
<p>
Gömülü <b>cjxl / djxl</b> 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.
</p>
<span class="visual-tag">JXL ↔ PNG / JPG / WebP / BMP / TIFF</span>
</div>
<div class="card">
<div class="ico">🎬</div>
<h3>Canlı FFmpeg Medya Laboratuvarı</h3>
<p>
Video ve ses dosyalarını dönüştürürken arka planda donup kalmayın. Canlı yüzde (1%..99%), <code>00:00:00</code> Trim ve Sesi Kaldır (Mute) seçenekleriyle tam kontrol elinizde.
</p>
<span class="visual-tag">H.264 / AAC / MP3 / Trim</span>
</div>
<div class="card">
<div class="ico">🛡️</div>
<h3>Zip Slip Korumalı Arşivleme</h3>
<p>
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.
</p>
<span class="visual-tag">ZIP · 7Z · RAR · AES-256</span>
</div>
<div class="card">
<div class="ico">🔍</div>
<h3>Çevrimdışı Akıllı OCR &amp; QR Kod</h3>
<p>
Taranmış belgeler ve resimlerdeki yazıları internete göndermeden metne dökün. Görseldeki QR kodları tek dokunuşla panoya kopyalayın.
</p>
<span class="visual-tag">rqrr Core + Yerleşik OCR</span>
</div>
</div>
</section>
<!-- Visual Pathways Flow -->
<section class="wrap" id="formatlar">
<div class="section-head">
<div>
<span class="kicker">Dönüşüm Rotaları</span>
<h2>En Popüler İş Akışları</h2>
</div>
<p>Karmaşık komut satırları veya web sitelerine dosya yükleme derdi yok.</p>
</div>
<div class="flow-grid">
<div class="flow-box">
<div class="flow-header">
<span class="flow-badge">Akademik &amp; Belge</span>
<span class="mono" style="font-size:11px;color:var(--muted)">OMML Pipeline</span>
</div>
<div class="flow-pipeline">
<span class="flow-node">Formulas.md</span>
<span class="flow-arrow">➔</span>
<span class="flow-node">LaTeX Parser</span>
<span class="flow-arrow">➔</span>
<span class="flow-result">Düzenlenebilir Word (.docx)</span>
</div>
<p style="font-size:12px;color:var(--muted)">Matematik sembolleri, kesirler, integraller ve matrisler Word'ün yerel denklem editörüyle tam uyumlu çıkar.</p>
</div>
<div class="flow-box">
<div class="flow-header">
<span class="flow-badge">Yeni Nesil Görsel</span>
<span class="mono" style="font-size:11px;color:var(--muted)">Next-Gen Graphics</span>
</div>
<div class="flow-pipeline">
<span class="flow-node">Photo.jxl</span>
<span class="flow-arrow">➔</span>
<span class="flow-node">Rust Image / FFmpeg</span>
<span class="flow-arrow">➔</span>
<span class="flow-result">WebP / PNG / JPG</span>
</div>
<p style="font-size:12px;color:var(--muted)">İster yüzlerce fotoğrafı WebP yapın, ister web siteniz için ultra hafif kayıpsız JXL çıktısı alın.</p>
</div>
</div>
</section>
<!-- Format Matrix Table -->
<section class="wrap">
<table class="matrix">
<thead>
<tr>
<th>Kategori</th>
<th>Girdi Formatları</th>
<th>Çıktı &amp; Özel Yetenekler</th>
<th>Çekirdek Motor</th>
</tr>
</thead>
<tbody>
<tr>
<td>Görseller</td>
<td>PNG, JPG, WebP, JXL, AVIF, BMP, TIFF, GIF, ICO</td>
<td>Kalite ayarı, boyutlandırma, animasyonlu GIF yapma</td>
<td><span class="tag native">Pure Rust + FFmpeg</span></td>
</tr>
<tr>
<td>Matematik &amp; Belge</td>
<td>Markdown (.md), PDF, DOCX, TXT, HTML</td>
<td>OMML &lt;m:oMath&gt; düzenlenebilir denklem çıktısı</td>
<td><span class="tag omml">Pandoc &amp; LD Math Engine</span></td>
</tr>
<tr>
<td>Medya (Video / Ses)</td>
<td>MP4, MKV, AVI, MOV, WEBM, MP3, WAV, FLAC, AAC</td>
<td>Canlı yüzde akışı, 00:00:00 Trim, Sesi Kaldır</td>
<td><span class="tag stream">FFmpeg Stream Engine</span></td>
</tr>
<tr>
<td>Arşiv &amp; Güvenlik</td>
<td>ZIP, 7Z, TAR, GZ, RAR</td>
<td>Zip Slip koruması, AES şifreli açma, @listfile</td>
<td><span class="tag native">Rust Zip &amp; 7-Zip CLI</span></td>
</tr>
</tbody>
</table>
</section>
<!-- Download & Setup Card -->
<section class="wrap" id="indir">
<div class="download-card">
<div>
<div class="eyebrow" style="margin-bottom:12px">Güncel Kararlı Sürüm</div>
<div class="big">LD Converter v3.6.4</div>
<p style="color:#b5cbd5;font-size:13.5px;margin:8px 0 18px">
Tauri v2 + Rust mimarisi, saf Rust OMML denklem &amp; ofis motoru, Explorer sağ tık menüsü ve GPU ivmesiyle sıfır hata onaylı Windows 10/11 masaüstü paketi.
</p>
<div class="actions">
<a class="btn btn-primary" href="/static/downloads/ld-apps/LD-Converter-v3.6.4-Setup.exe" download>
⬇️ Kurulum Paketini İndir (Setup.exe)
</a>
<a class="btn btn-ghost" href="https://github.com" target="_blank" rel="noopener">
📦 Kaynak Kodları İncele
</a>
</div>
<div class="hash">
SHA-256: 1A5E0BC161A0645578FDF2A12D7A4CD9D5C0B394692DDF386D0D704A605D5CB3
</div>
</div>
<div>
<div style="border:1px solid var(--line);border-radius:14px;background:rgba(5,11,16,.7);padding:18px">
<div style="font-family:var(--mono);font-size:11px;color:var(--cyan);margin-bottom:10px">SİSTEM GEREKSİNİMLERİ</div>
<ul style="margin:0;padding-left:18px;font-size:12px;color:var(--muted);display:grid;gap:6px">
<li>Windows 10 / Windows 11 (x64)</li>
<li>WebView2 Runtime (Sistemle hazır gelir)</li>
<li>Kurulum boyutu: ~8.3 MB (Tauri v2 + Saf Rust Çekirdeği)</li>
<li>Dahili Rust Motoru: Pandoc/Python gerekmez, cjxl/djxl gömülü</li>
</ul>
</div>
</div>
</div>
</section>
<footer>
<div class="wrap">
<div>
<b>LD Converter</b> — LilDosto tarafından geliştirildi.
</div>
<div>
<a href="/">Ana Sayfa</a> · <a href="/ld-fdpi">LD FDPI</a> · <a href="https://ttmadethat.shop">ttmadethat.shop</a>
</div>
</div>
</footer>
</body>
</html>

View file

@ -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"]

4
src-tauri/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
# Generated by Cargo
# will have compiled files and executables
/target/
/gen/schemas

7107
src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

56
src-tauri/Cargo.toml Normal file
View file

@ -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"

Binary file not shown.

10
src-tauri/build.rs Normal file
View file

@ -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}");
}
}

View file

@ -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"
]
}

BIN
src-tauri/icons/128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

BIN
src-tauri/icons/32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

BIN
src-tauri/icons/64x64.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

BIN
src-tauri/icons/icon.icns Normal file

Binary file not shown.

BIN
src-tauri/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

BIN
src-tauri/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 KiB

View file

@ -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<ToolChoice> {
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<ToolChoice> = 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<ToolChoice> {
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<ToolChoice> {
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"),
]
}
}

121
src-tauri/src/cli.rs Normal file
View file

@ -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 <eylem> <dosya...>`
//! 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<String>)> {
let index = args.iter().position(|arg| arg == "--convert")?;
let action = args.get(index + 1)?.clone();
let files: Vec<String> = 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 <eylem> <dosya...>",
true,
);
return 2;
};
let existing: Vec<String> = 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
}
}
}

View file

@ -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<String>) -> AppResult<Vec<ToolChoice>> {
Ok(FormatCatalog::get_choices_for_files(
&files,
None,
crate::services::EngineResolver::jxl_available(),
))
}
#[tauri::command]
pub fn get_default_choices() -> AppResult<Vec<ToolChoice>> {
Ok(FormatCatalog::get_default_choices())
}

View file

@ -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<String>,
target_action_id: String,
options: Option<ConversionOptions>,
task_id: Option<String>,
state: State<'_, AppState>,
) -> AppResult<ConversionResult> {
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<bool> {
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)
}
}

View file

@ -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<Vec<HistoryEntry>> {
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(())
}

View file

@ -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::*;

View file

@ -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<AppPreferences> {
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(())
}

View file

@ -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<EngineStatus> {
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<String> {
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<String> {
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<String>) -> Vec<u64> {
paths.iter().map(|path| crate::utils::total_size(path)).collect()
}

View file

@ -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()))
}

46
src-tauri/src/error.rs Normal file
View file

@ -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<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
pub type AppResult<T> = Result<T, AppError>;

224
src-tauri/src/lib.rs Normal file
View file

@ -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<u16> { 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<u16> { 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);
}
}

65
src-tauri/src/logging.rs Normal file
View file

@ -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<PathBuf> {
dirs::data_local_dir().map(|dir| dir.join("LDConverter").join("logs"))
}
pub fn log_path() -> Option<PathBuf> {
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);
}

20
src-tauri/src/main.rs Normal file
View file

@ -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<String> = 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();
}

View file

@ -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<String>,
display_name: impl Into<String>,
category: impl Into<String>,
icon_name: impl Into<String>,
description: impl Into<String>,
) -> Self {
Self {
id: id.into(),
display_name: display_name.into(),
category: category.into(),
icon_name: icon_name.into(),
description: description.into(),
}
}
}

View file

@ -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<String>,
pub output_files: Vec<String>,
pub original_size_bytes: u64,
pub output_size_bytes: u64,
pub timestamp: DateTime<Utc>,
pub success: bool,
pub error_message: Option<String>,
}

View file

@ -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};

View file

@ -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,
}
}
}

View file

@ -0,0 +1,58 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversionOptions {
pub destination_folder: Option<String>,
pub overwrite_existing: bool,
pub image_quality: u8,
pub target_width: Option<u32>,
pub target_height: Option<u32>,
pub strip_metadata: bool,
pub video_preset: Option<String>,
pub video_crf: Option<u8>,
pub audio_bitrate_kbps: Option<u16>,
pub start_time: Option<String>,
pub end_time: Option<String>,
pub mute_audio: bool,
pub pdf_page_range: Option<String>,
pub pdf_rotate_degrees: Option<i32>,
pub archive_password: Option<String>,
}
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<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversionResult {
pub success: bool,
pub output_files: Vec<String>,
pub error_message: Option<String>,
pub duration_ms: u64,
}

1010
src-tauri/src/selftest.rs Normal file

File diff suppressed because it is too large Load diff

View file

@ -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<PathBuf> {
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<PathBuf> {
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<PathBuf> {
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::<File>(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<PathBuf> {
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<F>(
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<PathBuf> {
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<PathBuf> {
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<PathBuf> {
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<PathBuf> {
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<Option<PathBuf>> {
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<PathBuf> {
let canonical_dest = destination_dir.canonicalize()?;
let mut recorded_err: Option<AppError> = 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<PathBuf> {
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<PathBuf> {
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<W: Write>(
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<dyn std::error::Error>> {
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(())
}
}

View file

@ -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<String> {
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,
}
}

File diff suppressed because it is too large Load diff

View file

@ -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<String> {
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<PathBuf> {
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(
"<!doctype html><html lang=\"tr\"><head><meta charset=\"utf-8\"></head><body>",
);
for line in text.lines() {
if line.trim().is_empty() {
continue;
}
html.push_str("<p>");
html.push_str(&escape_html(line));
html.push_str("</p>\n");
}
html.push_str("</body></html>");
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<image::DynamicImage> = 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<Vec<String>> {
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<u16> = 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<String> {
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<Vec<(String, Vec<u8>)>> {
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<u32> {
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("</w:p>", "\n")
.replace("<w:br/>", "\n")
.replace("<w:br />", "\n")
.replace("<w:tab/>", "\t")
.replace("<w:tab />", "\t")
.replace("</w:tr>", "\n")
.replace("</w:tc>", "\t");
text = remove_tags(&text);
unescape_xml(&text)
}
fn strip_odf_xml(xml: &str) -> String {
let mut text = xml
.replace("</text:p>", "\n")
.replace("</text:h>", "\n")
.replace("<text:tab/>", "\t")
.replace("<text:line-break/>", "\n")
.replace("</table:table-cell>", "\t")
.replace("</table:table-row>", "\n");
text = remove_tags(&text);
unescape_xml(&text)
}
fn strip_drawingml_xml(xml: &str) -> String {
let mut text = xml.replace("</a:p>", "\n").replace("</a:tr>", "\n");
text = remove_tags(&text);
unescape_xml(&text)
}
fn read_xlsx(path: &Path) -> AppResult<String> {
let shared: Vec<String> = 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("<row").skip(1) {
let mut cells = Vec::new();
for cell in row.split("<c").skip(1) {
let is_shared = cell.contains("t=\"s\"");
let value = extract_first(cell, "v")
.or_else(|| extract_first(cell, "t"))
.unwrap_or_default();
let value = unescape_xml(&value).trim().to_string();
if value.is_empty() {
cells.push(String::new());
} else if is_shared {
let index: usize = value.parse().unwrap_or(usize::MAX);
cells.push(shared.get(index).cloned().unwrap_or_default());
} else {
cells.push(value);
}
}
let line = cells.join("\t");
if !line.trim().is_empty() {
sheet_text.push_str(line.trim_end());
sheet_text.push('\n');
}
}
sheets.push(sheet_text);
}
Ok(sheets.join("\n\n---\n\n"))
}
fn extract_first(xml: &str, tag: &str) -> Option<String> {
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<String> {
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 [
"<script", "</script", "<style", "</style",
] {
// script/style bloklarını kaba biçimde kaldır
while let Some(start) = lower.find(tag) {
let end = if tag.starts_with("</") {
lower[start..].find('>').map(|i| start + i + 1)
} else {
let closing = format!("</{}", &tag[1..]);
lower[start..]
.find(&closing)
.and_then(|i| lower[start + i..].find('>').map(|j| start + i + j + 1))
};
match end {
Some(end) => {
lower.replace_range(start..end, "");
}
None => break,
}
}
}
let mut text = lower
.replace("<br>", "\n")
.replace("<br/>", "\n")
.replace("<br />", "\n")
.replace("</p>", "\n")
.replace("</div>", "\n")
.replace("</h1>", "\n")
.replace("</h2>", "\n")
.replace("</h3>", "\n")
.replace("</h4>", "\n")
.replace("</li>", "\n")
.replace("<li>", "• ")
.replace("</tr>", "\n")
.replace("</td>", "\t")
.replace("</th>", "\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("&lt;", "<")
.replace("&gt;", ">")
.replace("&quot;", "\"")
.replace("&apos;", "'")
.replace("&nbsp;", " ")
.replace("&#x1F", " ")
.replace("&amp;", "&")
}
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::<i32>() {
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<String> = 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('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
}

View file

@ -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("<w:p><w:r><w:br w:type=\"page\"/></w:r></w:p>");
}
body.push_str("<w:p><w:r>");
if !line.trim().is_empty() {
body.push_str("<w:t xml:space=\"preserve\">");
body.push_str(&escape(line));
body.push_str("</w:t>");
}
body.push_str("</w:r></w:p>");
}
}
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<u8>)> = 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(&paragraph_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("<w:p><w:r><w:br w:type=\"page\"/></w:r></w:p>");
}
}
}
if !document.header.is_empty() {
body.push_str(&paragraph_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(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><w:numbering xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">",
);
for index in 0..self.next_id {
xml.push_str(&format!(
"<w:abstractNum w:abstractNumId=\"{0}\"><w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1.\"/><w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr></w:lvl></w:abstractNum>",
index
));
xml.push_str(&format!(
"<w:num w:numId=\"{0}\"><w:abstractNumId w:val=\"{0}\"/></w:num>",
index + 1
));
}
xml.push_str("</w:numbering>");
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("<w:p>");
let mut properties = String::new();
if let Some(level) = paragraph.style.heading {
let clamped = level.clamp(1, 6);
properties.push_str(&format!(
"<w:pStyle w:val=\"Heading{}\"/><w:outlineLvl w:val=\"{}\"/>",
clamped,
clamped.saturating_sub(1)
));
}
if let Some(list) = paragraph.style.list {
let num_id = numbering.next();
properties.push_str(&format!(
"<w:numPr><w:ilvl w:val=\"{}\"/><w:numId w:val=\"{}\"/></w:numPr>",
paragraph.style.level.min(8),
num_id
));
if list == ListKind::Bullet {
properties.push_str("<w:rPr><w:rFonts w:ascii=\"Segoe UI\"/></w:rPr>");
}
}
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!("<w:jc w:val=\"{}\"/>", 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("<w:spacing w:before=\"240\" w:after=\"120\" w:line=\"280\" w:lineRule=\"auto\"/>"),
2 => properties.push_str("<w:spacing w:before=\"180\" w:after=\"80\" w:line=\"260\" w:lineRule=\"auto\"/>"),
_ => properties.push_str("<w:spacing w:before=\"120\" w:after=\"60\" w:line=\"240\" w:lineRule=\"auto\"/>"),
}
} else if paragraph.style.space_before_pt > 0.0 || paragraph.style.space_after_pt > 0.0 {
properties.push_str(&format!(
"<w:spacing w:before=\"{}\" w:after=\"{}\" w:line=\"260\" w:lineRule=\"auto\"/>",
(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("<w:spacing w:before=\"100\" w:after=\"100\" w:line=\"240\" w:lineRule=\"auto\"/>");
} else {
// Gövde paragraflarında standart akıcı boşluk
properties.push_str("<w:spacing w:before=\"0\" w:after=\"100\" w:line=\"260\" w:lineRule=\"auto\"/>");
}
if paragraph.style.indent_left_pt > 0.0 {
properties.push_str(&format!(
"<w:ind w:left=\"{}\"/>",
(paragraph.style.indent_left_pt * 20.0).round() as i32
));
}
if !properties.is_empty() {
xml.push_str(&format!("<w:pPr>{}</w:pPr>", properties));
}
for run in &paragraph.runs {
if let Some(omml) = &run.omml {
let trimmed = omml.trim();
if paragraph.style.is_display_math {
if trimmed.starts_with("<m:oMathPara") {
xml.push_str(trimmed);
} else if trimmed.starts_with("<m:oMath") {
xml.push_str(&format!("<m:oMathPara>{}</m:oMathPara>", trimmed));
} else {
xml.push_str(&format!(
"<m:oMathPara><m:oMath>{}</m:oMath></m:oMathPara>",
trimmed
));
}
} else if trimmed.starts_with("<m:oMath") || trimmed.starts_with("<m:oMathPara") {
xml.push_str(trimmed);
} else {
xml.push_str(&format!("<m:oMath>{}</m:oMath>", 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("<w:b/><w:bCs/>");
}
if run.italic {
run_properties.push_str("<w:i/><w:iCs/>");
}
if run.underline {
run_properties.push_str("<w:u w:val=\"single\"/>");
}
if run.strike {
run_properties.push_str("<w:strike/>");
}
if let Some(size) = run.size_pt {
let half_pt = (size * 2.0).round() as i32;
run_properties.push_str(&format!("<w:sz w:val=\"{half_pt}\"/><w:szCs w:val=\"{half_pt}\"/>"));
}
if let Some(color) = run.color {
run_properties.push_str(&format!(
"<w:color w:val=\"{:02X}{:02X}{:02X}\"/>",
color[0], color[1], color[2]
));
}
if let Some(font) = &run.font {
run_properties.push_str(&format!(
"<w:rFonts w:ascii=\"{0}\" w:hAnsi=\"{0}\"/>",
escape(font)
));
}
if let Some(align) = run.vert_align {
run_properties.push_str(match align {
VertAlign::Subscript => "<w:vertAlign w:val=\"subscript\"/>",
VertAlign::Superscript => "<w:vertAlign w:val=\"superscript\"/>",
});
}
xml.push_str("<w:r>");
if !run_properties.is_empty() {
xml.push_str(&format!("<w:rPr>{}</w:rPr>", run_properties));
}
xml.push_str("<w:t xml:space=\"preserve\">");
xml.push_str(&escape(&run.text));
xml.push_str("</w:t></w:r>");
}
xml.push_str("</w:p>");
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::<usize>())
.max()
.unwrap_or(1);
let mut xml = String::from(
"<w:tbl><w:tblPr><w:tblW w:w=\"5000\" w:type=\"pct\"/><w:tblBorders>",
);
for edge in ["top", "left", "bottom", "right", "insideH", "insideV"] {
xml.push_str(&format!(
"<w:{} w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"9AA5B1\"/>",
edge
));
}
xml.push_str("</w:tblBorders></w:tblPr><w:tblGrid>");
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!("<w:gridCol w:w=\"{}\"/>", twips));
}
xml.push_str("</w:tblGrid>");
for row in &table.rows {
xml.push_str("<w:tr>");
for cell in row {
xml.push_str(&cell_xml(cell, numbering));
}
xml.push_str("</w:tr>");
}
xml.push_str("</w:tbl>");
xml
}
fn cell_xml(cell: &Cell, numbering: &mut NumberingState) -> String {
let mut xml = String::from("<w:tc><w:tcPr>");
if cell.colspan > 1 {
xml.push_str(&format!("<w:gridSpan w:val=\"{}\"/>", cell.colspan));
}
if cell.rowspan > 1 {
xml.push_str("<w:vMerge w:val=\"restart\"/>");
}
if let Some(shade) = cell.shade {
xml.push_str(&format!(
"<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"{:02X}{:02X}{:02X}\"/>",
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!("<w:jc w:val=\"{}\"/>", align));
}
xml.push_str("</w:tcPr>");
if cell.paragraphs.is_empty() {
xml.push_str("<w:p/>");
}
for paragraph in &cell.paragraphs {
xml.push_str(&paragraph_xml(paragraph, numbering));
}
xml.push_str("</w:tc>");
xml
}
fn image_paragraph_xml(image: &ImageBlock, index: usize, media: &mut Vec<(String, Vec<u8>)>) -> 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!(
"<w:p><w:r><w:drawing><wp:inline distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\"><wp:extent cx=\"{cx}\" cy=\"{cy}\"/><wp:docPr id=\"{index}\" name=\"Resim {index}\"/><a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"><pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"><pic:nvPicPr><pic:cNvPr id=\"{index}\" name=\"{file_name}\"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed=\"rIdImg{index}\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{cx}\" cy=\"{cy}\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>",
cx = cx,
cy = cy,
index = index,
file_name = file_name
)
}
fn write_package(
output_path: &Path,
body: &str,
numbering: &str,
media: &[(String, Vec<u8>)],
) -> AppResult<()> {
let document_xml = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><w:body>{}</w:body></w:document>"#,
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!(
"<Default Extension=\"{}\" ContentType=\"{}\"/>",
extension, mime
));
}
let numbering_override = if numbering.is_empty() {
""
} else {
r#"<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>"#
};
let content_types = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>{defaults}<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/><Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/>{numbering_override}</Types>"#
);
let rels = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let mut document_rels = String::from(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/><Relationship Id="rIdSettings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/>"#,
);
if !numbering.is_empty() {
document_rels.push_str(
r#"<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>"#,
);
}
for (index, (name, _)) in media.iter().enumerate() {
document_rels.push_str(&format!(
"<Relationship Id=\"rIdImg{}\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\" Target=\"media/{}\"/>",
index + 1,
name
));
}
document_rels.push_str("</Relationships>");
let styles_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:cs="Calibri"/><w:sz w:val="22"/><w:szCs w:val="22"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:before="0" w:after="100" w:line="260" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style><w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/><w:pPr><w:keepNext/><w:spacing w:before="240" w:after="120" w:line="280" w:lineRule="auto"/><w:outlineLvl w:val="0"/></w:pPr><w:rPr><w:b/><w:bCs/><w:color w:val="0F172A"/><w:sz w:val="36"/><w:szCs w:val="36"/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/><w:pPr><w:keepNext/><w:spacing w:before="180" w:after="80" w:line="260" w:lineRule="auto"/><w:outlineLvl w:val="1"/></w:pPr><w:rPr><w:b/><w:bCs/><w:color w:val="1E293B"/><w:sz w:val="28"/><w:szCs w:val="28"/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="Heading3"><w:name w:val="heading 3"/><w:basedOn w:val="Normal"/><w:pPr><w:keepNext/><w:spacing w:before="120" w:after="60" w:line="240" w:lineRule="auto"/><w:outlineLvl w:val="2"/></w:pPr><w:rPr><w:b/><w:bCs/><w:color w:val="334155"/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr></w:style></w:styles>"#;
let settings_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><m:mathPr><m:mathFont m:val="Cambria Math"/><m:brkBin m:val="before"/><m:brkBinSub m:val="--"/><m:smallFrac m:val="0"/><m:dispDef/><m:lMargin m:val="0"/><m:rMargin m:val="0"/><m:defJc m:val="centerGroup"/><m:wrapIndent m:val="1440"/><m:intLim m:val="subSup"/><m:naryLim m:val="undOvr"/></m:mathPr></w:settings>"#;
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<u8>)> = 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('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
}

View file

@ -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<String>,
pandoc: Option<String>,
seven_zip: Option<String>,
}
static CUSTOM_PATHS: OnceLock<RwLock<CustomPaths>> = OnceLock::new();
fn custom_paths() -> &'static RwLock<CustomPaths> {
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<String>) -> Option<String> {
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<String>,
pub pandoc_path: Option<String>,
pub seven_zip_path: Option<String>,
}
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<String> {
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<String> {
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<String> {
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<String> {
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<bool> = 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<String> {
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<String> {
Self::resolve_jxl_tool("cjxl.exe")
}
pub fn resolve_jxl_decoder() -> Option<String> {
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<bool> = 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<String> {
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
}
}

View file

@ -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<String> {
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<Vec<PathBuf>, 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::<serde_json::Value>(&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);
}
}

View file

@ -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<u16> {
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<Self> {
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::<BITMAPINFOHEADER>() 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<Vec<image::RgbImage>> {
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<String> = 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};

View file

@ -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<PathBuf> {
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<PathBuf> {
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<PathBuf> {
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<String>> = 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
}

File diff suppressed because it is too large Load diff

View file

@ -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<PathBuf> {
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
/// (`<m:oMath>` / `<m:oMathPara>`) 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<PathBuf> {
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 (`<m:oMath>`, `<m:oMathPara>`) 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!(
"<w:p><w:pPr><w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"F1F5F9\"/><w:ind w:left=\"280\"/></w:pPr><w:r><w:rPr><w:rFonts w:ascii=\"Consolas\" w:hAnsi=\"Consolas\"/><w:sz w:val=\"20\"/></w:rPr><w:t xml:space=\"preserve\">{}</w:t></w:r></w:p>",
escape_xml(cl)
));
}
continue;
}
// 2) Yatay ayraç (--- / *** / ___)
if is_horizontal_rule(trimmed) {
body.push_str("<w:p><w:pPr><w:pBdr><w:bottom w:val=\"single\" w:sz=\"6\" w:space=\"1\" w:color=\"CBD5E1\"/></w:pBdr></w:pPr></w:p>");
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!(
"<w:p><w:pPr><w:pStyle w:val=\"{}\"/></w:pPr>{}</w:p>",
style,
render_inline_markdown(title)
));
i += 1;
continue;
}
// 5) Alıntı (> ...)
if let Some(quoted) = trimmed.strip_prefix('>') {
body.push_str(&format!(
"<w:p><w:pPr><w:ind w:left=\"420\"/><w:pBdr><w:left w:val=\"single\" w:sz=\"12\" w:space=\"8\" w:color=\"94A3B8\"/></w:pBdr></w:pPr>{}</w:p>",
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!(
"<w:p><w:pPr><w:pStyle w:val=\"ListParagraph\"/><w:ind w:left=\"420\" w:hanging=\"220\"/></w:pPr><w:r><w:t xml:space=\"preserve\">{} </w:t></w:r>{}</w:p>",
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("<w:p/>");
}
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!("<w:p>{}</w:p>", omml),
Err(_) => format!(
"<w:p><w:pPr><w:jc w:val=\"center\"/></w:pPr><w:r><w:t xml:space=\"preserve\">{}</w:t></w:r></w:p>",
escape_xml(latex)
),
}
}
fn render_paragraph_with_embedded_display_math(text: &str) -> String {
if !text.contains("$$") && !text.contains("\\[") {
return format!("<w:p>{}</w:p>", 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!("<w:p>{}</w:p>", render_inline_markdown(rest.trim())));
}
break;
};
let before = rest[..pos].trim();
if !before.is_empty() {
out.push_str(&format!("<w:p>{}</w:p>", 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!(
"<w:p>{}</w:p>",
render_inline_markdown(rest[pos..].trim())
));
break;
}
}
if out.is_empty() {
"<w:p/>".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!(
"<w:r><w:t xml:space=\"preserve\">{}</w:t></w:r>",
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!(
"<w:r><w:rPr><w:rFonts w:ascii=\"Consolas\" w:hAnsi=\"Consolas\"/><w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"F1F5F9\"/></w:rPr><w:t xml:space=\"preserve\">{}</w:t></w:r>",
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!(
"<w:r><w:rPr><w:b/></w:rPr><w:t xml:space=\"preserve\">{}</w:t></w:r>",
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!(
"<w:r><w:rPr><w:i/></w:rPr><w:t xml:space=\"preserve\">{}</w:t></w:r>",
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() {
"<w:r><w:t xml:space=\"preserve\"></w:t></w:r>".to_string()
} else {
out
}
}
fn find_closing_inline_dollar(after_open: &str) -> Option<usize> {
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!(
"<w:r><w:rPr><w:i/></w:rPr><w:t xml:space=\"preserve\">{}</w:t></w:r>",
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(
"<w:tbl><w:tblPr><w:tblW w:w=\"9000\" w:type=\"dxa\"/><w:tblBorders><w:top w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"CBD5E1\"/><w:left w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"CBD5E1\"/><w:bottom w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"CBD5E1\"/><w:right w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"CBD5E1\"/><w:insideH w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"E2E8F0\"/><w:insideV w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"E2E8F0\"/></w:tblBorders></w:tblPr>",
);
for (row_idx, row_line) in rows.iter().enumerate() {
xml.push_str("<w:tr>");
let trimmed = row_line.trim().trim_matches('|');
for cell in trimmed.split('|') {
let shade = if row_idx == 0 {
"<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"F1F5F9\"/>"
} else {
""
};
let cell_runs = render_inline_markdown(cell.trim());
xml.push_str(&format!(
"<w:tc><w:tcPr>{}</w:tcPr><w:p>{}</w:p></w:tc>",
shade, cell_runs
));
}
xml.push_str("</w:tr>");
}
xml.push_str("</w:tbl>");
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!(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n\
<w:document xmlns:w=\"{w}\" xmlns:m=\"{m}\" xmlns:r=\"{r}\">\
<w:body>{body}<w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/><w:pgMar w:top=\"1134\" w:right=\"1134\" w:bottom=\"1134\" w:left=\"1134\"/></w:sectPr></w:body></w:document>",
w = WORD_NS,
m = MATH_NS,
r = REL_NS,
body = body
);
let content_types = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/><Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/></Types>"#;
let rels = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let document_rels = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/></Relationships>"#;
let styles_xml = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n\
<w:styles xmlns:w=\"{w}\">\
<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii=\"Calibri\" w:hAnsi=\"Calibri\" w:cs=\"Calibri\"/><w:sz w:val=\"22\"/><w:szCs w:val=\"22\"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after=\"120\" w:line=\"276\" w:lineRule=\"auto\"/></w:pPr></w:pPrDefault></w:docDefaults>\
<w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"Normal\"><w:name w:val=\"Normal\"/></w:style>\
<w:style w:type=\"paragraph\" w:styleId=\"Heading1\"><w:name w:val=\"heading 1\"/><w:basedOn w:val=\"Normal\"/><w:pPr><w:spacing w:before=\"240\" w:after=\"80\"/><w:keepNext/></w:pPr><w:rPr><w:b/><w:color w:val=\"0F172A\"/><w:sz w:val=\"36\"/><w:szCs w:val=\"36\"/></w:rPr></w:style>\
<w:style w:type=\"paragraph\" w:styleId=\"Heading2\"><w:name w:val=\"heading 2\"/><w:basedOn w:val=\"Normal\"/><w:pPr><w:spacing w:before=\"200\" w:after=\"60\"/><w:keepNext/></w:pPr><w:rPr><w:b/><w:color w:val=\"1E293B\"/><w:sz w:val=\"30\"/><w:szCs w:val=\"30\"/></w:rPr></w:style>\
<w:style w:type=\"paragraph\" w:styleId=\"Heading3\"><w:name w:val=\"heading 3\"/><w:basedOn w:val=\"Normal\"/><w:pPr><w:spacing w:before=\"160\" w:after=\"40\"/><w:keepNext/></w:pPr><w:rPr><w:b/><w:color w:val=\"334155\"/><w:sz w:val=\"26\"/><w:szCs w:val=\"26\"/></w:rPr></w:style>\
<w:style w:type=\"paragraph\" w:styleId=\"ListParagraph\"><w:name w:val=\"List Paragraph\"/><w:basedOn w:val=\"Normal\"/><w:pPr><w:contextualSpacing/></w:pPr></w:style>\
</w:styles>",
w = WORD_NS
);
let settings_xml = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n\
<w:settings xmlns:w=\"{w}\" xmlns:m=\"{m}\">\
<m:mathPr><m:mathFont m:val=\"Cambria Math\"/><m:brkBin m:val=\"before\"/><m:brkBinSub m:val=\"--\"/><m:smallFrac m:val=\"0\"/><m:dispDef/><m:lMargin m:val=\"0\"/><m:rMargin m:val=\"0\"/><m:defJc m:val=\"centerGroup\"/><m:wrapIndent m:val=\"1440\"/><m:intLim m:val=\"subSup\"/><m:naryLim m:val=\"undOvr\"/></m:mathPr>\
</w:settings>",
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(())
}

View file

@ -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<Option<&'static str>> = 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<AtomicBool>,
) -> AppResult<PathBuf> {
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<f64> = 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<f64> {
let parts: Vec<&str> = t.split(':').collect();
if parts.len() == 3 {
let hours = parts[0].parse::<f64>().ok()?;
let mins = parts[1].parse::<f64>().ok()?;
let secs = parts[2].parse::<f64>().ok()?;
Some(hours * 3600.0 + mins * 60.0 + secs)
} else {
None
}
}
}

View file

@ -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;

View file

@ -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<String> {
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<String> {
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<String> {
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<String, String> {
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<u8> = 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
}

View file

@ -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<String, (String, String)>, // 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<Document> {
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<String, (String, String)> {
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<String, HashMap<u8, String>> = 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::<u8>().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<String> {
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<'a, 'input>> {
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<Block>,
) {
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<Paragraph>) {
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<ImageBlock>) {
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::<u8>() {
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::<f32>().ok()) {
paragraph.style.space_before_pt = before / 20.0;
}
if let Some(after) = attribute(&spacing, "after").and_then(|value| value.parse::<f32>().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::<u8>().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<u8> {
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::<u8>().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<String>,
runs: &mut Vec<Run>,
images: &mut Vec<ImageBlock>,
) {
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::<f32>().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<String, (String, String)>, images: &mut Vec<ImageBlock>) {
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<String, (String, String)>,
images: &mut Vec<ImageBlock>,
) {
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::<f32>().ok()).unwrap_or(0.0);
let cy = attribute(&item, "cy").and_then(|value| value.parse::<f32>().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::<f32>().ok())
.unwrap_or(1.0);
widths.push(width);
}
}
let mut raw_rows: Vec<Vec<RawCell>> = 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::<usize>().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<Cell>> = 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,
}
}

View file

@ -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<PathBuf> {
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('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
}
fn inline_html(paragraph: &Paragraph) -> String {
let mut html = String::new();
for run in &paragraph.runs {
let mut text = escape(&run.text).replace('\t', "&emsp;").replace('\n', "<br>");
if text.is_empty() {
continue;
}
if run.bold {
text = format!("<strong>{}</strong>", text);
}
if run.italic {
text = format!("<em>{}</em>", text);
}
if run.underline {
text = format!("<u>{}</u>", text);
}
if run.strike {
text = format!("<s>{}</s>", text);
}
if let Some(align) = run.vert_align {
use crate::services::office_model::VertAlign;
text = match align {
VertAlign::Subscript => format!("<sub>{}</sub>", text),
VertAlign::Superscript => format!("<sup>{}</sup>", text),
};
}
if let Some(color) = run.color {
text = format!(
"<span style=\"color:#{:02x}{:02x}{:02x}\">{}</span>",
color[0], color[1], color[2], text
);
}
if let Some(link) = &run.link {
text = format!("<a href=\"{}\">{}</a>", 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("<!doctype html><html lang=\"tr\"><head><meta charset=\"utf-8\">");
html.push_str("<title>LD Converter</title><style>");
html.push_str(page_rule);
html.push_str(
"html,body{-webkit-print-color-adjust:exact;print-color-adjust:exact}\
body{font-family:Segoe UI,Arial,sans-serif;margin:0;line-height:1.55;color:#111;font-size:11pt}\
table{border-collapse:collapse;width:100%;margin:12px 0;page-break-inside:auto}\
td,th{border:1px solid #9aa5b1;padding:6px;vertical-align:top;page-break-inside:avoid}\
tr{page-break-inside:avoid}\
h1,h2,h3,h4{page-break-after:avoid;margin:16px 0 8px}\
img{max-width:100%;height:auto;page-break-inside:avoid}\
ol,ul{margin:6px 0 6px 24px}li{page-break-inside:avoid}\
.py-0{margin:0}.page-break{page-break-after:always;break-after:page}",
);
html.push_str("</style></head><body>");
if !document.header.is_empty() {
html.push_str("<header style=\"color:#666;font-size:12px;margin-bottom:16px\">");
for paragraph in &document.header {
html.push_str(&format!("<p>{}</p>", inline_html(paragraph)));
}
html.push_str("</header>");
}
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 => "</ul>",
ListKind::Numbered => "</ol>",
});
}
};
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 => "<ul>",
ListKind::Numbered => "<ol>",
});
list_state = Some((list, level));
}
}
html.push_str(&format!("<li>{}</li>", 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!("<h{0}{1}>{2}</h{0}>", level, align, content));
}
None => html.push_str(&format!("<p{}>{}</p>", align, content)),
}
}
Block::Table(table) => {
close_list(&mut html, &mut list_state);
html.push_str("<table>");
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("<colgroup>");
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!("<col style=\"width:{:.1}%\">", percent));
}
html.push_str("</colgroup>");
}
for (row_index, row) in table.rows.iter().enumerate() {
html.push_str("<tr>");
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("<br>");
}
html.push_str(&inline_html(paragraph));
}
html.push_str(&format!("</{}>", tag));
}
html.push_str("</tr>");
}
html.push_str("</table>");
}
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!(
"<p><img src=\"data:{};base64,{}\" alt=\"{}\" style=\"{}\"></p>",
image.format.mime(),
encoded,
escape(image.alt.as_deref().unwrap_or("")),
style
));
}
Block::PageBreak => {
close_list(&mut html, &mut list_state);
html.push_str("<div class=\"page-break\"></div>");
}
}
}
close_list(&mut html, &mut list_state);
html.push_str("</body></html>");
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
}

View file

@ -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<Run>,
}
#[derive(Debug, Clone, Default)]
pub struct ParagraphStyle {
pub heading: Option<u8>,
pub list: Option<ListKind>,
/// 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<f32>,
pub color: Option<[u8; 3]>,
pub font: Option<String>,
pub vert_align: Option<VertAlign>,
pub link: Option<String>,
pub omml: Option<String>,
}
impl Run {
pub fn plain(text: impl Into<String>) -> 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<String>) -> 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<u8>,
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<String>,
}
#[derive(Debug, Clone, Default)]
pub struct Cell {
pub colspan: u32,
pub rowspan: u32,
pub shade: Option<[u8; 3]>,
pub align: Align,
pub paragraphs: Vec<Paragraph>,
}
impl Cell {
pub fn text(&self) -> String {
self.paragraphs
.iter()
.map(Paragraph::text)
.collect::<Vec<_>>()
.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<f32>,
pub rows: Vec<Vec<Cell>>,
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<Block>,
pub header: Vec<Paragraph>,
pub footer: Vec<Paragraph>,
}
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(&paragraph.text()),
Block::Table(table) => {
for row in &table.rows {
let cells: Vec<String> = 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<Document> {
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),
}
}

File diff suppressed because it is too large Load diff

View file

@ -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<File>,
}
impl Package {
pub fn open(path: &Path) -> AppResult<Self> {
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<Vec<u8>> {
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<String> {
self.read(name)
.map(|bytes| String::from_utf8_lossy(&bytes).to_string())
}
pub fn names(&self) -> Vec<String> {
(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<String> {
node.attributes()
.find(|attribute| attribute.name() == name)
.map(|attribute| attribute.value().to_string())
}

File diff suppressed because it is too large Load diff

View file

@ -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<u32>);
pub struct PdfEngine;
impl PdfEngine {
fn load(path: &str) -> AppResult<Document> {
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<PathBuf> {
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<ObjectId> = 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<Object> = 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<ObjectId> {
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<ObjectId> {
// JPEG olarak kodla (DCTDecode ile doğrudan gömülür, sayfa boyutu küçük kalır)
let mut jpeg: Vec<u8> = 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<PathBuf> {
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<Object> = 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<PathBuf> {
let mut doc = Self::load(input_path)?;
let degrees = Self::normalize_rotation(degrees as i64);
let pages: Vec<ObjectId> = 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<Vec<PathBuf>> {
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<u32> = 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<ObjectId> = 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<ExtractedText> {
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<Vec<image::DynamicImage>> {
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<image::DynamicImage> {
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::<Vec<_>>()
.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<PathBuf> {
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<PathBuf> {
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<ObjectId> = 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<usize> {
let all_pages: Vec<usize> = (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<usize> = 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::<usize>(), end.trim().parse::<usize>())
{
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::<usize>() {
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<Object> {
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<usize> {
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<dyn std::error::Error>> {
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(())
}
}

View file

@ -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<u8>,
}
#[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<u8>, 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<u8> {
inject_corporate(pdf, placements, &[], &[])
}
pub fn inject_corporate(
pdf: &[u8],
placements: &[Placement],
links: &[LinkAnnotation],
outlines: &[OutlineEntry],
) -> Vec<u8> {
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<lopdf::ObjectId> = (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
}

Some files were not shown because too many files have changed in this diff Show more