diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8155c8c..cfbdd66 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,11 +34,16 @@ jobs: - name: Install OpenStitch Studio & test dependencies run: | python -m pip install --upgrade pip - pip install -e . - pip install pytest + pip install -e ".[dev]" - name: Run full test & binary embroidery verification suite env: QT_QPA_PLATFORM: offscreen run: | - pytest tests -v + pytest tests -v --durations=10 + + - name: Check the built-in test designs with the virtual stitch-out + env: + QT_QPA_PLATFORM: offscreen + run: | + python -m openstitch.analysis --corpus --formats diff --git a/.github/workflows/release_binaries.yml b/.github/workflows/release_binaries.yml index 63cee90..6f9699a 100644 --- a/.github/workflows/release_binaries.yml +++ b/.github/workflows/release_binaries.yml @@ -1,4 +1,4 @@ -name: Build Release Binaries (Windows & macOS M-Chip + Intel) +name: Build Release Binaries (Windows, macOS M-Chip + Intel, Linux) on: workflow_dispatch: @@ -10,6 +10,8 @@ on: push: tags: - 'v*' + pull_request: + branches: [ main ] permissions: contents: write @@ -35,6 +37,11 @@ jobs: arch: x64 python: "3.11" asset_name: OpenStitch-Studio-Windows-x64.exe + - name: Linux-x64 + os: ubuntu-22.04 + arch: x64 + python: "3.11" + asset_name: OpenStitch-Studio-Linux-x64.tar.gz runs-on: ${{ matrix.os }} @@ -49,6 +56,12 @@ jobs: architecture: ${{ matrix.arch }} cache: 'pip' + - name: Install Linux GUI libraries + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y libegl1 libgl1 libxkbcommon-x11-0 libxcb-cursor0 libdbus-1-3 + - name: Install dependencies & PyInstaller run: | python -m pip install --upgrade pip @@ -59,6 +72,7 @@ jobs: if: runner.os == 'macOS' run: | pyinstaller --noconfirm --windowed --name "OpenStitch Studio" \ + --osx-bundle-identifier org.openstitch.studio \ --exclude-module pytest --exclude-module tkinter --exclude-module matplotlib \ main.py cd dist @@ -70,12 +84,46 @@ jobs: run: | pyinstaller --noconfirm --onefile --windowed --name "OpenStitch-Studio-Windows-x64" --exclude-module pytest --exclude-module tkinter --exclude-module matplotlib main.py + - name: Build Linux single file + if: runner.os == 'Linux' + run: | + pyinstaller --noconfirm --onefile --windowed --name "OpenStitch-Studio" \ + --exclude-module pytest --exclude-module tkinter --exclude-module matplotlib \ + main.py + tar -C dist -czf "dist/${{ matrix.asset_name }}" OpenStitch-Studio + + - name: Self-test the packaged app + shell: bash + env: + QT_QPA_PLATFORM: offscreen + run: | + case "$RUNNER_OS" in + macOS) app="dist/OpenStitch Studio.app/Contents/MacOS/OpenStitch Studio" ;; + Linux) app="dist/OpenStitch-Studio" ;; + *) app="dist/OpenStitch-Studio-Windows-x64.exe" ;; + esac + rc=0 + "$app" --selftest || rc=$? + cat openstitch-selftest.txt || echo "no report written" + exit $rc + + - name: Keep the build for testing (pull requests) + if: github.event_name == 'pull_request' + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.asset_name }} + path: dist/${{ matrix.asset_name }} + retention-days: 7 + - name: Upload to GitHub Release + if: github.event_name != 'pull_request' env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} RELEASE_TAG: ${{ inputs.tag || github.ref_name }} run: | - if [ "${{ runner.os }}" = "macOS" ]; then + # Ein reiner Tag-Push ohne vorbereitete Notizen darf den Build nicht scheitern lassen + gh release view "$RELEASE_TAG" >/dev/null 2>&1 || gh release create "$RELEASE_TAG" --generate-notes || true + if [ "${{ runner.os }}" != "Windows" ]; then gh release upload "$RELEASE_TAG" "dist/${{ matrix.asset_name }}" --clobber else gh release upload "$RELEASE_TAG" "dist/OpenStitch-Studio-Windows-x64.exe" --clobber diff --git a/.github/workflows/stress.yml b/.github/workflows/stress.yml new file mode 100644 index 0000000..8e4daa0 --- /dev/null +++ b/.github/workflows/stress.yml @@ -0,0 +1,33 @@ +name: Stress tests + +# Lange Zufallstests, zu langsam für jeden Push +on: + workflow_dispatch: + schedule: + - cron: '0 3 * * 1' + +jobs: + stress: + runs-on: ubuntu-latest + timeout-minutes: 120 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: 'pip' + - name: Install + run: | + sudo apt-get update + sudo apt-get install -y libegl1 libgl1 libxkbcommon-x11-0 libxcb-cursor0 libdbus-1-3 + python -m pip install --upgrade pip + pip install -e ".[dev]" + - name: Fuzz, damaged files and monkey test + env: + QT_QPA_PLATFORM: offscreen + OPENSTITCH_FUZZ_RUNS: "400" + OPENSTITCH_BADFILE_ROUNDS: "200" + OPENSTITCH_MONKEY_STEPS: "1500" + OPENSTITCH_MONKEY_SEEDS: "1,2,3,4,5,6" + run: | + pytest tests/test_fuzz.py tests/test_bad_files.py tests/test_monkey.py -v diff --git a/.gitignore b/.gitignore index 7b79ede..ba864a7 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,6 @@ dist/ # Claude Code worktrees / local settings .claude/ + +# Zufallstests +.hypothesis/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e741d2..47346f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,47 @@ # Changelog +## v0.4.0 + +### Virtual stitch-out +- **Check design (`F7`) replaces the old Doctor.** You get a score out of 100, findings in plain language, a Show button that jumps to the spot and a Fix button where a one-click fix exists. +- **Fabric pull simulation.** A spring model shows how thread tension pulls the fabric in, with a preview you can exaggerate. Earlier objects move when later ones are stitched, so it can warn about gaps between a fill and its outline. Until you calibrate a fabric, this is an estimate. +- **Fixed rules and estimates are labelled.** Findings from the stitches are exact; only fabric pull is an estimate. +- **Calibration with real fabric.** Stitch a small test bar, measure it, enter the width. The simulation and pull compensation then use the measured value for that fabric. +- **Export check.** Every machine format is written, read back with an independent parser and compared stitch by stitch. +- **Command line:** `python -m openstitch.analysis design.dst --fabric jersey --formats`. + +### Stitch quality fixes found by the simulator +- **Satin density now works.** Spacing above about 0.4 mm had no effect, and needle holes along satin edges were uneven. +- Split satin no longer exceeds the maximum stitch length (it could by 17 %). +- The density guard can no longer turn repeated lines into 13 mm stitches, and it keeps lock stitches at run ends. +- Degenerate column lines can no longer throw stitches far off the shape. +- Hidden travel along a shape's edge no longer cuts across holes at the ring's start corner. +- **VP3 files with an accented thread name (such as Grün) were corrupted** and could not be read back. Thread names are now written in plain characters in all formats. +- Damaged project files give a clear message instead of crashing plan building. + +### New +- **Real fabric choice** (cotton, denim, cap, piqué, T-shirt, fleece, towel, leather, silk). It sets pull compensation and density, and tells you which stabilizer and needle to use. +- **Hidden stitches are skipped.** A fill no longer stitches under a later object that fully covers it, which saves stitches and avoids board-stiff spots. It keeps running 1 mm under the edge so no gaps open, and thin objects such as lettering keep their fill. +- **Send to machine.** Picks the right format for your machine, finds USB sticks, offers short names for older machines, lists the thread order, verifies the saved file and never overwrites silently. +- **Micro font tuned with a legibility measure.** `l` and `I` now differ, `A`, `e`, `4` have more open counters and `a` is easier to tell from `o`. From 3 mm every counter stays open; at 2.5 mm `e` and `4` are tight. +- Fixed: the text dialog refused heights under 4 mm, so 2.5 mm lettering could only be set afterwards. It now has a live preview and suggests the Micro font for small text. + +### Easier to use +- **Start page** with four clear ways in, sample designs and recent files. +- **The window fits a laptop.** It needed 2212 px of width and now fits 1280 px. +- **Light theme** next to the dark one, and a redesigned layout with a shorter toolbar. +- **One Open dialog** for projects, embroidery files, SVG and images. +- **Autosave with crash recovery**, and a crash report instead of a silent exit. +- **Five more languages:** Italian, Portuguese, Dutch, Polish and Turkish. These are machine translations, so corrections from native speakers are very welcome. +- The app starts in your system language, otherwise English. The tour is translated. +- Help menu: keyboard shortcuts, report a problem, about. +- Your machine choice is remembered. + +### Project +- Random shape tests, damaged file tests and a monkey test that clicks through the real window. Long versions run weekly. +- Linux download in releases. Every pull request now builds and self-tests the app on Windows, macOS (Apple Silicon and Intel) and Linux. +- The README explains how to open the unsigned app on a Mac. + ## v0.3.0 (2026-10-28) ### New diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 083c948..b71eec3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -46,3 +46,18 @@ Mit dem Einreichen eines Pull Requests oder Beitrags (Contribution) erklärst du 1. Du bestätigst, dass du der Urheber deines Beitrags bist und das Recht hast, ihn einzureichen. 2. Du räumst dem Projektgründer und Haupturheber **Linus Baumberger (`@lb2002`)** ein unwiderrufliches, weltweites, gebührenfreies, nicht-exklusives und unterlizenzierbares Recht ein, deinen Beitrag zusammen mit OpenStitch Studio sowohl unter der **GNU AGPL-3.0-or-later** als auch unter beliebigen anderen (einschließlich kommerziellen / proprietären Dual-Licensing-) Lizenzen zu nutzen, zu verändern und zu verbreiten. 3. Du behältst selbstverständlich das Urheberrecht an deinem eigenen Beitrag. + +## Testing your change + +```bash +pip install -e ".[dev]" +pytest tests -q +python -m openstitch.analysis --corpus --formats +``` + +The random tests get longer with `OPENSTITCH_FUZZ_RUNS`, `OPENSTITCH_MONKEY_STEPS`, `OPENSTITCH_MONKEY_SEEDS` and `OPENSTITCH_BADFILE_ROUNDS`. A long run happens every week in the Stress tests workflow. + +## Adding a language + +Copy `openstitch/locales/it.py`, translate the values, and add the language to `LANGUAGES` in `openstitch/i18n.py` and to `openstitch/locales/__init__.py`. A test checks that no text is missing and that placeholders such as `{count}` stayed the same. + diff --git a/README.de.md b/README.de.md index e0e60b9..96a800d 100644 --- a/README.de.md +++ b/README.de.md @@ -35,7 +35,7 @@ * Feine Konturen → **Dreifach-/Beanstich** * Schriften & Säulen → **Auto-Satinstich** mit fließend mitdrehendem Stichwinkel, Kurzstichen (Short-Stitches) in engen Innenkurven, Split-Satin bei breiten Säulen und automatischer Unterlage * Große Flächen → **Tatami-Füllstich** oder **gebogener Kontur-Füllstich (Contour Fill)** mit Boustrophedon-Abschnittszerlegung, unsichtbarem Travel-Routing entlang der Außenkante, Kanten-/Gitter-Unterlage und richtungsabhängiger Zugkompensation (Pull Compensation) -* **Color-Trap vs. Smart Knockdown + 0.7 mm Überlappungslinie:** Verhindert einerseits brettharte Doppellagen („Bulletproof Embroidery“) und andererseits weiße Stoffblitzer (Passerlücken) zwischen angrenzenden Farbflächen. +* **Verdecktes wird nicht gestickt:** Füllungen laufen nicht unter Objekten weiter, die sie ganz zudecken. Eine kleine Überlappung verhindert Lücken. * **Stoffprofile:** Standard (Baumwolle/Twill), Piqué/Polo/Strick, Frottee/Handtuch, Kappe/Cap, Leichter Stoff. * **Drag & Drop:** Ziehe Bilder (`.png`, `.jpg`, `.webp`), `.svg`-Vektorgrafiken oder Stickdateien direkt aus dem Explorer/Finder ins Programmfenster. @@ -51,10 +51,14 @@ ![OpenStitch Micro vs. TrueType bei 2.5 und 3 mm](./assets/micro_font_comparison.png) * **SVG-Vektor-Import** (Transformationen, Bögen, Stile, ``, Füllregeln) & **TTF/OTF-Schrift-Generator** (inkl. Bogentext & automatischer Satin/Tatami-Wahl). -### 3. 🩺 Stichdichte-Wächter, Heatmap & Qualitäts-Doktor (`F7`) -* **Automatischer Anti-Fadenbruch-Filter (`density_guard`):** Verhindert Nadelkollisionen, Fadennester („Birdnesting“) und Stofflöcher. -* **Live-Stichdichte-Heatmap:** Zeigt kritische Dichtestellen farbcodiert (Grün / Gelb / Rot) auf der Leinwand. -* **Qualitäts-Doktor (`F7`):** Prüft vor dem Export Rahmen-Sicherheitsabstand, Nadelanzahl, Kurzstich-Spitzen und Fadenschnitte. +### 3. 🧪 Virtueller Probestick (`F7`) +* **Design prüfen:** Punktzahl bis 100, Befunde in Klartext, **Zeigen** springt zur Stelle, **Beheben** löst es mit einem Klick, wo das möglich ist. +* **Feste Regeln und Schätzungen, klar getrennt:** Stichlängen, Rahmengrenzen, Fadenlagen, Vernähstiche und die exportierte Datei folgen exakt aus den Stichen. Nur der Stoffzug ist eine Schätzung. +* **Stoffzug-Simulation:** zeigt, wie der Faden den gewählten Stoff zusammenzieht und wo Kontur und Füllung auseinanderlaufen können. +* **Kalibrierung mit echtem Stoff:** Einen kleinen Testbalken sticken, die Breite messen und eintragen. Simulation und Zugausgleich rechnen dann für diesen Stoff mit deinem Messwert. +* **Maschinenregeln:** zu kurze und zu lange Stiche, lose Flottungen, fehlende Vernähstiche, Nadelhäufungen, zu viele Fadenlagen, Rahmenkollision. +* **Export-Prüfung:** Dateien werden mit einem unabhängigen Parser neu eingelesen und Stich für Stich verglichen. +* **Kommandozeile:** `python -m openstitch.analysis design.dst --fabric jersey --formats` ### 4. 🏭 Herstellerneutral & Alle wichtigen Maschinenformate * **Integrierte Maschinenprofile & Rahmen-Strategien:** @@ -78,6 +82,12 @@ Lade dir auf der **[GitHub Release-Seite (latest)](https://github.com/lb2002/ope * 🪟 **Windows (64-Bit Einzeldatei):** **[`OpenStitch-Studio-Windows-x64.exe`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-Windows-x64.exe)** *(einfach herunterladen & doppelklicken, kein Entpacken nötig!)* * 🍏 **macOS (Apple Silicon M1 / M2 / M3 / M4):** **[`OpenStitch-Studio-macOS-AppleSilicon-M-Chip-arm64.zip`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-macOS-AppleSilicon-M-Chip-arm64.zip)** *(`OpenStitch Studio.app`)* * 🍎 **macOS (Intel x64):** **[`OpenStitch-Studio-macOS-Intel-x64.zip`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-macOS-Intel-x64.zip)** *(`OpenStitch Studio.app`)* +* 🐧 **Linux (64-Bit):** **[`OpenStitch-Studio-Linux-x64.tar.gz`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-Linux-x64.tar.gz)** *(entpacken, dann `OpenStitch-Studio` starten)* + +> 🍏 **Öffnen auf dem Mac:** OpenStitch ist kostenlos und nicht mit einem bezahlten Apple-Zertifikat signiert, deshalb blockiert macOS es beim ersten Mal. Verschiebe die App nach *Programme*, versuche einmal sie zu öffnen, gehe dann zu *Systemeinstellungen → Datenschutz & Sicherheit* und klicke **Trotzdem öffnen**. Meldet macOS, die App sei beschädigt, führe einmal im Terminal aus: +> ```bash +> xattr -cr "/Applications/OpenStitch Studio.app" +> ``` --- diff --git a/README.es.md b/README.es.md index 7fff0fd..b4bdfe4 100644 --- a/README.es.md +++ b/README.es.md @@ -22,7 +22,8 @@ * 🪄 **Auto-Digitalizador (imagen / logotipo → archivo de bordado):** reducción de color en CIE-Lab, correspondencia con catálogos reales (**Madeira Polyneon 40, Isacord 40, Gunold Poly 40, Brother**), eliminación automática del fondo, detección del tipo de puntada (pespunte triple, **satén automático**, **tatami** / relleno de contorno), compensación de tirantez, entretela y solape de 0,7 mm entre colores. * 🎨 **Digitalización manual:** herramientas Tatami (`F`), Satén (`S`), Pespunte (`R`), editor de nodos (`N`), inspector paramétrico en vivo, columnas de satén a lo largo de la línea central dibujada, fuente de bordado **OpenStitch Micro** legible desde 2,5 mm, texto TTF/OTF con arco, importación SVG y arrastrar y soltar. * 🧵 **Herramientas pro:** modo espuma 3D (gorras), **aplique en 1 clic**, **PhotoStitch** (foto → bordado monocromo, sepia o CMYK). -* 🩺 **Control de calidad:** filtro anti-rotura de hilo, mapa de densidad en vivo, **doctor de calidad (`F7`)** y **verificación binaria** de cada archivo exportado. +* 🧪 **Prueba de bordado virtual (`F7`):** nota sobre 100, avisos en lenguaje claro con botones **Mostrar** y **Corregir**, simulación del tiro de la tela y relectura de cada archivo exportado. Es un modelo basado en reglas prácticas y no sustituye a una prueba real. +* 🧶 **Elección de tela:** algodón, vaquero, gorra, piqué, camiseta, polar, rizo, cuero, seda. La densidad y la compensación se ajustan, y se indican el estabilizador y la aguja. * 🏭 **Neutral respecto a fabricantes:** DST, PES, EXP, JEF, VP3, U01; perfiles para Tajima, Brother, Barudan, Ricoma/ZSK, Janome/Bernina, Pfaff/Husqvarna y Melco (gestor de disquete FAT12 `.IMG` incluido). * 🌍 **4 idiomas** conmutables al instante: 🇬🇧 🇩🇪 🇫🇷 🇪🇸. * 📄 **Hoja de producción PDF A4:** agujas, consumo de hilo, número de puntadas y tiempo estimado. @@ -36,6 +37,12 @@ Desde la **[página de releases (latest)](https://github.com/lb2002/openstitch/r * 🪟 **Windows (64 bits, archivo único):** [`OpenStitch-Studio-Windows-x64.exe`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-Windows-x64.exe) * 🍏 **macOS (Apple Silicon M1–M4):** [`OpenStitch-Studio-macOS-AppleSilicon-M-Chip-arm64.zip`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-macOS-AppleSilicon-M-Chip-arm64.zip) * 🍎 **macOS (Intel x64):** [`OpenStitch-Studio-macOS-Intel-x64.zip`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-macOS-Intel-x64.zip) +* 🐧 **Linux (64 bits):** **[`OpenStitch-Studio-Linux-x64.tar.gz`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-Linux-x64.tar.gz)** *(descomprime y ejecuta `OpenStitch-Studio`)* + +> 🍏 **Abrir en Mac:** OpenStitch es gratuito y no está firmado con un certificado de pago de Apple, por lo que macOS lo bloquea la primera vez. Mueve la app a *Aplicaciones*, intenta abrirla una vez, ve a *Ajustes del Sistema → Privacidad y seguridad* y pulsa **Abrir igualmente**. Si macOS dice que la app está dañada, ejecuta una vez en Terminal: +> ```bash +> xattr -cr "/Applications/OpenStitch Studio.app" +> ``` ### Opción B: desde el código fuente Requiere **Python 3.10+**. diff --git a/README.fr.md b/README.fr.md index 561fed1..4bfdd8e 100644 --- a/README.fr.md +++ b/README.fr.md @@ -22,7 +22,8 @@ * 🪄 **Auto-Numériseur (image / logo → fichier de broderie) :** réduction des couleurs en CIE-Lab, correspondance avec de vrais nuanciers (**Madeira Polyneon 40, Isacord 40, Gunold Poly 40, Brother**), suppression automatique du fond, détection du type de point (point droit triple, **satin automatique**, **tatami** / remplissage de contour), compensation de tirage, sous-couche et recouvrement de 0,7 mm entre couleurs. * 🎨 **Numérisation manuelle :** outils Tatami (`F`), Satin (`S`), Point droit (`R`), éditeur de nœuds (`N`), inspecteur paramétrique en direct, colonnes satin le long de la ligne centrale dessinée, police de broderie **OpenStitch Micro** lisible dès 2,5 mm, lettrage TTF/OTF avec texte en arc, import SVG, glisser-déposer. * 🧵 **Outils pro :** mode mousse 3D (casquettes), **appliqué en 1 clic**, **PhotoStitch** (photo → broderie monochrome, sépia ou CMJN). -* 🩺 **Contrôle qualité :** filtre anti-casse de fil, carte de densité en direct, **docteur qualité (`F7`)** et **vérification binaire** de chaque fichier exporté. +* 🧪 **Essai de broderie virtuel (`F7`) :** note sur 100, constats en langage clair avec boutons **Afficher** et **Corriger**, simulation de la traction du tissu et relecture de chaque fichier exporté. C'est un modèle fondé sur des règles empiriques, il ne remplace pas un essai réel. +* 🧶 **Choix du tissu :** coton, denim, casquette, piqué, t-shirt, polaire, éponge, cuir, soie. Densité et compensation s'adaptent, et le stabilisateur et l'aiguille sont indiqués. * 🏭 **Neutre vis-à-vis des fabricants :** DST, PES, EXP, JEF, VP3, U01 ; profils pour Tajima, Brother, Barudan, Ricoma/ZSK, Janome/Bernina, Pfaff/Husqvarna et Melco (gestionnaire de disquette FAT12 `.IMG` inclus). * 🌍 **4 langues** commutables à chaud : 🇬🇧 🇩🇪 🇫🇷 🇪🇸. * 📄 **Fiche de production PDF A4** : aiguilles, consommation de fil, nombre de points, durée estimée. @@ -36,6 +37,12 @@ Depuis la **[page des releases (latest)](https://github.com/lb2002/openstitch/re * 🪟 **Windows (64 bits, fichier unique) :** [`OpenStitch-Studio-Windows-x64.exe`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-Windows-x64.exe) * 🍏 **macOS (Apple Silicon M1–M4) :** [`OpenStitch-Studio-macOS-AppleSilicon-M-Chip-arm64.zip`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-macOS-AppleSilicon-M-Chip-arm64.zip) * 🍎 **macOS (Intel x64) :** [`OpenStitch-Studio-macOS-Intel-x64.zip`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-macOS-Intel-x64.zip) +* 🐧 **Linux (64 bits) :** **[`OpenStitch-Studio-Linux-x64.tar.gz`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-Linux-x64.tar.gz)** *(décompressez, puis lancez `OpenStitch-Studio`)* + +> 🍏 **Ouverture sur Mac :** OpenStitch est gratuit et n'est pas signé avec un certificat Apple payant, macOS le bloque donc la première fois. Déplacez l'app dans *Applications*, essayez de l'ouvrir une fois, puis allez dans *Réglages Système → Confidentialité et sécurité* et cliquez sur **Ouvrir quand même**. Si macOS indique que l'app est endommagée, exécutez une fois dans le Terminal : +> ```bash +> xattr -cr "/Applications/OpenStitch Studio.app" +> ``` ### Option B : depuis les sources Nécessite **Python 3.10+**. diff --git a/README.md b/README.md index 0a4e53b..65581ca 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,8 @@ ![OpenStitch Studio — Dark Studio Interface](./assets/screenshot_studio.png) +
Start pageDesign check with fabric preview
+
🔍 Preview: interactive in-app studio tour (spotlight & coach marks)
@@ -35,8 +37,8 @@ * thin lines → **triple / bean run** * lettering & columns → **auto satin** with smoothly rotating stitch angle, short-stitching on tight inner curves, split satin for wide columns and automatic underlay * large areas → **tatami fill** or curved **contour fill** with boustrophedon region splitting, hidden travel routing along the outline, edge/lattice underlay and directional pull compensation -* **Colour trap vs. smart knockdown + 0.7 mm overlap lip:** avoids bullet-proof stacking while eliminating fabric gaps between adjacent colours. -* **Fabric presets:** standard, piqué/polo/knit, terry/towel, caps, lightweight. +* **Hidden stitches are skipped:** fills do not stitch under objects that fully cover them, while a small overlap keeps gaps from opening. +* **Real fabric choice:** cotton, denim, cap, piqué, T-shirt, fleece, towel, leather, silk. It sets density and pull compensation, and tells you which stabilizer and needle to use. * **Drag & drop:** drop images (`.png`, `.jpg`, `.webp`), `.svg` vectors or embroidery files straight onto the window. ### 2. 🎨 Manual digitizing, node editor & pro tools @@ -51,14 +53,17 @@ ![OpenStitch Micro vs. TrueType at 2.5 and 3 mm](./assets/micro_font_comparison.png) * **SVG import** (transforms, arcs, styles, ``, fill rules) & **TTF/OTF lettering** (arc text, automatic satin/tatami choice). -### 3. 🩺 Density guard, heatmap & quality doctor (`F7`) -* **Anti-thread-break filter** prevents needle collisions, bird-nesting and fabric holes. -* **Live stitch-density heatmap** (green / yellow / red). -* **Quality doctor:** checks hoop clearance, needle count, micro-stitches and trims before export. -* **Binary verification on export:** every exported file is re-read by an independent parser and checked for size and geometry. +### 3. 🧪 Virtual stitch-out (`F7`) +* **Check design:** a score out of 100, findings in plain language, a **Show** button that jumps to the spot and a **Fix** button where one click solves it. +* **Fixed rules and estimates, clearly labelled:** stitch lengths, hoop limits, thread layers, lock stitches and the exported file follow exactly from the stitches. Only fabric pull is an estimate. +* **Fabric pull simulation:** see how thread tension pulls your chosen fabric in, and where outline and fill may no longer meet. +* **Calibration with real fabric:** stitch one small test bar, measure its width and enter it. The simulation and pull compensation then use your measured value for that fabric. +* **Machine rules:** stitches too short or too long, loose floats, missing lock stitches, needle pile-ups, too many thread layers, hoop collisions. +* **Export check:** files are read back with an independent parser and compared stitch by stitch. +* **Command line:** `python -m openstitch.analysis design.dst --fabric jersey --formats` ### 4. 🌍 Languages & real thread catalogs -* **UI languages:** 🇬🇧 English · 🇩🇪 Deutsch · 🇫🇷 Français · 🇪🇸 Español — switch live at the top of the window. +* **UI languages:** 🇬🇧 English · 🇩🇪 Deutsch · 🇫🇷 Français · 🇪🇸 Español · 🇮🇹 Italiano · 🇵🇹 Português · 🇳🇱 Nederlands · 🇵🇱 Polski · 🇹🇷 Türkçe — the app starts in your system language; switch any time at the bottom right. * **Thread catalogs with official colour numbers:** Madeira Polyneon No. 40, Isacord Polyester No. 40, Gunold POLY 40, Brother Embroidery and a universal palette; custom CSV palettes can be loaded too. ### 5. 🏭 Manufacturer-neutral & all major machine formats @@ -68,6 +73,19 @@ --- +## 🔬 How it is tested + +Nothing here has been proven on every real machine yet, so the project tests as much as it can without one: + +* **Virtual stitch-out:** machine rules, fabric pull and coverage on a set of 34 test designs (`python -m openstitch.analysis --corpus --formats`). +* **Export round trip:** every machine format is written, re-read by an independent parser and compared stitch by stitch. +* **Random shape tests:** thousands of odd shapes must never crash the engine or put stitches outside the shape. +* **Damaged files:** broken embroidery, project, SVG and floppy files must fail cleanly. +* **Monkey test:** thousands of random clicks and keys on the real window. +* **Every setting must have an effect:** this found that satin density did nothing above about 0.4 mm. + +Test stitch-outs on real machines are still the most useful contribution you can make. + ## 🚀 Quickstart & Installation ### Option A: 1-click download (no Python required) @@ -75,6 +93,12 @@ Get the ready-made app from the **[GitHub release page (latest)](https://github. * 🪟 **Windows (64-bit, single file):** [`OpenStitch-Studio-Windows-x64.exe`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-Windows-x64.exe) *(download & double-click, nothing to unpack)* * 🍏 **macOS (Apple Silicon M1 / M2 / M3 / M4):** [`OpenStitch-Studio-macOS-AppleSilicon-M-Chip-arm64.zip`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-macOS-AppleSilicon-M-Chip-arm64.zip) * 🍎 **macOS (Intel x64):** [`OpenStitch-Studio-macOS-Intel-x64.zip`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-macOS-Intel-x64.zip) +* 🐧 **Linux (64-bit):** **[`OpenStitch-Studio-Linux-x64.tar.gz`](https://github.com/lb2002/openstitch/releases/latest/download/OpenStitch-Studio-Linux-x64.tar.gz)** *(unpack, then run `OpenStitch-Studio`)* + +> 🍏 **Opening on a Mac:** OpenStitch is free and not signed with a paid Apple certificate, so macOS blocks it the first time. Move the app to *Applications*, try to open it once, then go to *System Settings → Privacy & Security* and click **Open Anyway**. If macOS says the app is damaged, run this once in Terminal: +> ```bash +> xattr -cr "/Applications/OpenStitch Studio.app" +> ``` ### Option B: run from source (Windows, macOS & Linux) Requires **Python 3.10+**. diff --git a/assets/screenshot_check.png b/assets/screenshot_check.png new file mode 100644 index 0000000..3c42531 Binary files /dev/null and b/assets/screenshot_check.png differ diff --git a/assets/screenshot_start.png b/assets/screenshot_start.png new file mode 100644 index 0000000..acef511 Binary files /dev/null and b/assets/screenshot_start.png differ diff --git a/assets/screenshot_studio.png b/assets/screenshot_studio.png index dfdae8b..a9c9a34 100644 Binary files a/assets/screenshot_studio.png and b/assets/screenshot_studio.png differ diff --git a/assets/screenshot_tour.png b/assets/screenshot_tour.png index b3d20cb..abf32da 100644 Binary files a/assets/screenshot_tour.png and b/assets/screenshot_tour.png differ diff --git a/openstitch/__init__.py b/openstitch/__init__.py index 9891e2f..776f19d 100644 --- a/openstitch/__init__.py +++ b/openstitch/__init__.py @@ -1,6 +1,6 @@ """OpenStitch Studio – Universal Open-Source Embroidery & Digitizing Suite.""" -__version__ = "0.3.0" +__version__ = "0.4.0" __author__ = "Linus Baumberger (@lb2002)" __license__ = "AGPL-3.0-or-later" APP_NAME = "OpenStitch" diff --git a/openstitch/__main__.py b/openstitch/__main__.py index 9558f0c..dbb41e9 100644 --- a/openstitch/__main__.py +++ b/openstitch/__main__.py @@ -1,6 +1,7 @@ """Sofortiger Splash-Screen & schneller Startpunkt für OpenStitch.""" from __future__ import annotations +import os import sys from PySide6.QtCore import QRectF, Qt, QTimer @@ -59,6 +60,11 @@ def _create_splash_pixmap() -> QPixmap: def main(): + if "--selftest" in sys.argv: + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + app = QApplication(sys.argv) # noqa: F841 - Bild- und Schriftfunktionen brauchen die Instanz + from .selftest import run + sys.exit(run()) app = QApplication(sys.argv) app.setApplicationName(APP_NAME) @@ -74,6 +80,7 @@ def main(): app.processEvents() # 2. Erst jetzt die Hauptmodule importieren + from .ui.crash import install as install_crash_handler from .ui.main_window import MainWindow splash.showMessage( @@ -84,11 +91,12 @@ def main(): app.processEvents() win = MainWindow(defer_starter=True) + install_crash_handler(win) win.show() app.processEvents() def _finish_startup(): - win._load_starter_design() + win.startup() splash.finish(win) win.setWindowState((win.windowState() & ~Qt.WindowMinimized) | Qt.WindowActive) win.raise_() diff --git a/openstitch/analysis/__init__.py b/openstitch/analysis/__init__.py new file mode 100644 index 0000000..5136090 --- /dev/null +++ b/openstitch/analysis/__init__.py @@ -0,0 +1,15 @@ +"""Virtueller Probestick: prüft einen Stichplan, ohne eine Maschine zu benötigen. + +- `checks`: Maschinen- und Nadelregeln (Kurzstiche, lange Flottungen, Vernähen, Nadelhäufung, Dichte) +- `pull`: Stoffverzug als Federgitter (Zug des Fadens, Passgenauigkeit zwischen Objekten) +- `coverage`: deckt der Faden die Fläche? +- `roundtrip`: Export → unabhängig wieder einlesen → Stich für Stich vergleichen +- `legibility`: bleibt Schrift bei kleiner Höhe lesbar? + +Die Physik ist ein Modell mit Erfahrungswerten: Es zeigt verlässlich Trends und Problemstellen, +ersetzt aber keinen echten Probestick. +""" +from ..core.fabric import DEFAULT_FABRIC, FABRICS, Fabric, fabric_by_id +from .report import Finding, Report, simulate_stitchout + +__all__ = ["DEFAULT_FABRIC", "FABRICS", "Fabric", "Finding", "Report", "fabric_by_id", "simulate_stitchout"] diff --git a/openstitch/analysis/__main__.py b/openstitch/analysis/__main__.py new file mode 100644 index 0000000..388a547 --- /dev/null +++ b/openstitch/analysis/__main__.py @@ -0,0 +1,78 @@ +"""Virtueller Probestick auf der Kommandozeile. + + python -m openstitch.analysis datei.dst [--fabric jersey] [--needles 1] [--image bericht.png] + python -m openstitch.analysis --corpus + +Beendet sich mit Code 1, wenn ein Fehler gefunden wurde (nützlich in Skripten und CI).""" +from __future__ import annotations + +import argparse +import os +import sys + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + + +def _load(path: str): + from ..engine.pro_tools import import_svg + from ..io.formats import import_file + from ..io.project import load_project + ext = os.path.splitext(path)[1].lower() + if ext == ".ostitch": + return load_project(path) + if ext == ".svg": + return import_svg(path) + return import_file(path) + + +def _print_report(name: str, design, fabric, needles, formats: bool) -> bool: + from ..analysis import simulate_stitchout + from ..analysis.roundtrip import check_all + plan = design.build_plan() + r = simulate_stitchout(design, plan, fabric, needles=needles) + m = r.metrics + print(f"{name}: score {r.score}/100, {plan.stitch_count} stitches, {len(plan.blocks)} colors, " + f"{plan.trim_count} trims, about {plan.estimated_minutes():.0f} min") + if r.pull is not None: + print(f" fabric pull: {m['p95_shift']:.2f} mm typical, {m['max_shift']:.2f} mm max, " + f"misregistration {m['misregistration']:.2f} mm; peak {m['peak_layers']:.1f} thread layers") + for f in r.findings: + where = f" near {f.where[0][0]:.1f}, {f.where[0][1]:.1f} mm" if f.where else "" + extra = {k: (round(v, 2) if isinstance(v, float) else v) for k, v in f.data.items()} + print(f" [{f.severity}] {f.code} x{f.count}{where} {extra if extra else ''}".rstrip()) + ok = r.ok + if formats: + for rt in check_all(plan): + state = "ok" if rt.ok else "FAIL " + "; ".join(rt.problems) + print(f" {rt.ext:4} {rt.bytes:8} bytes, max error {rt.max_error_mm:.2f} mm: {state}") + ok = ok and rt.ok + return ok + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(prog="python -m openstitch.analysis", description="Virtual stitch-out for embroidery designs") + ap.add_argument("file", nargs="?", help="project, embroidery file or SVG") + ap.add_argument("--fabric", help="woven, denim, twill_cap, pique, jersey, fleece, towel, leather, silk") + ap.add_argument("--needles", type=int, help="needles on your machine") + ap.add_argument("--formats", action="store_true", help="also test export to every machine format") + ap.add_argument("--corpus", action="store_true", help="check the built-in test designs") + args = ap.parse_args(argv) + if not args.file and not args.corpus: + ap.error("give a file or --corpus") + + from PySide6.QtCore import QCoreApplication + app = QCoreApplication.instance() or QCoreApplication(sys.argv) # noqa: F841 - Qt braucht eine Instanz + from ..core.fabric import fabric_by_id + fabric = fabric_by_id(args.fabric) if args.fabric else None + ok = True + if args.corpus: + from . import corpus + for name in corpus.designs(): + ok = _print_report(name, corpus.build(name), fabric, args.needles, args.formats) and ok + else: + ok = _print_report(os.path.basename(args.file), _load(args.file), fabric, args.needles, args.formats) + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/openstitch/analysis/calibrate.py b/openstitch/analysis/calibrate.py new file mode 100644 index 0000000..49c20eb --- /dev/null +++ b/openstitch/analysis/calibrate.py @@ -0,0 +1,50 @@ +"""Vom Schätzwert zum Messwert: Testfleck sticken, ausmessen, Stoffzug daran anpassen. + +Der Fadenzug hängt von Stoff, Vlies, Spannung und Maschine ab, das lässt sich nicht aus Tabellen +ablesen. Wie weit sich aber eine Satinsäule ohne Zugkompensation zusammenzieht, misst man in einer +Minute mit Lineal oder Messschieber. Aus diesem einen Wert wird der Faktor für Simulation und +Zugkompensation dieses Stoffs.""" +from __future__ import annotations + +import numpy as np +from shapely.geometry import LineString + +from ..core.design import Design, SatinObject +from ..core.fabric import Fabric, fabric_by_id, pull_scale +from ..core.stitchplan import Thread +from .pull import simulate_pull +from .stitches import Trace + +BAR_WIDTH = 5.0 +BAR_LENGTH = 40.0 +SCALE_MIN, SCALE_MAX = 0.1, 4.0 + + +def calibration_design(fabric_id: str) -> Design: + """Satinbalken ohne Zugkompensation: Seine Breite zeigt den Einzug ohne jede Korrektur.""" + bar = LineString([(-BAR_LENGTH / 2, 0), (BAR_LENGTH / 2, 0)]).buffer(BAR_WIDTH / 2, cap_style=2) + return Design(name="Calibration", fabric=fabric_id, + objects=[SatinObject(Thread((30, 30, 30), "Black"), name="Measure this bar", geom=bar, pull_comp=0.0)]) + + +def predicted_shrink(fabric: Fabric) -> float: + """Einzug des Balkens in mm laut Modell (ohne Kalibrierung).""" + plan = calibration_design(fabric.id).build_plan() + t = Trace.of(plan) + pull = simulate_pull(t, fabric, scale=1.0) + x, y = t.x[pull.idx], t.y[pull.idx] + mid = np.abs(x) < BAR_LENGTH / 4 + before = np.percentile(y[mid], 99) - np.percentile(y[mid], 1) + moved = y[mid] + pull.dy[mid] + return float(before - (np.percentile(moved, 99) - np.percentile(moved, 1))) + + +def fit_scale(fabric_id: str, measured_width_mm: float) -> float: + """Faktor, mit dem das Modell den gemessenen Einzug trifft.""" + fabric = fabric_by_id(fabric_id) + shrink = BAR_WIDTH - measured_width_mm + return min(max(shrink / max(predicted_shrink(fabric), 1e-3), SCALE_MIN), SCALE_MAX) + + +def is_measured(fabric_id: str) -> bool: + return pull_scale(fabric_id) != 1.0 diff --git a/openstitch/analysis/checks.py b/openstitch/analysis/checks.py new file mode 100644 index 0000000..3a0a64e --- /dev/null +++ b/openstitch/analysis/checks.py @@ -0,0 +1,123 @@ +"""Maschinen- und Nadelregeln: alles, was sich direkt aus den Stichen ablesen lässt.""" +from __future__ import annotations + +import numpy as np + +from ..core.stitchplan import Cmd +from .stitches import Trace, layers_map + +THREAD_W = 0.27 # mm, wirksame Breite von Stickgarn No. 40 (flach aufliegend) +SHORT_STITCH = 0.30 # darunter trifft die Nadel praktisch dasselbe Loch +FLOAT_WARN = 7.5 # längere Stiche bleiben leicht hängen und liegen lose auf +PILEUP_CELL = 0.25 # mm +PILEUP_LIMIT = 7 # Einstiche in einer Zelle: darüber wird der Stoff perforiert +MIN_RUN = 3 # kürzere Läufe halten nach dem Schnitt nicht + + +def _spots(xy: np.ndarray, limit: int = 12) -> list[tuple[float, float]]: + """Wenige repräsentative Positionen (Fehler liegen oft gehäuft dicht beieinander).""" + out: list[tuple[float, float]] = [] + for x, y in xy: + if all(abs(x - a) + abs(y - b) > 3.0 for a, b in out): + out.append((float(x), float(y))) + if len(out) >= limit: + break + return out + + +def check_stitch_lengths(t: Trace, max_stitch: float) -> list[dict]: + seg, _ = t.sewn_segments() + if len(seg) == 0: + return [] + length = np.hypot(seg[:, 2] - seg[:, 0], seg[:, 3] - seg[:, 1]) + out: list[dict] = [] + short = (length < SHORT_STITCH) & (length > 0.0) + if short.any(): + out.append({"code": "short_stitch", "severity": "warning" if short.mean() > 0.002 else "info", + "count": int(short.sum()), "share": float(short.mean()), + "where": _spots(seg[short, 2:4])}) + too_long = length > max_stitch + 0.05 + if too_long.any(): + out.append({"code": "over_max_stitch", "severity": "error", "count": int(too_long.sum()), + "max_mm": float(length.max()), "where": _spots(seg[too_long, 2:4])}) + floats = (length > FLOAT_WARN) & ~too_long + if floats.any(): + out.append({"code": "long_float", "severity": "warning", "count": int(floats.sum()), + "max_mm": float(length[floats].max()), "where": _spots(seg[floats, 2:4])}) + return out + + +def _has_lock(x: np.ndarray, y: np.ndarray) -> bool: + """Vernähung: die ersten Stiche laufen auf engem Raum vor und zurück.""" + if len(x) < 4: + return False + if max(np.ptp(x[:4]), np.ptp(y[:4])) < 1.5: + return True + # Rückkehr nahe an den Anfang wirkt auch mit grösserem Stich wie ein Knoten + return bool(np.hypot(x[2:4] - x[0], y[2:4] - y[0]).min() < 0.35) + + +def check_runs(t: Trace) -> list[dict]: + out: list[dict] = [] + loose, orphans = [], [] + for r in t.runs(): + x, y = t.x[r], t.y[r] + if len(r) - 1 < MIN_RUN: + orphans.append((x[0], y[0])) + continue + if not _has_lock(x, y): + loose.append((x[0], y[0])) + if not _has_lock(x[::-1], y[::-1]): + loose.append((x[-1], y[-1])) + if loose: + out.append({"code": "no_lock", "severity": "warning", "count": len(loose), + "where": _spots(np.array(loose))}) + if orphans: + out.append({"code": "orphan_run", "severity": "warning", "count": len(orphans), + "where": _spots(np.array(orphans))}) + # Sprünge ohne Schnitt legen einen Faden quer über das Motiv + untrimmed = [] + for i in np.nonzero(t.cmd == Cmd.JUMP)[0]: + p = i - 1 + if p >= 0 and t.cmd[p] == Cmd.STITCH and t.block[p] == t.block[i]: + if float(np.hypot(t.x[i] - t.x[p], t.y[i] - t.y[p])) > 2.0: + untrimmed.append((t.x[i], t.y[i])) + if untrimmed: + out.append({"code": "untrimmed_jump", "severity": "warning", "count": len(untrimmed), + "where": _spots(np.array(untrimmed))}) + return out + + +def check_needle_pileup(t: Trace) -> list[dict]: + m = t.cmd == Cmd.STITCH + if not m.any(): + return [] + ix = np.floor(t.x[m] / PILEUP_CELL).astype(np.int64) + iy = np.floor(t.y[m] / PILEUP_CELL).astype(np.int64) + uniq, inv, cnt = np.unique(ix * 1_000_003 + iy, return_inverse=True, return_counts=True) + hot = cnt > PILEUP_LIMIT + if not hot.any(): + return [] + mask = hot[inv] + return [{"code": "needle_pileup", "severity": "warning", "count": int(hot.sum()), "max_hits": int(cnt.max()), + "where": _spots(np.column_stack((t.x[m][mask], t.y[m][mask])))}] + + +def check_density(t: Trace, max_layers: float) -> tuple[list[dict], float]: + seg, _ = t.sewn_segments() + if len(seg) == 0: + return [], 0.0 + cell = 1.0 + x0, y0 = seg[:, [0, 2]].min() - 1, seg[:, [1, 3]].min() - 1 + w = int(np.ceil((seg[:, [0, 2]].max() - x0) / cell)) + 2 + h = int(np.ceil((seg[:, [1, 3]].max() - y0) / cell)) + 2 + grid = layers_map(seg, x0, y0, w, h, cell, THREAD_W) + peak = float(grid.max()) + over = grid > max_layers + if not over.any(): + return [], peak + ys, xs = np.nonzero(over) + pts = np.column_stack((x0 + (xs + 0.5) * cell, y0 + (ys + 0.5) * cell)) + sev = "error" if peak > max_layers * 1.6 and over.sum() >= 30 else "warning" + return [{"code": "too_dense", "severity": sev, "count": int(over.sum()), "peak": peak, + "limit": max_layers, "where": _spots(pts)}], peak diff --git a/openstitch/analysis/corpus.py b/openstitch/analysis/corpus.py new file mode 100644 index 0000000..f075c7f --- /dev/null +++ b/openstitch/analysis/corpus.py @@ -0,0 +1,118 @@ +"""Testsammlung: typische und bösartige Designs für Simulator, Tests und Bewertung.""" +from __future__ import annotations + +import math + +import numpy as np +from shapely.geometry import LineString, MultiPolygon, Point, Polygon, box + +from ..auto.digitize import AutoParams, auto_digitize +from ..core.design import ColumnObject, Design, FillObject, HOOPS, RunObject, SatinObject +from ..core.stitchplan import Thread +from ..text import TextObject + +RED = Thread((200, 30, 30), "Rot") +BLUE = Thread((30, 70, 200), "Blau") +GREEN = Thread((30, 150, 70), "Grün") +GOLD = Thread((235, 180, 30), "Gold") +WHITE = Thread((245, 245, 245), "Weiss") +BLACK = Thread((25, 25, 25), "Schwarz") + + +def _star(r1=30.0, r2=12.0, n=5): + pts = [] + for i in range(2 * n): + r = r1 if i % 2 == 0 else r2 + a = math.pi * i / n - math.pi / 2 + pts.append((r * math.cos(a), r * math.sin(a))) + return Polygon(pts) + + +def _d(*objs, hoop=None, name="corpus") -> Design: + d = Design(name=name, objects=list(objs)) + if hoop is not None: + d.hoop = hoop + return d + + +def _sine(a=10.0, length=60.0, n=60): + return LineString([(-length / 2 + length * i / n, a * math.sin(i / n * 2 * math.pi)) for i in range(n + 1)]) + + +def _image_blobs(size=240): + import cv2 + img = np.full((size, size, 4), 255, np.uint8) + cv2.circle(img, (80, 90), 55, (220, 40, 40, 255), -1) + cv2.rectangle(img, (120, 120), (215, 210), (20, 80, 200, 255), -1) + cv2.ellipse(img, (70, 180), (50, 28), 25, 0, 360, (60, 170, 30, 255), -1) + return img + + +def _image_logo(size=300): + import cv2 + img = np.full((size, size, 4), 255, np.uint8) + cv2.circle(img, (150, 150), 130, (20, 40, 120, 255), 12) + cv2.putText(img, "OS", (60, 195), cv2.FONT_HERSHEY_DUPLEX, 4.0, (200, 20, 20, 255), 14, cv2.LINE_AA) + return img + + +def _auto(img, width=80.0, colors=5) -> Design: + return auto_digitize(img, AutoParams(width_mm=width, colors=colors)).design + + +def designs() -> dict[str, callable]: + """Name → Fabrik (Fabriken, weil Bilder und Schriften erst bei Bedarf erzeugt werden sollen).""" + return { + "fill_circle": lambda: _d(FillObject(RED, geom=Point(0, 0).buffer(30), angle=30)), + "fill_large": lambda: _d(FillObject(BLUE, geom=box(-55, -55, 55, 55), angle=45), hoop=HOOPS[4]), + "fill_star": lambda: _d(FillObject(GREEN, geom=_star(), angle=10)), + "fill_donut": lambda: _d(FillObject(RED, geom=Point(0, 0).buffer(30).difference(Point(0, 0).buffer(14)))), + "fill_c_shape": lambda: _d(FillObject(BLUE, geom=box(-25, -25, 25, 25).difference(box(-10, -12, 30, 12)))), + "fill_islands": lambda: _d(FillObject(GOLD, geom=MultiPolygon( + [Point(-25, 0).buffer(10), Point(0, 18).buffer(8), Point(22, -5).buffer(12)]))), + "fill_sliver": lambda: _d(FillObject(RED, geom=Polygon([(-30, 0), (30, -0.8), (30, 0.8)]))), + "fill_tiny": lambda: _d(FillObject(RED, geom=Point(0, 0).buffer(1.2))), + "fill_no_underlay": lambda: _d(FillObject(RED, geom=box(-20, -15, 20, 15), underlay=False)), + "fill_patterns": lambda: _d(*[FillObject(c, geom=box(x, -14, x + 24, 14), pattern=p) + for x, c, p in ((-44, RED, "diagonal"), (-14, BLUE, "ziegel"), + (16, GREEN, "wellen"))]), + "fill_contour": lambda: _d(FillObject(GOLD, geom=Point(0, 0).buffer(25), pattern="kontur")), + "satin_straight": lambda: _d(SatinObject(RED, geom=LineString([(-30, 0), (30, 0)]).buffer(2.0, cap_style=2))), + "satin_curve": lambda: _d(SatinObject(BLUE, geom=_sine().buffer(2.5))), + "satin_thin": lambda: _d(SatinObject(GREEN, geom=_sine().buffer(0.6))), + "satin_wide": lambda: _d(SatinObject(GOLD, geom=LineString([(-30, 0), (30, 0)]).buffer(6.5, cap_style=2))), + "satin_ring": lambda: _d(SatinObject(RED, geom=Point(0, 0).buffer(30).difference(Point(0, 0).buffer(25)))), + "satin_cross": lambda: _d(SatinObject(BLUE, geom=LineString([(-25, 0), (25, 0)]).buffer(2.5, cap_style=2).union( + LineString([(0, -25), (0, 25)]).buffer(2.5, cap_style=2)))), + "column_arc": lambda: _d(ColumnObject(RED, geom=LineString( + [(30 * math.cos(a / 30 * math.pi), 30 * math.sin(a / 30 * math.pi)) for a in range(31)]), width=4.0)), + "column_corners": lambda: _d(ColumnObject(BLUE, geom=LineString([(-30, 15), (0, -15), (30, 15)]), width=3.0)), + "column_tight": lambda: _d(ColumnObject(GREEN, geom=_sine(a=8, length=30), width=5.0)), + "run_triple": lambda: _d(RunObject(BLACK, geom=box(-25, -25, 25, 25).exterior, repeats=1)), + "run_spiral": lambda: _d(RunObject(RED, geom=LineString( + [(a * 0.4 * math.cos(a), a * 0.4 * math.sin(a)) for a in np.arange(0.5, 60, 0.2)]))), + "text_micro_25": lambda: _d(TextObject(BLACK, text="Hamburg 2.5", height=2.5, font="builtin:micro")), + "text_micro_4": lambda: _d(TextObject(BLUE, text="OpenStitch Äöü", height=4.0, font="builtin:micro")), + "text_micro_8": lambda: _d(TextObject(RED, text="Studio", height=8.0, font="builtin:micro")), + "text_ttf_12": lambda: _d(TextObject(GOLD, text="Stitch", height=12.0)), + "text_ttf_30": lambda: _d(TextObject(RED, text="AB", height=30.0)), + "stack_badge": lambda: _d( + FillObject(BLUE, geom=Point(0, 0).buffer(32)), + SatinObject(GOLD, geom=Point(0, 0).buffer(33).difference(Point(0, 0).buffer(29))), + FillObject(RED, geom=_star(20, 8)), + TextObject(WHITE, text="OK", height=9.0)), + "stack_overlap": lambda: _d( + FillObject(RED, geom=box(-25, -25, 25, 25)), + FillObject(BLUE, geom=box(-12, -12, 12, 12), angle=-45), + FillObject(GREEN, geom=box(-6, -6, 6, 6), angle=0)), + "many_colors": lambda: _d(*[FillObject(Thread((20 * i, 200 - 15 * i, 100)), geom=box(-40 + i * 8, -12, -33 + i * 8, 12)) + for i in range(11)], hoop=HOOPS[3]), + "hoop_cap": lambda: _d(FillObject(BLUE, geom=box(-50, -15, 50, 15)), hoop=HOOPS[5]), + "hoop_jacket": lambda: _d(FillObject(RED, geom=Point(0, 0).buffer(110)), hoop=HOOPS[8]), + "auto_blobs": lambda: _auto(_image_blobs()), + "auto_logo": lambda: _auto(_image_logo()), + } + + +def build(name: str) -> Design: + return designs()[name]() diff --git a/openstitch/analysis/coverage.py b/openstitch/analysis/coverage.py new file mode 100644 index 0000000..184c0bd --- /dev/null +++ b/openstitch/analysis/coverage.py @@ -0,0 +1,73 @@ +"""Rastert Stiche und vergleicht sie mit den Objektformen: Deckt der Faden die Fläche?""" +from __future__ import annotations + +import cv2 +import numpy as np + +from ..core.design import Design +from ..engine.geom import polygons_of +from .stitches import Trace + +PX_PER_MM = 12.0 +THREAD_W = 0.38 + + +def _to_px(pts, x0, y0) -> np.ndarray: + return np.round((np.asarray(pts, float)[:, :2] - (x0, y0)) * PX_PER_MM * 16).astype(np.int32) + + +def thread_mask(seg: np.ndarray, x0, y0, w, h) -> np.ndarray: + img = np.zeros((h, w), np.uint8) + t = max(1, int(round(THREAD_W * PX_PER_MM))) + a, b = _to_px(seg[:, :2], x0, y0), _to_px(seg[:, 2:], x0, y0) + for p, q in zip(a.tolist(), b.tolist()): + cv2.line(img, p, q, 255, t, cv2.LINE_8, 4) + return img + + +def polygon_mask(geom, x0, y0, w, h) -> np.ndarray: + img = np.zeros((h, w), np.uint8) + for poly in polygons_of(geom): + rings = [_to_px(poly.exterior.coords, x0, y0)] + [_to_px(r.coords, x0, y0) for r in poly.interiors] + cv2.fillPoly(img, rings, 255, cv2.LINE_8, 4) + return img + + +def check_coverage(design: Design, t: Trace) -> tuple[list[dict], dict]: + """Deckung je Füll-/Satinobjekt. Die Form wird mit allem verglichen, was darauf liegt.""" + seg, _ = t.sewn_segments() + out: list[dict] = [] + per_obj: dict[int, float] = {} + objs = [o for o in design.objects if o.visible and o.kind in ("fill", "satin")] + if len(seg) == 0 or not objs: + return out, per_obj + # Das Raster muss auch die Formen umfassen, sonst fallen Teile ohne Stiche gar nicht auf + bs = [o.bounds() for o in objs] + x0 = min(seg[:, [0, 2]].min(), min(b[0] for b in bs)) - 2 + y0 = min(seg[:, [1, 3]].min(), min(b[1] for b in bs)) - 2 + w = int((max(seg[:, [0, 2]].max(), max(b[2] for b in bs)) + 2 - x0) * PX_PER_MM) + 1 + h = int((max(seg[:, [1, 3]].max(), max(b[3] for b in bs)) + 2 - y0) * PX_PER_MM) + 1 + if w * h > 40_000_000: + return out, per_obj + mask = thread_mask(seg, x0, y0, w, h) > 0 + for o in objs: + g = o.world_geom() + if g is None or g.is_empty: + continue + # Kantenbereich ausklammern: dort dürfen einzelne Pixel fehlen, das sieht man nicht + core = g.buffer(-0.35) + if core.is_empty or core.area < 1.0: + continue + pm = polygon_mask(core, x0, y0, w, h) > 0 + area = int(np.count_nonzero(pm)) + if area == 0: + continue + cov = int(np.count_nonzero(mask & pm)) / area + per_obj[o.id] = cov + # Gewollt lockere Füllungen (grosser Reihenabstand) nicht bemängeln + expected = min(0.97, THREAD_W / max(getattr(o, "spacing", 0.4), 1e-3) * 0.97) + if cov < expected - 0.12: + cx, cy = g.representative_point().coords[0] + out.append({"code": "low_coverage", "severity": "warning", "object": o.name or o.kind, + "percent": cov * 100.0, "count": 1, "where": [(cx, cy)]}) + return out, per_obj diff --git a/openstitch/analysis/legibility.py b/openstitch/analysis/legibility.py new file mode 100644 index 0000000..fe5d371 --- /dev/null +++ b/openstitch/analysis/legibility.py @@ -0,0 +1,101 @@ +"""Lesbarkeit kleiner Schrift, ohne OCR-Abhängigkeit. + +Jeder Buchstabe wird gestickt, mit Fadenbreite gerastert und unscharf gezeichnet (so sieht man ihn +aus Leseabstand). Lesbar ist er, wenn er sich von allen anderen Buchstaben klar unterscheidet und +Innenräume offen bleiben. Das Mass ist die Korrelation zum ähnlichsten anderen Buchstaben.""" +from __future__ import annotations + +from dataclasses import dataclass + +import cv2 +import numpy as np + +from ..core.design import Design +from ..core.stitchplan import Cmd, Thread +from ..text import TextObject + +PX_PER_MM = 16 +THREAD_W = 0.38 + + +def _render(chars: str, height: float, font: str) -> np.ndarray | None: + obj = TextObject(Thread((0, 0, 0)), text=chars, height=height, font=font) + d = Design(objects=[obj]) + plan = d.build_plan() + pts_runs: list[list[tuple[float, float]]] = [] + for b in plan.blocks: + cur: list[tuple[float, float]] = [] + for s in b.stitches: + if s.cmd == Cmd.STITCH: + cur.append((s.x, s.y)) + elif s.cmd == Cmd.JUMP: + if len(cur) > 1: + pts_runs.append(cur) + cur = [(s.x, s.y)] + elif s.cmd == Cmd.TRIM: + if len(cur) > 1: + pts_runs.append(cur) + cur = [] + if len(cur) > 1: + pts_runs.append(cur) + if not pts_runs: + return None + all_pts = np.array([p for r in pts_runs for p in r]) + x0, y0 = all_pts.min(axis=0) + x1, y1 = all_pts.max(axis=0) + # Einheitliche Leinwand, damit Buchstaben unterschiedlicher Breite vergleichbar bleiben + w = int(max(x1 - x0, height) * PX_PER_MM) + 2 * PX_PER_MM + h = int(max(y1 - y0, height) * PX_PER_MM) + 2 * PX_PER_MM + img = np.zeros((h, w), np.uint8) + t = max(1, int(round(THREAD_W * PX_PER_MM))) + for r in pts_runs: + arr = np.round((np.array(r) - (x0 - 1, y0 - 1)) * PX_PER_MM).astype(np.int32) + cv2.polylines(img, [arr.reshape(-1, 1, 2)], False, 255, t, cv2.LINE_AA) + return img + + +def _norm(img: np.ndarray, size: int = 64) -> np.ndarray: + # Aus Leseabstand verschwimmt alles unter etwa einer Fadenbreite + blur = cv2.GaussianBlur(img, (0, 0), THREAD_W * PX_PER_MM * 0.6) + a = cv2.resize(blur, (size, size), interpolation=cv2.INTER_AREA).astype(np.float32).ravel() + a -= a.mean() + return a / (np.linalg.norm(a) + 1e-6) + + +@dataclass +class Legibility: + height: float + font: str + worst_pairs: list[tuple[str, str, float]] + mean_nearest: float + blocked_counters: list[str] + + +def _blocked(img: np.ndarray) -> bool: + """Geschlossene Innenräume (a, e, o …) laufen zu, wenn sie kleiner als ~2 Fadenbreiten werden.""" + contours, hier = cv2.findContours((img > 127).astype(np.uint8), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) + if hier is None: + return False + holes = [cv2.contourArea(c) for c, h in zip(contours, hier[0]) if h[3] >= 0] + return bool(holes) and max(holes) < (0.5 * PX_PER_MM) ** 2 + + +def measure(chars: str, height: float, font: str) -> Legibility: + imgs = {c: _render(c, height, font) for c in chars} + imgs = {c: i for c, i in imgs.items() if i is not None} + keys = list(imgs) + vecs = np.stack([_norm(imgs[c]) for c in keys]) + sim = vecs @ vecs.T + np.fill_diagonal(sim, -1) + nearest = sim.max(axis=1) + order = np.dstack(np.unravel_index(np.argsort(-sim, axis=None), sim.shape))[0] + worst: list[tuple[str, str, float]] = [] + for i, j in order: + if i < j: + worst.append((keys[i], keys[j], float(sim[i, j]))) + if len(worst) >= 8: + break + # Innenräume: nur Zeichen, die im Original einen haben + probes = [c for c in "abdegopqABDOPQR04689" if c in imgs] + blocked = [c for c in probes if _blocked(imgs[c])] + return Legibility(height, font, worst, float(nearest.mean()), blocked) diff --git a/openstitch/analysis/pull.py b/openstitch/analysis/pull.py new file mode 100644 index 0000000..cdbb33b --- /dev/null +++ b/openstitch/analysis/pull.py @@ -0,0 +1,202 @@ +"""Stoffverzug als Federgitter. + +Jeder Einstich wird vom Faden zu seinen beiden Nachbar-Einstichen gezogen. Bei geraden Steppstichen +heben sich die Kräfte auf, bei Satin und Tatami ziehen sie die Kanten nach innen: genau der Effekt, +den die Zugkompensation ausgleicht. Das Gitter wird Abschnitt für Abschnitt belastet; bereits +gestickte Flächen versteifen den Stoff. Was zuerst gestickt wurde, wandert mit dem Stoff mit, wenn +später daneben gestickt wird. Daraus entstehen die Lücken zwischen Füllung und Kontur. +""" +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np +from scipy.sparse import coo_matrix +from scipy.sparse.linalg import splu + +from ..core.stitchplan import Cmd +from ..core.fabric import Fabric, pull_scale +from .stitches import Trace, layers_map + +# Kalibriert: 4 mm Satin ohne Kompensation auf gewebter Baumwolle zieht sich um ~0.3 mm zusammen +TENSION = 0.021 +THREAD_W = 0.27 +MARGIN = 12.0 +STIFFEN = 1.6 # je Fadenlage steigt die lokale Steifigkeit um diesen Faktor +MAX_NODES = 14_000 +MAX_CHUNKS = 8 + + +@dataclass +class PullResult: + x0: float + y0: float + h: float + dx: np.ndarray # Abweichung je Einstich von der gewollten Position + dy: np.ndarray + idx: np.ndarray # Index der Einstiche im Trace + chunk: np.ndarray # Abschnitt je Einstich + max_shift: float + p95_shift: float + misregistration: float # grösster Versatz zwischen Objekten am selben Ort + gaps: list[tuple[float, float]] + + +def _forces(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Fadenzug je Einstich (Summe der Einheitsvektoren zu den Nachbar-Einstichen).""" + dx, dy = np.diff(x), np.diff(y) + length = np.hypot(dx, dy) + ok = length > 1e-6 + ux, uy = np.zeros_like(dx), np.zeros_like(dy) + ux[ok], uy[ok] = dx[ok] / length[ok], dy[ok] / length[ok] + fx, fy = np.zeros_like(x), np.zeros_like(y) + fx[:-1] += ux + fy[:-1] += uy + fx[1:] -= ux + fy[1:] -= uy + return fx, fy + + +class _Grid: + def __init__(self, x0, y0, nx, ny, h): + self.x0, self.y0, self.nx, self.ny, self.h = x0, y0, nx, ny, h + + def _weights(self, x, y): + gx = np.clip((x - self.x0) / self.h, 0, self.nx - 1.001) + gy = np.clip((y - self.y0) / self.h, 0, self.ny - 1.001) + ix, iy = gx.astype(int), gy.astype(int) + return ix, iy, gx - ix, gy - iy + + def sample(self, u, x, y): + ix, iy, fx, fy = self._weights(x, y) + a = u[iy, ix] * ((1 - fx) * (1 - fy))[..., None] + u[iy, ix + 1] * (fx * (1 - fy))[..., None] + b = u[iy + 1, ix] * ((1 - fx) * fy)[..., None] + u[iy + 1, ix + 1] * (fx * fy)[..., None] + return a + b + + def spread(self, x, y, fx_, fy_): + f = np.zeros((self.ny, self.nx, 2)) + ix, iy, fx, fy = self._weights(x, y) + for dix, diy, w in ((0, 0, (1 - fx) * (1 - fy)), (1, 0, fx * (1 - fy)), + (0, 1, (1 - fx) * fy), (1, 1, fx * fy)): + np.add.at(f[..., 0], (iy + diy, ix + dix), fx_ * w) + np.add.at(f[..., 1], (iy + diy, ix + dix), fy_ * w) + return f + + +def _stiffness_matrix(grid: _Grid, s: np.ndarray): + """Federgitter (Kanten + Diagonalen), Randknoten fest (eingespannter Stoff).""" + nx, ny = grid.nx, grid.ny + nid = np.arange(nx * ny).reshape(ny, nx) + rows, cols, vals = [], [], [] + + def add(a, b, k, ex, ey): + # Feder zwischen a und b: k·(e eᵀ) auf die Freiheitsgrade 2·i, 2·i+1 + e = ((ex * ex, ex * ey), (ex * ey, ey * ey)) + for i in range(2): + for j in range(2): + w = k * e[i][j] + ia, ib, ja, jb = 2 * a + i, 2 * b + i, 2 * a + j, 2 * b + j + rows.extend((ia, ib, ia, ib)) + cols.extend((ja, jb, jb, ja)) + vals.extend((w, w, -w, -w)) + + add(nid[:, :-1].ravel(), nid[:, 1:].ravel(), (0.5 * (s[:, :-1] + s[:, 1:])).ravel(), 1.0, 0.0) + add(nid[:-1, :].ravel(), nid[1:, :].ravel(), (0.5 * (s[:-1, :] + s[1:, :])).ravel(), 0.0, 1.0) + r = 0.7071 + add(nid[:-1, :-1].ravel(), nid[1:, 1:].ravel(), (0.25 * (s[:-1, :-1] + s[1:, 1:])).ravel(), r, r) + add(nid[:-1, 1:].ravel(), nid[1:, :-1].ravel(), (0.25 * (s[:-1, 1:] + s[1:, :-1])).ravel(), r, -r) + n = 2 * nx * ny + K = coo_matrix((np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), shape=(n, n)).tocsc() + free = np.ones(n, bool) + edge = np.zeros((ny, nx), bool) + edge[0, :] = edge[-1, :] = True + edge[:, 0] = edge[:, -1] = True + fixed = nid[edge] + free[2 * fixed] = False + free[2 * fixed + 1] = False + return K[free][:, free], free + + +def _chunks(t: Trace, idx: np.ndarray) -> np.ndarray: + """Teilt die Einstiche in Abschnitte je Farbblock; ein Block gilt als ein Arbeitsgang. + + Würde eine grosse Füllung mittendrin geteilt, entstünden Sprünge in der Fläche, die es auf dem + Stoff nicht gibt. Bei sehr vielen Blöcken werden benachbarte zusammengelegt.""" + blocks = t.block[idx] + order = np.unique(blocks) + k = max(1, int(np.ceil(len(order) / MAX_CHUNKS))) + return np.searchsorted(order, blocks) // k + + +def simulate_pull(t: Trace, fabric: Fabric, scale: float | None = None) -> PullResult | None: + """`scale`: Faktor auf den Fadenzug, ohne Angabe der gemessene Wert dieses Stoffs.""" + tension = TENSION * (pull_scale(fabric.id) if scale is None else scale) + idx = np.nonzero(t.cmd == Cmd.STITCH)[0] + if len(idx) < 8: + return None + x, y = t.x[idx], t.y[idx] + bx0, by0, bx1, by1 = x.min(), y.min(), x.max(), y.max() + w, h = bx1 - bx0 + 2 * MARGIN, by1 - by0 + 2 * MARGIN + cell = max(1.0, float(np.sqrt(w * h / MAX_NODES))) + nx, ny = int(w / cell) + 2, int(h / cell) + 2 + grid = _Grid(bx0 - MARGIN, by0 - MARGIN, nx, ny, cell) + + stiff = np.full((ny, nx), float(fabric.stiffness)) + chunk = _chunks(t, idx) + u = np.zeros((ny, nx, 2)) + mat_x, mat_y = np.zeros_like(x), np.zeros_like(y) + + for c in range(int(chunk.max()) + 1): + m = chunk == c + cx, cy = x[m], y[m] + # Die Nadel trifft Rahmenkoordinaten; der Stoffpunkt darunter ist bereits verschoben + offs = grid.sample(u, cx, cy) + mat_x[m], mat_y[m] = cx - offs[:, 0], cy - offs[:, 1] + + K, free = _stiffness_matrix(grid, stiff) + fx, fy = _forces(cx, cy) + f = grid.spread(cx, cy, fx * tension, fy * tension) + b = np.empty(2 * nx * ny) + b[0::2], b[1::2] = f[..., 0].ravel(), f[..., 1].ravel() + du = np.zeros(2 * nx * ny) + du[free] = splu(K, permc_spec="MMD_AT_PLUS_A", options={"SymmetricMode": True}).solve(b[free]) + u[..., 0] += du[0::2].reshape(ny, nx) + u[..., 1] += du[1::2].reshape(ny, nx) + + # Bestickte Fläche versteift den Stoff für alles Folgende + seg = np.column_stack((cx[:-1], cy[:-1], cx[1:], cy[1:])) + lay = layers_map(seg, grid.x0, grid.y0, nx, ny, cell, THREAD_W) + stiff += fabric.stiffness * STIFFEN * np.minimum(lay, 3.0) + + final = grid.sample(u, mat_x, mat_y) + dx, dy = mat_x + final[:, 0] - x, mat_y + final[:, 1] - y + shift = np.hypot(dx, dy) + mis, gaps = _misregistration(x, y, dx, dy, chunk) + return PullResult(grid.x0, grid.y0, cell, dx, dy, idx, chunk, float(shift.max()), + float(np.percentile(shift, 95)), mis, gaps) + + +def _misregistration(x, y, dx, dy, chunk, cell: float = 1.0, min_points: int = 2): + """Versatz zwischen verschiedenen Abschnitten am selben Ort (mittlere Abweichung je Zelle).""" + ix = np.floor(x / cell).astype(np.int64) + iy = np.floor(y / cell).astype(np.int64) + key = (ix + 5000) * 10_007 + (iy + 5000) + (chunk.astype(np.int64)) * 200_000_000 + uniq, inv, cnt = np.unique(key, return_inverse=True, return_counts=True) + sx, sy = np.bincount(inv, dx) / cnt, np.bincount(inv, dy) / cnt + first = np.zeros(len(uniq), int) + first[inv[::-1]] = np.arange(len(x))[::-1] + cells: dict[tuple[int, int], list[tuple[float, float]]] = {} + for i in np.nonzero(cnt >= min_points)[0]: + k = (int(ix[first[i]]), int(iy[first[i]])) + cells.setdefault(k, []).append((float(sx[i]), float(sy[i]))) + worst = 0.0 + spots: list[tuple[float, float, float]] = [] + for (cx, cy), vecs in cells.items(): + if len(vecs) < 2: + continue + a = np.array(vecs) + d = float(np.hypot(*(a.max(axis=0) - a.min(axis=0)))) + worst = max(worst, d) + spots.append((d, (cx + 0.5) * cell, (cy + 0.5) * cell)) + spots.sort(reverse=True) + return worst, [(s[1], s[2]) for s in spots[:12] if s[0] > 0.35] diff --git a/openstitch/analysis/report.py b/openstitch/analysis/report.py new file mode 100644 index 0000000..561cab2 --- /dev/null +++ b/openstitch/analysis/report.py @@ -0,0 +1,120 @@ +"""Fasst alle Prüfungen zu einem Bericht mit Punktzahl zusammen.""" +from __future__ import annotations + +import math +from dataclasses import dataclass, field + +from ..core.design import Design +from ..core.fabric import DEFAULT_FABRIC, Fabric, fabric_by_id +from ..core.stitchplan import Cmd, StitchPlan +from .checks import check_density, check_needle_pileup, check_runs, check_stitch_lengths +from .coverage import check_coverage +from .pull import PullResult, simulate_pull +from .stitches import Trace + +_PENALTY = {"error": 22.0, "warning": 7.0, "info": 1.0} +_ORDER = {"error": 0, "warning": 1, "info": 2} +SMALL_TEXT_MM = 4.5 +PUCKER_MM = 0.7 # so weit zieht sich der Stoff zusammen, bevor man Wellen sieht + + +# Diese Befunde kommen aus dem Stoffmodell. Alle anderen folgen exakt aus den Stichen und Grenzwerten. +ESTIMATES = {"registration_gap", "puckering"} + + +@dataclass +class Finding: + code: str + severity: str + count: int = 1 + where: list[tuple[float, float]] = field(default_factory=list) + data: dict = field(default_factory=dict) + + @property + def is_estimate(self) -> bool: + return self.code in ESTIMATES + + +@dataclass +class Report: + score: int + findings: list[Finding] + metrics: dict + pull: PullResult | None = None + + @property + def ok(self) -> bool: + return not any(f.severity == "error" for f in self.findings) + + +def _finding(d: dict) -> Finding: + d = dict(d) + return Finding(d.pop("code"), d.pop("severity"), d.pop("count", 1), d.pop("where", []), d) + + +def _hoop_findings(design: Design, t: Trace) -> list[dict]: + m = (t.cmd == Cmd.STITCH) | (t.cmd == Cmd.JUMP) + if not m.any(): + return [] + hoop = design.hoop + x, y = t.x[m], t.y[m] + if hoop.round: + over = (x * x + y * y) ** 0.5 > hoop.width / 2 - hoop.margin_mm + else: + over = (abs(x) > hoop.width / 2 - hoop.margin_mm) | (abs(y) > hoop.height / 2 - hoop.margin_mm) + if over.any(): + k = int(over.argmax()) + return [{"code": "outside_hoop", "severity": "error", "count": 1, "where": [(float(x[k]), float(y[k]))]}] + return [] + + +def _small_text_findings(design: Design) -> list[dict]: + """Umriss-Schriften laufen unter 4.5 mm zu; die Einstrich-Schrift ist genau dafür gemacht.""" + out = [] + for o in design.objects: + if o.visible and o.kind == "text" and o.height < SMALL_TEXT_MM and not o.is_micro: + x0, y0, x1, y1 = o.bounds() + out.append({"code": "small_text", "severity": "warning", "object": o.name or o.text, + "mm": float(o.height), "where": [((x0 + x1) / 2, (y0 + y1) / 2)]}) + return out + + +def simulate_stitchout(design: Design | None, plan: StitchPlan, fabric: Fabric | None = None, + needles: int | None = None, physics: bool = True) -> Report: + """Virtueller Probestick. `design` darf None sein (dann nur stichbasierte Prüfungen). + + Ohne `fabric` gilt der im Design gewählte Stoff.""" + if fabric is None: + fabric = fabric_by_id(design.fabric) if design is not None else DEFAULT_FABRIC + t = Trace.of(plan) + raw: list[dict] = [] + max_stitch = design.settings.max_stitch if design is not None else 12.1 + raw += check_stitch_lengths(t, max_stitch) + raw += check_runs(t) + raw += check_needle_pileup(t) + dens, peak = check_density(t, fabric.max_layers) + raw += dens + metrics: dict = {"stitches": plan.stitch_count, "trims": plan.trim_count, "colors": len(plan.blocks), + "peak_layers": peak} + if design is not None: + raw += _hoop_findings(design, t) + raw += _small_text_findings(design) + cov, per_obj = check_coverage(design, t) + raw += cov + metrics["coverage"] = per_obj + if needles is not None: + unique = len({b.thread.hex for b in plan.blocks}) + if unique > needles: + raw.append({"code": "too_many_colors", "severity": "info" if needles == 1 else "warning", + "count": unique, "needles": needles}) + pull = simulate_pull(t, fabric) if physics else None + if pull is not None: + metrics.update(max_shift=pull.max_shift, p95_shift=pull.p95_shift, misregistration=pull.misregistration) + if pull.gaps: + raw.append({"code": "registration_gap", "severity": "warning", "count": len(pull.gaps), + "mm": pull.misregistration, "where": pull.gaps}) + if pull.p95_shift > PUCKER_MM: + raw.append({"code": "puckering", "severity": "warning", "count": 1, "mm": pull.p95_shift}) + findings = sorted((_finding(d) for d in raw), key=lambda f: (_ORDER[f.severity], f.code)) + score = 100.0 - sum(_PENALTY[f.severity] * (1 + min(math.log10(max(f.count, 1)), 2) / 4) for f in findings) + return Report(int(round(max(0.0, score))), findings, metrics, pull) diff --git a/openstitch/analysis/roundtrip.py b/openstitch/analysis/roundtrip.py new file mode 100644 index 0000000..b27ec0f --- /dev/null +++ b/openstitch/analysis/roundtrip.py @@ -0,0 +1,136 @@ +"""Export-Prüfung: Datei schreiben, unabhängig wieder einlesen und Stich für Stich vergleichen. + +Zum Lesen dient pyembroidery. Damit wird geprüft, was tatsächlich in der Datei steht, nicht was der +Plan sagt. Das deckt verlorene Trims, Rundungsdrift und falsche Farben auf.""" +from __future__ import annotations + +import os +import tempfile +from dataclasses import dataclass, field + +import numpy as np +import pyembroidery as pe +from scipy.spatial import cKDTree + +from ..core.stitchplan import Cmd, StitchPlan +from ..io.formats import export_plan + +MACHINE_FORMATS = ("dst", "exp", "pes", "pec", "jef", "vp3", "xxx", "u01", "tbf") +# Formate ohne Farbtabelle (Farben legt die Maschine fest) oder nur mit fester Hersteller-Palette +NO_RGB = {"dst", "exp", "u01", "tbf"} +PALETTE_RGB = {"pes", "pec", "jef"} + + +@dataclass +class RoundTrip: + ext: str + bytes: int = 0 + stitches: int = 0 + expected: int = 0 + max_error_mm: float = 0.0 + drift_mm: float = 0.0 + trims: int = 0 + expected_trims: int = 0 + colors: int = 0 + expected_colors: int = 0 + color_error: float = 0.0 + problems: list[str] = field(default_factory=list) + + @property + def ok(self) -> bool: + return not self.problems + + +def _plan_points(plan: StitchPlan) -> np.ndarray: + pts = [(s.x, s.y) for b in plan.blocks for s in b.stitches if s.cmd == Cmd.STITCH] + return np.array(pts, float).reshape(-1, 2) + + +def _read(path: str): + # Der JEF-Leser erkennt die Trim-Sprungfolge nur auf Wunsch + pat = pe.read(path, {"trims": True} if path.endswith(".jef") else None) + if pat is None: + raise ValueError("unreadable") + pts, trims, jumps_in_row, trim_like, colors, needles = [], 0, 0, 0, 1, 0 + for x, y, cmd in pat.stitches: + c = cmd & pe.COMMAND_MASK + if c == pe.STITCH: + if jumps_in_row >= 3: + trim_like += 1 + jumps_in_row = 0 + pts.append((x / 10.0, y / 10.0)) + elif c == pe.JUMP: + jumps_in_row += 1 + elif c == pe.TRIM: + trims += 1 + elif c == pe.COLOR_CHANGE: + colors += 1 + elif c == pe.NEEDLE_SET: + needles += 1 + # U01/TBF wählen Nadeln statt Farbwechsel + return np.array(pts, float).reshape(-1, 2), max(trims, trim_like), max(colors, needles), pat + + +def check_format(plan: StitchPlan, ext: str, folder: str | None = None) -> RoundTrip: + r = RoundTrip(ext) + expected = _plan_points(plan) + r.expected = len(expected) + r.expected_trims = plan.trim_count + r.expected_colors = len(plan.blocks) + own = folder is None + tmp = tempfile.TemporaryDirectory() if own else None + path = os.path.join(tmp.name if own else folder, f"roundtrip.{ext}") + try: + kw = {"trim_mode": "code"} if ext == "exp" else {} + export_plan(plan, path, **kw) + r.bytes = os.path.getsize(path) + pts, trims, colors, pat = _read(path) + except Exception as e: # noqa: BLE001 - jedes Versagen eines Formats ist ein Befund, kein Absturz + r.problems.append(f"export/read failed: {type(e).__name__}: {e}") + return r + finally: + if tmp is not None: + tmp.cleanup() + r.stitches = len(pts) + r.trims = trims + r.colors = colors + if len(pts) == 0: + r.problems.append("no stitches in file") + return r + # Dateien sind auf die Motivmitte zentriert; Y-Richtung ist nach dem Lesen wieder Bildschirm-Y + a = expected - (expected.min(axis=0) + expected.max(axis=0)) / 2 + b = pts - (pts.min(axis=0) + pts.max(axis=0)) / 2 + if len(a) == len(b): + # Die Mitte der Umrandung ist auf 0.1 mm gerundet: am Schwerpunkt aller Stiche ausrichten + b = b + (a - b).mean(axis=0) + forward = cKDTree(b).query(a)[0] + backward = cKDTree(a).query(b)[0] + r.max_error_mm = float(max(forward.max(), backward.max())) + if len(pts) == len(expected): + # Laufende Summe gerundeter Deltas darf sich nicht aufaddieren + n = min(len(a), len(b)) + r.drift_mm = float(np.hypot(*(a[:n] - b[:n]).T).max()) + if r.max_error_mm > 0.25: + r.problems.append(f"position error {r.max_error_mm:.2f} mm") + if r.drift_mm > 0.25: + r.problems.append(f"sequence drift {r.drift_mm:.2f} mm") + if abs(r.stitches - r.expected) > max(3, r.expected * 0.01): + r.problems.append(f"stitch count {r.stitches} != {r.expected}") + if r.trims < r.expected_trims - 1: + r.problems.append(f"trims lost: {r.trims} of {r.expected_trims}") + if r.expected_colors > 1 and r.colors != r.expected_colors: + r.problems.append(f"color changes {r.colors} != {r.expected_colors}") + if ext not in NO_RGB and len(pat.threadlist) >= len(plan.blocks): + errs = [] + for block, th in zip(plan.blocks, pat.threadlist): + got = np.array((th.get_red(), th.get_green(), th.get_blue()), float) + errs.append(float(np.linalg.norm(got - np.array(block.thread.color, float)))) + r.color_error = max(errs, default=0.0) + # Feste Paletten treffen seltene Farben nur grob; RGB-Formate müssen exakt sein + if r.color_error > (160 if ext in PALETTE_RGB else 3): + r.problems.append(f"color off by {r.color_error:.0f}") + return r + + +def check_all(plan: StitchPlan, formats=MACHINE_FORMATS) -> list[RoundTrip]: + return [check_format(plan, ext) for ext in formats] diff --git a/openstitch/analysis/stitches.py b/openstitch/analysis/stitches.py new file mode 100644 index 0000000..aa56f28 --- /dev/null +++ b/openstitch/analysis/stitches.py @@ -0,0 +1,83 @@ +"""Stichplan als Numpy-Arrays für die Analysen.""" +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + +from ..core.stitchplan import Cmd, StitchPlan + + +@dataclass +class Trace: + x: np.ndarray + y: np.ndarray + cmd: np.ndarray + block: np.ndarray + + @staticmethod + def of(plan: StitchPlan) -> "Trace": + xs, ys, cs, bs = [], [], [], [] + for bi, b in enumerate(plan.blocks): + for s in b.stitches: + xs.append(s.x) + ys.append(s.y) + cs.append(int(s.cmd)) + bs.append(bi) + return Trace(np.array(xs, float), np.array(ys, float), np.array(cs, int), np.array(bs, int)) + + def sewn_segments(self) -> tuple[np.ndarray, np.ndarray]: + """(N×4-Array x0,y0,x1,y1; Block je Segment): alle Stiche, die Faden auf den Stoff legen.""" + idx = np.nonzero(self.cmd == Cmd.STITCH)[0] + idx = idx[idx > 0] + prev = idx - 1 + # Nur Stiche, deren Vorgänger eine Nadelposition ist (STITCH oder JUMP), und im selben Block + keep = np.isin(self.cmd[prev], (Cmd.STITCH, Cmd.JUMP)) & (self.block[prev] == self.block[idx]) + i, p = idx[keep], prev[keep] + seg = np.column_stack((self.x[p], self.y[p], self.x[i], self.y[i])) + return seg, self.block[i] + + def runs(self) -> list[np.ndarray]: + """Zusammenhängende Nähläufe als Index-Arrays (Ende an Trim, Sprung oder Blockwechsel).""" + out: list[list[int]] = [] + cur: list[int] = [] + last_block = None + for i, (c, b) in enumerate(zip(self.cmd, self.block)): + if b != last_block: + if cur: + out.append(cur) + cur = [] + last_block = b + if c == Cmd.STITCH: + cur.append(i) + elif c == Cmd.JUMP: + if cur: + out.append(cur) + cur = [i] + elif c == Cmd.TRIM: + if cur: + out.append(cur) + cur = [] + if cur: + out.append(cur) + return [np.array(r) for r in out if len(r) >= 2] + + +def layers_map(seg: np.ndarray, x0: float, y0: float, w: int, h: int, cell: float, + thread_w: float) -> np.ndarray: + """Fadenlagen je Zelle: abgelegte Fadenfläche / Zellenfläche (1.0 = Stoff gerade bedeckt).""" + out = np.zeros((h, w), float) + if len(seg) == 0: + return out + dx, dy = seg[:, 2] - seg[:, 0], seg[:, 3] - seg[:, 1] + length = np.hypot(dx, dy) + n = np.maximum(np.ceil(length / (cell * 0.5)).astype(int), 1) + rep = np.repeat(np.arange(len(seg)), n) + # Abtastpunkte je Segment gleichmässig verteilt + k = np.concatenate([(np.arange(m) + 0.5) / m for m in n]) + px = seg[rep, 0] + dx[rep] * k + py = seg[rep, 1] + dy[rep] * k + ix = np.clip(((px - x0) / cell).astype(int), 0, w - 1) + iy = np.clip(((py - y0) / cell).astype(int), 0, h - 1) + np.add.at(out, (iy, ix), (length / n)[rep]) + return out * thread_w / (cell * cell) diff --git a/openstitch/core/design.py b/openstitch/core/design.py index 1af7bae..572735b 100644 --- a/openstitch/core/design.py +++ b/openstitch/core/design.py @@ -15,10 +15,14 @@ from ..engine.geom import Pt, clean, dist, lines_of, main_axis_angle, polygons_of, directional_grow from ..engine.running import bean_stitch, running_stitch, tie_stitches from ..engine.satin import UNDERLAY_STYLES, satin_runs +from .fabric import fabric_by_id, pull_scale from .stitchplan import Cmd, ColorBlock, Stitch, StitchPlan, Thread IDENTITY = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0) +KNOCKOUT_OVERLAP = 1.0 # mm: so weit läuft die Füllung unter dem Objekt darüber weiter +KNOCKOUT_MIN_AREA = 4.0 # mm²: kleinere verdeckte Stellen lohnen das Zerschneiden nicht + def compose(m2, m1): """m2 ∘ m1 (zuerst m1).""" @@ -97,6 +101,23 @@ def to_dict(self) -> dict: d[attr] = getattr(self, attr) return d + def footprint(self): + """Fläche, die dieses Objekt mit Faden bedeckt (Polygone), oder None bei Laufstichen.""" + g = self.world_geom() + return g if polygons_of(g) else None + + def covered_core(self): + """Kernbereich, unter dem nichts gestickt werden muss (zwischengespeichert).""" + key = (id(getattr(self, "geom", None)), self.transform, getattr(self, "width", None), + getattr(self, "text", None), getattr(self, "height", None), getattr(self, "font", None)) + cached = getattr(self, "_core", None) + if cached is None or cached[0] != key: + fp = self.footprint() + core = None if fp is None or fp.is_empty else fp.buffer(-KNOCKOUT_OVERLAP) + cached = (key, None if core is None or core.is_empty else core) + self._core = cached + return cached[1] + def clone(self): c = copy.deepcopy(self) c.id = _new_id() @@ -116,6 +137,7 @@ class FillObject(EmbObject): pattern: str = "standard" underlay: bool = True pull_comp: float = 0.20 + knockout: bool = True kind: str = "fill" PARAMS = (("angle", "Stichwinkel (°)", float, -180, 180, 5), @@ -123,7 +145,8 @@ class FillObject(EmbObject): ("stitch_len", "Stichlänge (mm)", float, 1.5, 7.0, 0.1), ("pattern", "Muster", ["standard", "diagonal", "ziegel", "wellen", "kontur"], 0, 0, 0), ("underlay", "Unterlage", bool, 0, 0, 0), - ("pull_comp", "Zugkompensation (mm)", float, 0.0, 1.0, 0.05)) + ("pull_comp", "Zugkompensation (mm)", float, 0.0, 1.0, 0.05), + ("knockout", "Verdecktes nicht sticken", bool, 0, 0, 0)) def local_geom(self): return self.geom @@ -132,6 +155,12 @@ def runs(self, start=None): g = self.world_geom() if g is None or g.is_empty: return [] + hidden = getattr(self, "_hidden", None) + if hidden is not None: + g = clean(g.difference(hidden)) + if g is None or g.is_empty: + return [] + spacing = self.spacing * getattr(self, "_density_factor", 1.0) # Winkel mit Objekt-Rotation mitdrehen a, b, d, e, _, _ = self.transform rot = math.degrees(math.atan2(d, a)) @@ -154,7 +183,7 @@ def runs(self, start=None): k = min(range(len(ring) - 1), key=lambda i: dist(ring[i], cur)) ring = ring[k:-1] + ring[:k + 1] edge = running_stitch(ring, 3.2) - lat = fill_runs(ip.buffer(-0.25), ang + 90, spacing=max(2.2, self.spacing * lat_mult), + lat = fill_runs(ip.buffer(-0.25), ang + 90, spacing=max(2.2, spacing * lat_mult), stitch_len=4.2, pattern="ziegel", start=edge[-1] if edge else cur) out.append(edge) out.extend(lat) @@ -168,7 +197,7 @@ def runs(self, start=None): # Rahmen-abhängiger Zuschlag auf die Zugkompensation ("Trampolin-Effekt" in grossen Rahmen / Kappen) hoop_pc_boost = getattr(self, "_hoop_pc_boost", 1.0) top_geom = directional_grow(g, self.pull_comp * hoop_pc_boost, ang) - top = fill_runs(top_geom, ang, self.spacing, self.stitch_len, self.pattern, start=cur) + top = fill_runs(top_geom, ang, spacing, self.stitch_len, self.pattern, start=cur) # Unterlage und Weg zum Deckstich-Einstieg liegen unter dem Deckstich → verbinden statt trimmen under = [r for r in out if len(r) >= 2] if under and top: @@ -203,8 +232,10 @@ def runs(self, start=None): g = self.world_geom() if g is None or g.is_empty: return [] - eff_spacing = min(self.spacing, 0.25) if self.puff_3d else self.spacing - eff_pc = max(self.pull_comp, 0.32) if self.puff_3d else self.pull_comp + spacing = self.spacing * getattr(self, "_density_factor", 1.0) + pull_comp = self.pull_comp * getattr(self, "_hoop_pc_boost", 1.0) + eff_spacing = min(spacing, 0.25) if self.puff_3d else spacing + eff_pc = max(pull_comp, 0.32) if self.puff_3d else pull_comp res = satin_runs( g, eff_spacing, eff_pc, self.max_stitch, self.underlay, start, puff_3d=self.puff_3d, underlay_style=self.underlay_style, @@ -289,6 +320,10 @@ def bounds(self): return (0, 0, 0, 0) return g.buffer(self.width * m_scale(self.transform) / 2.0).bounds + def footprint(self): + g = self.world_geom() + return None if g is None or g.is_empty else g.buffer(self.width * m_scale(self.transform) / 2.0) + def runs(self, start=None): from ..engine.column import column_runs g = self.world_geom() @@ -300,7 +335,8 @@ def runs(self, start=None): if cur is not None: lines.sort(key=lambda l: min(dist(cur, l.coords[0]), dist(cur, l.coords[-1]))) l = lines.pop(0) - rs = column_runs(list(l.coords), w, spacing=self.spacing, pull_comp=self.pull_comp, + rs = column_runs(list(l.coords), w, spacing=self.spacing * getattr(self, "_density_factor", 1.0), + pull_comp=self.pull_comp * getattr(self, "_hoop_pc_boost", 1.0), underlay="center" if self.underlay else "none", start=cur) rs = [r for r in rs if len(r) >= 2] if rs: @@ -333,17 +369,37 @@ def to_dict(self): "stitches": StitchesObject} +def _checked_param(typ, lo, hi, val): + """Wert aus einer Projektdatei prüfen: Zahlen in den erlaubten Bereich holen, Unsinn ablehnen.""" + if typ is bool: + return bool(val) + if typ in (int, float): + v = float(val) + if not math.isfinite(v): + raise ValueError(f"invalid number: {val!r}") + v = min(max(v, lo), hi) if hi > lo else v + return typ(v) + if isinstance(typ, (list, tuple)): + if val not in typ: + raise ValueError(f"unknown option: {val!r}") + return val + return str(val) + + def object_from_dict(d: dict) -> EmbObject: cls = OBJECT_TYPES[d["kind"]] - kw = {"thread": Thread.from_dict(d["thread"]), "name": d.get("name", ""), - "transform": tuple(d.get("transform", IDENTITY)), "visible": d.get("visible", True)} + transform = tuple(float(v) for v in d.get("transform", IDENTITY)) + if len(transform) != 6 or not all(math.isfinite(v) for v in transform): + raise ValueError("invalid transform") + kw = {"thread": Thread.from_dict(d["thread"]), "name": str(d.get("name", "")), + "transform": transform, "visible": bool(d.get("visible", True))} if "geom" in d: kw["geom"] = wkt.loads(d["geom"]) if d["geom"] else None if "stitch_runs" in d: kw["stitch_runs"] = [[tuple(p) for p in r] for r in d["stitch_runs"]] - for attr, *_ in getattr(cls, "PARAMS", ()): + for attr, _label, typ, lo, hi, _step in getattr(cls, "PARAMS", ()): if attr in d: - kw[attr] = d[attr] + kw[attr] = _checked_param(typ, lo, hi, d[attr]) for extra in getattr(cls, "EXTRA_FIELDS", ()): if extra in d: kw[extra] = d[extra] @@ -481,6 +537,7 @@ class Design: hoop: Hoop = field(default_factory=lambda: HOOPS[2]) settings: Settings = field(default_factory=Settings) name: str = "Unbenannt" + fabric: str = "woven" # Stoff-Profil (siehe core.fabric) _cache: dict = field(default_factory=dict, repr=False) def bounds(self): @@ -491,11 +548,37 @@ def bounds(self): return (min(b[0] for b in bs), min(b[1] for b in bs), max(b[2] for b in bs), max(b[3] for b in bs)) - def object_runs(self, obj: EmbObject, start) -> list[list[Pt]]: - # Rahmen-Modus und Zugkompensations-Boost an das Objekt übergeben + def _hidden_under(self, obj: EmbObject, later: list[EmbObject]): + """Fläche von `obj`, die spätere Objekte vollständig zudecken: dort entfällt die Füllung. + + Das spart Stiche und verhindert harte Stellen. Dünne Objekte (Text, Konturen unter 2 mm) + haben keinen Kern und bleiben unberührt: sie brauchen die Füllung als Unterlage.""" + if obj.kind != "fill" or not obj.knockout: + return None + x0, y0, x1, y1 = obj.bounds() + cores = [] + for o in later: + b = o.bounds() + if b[2] < x0 or b[0] > x1 or b[3] < y0 or b[1] > y1: + continue + c = o.covered_core() + if c is not None: + cores.append(c) + if not cores: + return None + hidden = unary_union(cores).intersection(obj.world_geom()) + return None if hidden.is_empty or hidden.area < KNOCKOUT_MIN_AREA else hidden + + def object_runs(self, obj: EmbObject, start, later: list[EmbObject] = ()) -> list[list[Pt]]: + # Rahmen- und Stoffeinflüsse an das Objekt übergeben + fabric = fabric_by_id(self.fabric) obj._hoop_mode = self.hoop.mode - obj._hoop_pc_boost = self.hoop.pc_boost - key = obj.cache_key(start) + f"|{self.hoop.mode}" + measured = pull_scale(fabric.id) + obj._hoop_pc_boost = self.hoop.pc_boost * fabric.pull_factor * measured + obj._density_factor = fabric.density_factor + obj._hidden = self._hidden_under(obj, later) + hidden_key = "" if obj._hidden is None else f"{obj._hidden.area:.3f}/{obj._hidden.length:.3f}" + key = obj.cache_key(start) + f"|{self.hoop.mode}|{fabric.id}|{measured}|{hidden_key}" r = self._cache.get((obj.id, key)) if r is None: r = obj.runs(start) @@ -522,7 +605,7 @@ def build_plan(self, progress=None) -> StitchPlan: for i, obj in enumerate(vis): if progress: progress(i, len(vis)) - runs = self.object_runs(obj, cur) + runs = self.object_runs(obj, cur, vis[i + 1:]) if not runs: continue if block is None or block.thread.hex != obj.thread.hex: diff --git a/openstitch/core/fabric.py b/openstitch/core/fabric.py new file mode 100644 index 0000000..46ceeba --- /dev/null +++ b/openstitch/core/fabric.py @@ -0,0 +1,54 @@ +"""Stoff-Profile für den Probestick und die Auto-Einstellungen. + +`stiffness`: Dehnwiderstand relativ zu gewebter Baumwolle (1.0). +`pull_factor`: Faktor auf die Zugkompensation. `density_factor`: Faktor auf den Reihenabstand +(> 1 = lockerer). `max_layers`: ab wie vielen Fadenlagen der Stoff leidet.""" +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class Fabric: + id: str + stiffness: float + pull_factor: float + density_factor: float + max_layers: float + topping: bool = False # wasserlösliche Folie empfohlen (hoher Flor) + stabilizer: str = "cutaway" # 'cutaway' | 'tearaway' | 'none' + needle: str = "75/11" + + +FABRICS: list[Fabric] = [ + Fabric("woven", 1.0, 1.0, 1.0, 4.5, stabilizer="tearaway"), + Fabric("denim", 1.8, 0.8, 1.0, 5.5, stabilizer="tearaway", needle="90/14"), + Fabric("twill_cap", 1.4, 1.1, 1.0, 5.0, stabilizer="tearaway", needle="80/12"), + Fabric("pique", 0.65, 1.5, 1.05, 4.0), + Fabric("jersey", 0.45, 2.0, 1.15, 3.2), + Fabric("fleece", 0.55, 1.8, 1.1, 3.8, topping=True), + Fabric("towel", 0.6, 1.6, 0.95, 4.5, topping=True, needle="80/12"), + Fabric("leather", 1.6, 0.7, 1.3, 2.6, stabilizer="none"), + Fabric("silk", 0.7, 1.3, 1.2, 2.8, stabilizer="tearaway", needle="65/9"), +] + +DEFAULT_FABRIC = FABRICS[0] + + +# Gemessener Faktor je Stoff (siehe analysis.calibrate); 1.0 = noch nicht gemessen +_pull_scale: dict[str, float] = {} + + +def pull_scale(fid: str) -> float: + return _pull_scale.get(fid, 1.0) + + +def set_pull_scale(fid: str, value: float | None) -> None: + if value is None: + _pull_scale.pop(fid, None) + else: + _pull_scale[fid] = float(value) + + +def fabric_by_id(fid: str | None) -> Fabric: + return next((f for f in FABRICS if f.id == fid), DEFAULT_FABRIC) diff --git a/openstitch/core/stitchplan.py b/openstitch/core/stitchplan.py index b0cc0dd..29772b3 100644 --- a/openstitch/core/stitchplan.py +++ b/openstitch/core/stitchplan.py @@ -41,6 +41,8 @@ def hex(self) -> str: @staticmethod def from_hex(h: str, name: str = "", code: str = "", brand: str = "") -> "Thread": h = h.lstrip("#") + if len(h) != 6: + raise ValueError(f"invalid colour: {h!r}") return Thread((int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)), name, code, brand) def to_dict(self) -> dict: diff --git a/openstitch/engine/column.py b/openstitch/engine/column.py index f2031c0..21bbeb6 100644 --- a/openstitch/engine/column.py +++ b/openstitch/engine/column.py @@ -22,12 +22,15 @@ import math +from shapely.geometry import LineString, Point + from .geom import Pt, dist, resample_path from .running import bean_stitch CORNER_DEG = 40.0 # ab dieser Richtungsänderung gilt ein Stützpunkt als Ecke # (Gehrung schon ab 40° – sauberer als reine Glättung) MITRE_MAX_DEG = 130.0 # bis hierhin weiche Gehrung, darüber beschnittene Gehrung +MAX_REACH = 2.5 # weiteste Gehrung (× halbe Breite), bevor ein Querschnitt als entartet gilt MITRE_LIMIT = 1.45 # max. Gehrungslänge (× halbe Breite) auf der Aussenseite MIN_SATIN_W = 0.7 # schmaler → Dreifachstich statt Satin UNDERLAY_MIN_W = 1.0 # schmaler → keine Unterlage (würde nur auftragen) @@ -68,7 +71,8 @@ def column_runs(centerline: list[Pt], width: float | list[float], spacing: float ws.reverse() if max(ws) < MIN_SATIN_W: return [bean_run(pts, run_len, closed)] - cross = _cross_sections(pts, ws, spacing, pull_comp, closed) + cross = _drop_escapes(_cross_sections(pts, ws, spacing, pull_comp, closed), pts, + max(ws) / 2 * MAX_REACH + pull_comp + 0.25) if len(cross) < 2: return [bean_run(pts, run_len, closed)] wavg = sum(ws) / len(ws) @@ -82,6 +86,14 @@ def column_runs(centerline: list[Pt], width: float | list[float], spacing: float return [run] if len(run) >= 2 else [] +def _drop_escapes(cross, pts, reach: float): + """Entartete Linien (Umkehr kürzer als die Säulenbreite) können Gehrungen weit über die Form + hinausschieben. Solche Querschnitte entfallen, statt Stiche neben das Motiv zu setzen.""" + line = LineString(pts) + return [q for q in cross + if line.distance(Point(q[1])) <= reach and line.distance(Point(q[2])) <= reach] + + def bean_run(pts: list[Pt], run_len: float = 1.0, closed: bool = False) -> list[Pt]: """Dreifachstich entlang einer Linie mit gleichmässigen Stichen (Ecken bleiben erhalten).""" ev = _even(pts, run_len) diff --git a/openstitch/engine/density_guard.py b/openstitch/engine/density_guard.py index f056a87..8d49acb 100644 --- a/openstitch/engine/density_guard.py +++ b/openstitch/engine/density_guard.py @@ -20,6 +20,10 @@ from ..core.stitchplan import Cmd, Stitch, StitchPlan +LOCK_GUARD = 5 # so viele Stiche an den Laufenden sind geschützt +MAX_BRIDGE_MM = 2.5 # so lang darf ein Stich werden, der einen gesättigten Einstich überbrückt + + def _is_turn(a: tuple[float, float], s: Stitch, nxt: Stitch) -> bool: """Wendepunkt (> 60° Richtungswechsel), z. B. Reihenwechsel im Tatami oder Satin-Kante. @@ -59,9 +63,16 @@ def optimize_stitches_for_melco( continue cell = (int(math.floor(s.x / cell_size_mm)), int(math.floor(s.y / cell_size_mm))) - if grid[cell] >= max_punctures_per_cell and not is_last_of_run: - # Zelle ist bereits gesättigt → Einstich überspringen, schont Stoff & Faden - continue + # Anfang und Ende eines Laufs bleiben: Dort sitzen die Vernähstiche, die den Faden halten + near_end = any(stitches[j].cmd != Cmd.STITCH + for j in range(max(0, i - LOCK_GUARD), min(len(stitches), i + LOCK_GUARD + 1))) + if grid[cell] >= max_punctures_per_cell and not is_last_of_run and not near_end: + # Zelle ist bereits gesättigt → Einstich überspringen, schont Stoff & Faden. + # Aber nur, wenn der nächste Stich dadurch nicht lang wird: sonst entsteht auf + # mehrfach abgefahrenen Linien ein Riesenstich quer über das Motiv. + nxt = stitches[i + 1] + if last_xy is None or math.hypot(nxt.x - last_xy[0], nxt.y - last_xy[1]) <= MAX_BRIDGE_MM: + continue grid[cell] += 1 out.append(s) diff --git a/openstitch/engine/geom.py b/openstitch/engine/geom.py index d78f9bd..e9ba7dc 100644 --- a/openstitch/engine/geom.py +++ b/openstitch/engine/geom.py @@ -82,6 +82,28 @@ def resample_path(coords: Iterable[Pt], step: float, closed: bool = False) -> li return merge_short(out, step * 0.35) +def resample_uniform(coords: Iterable[Pt], step: float, closed: bool = False) -> list[Pt]: + """Exakt gleiche Abstände entlang des Pfades, unabhängig von der Dichte der Stützpunkte. + + Für Satin-Querschnitte: `resample_path` unterteilt jedes Segment für sich und kann dadurch den + Abstand nie über den der Stützpunkte hinaus vergrössern (Skelette liegen dicht).""" + arr = np.array([tuple(c) for c in coords], float) + if closed and len(arr) and tuple(arr[0]) != tuple(arr[-1]): + arr = np.vstack((arr, arr[0])) + if len(arr) < 2: + return [tuple(p) for p in arr] + seg = np.hypot(*np.diff(arr, axis=0).T) + keep = np.concatenate(([True], seg > 1e-9)) + arr = arr[keep] + cum = np.concatenate(([0.0], np.cumsum(np.hypot(*np.diff(arr, axis=0).T)))) + total = float(cum[-1]) + if total < 1e-9: + return [tuple(arr[0])] + n = max(1, int(round(total / step))) + s = np.linspace(0.0, total, n + 1) + return list(zip(np.interp(s, cum, arr[:, 0]).tolist(), np.interp(s, cum, arr[:, 1]).tolist())) + + def merge_short(pts: list[Pt], min_len: float) -> list[Pt]: """Entfernt sehr kurze Stiche (Fadenbruch-Gefahr) ohne Endpunkt zu verlieren.""" if len(pts) < 3: @@ -144,14 +166,15 @@ def walk(s0: float, s1: float, forward: bool) -> list[Pt]: if forward: if s1 < s0: s1 += L - idx = [c for c in cum[1:-1]] + [c + L for c in cum[1:-1]] + # Auch der Startpunkt des Rings ist eine Ecke: Ohne ihn schneidet der Weg dort ab + idx = [c for c in cum[:-1]] + [c + L for c in cum[:-1]] for c in idx: if s0 < c < s1: pts.append(tuple(line.interpolate(c % L).coords[0])) else: if s1 > s0: s1 -= L - idx = sorted([c for c in cum[1:-1]] + [c - L for c in cum[1:-1]], reverse=True) + idx = sorted([c for c in cum[:-1]] + [c - L for c in cum[:-1]], reverse=True) for c in idx: if s1 < c < s0: pts.append(tuple(line.interpolate(c % L).coords[0])) diff --git a/openstitch/engine/pro_tools.py b/openstitch/engine/pro_tools.py index 18ae46e..49fdaf4 100644 --- a/openstitch/engine/pro_tools.py +++ b/openstitch/engine/pro_tools.py @@ -4,16 +4,14 @@ import math import re import xml.etree.ElementTree as ET -from collections import defaultdict from shapely.geometry import LineString, Polygon from shapely.ops import unary_union from ..auto.palette import nearest_thread from ..core.design import Design, EmbObject, FillObject, RunObject, SatinObject -from ..core.stitchplan import Cmd, StitchPlan, Thread +from ..core.stitchplan import Thread from ..engine.geom import clean, main_axis_angle, polygons_of -from ..i18n import fmt_float, fmt_int, tr # =========================================================================== @@ -624,60 +622,3 @@ def to_mm(geom): if not band.is_empty: d.objects.append(SatinObject(th, name="SVG-Kontur (Satin)", geom=band)) return d - - -# =========================================================================== -# 3. Qualitäts- & Maschinen-Doktor (Prüfung & Auto-Fix) -# =========================================================================== -def run_quality_doctor(design: Design, plan: StitchPlan, max_needles: int = 10) -> list[str]: - """Prüft das Design auf Stick-Probleme, die in der Praxis zu Fadenbruch, Nadelbruch oder Verzug führen.""" - issues: list[str] = [] - hw, hh = design.hoop.width / 2.0, design.hoop.height / 2.0 - x0, y0, x1, y1 = plan.bounds() - - if plan.stitch_count == 0: - return [tr("doc_empty")] - - # 1. Rahmengrenzen-Check (Kollisionsgefahr Nadel/Presserfuss mit dem Rahmen!) - if design.hoop.round: - # tatsächliche Nadelpositionen statt Bounding-Box-Ecken (die überschätzen runde Motive um bis zu 41 %) - r_max = max((math.hypot(s.x, s.y) for b in plan.blocks for s in b.stitches - if s.cmd in (Cmd.STITCH, Cmd.JUMP)), default=0.0) - if r_max > hw - 2.0: - issues.append(tr("doc_hoop_round").format(r=fmt_float(r_max), hoop=design.hoop.display_name, - hr=fmt_float(hw, 0))) - else: - if x0 < -hw + 2 or x1 > hw - 2 or y0 < -hh + 2 or y1 > hh - 2: - issues.append(tr("doc_hoop_rect").format(w=fmt_float(x1 - x0), h=fmt_float(y1 - y0), - hw=fmt_float(design.hoop.width, 0), - hh=fmt_float(design.hoop.height, 0))) - - # 2. Nadelanzahl-Check - unique_colors = len({b.thread.hex for b in plan.blocks}) - if unique_colors > max_needles: - issues.append(tr("doc_colors").format(n=unique_colors, needles=max_needles)) - - # 3. Objekt-Checks (zu kleine Schrift / zu schmale Satin-Säulen) - for o in design.objects: - if not o.visible: - continue - # Die Micro-Schrift ist genau für kleine Höhen digitalisiert → keine Warnung - if o.kind == "text" and getattr(o, "height", 10.0) < 4.5 and getattr(o, "font", "") != "builtin:micro": - issues.append(tr("doc_small_text").format(name=o.name or getattr(o, "text", ""), h=fmt_float(o.height))) - if o.kind == "satin" and getattr(o, "spacing", 0.4) < 0.28: - issues.append(tr("doc_satin_density").format(name=o.name, sp=fmt_float(o.spacing, 2))) - - # 4. Lokale Stichdichte prüfen - cells: dict[tuple[int, int], int] = defaultdict(int) - for b in plan.blocks: - for s in b.stitches: - if s.cmd == Cmd.STITCH: - cells[(int(math.floor(s.x)), int(math.floor(s.y)))] += 1 - hot_cells = sum(1 for c in cells.values() if c > 14) - if hot_cells > 5: - issues.append(tr("doc_density").format(n=hot_cells)) - - if not issues: - issues.append(tr("doc_ok").format(st=fmt_int(plan.stitch_count), n=unique_colors, needles=max_needles, - hoop=design.hoop.display_name)) - return issues diff --git a/openstitch/engine/satin.py b/openstitch/engine/satin.py index 5de6dcc..c462384 100644 --- a/openstitch/engine/satin.py +++ b/openstitch/engine/satin.py @@ -18,7 +18,7 @@ from shapely.prepared import prep from skimage.morphology import skeletonize -from .geom import Pt, clean, dist, polygons_of, resample_path, subdivide +from .geom import Pt, clean, dist, polygons_of, resample_path, resample_uniform, subdivide RES = 0.16 # mm pro Pixel (2.5x schneller bei identischer Stickgenauigkeit) @@ -194,7 +194,7 @@ def extend(p, q, hw): pts = list(reversed(extend(pts[0], pts[step_k], min(br.hw[0], 2.5)))) + pts if br.leaf_end and step_k >= 1: pts = pts + extend(pts[-1], pts[-1 - step_k], min(br.hw[-1], 2.5)) - path = resample_path(pts, spacing / 2.0, closed=closed) + path = resample_uniform(pts, spacing / 2.0, closed=closed) if len(path) < 2: return [] arr = np.array(path) @@ -289,7 +289,8 @@ def _zigzag(cross, max_stitch: float, short_stitch: bool = True) -> list[Pt]: w = dist(prev, target) # Split-Satin bei breiten Säulen (> max_stitch): versetzte Zwischenstiche if w > max_stitch: - nseg = int(math.ceil(w / max_stitch)) + # Der Versatz verlängert ein Teilstück um 17.5 % → auch das muss unter max_stitch bleiben + nseg = int(math.ceil(w * 1.175 / max_stitch)) shift = 0.35 if (i % 2) else -0.35 for k in range(1, nseg): t = max(0.15, min(0.85, (k + shift * 0.5) / nseg)) diff --git a/openstitch/fonts_micro.py b/openstitch/fonts_micro.py index e68c605..fa06d15 100644 --- a/openstitch/fonts_micro.py +++ b/openstitch/fonts_micro.py @@ -77,7 +77,8 @@ def g(ch, adv, *strokes): G[ch] = (adv, [_cat(s) for s in strokes]) # --- Versalien ----------------------------------------------------------- - g("A", 0.76, [(0.06, 0), (0.38, 1), (0.70, 0)], [(0.604, 0.30), (0.156, 0.30)]) + # Querstrich tief: Das obere Dreieck muss bei 2.5 mm offen bleiben + g("A", 0.80, [(0.05, 0), (0.40, 1), (0.75, 0)], [(0.662, 0.25), (0.138, 0.25)]) g("B", 0.66, _cat([(0.10, 0), (0.10, 1), (0.33, 1)], _arc(0.33, 0.765, 0.235, 0.235, 90, -90)), _cat([(0.10, 0.53), (0.36, 0.53)], _arc(0.36, 0.265, 0.265, 0.265, 90, -90), [(0.10, 0)])) g("C", 0.72, _arc(0.40, 0.5, 0.31, 0.5, 45, 315)) @@ -94,7 +95,7 @@ def g(ch, adv, *strokes): g("N", 0.76, [(0.10, 0), (0.10, 1), (0.66, 0), (0.66, 1)]) g("O", 0.82, _arc(0.41, 0.5, 0.33, 0.5, 180, 540)) g("P", 0.64, _cat([(0.10, 0), (0.10, 1), (0.34, 1)], _arc(0.34, 0.75, 0.25, 0.25, 90, -90), [(0.10, 0.5)])) - g("Q", 0.82, _arc(0.41, 0.5, 0.33, 0.5, 180, 540), [(0.50, 0.24), (0.76, -0.06)]) + g("Q", 0.86, _arc(0.41, 0.5, 0.33, 0.5, 180, 540), [(0.44, 0.30), (0.82, -0.14)]) g("R", 0.66, _cat([(0.10, 0), (0.10, 1), (0.34, 1)], _arc(0.34, 0.755, 0.245, 0.245, 90, -90), [(0.10, 0.51)]), [(0.32, 0.51), (0.62, 0)]) g("S", 0.66, _cat(_arc(0.33, 0.75, 0.22, 0.25, 25, 270), _arc(0.33, 0.25, 0.25, 0.25, 90, -155))) @@ -109,11 +110,13 @@ def g(ch, adv, *strokes): # --- Gemeine (x-Höhe 0.70) ----------------------------------------------- bowl_r = _cat([(0.54, 0.56)], _arc(0.31, 0.35, 0.23, 0.35, 40, 320), [(0.54, 0.14)]) # Bauch links vom Stamm bowl_l = _cat([(0.10, 0.14)], _arc(0.33, 0.35, 0.23, 0.35, 220, 500), [(0.10, 0.56)]) # Bauch rechts vom Stamm - g("a", 0.64, [(0.54, 0), (0.54, XH)], bowl_r) + # Stamm mit Fuss: unterscheidet das a im Kleinen vom o + g("a", 0.70, _cat([(0.54, XH), (0.54, 0.10)], _arc(0.64, 0.10, 0.10, 0.10, 180, 300)), bowl_r) g("b", 0.64, [(0.10, 1), (0.10, 0)], bowl_l) g("c", 0.58, _arc(0.32, 0.35, 0.24, 0.35, 42, 318)) g("d", 0.64, bowl_r, [(0.54, 1), (0.54, 0)]) - g("e", 0.62, _cat([(0.10, 0.37), (0.54, 0.37)], _arc(0.32, 0.35, 0.22, 0.35, 5, 318))) + # Querstrich tief: gibt dem Auge des e Platz + g("e", 0.64, _cat([(0.10, 0.31), (0.56, 0.31)], _arc(0.33, 0.35, 0.23, 0.35, -8, 318))) g("f", 0.42, _cat([(0.20, 0), (0.20, 0.78)], _arc(0.34, 0.78, 0.14, 0.20, 180, 40)), [(0.04, 0.66), (0.38, 0.66)]) g("g", 0.64, bowl_r, _cat([(0.54, XH), (0.54, -0.06)], _arc(0.32, -0.06, 0.22, 0.21, 0, -160))) @@ -121,7 +124,8 @@ def g(ch, adv, *strokes): g("i", 0.26, [(0.13, XH), (0.13, 0)], [(0.13, 1.0)]) g("j", 0.32, _cat([(0.20, XH), (0.20, -0.10)], _arc(0.07, -0.10, 0.13, 0.16, 0, -160)), [(0.20, 1.0)]) g("k", 0.60, [(0.10, 0), (0.10, 1)], [(0.50, XH), (0.11, 0.30), (0.53, 0)]) - g("l", 0.26, [(0.13, 1), (0.13, 0)]) + # Mit Bogen unten: sonst ist l nicht von I zu unterscheiden + g("l", 0.32, _cat([(0.13, 1), (0.13, 0.13)], _arc(0.25, 0.13, 0.12, 0.13, 180, 300))) g("m", 0.92, _cat([(0.10, 0), (0.10, 0.47)], _arc(0.255, 0.47, 0.155, 0.23, 180, 0)), _cat([(0.41, 0), (0.41, 0.47)], _arc(0.565, 0.47, 0.155, 0.23, 180, 0), [(0.72, 0)])) g("n", 0.62, _cat([(0.10, 0), (0.10, 0.47)], _arc(0.31, 0.47, 0.21, 0.23, 180, 0), [(0.52, 0)])) @@ -144,7 +148,7 @@ def g(ch, adv, *strokes): g("1", 0.62, [(0.12, 0.78), (0.36, 1), (0.36, 0)]) g("2", 0.62, _cat(_arc(0.31, 0.72, 0.23, 0.26, 155, -35), [(0.08, 0), (0.56, 0)])) g("3", 0.62, _cat(_arc(0.30, 0.76, 0.21, 0.24, 150, -90), _arc(0.30, 0.26, 0.25, 0.26, 90, -150))) - g("4", 0.62, [(0.44, 0), (0.44, 1), (0.04, 0.30), (0.58, 0.30)]) + g("4", 0.66, [(0.47, 0), (0.47, 1), (0.03, 0.24), (0.62, 0.24)]) g("5", 0.62, _cat([(0.53, 1), (0.13, 1), (0.12, 0.56)], _arc(0.31, 0.33, 0.25, 0.33, 135, -150))) g("6", 0.62, six) g("7", 0.62, [(0.06, 1), (0.56, 1), (0.24, 0)]) diff --git a/openstitch/i18n.py b/openstitch/i18n.py index 2dca76e..c1531e8 100644 --- a/openstitch/i18n.py +++ b/openstitch/i18n.py @@ -1,23 +1,42 @@ -"""Mehrsprachige Lokalisierung (DE, EN, FR, ES) für OpenStitch Studio.""" +"""Mehrsprachige Lokalisierung für OpenStitch Studio. + +DE, EN, FR und ES stehen in `_TABLE`. Weitere Sprachen liegen je als eigene Datei in `locales/` und +werden erst geladen, wenn man sie wählt; fehlende Texte fallen auf Englisch zurück.""" from __future__ import annotations -from PySide6.QtCore import QSettings +from PySide6.QtCore import QLocale, QSettings LANGUAGES: list[tuple[str, str]] = [ ("de", "🇩🇪 Deutsch"), ("en", "🇬🇧 English"), ("fr", "🇫🇷 Français"), ("es", "🇪🇸 Español"), + ("it", "🇮🇹 Italiano"), + ("pt", "🇵🇹 Português"), + ("nl", "🇳🇱 Nederlands"), + ("pl", "🇵🇱 Polski"), + ("tr", "🇹🇷 Türkçe"), ] +_SUPPORTED = {code for code, _ in LANGUAGES} +_COLUMN = {"de": 0, "en": 1, "fr": 2, "es": 3} +_extra_cache: dict[str, dict[str, str]] = {} _cur_lang = ["de"] +def extra_table(lang: str) -> dict[str, str]: + """Texte einer Sprache aus `locales/`, geladen erst beim ersten Gebrauch.""" + if lang not in _extra_cache: + from .locales import TABLES + _extra_cache[lang] = TABLES.get(lang, {}) + return _extra_cache[lang] + + def init_lang() -> str: s = QSettings("OpenStitch", "OpenStitchStudio") - lang = s.value("ui/lang", "de", type=str) - if lang not in ("de", "en", "fr", "es"): - lang = "de" + lang = s.value("ui/lang", "", type=str) or QLocale.system().name()[:2] + if lang not in _SUPPORTED: + lang = "en" # Beim ersten Start die Sprache des Systems, sonst Englisch _cur_lang[0] = lang return lang @@ -27,7 +46,7 @@ def current_lang() -> str: def set_lang(lang: str) -> None: - if lang in ("de", "en", "fr", "es"): + if lang in _SUPPORTED: _cur_lang[0] = lang s = QSettings("OpenStitch", "OpenStitchStudio") s.setValue("ui/lang", lang) @@ -49,13 +68,12 @@ def set_lang(lang: str) -> None: "tb_svg": ("SVG", "SVG", "SVG", "SVG"), "tb_export": ("Export", "Export", "Exporter", "Exportar"), "tb_pdf": ("PDF", "PDF", "PDF", "PDF"), - "tb_auto": ("Auto-Digitizer", "Auto-Digitizer", "Auto-Numériseur", "Auto-Digitalizador"), + "tb_auto": ("Bild → Stiche", "Image to stitches", "Image → points", "Imagen a puntadas"), "tb_photo": ("PhotoStitch", "PhotoStitch", "PhotoStitch", "PhotoStitch"), "tb_text": ("Schrift", "Lettering", "Lettrage", "Texto"), "tb_applique": ("Appliqué", "Appliqué", "Appliqué", "Aplique"), "tb_puff": ("3D-Puff", "3D-Puff", "3D-Puff", "3D-Puff"), "tb_transfer": ("Transfer", "Transfer", "Transfert", "Transferir"), - "tb_doctor": ("Doktor", "Doctor", "Docteur", "Doctor"), "tb_tour": ("Rundgang", "Tour", "Visite", "Guía"), # Kontextleiste über der Leinwand @@ -109,13 +127,13 @@ def set_lang(lang: str) -> None: ), # Linkes Dock (Garnkatalog & Farben) - "dock_palette": ("Garnfarben && Nadel-Sequenz", "Thread Catalog && Needle Sequence", "Catalogue Fils && Aiguilles", "Catálogo Hilos && Agujas"), + "dock_palette": ("Garne && Farben", "Threads && Colors", "Fils && couleurs", "Hilos y colores"), "lbl_catalog": ("Garnkatalog:", "Thread Catalog:", "Catalogue :", "Catálogo:"), "lbl_seq": ("Farb- & Nadel-Sequenz im Design:", "Design Thread & Needle Sequence:", "Séquence de couleurs & aiguilles :", "Secuencia de colores y agujas:"), "needle": ("Nadel", "Needle", "Aiguille", "Aguja"), # Rechtes Dock (Ebenen & Inspektor) - "dock_right": ("Ebenen && Objekt-Inspektor", "Layers && Object Inspector", "Calques && Inspecteur d'Objets", "Capas && Inspector de Objetos"), + "dock_right": ("Ebenen && Einstellungen", "Layers && Settings", "Calques && réglages", "Capas y ajustes"), "btn_visible": ("👁 Sichtbar", "👁 Visible", "👁 Visible", "👁 Visible"), "btn_copy": ("⧉ Kopie", "⧉ Copy", "⧉ Copier", "⧉ Copiar"), "lbl_inspector": ("Objekt-Parameter (Live-Neuberechnung):", "Object Parameters (Live Recalculation):", "Paramètres de l'objet (Calcul en direct) :", "Parámetros del objeto (Cálculo en vivo):"), @@ -149,8 +167,10 @@ def tr(key: str) -> str: row = _TABLE.get(key) if not row: return key - idx = {"de": 0, "en": 1, "fr": 2, "es": 3}.get(_cur_lang[0], 0) - return row[idx] + lang = _cur_lang[0] + if lang in _COLUMN: + return row[_COLUMN[lang]] + return extra_table(lang).get(key, row[1]) _TABLE.update({ @@ -170,7 +190,8 @@ def tr(key: str) -> str: "m_applique": ("Aus Fläche Applikation (Appliqué) erzeugen", "Create appliqué from shape", "Créer un appliqué depuis la forme", "Crear aplique desde la forma"), "m_puff": ("3D-Puff-Schaumstoff-Modus für Satin umschalten", "Toggle 3D puff foam mode for satin", "Activer le mode mousse 3D pour le satin", "Activar modo espuma 3D para satén"), "m_transfer": ("Maschinen-Transfer / Diskette / USB / NetBridge …", "Machine transfer / floppy / USB / NetBridge …", "Transfert machine / disquette / USB / NetBridge …", "Transferencia a máquina / disquete / USB / NetBridge …"), - "m_doctor": ("Qualitäts- & Maschinen-Doktor (Prüfung)", "Quality & Machine Doctor (check)", "Docteur qualité & machine (contrôle)", "Doctor de calidad y máquina (revisión)"), + "m_doctor": ("Design prüfen (virtueller Probestick)", "Check design (virtual stitch-out)", + "Vérifier le motif (essai virtuel)", "Revisar diseño (prueba virtual)"), "m_optimize": ("Farben minimieren (Nadelwechsel sparen)", "Minimize colors (save needle changes)", "Minimiser les couleurs (moins de changements)", "Minimizar colores (menos cambios de aguja)"), "m_tour": ("Interaktiver Studio-Rundgang (Onboarding) …", "Interactive studio tour (onboarding) …", "Visite interactive du studio …", "Guía interactiva del estudio …"), "m_restore_logo": ("Offizielles OpenStitch-Logo wiederherstellen", "Restore official OpenStitch logo", "Restaurer le logo officiel OpenStitch", "Restaurar el logotipo oficial de OpenStitch"), @@ -226,64 +247,347 @@ def key_for(german_text: str) -> str | None: }) -# Qualitäts-Doktor _TABLE.update({ - "doc_empty": ("Das Design enthält noch keine Stiche.", "The design has no stitches yet.", - "Le motif ne contient encore aucun point.", "El diseño aún no tiene puntadas."), - "doc_hoop_round": ( - "⚠ RAHMEN-KOLLISIONSGEFAHR: Das Motiv (Radius {r} mm) reicht an den Rand des Rundrahmens ({hoop}, Radius {hr} mm). " - "Wähle einen grösseren Rahmen oder zentriere/verkleinere das Motiv.", - "⚠ HOOP COLLISION RISK: the design (radius {r} mm) reaches the edge of the round hoop ({hoop}, radius {hr} mm). " - "Pick a larger hoop or centre/shrink the design.", - "⚠ RISQUE DE COLLISION AVEC LE CADRE : le motif (rayon {r} mm) atteint le bord du cadre rond ({hoop}, rayon {hr} mm). " - "Choisissez un cadre plus grand ou centrez/réduisez le motif.", - "⚠ RIESGO DE CHOQUE CON EL BASTIDOR: el diseño (radio {r} mm) llega al borde del bastidor redondo ({hoop}, radio {hr} mm). " - "Elige un bastidor mayor o centra/reduce el diseño."), - "doc_hoop_rect": ( - "⚠ RAHMEN-KOLLISIONSGEFAHR: Das Motiv ({w}×{h} mm) überschreitet das sichere Stickfeld des Rahmens ({hw}×{hh} mm).", - "⚠ HOOP COLLISION RISK: the design ({w}×{h} mm) exceeds the hoop's safe sewing field ({hw}×{hh} mm).", - "⚠ RISQUE DE COLLISION AVEC LE CADRE : le motif ({w}×{h} mm) dépasse la zone de broderie sûre du cadre ({hw}×{hh} mm).", - "⚠ RIESGO DE CHOQUE CON EL BASTIDOR: el diseño ({w}×{h} mm) supera el área segura del bastidor ({hw}×{hh} mm)."), - "doc_colors": ( - "⚠ ZU VIELE FARBEN: Das Design verwendet {n} Garnfarben, die Maschine hat {needles} Nadeln. " - "Reduziere die Farben oder plane einen manuellen Garnwechsel ein.", - "⚠ TOO MANY COLOURS: the design uses {n} thread colours but the machine has {needles} needles. " - "Reduce colours or plan a manual thread change.", - "⚠ TROP DE COULEURS : le motif utilise {n} couleurs de fil, la machine a {needles} aiguilles. " - "Réduisez les couleurs ou prévoyez un changement de fil manuel.", - "⚠ DEMASIADOS COLORES: el diseño usa {n} colores de hilo y la máquina tiene {needles} agujas. " - "Reduce los colores o planifica un cambio de hilo manual."), - "doc_small_text": ( - "⚠ KLEINE SCHRIFT ({name}, {h} mm): Umriss-Schriften unter 4.5 mm laufen auf Stoff oft zu. " - "Tipp: Für kleine Schrift die Schriftart „OpenStitch Micro“ verwenden.", - "⚠ SMALL LETTERING ({name}, {h} mm): outline fonts below 4.5 mm tend to fill in on fabric. " - "Tip: use the “OpenStitch Micro” font for small lettering.", - "⚠ PETIT TEXTE ({name}, {h} mm) : sous 4,5 mm, les polices à contour se bouchent souvent sur le tissu. " - "Astuce : utilisez la police « OpenStitch Micro » pour les petits textes.", - "⚠ TEXTO PEQUEÑO ({name}, {h} mm): las fuentes de contorno por debajo de 4,5 mm suelen cerrarse en la tela. " - "Consejo: usa la fuente «OpenStitch Micro» para texto pequeño."), - "doc_satin_density": ( - "⚠ HOHE SATIN-DICHTE ({name}, {sp} mm): Dichte unter 0.28 mm kann zu Fadenbruch führen (empfohlen: 0.36–0.42 mm).", - "⚠ HIGH SATIN DENSITY ({name}, {sp} mm): spacing below 0.28 mm can break threads (recommended: 0.36–0.42 mm).", - "⚠ DENSITÉ SATIN ÉLEVÉE ({name}, {sp} mm) : un espacement sous 0,28 mm peut casser le fil (conseillé : 0,36–0,42 mm).", - "⚠ DENSIDAD DE SATÉN ALTA ({name}, {sp} mm): un espaciado inferior a 0,28 mm puede romper el hilo " - "(recomendado: 0,36–0,42 mm)."), - "doc_density": ( - "⚠ DICHTE-SPITZEN: An {n} Stellen (1×1 mm) liegen mehr als 14 Stiche übereinander " - "(Strg+H zeigt die Heatmap).", - "⚠ DENSITY HOT SPOTS: {n} places (1×1 mm) have more than 14 stitches on top of each other " - "(Ctrl+H shows the heatmap).", - "⚠ PICS DE DENSITÉ : {n} zones (1×1 mm) comptent plus de 14 points superposés " - "(Ctrl+H affiche la carte de densité).", - "⚠ PICOS DE DENSIDAD: en {n} puntos (1×1 mm) hay más de 14 puntadas superpuestas " - "(Ctrl+H muestra el mapa de calor)."), - "doc_ok": ( - "✅ Keine Probleme gefunden ({st} Stiche, {n} von {needles} Nadeln, sicher im Rahmen {hoop}).", - "✅ No problems found ({st} stitches, {n} of {needles} needles, safely inside {hoop}).", - "✅ Aucun problème détecté ({st} points, {n} aiguilles sur {needles}, bien dans le cadre {hoop}).", - "✅ No se encontraron problemas ({st} puntadas, {n} de {needles} agujas, dentro del bastidor {hoop})."), + "ph_text": ("Dein Text", "Your text", "Votre texte", "Tu texto"), + "tip_use_micro": ("Für so kleine Schrift besser „OpenStitch Micro“ verwenden (ein Klick hier)", + "For lettering this small, use “OpenStitch Micro” (click here)", + "Pour un texte aussi petit, utilisez « OpenStitch Micro » (cliquez ici)", + "Para un texto tan pequeño, usa «OpenStitch Micro» (haz clic aquí)"), +}) + +# Hilfe, Fehlerbericht +_TABLE.update({ + "act_shortcuts": ("Tastenkürzel …", "Keyboard shortcuts …", "Raccourcis clavier …", "Atajos de teclado …"), + "act_report": ("Problem melden …", "Report a problem …", "Signaler un problème …", "Informar de un problema …"), + "act_about": ("Über OpenStitch …", "About OpenStitch …", "À propos d'OpenStitch …", "Acerca de OpenStitch …"), + "about_text": ("Freie Stick- und Digitalisier-Software. Lizenz: AGPL-3.0, der Quellcode ist frei verfügbar.", + "Free embroidery and digitizing software. License: AGPL-3.0, the source code is freely available.", + "Logiciel libre de broderie et de numérisation. Licence : AGPL-3.0, le code source est librement disponible.", + "Software libre de bordado y digitalización. Licencia: AGPL-3.0, el código fuente está disponible."), + "keys_title": ("Tastenkürzel", "Keyboard shortcuts", "Raccourcis clavier", "Atajos de teclado"), + "key_select": ("Auswählen und verschieben", "Select and move", "Sélectionner et déplacer", "Seleccionar y mover"), + "key_nodes": ("Knoten bearbeiten", "Edit nodes", "Modifier les nœuds", "Editar nodos"), + "key_fill": ("Fläche zeichnen", "Draw fill", "Dessiner un remplissage", "Dibujar relleno"), + "key_satin": ("Satinsäule zeichnen", "Draw satin column", "Dessiner une colonne satin", "Dibujar columna de satén"), + "key_run": ("Steppstich zeichnen", "Draw running stitch", "Dessiner un point droit", "Dibujar puntada recta"), + "key_finish": ("Zeichnen beenden", "Finish drawing", "Terminer le dessin", "Terminar el dibujo"), + "key_cancel": ("Zeichnen abbrechen", "Cancel drawing", "Annuler le dessin", "Cancelar el dibujo"), + "key_zoom": ("Zoomen", "Zoom", "Zoomer", "Ampliar"), + "key_pan": ("Ansicht verschieben", "Pan the view", "Déplacer la vue", "Desplazar la vista"), + "key_wheel": ("Mausrad", "Mouse wheel", "Molette", "Rueda del ratón"), + "key_middle": ("Mittlere Maustaste", "Middle mouse button", "Bouton central", "Botón central"), + "crash_title": ("Das hätte nicht passieren dürfen", "That should not have happened", "Cela n'aurait pas dû arriver", + "Esto no debería haber pasado"), + "crash_text": ("OpenStitch hat einen Fehler bemerkt. Deine Arbeit wurde gesichert und du kannst weitermachen.\n\n" + "Wenn du das Problem melden möchtest, hänge bitte diese Datei an:\n{}", + "OpenStitch ran into an error. Your work was saved and you can carry on.\n\n" + "If you would like to report it, please attach this file:\n{}", + "OpenStitch a rencontré une erreur. Votre travail a été sauvegardé et vous pouvez continuer.\n\n" + "Pour la signaler, joignez ce fichier :\n{}", + "OpenStitch encontró un error. Tu trabajo se guardó y puedes continuar.\n\n" + "Si quieres informar del problema, adjunta este archivo:\n{}"), }) +# An die Maschine senden +_TABLE.update({ + "exp_title": ("An die Maschine senden", "Send to machine", "Envoyer à la machine", "Enviar a la máquina"), + "exp_heading": ("Fertig zum Sticken?", "Ready to stitch?", "Prêt à broder ?", "¿Listo para bordar?"), + "exp_facts": ("{st} Stiche · {colors} Farben · {w} × {h} mm", "{st} stitches · {colors} colors · {w} × {h} mm", + "{st} points · {colors} couleurs · {w} × {h} mm", "{st} puntadas · {colors} colores · {w} × {h} mm"), + "exp_format": ("Dateiformat:", "File format:", "Format de fichier :", "Formato de archivo:"), + "exp_recommended": ("{} (empfohlen)", "{} (recommended)", "{} (recommandé)", "{} (recomendado)"), + "exp_name": ("Dateiname:", "File name:", "Nom du fichier :", "Nombre de archivo:"), + "exp_short": ("Kurzer Name für ältere Maschinen", "Short name for older machines", + "Nom court pour machines anciennes", "Nombre corto para máquinas antiguas"), + "exp_short_tip": ("Viele ältere Maschinen zeigen nur 8 Zeichen ohne Umlaute an.", + "Many older machines only show 8 plain characters.", + "Beaucoup de machines anciennes n'affichent que 8 caractères simples.", + "Muchas máquinas antiguas solo muestran 8 caracteres simples."), + "exp_where": ("Speichern auf:", "Save to:", "Enregistrer sur :", "Guardar en:"), + "exp_usb": ("USB-Stick: {}", "USB stick: {}", "Clé USB : {}", "Memoria USB: {}"), + "exp_browse": ("Ordner …", "Folder …", "Dossier …", "Carpeta …"), + "exp_refresh": ("Aktualisieren", "Refresh", "Actualiser", "Actualizar"), + "exp_threads": ("Garnfolge für die Maschine", "Thread order for the machine", "Ordre des fils pour la machine", + "Orden de hilos para la máquina"), + "exp_save": ("Speichern", "Save", "Enregistrer", "Guardar"), + "exp_done": ("„{name}“ gespeichert und geprüft: {st} Stiche korrekt gelesen. Jetzt den Stick an die Maschine stecken.", + "“{name}” saved and verified: {st} stitches read back correctly. Now plug the stick into your machine.", + "« {name} » enregistré et vérifié : {st} points relus correctement. Branchez la clé sur la machine.", + "«{name}» guardado y verificado: {st} puntadas leídas correctamente. Conecta la memoria a la máquina."), + "exp_overwrite": ("„{}“ gibt es dort schon. Ersetzen?", "“{}” already exists there. Replace it?", + "« {} » existe déjà à cet endroit. Le remplacer ?", "«{}» ya existe ahí. ¿Reemplazarlo?"), + "exp_done_plain": ("„{name}“ gespeichert.", "“{name}” saved.", "« {name} » enregistré.", "«{name}» guardado."), + "exp_failed": ("Speichern fehlgeschlagen: {}", "Could not save: {}", "Échec de l'enregistrement : {}", + "No se pudo guardar: {}"), + "btn_close": ("Schliessen", "Close", "Fermer", "Cerrar"), +}) + +# Feste Regeln, Schätzungen und Kalibrierung +_TABLE.update({ + 'chk_tag_rule': ('Feste Regel', + 'Fixed rule', + 'Règle fixe', + 'Regla fija'), + 'chk_tag_model': ('Schätzung', + 'Estimate', + 'Estimation', + 'Estimación'), + 'cal_open': ('Mit echtem Stoff kalibrieren …', + 'Calibrate with real fabric …', + 'Calibrer avec du vrai tissu …', + 'Calibrar con tela real …'), + 'cal_title': ('Stoff kalibrieren', + 'Calibrate fabric', + 'Calibrer le tissu', + 'Calibrar tela'), + 'cal_intro': ('1. Testbalken laden und mit Stoff, Vlies und Fadenspannung sticken, die du wirklich verwendest.\n2. Breite in der Mitte des Balkens messen. Geplant sind {width} mm.\n3. Messwert eintragen. Simulation und Zugausgleich rechnen dann mit deinem echten Wert.', + '1. Load the test bar and stitch it with the fabric, stabilizer and tension you really use.\n2. Measure the width in the middle of the bar. It is planned at {width} mm.\n3. Enter the measurement. The simulation and pull compensation then use your real value.', + '1. Chargez la barre de test et brodez-la avec le tissu, le stabilisateur et la tension que vous utilisez vraiment.\n2. Mesurez la largeur au milieu de la barre. Elle est prévue à {width} mm.\n3. Saisissez la mesure. La simulation et la compensation utilisent alors votre valeur réelle.', + '1. Carga la barra de prueba y bórdala con la tela, el estabilizador y la tensión que usas de verdad.\n2. Mide el ancho en el centro de la barra. Está prevista de {width} mm.\n3. Introduce la medida. La simulación y la compensación usarán tu valor real.'), + 'cal_load': ('Testbalken laden', + 'Load test bar', + 'Charger la barre de test', + 'Cargar barra de prueba'), + 'cal_measured': ('Gemessene Breite:', + 'Measured width:', + 'Largeur mesurée :', + 'Ancho medido:'), + 'cal_apply': ('Übernehmen', + 'Apply', + 'Appliquer', + 'Aplicar'), + 'cal_reset': ('Zurücksetzen', + 'Reset', + 'Réinitialiser', + 'Restablecer'), + 'cal_state_estimate': ('Dieser Stoff ist noch nicht gemessen: Der Stoffzug ist eine Schätzung.', + 'This fabric has not been measured yet: fabric pull is an estimate.', + "Ce tissu n'a pas encore été mesuré : la traction est une estimation.", + 'Esta tela aún no se ha medido: el tiro es una estimación.'), + 'cal_state_measured': ('Gemessen: Der Stoffzug ist das {factor}-Fache der Schätzung.', + 'Measured: fabric pull is {factor} times the estimate.', + "Mesuré : la traction vaut {factor} fois l'estimation.", + 'Medido: el tiro es {factor} veces la estimación.'), + 'chk_disclaimer': ('Feste Regeln folgen exakt aus den Stichen. Schätzungen zum Stoffzug werden genau, wenn du den Stoff kalibrierst.', + 'Fixed rules follow exactly from the stitches. Fabric pull estimates become accurate once you calibrate the fabric.', + 'Les règles fixes découlent exactement des points. Les estimations de traction deviennent précises une fois le tissu calibré.', + 'Las reglas fijas se derivan exactamente de las puntadas. Las estimaciones del tiro son precisas al calibrar la tela.'), +}) + +# Design-Prüfung (virtueller Probestick) +_TABLE.update({ + "chk_title": ("Design prüfen", "Check design", "Vérifier le motif", "Revisar diseño"), + "chk_running": ("Wird geprüft …", "Checking …", "Vérification …", "Revisando …"), + "chk_failed": ("Prüfung fehlgeschlagen", "Check failed", "Échec de la vérification", "Falló la revisión"), + "chk_empty": ("Noch keine Stiche", "No stitches yet", "Aucun point pour l'instant", "Aún no hay puntadas"), + "chk_again": ("Erneut prüfen", "Check again", "Vérifier à nouveau", "Revisar de nuevo"), + "chk_good": ("Bereit zum Sticken", "Ready to stitch", "Prêt à broder", "Listo para bordar"), + "chk_ok": ("Stickbar, mit kleinen Risiken", "Stitchable, with small risks", "Brodable, avec de petits risques", + "Bordable, con pequeños riesgos"), + "chk_bad": ("Besser zuerst überarbeiten", "Better fix this first", "À corriger d'abord", "Mejor corregirlo antes"), + "chk_none": ("Keine Probleme gefunden.", "No problems found.", "Aucun problème détecté.", + "No se encontraron problemas."), + "chk_facts": ("{st} Stiche · {colors} Farben · {trims} Fadenschnitte · ca. {min} Min. · {thread} m Garn", + "{st} stitches · {colors} colors · {trims} trims · about {min} min · {thread} m thread", + "{st} points · {colors} couleurs · {trims} coupes · env. {min} min · {thread} m de fil", + "{st} puntadas · {colors} colores · {trims} cortes · aprox. {min} min · {thread} m de hilo"), + "chk_preview": ("So zieht sich der Stoff zusammen", "How the fabric will pull in", + "Comment le tissu va se resserrer", "Cómo se encogerá la tela"), + "chk_boost": ("Effekt verstärken", "Exaggerate effect", "Amplifier l'effet", "Exagerar el efecto"), + "chk_show": ("Zeigen", "Show", "Afficher", "Mostrar"), + "chk_fix": ("Beheben", "Fix", "Corriger", "Corregir"), + "undo_fix": ("Automatische Korrektur", "Automatic fix", "Correction automatique", "Corrección automática"), + "chk_sev_error": ("Problem", "Problem", "Problème", "Problema"), + "chk_sev_warning": ("Warnung", "Warning", "Avertissement", "Aviso"), + "chk_sev_info": ("Hinweis", "Note", "Remarque", "Nota"), + "chk_short_stitch_t": ("Sehr kurze Stiche", "Very short stitches", "Points très courts", "Puntadas muy cortas"), + "chk_short_stitch_d": ("Anzahl unter 0,3 mm: {count}. Die Nadel trifft fast dasselbe Loch, der Faden kann reissen.", + "Stitches under 0.3 mm: {count}. The needle nearly hits the same hole and the thread can break.", + "Points de moins de 0,3 mm : {count}. L'aiguille repique presque au même endroit et le fil peut casser.", + "Puntadas de menos de 0,3 mm: {count}. La aguja casi repite el agujero y el hilo puede romperse."), + "chk_over_max_stitch_t": ("Stiche zu lang für die Maschine", "Stitches too long for the machine", + "Points trop longs pour la machine", "Puntadas demasiado largas para la máquina"), + "chk_over_max_stitch_d": ("{count} Stiche überschreiten die Maschinengrenze (längster: {max_mm} mm).", + "{count} stitches exceed the machine limit (longest: {max_mm} mm).", + "{count} points dépassent la limite de la machine (le plus long : {max_mm} mm).", + "{count} puntadas superan el límite de la máquina (la más larga: {max_mm} mm)."), + "chk_long_float_t": ("Lange lose Stiche", "Long loose stitches", "Longs points lâches", "Puntadas largas y sueltas"), + "chk_long_float_d": ("{count} Stiche sind länger als 7,5 mm (bis {max_mm} mm). Sie bleiben im Alltag leicht hängen.", + "{count} stitches are longer than 7.5 mm (up to {max_mm} mm). They snag easily in daily use.", + "{count} points dépassent 7,5 mm (jusqu'à {max_mm} mm). Ils s'accrochent facilement à l'usage.", + "{count} puntadas superan 7,5 mm (hasta {max_mm} mm). Se enganchan fácilmente con el uso."), + "chk_no_lock_t": ("Fadenenden nicht vernäht", "Thread ends not locked", "Extrémités de fil non arrêtées", + "Extremos de hilo sin rematar"), + "chk_no_lock_d": ("An {count} Stellen fehlen Vernähstiche. Dort kann sich die Stickerei beim Waschen lösen.", + "{count} places have no lock stitches. The embroidery can come loose there when washed.", + "{count} endroits sans points d'arrêt. La broderie peut s'y défaire au lavage.", + "{count} lugares sin puntadas de remate. El bordado puede soltarse ahí al lavarlo."), + "chk_orphan_run_t": ("Zu kurze Abschnitte", "Sections too short", "Sections trop courtes", "Secciones demasiado cortas"), + "chk_orphan_run_d": ("{count} Abschnitte haben weniger als 3 Stiche und halten nach dem Fadenschnitt kaum.", + "{count} sections have fewer than 3 stitches and barely hold after the thread is cut.", + "{count} sections ont moins de 3 points et tiennent mal après la coupe du fil.", + "{count} secciones tienen menos de 3 puntadas y apenas aguantan tras cortar el hilo."), + "chk_untrimmed_jump_t": ("Sprünge ohne Fadenschnitt", "Jumps without a trim", "Sauts sans coupe de fil", + "Saltos sin corte de hilo"), + "chk_untrimmed_jump_d": ("{count} Sprünge lassen einen Faden quer über dem Motiv liegen.", + "{count} jumps leave a thread lying across the design.", + "{count} sauts laissent un fil en travers du motif.", + "{count} saltos dejan un hilo cruzando el diseño."), + "chk_needle_pileup_t": ("Zu viele Einstiche an einem Punkt", "Too many needle hits in one spot", + "Trop de piqûres au même endroit", "Demasiadas puntadas en un punto"), + "chk_needle_pileup_d": ("An {count} Stellen sticht die Nadel bis zu {max_hits}-mal ein. Das kann Stoff und Nadel beschädigen.", + "In {count} places the needle hits up to {max_hits} times. This can damage fabric and needle.", + "À {count} endroits l'aiguille pique jusqu'à {max_hits} fois. Cela peut abîmer le tissu et l'aiguille.", + "En {count} lugares la aguja entra hasta {max_hits} veces. Puede dañar la tela y la aguja."), + "chk_too_dense_t": ("Zu dicht gestickt", "Stitched too densely", "Broderie trop dense", "Bordado demasiado denso"), + "chk_too_dense_d": ("An {count} mm² liegen bis zu {peak} Fadenlagen (Grenze für diesen Stoff: {limit}). Die Stelle wird brettartig.", + "{count} mm² carry up to {peak} thread layers (limit for this fabric: {limit}). The area turns board-stiff.", + "{count} mm² portent jusqu'à {peak} couches de fil (limite pour ce tissu : {limit}). La zone devient rigide.", + "{count} mm² llevan hasta {peak} capas de hilo (límite de esta tela: {limit}). La zona queda rígida."), + "chk_outside_hoop_t": ("Motiv passt nicht in den Rahmen", "Design does not fit the hoop", + "Le motif ne tient pas dans le cadre", "El diseño no cabe en el bastidor"), + "chk_outside_hoop_d": ("Stiche liegen im Randbereich des Rahmens. Die Nadel kann den Rahmen treffen.", + "Stitches lie in the edge zone of the hoop. The needle could hit the hoop.", + "Des points se trouvent en bordure du cadre. L'aiguille pourrait le toucher.", + "Hay puntadas en el borde del bastidor. La aguja podría golpearlo."), + "chk_low_coverage_t": ("Stoff scheint durch", "Fabric shows through", "Le tissu transparaît", "Se ve la tela"), + "chk_low_coverage_d": ("„{object}“ ist nur zu {percent} % bedeckt.", "“{object}” is only {percent}% covered.", + "« {object} » n'est couvert qu'à {percent} %.", "«{object}» solo está cubierto al {percent} %."), + "chk_too_many_colors_t": ("Mehr Farben als Nadeln", "More colors than needles", "Plus de couleurs que d'aiguilles", + "Más colores que agujas"), + "chk_too_many_colors_d": ("{count} Farben bei {needles} Nadeln: Du musst unterwegs den Faden wechseln.", + "{count} colors on {needles} needles: you will change thread along the way.", + "{count} couleurs pour {needles} aiguilles : il faudra changer de fil en cours de route.", + "{count} colores con {needles} agujas: tendrás que cambiar de hilo durante el bordado."), + "chk_registration_gap_t": ("Lücken zwischen Objekten möglich", "Gaps between objects are likely", + "Risque d'espaces entre les objets", "Posibles huecos entre objetos"), + "chk_registration_gap_d": ("Der Stoffzug verschiebt Teile um bis zu {mm} mm gegeneinander. Mehr Zugausgleich hilft.", + "Fabric pull shifts parts by up to {mm} mm against each other. More pull compensation helps.", + "La traction du tissu décale des parties jusqu'à {mm} mm. Plus de compensation aide.", + "El tiro de la tela desplaza partes hasta {mm} mm. Más compensación ayuda."), + "chk_puckering_t": ("Stoff kann Wellen werfen", "Fabric may pucker", "Le tissu peut godailler", "La tela puede fruncirse"), + "chk_puckering_d": ("Die Stickerei zieht den Stoff um rund {mm} mm zusammen. Verwende ein festeres Vlies.", + "The embroidery pulls the fabric in by about {mm} mm. Use a firmer stabilizer.", + "La broderie resserre le tissu d'environ {mm} mm. Utilisez un stabilisateur plus ferme.", + "El bordado encoge la tela unos {mm} mm. Usa un estabilizador más firme."), + "chk_small_text_t": ("Schrift zu klein für diese Schriftart", "Lettering too small for this font", + "Texte trop petit pour cette police", "Texto demasiado pequeño para esta fuente"), + "chk_small_text_d": ("„{object}“ ist {mm} mm hoch. Umriss-Schriften laufen so klein zu. Nimm „OpenStitch Micro“.", + "“{object}” is {mm} mm tall. Outline fonts fill in at this size. Use “OpenStitch Micro”.", + "« {object} » mesure {mm} mm. Les polices à contour se bouchent à cette taille. Utilisez « OpenStitch Micro ».", + "«{object}» mide {mm} mm. Las fuentes de contorno se cierran a este tamaño. Usa «OpenStitch Micro»."), + "chk_export_ok_t": ("{ext}-Datei geprüft", "{ext} file verified", "Fichier {ext} vérifié", "Archivo {ext} verificado"), + "chk_export_ok_d": ("{st} Stiche neu eingelesen, grösste Abweichung {err} mm.", + "{st} stitches read back, largest error {err} mm.", + "{st} points relus, écart maximal {err} mm.", + "{st} puntadas releídas, desviación máxima {err} mm."), + "chk_export_bad_t": ("Problem in der {ext}-Datei", "Problem in the {ext} file", "Problème dans le fichier {ext}", + "Problema en el archivo {ext}"), +}) + +# Startseite, Stoffe, neue Oberfläche +_TABLE.update({ + "tb_open": ("Öffnen", "Open", "Ouvrir", "Abrir"), + "tb_save": ("Speichern", "Save", "Enregistrer", "Guardar"), + "tb_check": ("Prüfen", "Check", "Vérifier", "Revisar"), + "act_home": ("Startseite anzeigen", "Show start page", "Afficher la page d'accueil", "Mostrar página de inicio"), + "act_theme_dark": ("Dunkles Design", "Dark theme", "Thème sombre", "Tema oscuro"), + "act_theme_light": ("Helles Design", "Light theme", "Thème clair", "Tema claro"), + "menu_recent": ("Zuletzt geöffnet", "Open recent", "Fichiers récents", "Abrir reciente"), + "lbl_fabric": ("Stoff:", "Fabric:", "Tissu :", "Tela:"), + "fab_woven": ("Baumwolle / Hemd (gewebt)", "Cotton / shirt (woven)", "Coton / chemise (tissé)", + "Algodón / camisa (tejido)"), + "fab_denim": ("Jeans / Canvas", "Denim / canvas", "Denim / toile", "Vaquero / lona"), + "fab_twill_cap": ("Kappe (Twill)", "Cap (twill)", "Casquette (sergé)", "Gorra (sarga)"), + "fab_pique": ("Polo-Piqué", "Polo piqué", "Piqué polo", "Piqué de polo"), + "fab_jersey": ("T-Shirt (Jersey)", "T-shirt (jersey)", "T-shirt (jersey)", "Camiseta (punto)"), + "fab_fleece": ("Fleece / Sweatshirt", "Fleece / sweatshirt", "Polaire / sweat", "Polar / sudadera"), + "fab_towel": ("Frottee / Handtuch", "Terry / towel", "Éponge / serviette", "Rizo / toalla"), + "fab_leather": ("Leder", "Leather", "Cuir", "Cuero"), + "fab_silk": ("Seide / feiner Stoff", "Silk / fine fabric", "Soie / tissu fin", "Seda / tela fina"), + "stab_cutaway": ("Schneidvlies", "cut-away stabilizer", "stabilisateur à découper", "estabilizador recortable"), + "stab_tearaway": ("Reissvlies", "tear-away stabilizer", "stabilisateur à déchirer", "estabilizador desprendible"), + "stab_none": ("kein Vlies", "no stabilizer", "pas de stabilisateur", "sin estabilizador"), + "fabric_advice": ("{fabric}: {stabilizer} verwenden, Nadel {needle}. Dichte und Zugausgleich sind angepasst.", + "{fabric}: use {stabilizer}, needle {needle}. Density and pull compensation are adjusted.", + "{fabric} : utilisez un {stabilizer}, aiguille {needle}. Densité et compensation ajustées.", + "{fabric}: usa {stabilizer}, aguja {needle}. Densidad y compensación ajustadas."), + "fabric_topping": ("Obenauf wasserlösliche Folie legen, damit die Stiche nicht einsinken.", + "Put water-soluble topping on top so stitches do not sink in.", + "Posez un film soluble dessus pour que les points ne s'enfoncent pas.", + "Coloca film soluble encima para que las puntadas no se hundan."), + "tip_obj_visible": ("Objekt ein- oder ausblenden", "Show or hide object", "Afficher ou masquer l'objet", + "Mostrar u ocultar objeto"), + "tip_obj_copy": ("Objekt duplizieren", "Duplicate object", "Dupliquer l'objet", "Duplicar objeto"), + "param_knockout": ("Verdecktes nicht sticken", "Skip hidden parts", "Ignorer les parties cachées", + "Omitir partes ocultas"), + "canvas_empty_hint": ("Bild hierher ziehen oder links ein Zeichenwerkzeug wählen", + "Drop an image here or pick a drawing tool on the left", + "Déposez une image ici ou choisissez un outil de dessin à gauche", + "Suelta una imagen aquí o elige una herramienta de dibujo a la izquierda"), + "start_title": ("Was möchtest du sticken?", "What would you like to embroider?", + "Que souhaitez-vous broder ?", "¿Qué te gustaría bordar?"), + "start_subtitle": ("Wähle einen Einstieg. Du brauchst keine Vorkenntnisse.", + "Pick a starting point. No experience needed.", + "Choisissez un point de départ. Aucune expérience requise.", + "Elige un punto de partida. No necesitas experiencia."), + "start_image": ("Bild in Stickerei umwandeln", "Turn an image into embroidery", "Transformer une image en broderie", + "Convertir una imagen en bordado"), + "start_image_d": ("Logo oder Zeichnung wählen, den Rest erledigt OpenStitch.", + "Pick a logo or drawing and OpenStitch does the rest.", + "Choisissez un logo ou un dessin, OpenStitch fait le reste.", + "Elige un logotipo o dibujo y OpenStitch hará el resto."), + "start_text": ("Text sticken", "Embroider text", "Broder du texte", "Bordar texto"), + "start_text_d": ("Name oder Schriftzug, sauber lesbar ab 2,5 mm Höhe.", + "A name or slogan, cleanly readable from 2.5 mm tall.", + "Un nom ou un slogan, lisible dès 2,5 mm de haut.", + "Un nombre o lema, legible desde 2,5 mm de alto."), + "start_draw": ("Selbst zeichnen", "Draw it yourself", "Dessiner vous-même", "Dibujar tú mismo"), + "start_draw_d": ("Flächen, Satinsäulen und Linien mit der Maus zeichnen.", + "Draw fills, satin columns and lines with the mouse.", + "Dessinez des remplissages, colonnes satin et lignes à la souris.", + "Dibuja rellenos, columnas de satén y líneas con el ratón."), + "start_open": ("Datei öffnen", "Open a file", "Ouvrir un fichier", "Abrir un archivo"), + "start_open_d": ("Projekt, Stickdatei (DST, PES, JEF …), SVG oder Bild.", + "Project, embroidery file (DST, PES, JEF …), SVG or image.", + "Projet, fichier de broderie (DST, PES, JEF …), SVG ou image.", + "Proyecto, archivo de bordado (DST, PES, JEF …), SVG o imagen."), + "start_samples": ("Oder mit einem Beispiel anfangen", "Or start from an example", + "Ou commencez par un exemple", "O empieza con un ejemplo"), + "start_recent": ("Zuletzt geöffnet", "Recent files", "Fichiers récents", "Archivos recientes"), + "start_tour": ("Kurze Einführung ansehen", "Take a short tour", "Suivre une courte visite", + "Ver una breve introducción"), + "sample_patch": ("Namensschild", "Name patch", "Écusson prénom", "Parche con nombre"), + "sample_heart": ("Herz", "Heart", "Cœur", "Corazón"), + "sample_flower": ("Blume", "Flower", "Fleur", "Flor"), + "sample_monogram": ("Monogramm", "Monogram", "Monogramme", "Monograma"), + "fd_open_any": ("Datei öffnen", "Open file", "Ouvrir un fichier", "Abrir archivo"), + "filter_supported": ("Alle unterstützten Dateien", "All supported files", "Tous les fichiers pris en charge", + "Todos los archivos compatibles"), + "err_file_gone": ("Die Datei wurde nicht gefunden:\n{}", "The file was not found:\n{}", + "Fichier introuvable :\n{}", "No se encontró el archivo:\n{}"), + "err_unknown_type": ("„{}“ hat einen Dateityp, den OpenStitch nicht kennt.", + "“{}” has a file type OpenStitch does not know.", + "« {} » a un type de fichier inconnu d'OpenStitch.", + "«{}» tiene un tipo de archivo que OpenStitch no conoce."), + "dlg_recover_title": ("Arbeit wiederherstellen?", "Restore your work?", "Restaurer votre travail ?", + "¿Restaurar tu trabajo?"), + "dlg_recover_text": ("OpenStitch wurde nicht sauber beendet. Möchtest du die letzte automatische Sicherung öffnen?", + "OpenStitch did not close properly. Open the last automatic backup?", + "OpenStitch ne s'est pas fermé correctement. Ouvrir la dernière sauvegarde automatique ?", + "OpenStitch no se cerró correctamente. ¿Abrir la última copia automática?"), + "status_autosave_failed": ("Automatisches Speichern fehlgeschlagen: {}", "Autosave failed: {}", + "Échec de l'enregistrement automatique : {}", "Falló el guardado automático: {}"), +}) + +# Fehlermeldungen beim Laden +_TABLE.update({ + "err_project_damaged": ( + "„{name}“ ist beschädigt oder keine OpenStitch-Projektdatei.", + "“{name}” is damaged or not an OpenStitch project file.", + "« {name} » est endommagé ou n'est pas un fichier de projet OpenStitch.", + "«{name}» está dañado o no es un archivo de proyecto de OpenStitch."), +}) def tr_all(key: str) -> list[str]: return list(_TABLE.get(key, (key,) * 4)) @@ -296,8 +600,8 @@ def tr_opt(key: str, fallback: str) -> str: # Zahlenformat je Sprache: Tausendertrennzeichen und Dezimalzeichen # (de: Schweizer Apostroph, fr: schmales geschütztes Leerzeichen) -_GROUP_SEP = {"de": "’", "en": ",", "fr": " ", "es": "."} -_DEC_SEP = {"de": ".", "en": ".", "fr": ",", "es": ","} +_GROUP_SEP = {"de": "’", "en": ",", "fr": " ", "es": ".", "it": ".", "pt": "\u00a0", "nl": ".", "pl": "\u00a0", "tr": "."} +_DEC_SEP = {"de": ".", "en": ".", "fr": ",", "es": ",", "it": ",", "pt": ",", "nl": ",", "pl": ",", "tr": ","} def fmt_int(n) -> str: @@ -445,8 +749,6 @@ def fmt_float(x: float, decimals: int = 1) -> str: "Please select a fill or satin shape on the canvas first.", "Veuillez d'abord sélectionner une forme sur le canevas.", "Primero selecciona una forma en el lienzo."), - "msg_doctor_title": ("Qualitäts- & Maschinen-Doktor", "Quality & Machine Doctor", - "Docteur qualité & machine", "Doctor de calidad y máquina"), "msg_export_verified_title": ("Export & Binär-Verifikation erfolgreich", "Export & binary verification successful", "Export et vérification binaire réussis", "Exportación y verificación binaria correctas"), @@ -870,3 +1172,6 @@ def machine_display_name(name: str) -> str: "Séquence de couleurs et attribution des aiguilles ({} aiguilles)", "Secuencia de colores y asignación de agujas ({} agujas)"), }) + +from .i18n_tour import TOUR_TABLE # noqa: E402 +_TABLE.update(TOUR_TABLE) diff --git a/openstitch/i18n_tour.py b/openstitch/i18n_tour.py new file mode 100644 index 0000000..3a84b5d --- /dev/null +++ b/openstitch/i18n_tour.py @@ -0,0 +1,230 @@ +"""Übersetzungen des Studio-Rundgangs (DE, EN, FR, ES). + +Eigene Datei, damit die langen Rundgang-Texte i18n.py nicht aufblähen. Die Tabelle wird am Ende von +i18n.py in `_TABLE` übernommen. Die Texte sind Rich Text: `` & Co. sind erlaubt, ein `&` im Fliesstext +wird als `&` geschrieben. Bezeichnungen wie "Prüfen" müssen zu den Knöpfen der Oberfläche passen. +""" +from __future__ import annotations + +TOUR_TABLE: dict[str, tuple[str, str, str, str]] = { + # Gemeinsame Bedienelemente + "tour_next": ("Weiter →", "Next →", "Suivant →", "Siguiente →"), + "tour_prev_tip": ("Vorheriger Schritt", "Previous step", "Étape précédente", "Paso anterior"), + "tour_close_tip": ("Rundgang schliessen (Esc)", "Close the tour (Esc)", "Fermer la visite (Échap)", + "Cerrar la guía (Esc)"), + "tour_on_start": ("Beim Start", "At startup", "Au démarrage", "Al iniciar"), + "tour_done": ("Fertig ✓", "Done ✓", "Terminé ✓", "Listo ✓"), + + # Rundgang als eigenes Fenster + + + + + + + # Rundgang direkt im Hauptfenster + "tour_app_1_badge": ("WILLKOMMEN · 1 / 7", "WELCOME · 1 / 7", "BIENVENUE · 1 / 7", "BIENVENIDA · 1 / 7"), + "tour_app_1_title": ("Die Leinwand: dein Design in 3D", "The canvas: your design in 3D", + "Le canevas : votre motif en 3D", "El lienzo: tu diseño en 3D"), + "tour_app_1_body": ( + "In der Mitte liegt dein Design im Stickrahmen, zum Start unser OpenStitch-Wappen.

" + "• Klicken und ziehen: Objekte auswählen, verschieben oder am Eckgriff skalieren.
" + "• Mausrad: Stufenlos bis auf einzelne Einstiche hineinzoomen.", + "Your design sits in the hoop in the middle. To start with, that is our " + "OpenStitch crest.

" + "• Click and drag: select parts, move them, or resize them with the corner handle.
" + "• Mouse wheel: zoom in smoothly, right down to single stitches.", + "Votre motif apparaît au centre, dans le cadre. Pour commencer, c'est notre " + "blason OpenStitch.

" + "• Cliquer et glisser : sélectionnez des éléments, déplacez-les ou redimensionnez-les avec " + "la poignée d'angle.
" + "• Molette de la souris : zoomez en douceur jusqu'à voir chaque point.", + "Tu diseño aparece en el centro, dentro del bastidor. Para empezar, es nuestro " + "escudo de OpenStitch.

" + "• Clic y arrastrar: selecciona partes, muévelas o cambia su tamaño con el tirador de la " + "esquina.
" + "• Rueda del ratón: acerca la vista poco a poco hasta ver cada puntada.", + ), + "tour_app_1_action": ("🎨 Stofffarbe im Rahmen testen (Dunkel / Sand / Hell)", + "🎨 Try a fabric color in the hoop (dark / sand / light)", + "🎨 Essayer une couleur de tissu (sombre / sable / clair)", + "🎨 Probar un color de tela (oscuro / arena / claro)"), + + "tour_app_2_badge": ("ÜBER DER LEINWAND · 2 / 7", "ABOVE THE CANVAS · 2 / 7", "AU-DESSUS DU CANEVAS · 2 / 7", + "ENCIMA DEL LIENZO · 2 / 7"), + "tour_app_2_title": ("Maschine, Stickrahmen und Stoff", "Machine, hoop and fabric", "Machine, cadre et tissu", + "Máquina, bastidor y tela"), + "tour_app_2_body": ( + "Direkt über der Leinwand sagst du OpenStitch, worauf gestickt wird:

" + "• Maschine: Universal, Tajima, Brother, Barudan, Melco …
" + "• Stickrahmen: Je nach Grösse passt OpenStitch Unterlage und Zugkompensation automatisch an, " + "z. B. Anti-Trampolin bei grossen Rahmen oder Center-Out und Bottom-Up bei Kappen.
" + "• Stoff: Passt Dichte und Zugausgleich an und empfiehlt dir Vlies und Nadel.", + "Right above the canvas you tell OpenStitch what you are stitching on:

" + "• Machine: Universal, Tajima, Brother, Barudan, Melco …
" + "• Hoop: OpenStitch adjusts the underlay and pull compensation to the size. Large hoops get " + "extra support against bouncing, and caps are stitched from the center outward and from the " + "brim upward.
" + "• Fabric: adjusts density and pull compensation, and recommends a stabilizer and needle.", + "Juste au-dessus du canevas, indiquez à OpenStitch sur quoi vous brodez :

" + "• Machine : Universal, Tajima, Brother, Barudan, Melco …
" + "• Cadre : OpenStitch adapte la sous-couche et la compensation de traction à la taille. Les " + "grands cadres sont renforcés contre l'effet trampoline, et les casquettes sont brodées du centre " + "vers l'extérieur et de la visière vers le haut.
" + "• Tissu : ajuste la densité et la compensation de traction, et vous conseille un " + "stabilisateur et une aiguille.", + "Justo encima del lienzo le indicas a OpenStitch sobre qué vas a bordar:

" + "• Máquina: Universal, Tajima, Brother, Barudan, Melco …
" + "• Bastidor: OpenStitch ajusta el refuerzo y la compensación de tirón según el tamaño. Los " + "bastidores grandes llevan más sujeción contra el efecto trampolín, y las gorras se bordan del " + "centro hacia fuera y desde la visera hacia arriba.
" + "• Tela: ajusta la densidad y la compensación de tirón, y te recomienda estabilizador y aguja.", + ), + "tour_app_2_action": ("⛶ Design optimal in den Rahmen einpassen (Auto-Fit)", + "⛶ Fit the design to the hoop (Auto-Fit)", + "⛶ Ajuster le motif au cadre", + "⛶ Ajustar el diseño al bastidor (Auto-Ajuste)"), + + "tour_app_3_badge": ("OBERE LEISTE · 3 / 7", "TOP TOOLBAR · 3 / 7", "BARRE SUPÉRIEURE · 3 / 7", + "BARRA SUPERIOR · 3 / 7"), + "tour_app_3_title": ("Bild, Schrift, Prüfen und Export", "Image, lettering, check and export", + "Image, lettrage, vérification et export", "Imagen, texto, revisión y exportación"), + "tour_app_3_body": ( + "Neben den Datei-Knöpfen und Rückgängig findest du hier die wichtigsten Schritte:

" + "• Bild → Stiche (Ctrl+D): Bild wählen, OpenStitch stellt es frei und erzeugt die " + "Stickflächen.
" + "• Schrift (Ctrl+T): Text und Monogramme einfügen.
" + "• Prüfen (F7): Testet dein Design und gibt ihm eine Punktzahl bis 100.
" + "• Export (Ctrl+E): Speichert die Datei für deine Maschine.

" + "PhotoStitch, Appliqué und 3D-Puff sind im Menü Digitalisieren, SVG in Datei, " + "Transfer in Maschine & Export.", + "Next to the file buttons and Undo you find the main steps:

" + "• Image to stitches (Ctrl+D): pick an image, and OpenStitch removes the background and " + "creates the stitch areas.
" + "• Lettering (Ctrl+T): add text and monograms.
" + "• Check (F7): tests your design and gives it a score out of 100.
" + "• Export (Ctrl+E): saves the file for your machine.

" + "PhotoStitch, Appliqué and 3D-Puff are in the Digitize menu, SVG is in File, and " + "Transfer is in Machine & Export.", + "À côté des boutons de fichier et d'annulation se trouvent les étapes principales :

" + "• Image → points (Ctrl+D) : choisissez une image, OpenStitch retire le fond et crée les " + "zones de broderie.
" + "• Lettrage (Ctrl+T) : ajoutez du texte et des monogrammes.
" + "• Vérifier (F7) : teste votre motif et lui donne une note sur 100.
" + "• Exporter (Ctrl+E) : enregistre le fichier pour votre machine.

" + "PhotoStitch, Appliqué et 3D-Puff sont dans le menu Numériser, SVG dans Fichier et " + "Transfert dans Machine & Export.", + "Junto a los botones de archivo y de deshacer están los pasos principales:

" + "• Imagen a puntadas (Ctrl+D): elige una imagen y OpenStitch quita el fondo y crea las " + "zonas de bordado.
" + "• Texto (Ctrl+T): añade texto y monogramas.
" + "• Revisar (F7): prueba tu diseño y le da una puntuación sobre 100.
" + "• Exportar (Ctrl+E): guarda el archivo para tu máquina.

" + "PhotoStitch, Aplique y 3D-Puff están en el menú Digitalizar, SVG en Archivo y " + "Transferir en Máquina & Exportar.", + ), + "tour_app_3_action": ("✨ Bild → Stiche öffnen …", "✨ Open Image to stitches …", "✨ Ouvrir Image → points …", + "✨ Abrir Imagen a puntadas …"), + + "tour_app_4_badge": ("WERKZEUGE · 4 / 7", "TOOLS · 4 / 7", "OUTILS · 4 / 7", "HERRAMIENTAS · 4 / 7"), + "tour_app_4_title": ("Selbst zeichnen und Knoten bearbeiten (N)", "Draw by hand and edit nodes (N)", + "Dessiner à la main et modifier les nœuds (N)", "Dibujar a mano y editar nodos (N)"), + "tour_app_4_body": ( + "Die schmale Leiste links zeigt nur Symbole. Zeige mit der Maus darauf, dann erscheint der " + "Name:

" + "• Tatami (F) / Satin (S) / Stepp (R): Eigene Formen frei auf der Leinwand zeichnen.
" + "• Knoten (N): Konturpunkte einzeln verschieben und an der gelben Achse den " + "Stichwinkel drehen.", + "The narrow bar on the left shows icons only. Point the mouse at one to see its name:

" + "• Tatami (F) / Satin (S) / Run (R): draw your own shapes on the canvas.
" + "• Nodes (N): move outline points one by one, and drag the yellow axis to turn the " + "stitch angle.", + "La barre étroite à gauche n'affiche que des icônes. Pointez-en une avec la souris pour voir son " + "nom :

" + "• Tatami (F) / Satin (S) / Point droit (R) : dessinez vos propres formes sur le canevas.
" + "• Nœuds (N) : déplacez les points du contour un par un et tirez l'axe jaune pour " + "tourner l'angle de point.", + "La barra estrecha de la izquierda solo muestra iconos. Pasa el ratón sobre uno para ver su " + "nombre:

" + "• Tatami (F) / Satén (S) / Pespunte (R): dibuja tus propias formas en el lienzo.
" + "• Nodos (N): mueve los puntos del contorno uno a uno y arrastra el eje amarillo para " + "girar el ángulo de puntada.", + ), + "tour_app_4_action": ("❖ Knoten- und Stichwinkel-Editor (N) einschalten", + "❖ Turn on the node and stitch angle editor (N)", + "❖ Activer l'éditeur de nœuds et d'angle (N)", + "❖ Activar el editor de nodos y ángulo (N)"), + + "tour_app_5_badge": ("GARNFARBEN · 5 / 7", "THREAD COLORS · 5 / 7", "COULEURS DE FIL · 5 / 7", + "COLORES DE HILO · 5 / 7"), + "tour_app_5_title": ("Farben und Nadel-Reihenfolge", "Colors and needle order", "Couleurs et ordre des aiguilles", + "Colores y orden de agujas"), + "tour_app_5_body": ( + "Links wählst du mit einem Klick eine Farbe aus dem Garnkatalog (Madeira, Isacord, Gunold, " + "Brother …) oder über RGB einen eigenen Ton.

" + "• Darunter siehst du die Reihenfolge der Farben und Nadeln in deinem Design, mit der " + "Stichanzahl pro Farbe.", + "On the left you pick a color from the thread catalog (Madeira, Isacord, Gunold, " + "Brother …) with one click, or mix your own with RGB.

" + "• Below that you see the order of colors and needles in your design, with the number of " + "stitches per color.", + "À gauche, choisissez en un clic une couleur du catalogue de fils (Madeira, Isacord, Gunold, " + "Brother …) ou créez votre propre teinte avec RGB.

" + "• En dessous, vous voyez l'ordre des couleurs et des aiguilles de votre motif, avec le " + "nombre de points par couleur.", + "A la izquierda eliges con un clic un color del catálogo de hilos (Madeira, Isacord, Gunold, " + "Brother …) o creas tu propio tono con RGB.

" + "• Debajo ves el orden de colores y agujas de tu diseño, con el número de puntadas por " + "color.", + ), + + "tour_app_6_badge": ("EBENEN UND EINSTELLUNGEN · 6 / 7", "LAYERS AND SETTINGS · 6 / 7", + "CALQUES ET RÉGLAGES · 6 / 7", "CAPAS Y AJUSTES · 6 / 7"), + "tour_app_6_title": ("Ebenen und Objekt-Einstellungen", "Layers and object settings", + "Calques et réglages de l'objet", "Capas y ajustes del objeto"), + "tour_app_6_body": ( + "Rechts legst du die Stickreihenfolge fest. Darunter stellst du für das gewählte Objekt " + "Reihenabstand, Muster (z. B. Kontur), Zugkompensation oder bei Satin 3D-Puff ein." + "

" + "• Jede Änderung berechnet die Stiche sofort auf der Leinwand neu.", + "On the right you set the stitching order. Below it you adjust the selected object: row " + "spacing, pattern (for example Contour), pull compensation, or 3D puff for satin." + "

" + "• Every change recalculates the stitches on the canvas right away.", + "À droite, vous définissez l'ordre de broderie. En dessous, réglez l'objet sélectionné : " + "espacement des rangs, motif de remplissage (par exemple Contour), compensation de traction " + "ou Puff 3D pour le satin.

" + "• Chaque modification recalcule les points sur le canevas aussitôt.", + "A la derecha fijas el orden de bordado. Debajo ajustas el objeto seleccionado: separación " + "de filas, patrón (por ejemplo Contorno), compensación de tirón o Puff 3D para el " + "satén.

" + "• Cada cambio recalcula las puntadas en el lienzo al instante.", + ), + + "tour_app_7_badge": ("SIMULATOR UND STATUS · 7 / 7", "SIMULATOR AND STATUS · 7 / 7", + "SIMULATEUR ET ÉTAT · 7 / 7", "SIMULADOR Y ESTADO · 7 / 7"), + "tour_app_7_title": ("Stich-Simulator und Statusleiste", "Stitch simulator and status bar", + "Simulateur de points et barre d'état", "Simulador de puntadas y barra de estado"), + "tour_app_7_body": ( + "Unter der Leinwand spielst du den kompletten Stickablauf Stich für Stich ab.

" + "• In der Statusleiste ganz unten siehst du Stiche, Grösse, Farbwechsel, Fadenschnitte und die " + "geschätzte Laufzeit. Zeige mit der Maus darauf für Tempo und Spitzendichte.
" + "• Die Sprache stellst du unten rechts um.", + "Below the canvas you can play the whole design stitch by stitch.

" + "• The status bar at the very bottom shows stitches, size, color changes, trims and the " + "estimated runtime. Point the mouse at it for speed and peak density.
" + "• You change the language at the bottom right.", + "Sous le canevas, vous pouvez rejouer tout le motif point par point.

" + "• La barre d'état tout en bas indique les points, la taille, les changements de couleur, les " + "coupes et la durée estimée. Pointez-la avec la souris pour voir la vitesse et la " + "densité maximale.
" + "• La langue se change en bas à droite.", + "Debajo del lienzo puedes reproducir todo el diseño puntada a puntada.

" + "• La barra de estado, abajo del todo, muestra las puntadas, el tamaño, los cambios de color, los " + "cortes y el tiempo estimado. Pasa el ratón por encima para ver la velocidad y la " + "densidad máxima.
" + "• El idioma se cambia abajo a la derecha.", + ), + "tour_app_7_action": ("▶ Simulation starten / stoppen", "▶ Start / stop the simulation", + "▶ Lancer / arrêter la simulation", "▶ Iniciar / detener la simulación"), +} diff --git a/openstitch/io/drives.py b/openstitch/io/drives.py new file mode 100644 index 0000000..20a3e8d --- /dev/null +++ b/openstitch/io/drives.py @@ -0,0 +1,33 @@ +"""USB-Sticks finden, damit das Speichern für die Maschine ohne Ordnersuche geht.""" +from __future__ import annotations + +import os +import sys + +from PySide6.QtCore import QStorageInfo + + +def _is_removable_windows(root: str) -> bool: + import ctypes + DRIVE_REMOVABLE = 2 + return ctypes.windll.kernel32.GetDriveTypeW(root) == DRIVE_REMOVABLE + + +def removable_drives() -> list[tuple[str, str]]: + """(Pfad, Anzeigename) aller beschreibbaren Wechseldatenträger.""" + out: list[tuple[str, str]] = [] + for vol in QStorageInfo.mountedVolumes(): + if not vol.isValid() or not vol.isReady() or vol.isReadOnly() or vol.isRoot(): + continue + root = vol.rootPath() + if sys.platform == "win32": + ok = _is_removable_windows(os.path.join(root, "")) + elif sys.platform == "darwin": + ok = root.startswith("/Volumes/") + else: + ok = root.startswith(("/media/", "/run/media/", "/mnt/")) + if ok: + name = vol.displayName() or root + free = vol.bytesAvailable() / 1e9 + out.append((root, f"{name} ({root}, {free:.1f} GB)")) + return out diff --git a/openstitch/io/formats.py b/openstitch/io/formats.py index cba46cf..366a72e 100644 --- a/openstitch/io/formats.py +++ b/openstitch/io/formats.py @@ -2,6 +2,7 @@ from __future__ import annotations import os +import unicodedata import pyembroidery as pe @@ -9,6 +10,8 @@ from ..core.stitchplan import Cmd, StitchPlan, Thread from .exp import write_exp +_SPECIAL = str.maketrans({"ß": "ss", "ø": "o", "Ø": "O", "ł": "l", "Ł": "L", "ı": "i", "æ": "ae", "œ": "oe"}) + READ_EXT = ["exp", "dst", "pes", "pec", "jef", "vp3", "xxx", "hus", "vip", "sew", "u01", "pcs", "dsb", "dsz", "tbf", "shv", "10o", "100", "ksm", "max", "stx", "phb", "phc", "gt", "inb", "emd", "bro", "mit", "new", "zhs", "tap", "stc", "zxy", "pmv", "spx", "jpx", "csv", "json"] @@ -30,6 +33,15 @@ } +def _ascii(text: str) -> str: + """Garnnamen für Stickdateien: nur einfache Zeichen. + + Maschinen zeigen ohnehin keine Umlaute. Vor allem aber schreibt pyembroidery in VP3 die Länge + in Zeichen statt Bytes: Schon ein „ü“ verschiebt den Rest und die Datei ist unlesbar.""" + text = text.translate(_SPECIAL) + return unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii") + + def plan_to_pattern(plan: StitchPlan) -> pe.EmbPattern: p = pe.EmbPattern() x0, y0, x1, y1 = plan.bounds() @@ -37,9 +49,9 @@ def plan_to_pattern(plan: StitchPlan) -> pe.EmbPattern: for bi, block in enumerate(plan.blocks): t = pe.EmbThread() t.set_color(*block.thread.color) - t.description = block.thread.name - t.catalog_number = block.thread.code - t.brand = block.thread.brand + t.description = _ascii(block.thread.name) + t.catalog_number = _ascii(block.thread.code) + t.brand = _ascii(block.thread.brand) p.add_thread(t) if bi > 0: p.add_command(pe.COLOR_CHANGE) diff --git a/openstitch/io/project.py b/openstitch/io/project.py index 1699423..bf30477 100644 --- a/openstitch/io/project.py +++ b/openstitch/io/project.py @@ -7,9 +7,11 @@ from PySide6.QtCore import QRectF, Qt from PySide6.QtGui import QColor, QFont, QImage, QPageLayout, QPageSize, QPainter, QPdfWriter, QPen +from shapely.errors import GEOSException from .. import APP_NAME, __version__ from ..core.design import HOOPS, Design, Hoop, Settings, object_from_dict +from ..core.fabric import fabric_by_id from ..core.stitchplan import StitchPlan from ..i18n import fmt_int, machine_display_name, tr from ..render import render_image @@ -20,6 +22,7 @@ def save_project(design: Design, path: str) -> None: "app": APP_NAME, "version": __version__, "name": design.name, + "fabric": design.fabric, "hoop": { "name": design.hoop.name, "width": design.hoop.width, @@ -38,21 +41,35 @@ def save_project(design: Design, path: str) -> None: os.replace(tmp, path) +def _load_hoop(h: dict) -> Hoop: + hoop = Hoop(str(h.get("name", "Rahmen")), float(h.get("width", 150)), float(h.get("height", 150)), + bool(h.get("round", True)), str(h.get("mode", "medium")), float(h.get("margin_mm", 4.5))) + if not (10 <= hoop.width <= 2000 and 10 <= hoop.height <= 2000): + raise ValueError("invalid hoop size") + return hoop + + +def _load_settings(values: dict) -> Settings: + st = Settings(**{k: v for k, v in values.items() if k in Settings.__annotations__}) + st.max_stitch = min(max(float(st.max_stitch), 1.0), 12.7) + st.min_trim = min(max(float(st.min_trim), 0.0), 50.0) + st.needles = max(1, int(st.needles)) + return st + + def load_project(path: str) -> Design: - with open(path, "r", encoding="utf-8-sig") as f: - data = json.load(f) - h = data.get("hoop", {}) - hoop = Hoop( - h.get("name", "Rahmen"), - h.get("width", 150), - h.get("height", 150), - h.get("round", True), - h.get("mode", "medium"), - h.get("margin_mm", 4.5), - ) - st = Settings(**{k: v for k, v in data.get("settings", {}).items() if k in Settings.__annotations__}) - objs = [object_from_dict(od) for od in data.get("objects", [])] - return Design(objects=objs, hoop=hoop, settings=st, name=data.get("name", "Projekt")) + """Lädt ein Projekt. Beschädigte Dateien ergeben einen ValueError mit lesbarem Text.""" + try: + with open(path, "r", encoding="utf-8-sig") as f: + data = json.load(f) + objs = [object_from_dict(od) for od in data.get("objects", [])] + return Design(objects=objs, hoop=_load_hoop(data.get("hoop", {})), + settings=_load_settings(data.get("settings", {})), name=str(data.get("name", "Projekt")), + fabric=fabric_by_id(data.get("fabric")).id) + except OSError: + raise + except (ValueError, KeyError, TypeError, AttributeError, IndexError, GEOSException) as exc: + raise ValueError(tr("err_project_damaged").format(name=os.path.basename(path))) from exc def export_worksheet_pdf(design: Design, plan: StitchPlan, path: str, machine_name: str | None = None) -> None: diff --git a/openstitch/locales/__init__.py b/openstitch/locales/__init__.py new file mode 100644 index 0000000..3f5fe2d --- /dev/null +++ b/openstitch/locales/__init__.py @@ -0,0 +1,6 @@ +"""Weitere Sprachen, je eine Datei mit `TABLE: dict[str, str]` (Schlüssel wie in i18n._TABLE). + +Bewusst feste Importe: So erkennt PyInstaller die Dateien und packt sie in die fertigen Programme.""" +from . import it, nl, pl, pt, tr + +TABLES: dict[str, dict[str, str]] = {"it": it.TABLE, "nl": nl.TABLE, "pl": pl.TABLE, "pt": pt.TABLE, "tr": tr.TABLE} diff --git a/openstitch/locales/it.py b/openstitch/locales/it.py new file mode 100644 index 0000000..3118414 --- /dev/null +++ b/openstitch/locales/it.py @@ -0,0 +1,524 @@ +"""Italiano.""" + +TABLE: dict[str, str] = { + "menu_file": "&File", + "menu_edit": "Mo&difica", + "menu_view": "&Visualizza", + "menu_create": "Di&gitalizza", + "menu_machine": "&Macchina && Esporta", + "menu_help": "&Aiuto", + "tb_new": "Nuovo", + "tb_import": "Importa", + "tb_svg": "SVG", + "tb_export": "Esporta", + "tb_pdf": "PDF", + "tb_auto": "Immagine in punti", + "tb_photo": "PhotoStitch", + "tb_text": "Testo", + "tb_applique": "Applicazione", + "tb_puff": "Puff 3D", + "tb_transfer": "Trasferisci", + "tb_tour": "Tour", + "lbl_machine": "Macchina:", + "lbl_hoop": "Telaio:", + "btn_autofit": "Adatta", + "fabric_slate": "Tessuto: scuro", + "fabric_sand": "Tessuto: sabbia", + "fabric_light": "Tessuto: chiaro", + "lbl_strategy": "Strategia", + "tool_select": "Seleziona (V)", + "tool_nodes": "Nodi (N)", + "tool_fill": "Tatami (F)", + "tool_satin": "Raso (S)", + "tool_run": "Filza (R)", + "tool_heatmap": "Densità", + "tool_zoom": "Adatta al telaio", + "hud_select": "Seleziona (V) · Trascina = sposta, maniglia d'angolo = ridimensiona, rotella = zoom", + "hud_nodes": "Nodi e angolo dei punti (N) · Nodi bianchi = modifica il contorno, maniglia gialla = ruota l'angolo dei punti", + "hud_fill": "Disegna riempimento tatami (F) · Clic = aggiungi punto, doppio clic/Invio = termina", + "hud_satin": "Disegna colonna di raso (S) · Clic = aggiungi punto, doppio clic/Invio = termina", + "hud_run": "Disegna punto filza (R) · Clic = aggiungi punto, doppio clic/Invio = termina", + "dock_palette": "Fili && Colori", + "lbl_catalog": "Catalogo fili:", + "lbl_seq": "Sequenza fili e aghi del disegno:", + "needle": "Ago", + "dock_right": "Livelli && Impostazioni", + "btn_visible": "👁 Visibile", + "btn_copy": "⧉ Copia", + "lbl_inspector": "Parametri dell'oggetto (ricalcolo in tempo reale):", + "lbl_no_sel": "Nessun oggetto selezionato.\nClicca un elemento sulla tela o nell'elenco dei livelli.", + "lbl_obj_name": "Nome", + "dock_bottom": "Simulatore && Riproduzione dei punti", + "btn_play": "▶ Simula", + "btn_pause": "⏸ Pausa", + "btn_show_all": "⏭ Mostra tutto", + "lbl_progress": " Avanzamento:", + "lbl_speed": "Velocità:", + "stats_stitches": "Punti", + "stats_size": "Misura", + "stats_avg": "Lungh. media", + "stats_spm": "Velocità eff.", + "stats_peak": "Densità max", + "stats_colors": "Cambi colore", + "stats_runtime": "Durata: ~", + "stats_min": "min", + "m_new": "Nuovo disegno", + "m_open": "Apri progetto (.ostitch) …", + "m_save": "Salva progetto (.ostitch) …", + "m_import": "Importa file di ricamo (EXP, DST, PES, JEF …) …", + "m_import_svg": "Importa grafica vettoriale SVG (.svg) …", + "m_export": "Esporta file di ricamo (EXP, DST, PES, JEF …) …", + "m_export_pdf": "Salva la scheda di produzione come PDF …", + "m_export_png": "Salva l'anteprima 3D realistica come PNG …", + "m_quit": "Esci", + "m_auto": "Digitalizza immagine in automatico (Auto-Digitizer) …", + "m_photo": "PhotoStitch (foto ritratto → ricamo) …", + "m_text": "Inserisci testo / monogramma …", + "m_applique": "Crea applicazione da una forma", + "m_puff": "Attiva o disattiva la modalità puff 3D (schiuma) per il raso", + "m_transfer": "Trasferimento alla macchina / floppy / USB / NetBridge …", + "m_doctor": "Controlla il disegno (ricamo virtuale)", + "m_optimize": "Riduci i colori (meno cambi d'ago)", + "m_tour": "Tour interattivo dello studio (introduzione) …", + "m_restore_logo": "Ripristina il logo ufficiale di OpenStitch", + "m_undo": "Annulla", + "m_redo": "Ripeti", + "m_duplicate": "Duplica l'oggetto selezionato", + "m_delete": "Elimina l'oggetto selezionato", + "m_center": "Centra il disegno nel telaio", + "m_fit": "Adatta al meglio al telaio attuale (Auto-Fit)", + "m_pick_hoop": "Scegli in automatico il telaio più piccolo adatto", + "m_scale": "Ridimensiona il disegno (% / mm) …", + "m_3d": "Resa 3D del filo", + "m_jumps": "Mostra i punti di salto", + "m_grid": "Mostra la griglia millimetrata", + "m_heatmap": "Mappa della densità dei punti (stress sul tessuto)", + "m_zoom": "Zoom sul telaio", + "lbl_lang": "Lingua:", + "status_computing": "Calcolo dei punti …", + "dlg_unsaved_title": "Modifiche non salvate", + "dlg_unsaved_text": "Il disegno attuale ha modifiche non salvate. Vuoi salvarle ora?", + "status_plan_error": "Generazione dei punti non riuscita", + "kind_column": "Colonna di raso", + "param_column_width": "Larghezza colonna (mm)", + "msg_overwrite_title": "Sostituire il file?", + "msg_overwrite_text": "{name} esiste già nell'immagine del floppy. Vuoi sostituirlo?", + "ph_text": "Il tuo testo", + "tip_use_micro": "Per un testo così piccolo usa “OpenStitch Micro” (clicca qui)", + "act_shortcuts": "Scorciatoie da tastiera …", + "act_report": "Segnala un problema …", + "act_about": "Informazioni su OpenStitch …", + "about_text": "Software gratuito per ricamo e digitalizzazione. Licenza: AGPL-3.0, il codice sorgente è liberamente disponibile.", + "keys_title": "Scorciatoie da tastiera", + "key_select": "Seleziona e sposta", + "key_nodes": "Modifica i nodi", + "key_fill": "Disegna un riempimento", + "key_satin": "Disegna una colonna di raso", + "key_run": "Disegna un punto filza", + "key_finish": "Termina il disegno", + "key_cancel": "Annulla il disegno", + "key_zoom": "Zoom", + "key_pan": "Sposta la vista", + "key_wheel": "Rotella del mouse", + "key_middle": "Tasto centrale del mouse", + "crash_title": "Non doveva succedere", + "crash_text": "OpenStitch ha riscontrato un errore. Il tuo lavoro è stato salvato e puoi continuare.\n\nSe vuoi segnalarlo, allega questo file:\n{}", + "exp_title": "Invia alla macchina", + "exp_heading": "Pronto a ricamare?", + "exp_facts": "{st} punti · {colors} colori · {w} × {h} mm", + "exp_format": "Formato del file:", + "exp_recommended": "{} (consigliato)", + "exp_name": "Nome del file:", + "exp_short": "Nome breve per macchine più vecchie", + "exp_short_tip": "Molte macchine più vecchie mostrano solo 8 caratteri semplici.", + "exp_where": "Salva in:", + "exp_usb": "Chiavetta USB: {}", + "exp_browse": "Cartella …", + "exp_refresh": "Aggiorna", + "exp_threads": "Ordine dei fili per la macchina", + "exp_save": "Salva", + "exp_done": "“{name}” salvato e verificato: {st} punti riletti correttamente. Ora inserisci la chiavetta nella macchina.", + "exp_overwrite": "“{}” esiste già qui. Vuoi sostituirlo?", + "exp_done_plain": "“{name}” salvato.", + "exp_failed": "Salvataggio non riuscito: {}", + "btn_close": "Chiudi", + "chk_title": "Controlla il disegno", + "chk_running": "Controllo in corso …", + "chk_failed": "Controllo non riuscito", + "chk_empty": "Ancora nessun punto", + "chk_again": "Controlla di nuovo", + "chk_good": "Pronto da ricamare", + "chk_ok": "Ricamabile, con piccoli rischi", + "chk_bad": "Meglio correggere prima", + "chk_none": "Nessun problema trovato.", + "chk_facts": "{st} punti · {colors} colori · {trims} tagli · circa {min} min · {thread} m di filo", + "chk_preview": "Come si tira il tessuto", + "chk_boost": "Esaspera l'effetto", + "chk_show": "Mostra", + "chk_fix": "Correggi", + "undo_fix": "Correzione automatica", + "chk_sev_error": "Problema", + "chk_sev_warning": "Attenzione", + "chk_sev_info": "Nota", + "chk_short_stitch_t": "Punti molto corti", + "chk_short_stitch_d": "Punti sotto 0,3 mm: {count}. L'ago colpisce quasi lo stesso foro e il filo può rompersi.", + "chk_over_max_stitch_t": "Punti troppo lunghi per la macchina", + "chk_over_max_stitch_d": "{count} punti superano il limite della macchina (il più lungo: {max_mm} mm).", + "chk_long_float_t": "Punti lunghi e liberi", + "chk_long_float_d": "{count} punti sono più lunghi di 7,5 mm (fino a {max_mm} mm). Si impigliano facilmente nell'uso di tutti i giorni.", + "chk_no_lock_t": "Capi del filo non fermati", + "chk_no_lock_d": "{count} punti non hanno i punti di fermo. Lì il ricamo può sciogliersi dopo il lavaggio.", + "chk_orphan_run_t": "Tratti troppo corti", + "chk_orphan_run_d": "{count} tratti hanno meno di 3 punti e dopo il taglio del filo non tengono quasi per niente.", + "chk_untrimmed_jump_t": "Salti senza taglio", + "chk_untrimmed_jump_d": "{count} salti lasciano un filo steso sul disegno.", + "chk_needle_pileup_t": "Troppi colpi d'ago nello stesso punto", + "chk_needle_pileup_d": "In {count} zone l'ago colpisce fino a {max_hits} volte. Può rovinare tessuto e ago.", + "chk_too_dense_t": "Ricamato troppo fitto", + "chk_too_dense_d": "{count} mm² hanno fino a {peak} strati di filo (limite per questo tessuto: {limit}). La zona diventa dura come un cartone.", + "chk_outside_hoop_t": "Il disegno non entra nel telaio", + "chk_outside_hoop_d": "Alcuni punti cadono nella zona del bordo del telaio. L'ago potrebbe colpire il telaio.", + "chk_low_coverage_t": "Il tessuto si vede", + "chk_low_coverage_d": "“{object}” è coperto solo al {percent}%.", + "chk_too_many_colors_t": "Più colori che aghi", + "chk_too_many_colors_d": "{count} colori su {needles} aghi: dovrai cambiare il filo durante il ricamo.", + "chk_registration_gap_t": "Probabili spazi tra gli oggetti", + "chk_registration_gap_d": "La trazione del tessuto sposta le parti fino a {mm} mm l'una rispetto all'altra. Più compensazione della trazione aiuta.", + "chk_puckering_t": "Il tessuto potrebbe arricciarsi", + "chk_puckering_d": "Il ricamo tira il tessuto di circa {mm} mm. Usa uno stabilizzatore più rigido.", + "chk_small_text_t": "Testo troppo piccolo per questo font", + "chk_small_text_d": "“{object}” è alto {mm} mm. I font a contorno si riempiono a questa misura. Usa “OpenStitch Micro”.", + "chk_export_ok_t": "File {ext} verificato", + "chk_export_ok_d": "{st} punti riletti, errore massimo {err} mm.", + "chk_export_bad_t": "Problema nel file {ext}", + "tb_open": "Apri", + "tb_save": "Salva", + "tb_check": "Controlla", + "act_home": "Mostra la pagina iniziale", + "act_theme_dark": "Tema scuro", + "act_theme_light": "Tema chiaro", + "menu_recent": "Apri recenti", + "lbl_fabric": "Tessuto:", + "fab_woven": "Cotone / camicia (tessuto)", + "fab_denim": "Jeans / tela", + "fab_twill_cap": "Cappellino (twill)", + "fab_pique": "Polo in piqué", + "fab_jersey": "T-shirt (jersey)", + "fab_fleece": "Pile / felpa", + "fab_towel": "Spugna / asciugamano", + "fab_leather": "Pelle", + "fab_silk": "Seta / tessuto delicato", + "stab_cutaway": "stabilizzatore da tagliare", + "stab_tearaway": "stabilizzatore da strappare", + "stab_none": "nessuno stabilizzatore", + "fabric_advice": "{fabric}: usa {stabilizer}, ago {needle}. Densità e compensazione della trazione vengono adattate.", + "fabric_topping": "Metti sopra un topping idrosolubile, così i punti non affondano.", + "tip_obj_visible": "Mostra o nascondi l'oggetto", + "tip_obj_copy": "Duplica l'oggetto", + "param_knockout": "Salta le parti nascoste", + "canvas_empty_hint": "Trascina qui un'immagine o scegli uno strumento di disegno a sinistra", + "start_title": "Cosa vuoi ricamare?", + "start_subtitle": "Scegli da dove iniziare. Non serve esperienza.", + "start_image": "Trasforma un'immagine in ricamo", + "start_image_d": "Scegli un logo o un disegno e OpenStitch fa il resto.", + "start_text": "Ricama un testo", + "start_text_d": "Un nome o uno slogan, ben leggibile già da 2,5 mm di altezza.", + "start_draw": "Disegna da te", + "start_draw_d": "Disegna riempimenti, colonne di raso e linee con il mouse.", + "start_open": "Apri un file", + "start_open_d": "Progetto, file di ricamo (DST, PES, JEF …), SVG o immagine.", + "start_samples": "Oppure parti da un esempio", + "start_recent": "File recenti", + "start_tour": "Fai un breve tour", + "sample_patch": "Targhetta con nome", + "sample_heart": "Cuore", + "sample_flower": "Fiore", + "sample_monogram": "Monogramma", + "fd_open_any": "Apri file", + "filter_supported": "Tutti i file supportati", + "err_file_gone": "Il file non è stato trovato:\n{}", + "err_unknown_type": "“{}” è un tipo di file che OpenStitch non conosce.", + "dlg_recover_title": "Ripristinare il tuo lavoro?", + "dlg_recover_text": "OpenStitch non si è chiuso correttamente. Vuoi aprire l'ultimo salvataggio automatico?", + "status_autosave_failed": "Salvataggio automatico non riuscito: {}", + "err_project_damaged": "“{name}” è danneggiato o non è un file di progetto OpenStitch.", + "label_colon": ":", + "btn_cancel": "Annulla", + "btn_apply": "Applica", + "btn_save": "Salva", + "btn_discard": "Scarta", + "dlg_error": "Errore", + "dlg_notice": "Avviso", + "filter_all_files": "Tutti i file", + "filter_all_images": "Tutte le immagini", + "filter_images": "Immagini", + "filter_all_img_vec": "Tutte le immagini e i file vettoriali", + "filter_raster": "Immagini raster", + "filter_svg": "Grafica vettoriale SVG", + "filter_photos": "Foto e immagini", + "filter_project": "Progetto OpenStitch", + "filter_emb": "File di ricamo", + "filter_png": "Immagine PNG", + "filter_floppy": "Immagine floppy", + "err_open_title": "Errore all'apertura del file", + "err_load_title": "Errore nel caricamento del file", + "err_svg_title": "Errore di importazione SVG", + "err_import_title": "Errore di importazione", + "err_save_title": "Errore di salvataggio", + "err_export_title": "Errore di esportazione", + "err_pdf_title": "Errore PDF", + "err_png_title": "Errore PNG", + "err_png_text": "Impossibile salvare l'immagine:\n{}", + "err_image_title": "Errore immagine", + "app_tagline": "Suite universale open source per ricamo e digitalizzazione", + "tb_title_studio": "Barra dello studio", + "tb_title_tools": "Strumenti di disegno", + "tip_autofit": "Adatta al meglio il disegno al telaio selezionato (Ctrl+F)", + "tip_fabric": "Cambia lo sfondo del tessuto nel telaio (ardesia scura / sabbia calda / chiaro)", + "tip_tool_select": "Seleziona, sposta e ridimensiona gli oggetti (tasto V)", + "tip_tool_nodes": "Trascina direttamente i nodi del contorno e l'asse dell'angolo dei punti (tasto N)", + "tip_tool_fill": "Disegna sulla tela una nuova area di riempimento tatami (tasto F)", + "tip_tool_satin": "Disegna sulla tela una nuova colonna di raso (tasto S)", + "tip_tool_run": "Disegna un nuovo percorso a punto filza (tasto R)", + "tip_tool_heatmap": "Mostra o nascondi la mappa della densità dei punti (verde/giallo/rosso) (Ctrl+H)", + "tip_tool_zoom": "Adatta la vista al telaio (Ctrl+0)", + "tip_obj_up": "Sposta l'oggetto più su nell'ordine di ricamo", + "tip_obj_down": "Sposta l'oggetto più giù nell'ordine di ricamo", + "tip_obj_delete": "Elimina l'oggetto selezionato (Canc)", + "sim_all": "Tutti", + "sim_speed_suffix": " pt./tick", + "abbr_stitches": "pt.", + "stats_trims": "Tagli", + "kind_fill": "Riempimento", + "kind_satin": "Raso", + "kind_run": "Punto filza", + "kind_text": "Testo", + "kind_stitches": "Punti", + "obj_hidden": "[Nascosto]", + "btn_font_arc": "Regola font e arco …", + "status_hoop_strategy": "Strategia del telaio attiva: {}", + "status_saved": "Salvato: {}", + "color_dialog_title": "Scegli il colore del filo", + "default_design_name": "Nuovo_Disegno", + "fd_open_project": "Apri progetto", + "fd_save_project": "Salva progetto", + "fd_import_emb": "Importa file di ricamo", + "fd_import_svg": "Importa grafica vettoriale SVG", + "fd_export_emb": "Esporta file di ricamo", + "fd_save_pdf": "Salva la scheda di produzione (PDF)", + "pdf_file_suffix": "scheda_produzione", + "fd_save_png": "Salva l'anteprima 3D dei punti", + "fd_pick_image": "Scegli un'immagine, una grafica o un logo (Download / Immagini / Desktop)", + "fd_pick_photo": "Scegli una foto, ritratto o paesaggio (Download / Immagini / Desktop)", + "msg_applique_title": "Applicazione", + "msg_applique_text": "Prima seleziona sulla tela una forma di riempimento o di raso.", + "msg_export_verified_title": "Esportazione e verifica binaria riuscite", + "msg_export_verified_text": "✅ File di ricamo salvato e verificato nel simulatore:\n{path}\n\n• Dimensione del file: {size} byte\n• Punti verificati: {stitches}\n• Misure: {w:.1f} × {h:.1f} mm\n• Lunghezza massima del passo: {step:.1f} mm\n• Cambi colore: {colors} · Salti: {jumps}", + "msg_export_ok_title": "Esportazione riuscita", + "msg_export_ok_text": "File salvato:\n{}", + "msg_pdf_ok_title": "PDF creato", + "msg_pdf_ok_text": "Scheda di produzione salvata:\n{}", + "msg_puff_title": "Schiuma puff 3D", + "msg_puff_text": "Seleziona un oggetto in raso.", + "dlg_scale_title": "Ridimensiona il disegno (i punti verranno ricalcolati!)", + "dlg_scale_label": "Fattore di scala (%):", + "hoop_round9": "Rotondo 9 cm (piccolo/petto)", + "hoop_round12": "Rotondo 12 cm (logo sul petto)", + "hoop_round15": "Rotondo 15 cm (standard)", + "hoop_round18": "Rotondo 18 cm (grande)", + "hoop_round21": "Rotondo 21 cm (XL)", + "hoop_cap": "Cappellino 13 × 5 cm", + "hoop_widecap": "Cappellino largo 30 × 7 cm", + "hoop_rect13x18": "Rettangolare 13 × 18 cm (casa)", + "hoop_jacket": "Schiena giacca 30 × 30 cm", + "hoop_field40x30": "Campo grande 40 × 30 cm (industriale)", + "hoop_strat_small": "Tensione ferma · dettagli fini (-10% compensazione della trazione, sottofondo standard)", + "hoop_strat_medium": "Equilibrata · telaio standard per petto/manica (100% compensazione della trazione)", + "hoop_strat_large": "Anti-trampolino · sottofondo rinforzato (+20% compensazione della trazione + griglia incrociata sulle aree grandi)", + "hoop_strat_jacket": "Stabilizzazione per schiena giacca (+35% compensazione della trazione, sottofondo a doppia griglia, max. 750 SPM)", + "hoop_strat_cap": "Modalità cappellino (dal centro verso l'esterno e dalla visiera verso l'alto, +30% compensazione della trazione)", + "hoop_strat_default": "Standard", + "machine_universal_multi": "Standard universale (DST / PES / EXP · 15 aghi)", + "machine_tajima_tmez": "Tajima TMEZ / TFMX / TMBR (15 aghi)", + "machine_brother_pr": "Brother serie PR / Persona (6–10 aghi)", + "machine_brother_home": "Brother / Baby Lock domestica (1 ago · PES)", + "machine_barudan_bext": "Barudan BEKT / BEXT (15 aghi)", + "machine_ricoma_happy_zsk": "Ricoma / HappyJapan / SWF / ZSK (12–15 aghi)", + "machine_janome_elna": "Janome / Elna / Bernina domestica (JEF / EXP)", + "machine_pfaff_husqvarna": "Pfaff / Husqvarna Viking (VP3)", + "machine_melco_emt10_4": "Melco EMT10/4 (4 teste / 10 aghi)", + "machine_melco_amaya_bravo": "Melco Amaya / EMT16X / Bravo (16 aghi)", + "param_angle": "Angolo dei punti (°)", + "param_fill_spacing": "Distanza tra le file (mm)", + "param_satin_spacing": "Densità (mm)", + "param_stitch_len": "Lunghezza del punto (mm)", + "param_pattern": "Motivo", + "param_underlay": "Sottofondo", + "param_pull_comp": "Compensazione della trazione (mm)", + "param_max_stitch": "Punto max. / divisione (mm)", + "param_underlay_style": "Tipo di sottofondo", + "param_puff_3d": "Puff 3D (modalità cappellino)", + "param_repeats": "Ripetizioni (0 = singolo, 1 = triplo)", + "param_text": "Testo", + "param_font": "Font", + "param_height": "Altezza lettere (mm)", + "param_letter_spacing": "Spaziatura lettere (mm)", + "param_arc_radius": "Raggio dell'arco (mm, 0 = dritto)", + "param_mode": "Tipo di punto", + "param_density": "Densità (mm)", + "opt_standard": "Standard", + "opt_diagonal": "Diagonale", + "opt_ziegel": "Mattoni", + "opt_wellen": "Onde", + "opt_kontur": "Contorno", + "opt_auto": "Automatico", + "opt_mitte": "Filza centrale", + "opt_kante": "Filza sul bordo", + "opt_zickzack": "Zigzag", + "opt_kante+zickzack": "Bordo + zigzag", + "opt_satin": "Punto raso", + "opt_fill": "Riempimento tatami", + "dlg_auto_title": "Digitalizza immagine in automatico (Auto-Digitizer)", + "lbl_orig_image": "Immagine originale ({})", + "btn_other_image": "📂 Scegli un'altra immagine (Download / Desktop / Immagini …)", + "grp_auto_settings": "Impostazioni di ricamo e automazione", + "lbl_target_width_motif": "Larghezza del disegno:", + "lbl_max_colors": "Max. colori di filo (aghi):", + "cb_remove_bg": "Rimuovi automaticamente lo sfondo dell'immagine", + "fabric_opt_normal": "Standard (cotone / twill / universale)", + "fabric_opt_strick": "Piqué / polo / maglia (più compensazione della trazione)", + "fabric_opt_frottee": "Spugna / asciugamano (più fitto + sottofondo forte)", + "fabric_opt_cap": "Cappellino (alta compensazione della trazione)", + "fabric_opt_leicht": "Tessuto leggero / camicia (densità minore)", + "lbl_fabric_type": "Tessuto / materiale:", + "lbl_density_row": "Densità dei punti (distanza tra le file):", + "lbl_satin_limit": "Limite del raso (più stretto = raso):", + "lbl_min_area": "Ignora le aree più piccole di:", + "cb_outline": "Aggiungi un contorno in raso attorno al disegno", + "cb_palette": "Adatta i colori alla palette dei fili", + "status_ready": "Pronto.", + "btn_digitize_apply": "Digitalizza && applica ora", + "fd_pick_logo": "Scegli un'immagine o un logo (Download / Immagini / Desktop)", + "fd_pick_logo_short": "Scegli un'immagine o un logo", + "err_digitize_title": "Digitalizzazione non riuscita", + "prog_computing_stitches": "Calcolo dei punti ({}/{}) …", + "prog_prepare": "Preparazione dell'immagine …", + "prog_reduce": "Riduzione dei colori …", + "prog_clean": "Pulizia delle aree …", + "prog_vectorize": "Vettorializzazione dei contorni …", + "prog_done": "Fatto", + "prog_classify": "Classificazione area {}/{} …", + "dlg_text_title": "Crea testo / monogramma", + "lbl_text": "Testo:", + "lbl_font_file": "Font (TTF/OTF):", + "lbl_letter_height": "Altezza lettere (maiuscole):", + "lbl_letter_spacing": "Spaziatura lettere:", + "sfx_arc": " mm (0 = dritto)", + "lbl_arc_radius": "Raggio dell'arco:", + "text_mode_auto": "Automatico (raso fino a 7 mm, tatami oltre)", + "text_mode_satin": "Sempre punto raso (testo lucido)", + "text_mode_fill": "Sempre riempimento tatami", + "lbl_stitch_type": "Tipo di punto:", + "lbl_stitch_density": "Densità dei punti:", + "msg_enter_text": "Inserisci un testo.", + "text_obj_name": "Testo “{}”", + "dlg_transfer_title": "Trasferimento alla macchina (USB / emulatore floppy da 1,44 MB / Wi-Fi NetBridge)", + "grp_transfer_1": "1. Impostazioni di macchina e taglio (EXP / formato industriale)", + "lbl_dos_name": "Nome file DOS (formato 8.3):", + "trim_both": "Combinato: codice di taglio EXP + 3 salti (massima compatibilità)", + "trim_code": "Codice di taglio EXP standard (80 80 07 00)", + "trim_jumps": "Solo sequenza di salti (per firmware EMT più vecchi)", + "lbl_trim_mode": "Modalità di taglio:", + "grp_transfer_2": "2. Invia direttamente a una chiavetta USB / unità o via Wi-Fi NetBridge", + "btn_save_exp_usb": "Salva EXP direttamente su chiavetta USB / cartella …", + "lbl_netbridge_url": "URL di NetBridge:", + "btn_send_netbridge": "Invia a Melco NetBridge via Wi-Fi", + "grp_transfer_3": "3. Immagine floppy FAT12 da 1,44 MB (.IMG) per emulatore USB (GoTek / HxC)", + "lbl_img_initial": "Immagine attuale: nuova immagine vuota da 1,44 MB (FAT12)", + "btn_open_img": "Apri .IMG esistente …", + "btn_add_cur_img": "Aggiungi il disegno attuale all'immagine", + "btn_del_file": "Elimina il file selezionato", + "btn_save_img": "Salva file .IMG …", + "unit_bytes": "byte", + "img_new": "Nuova immagine da 1,44 MB", + "img_free": "{src} — Spazio libero: {free} KB su {total} KB", + "fd_save_exp": "Salva Melco EXP", + "msg_saved_title": "Salvato", + "msg_exp_saved": "File di ricamo Melco salvato:\n{path}\n({size} byte)", + "msg_wifi_ok_title": "Trasferimento Wi-Fi riuscito", + "msg_wifi_ok_text": "Inviato a {url}:\n{body}", + "msg_netbridge_fail_title": "NetBridge non raggiungibile", + "msg_netbridge_fail_text": "Impossibile raggiungere {url}:\n{err}", + "fd_open_img": "Apri immagine floppy FAT12", + "fd_save_img": "Salva immagine floppy FAT12 da 1,44 MB", + "msg_img_saved_title": "Immagine floppy salvata", + "msg_img_saved_text": "Immagine FAT12 da 1,44 MB salvata:\n{path}\n\nSuggerimento per GoTek/FlashFloppy: sulla chiavetta USB dai alle immagini nomi come DSKA0000.IMG, DSKA0001.IMG, oppure copia direttamente il file .EXP se FlashFloppy lavora in modalità file diretto.", + "dlg_photo_title": "PhotoStitch — crea ricami da ritratti e foto", + "lbl_orig_photo": "Foto originale ({})", + "btn_other_photo": "📂 Scegli un'altra foto (Download / Desktop / Immagini …)", + "grp_photo_settings": "Impostazioni PhotoStitch", + "lbl_target_width": "Larghezza desiderata:", + "photo_mode_mono": "Incisione monocromatica (1 colore di filo su tessuto chiaro)", + "photo_mode_sepia": "Ritratto seppia (2 colori di filo: marrone chiaro + marrone scuro)", + "photo_mode_color4": "Mezzitoni CMYK a 4 colori (giallo, magenta, ciano, nero)", + "lbl_color_mode": "Modalità colore:", + "lbl_row_spacing_fine": "Distanza tra le file (finezza):", + "lbl_contrast": "Aumento del contrasto:", + "btn_photo_apply": "Calcola && applica PhotoStitch", + "pdf_title": "{} — Scheda di produzione e allestimento", + "pdf_created": "Creato con {app} il {date}", + "pdf_date_fmt": "%d/%m/%Y %H:%M", + "pdf_total_stitches": "Punti totali", + "pdf_size": "Misura (L × A)", + "pdf_color_changes": "Cambi colore / blocchi", + "pdf_blocks_val": "{} ({} blocchi)", + "pdf_trims": "Tagli del filo", + "pdf_hoop": "Telaio", + "pdf_runtime": "Durata (circa {} SPM)", + "pdf_thread_usage": "Filo più usato", + "pdf_machine": "Profilo della macchina", + "pdf_sequence": "Sequenza dei colori e assegnazione degli aghi ({} aghi)", + "tour_next": "Avanti →", + "tour_prev_tip": "Passo precedente", + "tour_close_tip": "Chiudi il tour (Esc)", + "tour_on_start": "All'avvio", + "tour_done": "Fatto ✓", + "tour_app_1_badge": "BENVENUTO · 1 / 7", + "tour_app_1_title": "La tela: il tuo disegno in 3D", + "tour_app_1_body": "Il tuo disegno è nel telaio, al centro. Per cominciare c'è il nostro stemma OpenStitch.

• Clicca e trascina: seleziona le parti, spostale o ridimensionale con la maniglia d'angolo.
• Rotella del mouse: ingrandisci con fluidità, fino ai singoli punti.", + "tour_app_1_action": "🎨 Prova un colore di tessuto nel telaio (scuro / sabbia / chiaro)", + "tour_app_2_badge": "SOPRA LA TELA · 2 / 7", + "tour_app_2_title": "Macchina, telaio e tessuto", + "tour_app_2_body": "Subito sopra la tela dici a OpenStitch su cosa stai ricamando:

• Macchina: Universale, Tajima, Brother, Barudan, Melco …
• Telaio: OpenStitch adatta il sottofondo e la compensazione della trazione alla misura. I telai grandi ricevono un sostegno in più contro l'effetto trampolino, e i cappellini si ricamano dal centro verso l'esterno e dalla visiera verso l'alto.
• Tessuto: adatta densità e compensazione della trazione, e consiglia stabilizzatore e ago.", + "tour_app_2_action": "⛶ Adatta il disegno al telaio (Auto-Fit)", + "tour_app_3_badge": "BARRA IN ALTO · 3 / 7", + "tour_app_3_title": "Immagine, testo, controllo ed esportazione", + "tour_app_3_body": "Accanto ai pulsanti dei file e ad Annulla trovi i passi principali:

• Immagine in punti (Ctrl+D): scegli un'immagine e OpenStitch toglie lo sfondo e crea le aree di punti.
• Testo (Ctrl+T): aggiungi testi e monogrammi.
• Controlla (F7): verifica il disegno e gli dà un punteggio su 100.
• Esporta (Ctrl+E): salva il file per la tua macchina.

PhotoStitch, Applicazione e Puff 3D sono nel menu Digitalizza, SVG è in File e Trasferisci è in Macchina & Esporta.", + "tour_app_3_action": "✨ Apri Immagine in punti …", + "tour_app_4_badge": "STRUMENTI · 4 / 7", + "tour_app_4_title": "Disegna a mano e modifica i nodi (N)", + "tour_app_4_body": "La barra stretta a sinistra mostra solo le icone. Avvicina il mouse a una per vederne il nome:

• Tatami (F) / Raso (S) / Filza (R): disegna le tue forme sulla tela.
• Nodi (N): sposta uno a uno i punti del contorno e trascina l'asse giallo per ruotare l'angolo dei punti.", + "tour_app_4_action": "❖ Attiva l'editor dei nodi e dell'angolo dei punti (N)", + "tour_app_5_badge": "COLORI DEI FILI · 5 / 7", + "tour_app_5_title": "Colori e ordine degli aghi", + "tour_app_5_body": "A sinistra scegli con un clic un colore dal catalogo fili (Madeira, Isacord, Gunold, Brother …) oppure ne mescoli uno tuo con RGB.

• Più sotto vedi l'ordine dei colori e degli aghi del tuo disegno, con il numero di punti per ogni colore.", + "tour_app_6_badge": "LIVELLI E IMPOSTAZIONI · 6 / 7", + "tour_app_6_title": "Livelli e impostazioni dell'oggetto", + "tour_app_6_body": "A destra imposti l'ordine di ricamo. Sotto regoli l'oggetto selezionato: distanza tra le file, motivo (ad esempio Contorno), compensazione della trazione, oppure puff 3D per il raso.

• Ogni modifica ricalcola i punti sulla tela subito.", + "tour_app_7_badge": "SIMULATORE E STATO · 7 / 7", + "tour_app_7_title": "Simulatore dei punti e barra di stato", + "tour_app_7_body": "Sotto la tela puoi riprodurre l'intero disegno punto per punto.

• La barra di stato in fondo mostra punti, misura, cambi colore, tagli e la durata stimata. Avvicina il mouse per vedere velocità e densità massima.
• La lingua si cambia in basso a destra.", + "tour_app_7_action": "▶ Avvia / ferma la simulazione", + 'chk_tag_rule': 'Regola fissa', + 'chk_tag_model': 'Stima', + 'cal_open': 'Calibra con tessuto reale …', + 'cal_title': 'Calibra tessuto', + 'cal_intro': '1. Carica la barra di prova e ricamala con il tessuto, lo stabilizzatore e la tensione che usi davvero.\n2. Misura la larghezza al centro della barra. Quella prevista è {width} mm.\n3. Inserisci la misura. La simulazione e la compensazione useranno il tuo valore reale.', + 'cal_load': 'Carica barra di prova', + 'cal_measured': 'Larghezza misurata:', + 'cal_apply': 'Applica', + 'cal_reset': 'Ripristina', + 'cal_state_estimate': 'Questo tessuto non è ancora stato misurato: la trazione è una stima.', + 'cal_state_measured': 'Misurato: la trazione è {factor} volte la stima.', + 'chk_disclaimer': 'Le regole fisse derivano esattamente dai punti. Le stime della trazione diventano precise calibrando il tessuto.', +} diff --git a/openstitch/locales/nl.py b/openstitch/locales/nl.py new file mode 100644 index 0000000..8e3c36f --- /dev/null +++ b/openstitch/locales/nl.py @@ -0,0 +1,524 @@ +"""Nederlands.""" + +TABLE: dict[str, str] = { + "menu_file": "&Bestand", + "menu_edit": "Bewer&ken", + "menu_view": "&Weergave", + "menu_create": "&Digitaliseren", + "menu_machine": "&Machine && export", + "menu_help": "&Help", + "tb_new": "Nieuw", + "tb_import": "Import", + "tb_svg": "SVG", + "tb_export": "Export", + "tb_pdf": "PDF", + "tb_auto": "Afbeelding naar steken", + "tb_photo": "PhotoStitch", + "tb_text": "Tekst", + "tb_applique": "Applicatie", + "tb_puff": "3D-puff", + "tb_transfer": "Overdracht", + "tb_tour": "Tour", + "lbl_machine": "Machine:", + "lbl_hoop": "Borduurraam:", + "btn_autofit": "Auto-fit", + "fabric_slate": "Stof: donker", + "fabric_sand": "Stof: zand", + "fabric_light": "Stof: licht", + "lbl_strategy": "Strategie", + "tool_select": "Selecteren (V)", + "tool_nodes": "Knooppunten (N)", + "tool_fill": "Tatami (F)", + "tool_satin": "Satijn (S)", + "tool_run": "Voorsteek (R)", + "tool_heatmap": "Heatmap", + "tool_zoom": "Op raam passen", + "hud_select": "Selecteren (V) · Slepen = verplaatsen, hoekgreep = schalen, muiswiel = zoomen", + "hud_nodes": "Knooppunten & steekhoek (N) · Witte knooppunten = contour aanpassen, gele greep = steekhoek draaien", + "hud_fill": "Tatamivulling tekenen (F) · Klik = punt toevoegen, dubbelklik/Enter = klaar", + "hud_satin": "Satijnkolom tekenen (S) · Klik = punt toevoegen, dubbelklik/Enter = klaar", + "hud_run": "Voorsteek tekenen (R) · Klik = punt toevoegen, dubbelklik/Enter = klaar", + "dock_palette": "Garens && kleuren", + "lbl_catalog": "Garencatalogus:", + "lbl_seq": "Draad- en naaldvolgorde in het ontwerp:", + "needle": "Naald", + "dock_right": "Lagen && instellingen", + "btn_visible": "👁 Zichtbaar", + "btn_copy": "⧉ Kopie", + "lbl_inspector": "Objectinstellingen (direct herberekend):", + "lbl_no_sel": "Geen object geselecteerd.\nKlik op een onderdeel op het werkblad of in de lagenlijst.", + "lbl_obj_name": "Naam", + "dock_bottom": "Steeksimulator && afspeler", + "btn_play": "▶ Simuleren", + "btn_pause": "⏸ Pauze", + "btn_show_all": "⏭ Alles tonen", + "lbl_progress": " Voortgang:", + "lbl_speed": "Snelheid:", + "stats_stitches": "Steken", + "stats_size": "Afmeting", + "stats_avg": "Gem. lengte", + "stats_spm": "Eff. snelheid", + "stats_peak": "Piekdichtheid", + "stats_colors": "Kleurwissels", + "stats_runtime": "Looptijd: ca.", + "stats_min": "min", + "m_new": "Nieuw ontwerp", + "m_open": "Project openen (.ostitch) …", + "m_save": "Project opslaan (.ostitch) …", + "m_import": "Borduurbestand importeren (EXP, DST, PES, JEF …) …", + "m_import_svg": "SVG-vectorafbeelding importeren (.svg) …", + "m_export": "Borduurbestand exporteren (EXP, DST, PES, JEF …) …", + "m_export_pdf": "Productieblad opslaan als PDF …", + "m_export_png": "Realistische 3D-voorvertoning opslaan als PNG …", + "m_quit": "Afsluiten", + "m_auto": "Afbeelding automatisch digitaliseren (Auto-Digitizer) …", + "m_photo": "PhotoStitch (portretfoto → borduurwerk) …", + "m_text": "Tekst / monogram invoegen …", + "m_applique": "Applicatie maken van vorm", + "m_puff": "3D-puff-schuimmodus voor satijn aan/uit", + "m_transfer": "Overdracht naar machine / diskette / USB / NetBridge …", + "m_doctor": "Ontwerp controleren (virtuele proefborduring)", + "m_optimize": "Kleuren minimaliseren (minder naaldwissels)", + "m_tour": "Interactieve rondleiding door de studio …", + "m_restore_logo": "Officieel OpenStitch-logo herstellen", + "m_undo": "Ongedaan maken", + "m_redo": "Opnieuw doen", + "m_duplicate": "Geselecteerd object dupliceren", + "m_delete": "Geselecteerd object verwijderen", + "m_center": "Ontwerp centreren in raam", + "m_fit": "Optimaal in huidig raam passen (Auto-fit)", + "m_pick_hoop": "Kleinste passende raam automatisch kiezen", + "m_scale": "Ontwerp schalen (% / mm) …", + "m_3d": "3D-draadweergave", + "m_jumps": "Sprongsteken tonen", + "m_grid": "Millimeterraster tonen", + "m_heatmap": "Heatmap van steekdichtheid (stofbelasting)", + "m_zoom": "Zoomen op raam", + "lbl_lang": "Taal:", + "status_computing": "Steken worden berekend …", + "dlg_unsaved_title": "Niet-opgeslagen wijzigingen", + "dlg_unsaved_text": "Het huidige ontwerp heeft niet-opgeslagen wijzigingen. Nu opslaan?", + "status_plan_error": "Steken maken is mislukt", + "kind_column": "Satijnkolom", + "param_column_width": "Kolombreedte (mm)", + "msg_overwrite_title": "Bestand vervangen?", + "msg_overwrite_text": "{name} staat al op de diskette-image. Vervangen?", + "ph_text": "Jouw tekst", + "tip_use_micro": "Voor zulke kleine letters is “OpenStitch Micro” beter (klik hier)", + "act_shortcuts": "Sneltoetsen …", + "act_report": "Probleem melden …", + "act_about": "Over OpenStitch …", + "about_text": "Gratis borduur- en digitaliseersoftware. Licentie: AGPL-3.0, de broncode is vrij beschikbaar.", + "keys_title": "Sneltoetsen", + "key_select": "Selecteren en verplaatsen", + "key_nodes": "Knooppunten bewerken", + "key_fill": "Vulling tekenen", + "key_satin": "Satijnkolom tekenen", + "key_run": "Voorsteek tekenen", + "key_finish": "Tekenen afronden", + "key_cancel": "Tekenen annuleren", + "key_zoom": "Zoomen", + "key_pan": "Weergave verschuiven", + "key_wheel": "Muiswiel", + "key_middle": "Middelste muisknop", + "crash_title": "Dat had niet mogen gebeuren", + "crash_text": "OpenStitch is op een fout gestuit. Je werk is opgeslagen en je kunt gewoon verder.\n\nWil je de fout melden? Voeg dan dit bestand toe:\n{}", + "exp_title": "Naar machine sturen", + "exp_heading": "Klaar om te borduren?", + "exp_facts": "{st} steken · {colors} kleuren · {w} × {h} mm", + "exp_format": "Bestandsformaat:", + "exp_recommended": "{} (aanbevolen)", + "exp_name": "Bestandsnaam:", + "exp_short": "Korte naam voor oudere machines", + "exp_short_tip": "Veel oudere machines tonen maar 8 gewone tekens.", + "exp_where": "Opslaan in:", + "exp_usb": "USB-stick: {}", + "exp_browse": "Map …", + "exp_refresh": "Vernieuwen", + "exp_threads": "Draadvolgorde voor de machine", + "exp_save": "Opslaan", + "exp_done": "“{name}” opgeslagen en gecontroleerd: {st} steken correct teruggelezen. Steek de stick nu in je machine.", + "exp_overwrite": "“{}” bestaat daar al. Vervangen?", + "exp_done_plain": "“{name}” opgeslagen.", + "exp_failed": "Opslaan is mislukt: {}", + "btn_close": "Sluiten", + "chk_title": "Ontwerp controleren", + "chk_running": "Bezig met controleren …", + "chk_failed": "Controle mislukt", + "chk_empty": "Nog geen steken", + "chk_again": "Opnieuw controleren", + "chk_good": "Klaar om te borduren", + "chk_ok": "Te borduren, met kleine risico’s", + "chk_bad": "Los dit eerst beter op", + "chk_none": "Geen problemen gevonden.", + "chk_facts": "{st} steken · {colors} kleuren · {trims} afsnijdingen · ca. {min} min · {thread} m draad", + "chk_preview": "Zo trekt de stof samen", + "chk_boost": "Effect overdrijven", + "chk_show": "Tonen", + "chk_fix": "Herstellen", + "undo_fix": "Automatisch herstel", + "chk_sev_error": "Probleem", + "chk_sev_warning": "Waarschuwing", + "chk_sev_info": "Opmerking", + "chk_short_stitch_t": "Zeer korte steken", + "chk_short_stitch_d": "Steken korter dan 0,3 mm: {count}. De naald prikt bijna in hetzelfde gaatje en de draad kan breken.", + "chk_over_max_stitch_t": "Steken te lang voor de machine", + "chk_over_max_stitch_d": "{count} steken zijn langer dan de machine aankan (langste: {max_mm} mm).", + "chk_long_float_t": "Lange losse steken", + "chk_long_float_d": "{count} steken zijn langer dan 7,5 mm (tot {max_mm} mm). Ze blijven in dagelijks gebruik gemakkelijk haken.", + "chk_no_lock_t": "Draadeinden niet vergrendeld", + "chk_no_lock_d": "Op {count} plekken ontbreken vergrendelsteken. Het borduurwerk kan daar bij het wassen losgaan.", + "chk_orphan_run_t": "Stukken te kort", + "chk_orphan_run_d": "{count} stukken hebben minder dan 3 steken en houden nauwelijks na het afsnijden van de draad.", + "chk_untrimmed_jump_t": "Sprongen zonder afsnijding", + "chk_untrimmed_jump_d": "Door {count} sprongen ligt er een draad dwars over het ontwerp.", + "chk_needle_pileup_t": "Te veel naaldprikken op één plek", + "chk_needle_pileup_d": "Op {count} plekken prikt de naald tot {max_hits} keer. Dat kan stof en naald beschadigen.", + "chk_too_dense_t": "Te dicht geborduurd", + "chk_too_dense_d": "{count} mm² hebben tot {peak} draadlagen (maximum voor deze stof: {limit}). Het vlak wordt plankhard.", + "chk_outside_hoop_t": "Ontwerp past niet in het raam", + "chk_outside_hoop_d": "Steken liggen in de randzone van het raam. De naald kan het raam raken.", + "chk_low_coverage_t": "Stof schemert door", + "chk_low_coverage_d": "“{object}” is maar voor {percent}% bedekt.", + "chk_too_many_colors_t": "Meer kleuren dan naalden", + "chk_too_many_colors_d": "{count} kleuren op {needles} naalden: je moet onderweg van draad wisselen.", + "chk_registration_gap_t": "Kans op openingen tussen objecten", + "chk_registration_gap_d": "Door het samentrekken van de stof verschuiven delen tot {mm} mm ten opzichte van elkaar. Meer trekcompensatie helpt.", + "chk_puckering_t": "Stof kan gaan rimpelen", + "chk_puckering_d": "Het borduurwerk trekt de stof ongeveer {mm} mm samen. Gebruik een stevigere stabilizer.", + "chk_small_text_t": "Letters te klein voor dit lettertype", + "chk_small_text_d": "“{object}” is {mm} mm hoog. Contourlettertypen lopen op deze grootte dicht. Gebruik “OpenStitch Micro”.", + "chk_export_ok_t": "{ext}-bestand gecontroleerd", + "chk_export_ok_d": "{st} steken teruggelezen, grootste afwijking {err} mm.", + "chk_export_bad_t": "Probleem in het {ext}-bestand", + "tb_open": "Openen", + "tb_save": "Opslaan", + "tb_check": "Controle", + "act_home": "Startpagina tonen", + "act_theme_dark": "Donker thema", + "act_theme_light": "Licht thema", + "menu_recent": "Recent geopend", + "lbl_fabric": "Stof:", + "fab_woven": "Katoen / overhemd (geweven)", + "fab_denim": "Denim / canvas", + "fab_twill_cap": "Pet (twill)", + "fab_pique": "Polo piqué", + "fab_jersey": "T-shirt (jersey)", + "fab_fleece": "Fleece / sweater", + "fab_towel": "Badstof / handdoek", + "fab_leather": "Leer", + "fab_silk": "Zijde / fijne stof", + "stab_cutaway": "knip-stabilizer", + "stab_tearaway": "scheur-stabilizer", + "stab_none": "geen stabilizer", + "fabric_advice": "{fabric}: gebruik {stabilizer}, naald {needle}. Dichtheid en trekcompensatie worden aangepast.", + "fabric_topping": "Leg wateroplosbare topping bovenop, zodat de steken er niet in wegzakken.", + "tip_obj_visible": "Object tonen of verbergen", + "tip_obj_copy": "Object dupliceren", + "param_knockout": "Verborgen delen overslaan", + "canvas_empty_hint": "Sleep hier een afbeelding naartoe of kies links een tekengereedschap", + "start_title": "Wat wil je borduren?", + "start_subtitle": "Kies een beginpunt. Ervaring is niet nodig.", + "start_image": "Maak borduurwerk van een afbeelding", + "start_image_d": "Kies een logo of tekening en OpenStitch doet de rest.", + "start_text": "Tekst borduren", + "start_text_d": "Een naam of slogan, goed leesbaar vanaf 2,5 mm hoog.", + "start_draw": "Zelf tekenen", + "start_draw_d": "Teken vullingen, satijnkolommen en lijnen met de muis.", + "start_open": "Een bestand openen", + "start_open_d": "Project, borduurbestand (DST, PES, JEF …), SVG of afbeelding.", + "start_samples": "Of begin met een voorbeeld", + "start_recent": "Recente bestanden", + "start_tour": "Volg een korte rondleiding", + "sample_patch": "Naamlabel", + "sample_heart": "Hart", + "sample_flower": "Bloem", + "sample_monogram": "Monogram", + "fd_open_any": "Bestand openen", + "filter_supported": "Alle ondersteunde bestanden", + "err_file_gone": "Het bestand is niet gevonden:\n{}", + "err_unknown_type": "“{}” heeft een bestandstype dat OpenStitch niet kent.", + "dlg_recover_title": "Je werk herstellen?", + "dlg_recover_text": "OpenStitch is niet goed afgesloten. De laatste automatische back-up openen?", + "status_autosave_failed": "Automatisch opslaan is mislukt: {}", + "err_project_damaged": "“{name}” is beschadigd of geen OpenStitch-projectbestand.", + "label_colon": ":", + "btn_cancel": "Annuleren", + "btn_apply": "Toepassen", + "btn_save": "Opslaan", + "btn_discard": "Verwerpen", + "dlg_error": "Fout", + "dlg_notice": "Melding", + "filter_all_files": "Alle bestanden", + "filter_all_images": "Alle afbeeldingen", + "filter_images": "Afbeeldingen", + "filter_all_img_vec": "Alle afbeeldings- en vectorbestanden", + "filter_raster": "Rasterafbeeldingen", + "filter_svg": "SVG-vectorafbeelding", + "filter_photos": "Foto’s en afbeeldingen", + "filter_project": "OpenStitch-project", + "filter_emb": "Borduurbestanden", + "filter_png": "PNG-afbeelding", + "filter_floppy": "Diskette-image", + "err_open_title": "Fout bij openen van bestand", + "err_load_title": "Fout bij laden van bestand", + "err_svg_title": "SVG-importfout", + "err_import_title": "Importfout", + "err_save_title": "Opslagfout", + "err_export_title": "Exportfout", + "err_pdf_title": "PDF-fout", + "err_png_title": "PNG-fout", + "err_png_text": "De afbeelding kon niet worden opgeslagen:\n{}", + "err_image_title": "Afbeeldingsfout", + "app_tagline": "Universele open-source borduur- en digitaliseersuite", + "tb_title_studio": "Studiowerkbalk", + "tb_title_tools": "Tekengereedschap", + "tip_autofit": "Het ontwerp optimaal in het gekozen raam passen (Ctrl+F)", + "tip_fabric": "Stofachtergrond in het raam wisselen (donker / warm zand / licht)", + "tip_tool_select": "Objecten selecteren, verplaatsen en schalen (toets V)", + "tip_tool_nodes": "Contourpunten en de steekhoekas direct slepen (toets N)", + "tip_tool_fill": "Een nieuw tatamivlak op het werkblad tekenen (toets F)", + "tip_tool_satin": "Een nieuwe satijnkolom op het werkblad tekenen (toets S)", + "tip_tool_run": "Een nieuw voorsteekpad tekenen (toets R)", + "tip_tool_heatmap": "Heatmap van de steekdichtheid tonen/verbergen (groen/geel/rood) (Ctrl+H)", + "tip_tool_zoom": "De weergave aan het raam aanpassen (Ctrl+0)", + "tip_obj_up": "Object eerder in de steekvolgorde zetten", + "tip_obj_down": "Object later in de steekvolgorde zetten", + "tip_obj_delete": "Geselecteerd object verwijderen (Del)", + "sim_all": "Alle", + "sim_speed_suffix": " st./tick", + "abbr_stitches": "st.", + "stats_trims": "Afsnijdingen", + "kind_fill": "Vulling", + "kind_satin": "Satijn", + "kind_run": "Voorsteek", + "kind_text": "Tekst", + "kind_stitches": "Steken", + "obj_hidden": "[Verborgen]", + "btn_font_arc": "Lettertype en boog aanpassen …", + "status_hoop_strategy": "Raamstrategie actief: {}", + "status_saved": "Opgeslagen: {}", + "color_dialog_title": "Draadkleur kiezen", + "default_design_name": "Nieuw_ontwerp", + "fd_open_project": "Project openen", + "fd_save_project": "Project opslaan", + "fd_import_emb": "Borduurbestand importeren", + "fd_import_svg": "SVG-vectorafbeelding importeren", + "fd_export_emb": "Borduurbestand exporteren", + "fd_save_pdf": "Productieblad opslaan (PDF)", + "pdf_file_suffix": "productieblad", + "fd_save_png": "3D-steekvoorbeeld opslaan", + "fd_pick_image": "Kies een afbeelding, tekening of logo (Downloads / Afbeeldingen / Bureaublad)", + "fd_pick_photo": "Kies een portret- of landschapsfoto (Downloads / Afbeeldingen / Bureaublad)", + "msg_applique_title": "Applicatie", + "msg_applique_text": "Selecteer eerst een vulling of satijnvorm op het werkblad.", + "msg_export_verified_title": "Export en binaire controle geslaagd", + "msg_export_verified_text": "✅ Borduurbestand opgeslagen en in de simulator gecontroleerd:\n{path}\n\n• Bestandsgrootte: {size} bytes\n• Gecontroleerde steken: {stitches}\n• Afmetingen: {w:.1f} × {h:.1f} mm\n• Max. staplengte: {step:.1f} mm\n• Kleurwissels: {colors} · Sprongen: {jumps}", + "msg_export_ok_title": "Export geslaagd", + "msg_export_ok_text": "Bestand opgeslagen:\n{}", + "msg_pdf_ok_title": "PDF gemaakt", + "msg_pdf_ok_text": "Productieblad opgeslagen:\n{}", + "msg_puff_title": "3D-puff-schuim", + "msg_puff_text": "Selecteer een satijnobject.", + "dlg_scale_title": "Ontwerp schalen (steken worden opnieuw berekend!)", + "dlg_scale_label": "Schaalfactor (%):", + "hoop_round9": "Rond 9 cm (klein/borst)", + "hoop_round12": "Rond 12 cm (borstlogo)", + "hoop_round15": "Rond 15 cm (standaard)", + "hoop_round18": "Rond 18 cm (groot)", + "hoop_round21": "Rond 21 cm (XL)", + "hoop_cap": "Pet 13 × 5 cm", + "hoop_widecap": "Brede pet 30 × 7 cm", + "hoop_rect13x18": "Rechthoek 13 × 18 cm (thuis)", + "hoop_jacket": "Jasrug 30 × 30 cm", + "hoop_field40x30": "Groot veld 40 × 30 cm (industrieel)", + "hoop_strat_small": "Strakke spanning · fijne details (-10% trekcompensatie, standaard onderlaag)", + "hoop_strat_medium": "Gebalanceerd · standaard borst-/mouwraam (100% trekcompensatie)", + "hoop_strat_large": "Anti-trampoline · versterkte onderlaag (+20% trekcompensatie + kruisraster op grote vlakken)", + "hoop_strat_jacket": "Stabilisatie voor jasrug (+35% trekcompensatie, dubbele rasteronderlaag, max. 750 SPM)", + "hoop_strat_cap": "Petmodus (van het midden naar buiten en van de klep omhoog, +30% trekcompensatie)", + "hoop_strat_default": "Standaard", + "machine_universal_multi": "Universele standaard (DST / PES / EXP · 15 naalden)", + "machine_tajima_tmez": "Tajima TMEZ / TFMX / TMBR (15 naalden)", + "machine_brother_pr": "Brother PR-serie / Persona (6–10 naalden)", + "machine_brother_home": "Brother / Baby Lock thuismachine (1 naald · PES)", + "machine_barudan_bext": "Barudan BEKT / BEXT (15 naalden)", + "machine_ricoma_happy_zsk": "Ricoma / HappyJapan / SWF / ZSK (12–15 naalden)", + "machine_janome_elna": "Janome / Elna / Bernina thuismachine (JEF / EXP)", + "machine_pfaff_husqvarna": "Pfaff / Husqvarna Viking (VP3)", + "machine_melco_emt10_4": "Melco EMT10/4 (4 koppen / 10 naalden)", + "machine_melco_amaya_bravo": "Melco Amaya / EMT16X / Bravo (16 naalden)", + "param_angle": "Steekhoek (°)", + "param_fill_spacing": "Rijafstand (mm)", + "param_satin_spacing": "Dichtheid (mm)", + "param_stitch_len": "Steeklengte (mm)", + "param_pattern": "Patroon", + "param_underlay": "Onderlaag", + "param_pull_comp": "Trekcompensatie (mm)", + "param_max_stitch": "Max. steek / splitsen (mm)", + "param_underlay_style": "Type onderlaag", + "param_puff_3d": "3D-puff (petmodus)", + "param_repeats": "Herhalingen (0 = enkel, 1 = drievoudig)", + "param_text": "Tekst", + "param_font": "Lettertype", + "param_height": "Lettershoogte (mm)", + "param_letter_spacing": "Letterafstand (mm)", + "param_arc_radius": "Boogstraal (mm, 0 = recht)", + "param_mode": "Steektype", + "param_density": "Dichtheid (mm)", + "opt_standard": "Standaard", + "opt_diagonal": "Diagonaal", + "opt_ziegel": "Baksteen", + "opt_wellen": "Golven", + "opt_kontur": "Contour", + "opt_auto": "Automatisch", + "opt_mitte": "Middenloop", + "opt_kante": "Randloop", + "opt_zickzack": "Zigzag", + "opt_kante+zickzack": "Randloop + zigzag", + "opt_satin": "Satijnsteek", + "opt_fill": "Tatamivulling", + "dlg_auto_title": "Afbeelding automatisch digitaliseren (Auto-Digitizer)", + "lbl_orig_image": "Originele afbeelding ({})", + "btn_other_image": "📂 Andere afbeelding kiezen (Downloads / Bureaublad / Afbeeldingen …)", + "grp_auto_settings": "Borduurinstellingen en automatisering", + "lbl_target_width_motif": "Gewenste breedte van het ontwerp:", + "lbl_max_colors": "Max. draadkleuren (naalden):", + "cb_remove_bg": "Achtergrond van de afbeelding automatisch verwijderen", + "fabric_opt_normal": "Standaard (katoen / twill / universeel)", + "fabric_opt_strick": "Piqué / polo / tricot (meer trekcompensatie)", + "fabric_opt_frottee": "Badstof / handdoek (dichter + sterke onderlaag)", + "fabric_opt_cap": "Pet (hoge trekcompensatie)", + "fabric_opt_leicht": "Lichte stof / overhemd (lagere dichtheid)", + "lbl_fabric_type": "Stof / materiaal:", + "lbl_density_row": "Steekdichtheid (rijafstand):", + "lbl_satin_limit": "Satijngrens (smaller = satijn):", + "lbl_min_area": "Kleine vlakjes eruit filteren onder:", + "cb_outline": "Een satijncontour rond het ontwerp toevoegen", + "cb_palette": "Kleuren afstemmen op het garenpalet", + "status_ready": "Klaar.", + "btn_digitize_apply": "Digitaliseren && nu toepassen", + "fd_pick_logo": "Kies een afbeelding of logo (Downloads / Afbeeldingen / Bureaublad)", + "fd_pick_logo_short": "Kies een afbeelding of logo", + "err_digitize_title": "Digitaliseren mislukt", + "prog_computing_stitches": "Steken berekenen ({}/{}) …", + "prog_prepare": "Afbeelding voorbereiden …", + "prog_reduce": "Kleuren verminderen …", + "prog_clean": "Vlakken opschonen …", + "prog_vectorize": "Contouren vectoriseren …", + "prog_done": "Klaar", + "prog_classify": "Vlak {}/{} indelen …", + "dlg_text_title": "Tekst / monogram maken", + "lbl_text": "Tekst:", + "lbl_font_file": "Lettertype (TTF/OTF):", + "lbl_letter_height": "Lettershoogte (hoofdletterhoogte):", + "lbl_letter_spacing": "Letterafstand:", + "sfx_arc": " mm (0 = recht)", + "lbl_arc_radius": "Boogstraal:", + "text_mode_auto": "Automatisch (satijn tot 7 mm, daarboven tatami)", + "text_mode_satin": "Altijd satijnsteek (glanzende letters)", + "text_mode_fill": "Altijd tatamivulling", + "lbl_stitch_type": "Steektype:", + "lbl_stitch_density": "Steekdichtheid:", + "msg_enter_text": "Typ eerst een tekst.", + "text_obj_name": "Tekst “{}”", + "dlg_transfer_title": "Overdracht naar machine (USB / 1,44 MB diskette-emulator / wifi NetBridge)", + "grp_transfer_1": "1. Machine- en afsnijinstellingen (EXP / industrieel formaat)", + "lbl_dos_name": "DOS-bestandsnaam (8.3-formaat):", + "trim_both": "Gecombineerd: EXP-afsnijcode + 3 sprongen (hoogste compatibiliteit)", + "trim_code": "Standaard EXP-afsnijcode (80 80 07 00)", + "trim_jumps": "Alleen sprongreeks (voor oudere EMT-firmware)", + "lbl_trim_mode": "Afsnijmodus:", + "grp_transfer_2": "2. Direct naar een USB-stick / station sturen of via wifi NetBridge", + "btn_save_exp_usb": "EXP direct opslaan op USB-stick / in map …", + "lbl_netbridge_url": "NetBridge-URL:", + "btn_send_netbridge": "Via wifi naar Melco NetBridge sturen", + "grp_transfer_3": "3. 1,44 MB FAT12-diskette-image (.IMG) voor USB-emulator (GoTek / HxC)", + "lbl_img_initial": "Huidige image: nieuwe lege 1,44 MB-image (FAT12)", + "btn_open_img": "Bestaande .IMG openen …", + "btn_add_cur_img": "Huidig ontwerp aan image toevoegen", + "btn_del_file": "Geselecteerd bestand verwijderen", + "btn_save_img": ".IMG-bestand opslaan …", + "unit_bytes": "bytes", + "img_new": "Nieuwe 1,44 MB-image", + "img_free": "{src} — Vrije ruimte: {free} KB van {total} KB", + "fd_save_exp": "Melco EXP opslaan", + "msg_saved_title": "Opgeslagen", + "msg_exp_saved": "Melco-borduurbestand opgeslagen:\n{path}\n({size} bytes)", + "msg_wifi_ok_title": "Wifi-overdracht geslaagd", + "msg_wifi_ok_text": "Verzonden naar {url}:\n{body}", + "msg_netbridge_fail_title": "NetBridge niet bereikbaar", + "msg_netbridge_fail_text": "{url} is niet bereikbaar:\n{err}", + "fd_open_img": "FAT12-diskette-image openen", + "fd_save_img": "1,44 MB FAT12-diskette-image opslaan", + "msg_img_saved_title": "Diskette-image opgeslagen", + "msg_img_saved_text": "1,44 MB FAT12-image opgeslagen:\n{path}\n\nTip voor GoTek/FlashFloppy: geef de images op de USB-stick namen als DSKA0000.IMG, DSKA0001.IMG, of kopieer het .EXP-bestand direct als FlashFloppy in directbestandsmodus draait.", + "dlg_photo_title": "PhotoStitch — portret- en fotoborduurwerk maken", + "lbl_orig_photo": "Originele foto ({})", + "btn_other_photo": "📂 Andere foto kiezen (Downloads / Bureaublad / Afbeeldingen …)", + "grp_photo_settings": "PhotoStitch-instellingen", + "lbl_target_width": "Gewenste breedte:", + "photo_mode_mono": "Monochrome gravure (1 draadkleur op lichte stof)", + "photo_mode_sepia": "Sepiaportret (2 draadkleuren: lichtbruin + donkerbruin)", + "photo_mode_color4": "4-kleuren CMYK-halftoon (geel, magenta, cyaan, zwart)", + "lbl_color_mode": "Kleurmodus:", + "lbl_row_spacing_fine": "Rijafstand (fijnheid):", + "lbl_contrast": "Contrastversterking:", + "btn_photo_apply": "PhotoStitch berekenen && toepassen", + "pdf_title": "{} — Productie- en instelblad", + "pdf_created": "Gemaakt met {app} op {date}", + "pdf_date_fmt": "%d-%m-%Y %H:%M", + "pdf_total_stitches": "Totaal aantal steken", + "pdf_size": "Afmeting (B × H)", + "pdf_color_changes": "Kleurwissels / blokken", + "pdf_blocks_val": "{} ({} blokken)", + "pdf_trims": "Draadafsnijdingen", + "pdf_hoop": "Borduurraam", + "pdf_runtime": "Looptijd (ca. {} SPM)", + "pdf_thread_usage": "Verbruik bovendraad", + "pdf_machine": "Machineprofiel", + "pdf_sequence": "Kleurvolgorde en naaldtoewijzing ({} naalden)", + "tour_next": "Volgende →", + "tour_prev_tip": "Vorige stap", + "tour_close_tip": "Tour sluiten (Esc)", + "tour_on_start": "Bij het opstarten", + "tour_done": "Klaar ✓", + "tour_app_1_badge": "WELKOM · 1 / 7", + "tour_app_1_title": "Het werkblad: je ontwerp in 3D", + "tour_app_1_body": "Je ontwerp ligt in het midden in het raam. In het begin is dat ons OpenStitch-wapen.

• Klikken en slepen: onderdelen selecteren, verplaatsen of met de hoekgreep vergroten of verkleinen.
• Muiswiel: soepel inzoomen, tot op de afzonderlijke steken.", + "tour_app_1_action": "🎨 Probeer een stofkleur in het raam (donker / zand / licht)", + "tour_app_2_badge": "BOVEN HET WERKBLAD · 2 / 7", + "tour_app_2_title": "Machine, raam en stof", + "tour_app_2_body": "Direct boven het werkblad vertel je OpenStitch waarop je borduurt:

• Machine: Universeel, Tajima, Brother, Barudan, Melco …
• Raam: OpenStitch past de onderlaag en de trekcompensatie aan op de grootte. Grote ramen krijgen extra steun tegen stuiteren, en petten worden vanuit het midden naar buiten en van de klep omhoog geborduurd.
• Stof: past dichtheid en trekcompensatie aan en adviseert een stabilizer en naald.", + "tour_app_2_action": "⛶ Het ontwerp in het raam passen (Auto-fit)", + "tour_app_3_badge": "WERKBALK BOVENAAN · 3 / 7", + "tour_app_3_title": "Afbeelding, tekst, controle en export", + "tour_app_3_body": "Naast de bestandsknoppen en Ongedaan maken vind je de belangrijkste stappen:

• Afbeelding naar steken (Ctrl+D): kies een afbeelding en OpenStitch verwijdert de achtergrond en maakt de steekvlakken.
• Tekst (Ctrl+T): voeg tekst en monogrammen toe.
• Controle (F7): test je ontwerp en geeft het een score op 100.
• Export (Ctrl+E): slaat het bestand voor je machine op.

PhotoStitch, Applicatie en 3D-puff staan in het menu Digitaliseren, SVG staat onder Bestand en Overdracht onder Machine & export.", + "tour_app_3_action": "✨ Afbeelding naar steken openen …", + "tour_app_4_badge": "GEREEDSCHAP · 4 / 7", + "tour_app_4_title": "Met de hand tekenen en knooppunten bewerken (N)", + "tour_app_4_body": "De smalle balk links toont alleen pictogrammen. Wijs er een aan met de muis om de naam te zien:

• Tatami (F) / Satijn (S) / Voorsteek (R): teken je eigen vormen op het werkblad.
• Knooppunten (N): verplaats contourpunten één voor één en sleep de gele as om de steekhoek te draaien.", + "tour_app_4_action": "❖ Knooppunten- en steekhoekeditor aanzetten (N)", + "tour_app_5_badge": "DRAADKLEUREN · 5 / 7", + "tour_app_5_title": "Kleuren en naaldvolgorde", + "tour_app_5_body": "Links kies je met één klik een kleur uit de garencatalogus (Madeira, Isacord, Gunold, Brother …), of mix je eigen kleur met RGB.

• Daaronder zie je de volgorde van kleuren en naalden in je ontwerp, met het aantal steken per kleur.", + "tour_app_6_badge": "LAGEN EN INSTELLINGEN · 6 / 7", + "tour_app_6_title": "Lagen en objectinstellingen", + "tour_app_6_body": "Rechts stel je de borduurvolgorde in. Daaronder pas je het geselecteerde object aan: rijafstand, patroon (bijvoorbeeld Contour), trekcompensatie of 3D-puff voor satijn.

• Elke wijziging herberekent de steken op het werkblad meteen.", + "tour_app_7_badge": "SIMULATOR EN STATUS · 7 / 7", + "tour_app_7_title": "Steeksimulator en statusbalk", + "tour_app_7_body": "Onder het werkblad kun je het hele ontwerp steek voor steek afspelen.

• De statusbalk helemaal onderaan toont steken, afmeting, kleurwissels, afsnijdingen en de geschatte looptijd. Wijs er met de muis naar voor snelheid en piekdichtheid.
• De taal wijzig je rechtsonder.", + "tour_app_7_action": "▶ Simulatie starten / stoppen", + 'chk_tag_rule': 'Vaste regel', + 'chk_tag_model': 'Schatting', + 'cal_open': 'Kalibreren met echte stof …', + 'cal_title': 'Stof kalibreren', + 'cal_intro': '1. Laad de testbalk en borduur die met de stof, versteviging en spanning die je echt gebruikt.\n2. Meet de breedte in het midden van de balk. Gepland is {width} mm.\n3. Vul de meting in. De simulatie en trekcompensatie gebruiken dan je echte waarde.', + 'cal_load': 'Testbalk laden', + 'cal_measured': 'Gemeten breedte:', + 'cal_apply': 'Toepassen', + 'cal_reset': 'Herstellen', + 'cal_state_estimate': 'Deze stof is nog niet gemeten: de trekkracht is een schatting.', + 'cal_state_measured': 'Gemeten: de trekkracht is {factor} keer de schatting.', + 'chk_disclaimer': 'Vaste regels volgen precies uit de steken. Schattingen van de trekkracht worden nauwkeurig als je de stof kalibreert.', +} diff --git a/openstitch/locales/pl.py b/openstitch/locales/pl.py new file mode 100644 index 0000000..08b36c4 --- /dev/null +++ b/openstitch/locales/pl.py @@ -0,0 +1,524 @@ +"""Polski.""" + +TABLE: dict[str, str] = { + "menu_file": "&Plik", + "menu_edit": "&Edycja", + "menu_view": "&Widok", + "menu_create": "&Digitalizacja", + "menu_machine": "&Maszyna && eksport", + "menu_help": "P&omoc", + "tb_new": "Nowy", + "tb_import": "Import", + "tb_svg": "SVG", + "tb_export": "Eksport", + "tb_pdf": "PDF", + "tb_auto": "Obraz → haft", + "tb_photo": "PhotoStitch", + "tb_text": "Napis", + "tb_applique": "Aplikacja", + "tb_puff": "3D-Puff", + "tb_transfer": "Transfer", + "tb_tour": "Przewodnik", + "lbl_machine": "Maszyna:", + "lbl_hoop": "Tamborek:", + "btn_autofit": "Auto-Fit", + "fabric_slate": "Tkanina: ciemna", + "fabric_sand": "Tkanina: piaskowa", + "fabric_light": "Tkanina: jasna", + "lbl_strategy": "Strategia", + "tool_select": "Zaznacz (V)", + "tool_nodes": "Węzły (N)", + "tool_fill": "Tatami (F)", + "tool_satin": "Satyna (S)", + "tool_run": "Prosty (R)", + "tool_heatmap": "Mapa gęstości", + "tool_zoom": "Dopasuj do tamborka", + "hud_select": "Zaznacz (V) · Przeciąganie = przesuwanie, uchwyt w rogu = skalowanie, kółko myszy = powiększenie", + "hud_nodes": "Węzły i kąt ściegu (N) · Białe węzły = zmiana konturu, żółty uchwyt = obrót kąta ściegu", + "hud_fill": "Rysuj wypełnienie tatami (F) · Klik = dodaj punkt, podwójny klik/Enter = zakończ", + "hud_satin": "Rysuj kolumnę satynową (S) · Klik = dodaj punkt, podwójny klik/Enter = zakończ", + "hud_run": "Rysuj ścieg prosty (R) · Klik = dodaj punkt, podwójny klik/Enter = zakończ", + "dock_palette": "Nici && kolory", + "lbl_catalog": "Katalog nici:", + "lbl_seq": "Kolejność nici i igieł w projekcie:", + "needle": "Igła", + "dock_right": "Warstwy && ustawienia", + "btn_visible": "👁 Widoczny", + "btn_copy": "⧉ Kopiuj", + "lbl_inspector": "Parametry obiektu (przeliczane na żywo):", + "lbl_no_sel": "Nie zaznaczono obiektu.\nKliknij element na płótnie lub na liście warstw.", + "lbl_obj_name": "Nazwa", + "dock_bottom": "Symulator ściegów i odtwarzacz", + "btn_play": "▶ Symuluj", + "btn_pause": "⏸ Pauza", + "btn_show_all": "⏭ Pokaż całość", + "lbl_progress": " Postęp:", + "lbl_speed": "Prędkość:", + "stats_stitches": "Ściegi", + "stats_size": "Rozmiar", + "stats_avg": "Śr. dł.", + "stats_spm": "Prędk. rzecz.", + "stats_peak": "Maks. gęstość", + "stats_colors": "Zmiany koloru", + "stats_runtime": "Czas: ok.", + "stats_min": "min", + "m_new": "Nowy projekt", + "m_open": "Otwórz projekt (.ostitch) …", + "m_save": "Zapisz projekt (.ostitch) …", + "m_import": "Importuj plik haftu (EXP, DST, PES, JEF …) …", + "m_import_svg": "Importuj grafikę wektorową SVG (.svg) …", + "m_export": "Eksportuj plik haftu (EXP, DST, PES, JEF …) …", + "m_export_pdf": "Zapisz kartę produkcyjną jako PDF …", + "m_export_png": "Zapisz realistyczny podgląd 3D jako PNG …", + "m_quit": "Zakończ", + "m_auto": "Automatycznie zdigitalizuj obraz (Auto-Digitizer) …", + "m_photo": "PhotoStitch (portret ze zdjęcia → haft) …", + "m_text": "Wstaw napis / monogram …", + "m_applique": "Utwórz aplikację z kształtu", + "m_puff": "Przełącz tryb 3D-Puff (pianka) dla satyny", + "m_transfer": "Transfer do maszyny / dyskietka / USB / NetBridge …", + "m_doctor": "Sprawdź projekt (wirtualny haft próbny)", + "m_optimize": "Zmniejsz liczbę kolorów (mniej zmian igły)", + "m_tour": "Interaktywny przewodnik po programie …", + "m_restore_logo": "Przywróć oficjalne logo OpenStitch", + "m_undo": "Cofnij", + "m_redo": "Ponów", + "m_duplicate": "Duplikuj zaznaczony obiekt", + "m_delete": "Usuń zaznaczony obiekt", + "m_center": "Wyśrodkuj projekt w tamborku", + "m_fit": "Dopasuj optymalnie do bieżącego tamborka (Auto-Fit)", + "m_pick_hoop": "Automatycznie wybierz najmniejszy pasujący tamborek", + "m_scale": "Skaluj projekt (% / mm) …", + "m_3d": "Wygląd nici w 3D", + "m_jumps": "Pokaż przeskoki", + "m_grid": "Pokaż siatkę milimetrową", + "m_heatmap": "Mapa gęstości ściegów (obciążenie tkaniny)", + "m_zoom": "Dopasuj widok do tamborka", + "lbl_lang": "Język:", + "status_computing": "Obliczanie ściegów …", + "dlg_unsaved_title": "Niezapisane zmiany", + "dlg_unsaved_text": "Bieżący projekt ma niezapisane zmiany. Zapisać je teraz?", + "status_plan_error": "Nie udało się wygenerować ściegów", + "kind_column": "Kolumna satynowa", + "param_column_width": "Szerokość kolumny (mm)", + "msg_overwrite_title": "Zastąpić plik?", + "msg_overwrite_text": "Plik {name} już istnieje na obrazie dyskietki. Zastąpić go?", + "ph_text": "Twój tekst", + "tip_use_micro": "Przy tak małym napisie użyj „OpenStitch Micro” (kliknij tutaj)", + "act_shortcuts": "Skróty klawiszowe …", + "act_report": "Zgłoś problem …", + "act_about": "O programie OpenStitch …", + "about_text": "Darmowe oprogramowanie do haftu i digitalizacji. Licencja: AGPL-3.0, kod źródłowy jest ogólnie dostępny.", + "keys_title": "Skróty klawiszowe", + "key_select": "Zaznaczanie i przesuwanie", + "key_nodes": "Edycja węzłów", + "key_fill": "Rysowanie wypełnienia", + "key_satin": "Rysowanie kolumny satynowej", + "key_run": "Rysowanie ściegu prostego", + "key_finish": "Zakończ rysowanie", + "key_cancel": "Anuluj rysowanie", + "key_zoom": "Powiększenie", + "key_pan": "Przesuwanie widoku", + "key_wheel": "Kółko myszy", + "key_middle": "Środkowy przycisk myszy", + "crash_title": "To nie powinno się zdarzyć", + "crash_text": "W OpenStitch wystąpił błąd. Twoja praca została zapisana i możesz pracować dalej.\n\nJeśli chcesz zgłosić problem, dołącz ten plik:\n{}", + "exp_title": "Wyślij do maszyny", + "exp_heading": "Gotowe do haftowania?", + "exp_facts": "Ściegi: {st} · kolory: {colors} · {w} × {h} mm", + "exp_format": "Format pliku:", + "exp_recommended": "{} (zalecany)", + "exp_name": "Nazwa pliku:", + "exp_short": "Krótka nazwa dla starszych maszyn", + "exp_short_tip": "Wiele starszych maszyn pokazuje tylko 8 prostych znaków.", + "exp_where": "Zapisz w:", + "exp_usb": "Pendrive: {}", + "exp_browse": "Folder …", + "exp_refresh": "Odśwież", + "exp_threads": "Kolejność nici dla maszyny", + "exp_save": "Zapisz", + "exp_done": "Zapisano i sprawdzono „{name}”: ściegi poprawnie odczytane ({st}). Teraz włóż pendrive do maszyny.", + "exp_overwrite": "Plik „{}” już tam istnieje. Zastąpić go?", + "exp_done_plain": "Zapisano „{name}”.", + "exp_failed": "Nie udało się zapisać: {}", + "btn_close": "Zamknij", + "chk_title": "Sprawdź projekt", + "chk_running": "Sprawdzanie …", + "chk_failed": "Sprawdzanie nie powiodło się", + "chk_empty": "Brak jeszcze ściegów", + "chk_again": "Sprawdź ponownie", + "chk_good": "Gotowe do haftowania", + "chk_ok": "Do wyhaftowania, z drobnym ryzykiem", + "chk_bad": "Lepiej najpierw poprawić", + "chk_none": "Nie znaleziono problemów.", + "chk_facts": "Ściegi: {st} · kolory: {colors} · cięcia nici: {trims} · ok. {min} min · nić: {thread} m", + "chk_preview": "Jak tkanina się ściągnie", + "chk_boost": "Wzmocnij efekt", + "chk_show": "Pokaż", + "chk_fix": "Napraw", + "undo_fix": "Automatyczna poprawka", + "chk_sev_error": "Problem", + "chk_sev_warning": "Ostrzeżenie", + "chk_sev_info": "Uwaga", + "chk_short_stitch_t": "Bardzo krótkie ściegi", + "chk_short_stitch_d": "Ściegi krótsze niż 0,3 mm: {count}. Igła trafia prawie w ten sam otwór i nić może się zerwać.", + "chk_over_max_stitch_t": "Ściegi za długie dla maszyny", + "chk_over_max_stitch_d": "Ściegi przekraczające limit maszyny: {count} (najdłuższy: {max_mm} mm).", + "chk_long_float_t": "Długie luźne ściegi", + "chk_long_float_d": "Ściegi dłuższe niż 7,5 mm: {count} (do {max_mm} mm). W codziennym użytkowaniu łatwo się zahaczają.", + "chk_no_lock_t": "Końce nici bez zabezpieczenia", + "chk_no_lock_d": "Miejsca bez ściegów ryglujących: {count}. W tych miejscach haft może się spruć podczas prania.", + "chk_orphan_run_t": "Zbyt krótkie odcinki", + "chk_orphan_run_d": "Odcinki krótsze niż 3 ściegi: {count}. Po obcięciu nici ledwo się trzymają.", + "chk_untrimmed_jump_t": "Przeskoki bez cięcia nici", + "chk_untrimmed_jump_d": "Przeskoki bez cięcia: {count}. Nić zostaje w poprzek wzoru.", + "chk_needle_pileup_t": "Zbyt wiele wkłuć w jednym miejscu", + "chk_needle_pileup_d": "Miejsca z problemem: {count}. Igła wbija się tam do {max_hits} razy. Może to uszkodzić tkaninę i igłę.", + "chk_too_dense_t": "Zbyt gęsty haft", + "chk_too_dense_d": "Na powierzchni {count} mm² leży do {peak} warstw nici (limit dla tej tkaniny: {limit}). Miejsce robi się sztywne jak deska.", + "chk_outside_hoop_t": "Wzór nie mieści się w tamborku", + "chk_outside_hoop_d": "Ściegi leżą w strefie przy brzegu tamborka. Igła może uderzyć w tamborek.", + "chk_low_coverage_t": "Tkanina prześwituje", + "chk_low_coverage_d": "Pokrycie obiektu „{object}”: tylko {percent}%.", + "chk_too_many_colors_t": "Więcej kolorów niż igieł", + "chk_too_many_colors_d": "Kolory: {count}, igły: {needles}. W trakcie haftu trzeba będzie zmieniać nić.", + "chk_registration_gap_t": "Możliwe szczeliny między obiektami", + "chk_registration_gap_d": "Ściąganie tkaniny przesuwa elementy względem siebie nawet o {mm} mm. Pomaga większa kompensacja ściągania.", + "chk_puckering_t": "Tkanina może się marszczyć", + "chk_puckering_d": "Haft ściąga tkaninę o ok. {mm} mm. Użyj sztywniejszej flizeliny.", + "chk_small_text_t": "Napis za mały dla tej czcionki", + "chk_small_text_d": "Napis „{object}” ma {mm} mm wysokości. Czcionki konturowe przy tym rozmiarze zalewają się. Użyj „OpenStitch Micro”.", + "chk_export_ok_t": "Plik {ext} sprawdzony", + "chk_export_ok_d": "Ponownie odczytane ściegi: {st}, największe odchylenie: {err} mm.", + "chk_export_bad_t": "Problem w pliku {ext}", + "tb_open": "Otwórz", + "tb_save": "Zapisz", + "tb_check": "Sprawdź", + "act_home": "Pokaż stronę startową", + "act_theme_dark": "Ciemny motyw", + "act_theme_light": "Jasny motyw", + "menu_recent": "Ostatnio otwarte", + "lbl_fabric": "Tkanina:", + "fab_woven": "Bawełna / koszula (tkanina)", + "fab_denim": "Jeans / płótno", + "fab_twill_cap": "Czapka (drelich)", + "fab_pique": "Polo piqué", + "fab_jersey": "T-shirt (dzianina)", + "fab_fleece": "Polar / bluza", + "fab_towel": "Frotte / ręcznik", + "fab_leather": "Skóra", + "fab_silk": "Jedwab / cienka tkanina", + "stab_cutaway": "flizelina odcinana", + "stab_tearaway": "flizelina odrywana", + "stab_none": "bez flizeliny", + "fabric_advice": "{fabric}: {stabilizer}, igła {needle}. Gęstość i kompensacja ściągania zostały dostosowane.", + "fabric_topping": "Połóż na wierzchu folię rozpuszczalną w wodzie, aby ściegi nie zapadały się w tkaninę.", + "tip_obj_visible": "Pokaż lub ukryj obiekt", + "tip_obj_copy": "Duplikuj obiekt", + "param_knockout": "Nie haftuj zakrytych części", + "canvas_empty_hint": "Upuść tutaj obraz lub wybierz narzędzie rysowania po lewej", + "start_title": "Co chcesz wyhaftować?", + "start_subtitle": "Wybierz punkt wyjścia. Nie potrzebujesz doświadczenia.", + "start_image": "Zamień obraz w haft", + "start_image_d": "Wybierz logo lub rysunek, a resztę zrobi OpenStitch.", + "start_text": "Wyhaftuj tekst", + "start_text_d": "Imię lub hasło, czytelne już od 2,5 mm wysokości.", + "start_draw": "Narysuj sam", + "start_draw_d": "Rysuj wypełnienia, kolumny satynowe i linie myszą.", + "start_open": "Otwórz plik", + "start_open_d": "Projekt, plik haftu (DST, PES, JEF …), SVG lub obraz.", + "start_samples": "Albo zacznij od przykładu", + "start_recent": "Ostatnie pliki", + "start_tour": "Obejrzyj krótki przewodnik", + "sample_patch": "Naszywka z imieniem", + "sample_heart": "Serce", + "sample_flower": "Kwiat", + "sample_monogram": "Monogram", + "fd_open_any": "Otwórz plik", + "filter_supported": "Wszystkie obsługiwane pliki", + "err_file_gone": "Nie znaleziono pliku:\n{}", + "err_unknown_type": "Plik „{}” ma typ, którego OpenStitch nie zna.", + "dlg_recover_title": "Przywrócić pracę?", + "dlg_recover_text": "OpenStitch nie został poprawnie zamknięty. Otworzyć ostatnią automatyczną kopię zapasową?", + "status_autosave_failed": "Autozapis nie powiódł się: {}", + "err_project_damaged": "Plik „{name}” jest uszkodzony lub nie jest plikiem projektu OpenStitch.", + "label_colon": ":", + "btn_cancel": "Anuluj", + "btn_apply": "Zastosuj", + "btn_save": "Zapisz", + "btn_discard": "Odrzuć", + "dlg_error": "Błąd", + "dlg_notice": "Informacja", + "filter_all_files": "Wszystkie pliki", + "filter_all_images": "Wszystkie obrazy", + "filter_images": "Obrazy", + "filter_all_img_vec": "Wszystkie obrazy i pliki wektorowe", + "filter_raster": "Obrazy rastrowe", + "filter_svg": "Grafika wektorowa SVG", + "filter_photos": "Zdjęcia i obrazy", + "filter_project": "Projekt OpenStitch", + "filter_emb": "Pliki haftu", + "filter_png": "Obraz PNG", + "filter_floppy": "Obraz dyskietki", + "err_open_title": "Błąd otwierania pliku", + "err_load_title": "Błąd wczytywania pliku", + "err_svg_title": "Błąd importu SVG", + "err_import_title": "Błąd importu", + "err_save_title": "Błąd zapisu", + "err_export_title": "Błąd eksportu", + "err_pdf_title": "Błąd PDF", + "err_png_title": "Błąd PNG", + "err_png_text": "Nie udało się zapisać obrazu:\n{}", + "err_image_title": "Błąd obrazu", + "app_tagline": "Uniwersalny pakiet open source do haftu i digitalizacji", + "tb_title_studio": "Pasek studia", + "tb_title_tools": "Narzędzia rysowania", + "tip_autofit": "Dopasuj projekt optymalnie do wybranego tamborka (Ctrl+F)", + "tip_fabric": "Zmień tło tkaniny w tamborku (ciemna łupkowa / ciepła piaskowa / jasna)", + "tip_tool_select": "Zaznaczaj, przesuwaj i skaluj obiekty (klawisz V)", + "tip_tool_nodes": "Przeciągaj węzły konturu i oś kąta ściegu bezpośrednio (klawisz N)", + "tip_tool_fill": "Narysuj na płótnie nowe wypełnienie tatami (klawisz F)", + "tip_tool_satin": "Narysuj na płótnie nową kolumnę satynową (klawisz S)", + "tip_tool_run": "Narysuj nową ścieżkę ściegu prostego (klawisz R)", + "tip_tool_heatmap": "Pokaż/ukryj mapę gęstości ściegów (zielona/żółta/czerwona) (Ctrl+H)", + "tip_tool_zoom": "Dopasuj widok do tamborka (Ctrl+0)", + "tip_obj_up": "Przesuń obiekt wyżej w kolejności haftowania", + "tip_obj_down": "Przesuń obiekt niżej w kolejności haftowania", + "tip_obj_delete": "Usuń zaznaczony obiekt (Del)", + "sim_all": "Wszystko", + "sim_speed_suffix": " śc./takt", + "abbr_stitches": "śc.", + "stats_trims": "Cięcia nici", + "kind_fill": "Tatami", + "kind_satin": "Satyna", + "kind_run": "Ścieg prosty", + "kind_text": "Napis", + "kind_stitches": "Ściegi", + "obj_hidden": "[Ukryty]", + "btn_font_arc": "Dostosuj czcionkę i łuk …", + "status_hoop_strategy": "Strategia tamborka aktywna: {}", + "status_saved": "Zapisano: {}", + "color_dialog_title": "Wybierz kolor nici", + "default_design_name": "Nowy_projekt", + "fd_open_project": "Otwórz projekt", + "fd_save_project": "Zapisz projekt", + "fd_import_emb": "Importuj plik haftu", + "fd_import_svg": "Importuj grafikę wektorową SVG", + "fd_export_emb": "Eksportuj plik haftu", + "fd_save_pdf": "Zapisz kartę produkcyjną (PDF)", + "pdf_file_suffix": "karta_produkcyjna", + "fd_save_png": "Zapisz podgląd ściegów 3D", + "fd_pick_image": "Wybierz obraz, grafikę lub logo (Pobrane / Obrazy / Pulpit)", + "fd_pick_photo": "Wybierz zdjęcie portretowe lub krajobrazowe (Pobrane / Obrazy / Pulpit)", + "msg_applique_title": "Aplikacja", + "msg_applique_text": "Najpierw zaznacz na płótnie wypełnienie lub kształt satynowy.", + "msg_export_verified_title": "Eksport i weryfikacja binarna zakończone powodzeniem", + "msg_export_verified_text": "✅ Plik haftu zapisany i sprawdzony w symulatorze:\n{path}\n\n• Rozmiar pliku: {size} bajtów\n• Sprawdzone ściegi: {stitches}\n• Wymiary: {w:.1f} × {h:.1f} mm\n• Maks. długość kroku: {step:.1f} mm\n• Zmiany koloru: {colors} · Przeskoki: {jumps}", + "msg_export_ok_title": "Eksport zakończony", + "msg_export_ok_text": "Plik zapisany:\n{}", + "msg_pdf_ok_title": "PDF utworzony", + "msg_pdf_ok_text": "Karta produkcyjna zapisana:\n{}", + "msg_puff_title": "Pianka 3D-Puff", + "msg_puff_text": "Wybierz obiekt satynowy.", + "dlg_scale_title": "Skaluj projekt (ściegi zostaną przeliczone!)", + "dlg_scale_label": "Współczynnik skali (%):", + "hoop_round9": "Okrągły 9 cm (mały/pierś)", + "hoop_round12": "Okrągły 12 cm (logo na piersi)", + "hoop_round15": "Okrągły 15 cm (standard)", + "hoop_round18": "Okrągły 18 cm (duży)", + "hoop_round21": "Okrągły 21 cm (XL)", + "hoop_cap": "Czapka 13 × 5 cm", + "hoop_widecap": "Szeroka czapka 30 × 7 cm", + "hoop_rect13x18": "Prostokąt 13 × 18 cm (domowy)", + "hoop_jacket": "Plecy kurtki 30 × 30 cm", + "hoop_field40x30": "Duże pole 40 × 30 cm (przemysłowe)", + "hoop_strat_small": "Mocne napięcie · drobne detale (-10% kompensacji ściągania, standardowy podkład)", + "hoop_strat_medium": "Zrównoważone · standardowy tamborek na pierś/rękaw (100% kompensacji ściągania)", + "hoop_strat_large": "Przeciw falowaniu · wzmocniony podkład (+20% kompensacji ściągania + siatka krzyżowa na dużych powierzchniach)", + "hoop_strat_jacket": "Stabilizacja pleców kurtki (+35% kompensacji ściągania, podwójny podkład siatkowy, maks. 750 SPM)", + "hoop_strat_cap": "Tryb czapki (od środka na zewnątrz i od dołu do góry od daszka, +30% kompensacji ściągania)", + "hoop_strat_default": "Standard", + "machine_universal_multi": "Uniwersalny standard (DST / PES / EXP · 15 igieł)", + "machine_tajima_tmez": "Tajima TMEZ / TFMX / TMBR (15 igieł)", + "machine_brother_pr": "Brother seria PR / Persona (6–10 igieł)", + "machine_brother_home": "Brother / Baby Lock domowe (1 igła · PES)", + "machine_barudan_bext": "Barudan BEKT / BEXT (15 igieł)", + "machine_ricoma_happy_zsk": "Ricoma / HappyJapan / SWF / ZSK (12–15 igieł)", + "machine_janome_elna": "Janome / Elna / Bernina domowe (JEF / EXP)", + "machine_pfaff_husqvarna": "Pfaff / Husqvarna Viking (VP3)", + "machine_melco_emt10_4": "Melco EMT10/4 (4 głowice / 10 igieł)", + "machine_melco_amaya_bravo": "Melco Amaya / EMT16X / Bravo (16 igieł)", + "param_angle": "Kąt ściegu (°)", + "param_fill_spacing": "Odstęp rzędów (mm)", + "param_satin_spacing": "Gęstość (mm)", + "param_stitch_len": "Długość ściegu (mm)", + "param_pattern": "Wzór", + "param_underlay": "Podkład", + "param_pull_comp": "Kompensacja ściągania (mm)", + "param_max_stitch": "Maks. ścieg / podział (mm)", + "param_underlay_style": "Rodzaj podkładu", + "param_puff_3d": "3D-Puff (tryb czapki)", + "param_repeats": "Powtórzenia (0 = pojedynczy, 1 = potrójny)", + "param_text": "Tekst", + "param_font": "Czcionka", + "param_height": "Wysokość liter (mm)", + "param_letter_spacing": "Odstęp liter (mm)", + "param_arc_radius": "Promień łuku (mm, 0 = prosto)", + "param_mode": "Rodzaj ściegu", + "param_density": "Gęstość (mm)", + "opt_standard": "Standard", + "opt_diagonal": "Ukośny", + "opt_ziegel": "Cegiełka", + "opt_wellen": "Fale", + "opt_kontur": "Kontur", + "opt_auto": "Automatycznie", + "opt_mitte": "Przebieg środkiem", + "opt_kante": "Przebieg krawędzią", + "opt_zickzack": "Zygzak", + "opt_kante+zickzack": "Przebieg krawędzią + zygzak", + "opt_satin": "Ścieg satynowy", + "opt_fill": "Wypełnienie tatami", + "dlg_auto_title": "Automatycznie zdigitalizuj obraz (Auto-Digitizer)", + "lbl_orig_image": "Obraz oryginalny ({})", + "btn_other_image": "📂 Wybierz inny obraz (Pobrane / Pulpit / Obrazy …)", + "grp_auto_settings": "Ustawienia haftu i automatyka", + "lbl_target_width_motif": "Docelowa szerokość wzoru:", + "lbl_max_colors": "Maks. kolorów nici (igieł):", + "cb_remove_bg": "Automatycznie usuń tło obrazu", + "fabric_opt_normal": "Standard (bawełna / drelich / uniwersalna)", + "fabric_opt_strick": "Piqué / polo / dzianina (większa kompensacja ściągania)", + "fabric_opt_frottee": "Frotte / ręcznik (gęściej + mocny podkład)", + "fabric_opt_cap": "Czapka (wysoka kompensacja ściągania)", + "fabric_opt_leicht": "Lekka tkanina / koszula (mniejsza gęstość)", + "lbl_fabric_type": "Tkanina / materiał:", + "lbl_density_row": "Gęstość ściegów (odstęp rzędów):", + "lbl_satin_limit": "Granica satyny (węższe = satyna):", + "lbl_min_area": "Pomijaj drobne obszary poniżej:", + "cb_outline": "Dodaj satynowy kontur wokół wzoru", + "cb_palette": "Dopasuj kolory do palety nici", + "status_ready": "Gotowe.", + "btn_digitize_apply": "Zdigitalizuj && zastosuj", + "fd_pick_logo": "Wybierz obraz lub logo (Pobrane / Obrazy / Pulpit)", + "fd_pick_logo_short": "Wybierz obraz lub logo", + "err_digitize_title": "Digitalizacja nie powiodła się", + "prog_computing_stitches": "Obliczanie ściegów ({}/{}) …", + "prog_prepare": "Przygotowanie obrazu …", + "prog_reduce": "Redukcja kolorów …", + "prog_clean": "Porządkowanie obszarów …", + "prog_vectorize": "Wektoryzacja konturów …", + "prog_done": "Gotowe", + "prog_classify": "Klasyfikacja obszaru {}/{} …", + "dlg_text_title": "Utwórz napis / monogram", + "lbl_text": "Tekst:", + "lbl_font_file": "Czcionka (TTF/OTF):", + "lbl_letter_height": "Wysokość liter (wersaliki):", + "lbl_letter_spacing": "Odstęp liter:", + "sfx_arc": " mm (0 = prosto)", + "lbl_arc_radius": "Promień łuku:", + "text_mode_auto": "Automatycznie (satyna do 7 mm, powyżej tatami)", + "text_mode_satin": "Zawsze ścieg satynowy (błyszczący napis)", + "text_mode_fill": "Zawsze wypełnienie tatami", + "lbl_stitch_type": "Rodzaj ściegu:", + "lbl_stitch_density": "Gęstość ściegów:", + "msg_enter_text": "Wpisz jakiś tekst.", + "text_obj_name": "Tekst „{}”", + "dlg_transfer_title": "Transfer do maszyny (USB / emulator dyskietki 1,44 MB / Wi-Fi NetBridge)", + "grp_transfer_1": "1. Ustawienia maszyny i cięcia nici (EXP / format przemysłowy)", + "lbl_dos_name": "Nazwa pliku DOS (format 8.3):", + "trim_both": "Łączony: kod cięcia EXP + 3 przeskoki (najlepsza zgodność)", + "trim_code": "Standardowy kod cięcia EXP (80 80 07 00)", + "trim_jumps": "Tylko sekwencja przeskoków (dla starszego firmware EMT)", + "lbl_trim_mode": "Tryb cięcia nici:", + "grp_transfer_2": "2. Wyślij bezpośrednio na pendrive / dysk lub przez Wi-Fi NetBridge", + "btn_save_exp_usb": "Zapisz EXP bezpośrednio na pendrive / do folderu …", + "lbl_netbridge_url": "Adres URL NetBridge:", + "btn_send_netbridge": "Wyślij do Melco NetBridge przez Wi-Fi", + "grp_transfer_3": "3. Obraz dyskietki FAT12 1,44 MB (.IMG) dla emulatora USB (GoTek / HxC)", + "lbl_img_initial": "Bieżący obraz: nowy pusty obraz 1,44 MB (FAT12)", + "btn_open_img": "Otwórz istniejący .IMG …", + "btn_add_cur_img": "Dodaj bieżący projekt do obrazu", + "btn_del_file": "Usuń zaznaczony plik", + "btn_save_img": "Zapisz plik .IMG …", + "unit_bytes": "bajtów", + "img_new": "Nowy obraz 1,44 MB", + "img_free": "{src} — Wolne miejsce: {free} KB z {total} KB", + "fd_save_exp": "Zapisz Melco EXP", + "msg_saved_title": "Zapisano", + "msg_exp_saved": "Plik haftu Melco zapisany:\n{path}\n({size} bajtów)", + "msg_wifi_ok_title": "Transfer przez Wi-Fi zakończony", + "msg_wifi_ok_text": "Wysłano do {url}:\n{body}", + "msg_netbridge_fail_title": "NetBridge niedostępny", + "msg_netbridge_fail_text": "Nie udało się połączyć z {url}:\n{err}", + "fd_open_img": "Otwórz obraz dyskietki FAT12", + "fd_save_img": "Zapisz obraz dyskietki FAT12 1,44 MB", + "msg_img_saved_title": "Obraz dyskietki zapisany", + "msg_img_saved_text": "Obraz FAT12 1,44 MB zapisany:\n{path}\n\nWskazówka dla GoTek/FlashFloppy: nazwij obrazy na pendrive np. DSKA0000.IMG, DSKA0001.IMG albo skopiuj plik .EXP bezpośrednio, jeśli FlashFloppy działa w trybie plików bezpośrednich.", + "dlg_photo_title": "PhotoStitch — haft portretów i zdjęć", + "lbl_orig_photo": "Zdjęcie oryginalne ({})", + "btn_other_photo": "📂 Wybierz inne zdjęcie (Pobrane / Pulpit / Obrazy …)", + "grp_photo_settings": "Ustawienia PhotoStitch", + "lbl_target_width": "Docelowa szerokość:", + "photo_mode_mono": "Grawer jednobarwny (1 kolor nici na jasnej tkaninie)", + "photo_mode_sepia": "Portret sepia (2 kolory nici: jasnobrązowy + ciemnobrązowy)", + "photo_mode_color4": "Półton CMYK w 4 kolorach (żółty, magenta, cyjan, czarny)", + "lbl_color_mode": "Tryb kolorów:", + "lbl_row_spacing_fine": "Odstęp rzędów (dokładność):", + "lbl_contrast": "Wzmocnienie kontrastu:", + "btn_photo_apply": "Oblicz && zastosuj PhotoStitch", + "pdf_title": "{} — Karta produkcyjna i ustawień", + "pdf_created": "Utworzono w {app} dnia {date}", + "pdf_date_fmt": "%d.%m.%Y %H:%M", + "pdf_total_stitches": "Ściegi łącznie", + "pdf_size": "Rozmiar (szer. × wys.)", + "pdf_color_changes": "Zmiany koloru / bloki", + "pdf_blocks_val": "{} (bloków: {})", + "pdf_trims": "Cięcia nici", + "pdf_hoop": "Tamborek", + "pdf_runtime": "Czas pracy (ok. {} SPM)", + "pdf_thread_usage": "Zużycie nici górnej", + "pdf_machine": "Profil maszyny", + "pdf_sequence": "Kolejność kolorów i przypisanie igieł (igieł: {})", + "tour_next": "Dalej →", + "tour_prev_tip": "Poprzedni krok", + "tour_close_tip": "Zamknij przewodnik (Esc)", + "tour_on_start": "Przy uruchomieniu", + "tour_done": "Gotowe ✓", + "tour_app_1_badge": "WITAJ · 1 / 7", + "tour_app_1_title": "Płótno: twój projekt w 3D", + "tour_app_1_body": "Na środku w tamborku leży twój projekt. Na początek to nasz herb OpenStitch.

• Klikanie i przeciąganie: zaznaczaj części, przesuwaj je albo zmieniaj rozmiar uchwytem w rogu.
• Kółko myszy: płynnie powiększaj aż do pojedynczych ściegów.", + "tour_app_1_action": "🎨 Wypróbuj kolor tkaniny w tamborku (ciemna / piaskowa / jasna)", + "tour_app_2_badge": "NAD PŁÓTNEM · 2 / 7", + "tour_app_2_title": "Maszyna, tamborek i tkanina", + "tour_app_2_body": "Tuż nad płótnem mówisz OpenStitch, na czym haftujesz:

• Maszyna: uniwersalna, Tajima, Brother, Barudan, Melco …
• Tamborek: OpenStitch dopasowuje podkład i kompensację ściągania do rozmiaru. Duże tamborki dostają dodatkowe wsparcie przeciw falowaniu, a czapki są haftowane od środka na zewnątrz i od daszka do góry.
• Tkanina: dostosowuje gęstość i kompensację ściągania oraz poleca flizelinę i igłę.", + "tour_app_2_action": "⛶ Dopasuj projekt do tamborka (Auto-Fit)", + "tour_app_3_badge": "GÓRNY PASEK · 3 / 7", + "tour_app_3_title": "Obraz, napis, sprawdzanie i eksport", + "tour_app_3_body": "Obok przycisków plików i Cofnij znajdziesz najważniejsze kroki:

• Obraz → haft (Ctrl+D): wybierz obraz, a OpenStitch usunie tło i utworzy obszary haftu.
• Napis (Ctrl+T): dodawaj tekst i monogramy.
• Sprawdź (F7): testuje projekt i daje mu ocenę w skali do 100.
• Eksport (Ctrl+E): zapisuje plik dla twojej maszyny.

PhotoStitch, Aplikacja i 3D-Puff są w menu Digitalizacja, SVG w menu Plik, a Transfer w menu Maszyna & eksport.", + "tour_app_3_action": "✨ Otwórz Obraz → haft …", + "tour_app_4_badge": "NARZĘDZIA · 4 / 7", + "tour_app_4_title": "Rysuj ręcznie i edytuj węzły (N)", + "tour_app_4_body": "Wąski pasek po lewej pokazuje tylko ikony. Najedź na jedną myszą, aby zobaczyć jej nazwę:

• Tatami (F) / Satyna (S) / Prosty (R): rysuj własne kształty na płótnie.
• Węzły (N): przesuwaj punkty konturu po jednym i przeciągaj żółtą oś, aby obrócić kąt ściegu.", + "tour_app_4_action": "❖ Włącz edytor węzłów i kąta ściegu (N)", + "tour_app_5_badge": "KOLORY NICI · 5 / 7", + "tour_app_5_title": "Kolory i kolejność igieł", + "tour_app_5_body": "Po lewej jednym kliknięciem wybierasz kolor z katalogu nici (Madeira, Isacord, Gunold, Brother …) albo mieszasz własny w RGB.

• Poniżej widzisz kolejność kolorów i igieł w projekcie, z liczbą ściegów dla każdego koloru.", + "tour_app_6_badge": "WARSTWY I USTAWIENIA · 6 / 7", + "tour_app_6_title": "Warstwy i ustawienia obiektu", + "tour_app_6_body": "Po prawej ustalasz kolejność haftowania. Poniżej dostosowujesz zaznaczony obiekt: odstęp rzędów, wzór (na przykład Kontur), kompensację ściągania albo 3D-Puff dla satyny.

• Każda zmiana przelicza ściegi na płótnie od razu.", + "tour_app_7_badge": "SYMULATOR I STATUS · 7 / 7", + "tour_app_7_title": "Symulator ściegów i pasek stanu", + "tour_app_7_body": "Pod płótnem możesz odtworzyć cały projekt ścieg po ściegu.

• Pasek stanu na samym dole pokazuje ściegi, rozmiar, zmiany koloru, cięcia nici i szacowany czas pracy. Najedź na niego myszą, aby zobaczyć prędkość i maksymalną gęstość.
• Język zmieniasz w prawym dolnym rogu.", + "tour_app_7_action": "▶ Uruchom / zatrzymaj symulację", + 'chk_tag_rule': 'Stała reguła', + 'chk_tag_model': 'Szacunek', + 'cal_open': 'Kalibruj na prawdziwej tkaninie …', + 'cal_title': 'Kalibracja tkaniny', + 'cal_intro': '1. Wczytaj pasek testowy i wyhaftuj go na tkaninie, z flizeliną i naprężeniem, których naprawdę używasz.\n2. Zmierz szerokość na środku paska. Planowana szerokość to {width} mm.\n3. Wpisz pomiar. Symulacja i kompensacja użyją wtedy Twojej rzeczywistej wartości.', + 'cal_load': 'Wczytaj pasek testowy', + 'cal_measured': 'Zmierzona szerokość:', + 'cal_apply': 'Zastosuj', + 'cal_reset': 'Resetuj', + 'cal_state_estimate': 'Ta tkanina nie została jeszcze zmierzona: ściąganie jest szacowane.', + 'cal_state_measured': 'Zmierzono: ściąganie to {factor} × wartość szacowana.', + 'chk_disclaimer': 'Stałe reguły wynikają wprost ze ściegów. Szacunki ściągania stają się dokładne po kalibracji tkaniny.', +} diff --git a/openstitch/locales/pt.py b/openstitch/locales/pt.py new file mode 100644 index 0000000..657c898 --- /dev/null +++ b/openstitch/locales/pt.py @@ -0,0 +1,524 @@ +"""Português.""" + +TABLE: dict[str, str] = { + "menu_file": "&Arquivo", + "menu_edit": "&Editar", + "menu_view": "&Ver", + "menu_create": "&Digitalizar", + "menu_machine": "&Máquina && Exportar", + "menu_help": "A&juda", + "tb_new": "Novo", + "tb_import": "Importar", + "tb_svg": "SVG", + "tb_export": "Exportar", + "tb_pdf": "PDF", + "tb_auto": "Imagem em pontos", + "tb_photo": "PhotoStitch", + "tb_text": "Letras", + "tb_applique": "Apliqué", + "tb_puff": "Puff 3D", + "tb_transfer": "Transferir", + "tb_tour": "Tour", + "lbl_machine": "Máquina:", + "lbl_hoop": "Bastidor:", + "btn_autofit": "Autoajuste", + "fabric_slate": "Tecido: escuro", + "fabric_sand": "Tecido: areia", + "fabric_light": "Tecido: claro", + "lbl_strategy": "Estratégia", + "tool_select": "Selecionar (V)", + "tool_nodes": "Nós (N)", + "tool_fill": "Tatami (F)", + "tool_satin": "Cetim (S)", + "tool_run": "Corrido (R)", + "tool_heatmap": "Mapa de calor", + "tool_zoom": "Ajustar ao bastidor", + "hud_select": "Selecionar (V) · Arrastar = mover, alça do canto = redimensionar, roda do mouse = zoom", + "hud_nodes": "Nós e ângulo do ponto (N) · Nós brancos = editar o contorno, alça amarela = girar o ângulo do ponto", + "hud_fill": "Desenhar preenchimento tatami (F) · Clique = adicionar nó, duplo clique/Enter = concluir", + "hud_satin": "Desenhar coluna de cetim (S) · Clique = adicionar nó, duplo clique/Enter = concluir", + "hud_run": "Desenhar ponto corrido (R) · Clique = adicionar nó, duplo clique/Enter = concluir", + "dock_palette": "Linhas && cores", + "lbl_catalog": "Catálogo de linhas:", + "lbl_seq": "Sequência de cores e agulhas do desenho:", + "needle": "Agulha", + "dock_right": "Camadas && ajustes", + "btn_visible": "👁 Visível", + "btn_copy": "⧉ Copiar", + "lbl_inspector": "Parâmetros do objeto (recálculo ao vivo):", + "lbl_no_sel": "Nenhum objeto selecionado.\nClique num elemento da tela ou da lista de camadas.", + "lbl_obj_name": "Nome", + "dock_bottom": "Simulador de pontos", + "btn_play": "▶ Simular", + "btn_pause": "⏸ Pausar", + "btn_show_all": "⏭ Mostrar tudo", + "lbl_progress": " Progresso:", + "lbl_speed": "Velocidade:", + "stats_stitches": "Pontos", + "stats_size": "Tamanho", + "stats_avg": "Comp. médio", + "stats_spm": "Veloc. efet.", + "stats_peak": "Densidade máx.", + "stats_colors": "Trocas de cor", + "stats_runtime": "Duração: ~", + "stats_min": "min", + "m_new": "Novo desenho", + "m_open": "Abrir projeto (.ostitch) …", + "m_save": "Salvar projeto (.ostitch) …", + "m_import": "Importar arquivo de bordado (EXP, DST, PES, JEF …) …", + "m_import_svg": "Importar gráfico vetorial SVG (.svg) …", + "m_export": "Exportar arquivo de bordado (EXP, DST, PES, JEF …) …", + "m_export_pdf": "Salvar ficha de produção em PDF …", + "m_export_png": "Salvar pré-visualização 3D realista como PNG …", + "m_quit": "Sair", + "m_auto": "Digitalizar imagem automaticamente (Auto-Digitizer) …", + "m_photo": "PhotoStitch (foto de retrato → bordado) …", + "m_text": "Inserir letras / monograma …", + "m_applique": "Criar apliqué a partir da forma", + "m_puff": "Ativar ou desativar o modo espuma puff 3D no cetim", + "m_transfer": "Transferência para a máquina / disquete / USB / NetBridge …", + "m_doctor": "Verificar desenho (teste de bordado virtual)", + "m_optimize": "Minimizar cores (menos trocas de agulha)", + "m_tour": "Tour interativo pelo estúdio (introdução) …", + "m_restore_logo": "Restaurar o logotipo oficial do OpenStitch", + "m_undo": "Desfazer", + "m_redo": "Refazer", + "m_duplicate": "Duplicar o objeto selecionado", + "m_delete": "Apagar o objeto selecionado", + "m_center": "Centralizar o desenho no bastidor", + "m_fit": "Ajustar da melhor forma ao bastidor atual (autoajuste)", + "m_pick_hoop": "Escolher automaticamente o menor bastidor adequado", + "m_scale": "Redimensionar desenho (% / mm) …", + "m_3d": "Visualização 3D das linhas", + "m_jumps": "Mostrar saltos", + "m_grid": "Mostrar grade milimétrica", + "m_heatmap": "Mapa de calor da densidade de pontos (tensão no tecido)", + "m_zoom": "Zoom no bastidor", + "lbl_lang": "Idioma:", + "status_computing": "Cálculo dos pontos …", + "dlg_unsaved_title": "Alterações não salvas", + "dlg_unsaved_text": "O desenho atual tem alterações não salvas. Salvar agora?", + "status_plan_error": "Falha ao gerar os pontos", + "kind_column": "Coluna de cetim", + "param_column_width": "Largura da coluna (mm)", + "msg_overwrite_title": "Substituir arquivo?", + "msg_overwrite_text": "{name} já existe na imagem de disquete. Substituir?", + "ph_text": "Seu texto", + "tip_use_micro": "Para letras tão pequenas, use “OpenStitch Micro” (clique aqui)", + "act_shortcuts": "Atalhos de teclado …", + "act_report": "Relatar um problema …", + "act_about": "Sobre o OpenStitch …", + "about_text": "Software livre de bordado e digitalização. Licença: AGPL-3.0, o código-fonte está disponível gratuitamente.", + "keys_title": "Atalhos de teclado", + "key_select": "Selecionar e mover", + "key_nodes": "Editar nós", + "key_fill": "Desenhar preenchimento", + "key_satin": "Desenhar coluna de cetim", + "key_run": "Desenhar ponto corrido", + "key_finish": "Concluir o desenho", + "key_cancel": "Cancelar o desenho", + "key_zoom": "Zoom", + "key_pan": "Mover a vista", + "key_wheel": "Roda do mouse", + "key_middle": "Botão do meio do mouse", + "crash_title": "Isto não deveria ter acontecido", + "crash_text": "O OpenStitch encontrou um erro. O seu trabalho foi salvo e pode continuar.\n\nSe quiser relatar o problema, anexe este arquivo:\n{}", + "exp_title": "Enviar para a máquina", + "exp_heading": "Pronto para bordar?", + "exp_facts": "{st} pontos · {colors} cores · {w} × {h} mm", + "exp_format": "Formato do arquivo:", + "exp_recommended": "{} (recomendado)", + "exp_name": "Nome do arquivo:", + "exp_short": "Nome curto para máquinas antigas", + "exp_short_tip": "Muitas máquinas antigas só mostram 8 caracteres simples.", + "exp_where": "Salvar em:", + "exp_usb": "Pen drive USB: {}", + "exp_browse": "Pasta …", + "exp_refresh": "Atualizar", + "exp_threads": "Ordem das linhas para a máquina", + "exp_save": "Salvar", + "exp_done": "“{name}” salvo e verificado: {st} pontos lidos corretamente. Agora conecte o pen drive à máquina.", + "exp_overwrite": "“{}” já existe neste local. Substituir?", + "exp_done_plain": "“{name}” salvo.", + "exp_failed": "Não foi possível salvar: {}", + "btn_close": "Fechar", + "chk_title": "Verificar desenho", + "chk_running": "Em verificação …", + "chk_failed": "A verificação falhou", + "chk_empty": "Ainda sem pontos", + "chk_again": "Verificar de novo", + "chk_good": "Pronto para bordar", + "chk_ok": "Bordável, com pequenos riscos", + "chk_bad": "Melhor corrigir primeiro", + "chk_none": "Nenhum problema encontrado.", + "chk_facts": "{st} pontos · {colors} cores · {trims} cortes · cerca de {min} min · {thread} m de linha", + "chk_preview": "Como o tecido vai contrair", + "chk_boost": "Exagerar o efeito", + "chk_show": "Mostrar", + "chk_fix": "Corrigir", + "undo_fix": "Correção automática", + "chk_sev_error": "Problema", + "chk_sev_warning": "Aviso", + "chk_sev_info": "Nota", + "chk_short_stitch_t": "Pontos muito curtos", + "chk_short_stitch_d": "Pontos com menos de 0,3 mm: {count}. A agulha quase fura o mesmo lugar e a linha pode romper.", + "chk_over_max_stitch_t": "Pontos longos demais para a máquina", + "chk_over_max_stitch_d": "{count} pontos ultrapassam o limite da máquina (o mais longo: {max_mm} mm).", + "chk_long_float_t": "Pontos soltos longos", + "chk_long_float_d": "{count} pontos têm mais de 7,5 mm (até {max_mm} mm). Enganchar neles é fácil no dia a dia.", + "chk_no_lock_t": "Pontas de linha sem fixação", + "chk_no_lock_d": "{count} locais sem pontos de fixação. Ali o bordado pode descosturar ao lavar.", + "chk_orphan_run_t": "Trechos curtos demais", + "chk_orphan_run_d": "{count} trechos têm menos de 3 pontos e quase não seguram depois do corte da linha.", + "chk_untrimmed_jump_t": "Saltos sem corte", + "chk_untrimmed_jump_d": "{count} saltos deixam uma linha atravessada no desenho.", + "chk_needle_pileup_t": "Furos demais no mesmo lugar", + "chk_needle_pileup_d": "Em {count} locais a agulha fura até {max_hits} vezes. Isso pode danificar o tecido e a agulha.", + "chk_too_dense_t": "Bordado denso demais", + "chk_too_dense_d": "{count} mm² têm até {peak} camadas de linha (limite para este tecido: {limit}). A zona fica dura como uma tábua.", + "chk_outside_hoop_t": "O desenho não cabe no bastidor", + "chk_outside_hoop_d": "Há pontos na zona de borda do bastidor. A agulha pode bater nele.", + "chk_low_coverage_t": "O tecido aparece", + "chk_low_coverage_d": "“{object}” tem só {percent}% de cobertura.", + "chk_too_many_colors_t": "Mais cores do que agulhas", + "chk_too_many_colors_d": "{count} cores para {needles} agulhas: será preciso trocar a linha durante o bordado.", + "chk_registration_gap_t": "Provável haver folgas entre objetos", + "chk_registration_gap_d": "A tração do tecido desloca as partes até {mm} mm umas contra as outras. Mais compensação de tração ajuda.", + "chk_puckering_t": "O tecido pode enrugar", + "chk_puckering_d": "O bordado puxa o tecido cerca de {mm} mm. Use um estabilizador mais firme.", + "chk_small_text_t": "Letras pequenas demais para esta fonte", + "chk_small_text_d": "“{object}” tem {mm} mm de altura. Neste tamanho, as fontes de contorno entopem. Use “OpenStitch Micro”.", + "chk_export_ok_t": "Arquivo {ext} verificado", + "chk_export_ok_d": "{st} pontos relidos, maior desvio {err} mm.", + "chk_export_bad_t": "Problema no arquivo {ext}", + "tb_open": "Abrir", + "tb_save": "Salvar", + "tb_check": "Verificar", + "act_home": "Mostrar página inicial", + "act_theme_dark": "Tema escuro", + "act_theme_light": "Tema claro", + "menu_recent": "Abrir recentes", + "lbl_fabric": "Tecido:", + "fab_woven": "Algodão / camisa (tecido plano)", + "fab_denim": "Jeans / lona", + "fab_twill_cap": "Boné (sarja)", + "fab_pique": "Polo piquê", + "fab_jersey": "Camiseta (malha)", + "fab_fleece": "Fleece / sweatshirt", + "fab_towel": "Atoalhado / toalha", + "fab_leather": "Couro", + "fab_silk": "Seda / tecido fino", + "stab_cutaway": "estabilizador de corte", + "stab_tearaway": "estabilizador rasgável", + "stab_none": "sem estabilizador", + "fabric_advice": "{fabric}: use {stabilizer}, agulha {needle}. A densidade e a compensação de tração foram ajustadas.", + "fabric_topping": "Coloque por cima uma película solúvel em água para os pontos não afundarem.", + "tip_obj_visible": "Mostrar ou ocultar objeto", + "tip_obj_copy": "Duplicar objeto", + "param_knockout": "Ignorar partes ocultas", + "canvas_empty_hint": "Solte uma imagem aqui ou escolha uma ferramenta de desenho à esquerda", + "start_title": "O que quer bordar?", + "start_subtitle": "Escolha um ponto de partida. Não é preciso experiência.", + "start_image": "Transforme uma imagem em bordado", + "start_image_d": "Escolha um logotipo ou desenho e o OpenStitch faz o resto.", + "start_text": "Bordar texto", + "start_text_d": "Um nome ou slogan, legível a partir de 2,5 mm de altura.", + "start_draw": "Desenhar por conta própria", + "start_draw_d": "Desenhe preenchimentos, colunas de cetim e linhas com o mouse.", + "start_open": "Abrir um arquivo", + "start_open_d": "Projeto, arquivo de bordado (DST, PES, JEF …), SVG ou imagem.", + "start_samples": "Ou comece por um exemplo", + "start_recent": "Arquivos recentes", + "start_tour": "Fazer um tour rápido", + "sample_patch": "Etiqueta com nome", + "sample_heart": "Coração", + "sample_flower": "Flor", + "sample_monogram": "Monograma", + "fd_open_any": "Abrir arquivo", + "filter_supported": "Todos os arquivos compatíveis", + "err_file_gone": "O arquivo não foi encontrado:\n{}", + "err_unknown_type": "“{}” tem um tipo de arquivo que o OpenStitch não conhece.", + "dlg_recover_title": "Recuperar o seu trabalho?", + "dlg_recover_text": "O OpenStitch não foi fechado corretamente. Abrir o último backup automático?", + "status_autosave_failed": "Falha ao salvar automaticamente: {}", + "err_project_damaged": "“{name}” está danificado ou não é um arquivo de projeto do OpenStitch.", + "label_colon": ":", + "btn_cancel": "Cancelar", + "btn_apply": "Aplicar", + "btn_save": "Salvar", + "btn_discard": "Descartar", + "dlg_error": "Erro", + "dlg_notice": "Aviso", + "filter_all_files": "Todos os arquivos", + "filter_all_images": "Todas as imagens", + "filter_images": "Imagens", + "filter_all_img_vec": "Todos os arquivos de imagem e vetoriais", + "filter_raster": "Imagens raster", + "filter_svg": "Gráfico vetorial SVG", + "filter_photos": "Fotos e imagens", + "filter_project": "Projeto OpenStitch", + "filter_emb": "Arquivos de bordado", + "filter_png": "Imagem PNG", + "filter_floppy": "Imagem de disquete", + "err_open_title": "Erro ao abrir o arquivo", + "err_load_title": "Erro ao carregar o arquivo", + "err_svg_title": "Erro de importação de SVG", + "err_import_title": "Erro de importação", + "err_save_title": "Erro ao salvar", + "err_export_title": "Erro de exportação", + "err_pdf_title": "Erro de PDF", + "err_png_title": "Erro de PNG", + "err_png_text": "Não foi possível salvar a imagem:\n{}", + "err_image_title": "Erro de imagem", + "app_tagline": "Suíte universal de código aberto para bordado e digitalização", + "tb_title_studio": "Barra do estúdio", + "tb_title_tools": "Ferramentas de desenho", + "tip_autofit": "Ajustar o desenho da melhor forma ao bastidor escolhido (Ctrl+F)", + "tip_fabric": "Alternar o fundo do tecido no bastidor (ardósia escura / areia quente / claro)", + "tip_tool_select": "Selecionar, mover e redimensionar objetos (tecla V)", + "tip_tool_nodes": "Arrastar diretamente os nós do contorno e o eixo do ângulo do ponto (tecla N)", + "tip_tool_fill": "Desenhar uma nova área de preenchimento tatami na tela (tecla F)", + "tip_tool_satin": "Desenhar uma nova coluna de cetim na tela (tecla S)", + "tip_tool_run": "Desenhar um novo trajeto de ponto corrido (tecla R)", + "tip_tool_heatmap": "Mostrar/ocultar o mapa de calor da densidade de pontos (verde/amarelo/vermelho) (Ctrl+H)", + "tip_tool_zoom": "Ajustar a vista ao bastidor (Ctrl+0)", + "tip_obj_up": "Subir o objeto na ordem de bordado", + "tip_obj_down": "Descer o objeto na ordem de bordado", + "tip_obj_delete": "Apagar o objeto selecionado (Del)", + "sim_all": "Tudo", + "sim_speed_suffix": " pts/tick", + "abbr_stitches": "pts", + "stats_trims": "Cortes", + "kind_fill": "Preenchimento", + "kind_satin": "Cetim", + "kind_run": "Ponto corrido", + "kind_text": "Letras", + "kind_stitches": "Pontos", + "obj_hidden": "[Oculto]", + "btn_font_arc": "Ajustar fonte e arco …", + "status_hoop_strategy": "Estratégia de bastidor ativa: {}", + "status_saved": "Salvo: {}", + "color_dialog_title": "Escolher a cor da linha", + "default_design_name": "Novo_desenho", + "fd_open_project": "Abrir projeto", + "fd_save_project": "Salvar projeto", + "fd_import_emb": "Importar arquivo de bordado", + "fd_import_svg": "Importar gráfico vetorial SVG", + "fd_export_emb": "Exportar arquivo de bordado", + "fd_save_pdf": "Salvar ficha de produção (PDF)", + "pdf_file_suffix": "ficha_de_producao", + "fd_save_png": "Salvar pré-visualização 3D dos pontos", + "fd_pick_image": "Escolha uma imagem, gráfico ou logotipo (Downloads / Imagens / Desktop)", + "fd_pick_photo": "Escolha uma foto de retrato ou de paisagem (Downloads / Imagens / Desktop)", + "msg_applique_title": "Apliqué", + "msg_applique_text": "Selecione primeiro uma forma de preenchimento ou de cetim na tela.", + "msg_export_verified_title": "Exportação e verificação binária concluídas", + "msg_export_verified_text": "✅ Arquivo de bordado salvo e verificado no simulador:\n{path}\n\n• Tamanho do arquivo: {size} bytes\n• Pontos verificados: {stitches}\n• Dimensões: {w:.1f} × {h:.1f} mm\n• Comprimento máx. do passo: {step:.1f} mm\n• Trocas de cor: {colors} · Saltos: {jumps}", + "msg_export_ok_title": "Exportação concluída", + "msg_export_ok_text": "Arquivo salvo:\n{}", + "msg_pdf_ok_title": "PDF criado", + "msg_pdf_ok_text": "Ficha de produção salva:\n{}", + "msg_puff_title": "Espuma puff 3D", + "msg_puff_text": "Selecione um objeto de cetim.", + "dlg_scale_title": "Redimensionar desenho (os pontos serão recalculados!)", + "dlg_scale_label": "Fator de escala (%):", + "hoop_round9": "Redondo 9 cm (pequeno/peito)", + "hoop_round12": "Redondo 12 cm (logotipo no peito)", + "hoop_round15": "Redondo 15 cm (padrão)", + "hoop_round18": "Redondo 18 cm (grande)", + "hoop_round21": "Redondo 21 cm (XL)", + "hoop_cap": "Boné 13 × 5 cm", + "hoop_widecap": "Boné largo 30 × 7 cm", + "hoop_rect13x18": "Retângulo 13 × 18 cm (doméstico)", + "hoop_jacket": "Costas de casaco 30 × 30 cm", + "hoop_field40x30": "Campo grande 40 × 30 cm (industrial)", + "hoop_strat_small": "Tensão firme · detalhes finos (-10% de compensação de tração, base padrão)", + "hoop_strat_medium": "Equilibrada · bastidor padrão de peito/manga (100% de compensação de tração)", + "hoop_strat_large": "Anti-trampolim · base reforçada (+20% de compensação de tração + grade cruzada em áreas grandes)", + "hoop_strat_jacket": "Estabilização para costas de casaco (+35% de compensação de tração, base de grade dupla, máx. 750 SPM)", + "hoop_strat_cap": "Modo boné (do centro para fora e de baixo para cima, a partir da aba, +30% de compensação de tração)", + "hoop_strat_default": "Padrão", + "machine_universal_multi": "Padrão universal (DST / PES / EXP · 15 agulhas)", + "machine_tajima_tmez": "Tajima TMEZ / TFMX / TMBR (15 agulhas)", + "machine_brother_pr": "Brother série PR / Persona (6–10 agulhas)", + "machine_brother_home": "Brother / Baby Lock doméstica (1 agulha · PES)", + "machine_barudan_bext": "Barudan BEKT / BEXT (15 agulhas)", + "machine_ricoma_happy_zsk": "Ricoma / HappyJapan / SWF / ZSK (12–15 agulhas)", + "machine_janome_elna": "Janome / Elna / Bernina doméstica (JEF / EXP)", + "machine_pfaff_husqvarna": "Pfaff / Husqvarna Viking (VP3)", + "machine_melco_emt10_4": "Melco EMT10/4 (4 cabeças / 10 agulhas)", + "machine_melco_amaya_bravo": "Melco Amaya / EMT16X / Bravo (16 agulhas)", + "param_angle": "Ângulo do ponto (°)", + "param_fill_spacing": "Espaçamento entre fileiras (mm)", + "param_satin_spacing": "Densidade (mm)", + "param_stitch_len": "Comprimento do ponto (mm)", + "param_pattern": "Padrão", + "param_underlay": "Base", + "param_pull_comp": "Compensação de tração (mm)", + "param_max_stitch": "Ponto máx. / divisão (mm)", + "param_underlay_style": "Tipo de base", + "param_puff_3d": "Puff 3D (modo boné)", + "param_repeats": "Repetições (0 = simples, 1 = triplo)", + "param_text": "Texto", + "param_font": "Fonte", + "param_height": "Altura das letras (mm)", + "param_letter_spacing": "Espaçamento entre letras (mm)", + "param_arc_radius": "Raio do arco (mm, 0 = reto)", + "param_mode": "Tipo de ponto", + "param_density": "Densidade (mm)", + "opt_standard": "Padrão", + "opt_diagonal": "Diagonal", + "opt_ziegel": "Tijolo", + "opt_wellen": "Ondas", + "opt_kontur": "Contorno", + "opt_auto": "Automático", + "opt_mitte": "Passada central", + "opt_kante": "Passada de borda", + "opt_zickzack": "Zigue-zague", + "opt_kante+zickzack": "Passada de borda + zigue-zague", + "opt_satin": "Ponto cetim", + "opt_fill": "Preenchimento tatami", + "dlg_auto_title": "Digitalizar imagem automaticamente (Auto-Digitizer)", + "lbl_orig_image": "Imagem original ({})", + "btn_other_image": "📂 Escolher outra imagem (Downloads / Desktop / Imagens …)", + "grp_auto_settings": "Ajustes de bordado e automação", + "lbl_target_width_motif": "Largura desejada do desenho:", + "lbl_max_colors": "Máx. de cores de linha (agulhas):", + "cb_remove_bg": "Remover o fundo da imagem automaticamente", + "fabric_opt_normal": "Padrão (algodão / sarja / universal)", + "fabric_opt_strick": "Piquê / polo / malha (mais compensação de tração)", + "fabric_opt_frottee": "Atoalhado / toalha (mais denso + base forte)", + "fabric_opt_cap": "Boné (compensação de tração alta)", + "fabric_opt_leicht": "Tecido leve / camisa (densidade menor)", + "lbl_fabric_type": "Tipo de tecido / material:", + "lbl_density_row": "Densidade de pontos (espaçamento entre fileiras):", + "lbl_satin_limit": "Limite do cetim (mais estreito = cetim):", + "lbl_min_area": "Ignorar áreas minúsculas abaixo de:", + "cb_outline": "Adicionar contorno de cetim ao redor do desenho", + "cb_palette": "Ajustar as cores à paleta de linhas", + "status_ready": "Pronto.", + "btn_digitize_apply": "Digitalizar && aplicar agora", + "fd_pick_logo": "Escolha uma imagem ou logotipo (Downloads / Imagens / Desktop)", + "fd_pick_logo_short": "Escolha uma imagem ou logotipo", + "err_digitize_title": "Falha na digitalização", + "prog_computing_stitches": "Cálculo dos pontos ({}/{}) …", + "prog_prepare": "Preparação da imagem …", + "prog_reduce": "Redução das cores …", + "prog_clean": "Limpeza das áreas …", + "prog_vectorize": "Vetorização dos contornos …", + "prog_done": "Concluído", + "prog_classify": "Classificação da área {}/{} …", + "dlg_text_title": "Criar letras / monograma", + "lbl_text": "Texto:", + "lbl_font_file": "Fonte (TTF/OTF):", + "lbl_letter_height": "Altura das letras (altura das maiúsculas):", + "lbl_letter_spacing": "Espaçamento entre letras:", + "sfx_arc": " mm (0 = reto)", + "lbl_arc_radius": "Raio do arco:", + "text_mode_auto": "Automático (cetim até 7 mm, tatami acima)", + "text_mode_satin": "Sempre ponto cetim (letras brilhantes)", + "text_mode_fill": "Sempre preenchimento tatami", + "lbl_stitch_type": "Tipo de ponto:", + "lbl_stitch_density": "Densidade de pontos:", + "msg_enter_text": "Digite um texto.", + "text_obj_name": "Texto “{}”", + "dlg_transfer_title": "Transferência para a máquina (USB / emulador de disquete de 1,44 MB / NetBridge Wi-Fi)", + "grp_transfer_1": "1. Ajustes da máquina e do corte de linha (EXP / formato industrial)", + "lbl_dos_name": "Nome de arquivo DOS (formato 8.3):", + "trim_both": "Combinado: código de corte EXP + 3 saltos (máxima compatibilidade)", + "trim_code": "Código de corte EXP padrão (80 80 07 00)", + "trim_jumps": "Apenas sequência de saltos (para firmware EMT antigo)", + "lbl_trim_mode": "Modo de corte de linha:", + "grp_transfer_2": "2. Enviar direto para um pen drive / unidade USB ou por NetBridge Wi-Fi", + "btn_save_exp_usb": "Salvar EXP direto no pen drive / pasta …", + "lbl_netbridge_url": "URL do NetBridge:", + "btn_send_netbridge": "Enviar ao Melco NetBridge por Wi-Fi", + "grp_transfer_3": "3. Imagem de disquete FAT12 de 1,44 MB (.IMG) para emulador USB (GoTek / HxC)", + "lbl_img_initial": "Imagem atual: nova imagem vazia de 1,44 MB (FAT12)", + "btn_open_img": "Abrir .IMG existente …", + "btn_add_cur_img": "Adicionar o desenho atual à imagem", + "btn_del_file": "Apagar o arquivo selecionado", + "btn_save_img": "Salvar arquivo .IMG …", + "unit_bytes": "bytes", + "img_new": "Nova imagem de 1,44 MB", + "img_free": "{src} — Espaço livre: {free} KB de {total} KB", + "fd_save_exp": "Salvar Melco EXP", + "msg_saved_title": "Salvo", + "msg_exp_saved": "Arquivo de bordado Melco salvo:\n{path}\n({size} bytes)", + "msg_wifi_ok_title": "Transferência Wi-Fi concluída", + "msg_wifi_ok_text": "Enviado para {url}:\n{body}", + "msg_netbridge_fail_title": "NetBridge inacessível", + "msg_netbridge_fail_text": "Não foi possível acessar {url}:\n{err}", + "fd_open_img": "Abrir imagem de disquete FAT12", + "fd_save_img": "Salvar imagem de disquete FAT12 de 1,44 MB", + "msg_img_saved_title": "Imagem de disquete salva", + "msg_img_saved_text": "Imagem FAT12 de 1,44 MB salva:\n{path}\n\nDica para GoTek/FlashFloppy: dê às imagens no pen drive nomes como DSKA0000.IMG, DSKA0001.IMG, ou copie o arquivo .EXP diretamente, se o FlashFloppy estiver no modo de arquivo direto.", + "dlg_photo_title": "PhotoStitch — criar bordado de retratos e fotos", + "lbl_orig_photo": "Foto original ({})", + "btn_other_photo": "📂 Escolher outra foto (Downloads / Desktop / Imagens …)", + "grp_photo_settings": "Ajustes do PhotoStitch", + "lbl_target_width": "Largura desejada:", + "photo_mode_mono": "Gravura monocromática (1 cor de linha em tecido claro)", + "photo_mode_sepia": "Retrato sépia (2 cores de linha: marrom-claro + marrom-escuro)", + "photo_mode_color4": "Meio-tom CMYK de 4 cores (amarelo, magenta, ciano, preto)", + "lbl_color_mode": "Modo de cor:", + "lbl_row_spacing_fine": "Espaçamento entre linhas (finura):", + "lbl_contrast": "Reforço de contraste:", + "btn_photo_apply": "Calcular && aplicar PhotoStitch", + "pdf_title": "{} — Ficha de produção e de preparação", + "pdf_created": "Criado com {app} em {date}", + "pdf_date_fmt": "%d/%m/%Y %H:%M", + "pdf_total_stitches": "Total de pontos", + "pdf_size": "Tamanho (L × A)", + "pdf_color_changes": "Trocas de cor / blocos", + "pdf_blocks_val": "{} ({} blocos)", + "pdf_trims": "Cortes de linha", + "pdf_hoop": "Bastidor", + "pdf_runtime": "Duração (aprox. {} SPM)", + "pdf_thread_usage": "Consumo de linha superior", + "pdf_machine": "Perfil da máquina", + "pdf_sequence": "Sequência de cores e atribuição de agulhas ({} agulhas)", + "tour_next": "Avançar →", + "tour_prev_tip": "Passo anterior", + "tour_close_tip": "Fechar o tour (Esc)", + "tour_on_start": "Ao iniciar", + "tour_done": "Concluído ✓", + "tour_app_1_badge": "BOAS-VINDAS · 1 / 7", + "tour_app_1_title": "A tela: o seu desenho em 3D", + "tour_app_1_body": "O seu desenho fica no bastidor, no meio. No início, é o nosso brasão do OpenStitch.

• Clicar e arrastar: selecione partes, mova-as ou redimensione-as pela alça do canto.
• Roda do mouse: aproxime com suavidade, até chegar a cada ponto.", + "tour_app_1_action": "🎨 Experimente uma cor de tecido no bastidor (escuro / areia / claro)", + "tour_app_2_badge": "ACIMA DA TELA · 2 / 7", + "tour_app_2_title": "Máquina, bastidor e tecido", + "tour_app_2_body": "Logo acima da tela, indique ao OpenStitch em que vai bordar:

• Máquina: Universal, Tajima, Brother, Barudan, Melco …
• Bastidor: o OpenStitch ajusta a base e a compensação de tração ao tamanho. Bastidores grandes recebem reforço contra o efeito trampolim, e bonés são bordados do centro para fora e a partir da aba, para cima.
• Tecido: ajusta a densidade e a compensação de tração e recomenda estabilizador e agulha.", + "tour_app_2_action": "⛶ Ajustar o desenho ao bastidor (autoajuste)", + "tour_app_3_badge": "BARRA SUPERIOR · 3 / 7", + "tour_app_3_title": "Imagem, letras, verificação e exportação", + "tour_app_3_body": "Ao lado dos botões de arquivo e de Desfazer ficam os passos principais:

• Imagem em pontos (Ctrl+D): escolha uma imagem e o OpenStitch remove o fundo e cria as áreas de bordado.
• Letras (Ctrl+T): adicione texto e monogramas.
• Verificar (F7): testa o seu desenho e dá uma nota de 0 a 100.
• Exportar (Ctrl+E): salva o arquivo para a sua máquina.

PhotoStitch, Apliqué e Puff 3D estão no menu Digitalizar, SVG em Arquivo e Transferir em Máquina & Exportar.", + "tour_app_3_action": "✨ Abrir Imagem em pontos …", + "tour_app_4_badge": "FERRAMENTAS · 4 / 7", + "tour_app_4_title": "Desenhar à mão e editar nós (N)", + "tour_app_4_body": "A barra estreita à esquerda mostra só ícones. Aponte o mouse para um deles para ver o nome:

• Tatami (F) / Cetim (S) / Corrido (R): desenhe as suas próprias formas na tela.
• Nós (N): mova os pontos do contorno um a um e arraste o eixo amarelo para girar o ângulo do ponto.", + "tour_app_4_action": "❖ Ativar o editor de nós e do ângulo do ponto (N)", + "tour_app_5_badge": "CORES DE LINHA · 5 / 7", + "tour_app_5_title": "Cores e ordem das agulhas", + "tour_app_5_body": "À esquerda, escolha com um clique uma cor do catálogo de linhas (Madeira, Isacord, Gunold, Brother …) ou crie o seu próprio tom com RGB.

• Abaixo, veja a ordem das cores e das agulhas do seu desenho, com o número de pontos por cor.", + "tour_app_6_badge": "CAMADAS E AJUSTES · 6 / 7", + "tour_app_6_title": "Camadas e ajustes do objeto", + "tour_app_6_body": "À direita, defina a ordem de bordado. Abaixo, ajuste o objeto selecionado: espaçamento entre fileiras, padrão (por exemplo Contorno), compensação de tração ou puff 3D para cetim.

• Cada alteração recalcula os pontos na tela imediatamente.", + "tour_app_7_badge": "SIMULADOR E ESTADO · 7 / 7", + "tour_app_7_title": "Simulador de pontos e barra de estado", + "tour_app_7_body": "Abaixo da tela, reproduza todo o desenho ponto a ponto.

• A barra de estado, na parte de baixo, mostra pontos, tamanho, trocas de cor, cortes e a duração estimada. Aponte o mouse para ela para ver a velocidade e a densidade máxima.
• O idioma é alterado no canto inferior direito.", + "tour_app_7_action": "▶ Iniciar / parar a simulação", + 'chk_tag_rule': 'Regra fixa', + 'chk_tag_model': 'Estimativa', + 'cal_open': 'Calibrar com tecido real …', + 'cal_title': 'Calibrar tecido', + 'cal_intro': '1. Carregue a barra de teste e borde-a com o tecido, o estabilizador e a tensão que usa de verdade.\n2. Meça a largura no meio da barra. A prevista é {width} mm.\n3. Introduza a medida. A simulação e a compensação passam a usar o seu valor real.', + 'cal_load': 'Carregar barra de teste', + 'cal_measured': 'Largura medida:', + 'cal_apply': 'Aplicar', + 'cal_reset': 'Repor', + 'cal_state_estimate': 'Este tecido ainda não foi medido: a tração é uma estimativa.', + 'cal_state_measured': 'Medido: a tração é {factor} vezes a estimativa.', + 'chk_disclaimer': 'As regras fixas resultam exatamente dos pontos. As estimativas de tração ficam precisas ao calibrar o tecido.', +} diff --git a/openstitch/locales/tr.py b/openstitch/locales/tr.py new file mode 100644 index 0000000..f1d5f5f --- /dev/null +++ b/openstitch/locales/tr.py @@ -0,0 +1,524 @@ +"""Türkçe.""" + +TABLE: dict[str, str] = { + "menu_file": "&Dosya", + "menu_edit": "D&üzenle", + "menu_view": "&Görünüm", + "menu_create": "D&ijitize", + "menu_machine": "&Makine && Dışa Aktarma", + "menu_help": "&Yardım", + "tb_new": "Yeni", + "tb_import": "İçe aktar", + "tb_svg": "SVG", + "tb_export": "Dışa aktar", + "tb_pdf": "PDF", + "tb_auto": "Resimden dikişe", + "tb_photo": "PhotoStitch", + "tb_text": "Yazı", + "tb_applique": "Aplike", + "tb_puff": "3D Puff", + "tb_transfer": "Aktarım", + "tb_tour": "Tanıtım", + "lbl_machine": "Makine:", + "lbl_hoop": "Kasnak:", + "btn_autofit": "Sığdır", + "fabric_slate": "Kumaş: Koyu", + "fabric_sand": "Kumaş: Kum", + "fabric_light": "Kumaş: Açık", + "lbl_strategy": "Strateji", + "tool_select": "Seç (V)", + "tool_nodes": "Düğümler (N)", + "tool_fill": "Tatami (F)", + "tool_satin": "Saten (S)", + "tool_run": "Düz dikiş (R)", + "tool_heatmap": "Yoğunluk", + "tool_zoom": "Kasnağa sığdır", + "hud_select": "Seç (V) · Sürükle = Taşı, Köşe tutamacı = Boyutlandır, Tekerlek = Yakınlaştır", + "hud_nodes": "Düğümler & Dikiş açısı (N) · Beyaz düğümler = Konturu düzenle, Sarı tutamaç = Dikiş açısını döndür", + "hud_fill": "Tatami dolgu çiz (F) · Tıkla = Nokta ekle, Çift tıkla/Enter = Bitir", + "hud_satin": "Saten sütunu çiz (S) · Tıkla = Nokta ekle, Çift tıkla/Enter = Bitir", + "hud_run": "Düz dikiş çiz (R) · Tıkla = Nokta ekle, Çift tıkla/Enter = Bitir", + "dock_palette": "İplikler && Renkler", + "lbl_catalog": "İplik kataloğu:", + "lbl_seq": "Tasarımdaki iplik & iğne sırası:", + "needle": "İğne", + "dock_right": "Katmanlar && Ayarlar", + "btn_visible": "👁 Görünür", + "btn_copy": "⧉ Kopyala", + "lbl_inspector": "Nesne parametreleri (anında yeniden hesaplanır):", + "lbl_no_sel": "Seçili nesne yok.\nTuval üzerindeki ya da katman listesindeki bir öğeye tıklayın.", + "lbl_obj_name": "Ad", + "dock_bottom": "Dikiş Simülatörü && Oynatıcı", + "btn_play": "▶ Simüle et", + "btn_pause": "⏸ Duraklat", + "btn_show_all": "⏭ Tümünü göster", + "lbl_progress": " İlerleme:", + "lbl_speed": "Hız:", + "stats_stitches": "Dikiş", + "stats_size": "Boyut", + "stats_avg": "Ort. uzunluk", + "stats_spm": "Etkin hız", + "stats_peak": "En yüksek yoğunluk", + "stats_colors": "Renk değişimi", + "stats_runtime": "Çalışma süresi: ~", + "stats_min": "dk", + "m_new": "Yeni tasarım", + "m_open": "Proje aç (.ostitch) …", + "m_save": "Projeyi kaydet (.ostitch) …", + "m_import": "Nakış dosyası içe aktar (EXP, DST, PES, JEF …) …", + "m_import_svg": "SVG vektör grafiği içe aktar (.svg) …", + "m_export": "Nakış dosyası dışa aktar (EXP, DST, PES, JEF …) …", + "m_export_pdf": "Üretim sayfasını PDF olarak kaydet …", + "m_export_png": "Gerçekçi 3D önizlemeyi PNG olarak kaydet …", + "m_quit": "Çıkış", + "m_auto": "Resmi otomatik dijitize et (Otomatik Dijitize Edici) …", + "m_photo": "PhotoStitch (portre fotoğrafı → nakış) …", + "m_text": "Yazı / monogram ekle …", + "m_applique": "Şekilden aplike oluştur", + "m_puff": "Saten için 3D puff köpük modunu aç/kapat", + "m_transfer": "Makineye aktarım / disket / USB / NetBridge …", + "m_doctor": "Tasarımı kontrol et (sanal deneme dikişi)", + "m_optimize": "Renkleri azalt (iğne değişimlerinden tasarruf)", + "m_tour": "Etkileşimli stüdyo turu (tanıtım) …", + "m_restore_logo": "Resmi OpenStitch logosunu geri yükle", + "m_undo": "Geri al", + "m_redo": "Yinele", + "m_duplicate": "Seçili nesneyi çoğalt", + "m_delete": "Seçili nesneyi sil", + "m_center": "Tasarımı kasnakta ortala", + "m_fit": "Geçerli kasnağa en uygun şekilde sığdır (Otomatik sığdır)", + "m_pick_hoop": "Sığan en küçük kasnağı otomatik seç", + "m_scale": "Tasarımı ölçekle (% / mm) …", + "m_3d": "3D iplik görünümü", + "m_jumps": "Atlama dikişlerini göster", + "m_grid": "Milimetre ızgarasını göster", + "m_heatmap": "Dikiş yoğunluğu haritası (kumaş gerilimi)", + "m_zoom": "Kasnağa yakınlaştır", + "lbl_lang": "Dil:", + "status_computing": "Dikişler hesaplanıyor …", + "dlg_unsaved_title": "Kaydedilmemiş değişiklikler", + "dlg_unsaved_text": "Geçerli tasarımda kaydedilmemiş değişiklikler var. Şimdi kaydedilsin mi?", + "status_plan_error": "Dikişler oluşturulamadı", + "kind_column": "Saten sütunu", + "param_column_width": "Sütun genişliği (mm)", + "msg_overwrite_title": "Dosyanın üzerine yazılsın mı?", + "msg_overwrite_text": "{name} disket görüntüsünde zaten var. Üzerine yazılsın mı?", + "ph_text": "Metniniz", + "tip_use_micro": "Bu kadar küçük yazılar için “OpenStitch Micro” kullanın (buraya tıklayın)", + "act_shortcuts": "Klavye kısayolları …", + "act_report": "Sorun bildir …", + "act_about": "OpenStitch hakkında …", + "about_text": "Özgür nakış ve dijitize yazılımı. Lisans: AGPL-3.0, kaynak kodu serbestçe erişilebilir.", + "keys_title": "Klavye kısayolları", + "key_select": "Seç ve taşı", + "key_nodes": "Düğümleri düzenle", + "key_fill": "Dolgu çiz", + "key_satin": "Saten sütunu çiz", + "key_run": "Düz dikiş çiz", + "key_finish": "Çizimi bitir", + "key_cancel": "Çizimi iptal et", + "key_zoom": "Yakınlaştır", + "key_pan": "Görünümü kaydır", + "key_wheel": "Fare tekerleği", + "key_middle": "Orta fare düğmesi", + "crash_title": "Bu olmamalıydı", + "crash_text": "OpenStitch bir hatayla karşılaştı. Çalışmanız kaydedildi, devam edebilirsiniz.\n\nHatayı bildirmek isterseniz lütfen şu dosyayı ekleyin:\n{}", + "exp_title": "Makineye gönder", + "exp_heading": "Dikmeye hazır mısınız?", + "exp_facts": "{st} dikiş · {colors} renk · {w} × {h} mm", + "exp_format": "Dosya biçimi:", + "exp_recommended": "{} (önerilir)", + "exp_name": "Dosya adı:", + "exp_short": "Eski makineler için kısa ad", + "exp_short_tip": "Birçok eski makine yalnızca 8 sade karakter gösterir.", + "exp_where": "Kaydedilecek yer:", + "exp_usb": "USB bellek: {}", + "exp_browse": "Klasör …", + "exp_refresh": "Yenile", + "exp_threads": "Makine için iplik sırası", + "exp_save": "Kaydet", + "exp_done": "“{name}” kaydedildi ve doğrulandı: {st} dikiş doğru okundu. Şimdi belleği makinenize takın.", + "exp_overwrite": "“{}” orada zaten var. Üzerine yazılsın mı?", + "exp_done_plain": "“{name}” kaydedildi.", + "exp_failed": "Kaydedilemedi: {}", + "btn_close": "Kapat", + "chk_title": "Tasarımı kontrol et", + "chk_running": "Kontrol ediliyor …", + "chk_failed": "Kontrol başarısız oldu", + "chk_empty": "Henüz dikiş yok", + "chk_again": "Yeniden kontrol et", + "chk_good": "Dikmeye hazır", + "chk_ok": "Dikilebilir, küçük risklerle", + "chk_bad": "Önce düzeltmek daha iyi", + "chk_none": "Sorun bulunamadı.", + "chk_facts": "{st} dikiş · {colors} renk · {trims} iplik kesme · yaklaşık {min} dk · {thread} m iplik", + "chk_preview": "Kumaş nasıl çekilecek", + "chk_boost": "Etkiyi abartarak göster", + "chk_show": "Göster", + "chk_fix": "Düzelt", + "undo_fix": "Otomatik düzeltme", + "chk_sev_error": "Sorun", + "chk_sev_warning": "Uyarı", + "chk_sev_info": "Not", + "chk_short_stitch_t": "Çok kısa dikişler", + "chk_short_stitch_d": "0,3 mm'den kısa dikiş sayısı: {count}. İğne neredeyse aynı deliğe batar ve iplik kopabilir.", + "chk_over_max_stitch_t": "Makine için fazla uzun dikişler", + "chk_over_max_stitch_d": "{count} dikiş makinenin sınırını aşıyor (en uzunu: {max_mm} mm).", + "chk_long_float_t": "Uzun gevşek dikişler", + "chk_long_float_d": "{count} dikiş 7,5 mm'den uzun (en fazla {max_mm} mm). Günlük kullanımda kolayca takılırlar.", + "chk_no_lock_t": "İplik uçları sabitlenmemiş", + "chk_no_lock_d": "{count} yerde sabitleme dikişi yok. Nakış, yıkanınca buralardan sökülebilir.", + "chk_orphan_run_t": "Çok kısa bölümler", + "chk_orphan_run_d": "{count} bölümde 3'ten az dikiş var ve iplik kesildikten sonra zor tutunur.", + "chk_untrimmed_jump_t": "İplik kesilmeyen atlamalar", + "chk_untrimmed_jump_d": "{count} atlama, tasarımın üzerinde enine bir iplik bırakıyor.", + "chk_needle_pileup_t": "Tek noktaya çok fazla iğne batışı", + "chk_needle_pileup_d": "{count} yerde iğne en fazla {max_hits} kez batıyor. Bu, kumaşa ve iğneye zarar verebilir.", + "chk_too_dense_t": "Fazla sık dikilmiş", + "chk_too_dense_d": "{count} mm² alanda en fazla {peak} kat iplik var (bu kumaş için sınır: {limit}). Bu bölge tahta gibi sertleşir.", + "chk_outside_hoop_t": "Tasarım kasnağa sığmıyor", + "chk_outside_hoop_d": "Dikişler kasnağın kenar bölgesinde. İğne kasnağa çarpabilir.", + "chk_low_coverage_t": "Kumaş görünüyor", + "chk_low_coverage_d": "“{object}” yalnızca %{percent} oranında kaplanmış.", + "chk_too_many_colors_t": "İğne sayısından fazla renk", + "chk_too_many_colors_d": "{needles} iğneye karşılık {count} renk: dikiş sırasında ipliği değiştirmeniz gerekecek.", + "chk_registration_gap_t": "Nesneler arasında boşluk kalabilir", + "chk_registration_gap_d": "Kumaşın çekmesi parçaları birbirine göre en fazla {mm} mm kaydırıyor. Daha fazla çekme telafisi yardımcı olur.", + "chk_puckering_t": "Kumaş buruşabilir", + "chk_puckering_d": "Nakış kumaşı yaklaşık {mm} mm içeri çekiyor. Daha sert bir stabilizatör kullanın.", + "chk_small_text_t": "Yazı bu yazı tipi için çok küçük", + "chk_small_text_d": "“{object}” {mm} mm yüksekliğinde. Kontur yazı tipleri bu boyutta dolup kapanır. “OpenStitch Micro” kullanın.", + "chk_export_ok_t": "{ext} dosyası doğrulandı", + "chk_export_ok_d": "{st} dikiş geri okundu, en büyük sapma {err} mm.", + "chk_export_bad_t": "{ext} dosyasında sorun var", + "tb_open": "Aç", + "tb_save": "Kaydet", + "tb_check": "Kontrol", + "act_home": "Başlangıç sayfasını göster", + "act_theme_dark": "Koyu tema", + "act_theme_light": "Açık tema", + "menu_recent": "Son açılanlar", + "lbl_fabric": "Kumaş:", + "fab_woven": "Pamuk / gömlek (dokuma)", + "fab_denim": "Kot / kanvas", + "fab_twill_cap": "Şapka (twill)", + "fab_pique": "Polo piqué", + "fab_jersey": "Tişört (süprem)", + "fab_fleece": "Polar / sweatshirt", + "fab_towel": "Havlu kumaşı / havlu", + "fab_leather": "Deri", + "fab_silk": "İpek / ince kumaş", + "stab_cutaway": "kesilen stabilizatör", + "stab_tearaway": "koparılan stabilizatör", + "stab_none": "stabilizatörsüz", + "fabric_advice": "{fabric}: {stabilizer} kullanın, iğne {needle}. Yoğunluk ve çekme telafisi ayarlandı.", + "fabric_topping": "Dikişlerin içine gömülmemesi için üstüne suda eriyen film koyun.", + "tip_obj_visible": "Nesneyi göster veya gizle", + "tip_obj_copy": "Nesneyi çoğalt", + "param_knockout": "Gizli kısımları dikme", + "canvas_empty_hint": "Buraya bir resim sürükleyin ya da soldan bir çizim aracı seçin", + "start_title": "Ne işlemek istersiniz?", + "start_subtitle": "Bir başlangıç noktası seçin. Deneyim gerekmez.", + "start_image": "Resmi nakışa dönüştür", + "start_image_d": "Bir logo ya da çizim seçin, gerisini OpenStitch yapsın.", + "start_text": "Yazı işle", + "start_text_d": "Bir ad ya da slogan, 2,5 mm yükseklikten itibaren net okunur.", + "start_draw": "Kendiniz çizin", + "start_draw_d": "Dolguları, saten sütunlarını ve çizgileri fareyle çizin.", + "start_open": "Dosya aç", + "start_open_d": "Proje, nakış dosyası (DST, PES, JEF …), SVG ya da resim.", + "start_samples": "Ya da bir örnekle başlayın", + "start_recent": "Son dosyalar", + "start_tour": "Kısa bir tanıtım izleyin", + "sample_patch": "İsim yaması", + "sample_heart": "Kalp", + "sample_flower": "Çiçek", + "sample_monogram": "Monogram", + "fd_open_any": "Dosya aç", + "filter_supported": "Desteklenen tüm dosyalar", + "err_file_gone": "Dosya bulunamadı:\n{}", + "err_unknown_type": "“{}” dosyasının türünü OpenStitch tanımıyor.", + "dlg_recover_title": "Çalışmanız geri yüklensin mi?", + "dlg_recover_text": "OpenStitch düzgün kapanmadı. Son otomatik yedek açılsın mı?", + "status_autosave_failed": "Otomatik kaydetme başarısız oldu: {}", + "err_project_damaged": "“{name}” bozuk ya da bir OpenStitch proje dosyası değil.", + "label_colon": ":", + "btn_cancel": "İptal", + "btn_apply": "Uygula", + "btn_save": "Kaydet", + "btn_discard": "Kaydetme", + "dlg_error": "Hata", + "dlg_notice": "Bilgi", + "filter_all_files": "Tüm dosyalar", + "filter_all_images": "Tüm resimler", + "filter_images": "Resimler", + "filter_all_img_vec": "Tüm resim & vektör dosyaları", + "filter_raster": "Piksel resimler", + "filter_svg": "SVG vektör grafiği", + "filter_photos": "Fotoğraflar & resimler", + "filter_project": "OpenStitch projesi", + "filter_emb": "Nakış dosyaları", + "filter_png": "PNG resmi", + "filter_floppy": "Disket görüntüsü", + "err_open_title": "Dosya açılamadı", + "err_load_title": "Dosya yüklenemedi", + "err_svg_title": "SVG içe aktarma hatası", + "err_import_title": "İçe aktarma hatası", + "err_save_title": "Kaydetme hatası", + "err_export_title": "Dışa aktarma hatası", + "err_pdf_title": "PDF hatası", + "err_png_title": "PNG hatası", + "err_png_text": "Resim kaydedilemedi:\n{}", + "err_image_title": "Resim hatası", + "app_tagline": "Evrensel Açık Kaynaklı Nakış & Dijitize Paketi", + "tb_title_studio": "Stüdyo araç çubuğu", + "tb_title_tools": "Çizim araçları", + "tip_autofit": "Tasarımı seçili kasnağa en uygun şekilde sığdır (Ctrl+F)", + "tip_fabric": "Kasnaktaki kumaş arka planını değiştir (koyu arduvaz / sıcak kum / açık)", + "tip_tool_select": "Nesneleri seç, taşı ve boyutlandır (V tuşu)", + "tip_tool_nodes": "Kontur düğümlerini ve dikiş açısı eksenini doğrudan sürükle (N tuşu)", + "tip_tool_fill": "Tuvale yeni bir tatami dolgu alanı çiz (F tuşu)", + "tip_tool_satin": "Tuvale yeni bir saten sütunu çiz (S tuşu)", + "tip_tool_run": "Yeni bir düz dikiş yolu çiz (R tuşu)", + "tip_tool_heatmap": "Dikiş yoğunluğu haritasını (yeşil/sarı/kırmızı) göster/gizle (Ctrl+H)", + "tip_tool_zoom": "Görünümü kasnağa sığdır (Ctrl+0)", + "tip_obj_up": "Nesneyi dikiş sırasında yukarı taşı", + "tip_obj_down": "Nesneyi dikiş sırasında aşağı taşı", + "tip_obj_delete": "Seçili nesneyi sil (Del)", + "sim_all": "Tümü", + "sim_speed_suffix": " dik./tick", + "abbr_stitches": "dik.", + "stats_trims": "İplik kesme", + "kind_fill": "Dolgu", + "kind_satin": "Saten", + "kind_run": "Düz dikiş", + "kind_text": "Yazı", + "kind_stitches": "Dikişler", + "obj_hidden": "[Gizli]", + "btn_font_arc": "Yazı tipi & yayı ayarla …", + "status_hoop_strategy": "Kasnak stratejisi etkin: {}", + "status_saved": "Kaydedildi: {}", + "color_dialog_title": "İplik rengi seçin", + "default_design_name": "Yeni_Tasarim", + "fd_open_project": "Proje aç", + "fd_save_project": "Projeyi kaydet", + "fd_import_emb": "Nakış dosyası içe aktar", + "fd_import_svg": "SVG vektör grafiği içe aktar", + "fd_export_emb": "Nakış dosyası dışa aktar", + "fd_save_pdf": "Üretim sayfasını kaydet (PDF)", + "pdf_file_suffix": "uretim_sayfasi", + "fd_save_png": "3D dikiş önizlemesini kaydet", + "fd_pick_image": "Bir resim, grafik ya da logo seçin (İndirilenler / Resimler / Masaüstü)", + "fd_pick_photo": "Bir portre ya da manzara fotoğrafı seçin (İndirilenler / Resimler / Masaüstü)", + "msg_applique_title": "Aplike", + "msg_applique_text": "Lütfen önce tuval üzerinde bir dolgu ya da saten şekli seçin.", + "msg_export_verified_title": "Dışa aktarma ve ikili doğrulama başarılı", + "msg_export_verified_text": "✅ Nakış dosyası kaydedildi ve simülatörde doğrulandı:\n{path}\n\n• Dosya boyutu: {size} bayt\n• Doğrulanan dikişler: {stitches}\n• Boyutlar: {w:.1f} × {h:.1f} mm\n• En uzun adım: {step:.1f} mm\n• Renk değişimi: {colors} · Atlama: {jumps}", + "msg_export_ok_title": "Dışa aktarma başarılı", + "msg_export_ok_text": "Dosya kaydedildi:\n{}", + "msg_pdf_ok_title": "PDF oluşturuldu", + "msg_pdf_ok_text": "Üretim sayfası kaydedildi:\n{}", + "msg_puff_title": "3D puff köpük", + "msg_puff_text": "Lütfen bir saten nesnesi seçin.", + "dlg_scale_title": "Tasarımı ölçekle (dikişler yeniden hesaplanacak!)", + "dlg_scale_label": "Ölçek oranı (%):", + "hoop_round9": "Yuvarlak 9 cm (küçük/göğüs)", + "hoop_round12": "Yuvarlak 12 cm (göğüs logosu)", + "hoop_round15": "Yuvarlak 15 cm (standart)", + "hoop_round18": "Yuvarlak 18 cm (büyük)", + "hoop_round21": "Yuvarlak 21 cm (XL)", + "hoop_cap": "Şapka 13 × 5 cm", + "hoop_widecap": "Geniş şapka 30 × 7 cm", + "hoop_rect13x18": "Dikdörtgen 13 × 18 cm (ev tipi)", + "hoop_jacket": "Ceket sırtı 30 × 30 cm", + "hoop_field40x30": "Geniş alan 40 × 30 cm (endüstriyel)", + "hoop_strat_small": "Sıkı gerginlik · ince detaylar (%10 az çekme telafisi, standart alt dikiş)", + "hoop_strat_medium": "Dengeli · standart göğüs/kol kasnağı (%100 çekme telafisi)", + "hoop_strat_large": "Trambolin önleyici · güçlendirilmiş alt dikiş (%20 fazla çekme telafisi + büyük alanlarda çapraz ızgara)", + "hoop_strat_jacket": "Ceket sırtı sabitleme (%35 fazla çekme telafisi, çift ızgara alt dikiş, en fazla 750 SPM)", + "hoop_strat_cap": "Şapka modu (ortadan dışa ve siperlikten yukarı doğru, %30 fazla çekme telafisi)", + "hoop_strat_default": "Standart", + "machine_universal_multi": "Evrensel standart (DST / PES / EXP · 15 iğne)", + "machine_tajima_tmez": "Tajima TMEZ / TFMX / TMBR (15 iğne)", + "machine_brother_pr": "Brother PR serisi / Persona (6–10 iğne)", + "machine_brother_home": "Brother / Baby Lock ev tipi (1 iğne · PES)", + "machine_barudan_bext": "Barudan BEKT / BEXT (15 iğne)", + "machine_ricoma_happy_zsk": "Ricoma / HappyJapan / SWF / ZSK (12–15 iğne)", + "machine_janome_elna": "Janome / Elna / Bernina ev tipi (JEF / EXP)", + "machine_pfaff_husqvarna": "Pfaff / Husqvarna Viking (VP3)", + "machine_melco_emt10_4": "Melco EMT10/4 (4 kafa / 10 iğne)", + "machine_melco_amaya_bravo": "Melco Amaya / EMT16X / Bravo (16 iğne)", + "param_angle": "Dikiş açısı (°)", + "param_fill_spacing": "Sıra aralığı (mm)", + "param_satin_spacing": "Yoğunluk (mm)", + "param_stitch_len": "Dikiş uzunluğu (mm)", + "param_pattern": "Desen", + "param_underlay": "Alt dikiş", + "param_pull_comp": "Çekme telafisi (mm)", + "param_max_stitch": "En uzun dikiş / bölme (mm)", + "param_underlay_style": "Alt dikiş türü", + "param_puff_3d": "3D puff (şapka modu)", + "param_repeats": "Tekrar (0 = tek, 1 = üçlü)", + "param_text": "Metin", + "param_font": "Yazı tipi", + "param_height": "Harf yüksekliği (mm)", + "param_letter_spacing": "Harf aralığı (mm)", + "param_arc_radius": "Yay yarıçapı (mm, 0 = düz)", + "param_mode": "Dikiş türü", + "param_density": "Yoğunluk (mm)", + "opt_standard": "Standart", + "opt_diagonal": "Çapraz", + "opt_ziegel": "Tuğla", + "opt_wellen": "Dalga", + "opt_kontur": "Kontur", + "opt_auto": "Otomatik", + "opt_mitte": "Orta hat dikişi", + "opt_kante": "Kenar dikişi", + "opt_zickzack": "Zikzak", + "opt_kante+zickzack": "Kenar dikişi + zikzak", + "opt_satin": "Saten dikiş", + "opt_fill": "Tatami dolgu", + "dlg_auto_title": "Resmi otomatik dijitize et (Otomatik Dijitize Edici)", + "lbl_orig_image": "Özgün resim ({})", + "btn_other_image": "📂 Başka bir resim seç (İndirilenler / Masaüstü / Resimler …)", + "grp_auto_settings": "Nakış ayarları & otomasyon", + "lbl_target_width_motif": "Hedef tasarım genişliği:", + "lbl_max_colors": "En fazla iplik rengi (iğne):", + "cb_remove_bg": "Resmin arka planını otomatik kaldır", + "fabric_opt_normal": "Standart (pamuk / twill / genel)", + "fabric_opt_strick": "Piqué / polo / triko (daha fazla çekme telafisi)", + "fabric_opt_frottee": "Havlu kumaşı / havlu (daha sık + güçlü alt dikiş)", + "fabric_opt_cap": "Şapka (yüksek çekme telafisi)", + "fabric_opt_leicht": "Hafif kumaş / gömlek (daha düşük yoğunluk)", + "lbl_fabric_type": "Kumaş / malzeme:", + "lbl_density_row": "Dikiş yoğunluğu (sıra aralığı):", + "lbl_satin_limit": "Saten sınırı (daha dar = saten):", + "lbl_min_area": "Şundan küçük parçaları ele:", + "cb_outline": "Tasarımın çevresine saten kontur ekle", + "cb_palette": "Renkleri iplik paletine uydur", + "status_ready": "Hazır.", + "btn_digitize_apply": "Şimdi dijitize et && uygula", + "fd_pick_logo": "Bir resim ya da logo seçin (İndirilenler / Resimler / Masaüstü)", + "fd_pick_logo_short": "Bir resim ya da logo seçin", + "err_digitize_title": "Dijitize etme başarısız oldu", + "prog_computing_stitches": "Dikişler hesaplanıyor ({}/{}) …", + "prog_prepare": "Resim hazırlanıyor …", + "prog_reduce": "Renkler azaltılıyor …", + "prog_clean": "Alanlar temizleniyor …", + "prog_vectorize": "Konturlar vektörleştiriliyor …", + "prog_done": "Bitti", + "prog_classify": "Alan sınıflandırılıyor {}/{} …", + "dlg_text_title": "Yazı / monogram oluştur", + "lbl_text": "Metin:", + "lbl_font_file": "Yazı tipi (TTF/OTF):", + "lbl_letter_height": "Harf yüksekliği (büyük harf yüksekliği):", + "lbl_letter_spacing": "Harf aralığı:", + "sfx_arc": " mm (0 = düz)", + "lbl_arc_radius": "Yay yarıçapı:", + "text_mode_auto": "Otomatik (7 mm'ye kadar saten, üstünde tatami)", + "text_mode_satin": "Her zaman saten dikiş (parlak yazı)", + "text_mode_fill": "Her zaman tatami dolgu", + "lbl_stitch_type": "Dikiş türü:", + "lbl_stitch_density": "Dikiş yoğunluğu:", + "msg_enter_text": "Lütfen bir metin girin.", + "text_obj_name": "Metin “{}”", + "dlg_transfer_title": "Makineye aktarım (USB / 1,44 MB disket emülatörü / Wi-Fi NetBridge)", + "grp_transfer_1": "1. Makine & iplik kesme ayarları (EXP / endüstriyel biçim)", + "lbl_dos_name": "DOS dosya adı (8.3 biçimi):", + "trim_both": "Birleşik: EXP kesme kodu + 3 atlama (en yüksek uyumluluk)", + "trim_code": "Standart EXP kesme kodu (80 80 07 00)", + "trim_jumps": "Yalnızca atlama dizisi (eski EMT yazılımları için)", + "lbl_trim_mode": "İplik kesme modu:", + "grp_transfer_2": "2. Doğrudan USB belleğe / sürücüye ya da Wi-Fi NetBridge ile gönder", + "btn_save_exp_usb": "EXP'yi doğrudan USB belleğe / klasöre kaydet …", + "lbl_netbridge_url": "NetBridge URL'si:", + "btn_send_netbridge": "Wi-Fi ile Melco NetBridge'e gönder", + "grp_transfer_3": "3. USB emülatörü (GoTek / HxC) için 1,44 MB FAT12 disket görüntüsü (.IMG)", + "lbl_img_initial": "Geçerli görüntü: yeni boş 1,44 MB görüntü (FAT12)", + "btn_open_img": "Var olan .IMG dosyasını aç …", + "btn_add_cur_img": "Geçerli tasarımı görüntüye ekle", + "btn_del_file": "Seçili dosyayı sil", + "btn_save_img": ".IMG dosyasını kaydet …", + "unit_bytes": "bayt", + "img_new": "Yeni 1,44 MB görüntü", + "img_free": "{src} — Boş alan: {total} KB içinde {free} KB", + "fd_save_exp": "Melco EXP kaydet", + "msg_saved_title": "Kaydedildi", + "msg_exp_saved": "Melco nakış dosyası kaydedildi:\n{path}\n({size} bayt)", + "msg_wifi_ok_title": "Wi-Fi aktarımı başarılı", + "msg_wifi_ok_text": "{url} adresine gönderildi:\n{body}", + "msg_netbridge_fail_title": "NetBridge'e ulaşılamıyor", + "msg_netbridge_fail_text": "{url} adresine ulaşılamadı:\n{err}", + "fd_open_img": "FAT12 disket görüntüsünü aç", + "fd_save_img": "1,44 MB FAT12 disket görüntüsünü kaydet", + "msg_img_saved_title": "Disket görüntüsü kaydedildi", + "msg_img_saved_text": "1,44 MB FAT12 görüntüsü kaydedildi:\n{path}\n\nGoTek/FlashFloppy için ipucu: USB bellekteki görüntüleri örneğin DSKA0000.IMG, DSKA0001.IMG şeklinde adlandırın ya da FlashFloppy doğrudan dosya modunda çalışıyorsa .EXP dosyasını doğrudan kopyalayın.", + "dlg_photo_title": "PhotoStitch — portre & fotoğraf nakışı oluştur", + "lbl_orig_photo": "Özgün fotoğraf ({})", + "btn_other_photo": "📂 Başka bir fotoğraf seç (İndirilenler / Masaüstü / Resimler …)", + "grp_photo_settings": "PhotoStitch ayarları", + "lbl_target_width": "Hedef genişlik:", + "photo_mode_mono": "Tek renkli gravür (açık kumaşta 1 iplik rengi)", + "photo_mode_sepia": "Sepya portre (2 iplik rengi: açık kahve + koyu kahve)", + "photo_mode_color4": "4 renkli CMYK yarım ton (sarı, magenta, camgöbeği, siyah)", + "lbl_color_mode": "Renk modu:", + "lbl_row_spacing_fine": "Satır aralığı (inceliği):", + "lbl_contrast": "Kontrast artırma:", + "btn_photo_apply": "PhotoStitch'i hesapla && uygula", + "pdf_title": "{} — Üretim & hazırlık sayfası", + "pdf_created": "{app} ile {date} tarihinde oluşturuldu", + "pdf_date_fmt": "%d.%m.%Y %H:%M", + "pdf_total_stitches": "Toplam dikiş", + "pdf_size": "Boyut (G × Y)", + "pdf_color_changes": "Renk değişimi / blok", + "pdf_blocks_val": "{} ({} blok)", + "pdf_trims": "İplik kesme", + "pdf_hoop": "Kasnak", + "pdf_runtime": "Çalışma süresi (yaklaşık {} SPM)", + "pdf_thread_usage": "Üst iplik tüketimi", + "pdf_machine": "Makine profili", + "pdf_sequence": "Renk sırası & iğne ataması ({} iğne)", + "tour_next": "İleri →", + "tour_prev_tip": "Önceki adım", + "tour_close_tip": "Tanıtımı kapat (Esc)", + "tour_on_start": "Açılışta", + "tour_done": "Bitti ✓", + "tour_app_1_badge": "HOŞ GELDİNİZ · 1 / 7", + "tour_app_1_title": "Tuval: tasarımınız 3D olarak", + "tour_app_1_body": "Tasarımınız ortada, kasnağın içinde duruyor. Başlangıçta bu, OpenStitch arması.

• Tıklayıp sürükleyin: parçaları seçin, taşıyın ya da köşe tutamacıyla boyutlandırın.
• Fare tekerleği: tek tek dikişleri görene kadar pürüzsüzce yakınlaştırın.", + "tour_app_1_action": "🎨 Kasnakta bir kumaş rengi deneyin (koyu / kum / açık)", + "tour_app_2_badge": "TUVALİN ÜSTÜ · 2 / 7", + "tour_app_2_title": "Makine, kasnak ve kumaş", + "tour_app_2_body": "Tuvalin hemen üstünde, OpenStitch'e neyin üzerine diktiğinizi söylersiniz:

• Makine: Evrensel, Tajima, Brother, Barudan, Melco …
• Kasnak: OpenStitch alt dikişi ve çekme telafisini boyuta göre ayarlar. Büyük kasnaklara zıplamaya karşı ek destek verilir, şapkalar ise ortadan dışa ve siperlikten yukarı doğru dikilir.
• Kumaş: yoğunluğu ve çekme telafisini ayarlar, bir stabilizatör ve iğne önerir.", + "tour_app_2_action": "⛶ Tasarımı kasnağa sığdır (Otomatik sığdır)", + "tour_app_3_badge": "ÜST ARAÇ ÇUBUĞU · 3 / 7", + "tour_app_3_title": "Resim, yazı, kontrol ve dışa aktarma", + "tour_app_3_body": "Dosya düğmelerinin ve Geri al'ın yanında ana adımları bulursunuz:

• Resimden dikişe (Ctrl+D): bir resim seçin, OpenStitch arka planı kaldırır ve dikiş alanlarını oluşturur.
• Yazı (Ctrl+T): metin ve monogram ekleyin.
• Kontrol (F7): tasarımınızı sınar ve 100 üzerinden puan verir.
• Dışa aktar (Ctrl+E): makineniz için dosyayı kaydeder.

PhotoStitch, Aplike ve 3D Puff Dijitize menüsünde, SVG Dosya menüsünde, Aktarım ise Makine & Dışa Aktarma menüsünde.", + "tour_app_3_action": "✨ Resimden dikişe aracını aç …", + "tour_app_4_badge": "ARAÇLAR · 4 / 7", + "tour_app_4_title": "Elle çizin ve düğümleri düzenleyin (N)", + "tour_app_4_body": "Soldaki dar çubukta yalnızca simgeler görünür. Adını görmek için fareyi üzerine getirin:

• Tatami (F) / Saten (S) / Düz dikiş (R): tuval üzerinde kendi şekillerinizi çizin.
• Düğümler (N): kontur noktalarını tek tek taşıyın ve dikiş açısını çevirmek için sarı ekseni sürükleyin.", + "tour_app_4_action": "❖ Düğüm ve dikiş açısı düzenleyicisini aç (N)", + "tour_app_5_badge": "İPLİK RENKLERİ · 5 / 7", + "tour_app_5_title": "Renkler ve iğne sırası", + "tour_app_5_body": "Solda iplik kataloğundan (Madeira, Isacord, Gunold, Brother …) tek tıkla bir renk seçin ya da RGB ile kendi tonunuzu karıştırın.

• Altında, tasarımınızdaki renklerin ve iğnelerin sırasını her renk için dikiş sayısıyla birlikte görürsünüz.", + "tour_app_6_badge": "KATMANLAR VE AYARLAR · 6 / 7", + "tour_app_6_title": "Katmanlar ve nesne ayarları", + "tour_app_6_body": "Sağda dikiş sırasını belirlersiniz. Altında seçili nesneyi ayarlarsınız: sıra aralığı, desen (örneğin Kontur), çekme telafisi ya da saten için 3D puff.

• Her değişiklik, tuvaldeki dikişleri hemen yeniden hesaplar.", + "tour_app_7_badge": "SİMÜLATÖR VE DURUM · 7 / 7", + "tour_app_7_title": "Dikiş simülatörü ve durum çubuğu", + "tour_app_7_body": "Tuvalin altında tasarımın tamamını dikiş dikiş oynatabilirsiniz.

• En alttaki durum çubuğu dikişleri, boyutu, renk değişimlerini, iplik kesmeleri ve tahmini çalışma süresini gösterir. Hız ve en yüksek yoğunluk için fareyi üzerine getirin.
• Dili sağ alttan değiştirirsiniz.", + "tour_app_7_action": "▶ Simülasyonu başlat / durdur", + 'chk_tag_rule': 'Kesin kural', + 'chk_tag_model': 'Tahmin', + 'cal_open': 'Gerçek kumaşla kalibre et …', + 'cal_title': 'Kumaşı kalibre et', + 'cal_intro': '1. Test çubuğunu yükleyin ve gerçekten kullandığınız kumaş, tela ve iplik gerginliğiyle işleyin.\n2. Çubuğun ortasındaki genişliği ölçün. Planlanan genişlik {width} mm.\n3. Ölçümü girin. Simülasyon ve çekme telafisi artık gerçek değerinizi kullanır.', + 'cal_load': 'Test çubuğunu yükle', + 'cal_measured': 'Ölçülen genişlik:', + 'cal_apply': 'Uygula', + 'cal_reset': 'Sıfırla', + 'cal_state_estimate': 'Bu kumaş henüz ölçülmedi: kumaş çekmesi bir tahmindir.', + 'cal_state_measured': 'Ölçüldü: kumaş çekmesi tahminin {factor} katı.', + 'chk_disclaimer': 'Kesin kurallar doğrudan dikişlerden çıkar. Kumaş çekmesi tahminleri, kumaşı kalibre edince doğru olur.', +} diff --git a/openstitch/samples.py b/openstitch/samples.py new file mode 100644 index 0000000..9f845d2 --- /dev/null +++ b/openstitch/samples.py @@ -0,0 +1,78 @@ +"""Beispiel-Designs für die Startseite: fertige Motive zum Ausprobieren und Abwandeln.""" +from __future__ import annotations + +import math + +from shapely.geometry import LineString, Point, Polygon, box + +from .core.design import ColumnObject, Design, FillObject, HOOPS, RunObject, SatinObject +from .core.stitchplan import Thread +from .text import TextObject + +NAVY = Thread((24, 42, 92), "Navy") +GOLD = Thread((232, 176, 40), "Gold") +RED = Thread((205, 38, 52), "Red") +GREEN = Thread((44, 138, 84), "Green") +WHITE = Thread((245, 245, 245), "White") +ROSE = Thread((232, 120, 150), "Pink") +LEAF = Thread((88, 150, 70), "Leaf") +YELLOW = Thread((248, 205, 70), "Yellow") + + +def _heart(size: float) -> Polygon: + pts = [] + for i in range(80): + t = 2 * math.pi * i / 80 + x = 16 * math.sin(t) ** 3 + y = 13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t) + pts.append((x * size / 32, -y * size / 32)) + return Polygon(pts) + + +def name_patch() -> Design: + """Namensschild: Rand als Satin, Name in der Kleinschrift-tauglichen Einstrich-Schrift.""" + outer = box(-40, -14, 40, 14).buffer(6, join_style=1).buffer(-3) + inner = outer.buffer(-3.2) + d = Design(name="Name_Patch", hoop=HOOPS[2]) + d.objects.append(FillObject(NAVY, name="Background", geom=inner.buffer(0.4), angle=20)) + d.objects.append(SatinObject(GOLD, name="Border", geom=outer.difference(inner))) + d.objects.append(TextObject(WHITE, name="Name", text="Your Name", height=9.0, font="builtin:micro")) + return d + + +def heart() -> Design: + d = Design(name="Heart", hoop=HOOPS[1]) + shape = _heart(62) + d.objects.append(FillObject(RED, name="Heart", geom=shape, angle=35, pattern="ziegel")) + d.objects.append(SatinObject(ROSE, name="Outline", geom=shape.buffer(1.4).difference(shape.buffer(-1.6)))) + return d + + +def flower() -> Design: + d = Design(name="Flower", hoop=HOOPS[1]) + stem = LineString([(0, 6), (3, 24), (-1, 42)]) + d.objects.append(ColumnObject(LEAF, name="Stem", geom=stem, width=2.6)) + leaf = Polygon([(2, 30), (12, 21), (22, 22), (13, 31)]).buffer(1.2, join_style=1) + d.objects.append(FillObject(LEAF, name="Leaf", geom=leaf, angle=-30)) + for i in range(6): + a = i * math.pi / 3 + petal = Point(13 * math.cos(a), -8 + 13 * math.sin(a)).buffer(7.5) + d.objects.append(SatinObject(ROSE, name=f"Petal {i + 1}", geom=petal)) + d.objects.append(FillObject(YELLOW, name="Center", geom=Point(0, -8).buffer(7), angle=60)) + return d + + +def monogram() -> Design: + d = Design(name="Monogram", hoop=HOOPS[1]) + d.objects.append(SatinObject(GREEN, name="Ring", geom=Point(0, 0).buffer(32).difference(Point(0, 0).buffer(29)))) + d.objects.append(RunObject(GREEN, name="Inner ring", geom=Point(0, 0).buffer(26).exterior, repeats=1)) + d.objects.append(TextObject(GOLD, name="Monogram", text="AB", height=26.0)) + return d + + +SAMPLES = ( + ("patch", "sample_patch", name_patch), + ("heart", "sample_heart", heart), + ("flower", "sample_flower", flower), + ("monogram", "sample_monogram", monogram), +) diff --git a/openstitch/selftest.py b/openstitch/selftest.py new file mode 100644 index 0000000..6ae22c7 --- /dev/null +++ b/openstitch/selftest.py @@ -0,0 +1,60 @@ +"""Selbsttest für fertig gepackte Programme: `OpenStitch-Studio --selftest`. + +Fehlt beim Packen eine Bibliothek oder Sprachdatei, startet das Fenster oft trotzdem, und der Fehler +zeigt sich erst bei der ersten echten Aktion. Der Test führt diese Aktionen einmal durch.""" +from __future__ import annotations + +import traceback + +import numpy as np + +REPORT_FILE = "openstitch-selftest.txt" + + +def _steps(): + from .analysis import simulate_stitchout + from .analysis.roundtrip import MACHINE_FORMATS, check_format + from .auto.digitize import AutoParams, auto_digitize + from .i18n import LANGUAGES, extra_table + from .render import render_image + from .samples import SAMPLES + + design = SAMPLES[0][2]() + plan = design.build_plan() + assert plan.stitch_count > 100, "no stitches" + yield "stitch engine" + + assert simulate_stitchout(design, plan, needles=15).pull is not None, "no fabric simulation" + yield "virtual stitch-out" + + for ext in MACHINE_FORMATS: + result = check_format(plan, ext) + assert result.ok, (ext, result.problems) + yield "machine formats" + + assert render_image(plan, px_per_mm=2.0).width() > 10, "no preview" + yield "preview" + + img = np.full((120, 120, 4), 255, np.uint8) + img[30:90, 30:90, :3] = (200, 30, 30) + assert auto_digitize(img, AutoParams(width_mm=40.0, colors=2)).design.objects, "auto-digitizer found nothing" + yield "auto-digitizer" + + for code, _label in LANGUAGES: + assert code in ("de", "en", "fr", "es") or extra_table(code), f"language {code} missing" + yield "languages" + + +def run() -> int: + """0 = alles in Ordnung. Der Bericht landet in einer Datei, weil gepackte Programme keine Konsole haben.""" + lines: list[str] = [] + code = 0 + try: + for name in _steps(): + lines.append(f"ok {name}") + except Exception: # noqa: BLE001 - genau diese Fehler soll der Test sichtbar machen + lines.append("FAIL\n" + traceback.format_exc()) + code = 1 + with open(REPORT_FILE, "w", encoding="utf-8") as f: + f.write("\n".join(lines) + "\n") + return code diff --git a/openstitch/text.py b/openstitch/text.py index 74ba962..2909c39 100644 --- a/openstitch/text.py +++ b/openstitch/text.py @@ -301,13 +301,15 @@ def _micro_runs(self, start=None): """Micro-Schrift: Mittellinien je Zeichen als schmale Satinsäulen / Dreifachstich.""" cap = self.height * m_scale(self.transform) # wirksame Versalhöhe in mm w = micro_stroke_width(cap) - pc = micro_pull_comp(w, self.pull_comp) # schmale Säulen: wenig Zugkompensation + # Schmale Säulen brauchen wenig Zugkompensation + pc = micro_pull_comp(w, self.pull_comp * getattr(self, "_hoop_pc_boost", 1.0)) glyph_strokes, thin = [], [] for ch, g, _ in self._glyphs(): wg = affinity.affine_transform(g, self.transform) glyph_strokes.append([[tuple(c) for c in p.coords] for p in wg.geoms]) thin.append(micro_mark_strokes(ch)) - return micro_text_runs(glyph_strokes, w, spacing=self.density, pull_comp=pc, + return micro_text_runs(glyph_strokes, w, spacing=self.density * getattr(self, "_density_factor", 1.0), + pull_comp=pc, run_len=micro_run_length(cap), glyph_thin=thin) def runs(self, start=None): @@ -326,6 +328,8 @@ def runs(self, start=None): ang = 45.0 o = FillObject(self.thread, geom=part, angle=ang, spacing=self.density, pull_comp=self.pull_comp) + o._hoop_pc_boost = getattr(self, "_hoop_pc_boost", 1.0) + o._density_factor = getattr(self, "_density_factor", 1.0) rs = o.runs(cur) if rs: out.extend(rs) diff --git a/openstitch/ui/canvas.py b/openstitch/ui/canvas.py index 09c3e95..5e54f36 100644 --- a/openstitch/ui/canvas.py +++ b/openstitch/ui/canvas.py @@ -5,7 +5,7 @@ import os from collections import defaultdict -from PySide6.QtCore import QPointF, QRectF, Qt, Signal +from PySide6.QtCore import QPointF, QRectF, Qt, QTimer, Signal from PySide6.QtGui import ( QColor, QFont, @@ -25,6 +25,7 @@ from ..core.design import ColumnObject, Design, EmbObject, FillObject, RunObject, SatinObject, compose, m_scale from ..core.stitchplan import Cmd, StitchPlan, Thread from ..i18n import tr +from . import theme from ..render import draw_plan @@ -55,6 +56,7 @@ def __init__(self, parent=None): self.show_heatmap: bool = False self.fabric_theme: str = "slate" # 'slate' | 'sand' | 'light' self.sim_limit: int | None = None + self._spots: list[tuple[float, float]] = [] # Fundstellen der Design-Prüfung # 3D-Render-Cache (verhindert Neuberechnung von 100k Linien bei jedem Maus-Event!) self._cache_img: QImage | None = None @@ -81,6 +83,22 @@ def __init__(self, parent=None): self._dragging_node_idx: int | None = None self._dragging_angle: bool = False + def show_spots(self, pts: list[tuple[float, float]]): + """Zeigt Fundstellen der Prüfung: heranzoomen und für einige Sekunden markieren.""" + if not pts: + return + self._spots = list(pts) + x, y = pts[0] + self.px_per_mm = max(self.px_per_mm, 7.0) + self.pan_x, self.pan_y = -x * self.px_per_mm, -y * self.px_per_mm + self.invalidate_render_cache() + QTimer.singleShot(6000, self._clear_spots) + self.update() + + def _clear_spots(self): + self._spots = [] + self.update() + def invalidate_render_cache(self): self._plan_version += 1 self._cache_key = None @@ -180,7 +198,7 @@ def paintEvent(self, event): p.setRenderHint(QPainter.SmoothPixmapTransform, True) # Weicher, augenfreundlicher Studio-Hintergrund (kein hartes Schwarz) - p.fillRect(self.rect(), QColor(34, 38, 47)) + p.fillRect(self.rect(), theme.color("canvas")) p.save() p.translate(self.width() / 2.0 + self.pan_x, self.height() / 2.0 + self.pan_y) @@ -346,16 +364,25 @@ def paintEvent(self, event): "draw_satin": "hud_satin", "draw_run": "hud_run", } + if self._spots: + p.setBrush(Qt.NoBrush) + p.setPen(QPen(theme.color("err"), 2.2)) + for x, y in self._spots: + p.drawEllipse(self.mm_to_screen(x, y), 15, 15) hud_text = tr(tool_keys.get(self.tool, "hud_select")) p.setFont(QFont("Segoe UI", 8.5)) fm = p.fontMetrics() tw = fm.horizontalAdvance(hud_text) + 22 hud_rect = QRectF(12, 10, tw, 24) - p.setPen(QPen(QColor(68, 76, 94, 150), 1)) - p.setBrush(QColor(38, 43, 54, 210)) + p.setPen(QPen(theme.color("outline_soft"), 1)) + p.setBrush(theme.color("hud_bg")) p.drawRoundedRect(hud_rect, 12, 12) - p.setPen(QColor(186, 195, 212)) + p.setPen(theme.color("hud_text")) p.drawText(hud_rect, Qt.AlignCenter, hud_text) + if not self.design.objects and self.tool == "select": + p.setPen(theme.color("text_faint")) + r = self.rect().adjusted(40, 0, -40, 0) + p.drawText(r, Qt.AlignCenter | Qt.TextWordWrap, tr("canvas_empty_hint")) # --------------------------------------------------------- Maus / Key def wheelEvent(self, event: QWheelEvent): diff --git a/openstitch/ui/check_dialog.py b/openstitch/ui/check_dialog.py new file mode 100644 index 0000000..d5efff8 --- /dev/null +++ b/openstitch/ui/check_dialog.py @@ -0,0 +1,408 @@ +"""Design-Prüfung: virtueller Probestick mit Punktzahl, Befunden in Klartext und Stoffvorschau.""" +from __future__ import annotations + +import copy + +from PySide6.QtCore import QRectF, QSettings, Qt, QThread, Signal +from PySide6.QtGui import QFont, QImage, QPainter, QPen, QPixmap +from PySide6.QtWidgets import ( + QDialog, + QDoubleSpinBox, + QFrame, + QHBoxLayout, + QLabel, + QPushButton, + QScrollArea, + QSizePolicy, + QSlider, + QVBoxLayout, + QWidget, +) + +from ..analysis import Report, simulate_stitchout +from ..analysis.calibrate import BAR_WIDTH, calibration_design, fit_scale, is_measured +from ..analysis.roundtrip import RoundTrip, check_format +from ..core.design import Design +from ..core.fabric import pull_scale, set_pull_scale +from ..core.stitchplan import Cmd, ColorBlock, Stitch, StitchPlan +from ..i18n import fmt_float, fmt_int, tr +from ..render import render_image +from . import theme + +CANVAS_COLOR = {"slate": (52, 58, 72), "sand": (188, 182, 170), "light": (226, 222, 214)} +SEVERITY_KEY = {"error": "chk_sev_error", "warning": "chk_sev_warning", "info": "chk_sev_info"} + + +class _CheckWorker(QThread): + done = Signal(object, object) # Report, RoundTrip + failed = Signal(str) + + def __init__(self, design: Design, plan: StitchPlan, needles: int, ext: str, parent=None): + super().__init__(parent) + self.design, self.plan, self.needles, self.ext = design, plan, needles, ext + + def run(self): + try: + report = simulate_stitchout(self.design, self.plan, needles=self.needles) + export = check_format(self.plan, self.ext) if self.plan.stitch_count else None + self.done.emit(report, export) + except Exception as exc: # noqa: BLE001 - die Prüfung soll das Programm nie mitreissen + self.failed.emit(str(exc)) + + +class ScoreRing(QWidget): + """Punktzahl als Ring: auf einen Blick sichtbar, auch ohne die Zahl zu lesen.""" + + def __init__(self, parent=None): + super().__init__(parent) + self.score: int | None = None + self.setFixedSize(78, 78) + + def set_score(self, score: int | None): + self.score = score + self.update() + + def paintEvent(self, _ev): + p = QPainter(self) + p.setRenderHint(QPainter.Antialiasing, True) + r = QRectF(7, 7, self.width() - 14, self.height() - 14) + p.setPen(QPen(theme.color("surface_top"), 8)) + p.drawEllipse(r) + if self.score is None: + return + name = "ok" if self.score >= 85 else "warn" if self.score >= 60 else "err" + p.setPen(QPen(theme.color(name), 8, Qt.SolidLine, Qt.RoundCap)) + p.drawArc(r, 90 * 16, -int(self.score / 100 * 360 * 16)) + p.setPen(theme.color("text")) + f = QFont(self.font()) + f.setPointSizeF(15) + f.setBold(True) + p.setFont(f) + p.drawText(self.rect(), Qt.AlignCenter, str(self.score)) + + +def distorted_plan(plan: StitchPlan, report: Report, factor: float) -> StitchPlan: + """Stichplan so, wie er nach dem Fadenzug auf dem Stoff liegt (zur Sicht verstärkt um `factor`).""" + pull = report.pull + if pull is None: + return plan + shift = {int(i): (float(dx), float(dy)) for i, dx, dy in zip(pull.idx, pull.dx, pull.dy)} + out = StitchPlan() + n = 0 + for b in plan.blocks: + nb = ColorBlock(b.thread, object_ids=b.object_ids) + for s in b.stitches: + dx, dy = shift.get(n, (0.0, 0.0)) + if s.cmd == Cmd.STITCH: + nb.stitches.append(Stitch(s.x + dx * factor, s.y + dy * factor, s.cmd)) + else: + nb.stitches.append(Stitch(s.x, s.y, s.cmd)) + n += 1 + out.blocks.append(nb) + return out + + +class CalibrationDialog(QDialog): + """Testbalken sticken, messen, eintragen: Danach rechnet die Simulation mit dem echten Stoffzug.""" + + def __init__(self, win, parent=None): + super().__init__(parent or win) + self.win = win + self.fabric_id = win.canvas.design.fabric + self.setWindowTitle(tr("cal_title")) + self.resize(520, 300) + root = QVBoxLayout(self) + root.setContentsMargins(18, 16, 18, 14) + root.setSpacing(10) + head = QLabel(tr(f"fab_{self.fabric_id}")) + head.setProperty("role", "section") + root.addWidget(head) + intro = QLabel(tr("cal_intro").format(width=fmt_float(BAR_WIDTH, 1))) + intro.setWordWrap(True) + root.addWidget(intro) + btn_load = QPushButton(tr("cal_load")) + btn_load.clicked.connect(self.load_patch) + root.addWidget(btn_load, 0, Qt.AlignLeft) + row = QHBoxLayout() + row.addWidget(QLabel(tr("cal_measured"))) + self.sp_width = QDoubleSpinBox() + self.sp_width.setRange(2.5, 6.0) + self.sp_width.setSingleStep(0.05) + self.sp_width.setDecimals(2) + self.sp_width.setValue(BAR_WIDTH - 0.3) + self.sp_width.setSuffix(" mm") + row.addWidget(self.sp_width) + row.addStretch(1) + root.addLayout(row) + self.lbl_state = QLabel() + self.lbl_state.setWordWrap(True) + self.lbl_state.setProperty("role", "cardText") + root.addWidget(self.lbl_state) + root.addStretch(1) + btns = QHBoxLayout() + btns.addStretch(1) + btn_reset = QPushButton(tr("cal_reset")) + btn_reset.clicked.connect(self.reset) + btn_apply = QPushButton(tr("cal_apply")) + btn_apply.setObjectName("primaryBtn") + btn_apply.clicked.connect(self.apply) + btn_close = QPushButton(tr("btn_close")) + btn_close.clicked.connect(self.accept) + btns.addWidget(btn_reset) + btns.addWidget(btn_close) + btns.addWidget(btn_apply) + root.addLayout(btns) + self._show_state() + + def _show_state(self): + scale = pull_scale(self.fabric_id) + self.lbl_state.setText(tr("cal_state_measured").format(factor=fmt_float(scale, 2)) if is_measured(self.fabric_id) + else tr("cal_state_estimate")) + + def load_patch(self): + if self.win._confirm_discard(): + self.win.set_design(calibration_design(self.fabric_id), reset_undo=True) + + def apply(self): + self._store(fit_scale(self.fabric_id, self.sp_width.value())) + + def reset(self): + self._store(None) + + def _store(self, value: float | None): + set_pull_scale(self.fabric_id, value) + s = QSettings("OpenStitch", "OpenStitchStudio") + if value is None: + s.remove(f"calibration/{self.fabric_id}") + else: + s.setValue(f"calibration/{self.fabric_id}", value) + self.win.rebuild_plan() + self._show_state() + + +class DesignCheckDialog(QDialog): + """Nicht modal: Über „Zeigen“ soll man die Stelle auf der Leinwand ansehen können.""" + + def __init__(self, win): + super().__init__(win) + self.win = win + self._worker: _CheckWorker | None = None + self._report: Report | None = None + self._plan: StitchPlan | None = None + self.setWindowTitle(tr("chk_title")) + self.resize(900, 620) + self.setModal(False) + + root = QVBoxLayout(self) + root.setContentsMargins(18, 16, 18, 14) + root.setSpacing(12) + + head = QHBoxLayout() + head.setSpacing(16) + self.ring = ScoreRing() + head.addWidget(self.ring) + col = QVBoxLayout() + col.setSpacing(2) + self.lbl_verdict = QLabel(tr("chk_running")) + self.lbl_verdict.setProperty("role", "title") + self.lbl_facts = QLabel() + self.lbl_facts.setProperty("role", "subtitle") + self.lbl_facts.setWordWrap(True) + col.addStretch(1) + col.addWidget(self.lbl_verdict) + col.addWidget(self.lbl_facts) + col.addStretch(1) + head.addLayout(col, 1) + self.btn_again = QPushButton(tr("chk_again")) + self.btn_again.clicked.connect(self.start) + head.addWidget(self.btn_again, 0, Qt.AlignTop) + root.addLayout(head) + + body = QHBoxLayout() + body.setSpacing(14) + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + self.list_host = QWidget() + self.list_lay = QVBoxLayout(self.list_host) + self.list_lay.setContentsMargins(0, 0, 6, 0) + self.list_lay.setSpacing(8) + self.list_lay.addStretch(1) + scroll.setWidget(self.list_host) + body.addWidget(scroll, 5) + + right = QVBoxLayout() + right.setSpacing(6) + cap = QLabel(tr("chk_preview")) + cap.setProperty("role", "section") + right.addWidget(cap) + self.lbl_preview = QLabel() + self.lbl_preview.setAlignment(Qt.AlignCenter) + self.lbl_preview.setMinimumSize(320, 300) + self.lbl_preview.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + right.addWidget(self.lbl_preview, 1) + row = QHBoxLayout() + lbl = QLabel(tr("chk_boost")) + lbl.setProperty("role", "caption") + self.lbl_boost = QLabel("×1") + self.lbl_boost.setProperty("role", "caption") + self.slider = QSlider(Qt.Horizontal) + self.slider.setRange(1, 6) + self.slider.setValue(3) + self.slider.valueChanged.connect(self._update_preview) + row.addWidget(lbl) + row.addWidget(self.slider, 1) + row.addWidget(self.lbl_boost) + right.addLayout(row) + body.addLayout(right, 4) + root.addLayout(body, 1) + + foot = QHBoxLayout() + self.lbl_foot = QLabel(tr("chk_disclaimer")) + self.lbl_foot.setProperty("role", "caption") + self.lbl_foot.setWordWrap(True) + foot.addWidget(self.lbl_foot, 1) + btn_cal = QPushButton(tr("cal_open")) + btn_cal.setObjectName("linkBtn") + btn_cal.setCursor(Qt.PointingHandCursor) + btn_cal.clicked.connect(self._calibrate) + foot.addWidget(btn_cal, 0, Qt.AlignRight) + root.addLayout(foot) + + # ---------------------------------------------------------------- Ablauf + def showEvent(self, ev): + super().showEvent(ev) + self.start() + + def start(self): + if self._worker is not None and self._worker.isRunning(): + return + win = self.win + win.wait_for_plan() + d = win.canvas.design + # Eigene Kopie: Das Fenster bleibt bedienbar, während im Hintergrund geprüft wird + design = copy.copy(d) + design.objects = [o.snapshot() for o in d.objects] + design._cache = {} + self._plan = win.canvas.plan + mp = win.cmb_machine.currentData() + self.btn_again.setEnabled(False) + self.ring.set_score(None) + self.lbl_verdict.setText(tr("chk_running")) + self.lbl_facts.clear() + self._clear_list() + self._worker = _CheckWorker(design, self._plan, d.settings.needles, mp.native_ext if mp else "dst", self) + self._worker.done.connect(self._on_done) + self._worker.failed.connect(self._on_failed) + self._worker.start() + + def closeEvent(self, ev): + if self._worker is not None: + self._worker.wait(15000) + super().closeEvent(ev) + + def _on_failed(self, msg: str): + self.btn_again.setEnabled(True) + self.lbl_verdict.setText(tr("chk_failed")) + self.lbl_facts.setText(msg) + + def _on_done(self, report: Report, export: RoundTrip | None): + self._report = report + self.btn_again.setEnabled(True) + plan = self._plan + if plan.stitch_count == 0: + self.lbl_verdict.setText(tr("chk_empty")) + return + self.ring.set_score(report.score) + key = "chk_good" if report.score >= 85 and report.ok else "chk_ok" if report.score >= 60 and report.ok else "chk_bad" + self.lbl_verdict.setText(tr(key)) + self.lbl_facts.setText(tr("chk_facts").format( + st=fmt_int(plan.stitch_count), colors=len(plan.blocks), trims=plan.trim_count, + min=fmt_float(plan.estimated_minutes(self.win.canvas.design.settings.machine_spm), 0), + thread=fmt_float(plan.thread_length_m(), 0))) + for f in report.findings: + self._add_row(f) + if export is not None: + self._add_export_row(export) + if not report.findings: + none = QLabel(tr("chk_none")) + none.setProperty("severity", "ok") + self.list_lay.insertWidget(self.list_lay.count() - 1, none) + self._update_preview() + + # ---------------------------------------------------------------- Befunde + def _clear_list(self): + while self.list_lay.count() > 1: + w = self.list_lay.takeAt(0).widget() + if w is not None: + w.deleteLater() + + def _card(self, severity: str, title: str, text: str) -> tuple[QFrame, QHBoxLayout]: + card = QFrame() + card.setObjectName("card") + v = QVBoxLayout(card) + v.setContentsMargins(12, 9, 12, 9) + v.setSpacing(3) + t = QLabel(title) + t.setProperty("severity", severity) + t.setWordWrap(True) + d = QLabel(text) + d.setProperty("role", "cardText") + d.setWordWrap(True) + v.addWidget(t) + v.addWidget(d) + row = QHBoxLayout() + row.setSpacing(6) + row.addStretch(1) + v.addLayout(row) + self.list_lay.insertWidget(self.list_lay.count() - 1, card) + return card, row + + def _add_row(self, f): + data = dict(f.data) + data.setdefault("count", f.count) + fmt = {k: (fmt_float(v, 1) if isinstance(v, float) else v) for k, v in data.items()} + fmt["count"] = fmt_int(f.count) + tag = "chk_tag_model" if f.is_estimate else "chk_tag_rule" + title = f"{tr(f'chk_{f.code}_t')} · {tr(tag)}" + _card, row = self._card(f.severity, title, tr(f"chk_{f.code}_d").format(**fmt)) + if f.where: + b = QPushButton(tr("chk_show")) + b.clicked.connect(lambda _=False, pts=f.where: self.win.canvas.show_spots(pts)) + row.addWidget(b) + fix = self.win.fix_for(f.code) + if fix is not None: + b = QPushButton(tr("chk_fix")) + b.setObjectName("primaryBtn") + b.clicked.connect(lambda _=False, fn=fix: self._apply_fix(fn)) + row.addWidget(b) + + def _add_export_row(self, r: RoundTrip): + ext = r.ext.upper() + if r.ok: + self._card("ok", tr("chk_export_ok_t").format(ext=ext), + tr("chk_export_ok_d").format(st=fmt_int(r.stitches), err=fmt_float(r.max_error_mm, 2))) + else: + self._card("error", tr("chk_export_bad_t").format(ext=ext), "; ".join(r.problems)) + + def _apply_fix(self, fn): + fn() + self.start() + + def _calibrate(self): + CalibrationDialog(self.win, self).exec() + self.start() + + # --------------------------------------------------------------- Vorschau + def _update_preview(self): + factor = self.slider.value() + self.lbl_boost.setText(f"×{factor}") + if self._report is None or self._plan is None or self._plan.stitch_count == 0: + return + bg = CANVAS_COLOR.get(self.win.canvas.fabric_theme, CANVAS_COLOR["slate"]) + plan = distorted_plan(self._plan, self._report, float(factor)) + x0, y0, x1, y1 = plan.bounds() + size = max(x1 - x0, y1 - y0, 10.0) + img: QImage = render_image(plan, px_per_mm=min(620.0 / size, 12.0), margin_mm=3.0, background=bg) + pix = QPixmap.fromImage(img) + self.lbl_preview.setPixmap(pix.scaled(self.lbl_preview.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) diff --git a/openstitch/ui/crash.py b/openstitch/ui/crash.py new file mode 100644 index 0000000..d80551e --- /dev/null +++ b/openstitch/ui/crash.py @@ -0,0 +1,51 @@ +"""Unerwartete Fehler: Arbeit sichern, Bericht ablegen, verständlich melden. + +Im gepackten Programm gibt es keine Konsole. Ohne das hier würde ein Fehler spurlos verschwinden.""" +from __future__ import annotations + +import datetime as _dt +import os +import platform +import sys +import traceback + +from PySide6.QtCore import QStandardPaths +from PySide6.QtWidgets import QMessageBox + +from .. import __version__ +from ..i18n import tr + + +def log_path() -> str: + folder = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation) + os.makedirs(folder, exist_ok=True) + return os.path.join(folder, "crash.log") + + +def write_report(tp, val, tb) -> str: + path = log_path() + with open(path, "a", encoding="utf-8") as f: + f.write(f"\n=== {_dt.datetime.now().isoformat(timespec='seconds')} OpenStitch {__version__} " + f"on {platform.platform()}, Python {platform.python_version()}\n") + f.write("".join(traceback.format_exception(tp, val, tb))) + return path + + +def install(win) -> None: + busy = [False] + + def hook(tp, val, tb): + sys.__excepthook__(tp, val, tb) + if busy[0] or issubclass(tp, KeyboardInterrupt): + return + busy[0] = True + try: + win._autosave() + path = write_report(tp, val, tb) + QMessageBox.critical(win, tr("crash_title"), tr("crash_text").format(path)) + except Exception: # noqa: BLE001 - der Fehlerbericht selbst darf nie nachtreten + pass + finally: + busy[0] = False + + sys.excepthook = hook diff --git a/openstitch/ui/dialogs.py b/openstitch/ui/dialogs.py index d8d4654..b0867b8 100644 --- a/openstitch/ui/dialogs.py +++ b/openstitch/ui/dialogs.py @@ -6,7 +6,7 @@ import numpy as np from PySide6.QtCore import Qt, QThread, Signal -from PySide6.QtGui import QColor, QImage, QPixmap +from PySide6.QtGui import QColor, QImage, QPainter, QPainterPath, QPixmap from PySide6.QtWidgets import ( QCheckBox, QComboBox, @@ -25,16 +25,22 @@ QPushButton, QSpinBox, QVBoxLayout, + QWidget, ) from ..auto.digitize import AutoParams, AutoResult, auto_digitize, load_image from ..auto.photostitch import PhotoStitchParams, generate_photostitch from ..core.design import Design from ..core.stitchplan import StitchPlan, Thread +from ..engine.geom import polygons_of +from ..fonts_micro import MICRO_SPEC from ..io.exp import exp_bytes from ..io.fat12 import Fat12Image, dos_name from ..i18n import fmt_float, fmt_int, key_for, tr from ..text import TextObject, default_font, list_fonts +from . import theme + +MICRO_ADVICE_MM = 5.5 # darunter laufen Umriss-Schriften zu def _np_to_pixmap(rgb: np.ndarray, max_side: int = 360) -> QPixmap: @@ -144,7 +150,7 @@ def __init__(self, image_path: str, parent=None): top.addLayout(v1, 1) # Einstellungen rechts - grp = QGroupBox(tr("grp_auto_settings")) + grp = QGroupBox(tr("grp_auto_settings").replace("&", "&&")) form = QFormLayout(grp) self.sp_width = QDoubleSpinBox() @@ -162,11 +168,6 @@ def __init__(self, image_path: str, parent=None): self.cb_bg.setChecked(True) form.addRow("", self.cb_bg) - self.cmb_fabric = QComboBox() - for fab in ("normal", "strick", "frottee", "cap", "leicht"): - self.cmb_fabric.addItem(tr(f"fabric_opt_{fab}"), fab) - form.addRow(tr("lbl_fabric_type"), self.cmb_fabric) - self.sp_density = QDoubleSpinBox() self.sp_density.setRange(0.28, 1.0) self.sp_density.setSingleStep(0.02) @@ -238,7 +239,6 @@ def _run(self): width_mm=self.sp_width.value(), colors=self.sp_colors.value(), remove_background=self.cb_bg.isChecked(), - fabric=self.cmb_fabric.currentData(), density=self.sp_density.value(), satin_max_mm=self.sp_satin.value(), min_area_mm2=self.sp_min_area.value(), @@ -286,6 +286,44 @@ def reject(self): # =========================================================================== # 2. Schrift & Monogramme # =========================================================================== +class _TextPreview(QWidget): + """Sofort-Vorschau der Schrift (Umrisse statt Stiche: reagiert beim Tippen ohne Verzögerung).""" + + def __init__(self, parent=None): + super().__init__(parent) + self.setMinimumHeight(92) + self.obj: TextObject | None = None + + def set_object(self, obj: TextObject | None): + self.obj = obj + self.update() + + def paintEvent(self, _ev): + p = QPainter(self) + p.setRenderHint(QPainter.Antialiasing, True) + p.fillRect(self.rect(), theme.color("surface")) + geom = self.obj.world_geom() if self.obj is not None else None + if geom is None or geom.is_empty: + return + x0, y0, x1, y1 = geom.bounds + w, h = max(x1 - x0, 0.1), max(y1 - y0, 0.1) + k = min((self.width() - 24) / w, (self.height() - 18) / h) + p.translate(self.width() / 2 - (x0 + w / 2) * k, self.height() / 2 - (y0 + h / 2) * k) + p.scale(k, k) + p.setPen(Qt.NoPen) + p.setBrush(QColor(*self.obj.thread.color) if sum(self.obj.thread.color) > 150 else theme.color("text")) + path = QPainterPath() + path.setFillRule(Qt.OddEvenFill) + for poly in polygons_of(geom): + for ring in [poly.exterior, *poly.interiors]: + pts = list(ring.coords) + path.moveTo(*pts[0][:2]) + for q in pts[1:]: + path.lineTo(*q[:2]) + path.closeSubpath() + p.drawPath(path) + + class TextDialog(QDialog): def __init__(self, thread: Thread, existing: TextObject | None = None, parent=None): super().__init__(parent) @@ -297,8 +335,20 @@ def __init__(self, thread: Thread, existing: TextObject | None = None, parent=No root = QVBoxLayout(self) form = QFormLayout() + self._existing = existing + + self.preview = _TextPreview() + root.addWidget(self.preview) + self.lbl_font_tip = QPushButton() + self.lbl_font_tip.setObjectName("linkBtn") + self.lbl_font_tip.setCursor(Qt.PointingHandCursor) + self.lbl_font_tip.clicked.connect(self._use_micro) + root.addWidget(self.lbl_font_tip) self.ed_text = QLineEdit(existing.text if existing else "OPENSTITCH") + self.ed_text.setPlaceholderText(tr("ph_text")) + self.ed_text.selectAll() + self.ed_text.textChanged.connect(self._update_preview) form.addRow(tr("lbl_text"), self.ed_text) self.cmb_font = QComboBox() @@ -310,12 +360,14 @@ def __init__(self, thread: Thread, existing: TextObject | None = None, parent=No if spec == cur_font: cur_idx = idx self.cmb_font.setCurrentIndex(cur_idx) + self.cmb_font.currentIndexChanged.connect(self._update_preview) form.addRow(tr("lbl_font_file"), self.cmb_font) self.sp_height = QDoubleSpinBox() - self.sp_height.setRange(4.0, 150.0) + self.sp_height.setRange(2.0, 150.0) self.sp_height.setValue(existing.height if existing else 16.0) self.sp_height.setSuffix(" mm") + self.sp_height.valueChanged.connect(self._update_preview) form.addRow(tr("lbl_letter_height"), self.sp_height) self.sp_spacing = QDoubleSpinBox() @@ -323,6 +375,7 @@ def __init__(self, thread: Thread, existing: TextObject | None = None, parent=No self.sp_spacing.setSingleStep(0.2) self.sp_spacing.setValue(existing.letter_spacing if existing else 0.6) self.sp_spacing.setSuffix(" mm") + self.sp_spacing.valueChanged.connect(self._update_preview) form.addRow(tr("lbl_letter_spacing"), self.sp_spacing) self.sp_arc = QDoubleSpinBox() @@ -330,6 +383,7 @@ def __init__(self, thread: Thread, existing: TextObject | None = None, parent=No self.sp_arc.setSingleStep(5.0) self.sp_arc.setValue(existing.arc_radius if existing else 0.0) self.sp_arc.setSuffix(tr("sfx_arc")) + self.sp_arc.valueChanged.connect(self._update_preview) form.addRow(tr("lbl_arc_radius"), self.sp_arc) self.cmb_mode = QComboBox() @@ -356,6 +410,26 @@ def __init__(self, thread: Thread, existing: TextObject | None = None, parent=No btns.accepted.connect(self._apply) btns.rejected.connect(self.reject) root.addWidget(btns) + self._update_preview() + + def _update_preview(self): + txt = self.ed_text.text().strip() + font = self.cmb_font.currentData() + micro = font == MICRO_SPEC + small = self.sp_height.value() < MICRO_ADVICE_MM + self.lbl_font_tip.setVisible(small and not micro) + self.lbl_font_tip.setText(tr("tip_use_micro")) + try: + obj = TextObject(self.thread, text=txt, font=font, height=self.sp_height.value(), + letter_spacing=self.sp_spacing.value(), arc_radius=self.sp_arc.value()) if txt else None + except Exception: # noqa: BLE001 - defekte Schriftdatei: Vorschau bleibt leer, Dialog nutzbar + obj = None + self.preview.set_object(obj) + + def _use_micro(self): + idx = self.cmb_font.findData(MICRO_SPEC) + if idx >= 0: + self.cmb_font.setCurrentIndex(idx) def _apply(self): txt = self.ed_text.text().strip() @@ -391,7 +465,7 @@ def __init__(self, plan: StitchPlan, design_name: str, parent=None): root = QVBoxLayout(self) # Abschnitt 1: Dateiname & Trim-Modus - g1 = QGroupBox(tr("grp_transfer_1")) + g1 = QGroupBox(tr("grp_transfer_1").replace("&", "&&")) f1 = QFormLayout(g1) self.ed_name = QLineEdit(dos_name(design_name, "EXP")) f1.addRow(tr("lbl_dos_name"), self.ed_name) @@ -403,7 +477,7 @@ def __init__(self, plan: StitchPlan, design_name: str, parent=None): root.addWidget(g1) # Abschnitt 2: Direkt auf USB-Stick / Diskettenlaufwerk oder per WLAN-NetBridge senden - g2 = QGroupBox(tr("grp_transfer_2")) + g2 = QGroupBox(tr("grp_transfer_2").replace("&", "&&")) v2 = QVBoxLayout(g2) btn_folder = QPushButton(tr("btn_save_exp_usb")) btn_folder.clicked.connect(self._save_direct_exp) @@ -420,7 +494,7 @@ def __init__(self, plan: StitchPlan, design_name: str, parent=None): root.addWidget(g2) # Abschnitt 3: 1.44 MB FAT12 Diskettenabbild (.IMG) für GoTek / FlashFloppy / HxC - g3 = QGroupBox(tr("grp_transfer_3")) + g3 = QGroupBox(tr("grp_transfer_3").replace("&", "&&")) v3 = QVBoxLayout(g3) self.lbl_img = QLabel(tr("lbl_img_initial")) v3.addWidget(self.lbl_img) @@ -569,7 +643,7 @@ def __init__(self, image_path: str, parent=None): v1.addWidget(btn_change_img) top.addLayout(v1, 1) - grp = QGroupBox(tr("grp_photo_settings")) + grp = QGroupBox(tr("grp_photo_settings").replace("&", "&&")) form = QFormLayout(grp) self.sp_width = QDoubleSpinBox() diff --git a/openstitch/ui/export_dialog.py b/openstitch/ui/export_dialog.py new file mode 100644 index 0000000..ad67146 --- /dev/null +++ b/openstitch/ui/export_dialog.py @@ -0,0 +1,223 @@ +"""„An die Maschine senden“: passendes Format, USB-Stick, Prüfung der geschriebenen Datei.""" +from __future__ import annotations + +import os +import re + +from PySide6.QtCore import Qt +from PySide6.QtGui import QPixmap +from PySide6.QtWidgets import ( + QCheckBox, + QComboBox, + QDialog, + QFileDialog, + QFormLayout, + QHBoxLayout, + QLabel, + QLineEdit, + QListWidget, + QListWidgetItem, + QMessageBox, + QPushButton, + QVBoxLayout, +) + +from ..core.machines import MachineProfile +from ..i18n import fmt_float, fmt_int, tr +from ..io.drives import removable_drives +from ..io.formats import FORMAT_NAMES, WRITE_EXT, export_plan, verify_exported_file +from ..render import render_image + +MACHINE_EXT = ("exp", "dst", "pes", "jef", "vp3", "xxx", "u01", "pec", "tbf") + + +def short_name(name: str, limit: int = 8) -> str: + """Name für ältere Maschinen: nur A–Z, 0–9, höchstens 8 Zeichen.""" + clean = re.sub(r"[^A-Za-z0-9]+", "", name).upper() + return (clean or "DESIGN")[:limit] + + +def safe_name(name: str) -> str: + """Zeichen entfernen, die Dateisysteme oder Maschinen nicht mögen.""" + clean = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", name).strip(" .") + return clean or "design" + + +class ExportDialog(QDialog): + def __init__(self, win): + super().__init__(win) + self.win = win + self.setWindowTitle(tr("exp_title")) + self.resize(640, 560) + self.saved_path: str | None = None + design, plan = win.canvas.design, win.canvas.plan + mp: MachineProfile | None = win.cmb_machine.currentData() + + root = QVBoxLayout(self) + root.setContentsMargins(18, 16, 18, 14) + root.setSpacing(12) + + head = QHBoxLayout() + head.setSpacing(14) + thumb = QLabel() + thumb.setFixedSize(96, 96) + thumb.setAlignment(Qt.AlignCenter) + if plan.stitch_count: + size = max(plan.bounds()[2] - plan.bounds()[0], plan.bounds()[3] - plan.bounds()[1], 10.0) + img = render_image(plan, px_per_mm=min(190.0 / size, 8.0), margin_mm=2.0, background=None) + thumb.setPixmap(QPixmap.fromImage(img).scaled(92, 92, Qt.KeepAspectRatio, Qt.SmoothTransformation)) + head.addWidget(thumb) + col = QVBoxLayout() + col.setSpacing(2) + title = QLabel(tr("exp_heading")) + title.setProperty("role", "title") + facts = QLabel(tr("exp_facts").format( + st=fmt_int(plan.stitch_count), colors=len(plan.blocks), + w=fmt_float(plan.bounds()[2] - plan.bounds()[0], 0), h=fmt_float(plan.bounds()[3] - plan.bounds()[1], 0))) + facts.setProperty("role", "subtitle") + facts.setWordWrap(True) + col.addStretch(1) + col.addWidget(title) + col.addWidget(facts) + col.addStretch(1) + head.addLayout(col, 1) + root.addLayout(head) + + form = QFormLayout() + form.setVerticalSpacing(9) + form.setHorizontalSpacing(12) + + self.cmb_format = QComboBox() + native = mp.native_ext if mp else "dst" + for ext in [native] + [e for e in WRITE_EXT if e != native]: + label = FORMAT_NAMES.get(ext, ext.upper()) + if ext == native: + label = tr("exp_recommended").format(label) + self.cmb_format.addItem(label, ext) + self.cmb_format.currentIndexChanged.connect(self._update_path) + form.addRow(tr("exp_format"), self.cmb_format) + + self.ed_name = QLineEdit(safe_name(design.name)) + self.ed_name.textChanged.connect(self._update_path) + form.addRow(tr("exp_name"), self.ed_name) + + self.cb_short = QCheckBox(tr("exp_short")) + self.cb_short.setToolTip(tr("exp_short_tip")) + self.cb_short.setChecked(bool(mp and mp.floppy_144mb)) + self.cb_short.toggled.connect(self._update_path) + form.addRow("", self.cb_short) + + where = QHBoxLayout() + self.cmb_where = QComboBox() + self._fill_targets() + self.cmb_where.currentIndexChanged.connect(self._update_path) + btn_other = QPushButton(tr("exp_browse")) + btn_other.clicked.connect(self._pick_folder) + btn_refresh = QPushButton(tr("exp_refresh")) + btn_refresh.clicked.connect(self._refresh_targets) + where.addWidget(self.cmb_where, 1) + where.addWidget(btn_refresh) + where.addWidget(btn_other) + form.addRow(tr("exp_where"), where) + root.addLayout(form) + + self.lbl_path = QLabel() + self.lbl_path.setProperty("role", "caption") + self.lbl_path.setWordWrap(True) + root.addWidget(self.lbl_path) + + cap = QLabel(tr("exp_threads")) + cap.setProperty("role", "section") + root.addWidget(cap) + self.list_threads = QListWidget() + for i, b in enumerate(plan.blocks, 1): + icon = win.thread_icon(b.thread.color) + self.list_threads.addItem(QListWidgetItem(icon, f"{i}. {b.thread.name or b.thread.hex} {b.thread.code}".rstrip())) + root.addWidget(self.list_threads, 1) + + self.lbl_result = QLabel() + self.lbl_result.setWordWrap(True) + root.addWidget(self.lbl_result) + + row = QHBoxLayout() + row.addStretch(1) + self.btn_close = QPushButton(tr("btn_close")) + self.btn_close.clicked.connect(self.reject) + self.btn_save = QPushButton(tr("exp_save")) + self.btn_save.setObjectName("primaryBtn") + self.btn_save.setDefault(True) + self.btn_save.clicked.connect(self.save) + self.btn_save.setEnabled(plan.stitch_count > 0) + row.addWidget(self.btn_close) + row.addWidget(self.btn_save) + root.addLayout(row) + self._update_path() + + # ---------------------------------------------------------------- Zielort + def _fill_targets(self): + self.cmb_where.blockSignals(True) + self.cmb_where.clear() + for path, label in removable_drives(): + self.cmb_where.addItem(tr("exp_usb").format(label), path) + docs = self.win._default_open_dir() + self.cmb_where.addItem(docs, docs) + self.cmb_where.blockSignals(False) + + def _refresh_targets(self): + self._fill_targets() + self._update_path() + + def _pick_folder(self): + folder = QFileDialog.getExistingDirectory(self, tr("exp_where"), self.cmb_where.currentData() or "") + if folder: + self.cmb_where.insertItem(0, folder, folder) + self.cmb_where.setCurrentIndex(0) + + def target_path(self) -> str: + ext = self.cmb_format.currentData() + name = safe_name(self.ed_name.text()) + if self.cb_short.isChecked(): + name, ext = short_name(name), ext.upper() + return os.path.join(self.cmb_where.currentData() or ".", f"{name}.{ext}") + + def _update_path(self): + self.lbl_path.setText(self.target_path()) + + # -------------------------------------------------------------- Speichern + def _may_replace(self, path: str) -> bool: + """Kurze Namen kollidieren leicht: Eine vorhandene Datei wird nie stillschweigend ersetzt.""" + if not os.path.exists(path): + return True + ans = QMessageBox.question(self, tr("exp_title"), tr("exp_overwrite").format(os.path.basename(path)), + QMessageBox.Yes | QMessageBox.No, QMessageBox.No) + return ans == QMessageBox.Yes + + def save(self): + path = self.target_path() + if not self._may_replace(path): + return + plan = self.win.canvas.plan + self.lbl_result.setProperty("severity", "ok") + # Erst neben dem Ziel schreiben und prüfen: Ein Fehler lässt die alte Datei unberührt + stem, ext = os.path.splitext(path) + tmp = f"{stem}.partial{ext}" + try: + export_plan(plan, tmp) + if self.cmb_format.currentData() in MACHINE_EXT: + rep = verify_exported_file(tmp, plan) + msg = tr("exp_done").format(st=fmt_int(rep["stitches"]), name=os.path.basename(path)) + else: + msg = tr("exp_done_plain").format(name=os.path.basename(path)) + os.replace(tmp, path) + self.saved_path = path + self.btn_close.setDefault(True) + self.lbl_result.setText(msg) + except Exception as exc: # noqa: BLE001 - Schreibschutz, voller Stick, ungültiger Pfad … + self.lbl_result.setProperty("severity", "error") + self.lbl_result.setText(tr("exp_failed").format(exc)) + try: + os.remove(tmp) + except OSError: + pass + self.lbl_result.style().unpolish(self.lbl_result) + self.lbl_result.style().polish(self.lbl_result) diff --git a/openstitch/ui/main_window.py b/openstitch/ui/main_window.py index de46c5c..31ab7d4 100644 --- a/openstitch/ui/main_window.py +++ b/openstitch/ui/main_window.py @@ -6,7 +6,10 @@ from pathlib import Path from PySide6.QtCore import QSettings, QSize, QStandardPaths, Qt, QTimer, QUrl -from PySide6.QtGui import QAction, QColor, QDragEnterEvent, QDropEvent, QFont, QIcon, QKeySequence, QPainter, QPen, QPixmap +from PySide6.QtGui import ( + QAction, QActionGroup, QColor, QDesktopServices, QDragEnterEvent, QDropEvent, QIcon, QKeySequence, QPainter, + QPen, QPixmap, +) from PySide6.QtWidgets import ( QCheckBox, QColorDialog, @@ -25,186 +28,48 @@ QMainWindow, QMessageBox, QPushButton, + QScrollArea, + QSizePolicy, QSlider, QSpinBox, QSplitter, + QStackedWidget, QStatusBar, QToolBar, QToolButton, QVBoxLayout, QWidget, ) -from shapely.geometry import LineString, Point from .. import APP_NAME, __version__ from ..auto.palette import CATALOG_PALETTES, active_palette, nearest_thread, set_active_palette from ..i18n import ( LANGUAGES, current_lang, fmt_int, init_lang, key_for, machine_display_name, set_lang, tr, tr_opt, ) -from ..core.design import HOOPS, Design, EmbObject, FillObject, Hoop, RunObject, SatinObject, color_sorted +from ..core.design import HOOPS, Design, EmbObject, Hoop, SatinObject, color_sorted +from ..core.fabric import FABRICS, fabric_by_id, set_pull_scale from ..core.machines import MACHINE_PROFILES, MachineProfile from ..core.stitchplan import Thread -from ..engine.pro_tools import create_applique_objects, import_svg, run_quality_doctor -from ..io.formats import FORMAT_NAMES, READ_EXT, WRITE_EXT, export_plan, import_file, verify_exported_file +from ..engine.pro_tools import create_applique_objects, import_svg +from ..io.formats import READ_EXT, import_file from ..io.project import export_worksheet_pdf, load_project, save_project from ..render import render_image from ..text import TextObject from .canvas import StitchCanvas +from .check_dialog import DesignCheckDialog +from .export_dialog import ExportDialog from .dialogs import AutoDigitizeDialog, MelcoDiskDialog, PhotoStitchDialog, TextDialog -from .onboarding import InAppTourOverlay, OnboardingTourDialog, create_openstitch_logo_design, studio_icon +from .onboarding import InAppTourOverlay, create_openstitch_logo_design, studio_icon from .plan_worker import PlanBuilder +from .start_page import StartPage +from . import theme +from ..samples import SAMPLES -STUDIO_STYLE = """ -QMainWindow, QDialog, QDockWidget, QWidget { - background-color: #1f232b; - color: #dfe3ec; - font-family: "Segoe UI", "SF Pro Text", sans-serif; - font-size: 9.5pt; -} -QLabel, QCheckBox { - background: transparent; -} -QMenuBar { - background-color: #1a1d24; - color: #c9d0de; - border-bottom: 1px solid #2d3340; - padding: 3px 6px; -} -QMenuBar::item:selected { - background-color: #2c3342; - border-radius: 4px; -} -QMenu { - background-color: #242934; - border: 1px solid #363e4f; - padding: 4px; -} -QMenu::item:selected { - background-color: #3f6ec7; - border-radius: 4px; -} -QToolBar { - background-color: #232832; - border-bottom: 1px solid #303644; - border-right: 1px solid #303644; - spacing: 5px; - padding: 5px 8px; -} -QToolButton { - background-color: #2b313d; - border: 1px solid #394152; - border-radius: 6px; - padding: 4px 8px; - color: #e1e5ef; - font-weight: 500; -} -QToolButton:hover, QPushButton:hover { - background-color: #343c4b; - border-color: #6b99f0; -} -QToolButton:checked, QPushButton:checked { - background-color: rgba(138, 180, 248, 0.24); - border-color: #7cacf8; - color: #e8f0fe; -} -QPushButton { - background-color: #2b313d; - border: 1px solid #3a4253; - border-radius: 6px; - padding: 5px 10px; - color: #e1e5ef; -} -QPushButton#primaryBtn { - background-color: #4678d8; - border: 1px solid #6b99f0; - color: #f8f9fc; - font-weight: 600; -} -QPushButton#primaryBtn:hover { - background-color: #5486e6; -} -QDockWidget { - titlebar-close-icon: none; - titlebar-normal-icon: none; - font-weight: 600; - color: #9ba4b8; -} -QDockWidget::title { - background-color: #232832; - border-top: 1px solid #303644; - border-bottom: 1px solid #303644; - padding: 6px 10px; - text-transform: uppercase; - font-size: 8.5pt; - letter-spacing: 0.6px; -} -QFrame#card { - background-color: #262b35; - border: 1px solid #343b49; - border-radius: 8px; - padding: 6px; -} -QListWidget, QLineEdit, QComboBox, QSpinBox, QDoubleSpinBox { - background-color: #1a1e25; - border: 1px solid #323947; - border-radius: 6px; - padding: 4px 7px; - color: #e1e5ef; -} -QListWidget::item { - padding: 5px 6px; - border-radius: 5px; - margin: 1px 2px; -} -QListWidget::item:selected { - background-color: rgba(138, 180, 248, 0.25); - border: 1px solid rgba(138, 180, 248, 0.45); - color: #f0f4fc; -} -QListWidget::item:hover:!selected { - background-color: #282e3b; -} -QScrollBar:vertical { - background: #1c2028; - width: 8px; - margin: 0px; - border-radius: 4px; -} -QScrollBar::handle:vertical { - background: #384050; - min-height: 24px; - border-radius: 4px; -} -QScrollBar::handle:vertical:hover { - background: #4e586e; -} -QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { - height: 0px; -} -QSlider::groove:horizontal { - height: 6px; - background: #2c3240; - border-radius: 3px; -} -QSlider::sub-page:horizontal { - background: #5b8def; - border-radius: 3px; -} -QSlider::handle:horizontal { - background: #eef2fa; - border: 2px solid #5b8def; - width: 14px; - margin: -5px 0; - border-radius: 7px; -} -QStatusBar { - background-color: #191c23; - color: #9ba5b9; - border-top: 1px solid #2d3340; - font-size: 9pt; -} -""" - +IMAGE_EXT = ("png", "jpg", "jpeg", "bmp", "webp", "tif", "tiff", "gif") +REPO_URL = "https://github.com/lb2002/openstitch" +ISSUES_URL = f"{REPO_URL}/issues/new" +AUTOSAVE_MS = 90_000 +MAX_RECENT = 8 def _color_icon(rgb: tuple[int, int, int], size: int = 16) -> QIcon: pix = QPixmap(size, size) @@ -224,11 +89,18 @@ def __init__(self, defer_starter: bool = False, show_tour_on_init: bool = True): init_lang() self._tr_bindings: list[tuple] = [] self._bind(self.setWindowTitle, "app_tagline", fmt=lambda s: f"{APP_NAME} Studio {__version__} — {s}") - self.resize(1540, 920) - self.setStyleSheet(STUDIO_STYLE) + theme.init_theme() + theme.apply_to_app() + settings = QSettings("OpenStitch", "OpenStitchStudio") + for fab in FABRICS: # gemessene Stoffwerte aus früheren Sitzungen + measured = settings.value(f"calibration/{fab.id}", None) + set_pull_scale(fab.id, None if measured is None else float(measured)) + self._icon_refs: list[tuple] = [] + self.resize(1440, 900) self.setAcceptDrops(True) self._show_tour_on_init = show_tour_on_init self._tour_overlay: InAppTourOverlay | None = None + self._check_dlg: DesignCheckDialog | None = None self.canvas = StitchCanvas(self) self._planner = PlanBuilder(self) @@ -240,78 +112,81 @@ def __init__(self, defer_starter: bool = False, show_tour_on_init: bool = True): c_lay.setContentsMargins(0, 0, 0, 0) c_lay.setSpacing(0) - # Google-Studio Kontextleiste direkt über der Leinwand (Maschine, Rahmen, Auto-Fit, Stoff & Strategie) + # Kontextleiste: Worauf wird gestickt? (Maschine, Rahmen, Stoff) ctx_bar = QFrame(central) + ctx_bar.setObjectName("ctxBar") self.ctx_bar = ctx_bar - ctx_bar.setStyleSheet( - "QFrame { background-color: #1c2028; border-bottom: 1px solid #2e3442; }" - ) ctx_hb = QHBoxLayout(ctx_bar) - ctx_hb.setContentsMargins(12, 5, 12, 5) - ctx_hb.setSpacing(8) - - lbl_m = QLabel("Maschine:") - lbl_m.setStyleSheet("color: #8ab4f8; font-weight: 600;") - self._bind(lbl_m.setText, "lbl_machine") - ctx_hb.addWidget(lbl_m) - self.cmb_machine = QComboBox() - self.cmb_machine.setMinimumWidth(225) + ctx_hb.setContentsMargins(12, 6, 12, 7) + ctx_hb.setSpacing(10) + + def compact_combo() -> QComboBox: + # Lange Einträge dürfen die Fensterbreite nicht bestimmen; die Liste klappt breiter auf + c = QComboBox() + c.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon) + c.setMinimumContentsLength(9) + c.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) + c.view().setMinimumWidth(330) + return c + + def field(key: str, widget: QWidget, stretch: int = 1): + box = QVBoxLayout() + box.setContentsMargins(0, 0, 0, 0) + box.setSpacing(1) + cap = QLabel() + cap.setProperty("role", "caption") + self._bind(cap.setText, key, fmt=lambda t: t.rstrip(" :\u00a0")) + box.addWidget(cap) + box.addWidget(widget) + ctx_hb.addLayout(box, stretch) + + self.cmb_machine = compact_combo() for mp in MACHINE_PROFILES: self.cmb_machine.addItem(machine_display_name(mp.name), mp) self.cmb_machine.currentIndexChanged.connect(self._on_machine_changed) - ctx_hb.addWidget(self.cmb_machine) - - ctx_hb.addSpacing(4) - lbl_h = QLabel("Stickrahmen:") - lbl_h.setStyleSheet("color: #8ab4f8; font-weight: 600;") - self._bind(lbl_h.setText, "lbl_hoop") - ctx_hb.addWidget(lbl_h) - self.cmb_hoop = QComboBox() - self.cmb_hoop.setMinimumWidth(200) + field("lbl_machine", self.cmb_machine, 3) + + self.cmb_hoop = compact_combo() for h in HOOPS: self.cmb_hoop.addItem(self._hoop_label(h), h) self.cmb_hoop.setCurrentIndex(2) # Rund 15 cm Standard self.cmb_hoop.currentIndexChanged.connect(self._on_hoop_changed) - ctx_hb.addWidget(self.cmb_hoop) + field("lbl_hoop", self.cmb_hoop, 3) + + self.cmb_fabric = compact_combo() + for fab in FABRICS: + self.cmb_fabric.addItem(tr(f"fab_{fab.id}"), fab.id) + self.cmb_fabric.currentIndexChanged.connect(self._on_fabric_changed) + field("lbl_fabric", self.cmb_fabric, 2) btn_fit = QToolButton() - btn_fit.setIcon(studio_icon("fit", 16)) + self._icon(btn_fit.setIcon, "fit", 16) btn_fit.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) - btn_fit.setText("Auto-Fit") self._bind(btn_fit.setText, "btn_autofit") self._bind(btn_fit.setToolTip, "tip_autofit") btn_fit.clicked.connect(self.action_fit_to_hoop) - ctx_hb.addWidget(btn_fit) + ctx_hb.addWidget(btn_fit, 0, Qt.AlignBottom) self.btn_fabric = QToolButton() - self.btn_fabric.setText(tr("fabric_slate")) + self._icon(self.btn_fabric.setIcon, "palette", 16) self._bind(self.btn_fabric.setToolTip, "tip_fabric") self.btn_fabric.clicked.connect(self.cycle_fabric_theme) - ctx_hb.addWidget(self.btn_fabric) - - ctx_hb.addStretch(1) - - lbl_lang = QLabel("Sprache:") - lbl_lang.setStyleSheet("color: #8ab4f8; font-weight: 600;") - self._bind(lbl_lang.setText, "lbl_lang") - ctx_hb.addWidget(lbl_lang) - self.cmb_lang = QComboBox() - for code, label in LANGUAGES: - self.cmb_lang.addItem(label, code) - self.cmb_lang.setCurrentIndex(max(0, next((i for i, (c, _) in enumerate(LANGUAGES) if c == current_lang()), 0))) - self.cmb_lang.currentIndexChanged.connect(self._on_language_changed) - ctx_hb.addWidget(self.cmb_lang) - ctx_hb.addSpacing(6) - self.lbl_hoop_strategy = QLabel() # Text setzt retranslate_ui() - self.lbl_hoop_strategy.setStyleSheet( - "color: #81c995; background-color: rgba(129, 201, 149, 0.12); " - "border: 1px solid rgba(129, 201, 149, 0.28); border-radius: 5px; padding: 3px 8px; font-size: 8.5pt;" - ) - ctx_hb.addWidget(self.lbl_hoop_strategy) + ctx_hb.addWidget(self.btn_fabric, 0, Qt.AlignBottom) c_lay.addWidget(ctx_bar) c_lay.addWidget(self.canvas, 1) - self.setCentralWidget(central) + self.editor_page = central + + self.start_page = StartPage(self._bind, self._icon) + self.start_page.chosen.connect(self._on_start_choice) + self.start_page.sample_chosen.connect(self._open_sample) + self.start_page.recent_chosen.connect(self.open_path) + self.start_page.tour_requested.connect(self._tour_from_start) + self.stack = QStackedWidget(self) + self.stack.addWidget(self.start_page) + self.stack.addWidget(central) + self.stack.setCurrentWidget(central) + self.setCentralWidget(self.stack) self._undo_stack: list[tuple[str, list[EmbObject]]] = [] self._redo_stack: list[tuple[str, list[EmbObject]]] = [] @@ -327,6 +202,11 @@ def __init__(self, defer_starter: bool = False, show_tour_on_init: bool = True): self.sim_timer.setInterval(25) self.sim_timer.timeout.connect(self._sim_step) + self._autosave_timer = QTimer(self) + self._autosave_timer.setInterval(AUTOSAVE_MS) + self._autosave_timer.timeout.connect(self._autosave) + self._autosave_timer.start() + self._build_menus_and_header() self._build_left_tool_rail() self._build_left_palette_dock() @@ -359,10 +239,24 @@ def _apply_binding(setter, key, escape, fmt): setter(txt) def _update_strategy_label(self): - if hasattr(self, "lbl_hoop_strategy"): - self.lbl_hoop_strategy.setText( - f"{tr('lbl_strategy')}{tr('label_colon')} {self.canvas.design.hoop.strategy_description}" - ) + """Die Rahmen-Strategie steht im Tooltip der Rahmenwahl (auf der Leiste wäre sie zu lang).""" + self.cmb_hoop.setToolTip( + f"{tr('lbl_strategy')}{tr('label_colon')} {self.canvas.design.hoop.strategy_description}" + ) + + def _icon(self, setter, kind: str, size: int = 16): + """Setzt ein Symbol und merkt es sich: beim Themenwechsel wird es neu gezeichnet.""" + self._icon_refs.append((setter, kind, size)) + setter(studio_icon(kind, size)) + + def set_theme(self, tid: str): + theme.set_theme(tid) + for setter, kind, size in self._icon_refs: + setter(studio_icon(kind, size)) + self._refresh_object_list() + self._refresh_needle_list() + self._populate_properties(self.canvas.selected) + self.canvas.update() @staticmethod def _hoop_label(h: Hoop) -> str: @@ -375,13 +269,13 @@ def retranslate_ui(self): self.cmb_hoop.setItemText(i, self._hoop_label(self.cmb_hoop.itemData(i))) for i in range(self.cmb_machine.count()): self.cmb_machine.setItemText(i, machine_display_name(self.cmb_machine.itemData(i).name)) + for i in range(self.cmb_fabric.count()): + self.cmb_fabric.setItemText(i, tr(f"fab_{self.cmb_fabric.itemData(i)}")) self._refresh_object_list() total = self.canvas.plan.stitch_count if total: # Zahlenformat des Simulator-Zählers an die Sprache anpassen cur = total if self.canvas.sim_limit is None else self.canvas.sim_limit self.lbl_sim.setText(f"{fmt_int(cur)} / {fmt_int(total)}") - lbl = {"slate": "fabric_slate", "sand": "fabric_sand", "light": "fabric_light"} - self.btn_fabric.setText(tr(lbl.get(self.canvas.fabric_theme, "fabric_slate"))) self._refresh_stats() self._refresh_needle_list() self._populate_properties(self.canvas.selected) @@ -417,8 +311,9 @@ def _rebuild_swatch_grid(self): btn.setToolTip(f"{t.brand} {t.code} {t.name} ({t.hex})") r, g, b = t.color btn.setStyleSheet( - f"QToolButton {{ background-color: rgb({r},{g},{b}); border: 1px solid rgba(255,255,255,35); border-radius: 5px; }}" - f"QToolButton:hover {{ border: 2px solid #a8c7fa; }}" + f"QToolButton {{ background-color: rgb({r},{g},{b}); border: 1px solid rgba(128,128,128,70);" + f" border-radius: 5px; padding: 0; }}" + f"QToolButton:hover {{ border: 2px solid {theme.current().accent}; }}" ) btn.clicked.connect(lambda _=False, th=t: self._apply_thread(th)) grid.addWidget(btn, idx // cols, idx % cols) @@ -429,7 +324,7 @@ def cycle_fabric_theme(self): idx = next((i for i, (k, _) in enumerate(order) if k == cur), 0) nxt_k, nxt_key = order[(idx + 1) % len(order)] self.canvas.fabric_theme = nxt_k - self.btn_fabric.setText(tr(nxt_key)) + self.status.showMessage(tr(nxt_key), 3000) self.canvas.update() def resizeEvent(self, event): @@ -454,13 +349,16 @@ def _build_menus_and_header(self): self._bind(tb.setWindowTitle, "tb_title_studio") self.top_toolbar = tb tb.setMovable(False) - tb.setIconSize(QSize(16, 16)) + tb.setFloatable(False) + tb.toggleViewAction().setVisible(False) + tb.setIconSize(QSize(18, 18)) tb.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self.addToolBar(Qt.TopToolBarArea, tb) def add_act(menu, text, slot, shortcut=None, toolbar_label=None, icon_kind=None, checkable=False): - ic = studio_icon(icon_kind, 16) if icon_kind else QIcon() - act = QAction(ic, text, self) + act = QAction(text, self) + if icon_kind: + self._icon(act.setIcon, icon_kind, 16) key = key_for(text) if key: self._bind(act.setText, key, escape=True) @@ -470,7 +368,9 @@ def add_act(menu, text, slot, shortcut=None, toolbar_label=None, icon_kind=None, act.triggered.connect(slot) menu.addAction(act) if toolbar_label: - tb_act = QAction(ic, toolbar_label, self) + tb_act = QAction(toolbar_label, self) + if icon_kind: + self._icon(tb_act.setIcon, icon_kind, 18) tb_key = key_for(toolbar_label) if tb_key: self._bind(tb_act.setText, tb_key, escape=True) @@ -485,40 +385,61 @@ def add_act(menu, text, slot, shortcut=None, toolbar_label=None, icon_kind=None, return tb_act return act + def icon_only(a: QAction): + b = tb.widgetForAction(a) + if b is not None: + b.setToolButtonStyle(Qt.ToolButtonIconOnly) + # Datei + add_act(m_file, "Startseite anzeigen", self.show_start_page, None, None, "home") add_act(m_file, "Neues Design", self.action_new, "Ctrl+N", "Neu", "new") - add_act(m_file, "Projekt öffnen (.ostitch) …", self.action_open_project, "Ctrl+O") - add_act(m_file, "Projekt speichern (.ostitch) …", self.action_save_project, "Ctrl+S") + add_act(m_file, "Projekt öffnen (.ostitch) …", self.action_open_project, "Ctrl+O", "Öffnen", "open") + self.m_recent = m_file.addMenu("") + self._bind(self.m_recent.setTitle, "menu_recent") + self.m_recent.aboutToShow.connect(self._fill_recent_menu) + add_act(m_file, "Projekt speichern (.ostitch) …", self.action_save_project, "Ctrl+S", "Speichern", "save") m_file.addSeparator() - add_act(m_file, "Stickdatei importieren (EXP, DST, PES, JEF …) …", self.action_import_embroidery, "Ctrl+I", "Import", "import") - add_act(m_file, "SVG-Vektorgrafik importieren (.svg) …", self.action_import_svg, None, "SVG", "svg") - add_act(m_file, "Stickdatei exportieren (EXP, DST, PES, JEF …) …", self.action_export_embroidery, "Ctrl+E", "Export", "export") - add_act(m_file, "Produktionsblatt als PDF speichern …", self.action_export_pdf, None, "PDF", "pdf") + add_act(m_file, "Stickdatei importieren (EXP, DST, PES, JEF …) …", self.action_import_embroidery, "Ctrl+I", None, "import") + add_act(m_file, "SVG-Vektorgrafik importieren (.svg) …", self.action_import_svg, None, None, "svg") + add_act(m_file, "Produktionsblatt als PDF speichern …", self.action_export_pdf, None, None, "pdf") add_act(m_file, "Realistische 3D-Vorschau als PNG speichern …", self.action_export_png) m_file.addSeparator() add_act(m_file, "Beenden", self.close, "Ctrl+Q") + tb.addSeparator() + icon_only(add_act(m_edit, "Rückgängig", self.action_undo, "Ctrl+Z", "Rückgängig", "undo")) + icon_only(add_act(m_edit, "Wiederherstellen", self.action_redo, "Ctrl+Y", "Wiederherstellen", "redo")) tb.addSeparator() # Digitalisieren / Assistenten - add_act(m_create, "Bild automatisch digitalisieren (Auto-Digitizer) …", self.action_auto_digitize, "Ctrl+D", "Auto-Digitizer", "magic") - add_act(m_create, "PhotoStitch (Porträtfoto → Stickerei) …", self.action_photostitch, "Ctrl+P", "PhotoStitch", "photo") + add_act(m_create, "Bild automatisch digitalisieren (Auto-Digitizer) …", self.action_auto_digitize, "Ctrl+D", "Bild → Stiche", "magic") + add_act(m_create, "PhotoStitch (Porträtfoto → Stickerei) …", self.action_photostitch, "Ctrl+P", None, "photo") add_act(m_create, "Schrift / Monogramm einfügen …", self.action_add_text, "Ctrl+T", "Schrift", "text") - add_act(m_create, "Aus Fläche Applikation (Appliqué) erzeugen", self.action_make_applique, None, "Appliqué", "applique") - add_act(m_create, "3D-Puff-Schaumstoff-Modus für Satin umschalten", self.action_toggle_3d_puff, None, "3D-Puff", "puff") + add_act(m_create, "Aus Fläche Applikation (Appliqué) erzeugen", self.action_make_applique, None, None, "applique") + add_act(m_create, "3D-Puff-Schaumstoff-Modus für Satin umschalten", self.action_toggle_3d_puff, None, None, "puff") + + spacer = QWidget() + spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) + spacer.setStyleSheet("background: transparent;") + tb.addWidget(spacer) - tb.addSeparator() # Maschine & Qualitätsprüfung - add_act(m_machine, "Maschinen-Transfer / Diskette / USB / NetBridge …", self.action_melco_disk, "Ctrl+M", "Transfer", "transfer") - add_act(m_machine, "Qualitäts- & Maschinen-Doktor (Prüfung)", self.action_quality_doctor, "F7", "Doktor", "doctor") + add_act(m_machine, "Design prüfen (virtueller Probestick)", self.action_quality_doctor, "F7", "Prüfen", "doctor") + act_export = add_act(m_machine, "Stickdatei exportieren (EXP, DST, PES, JEF …) …", self.action_export_embroidery, "Ctrl+E", "Export", "export") + btn_export = tb.widgetForAction(act_export) + if btn_export is not None: + btn_export.setObjectName("accentTool") + add_act(m_machine, "Maschinen-Transfer / Diskette / USB / NetBridge …", self.action_melco_disk, "Ctrl+M", None, "transfer") add_act(m_machine, "Farben minimieren (Nadelwechsel sparen)", self.action_optimize_color_order) # Hilfe / Rundgang - add_act(m_help, "Interaktiver Studio-Rundgang (Onboarding) …", self.action_show_tour, "F1", "Rundgang", "tour") + add_act(m_help, "Interaktiver Studio-Rundgang (Onboarding) …", self.action_show_tour, "F1", None, "tour") + add_act(m_help, "Tastenkürzel …", self.action_shortcuts) add_act(m_help, "Offizielles OpenStitch-Logo wiederherstellen", self._load_starter_design) + m_help.addSeparator() + add_act(m_help, "Problem melden …", lambda: QDesktopServices.openUrl(QUrl(ISSUES_URL))) + add_act(m_help, "Über OpenStitch …", self.action_about) # Bearbeiten - add_act(m_edit, "Rückgängig", self.action_undo, "Ctrl+Z") - add_act(m_edit, "Wiederherstellen", self.action_redo, "Ctrl+Y") m_edit.addSeparator() add_act(m_edit, "Ausgewähltes Objekt duplizieren", self.action_duplicate_selected, "Ctrl+J") add_act(m_edit, "Ausgewähltes Objekt löschen", self.action_delete_selected, "Delete") @@ -536,28 +457,36 @@ def add_act(menu, text, slot, shortcut=None, toolbar_label=None, icon_kind=None, self.act_grid.setChecked(True) self.act_heatmap = add_act(m_view, "Stichdichte-Heatmap (Stoffbelastung)", self._toggle_view, "Ctrl+H", None, None, True) add_act(m_view, "Auf Rahmengrösse zoomen", self.canvas.zoom_to_fit, "Ctrl+0") + m_view.addSeparator() + self.m_view = m_view + group = QActionGroup(self) + for tid, label in (("dark", "Dunkles Design"), ("light", "Helles Design")): + a = add_act(m_view, label, lambda _=False, t=tid: self.set_theme(t), None, None, None, True) + a.setChecked(theme.current().id == tid) + group.addAction(a) # ================================= 2. Linke Vertikal-Werkzeugleiste (Tool-Rail) def _build_left_tool_rail(self): rail = QToolBar(tr("tb_title_tools"), self) self._bind(rail.setWindowTitle, "tb_title_tools") self.left_rail = rail + rail.setObjectName("rail") rail.setMovable(False) + rail.setFloatable(False) + rail.toggleViewAction().setVisible(False) rail.setOrientation(Qt.Vertical) - rail.setIconSize(QSize(17, 17)) - rail.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) + rail.setIconSize(QSize(20, 20)) + rail.setToolButtonStyle(Qt.ToolButtonIconOnly) self.addToolBar(Qt.LeftToolBarArea, rail) def rail_btn(key: str, icon_kind: str, tip_key: str, slot, checkable: bool = True) -> QAction: - a = QAction(studio_icon(icon_kind, 17), tr(key), self) + a = QAction(tr(key), self) + self._icon(a.setIcon, icon_kind, 20) self._bind(a.setText, key, escape=True) self._bind(a.setToolTip, tip_key) a.setCheckable(checkable) a.triggered.connect(slot) rail.addAction(a) - w_btn = rail.widgetForAction(a) - if w_btn is not None: - w_btn.setMinimumWidth(116) return a self.act_tool_select = rail_btn("tool_select", "select", "tip_tool_select", lambda: self._set_tool("select")) @@ -581,8 +510,9 @@ def _build_left_palette_dock(self): self._bind(dock.setWindowTitle, "dock_palette") self.left_dock = dock dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) + dock.setFeatures(QDockWidget.DockWidgetClosable | QDockWidget.DockWidgetMovable) w = QWidget() - w.setMaximumWidth(275) + w.setFixedWidth(248) lay = QVBoxLayout(w) lay.setContentsMargins(8, 8, 8, 8) lay.setSpacing(8) @@ -595,9 +525,8 @@ def _build_left_palette_dock(self): self.lbl_active_swatch = QLabel() self.lbl_active_swatch.setFixedSize(26, 26) self.lbl_active_name = QLabel("043 Rot") - self.lbl_active_name.setStyleSheet("font-weight: 600;") + self.lbl_active_name.setProperty("role", "strong") btn_rgb = QPushButton("RGB …") - btn_rgb.setFixedWidth(64) btn_rgb.clicked.connect(self._pick_custom_color) hc.addWidget(self.lbl_active_swatch) hc.addWidget(self.lbl_active_name, 1) @@ -605,16 +534,17 @@ def _build_left_palette_dock(self): lay.addWidget(card_cur) # Garnkatalog-Auswahl (Madeira, Isacord, Gunold, Brother, Universal) - hb_cat = QHBoxLayout() + hb_cat = QVBoxLayout() + hb_cat.setSpacing(1) lbl_cat = QLabel("Garnkatalog:") - lbl_cat.setStyleSheet("color: #8ab4f8; font-weight: 600;") + lbl_cat.setProperty("role", "caption") self._bind(lbl_cat.setText, "lbl_catalog") self.cmb_catalog = QComboBox() for pal in CATALOG_PALETTES: self.cmb_catalog.addItem(pal.name, pal) self.cmb_catalog.setCurrentIndex(0) hb_cat.addWidget(lbl_cat) - hb_cat.addWidget(self.cmb_catalog, 1) + hb_cat.addWidget(self.cmb_catalog) lay.addLayout(hb_cat) # Kompaktes 7-spaltiges Farbfeld-Grid (statt klobiger langer Liste!) @@ -629,11 +559,12 @@ def _build_left_palette_dock(self): lbl_seq = QLabel("Farb- & Nadel-Sequenz im Design:") self._bind(lbl_seq.setText, "lbl_seq") - lbl_seq.setStyleSheet("color: #9ba4b8; font-weight: 600; margin-top: 4px;") + lbl_seq.setProperty("role", "caption") lay.addWidget(lbl_seq) self.list_needles = QListWidget() self.list_needles.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + self.list_needles.setTextElideMode(Qt.ElideRight) lay.addWidget(self.list_needles, 1) dock.setWidget(w) @@ -644,7 +575,7 @@ def _update_active_swatch_ui(self): t = self.canvas.active_thread r, g, b = t.color self.lbl_active_swatch.setStyleSheet( - f"background-color: rgb({r},{g},{b}); border: 1px solid rgba(255,255,255,90); border-radius: 5px;" + f"background-color: rgb({r},{g},{b}); border: 1px solid rgba(128,128,128,120); border-radius: 5px;" ) self.lbl_active_name.setText(f"{t.code} {t.name}") @@ -654,36 +585,37 @@ def _build_right_dock(self): self._bind(dock.setWindowTitle, "dock_right") self.right_dock = dock dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) + dock.setFeatures(QDockWidget.DockWidgetClosable | QDockWidget.DockWidgetMovable) split = QSplitter(Qt.Vertical) - split.setMinimumWidth(330) - split.setMaximumWidth(370) + split.setMinimumWidth(304) w_top = QWidget() vt = QVBoxLayout(w_top) vt.setContentsMargins(8, 8, 8, 4) self.list_objects = QListWidget() self.list_objects.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + self.list_objects.setTextElideMode(Qt.ElideRight) self.list_objects.currentRowChanged.connect(self._on_object_row_changed) vt.addWidget(self.list_objects, 1) hb = QHBoxLayout() - btn_up = QPushButton("▲") - self._bind(btn_up.setToolTip, "tip_obj_up") - btn_up.clicked.connect(lambda: self._move_selected_object(-1)) - btn_dn = QPushButton("▼") - self._bind(btn_dn.setToolTip, "tip_obj_down") - btn_dn.clicked.connect(lambda: self._move_selected_object(1)) - btn_vis = QPushButton("👁 Sichtbar") - self._bind(btn_vis.setText, "btn_visible") - btn_vis.clicked.connect(self._toggle_selected_visibility) - btn_dup = QPushButton("⧉ Kopie") - self._bind(btn_dup.setText, "btn_copy") - btn_dup.clicked.connect(self.action_duplicate_selected) - btn_del = QPushButton("🗑") - self._bind(btn_del.setToolTip, "tip_obj_delete") - btn_del.clicked.connect(self.action_delete_selected) - for b in (btn_up, btn_dn, btn_vis, btn_dup, btn_del): + hb.setSpacing(4) + + def small_btn(kind: str, key: str, slot) -> QPushButton: + b = QPushButton() + b.setObjectName("iconBtn") + self._icon(b.setIcon, kind, 16) + self._bind(b.setToolTip, key) + b.clicked.connect(slot) hb.addWidget(b) + return b + + small_btn("up", "tip_obj_up", lambda: self._move_selected_object(-1)) + small_btn("down", "tip_obj_down", lambda: self._move_selected_object(1)) + hb.addStretch(1) + small_btn("eye", "tip_obj_visible", self._toggle_selected_visibility) + small_btn("copy", "tip_obj_copy", self.action_duplicate_selected) + small_btn("trash", "tip_obj_delete", self.action_delete_selected) vt.addLayout(hb) split.addWidget(w_top) @@ -692,7 +624,7 @@ def _build_right_dock(self): vb.setContentsMargins(8, 4, 8, 8) lbl_insp = QLabel("Objekt-Parameter (Live-Neuberechnung):") self._bind(lbl_insp.setText, "lbl_inspector") - lbl_insp.setStyleSheet("color: #8ab4f8; font-weight: 600;") + lbl_insp.setProperty("role", "caption") vb.addWidget(lbl_insp) self.prop_container = QFrame() self.prop_container.setObjectName("card") @@ -700,7 +632,13 @@ def _build_right_dock(self): self.prop_layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.prop_layout.setVerticalSpacing(8) self.prop_layout.setHorizontalSpacing(10) - vb.addWidget(self.prop_container, 1) + self.prop_layout.setContentsMargins(10, 10, 10, 10) + self.prop_layout.setLabelAlignment(Qt.AlignLeft) + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + scroll.setWidget(self.prop_container) + vb.addWidget(scroll, 1) split.addWidget(w_bot) split.setSizes([235, 485]) @@ -709,13 +647,12 @@ def _build_right_dock(self): # ========================================= 5. Unten: Simulator & Statusleiste def _build_bottom_bar(self): - dock = QDockWidget("Stich-Simulator && Näh-Player", self) - self._bind(dock.setWindowTitle, "dock_bottom") - self.bottom_dock = dock - dock.setFeatures(QDockWidget.NoDockWidgetFeatures) - w = QWidget() - hb = QHBoxLayout(w) - hb.setContentsMargins(12, 6, 12, 6) + bar = QFrame() + bar.setObjectName("simBar") + self.bottom_dock = bar # Ziel des Rundgangs + hb = QHBoxLayout(bar) + hb.setContentsMargins(12, 5, 12, 5) + hb.setSpacing(8) self.btn_play = QPushButton(tr("btn_play")) self.btn_play.setObjectName("primaryBtn") @@ -728,9 +665,6 @@ def _build_bottom_bar(self): btn_reset_sim.clicked.connect(self._reset_sim) hb.addWidget(btn_reset_sim) - lbl_prog = QLabel(" Fortschritt:") - self._bind(lbl_prog.setText, "lbl_progress") - hb.addWidget(lbl_prog) self.slider_sim = QSlider(Qt.Horizontal) self.slider_sim.setRange(0, 100) self.slider_sim.setValue(100) @@ -738,7 +672,7 @@ def _build_bottom_bar(self): hb.addWidget(self.slider_sim, 1) self.lbl_sim = QLabel(tr("sim_all")) - self.lbl_sim.setMinimumWidth(115) + self.lbl_sim.setMinimumWidth(96) hb.addWidget(self.lbl_sim) lbl_spd = QLabel("Tempo:") @@ -747,18 +681,27 @@ def _build_bottom_bar(self): self.sp_sim_speed = QSpinBox() self.sp_sim_speed.setRange(5, 500) self.sp_sim_speed.setValue(45) + self.sp_sim_speed.setFixedWidth(104) self._bind(self.sp_sim_speed.setSuffix, "sim_speed_suffix") hb.addWidget(self.sp_sim_speed) - dock.setWidget(w) - self.addDockWidget(Qt.BottomDockWidgetArea, dock) + self.editor_page.layout().addWidget(bar) self.status = QStatusBar(self) + self.status.setSizeGripEnabled(False) self.setStatusBar(self.status) self.lbl_stats = QLabel() + # Langer Text darf die Mindestbreite des Fensters nicht bestimmen + self.lbl_stats.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred) self.lbl_cursor = QLabel("X: 0.0 mm, Y: 0.0 mm") self.status.addWidget(self.lbl_stats, 1) self.status.addPermanentWidget(self.lbl_cursor) + self.cmb_lang = QComboBox() + for code, label in LANGUAGES: + self.cmb_lang.addItem(label, code) + self.cmb_lang.setCurrentIndex(max(0, next((i for i, (c, _) in enumerate(LANGUAGES) if c == current_lang()), 0))) + self.cmb_lang.currentIndexChanged.connect(self._on_language_changed) + self.status.addPermanentWidget(self.cmb_lang) # ============================================= Offizielles OpenStitch-Starter-Logo & In-App Rundgang def _load_starter_design(self): @@ -775,13 +718,33 @@ def _load_starter_design(self): if settings.value("show_tour_on_startup", True, type=bool): QTimer.singleShot(280, self.action_show_tour) + def action_about(self): + QMessageBox.about(self, tr("act_about").rstrip(" …"), ( + f"

{APP_NAME} Studio {__version__}

{tr('about_text')}

" + f'

{REPO_URL}

')) + + def action_shortcuts(self): + rows = [("V", "key_select"), ("N", "key_nodes"), ("F", "key_fill"), ("S", "key_satin"), ("R", "key_run"), + ("Enter", "key_finish"), ("Esc", "key_cancel"), (tr("key_wheel"), "key_zoom"), + (tr("key_middle"), "key_pan")] + body = "".join(f"{k}   {tr(t)}" for k, t in rows) + for a in self.findChildren(QAction): + sc = a.shortcut().toString(QKeySequence.NativeText) + if sc and a.text(): + body += f"{sc}   {a.text().replace('&&', '&')}" + QMessageBox.information(self, tr("keys_title"), f"{body}
") + def action_show_tour(self): + if self.stack.currentWidget() is self.start_page: + self._tour_from_start() # Der Rundgang erklärt die Arbeitsfläche, nicht die Startseite + return if self._tour_overlay is None: self._tour_overlay = InAppTourOverlay(self) self._tour_overlay.start_tour() # =================================================== Design-Rebuild & Sync def set_design(self, d: Design, reset_undo: bool = False, prebuilt_plan=None): + self.hide_start_page() self.canvas.design = d self.canvas.selected = d.objects[0] if d.objects else None self.canvas.sim_limit = None @@ -817,6 +780,10 @@ def _sync_hoop_machine_ui(self): self.cmb_machine.blockSignals(True) self.cmb_machine.setCurrentIndex(idx) self.cmb_machine.blockSignals(False) + if hasattr(self, "cmb_fabric"): + self.cmb_fabric.blockSignals(True) + self.cmb_fabric.setCurrentIndex(max(0, self.cmb_fabric.findData(d.fabric))) + self.cmb_fabric.blockSignals(False) def _snapshot(self, desc: str): self._dirty = True @@ -877,16 +844,18 @@ def _refresh_stats(self): x0, y0, x1, y1 = p.bounds() w, h = x1 - x0, y1 - y0 kin = analyze_kinematics(p, self.canvas.design.settings.machine_spm) + colon = tr("label_colon") self.lbl_stats.setText( - f"{tr('stats_stitches')}{tr('label_colon')} {fmt_int(p.stitch_count)} · " - f"{tr('stats_size')}{tr('label_colon')} {w:.1f} × {h:.1f} mm · " - f"{tr('stats_avg')}{tr('label_colon')} {kin['avg_len']:.1f} mm · " - f"{tr('stats_spm')}{tr('label_colon')} ~{kin['eff_spm']} SPM · " - f"{tr('stats_peak')}{tr('label_colon')} {kin['max_per_mm2']}/mm² · " - f"{tr('stats_colors')}{tr('label_colon')} {p.color_changes} · " - f"{tr('stats_trims')}{tr('label_colon')} {p.trim_count} · " + f"{tr('stats_stitches')}{colon} {fmt_int(p.stitch_count)} · {w:.1f} × {h:.1f} mm · " + f"{tr('stats_colors')}{colon} {p.color_changes} · " + f"{tr('stats_trims')}{colon} {p.trim_count} · " f"{tr('stats_runtime')} {kin['real_minutes']:.1f} {tr('stats_min')}" ) + self.lbl_stats.setToolTip( + f"{tr('stats_avg')}{colon} {kin['avg_len']:.1f} mm\n" + f"{tr('stats_spm')}{colon} ~{kin['eff_spm']} SPM\n" + f"{tr('stats_peak')}{colon} {kin['max_per_mm2']}/mm²" + ) def _refresh_object_list(self): self.list_objects.blockSignals(True) @@ -930,7 +899,7 @@ def _populate_properties(self, obj: EmbObject | None): if obj is None: lbl_empty = QLabel(tr("lbl_no_sel")) lbl_empty.setWordWrap(True) - lbl_empty.setStyleSheet("color: #7c8599;") + lbl_empty.setProperty("role", "muted") self.prop_layout.addRow(lbl_empty) self._updating_props = False return @@ -1092,7 +1061,25 @@ def action_fit_to_hoop(self): self.rebuild_plan() self.canvas.zoom_to_fit() + def _on_fabric_changed(self): + fid = self.cmb_fabric.currentData() + d = self.canvas.design + if fid and fid != d.fabric: + d.fabric = fid + self._dirty = True + self.rebuild_plan() + self.status.showMessage(self._fabric_advice(fid), 9000) + + @staticmethod + def _fabric_advice(fid: str) -> str: + f = fabric_by_id(fid) + text = tr("fabric_advice").format(fabric=tr(f"fab_{f.id}"), stabilizer=tr(f"stab_{f.stabilizer}"), needle=f.needle) + return f"{text} {tr('fabric_topping')}" if f.topping else text + def _on_machine_changed(self): + mp_now: MachineProfile = self.cmb_machine.currentData() + if mp_now is not None: + QSettings("OpenStitch", "OpenStitchStudio").setValue("ui/machine", mp_now.id) mp: MachineProfile = self.cmb_machine.currentData() self.canvas.design.settings.needles = mp.needles self.canvas.design.settings.machine_spm = mp.default_spm @@ -1153,6 +1140,11 @@ def closeEvent(self, event): if not self._confirm_discard(): event.ignore() return + self._autosave_timer.stop() + self.start_page.stop() + if self._check_dlg is not None: + self._check_dlg.close() + self._clear_autosave() # sauber beendet: nichts wiederherzustellen self._planner.wait(5.0) super().closeEvent(event) @@ -1256,38 +1248,161 @@ def dragEnterEvent(self, event: QDragEnterEvent): def dropEvent(self, event: QDropEvent): urls = event.mimeData().urls() - if not urls: - return - path = urls[0].toLocalFile() - if not path or not os.path.isfile(path): + if urls and urls[0].toLocalFile(): + self.open_path(urls[0].toLocalFile()) + + def open_path(self, path: str): + """Öffnet jede unterstützte Datei: Projekt, Stickdatei, SVG oder Bild.""" + if not os.path.isfile(path): + self._forget_recent(path) + QMessageBox.warning(self, tr("err_open_title"), tr("err_file_gone").format(path)) return self._remember_dir(path) ext = os.path.splitext(path)[1].lower().lstrip(".") - if (ext == "ostitch" or ext == "svg" or ext in READ_EXT) and not self._confirm_discard(): + if ext in IMAGE_EXT: + self._open_auto_digitize_for_path(path) return - if ext == "ostitch": - try: - self.set_design(load_project(path), reset_undo=True) - self.canvas.zoom_to_fit() - except Exception as exc: - QMessageBox.critical(self, tr("err_open_title"), str(exc)) - elif ext == "svg": - try: + if ext not in READ_EXT and ext not in ("ostitch", "svg"): + QMessageBox.warning(self, tr("err_open_title"), tr("err_unknown_type").format(os.path.basename(path))) + return + if not self._confirm_discard(): + return + title = {"ostitch": "err_open_title", "svg": "err_svg_title"}.get(ext, "err_import_title") + try: + if ext == "ostitch": + d = load_project(path) + elif ext == "svg": d = import_svg(path, target_width_mm=95.0) d.hoop = self.canvas.design.hoop - self.set_design(d, reset_undo=True) - self.canvas.zoom_to_fit() - except Exception as exc: - QMessageBox.critical(self, tr("err_svg_title"), str(exc)) - elif ext in READ_EXT: - try: + else: d = import_file(path) - self.set_design(d, reset_undo=True) - self.canvas.zoom_to_fit() - except Exception as exc: - QMessageBox.critical(self, tr("err_import_title"), str(exc)) - elif ext in ("png", "jpg", "jpeg", "bmp", "webp", "tif", "tiff", "gif"): - self._open_auto_digitize_for_path(path) + self.set_design(d, reset_undo=True) + self.canvas.zoom_to_fit() + self._add_recent(path) + except Exception as exc: + QMessageBox.critical(self, tr(title), str(exc)) + + # ------------------------------------------------------------- Startseite + def _chrome_visible(self, on: bool): + for w in (self.left_rail, self.left_dock, self.right_dock, self.top_toolbar, self.lbl_stats, self.lbl_cursor): + w.setVisible(on) + + def show_start_page(self): + self.start_page.set_recent(self._recent_files()) + self.start_page.load_thumbnails() + self.stack.setCurrentWidget(self.start_page) + self._chrome_visible(False) + + def hide_start_page(self): + if self.stack.currentWidget() is self.start_page: + self.stack.setCurrentWidget(self.editor_page) + self._chrome_visible(True) + + def _on_start_choice(self, what: str): + if what == "image": + self.action_auto_digitize() + elif what == "text": + self.hide_start_page() + self.canvas.zoom_to_fit() + self.action_add_text() + elif what == "draw": + self.hide_start_page() + self.canvas.zoom_to_fit() + self.act_tool_fill.setChecked(True) + self._set_tool("draw_fill") + elif what == "open": + self.action_open_any() + + def _open_sample(self, sid: str): + factory = next(f for s, _k, f in SAMPLES if s == sid) + if self._confirm_discard(): + self.set_design(factory(), reset_undo=True) + QTimer.singleShot(60, self.canvas.zoom_to_fit) + + def _tour_from_start(self): + self.set_design(create_openstitch_logo_design(), reset_undo=True) + QTimer.singleShot(120, self.action_show_tour) + + def startup(self): + """Erster Start im echten Programm (Tests bauen das Fenster direkt).""" + s = QSettings("OpenStitch", "OpenStitchStudio") + idx = self.cmb_machine.findText(s.value("ui/machine", "", type=str)) + for i in range(self.cmb_machine.count()): + if self.cmb_machine.itemData(i).id == s.value("ui/machine", "", type=str): + idx = i + if idx >= 0: + self.cmb_machine.setCurrentIndex(idx) + self.canvas.design = Design(name=tr("default_design_name")) + self._sync_hoop_machine_ui() + if not self._offer_recovery(): + self.show_start_page() + + # ---------------------------------------------------------- Zuletzt geöffnet + @staticmethod + def _recent_files() -> list[str]: + v = QSettings("OpenStitch", "OpenStitchStudio").value("recent/files", []) + if isinstance(v, str): + v = [v] + return [p for p in (v or []) if isinstance(p, str)] + + def _add_recent(self, path: str): + path = os.path.abspath(path) + files = [path] + [p for p in self._recent_files() if p != path] + QSettings("OpenStitch", "OpenStitchStudio").setValue("recent/files", files[:MAX_RECENT]) + + def _forget_recent(self, path: str): + QSettings("OpenStitch", "OpenStitchStudio").setValue( + "recent/files", [p for p in self._recent_files() if p != path]) + self.start_page.set_recent(self._recent_files()) + + def _fill_recent_menu(self): + self.m_recent.clear() + files = self._recent_files() + self.m_recent.setEnabled(bool(files)) + for path in files: + a = self.m_recent.addAction(os.path.basename(path).replace("&", "&&")) + a.setToolTip(path) + a.triggered.connect(lambda _=False, p=path: self.open_path(p)) + + # ---------------------------------------------------- Automatisches Speichern + @staticmethod + def _autosave_path() -> str: + folder = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation) + os.makedirs(folder, exist_ok=True) + return os.path.join(folder, "autosave.ostitch") + + def _autosave(self): + if self._dirty: + try: + save_project(self.canvas.design, self._autosave_path()) + except OSError as exc: + self.status.showMessage(tr("status_autosave_failed").format(exc), 8000) + + def _clear_autosave(self): + try: + os.remove(self._autosave_path()) + except OSError: + pass + + def _offer_recovery(self) -> bool: + """Nach einem Absturz: letzte automatische Sicherung anbieten.""" + path = self._autosave_path() + if not os.path.isfile(path): + return False + ans = QMessageBox.question(self, tr("dlg_recover_title"), tr("dlg_recover_text"), + QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) + if ans != QMessageBox.Yes: + self._clear_autosave() + return False + try: + self.set_design(load_project(path), reset_undo=True) + self._dirty = True + self.canvas.zoom_to_fit() + return True + except Exception as exc: + QMessageBox.critical(self, tr("err_open_title"), str(exc)) + self._clear_autosave() + return False # -------------------------------------------------------- Datei-Aktionen def action_new(self): @@ -1296,18 +1411,19 @@ def action_new(self): self.set_design(Design(name=tr("default_design_name")), reset_undo=True) def action_open_project(self): - if not self._confirm_discard(): - return + self.action_open_any() + + def action_open_any(self): + """Ein Dialog für alles: Projekte, Stickdateien, Vektorgrafiken und Bilder.""" + emb = " ".join(f"*.{e} *.{e.upper()}" for e in READ_EXT) + img = " ".join(f"*.{e}" for e in IMAGE_EXT) path = self._ask_open_file( - tr("fd_open_project"), f"{tr('filter_project')} (*.ostitch);;{tr('filter_all_files')} (*.*)" + tr("fd_open_any"), + f"{tr('filter_supported')} (*.ostitch *.svg {emb} {img});;{tr('filter_project')} (*.ostitch);;" + f"{tr('filter_emb')} ({emb});;{tr('filter_all_img_vec')} (*.svg {img});;{tr('filter_all_files')} (*.*)", ) - if not path: - return - try: - self.set_design(load_project(path), reset_undo=True) - self.canvas.zoom_to_fit() - except Exception as exc: - QMessageBox.critical(self, tr("err_open_title"), str(exc)) + if path: + self.open_path(path) def action_save_project(self): path = self._ask_save_file( @@ -1371,44 +1487,69 @@ def action_make_applique(self): self.rebuild_plan() def action_quality_doctor(self): - self.wait_for_plan() - issues = run_quality_doctor( - self.canvas.design, self.canvas.plan, max_needles=self.canvas.design.settings.needles - ) - QMessageBox.information( - self, - tr("msg_doctor_title"), - "\n\n".join(issues), - ) + """Virtueller Probestick. Bleibt offen, damit man Fundstellen auf der Leinwand ansehen kann.""" + if self._check_dlg is None: + self._check_dlg = DesignCheckDialog(self) + if self._check_dlg.isVisible(): + self._check_dlg.start() + self._check_dlg.raise_() + else: + self._check_dlg.show() + + def fix_for(self, code: str): + """Passende Ein-Klick-Lösung zu einem Prüfbefund, oder None.""" + return { + "outside_hoop": self.action_fit_to_hoop, + "too_many_colors": self.action_optimize_color_order, + "registration_gap": self._fix_pull_comp, + "long_float": self._fix_long_stitches, + "too_dense": self._fix_density, + "low_coverage": self._fix_coverage, + }.get(code) + + def _bulk_edit(self, desc: str, edit): + self._snapshot(desc) + for o in self.canvas.design.objects: + edit(o) + self._dirty = True + self.rebuild_plan() + + def _fix_pull_comp(self): + def edit(o): + if hasattr(o, "pull_comp"): + o.pull_comp = min(round(o.pull_comp + 0.1, 2), 0.8) + self._bulk_edit(tr("undo_fix"), edit) + + def _fix_long_stitches(self): + def edit(o): + if hasattr(o, "max_stitch"): + o.max_stitch = min(o.max_stitch, 7.0) + if hasattr(o, "stitch_len"): + o.stitch_len = min(o.stitch_len, 6.0) + self._bulk_edit(tr("undo_fix"), edit) + + def _fix_density(self): + def edit(o): + if hasattr(o, "knockout"): + o.knockout = True + for attr in ("spacing", "density"): + if hasattr(o, attr): + setattr(o, attr, min(round(getattr(o, attr) + 0.05, 2), 0.6)) + self._bulk_edit(tr("undo_fix"), edit) + + def _fix_coverage(self): + def edit(o): + if hasattr(o, "spacing"): + o.spacing = max(round(o.spacing - 0.05, 2), 0.3) + self._bulk_edit(tr("undo_fix"), edit) def action_export_embroidery(self): - mp: MachineProfile = self.cmb_machine.currentData() - ext_default = mp.native_ext.upper() if mp else "EXP" - filters = ";;".join(f"{FORMAT_NAMES.get(e, e.upper())} (*.{e})" for e in WRITE_EXT) - path = self._ask_save_file( - tr("fd_export_emb"), f"{self.canvas.design.name}.{ext_default}", filters - ) - if not path: - return self.wait_for_plan() - try: - export_plan(self.canvas.plan, path) - ext = os.path.splitext(path)[1].lower().lstrip(".") - if ext in ("exp", "dst", "pes", "jef", "vp3", "xxx", "u01", "pec", "tbf"): - rep = verify_exported_file(path, self.canvas.plan) - QMessageBox.information( - self, - tr("msg_export_verified_title"), - tr("msg_export_verified_text").format( - path=path, size=fmt_int(rep["bytes"]), stitches=fmt_int(rep["stitches"]), - w=rep["width_mm"], h=rep["height_mm"], step=rep["max_step_mm"], - colors=rep["color_changes"], jumps=rep["jumps"], - ), - ) - else: - QMessageBox.information(self, tr("msg_export_ok_title"), tr("msg_export_ok_text").format(path)) - except Exception as exc: - QMessageBox.critical(self, tr("err_export_title"), str(exc)) + ExportDialog(self).exec() + + @staticmethod + def thread_icon(rgb: tuple[int, int, int]) -> QIcon: + return _color_icon(rgb) def action_export_pdf(self): path = self._ask_save_file( @@ -1468,8 +1609,9 @@ def _open_auto_digitize_for_path(self, path: str): same_mode = res_d.hoop.mode == self.canvas.design.hoop.mode res_d.hoop = self.canvas.design.hoop res_d.settings = self.canvas.design.settings + res_d.fabric = self.canvas.design.fabric # Vorberechneter Plan gilt nur, wenn die Rahmen-Strategie identisch ist - self.set_design(res_d, prebuilt_plan=dlg.result_plan if same_mode else None) + self.set_design(res_d, prebuilt_plan=dlg.result_plan if same_mode and res_d.fabric == "woven" else None) self.canvas.zoom_to_fit() def action_photostitch(self): @@ -1489,6 +1631,7 @@ def action_photostitch(self): res_d = dlg.result_design res_d.hoop = self.canvas.design.hoop res_d.settings = self.canvas.design.settings + res_d.fabric = self.canvas.design.fabric self.set_design(res_d) self.canvas.zoom_to_fit() diff --git a/openstitch/ui/onboarding.py b/openstitch/ui/onboarding.py index 10b2027..9ff11df 100644 --- a/openstitch/ui/onboarding.py +++ b/openstitch/ui/onboarding.py @@ -5,9 +5,7 @@ from PySide6.QtCore import QPointF, QRectF, QSettings, Qt from PySide6.QtGui import ( QColor, - QFont, QIcon, - QLinearGradient, QPainter, QPainterPath, QPen, @@ -16,7 +14,6 @@ ) from PySide6.QtWidgets import ( QCheckBox, - QDialog, QFrame, QHBoxLayout, QLabel, @@ -24,11 +21,13 @@ QVBoxLayout, QWidget, ) -from shapely.geometry import LineString, Point, Polygon +from shapely.geometry import LineString, Polygon -from ..core.design import Design, FillObject, HOOPS, RunObject, SatinObject +from ..core.design import Design, FillObject, HOOPS, SatinObject from ..core.stitchplan import Thread +from ..i18n import tr from ..text import TextObject +from . import theme # =========================================================================== @@ -40,13 +39,14 @@ def studio_icon(kind: str, size: int = 18) -> QIcon: p = QPainter(pix) p.setRenderHint(QPainter.Antialiasing, True) - c_blue = QColor("#8ab4f8") - c_gold = QColor("#fdd663") - c_green = QColor("#81c995") - c_red = QColor("#f28b82") - c_purple = QColor("#c58af9") - c_cyan = QColor("#78d9ec") - c_light = QColor("#e8eaed") + th = theme.current() + c_blue = QColor(th.icon_blue) + c_gold = QColor(th.icon_gold) + c_green = QColor(th.icon_green) + c_red = QColor(th.icon_red) + c_purple = QColor(th.icon_purple) + c_cyan = QColor(th.icon_cyan) + c_light = QColor(th.icon_light) s = float(size) m = s * 0.16 @@ -234,6 +234,91 @@ def studio_icon(kind: str, size: int = 18) -> QIcon: p.drawEllipse(QPointF(s * 0.44, s * 0.44), s * 0.24, s * 0.24) p.drawLine(QPointF(s * 0.62, s * 0.62), QPointF(s * 0.82, s * 0.82)) + elif kind == "home": + p.setPen(QPen(c_light, 1.7, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) + p.drawPolyline(QPolygonF([QPointF(m, s * 0.5), QPointF(s * 0.5, m), QPointF(s - m, s * 0.5)])) + p.drawPolyline(QPolygonF([QPointF(s * 0.26, s * 0.46), QPointF(s * 0.26, s - m), + QPointF(s * 0.74, s - m), QPointF(s * 0.74, s * 0.46)])) + + elif kind == "open": + p.setPen(QPen(c_gold, 1.6, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) + path = QPainterPath() + path.moveTo(m, s * 0.8) + path.lineTo(m, s * 0.24) + path.lineTo(s * 0.4, s * 0.24) + path.lineTo(s * 0.5, s * 0.36) + path.lineTo(s * 0.8, s * 0.36) + path.lineTo(s * 0.8, s * 0.48) + path.moveTo(m, s * 0.8) + path.lineTo(s * 0.3, s * 0.48) + path.lineTo(s - m * 0.6, s * 0.48) + path.lineTo(s * 0.72, s * 0.8) + path.closeSubpath() + p.drawPath(path) + + elif kind == "save": + p.setPen(QPen(c_blue, 1.6, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) + p.drawRoundedRect(QRectF(m, m, s - 2 * m, s - 2 * m), 2.5, 2.5) + p.drawRect(QRectF(s * 0.32, m, s * 0.36, s * 0.24)) + p.drawRect(QRectF(s * 0.28, s * 0.58, s * 0.44, s - m - s * 0.58)) + + elif kind in ("undo", "redo"): + p.save() + if kind == "redo": + p.translate(s, 0) + p.scale(-1, 1) + p.setPen(QPen(c_light, 1.8, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) + path = QPainterPath() + path.moveTo(s * 0.26, s * 0.42) + path.lineTo(s * 0.62, s * 0.42) + path.cubicTo(s * 0.92, s * 0.42, s * 0.92, s * 0.8, s * 0.6, s * 0.8) + path.lineTo(s * 0.42, s * 0.8) + p.drawPath(path) + p.drawPolyline(QPolygonF([QPointF(s * 0.42, s * 0.24), QPointF(s * 0.24, s * 0.42), QPointF(s * 0.42, s * 0.6)])) + p.restore() + + elif kind == "palette": + p.setPen(QPen(c_light, 1.6, Qt.SolidLine, Qt.RoundCap)) + p.drawEllipse(QPointF(s * 0.5, s * 0.5), s * 0.36, s * 0.36) + p.setPen(Qt.NoPen) + for (dx, dy), col in (((0.36, 0.38), c_red), ((0.6, 0.34), c_gold), ((0.68, 0.56), c_green), ((0.42, 0.64), c_blue)): + p.setBrush(col) + p.drawEllipse(QPointF(s * dx, s * dy), s * 0.075, s * 0.075) + + elif kind in ("up", "down"): + p.setPen(QPen(c_light, 1.9, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) + a, b = (0.62, 0.38) if kind == "up" else (0.38, 0.62) + p.drawPolyline(QPolygonF([QPointF(s * 0.26, s * a), QPointF(s * 0.5, s * b), QPointF(s * 0.74, s * a)])) + + elif kind == "eye": + p.setPen(QPen(c_light, 1.6, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) + path = QPainterPath() + path.moveTo(m * 0.7, s * 0.5) + path.quadTo(s * 0.5, s * 0.14, s - m * 0.7, s * 0.5) + path.quadTo(s * 0.5, s * 0.86, m * 0.7, s * 0.5) + p.drawPath(path) + p.setBrush(c_light) + p.drawEllipse(QPointF(s * 0.5, s * 0.5), s * 0.11, s * 0.11) + + elif kind == "copy": + p.setPen(QPen(c_light, 1.6, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) + p.drawRoundedRect(QRectF(s * 0.36, s * 0.36, s * 0.46, s * 0.46), 2, 2) + p.drawPolyline(QPolygonF([QPointF(s * 0.24, s * 0.64), QPointF(s * 0.18, s * 0.64), QPointF(s * 0.18, s * 0.18), + QPointF(s * 0.64, s * 0.18), QPointF(s * 0.64, s * 0.24)])) + + elif kind == "trash": + p.setPen(QPen(c_red, 1.6, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) + p.drawLine(QPointF(s * 0.2, s * 0.28), QPointF(s * 0.8, s * 0.28)) + p.drawLine(QPointF(s * 0.4, s * 0.28), QPointF(s * 0.42, s * 0.16)) + p.drawLine(QPointF(s * 0.6, s * 0.28), QPointF(s * 0.58, s * 0.16)) + p.drawPolyline(QPolygonF([QPointF(s * 0.27, s * 0.28), QPointF(s * 0.32, s * 0.84), + QPointF(s * 0.68, s * 0.84), QPointF(s * 0.73, s * 0.28)])) + + elif kind == "usb": + p.setPen(QPen(c_blue, 1.6, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) + p.drawRoundedRect(QRectF(s * 0.28, s * 0.36, s * 0.44, s * 0.48), 3, 3) + p.drawRect(QRectF(s * 0.38, s * 0.14, s * 0.24, s * 0.22)) + p.end() return QIcon(pix) @@ -256,7 +341,7 @@ def create_openstitch_logo_design() -> Design: d.objects.append( FillObject( Thread.from_hex("#162847", "Space Indigo", "075", "OpenStitch"), - name="Wappen-Schild (Ziegel)", + name="Shield", geom=hex_poly.buffer(-2.6), angle=30.0, spacing=0.44, @@ -269,8 +354,8 @@ def create_openstitch_logo_design() -> Design: outer_ring = hex_poly.difference(hex_poly.buffer(-3.2)) d.objects.append( SatinObject( - Thread.from_hex("#4285F4", "Studio Blau", "035", "OpenStitch"), - name="Wappen-Satinrand", + Thread.from_hex("#4285F4", "Studio Blue", "035", "OpenStitch"), + name="Shield border", geom=outer_ring, spacing=0.38, pull_comp=0.18, @@ -287,7 +372,7 @@ def create_openstitch_logo_design() -> Design: d.objects.append( SatinObject( Thread.from_hex("#FBBC04", "Solar Gold", "023", "OpenStitch"), - name="Goldene Fadenwelle", + name="Golden thread", geom=wave_ribbon, spacing=0.36, pull_comp=0.18, @@ -302,8 +387,8 @@ def create_openstitch_logo_design() -> Design: arc_ribbon = LineString(arc_pts).buffer(1.45, cap_style=1, join_style=1) d.objects.append( SatinObject( - Thread.from_hex("#EA4335", "Korallenrot", "042", "OpenStitch"), - name="Korallen-Fadenschlaufe", + Thread.from_hex("#EA4335", "Coral Red", "042", "OpenStitch"), + name="Coral loop", geom=arc_ribbon, spacing=0.36, pull_comp=0.16, @@ -315,8 +400,8 @@ def create_openstitch_logo_design() -> Design: needle_geom = needle_line.buffer(1.8, cap_style=1) d.objects.append( SatinObject( - Thread.from_hex("#34A853", "Smaragd", "058", "OpenStitch"), - name="Präzisions-Nadel", + Thread.from_hex("#34A853", "Emerald", "058", "OpenStitch"), + name="Needle", geom=needle_geom, spacing=0.36, pull_comp=0.16, @@ -326,8 +411,8 @@ def create_openstitch_logo_design() -> Design: # 6. Markenschriftzug „OPENSTITCH“ in Reinweiss (#FFFFFF) d.objects.append( TextObject( - Thread.from_hex("#FFFFFF", "Reinweiss", "001", "OpenStitch"), - name='Schriftzug „OPENSTITCH“', + Thread.from_hex("#FFFFFF", "Pure White", "001", "OpenStitch"), + name="Lettering", text="OPENSTITCH", height=5.6, letter_spacing=0.45, @@ -339,397 +424,74 @@ def create_openstitch_logo_design() -> Design: # =========================================================================== -# 3. Interaktiver Studio-Rundgang (Google-Material-3 Onboarding-Tour) -# =========================================================================== -class _TourHeroBanner(QWidget): - """Vektor-illustrierter Header für jeden Schritt des Studio-Rundgangs.""" - - def __init__(self, parent=None): - super().__init__(parent) - self.setFixedHeight(145) - self.step_index = 0 - - def set_step(self, idx: int): - self.step_index = idx - self.update() - - def paintEvent(self, _ev): - p = QPainter(self) - p.setRenderHint(QPainter.Antialiasing, True) - w, h = float(self.width()), float(self.height()) - - # Edler Google-AI-Studio Verlaufshintergrund - grad = QLinearGradient(0, 0, w, h) - palettes = [ - (QColor("#16233b"), QColor("#1f3763"), QColor("#4285F4")), - (QColor("#142b29"), QColor("#1b433d"), QColor("#34A853")), - (QColor("#2c2214"), QColor("#463316"), QColor("#FBBC04")), - (QColor("#261a38"), QColor("#3c255c"), QColor("#c58af9")), - (QColor("#2d1a1e"), QColor("#4a2229"), QColor("#EA4335")), - ] - c0, c1, accent = palettes[self.step_index % len(palettes)] - grad.setColorAt(0.0, c0) - grad.setColorAt(1.0, c1) - - path = QPainterPath() - path.addRoundedRect(QRectF(0, 0, w, h), 12, 12) - p.fillPath(path, grad) - - # Dekoratives Millimeter-Grid im Hintergrund - p.setPen(QPen(QColor(255, 255, 255, 16), 1)) - for x in range(24, int(w), 24): - p.drawLine(x, 0, x, int(h)) - for y in range(24, int(h), 24): - p.drawLine(0, y, int(w), y) - - # Schritt-spezifische Vektor-Grafik in der Mitte - cx, cy = w * 0.5, h * 0.52 - p.setPen(QPen(accent, 2.4, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) - p.setBrush(QColor(accent.red(), accent.green(), accent.blue(), 42)) - - if self.step_index == 0: - # OpenStitch Hexagon + Fadenwelle - pts = [ - QPointF(cx + 42 * math.cos(math.radians(i * 60 - 30)), - cy + 42 * math.sin(math.radians(i * 60 - 30))) - for i in range(6) - ] - p.drawPolygon(QPolygonF(pts)) - p.setPen(QPen(QColor("#FBBC04"), 3.0, Qt.SolidLine, Qt.RoundCap)) - wave = QPainterPath() - wave.moveTo(cx - 28, cy + 4) - wave.cubicTo(QPointF(cx - 10, cy - 22), QPointF(cx + 10, cy + 28), QPointF(cx + 28, cy - 4)) - p.drawPath(wave) - elif self.step_index == 1: - # Stickrahmen + Cap Center-Out Pfeile - p.drawEllipse(QPointF(cx, cy), 42, 42) - p.setPen(QPen(QColor("#81c995"), 1.6, Qt.DashLine)) - p.drawEllipse(QPointF(cx, cy), 34, 34) - p.setPen(QPen(QColor("#ffffff"), 2.0)) - p.drawLine(QPointF(cx, cy + 16), QPointF(cx, cy - 18)) - p.drawLine(QPointF(cx, cy + 4), QPointF(cx - 20, cy + 4)) - p.drawLine(QPointF(cx, cy + 4), QPointF(cx + 20, cy + 4)) - elif self.step_index == 2: - # Bild -> Funken -> Stickerei - p.drawRoundedRect(QRectF(cx - 65, cy - 28, 52, 56), 6, 6) - p.setPen(QPen(QColor("#FBBC04"), 2.4)) - p.drawLine(QPointF(cx - 6, cy), QPointF(cx + 8, cy)) - p.drawRoundedRect(QRectF(cx + 16, cy - 28, 52, 56), 6, 6) - for ry in range(-18, 22, 8): - p.drawLine(QPointF(cx + 24, cy + ry), QPointF(cx + 60, cy + ry)) - elif self.step_index == 3: - # Bezier-Knoten & Stichwinkel-Achse - p.drawRoundedRect(QRectF(cx - 48, cy - 30, 96, 60), 10, 10) - p.setPen(QPen(QColor("#FBBC04"), 2.2, Qt.DashLine)) - p.drawLine(QPointF(cx - 32, cy + 16), QPointF(cx + 32, cy - 16)) - p.setBrush(QColor("#ffffff")) - p.drawEllipse(QPointF(cx - 32, cy + 16), 5, 5) - p.drawEllipse(QPointF(cx + 32, cy - 16), 5, 5) - else: - # Qualitäts-Doktor Schild + Haken - p.drawEllipse(QPointF(cx, cy), 40, 40) - p.setPen(QPen(QColor("#81c995"), 3.2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) - p.drawLine(QPointF(cx - 16, cy + 2), QPointF(cx - 4, cy + 15)) - p.drawLine(QPointF(cx - 4, cy + 15), QPointF(cx + 18, cy - 12)) - - p.end() - - -class OnboardingTourDialog(QDialog): - """Interaktiver 5-Schritte-Rundgang im Google-Studio-Look.""" - - STEPS = [ - { - "badge": "WILLKOMMEN · ÜBERBLICK", - "title": "Willkommen bei OpenStitch Studio", - "body": ( - "OpenStitch ist deine universelle, herstellerneutrale Open-Source-Suite für " - "professionelles Digitalisieren und Sticken.

" - "• Universell kompatibel: Unterstützt Tajima (.DST), Brother (.PES), " - "Melco/Bernina (.EXP), Janome (.JEF), Pfaff/Husqvarna (.VP3) & Barudan (.U01).
" - "• Starter-Design auf der Leinwand: Wir haben für dich direkt das offizielle " - "OpenStitch-Wappen geladen – klicke einzelne Elemente an, um sie live anzupassen!" - ), - "action_label": None, - "action_key": None, - }, - { - "badge": "SCHRITT 1 VON 4 · OBEN RECHTS", - "title": "Maschine & Intelligenter Stickrahmen", - "body": ( - "Oben rechts in der Studio-Leiste wählst du deine Maschine und deinen Stickrahmen:

" - "• Automatische Rahmen-Physik: Grosse Rahmen (18–30 cm) federn in der Mitte stärker " - "(Trampolin-Effekt). OpenStitch verstärkt dort automatisch die Unterlage und Zugkompensation.
" - "• Kappen-Modus (Cap): Sortiert Objekte automatisch Center-Out & Bottom-Up " - "(vom Schirm nach oben und von der Mittelnaht nach aussen), damit sich auf Caps keine Falten bilden." - ), - "action_label": "⛶ Design jetzt optimal in Rahmen einpassen (Auto-Fit)", - "action_key": "fit", - }, - { - "badge": "SCHRITT 2 VON 4 · OBEN MITTE", - "title": "In Sekunden vom Bild oder Vektor zur Stickdatei", - "body": ( - "Drei leistungsstarke Assistenten nehmen dir die Vorarbeit ab:

" - "• ✨ Auto-Digitizer (Ctrl+D): Entfernt den Bildhintergrund automatisch, trennt Farben per " - "CIE-Lab und erzeugt saubere Tatami- & Satin-Objekte mit 0.7 mm Überlappung gegen Stoffblitzer.
" - "• 🖼 PhotoStitch (Ctrl+P): Verwandelt Porträtfotos in monochrome oder 4-farbige CMYK-Wellenstickerei.
" - "• ✒ SVG & 🔤 Schrift (Ctrl+T): Importiert Vektor-Logos oder setzt TrueType-Schriften auf Bogen." - ), - "action_label": "✨ Auto-Digitizer jetzt öffnen …", - "action_key": "auto_digitize", - }, - { - "badge": "SCHRITT 3 VON 4 · LINKS & RECHTS", - "title": "Profi-Werkzeuge, Knoten-Editor & Live-Inspektor", - "body": ( - "Du hast jederzeit die volle manuelle Kontrolle:

" - "• Linke Werkzeugleiste: Zeichne eigene Tatami-Flächen (F), Satin-Säulen (S) oder " - "Steppstiche (R). Mit Knoten (N) ziehst du Konturpunkte und die gelbe Stichwinkel-Achse live.
" - "• Rechter Objekt-Inspektor: Ändere Dichte, Muster (z. B. Kontur-Fill), Zugkompensation oder " - "aktiviere den 3D-Puff-Schaumstoff-Modus für erhabene 3D-Caps – alles berechnet sich sofort neu!" - ), - "action_label": "❖ Knoten- & Stichwinkel-Editor (Taste N) aktivieren", - "action_key": "nodes_tool", - }, - { - "badge": "SCHRITT 4 VON 4 · PRÜFUNG & EXPORT", - "title": "Qualitäts-Doktor (F7), Simulator & Export", - "body": ( - "Bevor die Maschine startet, sorgt OpenStitch für maximale Produktionssicherheit:

" - "• 🩺 Qualitäts-Doktor (F7): Prüft dein Design auf Fadenriss-Risiken, Nadelbruch-Stellen " - "(>18 Stiche/mm²), Rahmen-Überschreitung und Nadelanzahl.
" - "• ▶ Näh-Simulator (Unten): Spiele den Stickverlauf Stich für Stich vor.
" - "• 💾 Export (Ctrl+E) & 📄 PDF: Exportiere für deine Maschine + drucke das A4-Produktionsblatt." - ), - "action_label": "🩺 Qualitäts-Doktor (F7) für das aktuelle Logo ausführen", - "action_key": "doctor", - }, - ] - - def __init__(self, main_win, parent=None): - super().__init__(parent or main_win) - self.main_win = main_win - self.idx = 0 - self.setWindowTitle("OpenStitch Studio — Interaktiver Rundgang") - self.setMinimumWidth(560) - self.setMaximumWidth(600) - self.setModal(False) - self.setWindowFlags(Qt.Dialog | Qt.WindowCloseButtonHint | Qt.WindowTitleHint) - - lay = QVBoxLayout(self) - lay.setContentsMargins(20, 20, 20, 18) - lay.setSpacing(14) - - self.hero = _TourHeroBanner(self) - lay.addWidget(self.hero) - - self.lbl_badge = QLabel() - self.lbl_badge.setStyleSheet( - "color: #8ab4f8; font-size: 8.5pt; font-weight: 700; letter-spacing: 1.1px;" - ) - lay.addWidget(self.lbl_badge) - - self.lbl_title = QLabel() - f = QFont("Segoe UI", 14, QFont.Bold) - self.lbl_title.setFont(f) - self.lbl_title.setStyleSheet("color: #f8f9fa;") - lay.addWidget(self.lbl_title) - - card = QFrame() - card.setObjectName("card") - cv = QVBoxLayout(card) - cv.setContentsMargins(14, 12, 14, 12) - self.lbl_body = QLabel() - self.lbl_body.setWordWrap(True) - self.lbl_body.setStyleSheet("color: #d2d8e6; font-size: 10pt; line-height: 1.45;") - cv.addWidget(self.lbl_body) - - self.btn_try = QPushButton() - self.btn_try.setCursor(Qt.PointingHandCursor) - self.btn_try.setStyleSheet( - "QPushButton { background-color: rgba(138, 180, 248, 0.14); border: 1px solid #4c8df6; " - "color: #8ab4f8; font-weight: 600; padding: 7px 12px; border-radius: 7px; margin-top: 6px; }" - "QPushButton:hover { background-color: rgba(138, 180, 248, 0.26); color: #ffffff; }" - ) - self.btn_try.clicked.connect(self._on_try_action) - cv.addWidget(self.btn_try) - lay.addWidget(card) - - # Fusszeile mit Schritt-Punkten, Checkbox & Navigation - foot = QHBoxLayout() - self.cb_startup = QCheckBox("Beim Start zeigen") - settings = QSettings("OpenStitch", "OpenStitchStudio") - self.cb_startup.setChecked(settings.value("show_tour_on_startup", True, type=bool)) - self.cb_startup.toggled.connect( - lambda v: QSettings("OpenStitch", "OpenStitchStudio").setValue("show_tour_on_startup", bool(v)) - ) - foot.addWidget(self.cb_startup) - - foot.addStretch(1) - self.lbl_dots = QLabel() - self.lbl_dots.setStyleSheet("color: #8ab4f8; font-size: 11pt; letter-spacing: 3px;") - foot.addWidget(self.lbl_dots) - foot.addStretch(1) - - self.btn_prev = QPushButton("← Zurück") - self.btn_prev.clicked.connect(self._prev) - foot.addWidget(self.btn_prev) - - self.btn_next = QPushButton("Weiter →") - self.btn_next.setObjectName("primaryBtn") - self.btn_next.clicked.connect(self._next) - foot.addWidget(self.btn_next) - - lay.addLayout(foot) - self._refresh() - - def _refresh(self): - st = self.STEPS[self.idx] - self.hero.set_step(self.idx) - self.lbl_badge.setText(st["badge"]) - self.lbl_title.setText(st["title"]) - self.lbl_body.setText(st["body"]) - - if st["action_label"]: - self.btn_try.setText(st["action_label"]) - self.btn_try.show() - else: - self.btn_try.hide() - - dots = ["●" if i == self.idx else "○" for i in range(len(self.STEPS))] - self.lbl_dots.setText(" ".join(dots)) - - self.btn_prev.setEnabled(self.idx > 0) - if self.idx == len(self.STEPS) - 1: - self.btn_next.setText("Loslegen ✓") - else: - self.btn_next.setText("Weiter →") - - def _prev(self): - if self.idx > 0: - self.idx -= 1 - self._refresh() - - def _next(self): - if self.idx < len(self.STEPS) - 1: - self.idx += 1 - self._refresh() - else: - self.accept() - - def _on_try_action(self): - key = self.STEPS[self.idx].get("action_key") - if not self.main_win: - return - if key == "fit": - self.main_win.action_fit_to_hoop() - elif key == "auto_digitize": - self.hide() - self.main_win.action_auto_digitize() - elif key == "nodes_tool": - self.main_win._set_tool("edit_nodes") - elif key == "doctor": - self.main_win.action_quality_doctor() - - -# =========================================================================== -# 4. In-App Spotlight & Coach-Mark Popups (Direkt im Hauptfenster!) +# 3. In-App Spotlight & Coach-Mark Popups (Direkt im Hauptfenster!) # =========================================================================== class InAppTourOverlay(QWidget): """Interaktives Spotlight-Overlay mit schwebenden Coach-Mark-Popups direkt über den UI-Bereichen.""" + # Enthält i18n-Schlüssel: Übersetzt wird erst in _refresh, damit der Rundgang der Sprache folgt. STEPS = [ { "target": "canvas_center", "place": "right", - "badge": "WILLKOMMEN · 1 / 7", - "title": "3D-Stickleinwand & OpenStitch-Wappen", - "body": ( - "Hier in der Mitte siehst du unser offizielles OpenStitch-Wappen im Stickrahmen.

" - "• Klicken & Ziehen: Objekte direkt auswählen, verschieben oder am Eckgriff skalieren.
" - "• Mausrad: Stufenlos bis auf einzelne Einstiche hineinzoomen." - ), - "action_label": "🎨 Stofffarbe im Rahmen testen (Dunkel / Sand / Hell)", + "badge": "tour_app_1_badge", + "title": "tour_app_1_title", + "body": "tour_app_1_body", + "action_label": "tour_app_1_action", "action_key": "cycle_fabric", }, { "target": "ctx_bar", "place": "below", - "badge": "KONTEXTLEISTE · 2 / 7", - "title": "Maschine, Stickrahmen & Rahmen-Physik", - "body": ( - "Direkt über der Leinwand wählst du deine Maschine (Universal, Tajima, Brother, Barudan, Melco …) " - "und den Stickrahmen:

" - "• Intelligente Strategie: Je nach Rahmengrösse (z. B. Anti-Trampolin bei grossen Rahmen " - "oder Center-Out & Bottom-Up bei Caps) passt OpenStitch Unterlage & Zugkompensation automatisch an!" - ), - "action_label": "⛶ Design optimal in den Rahmen einpassen (Auto-Fit)", + "badge": "tour_app_2_badge", + "title": "tour_app_2_title", + "body": "tour_app_2_body", + "action_label": "tour_app_2_action", "action_key": "fit", }, { "target": "top_toolbar", "place": "below", - "badge": "STUDIO-LEISTE · 3 / 7", - "title": "Auto-Digitizer, PhotoStitch, SVG & Doktor", - "body": ( - "Oben findest du alle Kreativ-Assistenten und Prüfwerkzeuge:

" - "• Auto-Digitizer (Ctrl+D): Bild hochladen → automatische Hintergrund-Freistellung & Stickflächen.
" - "• PhotoStitch (Ctrl+P): Porträtfotos als Wellen-/CMYK-Stickerei.
" - "• Doktor (F7): Prüft dein Design vorab auf Fadenriss- & Nadelbruch-Risiken." - ), - "action_label": "✨ Auto-Digitizer direkt öffnen …", + "badge": "tour_app_3_badge", + "title": "tour_app_3_title", + "body": "tour_app_3_body", + "action_label": "tour_app_3_action", "action_key": "auto_digitize", }, { "target": "left_rail", "place": "right", - "badge": "WERKZEUGE · 4 / 7", - "title": "Manuelles Zeichnen & Stichwinkel-Knoten (N)", - "body": ( - "In der vertikalen Werkzeugleiste links wechselst du den Bearbeitungsmodus:

" - "• Tatami (F) / Satin (S) / Stepp (R): Eigene Formen frei auf der Leinwand zeichnen.
" - "• Knoten (N): Konturpunkte einzeln verschieben und an der gelben Achse den Stichwinkel live drehen!" - ), - "action_label": "❖ Knoten- && Stichwinkel-Editor (N) jetzt einschalten", + "badge": "tour_app_4_badge", + "title": "tour_app_4_title", + "body": "tour_app_4_body", + "action_label": "tour_app_4_action", "action_key": "nodes_tool", }, { "target": "left_dock", "place": "right", - "badge": "GARNFARBEN · 5 / 7", - "title": "Farbpalette & Nadel-Sequenz", - "body": ( - "Links wählst du mit einem Klick aus 49 Industriepaletten-Farben oder einem eigenen RGB-Ton.

" - "• Darunter siehst du live die Nadel- & Farbwechsel-Sequenz deiner Maschine inklusive Stichanzahl pro Farbe." - ), + "badge": "tour_app_5_badge", + "title": "tour_app_5_title", + "body": "tour_app_5_body", "action_label": None, "action_key": None, }, { "target": "right_dock", "place": "left", - "badge": "INSPEKTOR · 6 / 7", - "title": "Ebenen & Live-Objekt-Parameter", - "body": ( - "Rechts steuerst du die Stickreihenfolge und stellst im Objekt-Inspektor " - "Reihenabstand, Muster (z. B. Kontur-Fill), Zugkompensation oder 3D-Puff-Schaumstoff ein.

" - "• Jede Änderung berechnet die Stiche sofort live auf der Leinwand neu!" - ), + "badge": "tour_app_6_badge", + "title": "tour_app_6_title", + "body": "tour_app_6_body", "action_label": None, "action_key": None, }, { "target": "bottom_bar", "place": "above", - "badge": "SIMULATOR & PRODUKTION · 7 / 7", - "title": "Stich-Simulator & Echtzeit-Kinematik", - "body": ( - "Unten spielst du den kompletten Nähvorgang Stich für Stich im Simulator vor.

" - "• In der Statusleiste ganz unten siehst du live die effektive Maschinengeschwindigkeit (SPM), " - "Spitzendichte (St./mm²), Trims und die reale Produktionslaufzeit!" - ), - "action_label": "▶ Näh-Simulation unten starten / stoppen", + "badge": "tour_app_7_badge", + "title": "tour_app_7_title", + "body": "tour_app_7_body", + "action_label": "tour_app_7_action", "action_key": "play_sim", }, ] @@ -764,15 +526,14 @@ def __init__(self, main_win): ) top_row.addWidget(self.lbl_badge) top_row.addStretch(1) - btn_close = QPushButton("✕") - btn_close.setFixedSize(24, 24) - btn_close.setToolTip("Rundgang schliessen (Esc)") - btn_close.setStyleSheet( + self.btn_close = QPushButton("✕") + self.btn_close.setFixedSize(24, 24) + self.btn_close.setStyleSheet( "QPushButton { background: transparent; border: none; color: #9aa4b8; font-size: 10pt; padding: 0; }" "QPushButton:hover { color: #ffffff; background-color: #343b4a; border-radius: 12px; }" ) - btn_close.clicked.connect(self.close_tour) - top_row.addWidget(btn_close) + self.btn_close.clicked.connect(self.close_tour) + top_row.addWidget(self.btn_close) lay.addLayout(top_row) self.lbl_title = QLabel() @@ -796,7 +557,7 @@ def __init__(self, main_win): lay.addWidget(self.btn_try) foot = QHBoxLayout() - self.cb_startup = QCheckBox("Beim Start") + self.cb_startup = QCheckBox() self.cb_startup.setStyleSheet("color: #9aa4b8; font-size: 8.5pt;") settings = QSettings("OpenStitch", "OpenStitchStudio") self.cb_startup.setChecked(settings.value("show_tour_on_startup", True, type=bool)) @@ -813,16 +574,21 @@ def __init__(self, main_win): self.btn_prev = QPushButton("←") self.btn_prev.setFixedWidth(34) - self.btn_prev.setToolTip("Vorheriger Schritt") self.btn_prev.clicked.connect(self._prev) foot.addWidget(self.btn_prev) - self.btn_next = QPushButton("Weiter →") + self.btn_next = QPushButton() self.btn_next.setObjectName("primaryBtn") self.btn_next.clicked.connect(self._next) foot.addWidget(self.btn_next) lay.addLayout(foot) + main_win.cmb_lang.currentIndexChanged.connect(self._on_language_changed) + + def _on_language_changed(self): + if self.isVisible(): + self._refresh() + def start_tour(self): self.idx = 0 self.setGeometry(self.main_win.rect()) @@ -867,12 +633,15 @@ def _target_rect(self) -> QRectF: def _refresh(self): self.setGeometry(self.main_win.rect()) st = self.STEPS[self.idx] - self.lbl_badge.setText(st["badge"]) - self.lbl_title.setText(st["title"]) - self.lbl_body.setText(st["body"]) + self.btn_close.setToolTip(tr("tour_close_tip")) + self.cb_startup.setText(tr("tour_on_start")) + self.btn_prev.setToolTip(tr("tour_prev_tip")) + self.lbl_badge.setText(tr(st["badge"])) + self.lbl_title.setText(tr(st["title"])) + self.lbl_body.setText(tr(st["body"])) if st["action_label"]: - self.btn_try.setText(st["action_label"]) + self.btn_try.setText(tr(st["action_label"])) self.btn_try.show() else: self.btn_try.hide() @@ -881,7 +650,7 @@ def _refresh(self): self.lbl_dots.setText(" ".join(dots)) self.btn_prev.setEnabled(self.idx > 0) - self.btn_next.setText("Fertig ✓" if self.idx == len(self.STEPS) - 1 else "Weiter →") + self.btn_next.setText(tr("tour_done") if self.idx == len(self.STEPS) - 1 else tr("tour_next")) self.card.adjustSize() spot = self._target_rect() diff --git a/openstitch/ui/plan_worker.py b/openstitch/ui/plan_worker.py index f0fb6c8..728d024 100644 --- a/openstitch/ui/plan_worker.py +++ b/openstitch/ui/plan_worker.py @@ -30,8 +30,10 @@ def __init__(self, parent=None): def _detach(design: Design) -> Design: """Flache Kopien der Objekte: Parameter/Geometrien sind unveränderlich bzw. werden nur ersetzt, so kann der Haupt-Thread weiter editieren, ohne die Berechnung zu stören.""" - return Design(objects=[copy.copy(o) for o in design.objects], hoop=design.hoop, - settings=copy.copy(design.settings), name=design.name, _cache=design._cache) + d = copy.copy(design) # so kommen auch künftige Felder (z. B. der Stoff) mit + d.objects = [copy.copy(o) for o in design.objects] + d.settings = copy.copy(design.settings) + return d def request(self, design: Design) -> int: with self._lock: diff --git a/openstitch/ui/start_page.py b/openstitch/ui/start_page.py new file mode 100644 index 0000000..791ef3b --- /dev/null +++ b/openstitch/ui/start_page.py @@ -0,0 +1,207 @@ +"""Startseite: führt in zwei Klicks zum ersten Design, auch ohne Stick-Vorwissen.""" +from __future__ import annotations + +import os + +from PySide6.QtCore import QSize, Qt, QThread, Signal +from PySide6.QtGui import QIcon, QImage, QPainter, QPixmap +from PySide6.QtWidgets import ( + QFrame, + QGridLayout, + QHBoxLayout, + QLabel, + QPushButton, + QScrollArea, + QSizePolicy, + QToolButton, + QVBoxLayout, + QWidget, +) + +from ..render import render_image +from ..samples import SAMPLES +from .onboarding import studio_icon + + +class _ThumbWorker(QThread): + """Rendert die Beispiel-Vorschauen im Hintergrund: Der Start bleibt sofort bedienbar.""" + ready = Signal(str, QImage) + + def run(self): + for sid, _key, factory in SAMPLES: + if self.isInterruptionRequested(): + return + try: + plan = factory().build_plan() + self.ready.emit(sid, render_image(plan, px_per_mm=4.0, margin_mm=4.0, background=None)) + except Exception: # noqa: BLE001 - eine fehlende Vorschau darf den Start nicht stören + continue + + +class StartPage(QWidget): + """Kacheln für die häufigsten Wege, darunter Beispiele und zuletzt geöffnete Dateien.""" + chosen = Signal(str) # "image" | "text" | "draw" | "open" + sample_chosen = Signal(str) + recent_chosen = Signal(str) + tour_requested = Signal() + + def __init__(self, bind, icon, parent=None): + super().__init__(parent) + self.setObjectName("startPage") + self.setAttribute(Qt.WA_StyledBackground, True) + self._bind = bind + self._icon = icon + self._thumbs: dict[str, QToolButton] = {} + self._worker: _ThumbWorker | None = None + + scroll = QScrollArea(self) + scroll.setWidgetResizable(True) + scroll.setFrameShape(QFrame.NoFrame) + outer = QVBoxLayout(self) + outer.setContentsMargins(0, 0, 0, 0) + outer.addWidget(scroll) + + body = QWidget() + body.setObjectName("startPage") + scroll.setWidget(body) + wrap = QHBoxLayout(body) + wrap.addStretch(1) + col = QVBoxLayout() + col.setContentsMargins(24, 30, 24, 24) + col.setSpacing(14) + holder = QWidget() + holder.setObjectName("startPage") + holder.setMaximumWidth(920) + holder.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) + holder.setLayout(col) + wrap.addWidget(holder, 6) + wrap.addStretch(1) + + title = QLabel() + title.setProperty("role", "title") + bind(title.setText, "start_title") + sub = QLabel() + sub.setProperty("role", "subtitle") + sub.setWordWrap(True) + bind(sub.setText, "start_subtitle") + col.addWidget(title) + col.addWidget(sub) + col.addSpacing(8) + + cards = QGridLayout() + cards.setSpacing(12) + for i, (what, kind, key_t, key_d) in enumerate(( + ("image", "magic", "start_image", "start_image_d"), + ("text", "text", "start_text", "start_text_d"), + ("draw", "fill", "start_draw", "start_draw_d"), + ("open", "open", "start_open", "start_open_d"), + )): + cards.addWidget(self._card(what, kind, key_t, key_d), i // 2, i % 2) + col.addLayout(cards) + col.addSpacing(10) + + lbl = QLabel() + lbl.setProperty("role", "section") + bind(lbl.setText, "start_samples") + col.addWidget(lbl) + row = QHBoxLayout() + row.setSpacing(10) + for sid, key, _factory in SAMPLES: + b = QToolButton() + b.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) + b.setIconSize(QSize(130, 110)) + b.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) + b.setCursor(Qt.PointingHandCursor) + bind(b.setText, key) + b.clicked.connect(lambda _=False, s=sid: self.sample_chosen.emit(s)) + self._thumbs[sid] = b + row.addWidget(b) + col.addLayout(row) + + self.recent_title = QLabel() + self.recent_title.setProperty("role", "section") + bind(self.recent_title.setText, "start_recent") + col.addWidget(self.recent_title) + self.recent_box = QVBoxLayout() + self.recent_box.setSpacing(0) + col.addLayout(self.recent_box) + + tour = QPushButton() + tour.setObjectName("linkBtn") + tour.setCursor(Qt.PointingHandCursor) + bind(tour.setText, "start_tour") + tour.clicked.connect(self.tour_requested) + col.addWidget(tour, 0, Qt.AlignLeft) + col.addStretch(1) + + def _card(self, what: str, kind: str, key_t: str, key_d: str) -> QPushButton: + """Kachel mit Symbol, Titel und einem Satz: Beschreibung im Button statt nur im Tooltip.""" + b = QPushButton() + b.setObjectName("startCard") + b.setCursor(Qt.PointingHandCursor) + b.setMinimumHeight(86) + b.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) + h = QHBoxLayout(b) + h.setContentsMargins(14, 10, 14, 10) + h.setSpacing(14) + ic = QLabel() + ic.setAttribute(Qt.WA_TransparentForMouseEvents) + ic.setPixmap(studio_icon(kind, 30).pixmap(30, 30)) + self._icon(lambda i, l=ic: l.setPixmap(i.pixmap(30, 30)), kind, 30) + h.addWidget(ic, 0, Qt.AlignVCenter) + v = QVBoxLayout() + v.setSpacing(2) + t = QLabel() + t.setProperty("role", "strong") + t.setAttribute(Qt.WA_TransparentForMouseEvents) + self._bind(t.setText, key_t) + self._bind(b.setAccessibleName, key_t) + d = QLabel() + d.setProperty("role", "cardText") + d.setWordWrap(True) + d.setAttribute(Qt.WA_TransparentForMouseEvents) + self._bind(d.setText, key_d) + self._bind(b.setAccessibleDescription, key_d) + v.addWidget(t) + v.addWidget(d) + h.addLayout(v, 1) + b.clicked.connect(lambda _=False, w=what: self.chosen.emit(w)) + return b + + def load_thumbnails(self): + if self._worker is not None: + return + self._worker = _ThumbWorker(self) + self._worker.ready.connect(self._set_thumb) + self._worker.start() + + def _set_thumb(self, sid: str, img: QImage): + b = self._thumbs.get(sid) + if b is not None: + # Auf feste Fläche zentrieren, damit alle Beschriftungen auf einer Linie stehen + pix = QPixmap.fromImage(img).scaled(b.iconSize(), Qt.KeepAspectRatio, Qt.SmoothTransformation) + canvas = QPixmap(b.iconSize()) + canvas.fill(Qt.transparent) + p = QPainter(canvas) + p.drawPixmap((canvas.width() - pix.width()) // 2, (canvas.height() - pix.height()) // 2, pix) + p.end() + b.setIcon(QIcon(canvas)) + + def set_recent(self, paths: list[str]): + while self.recent_box.count(): + w = self.recent_box.takeAt(0).widget() + if w is not None: + w.deleteLater() + self.recent_title.setVisible(bool(paths)) + for path in paths[:5]: + b = QPushButton(os.path.basename(path)) + b.setObjectName("linkBtn") + b.setToolTip(path) + b.setCursor(Qt.PointingHandCursor) + b.clicked.connect(lambda _=False, p=path: self.recent_chosen.emit(p)) + self.recent_box.addWidget(b, 0, Qt.AlignLeft) + + def stop(self): + if self._worker is not None: + self._worker.requestInterruption() + self._worker.wait(4000) diff --git a/openstitch/ui/theme.py b/openstitch/ui/theme.py new file mode 100644 index 0000000..f794843 --- /dev/null +++ b/openstitch/ui/theme.py @@ -0,0 +1,351 @@ +"""Farbtöne und Stylesheet (Material 3, dunkel und hell) an einer Stelle. + +Widgets setzen keine Farben selbst, sondern eine Rolle: ``label.setProperty("role", "caption")``.""" +from __future__ import annotations + +import os +import tempfile +from dataclasses import dataclass + +from PySide6.QtCore import QPointF, QSettings, Qt +from PySide6.QtGui import QColor, QImage, QPainter, QPen, QPolygonF +from PySide6.QtWidgets import QApplication + + +@dataclass(frozen=True) +class Theme: + id: str + window: str + surface: str + surface_high: str + surface_top: str + outline: str + outline_soft: str + text: str + text_dim: str + text_faint: str + accent: str + on_accent: str + accent_fill: str + accent_soft: str + ok: str + warn: str + err: str + canvas: str + hud_bg: str + hud_text: str + # Akzentfarben der Symbole + icon_light: str + icon_blue: str + icon_gold: str + icon_green: str + icon_red: str + icon_purple: str + icon_cyan: str + + +DARK = Theme( + id="dark", window="#14171c", surface="#1b1f26", surface_high="#232833", surface_top="#2c323e", + outline="#3a4250", outline_soft="#2a303b", text="#e6e9ef", text_dim="#a6afbe", text_faint="#7b8493", + accent="#8ab4f8", on_accent="#0b1d3a", accent_fill="#4f86ee", accent_soft="rgba(138, 180, 248, 0.16)", + ok="#7fd19b", warn="#f2c14e", err="#f28b82", canvas="#1a1d23", + hud_bg="rgba(38, 43, 54, 0.85)", hud_text="#bac3d4", + icon_light="#e8eaed", icon_blue="#8ab4f8", icon_gold="#fdd663", icon_green="#81c995", + icon_red="#f28b82", icon_purple="#c58af9", icon_cyan="#78d9ec", +) + +LIGHT = Theme( + id="light", window="#eef0f4", surface="#ffffff", surface_high="#f4f5f8", surface_top="#e8ebf0", + outline="#cdd3dc", outline_soft="#e1e4ea", text="#1c2028", text_dim="#4f5866", text_faint="#79828f", + accent="#1a5fd0", on_accent="#ffffff", accent_fill="#1a5fd0", accent_soft="rgba(26, 95, 208, 0.12)", + ok="#1e8e4e", warn="#a86f00", err="#c5362c", canvas="#dfe2e8", + hud_bg="rgba(255, 255, 255, 0.88)", hud_text="#3d4552", + icon_light="#3a4250", icon_blue="#1a5fd0", icon_gold="#b27a00", icon_green="#1e8e4e", + icon_red="#c5362c", icon_purple="#7b3fc4", icon_cyan="#00798c", +) + +_THEMES = {"dark": DARK, "light": LIGHT} +_current = [DARK] + + +def current() -> Theme: + return _current[0] + + +def color(name: str) -> QColor: + """Farbton als QColor (auch die rgba(...)-Werte).""" + v = getattr(current(), name) + if v.startswith("rgba("): + r, g, b, a = (float(x) for x in v[5:-1].split(",")) + return QColor(int(r), int(g), int(b), int(a * 255)) + return QColor(v) + + +def _glyph(kind: str, col: str) -> str: + """Kleine Pfeile und Haken als PNG: Stylesheets können Unterelemente nur aus Dateien zeichnen.""" + folder = os.path.join(tempfile.gettempdir(), "openstitch-ui") + os.makedirs(folder, exist_ok=True) + path = os.path.join(folder, f"{kind}-{col.strip('#')}.png") + if not os.path.isfile(path): + s = 28 # doppelte Grösse: bleibt auf HiDPI-Bildschirmen scharf + img = QImage(s, s, QImage.Format_ARGB32_Premultiplied) + img.fill(Qt.transparent) + p = QPainter(img) + p.setRenderHint(QPainter.Antialiasing, True) + p.setPen(QPen(QColor(col), 3.2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) + pts = {"down": ((7, 10), (14, 18), (21, 10)), "up": ((7, 18), (14, 10), (21, 18)), + "check": ((6, 15), (12, 21), (22, 8))}[kind] + p.drawPolyline(QPolygonF([QPointF(*q) for q in pts])) + p.end() + img.save(path) + return path.replace("\\", "/") + + +def stylesheet(t: Theme | None = None) -> str: + t = t or current() + down, up = _glyph("down", t.text_dim), _glyph("up", t.text_dim) + check = _glyph("check", "#ffffff") + return f""" +QMainWindow, QDialog, QDockWidget, QWidget {{ + background-color: {t.window}; + color: {t.text}; + font-family: "Segoe UI Variable Text", "Segoe UI", "SF Pro Text", "Cantarell", "Noto Sans", sans-serif; + font-size: 9.5pt; +}} +QLabel, QCheckBox, QRadioButton {{ background: transparent; }} +QToolTip {{ + background-color: {t.surface_top}; + color: {t.text}; + border: 1px solid {t.outline}; + padding: 4px 6px; +}} +QMenuBar {{ + background-color: {t.surface}; + color: {t.text_dim}; + border-bottom: 1px solid {t.outline_soft}; + padding: 2px 6px; +}} +QMenuBar::item {{ background: transparent; padding: 4px 9px; border-radius: 6px; }} +QMenuBar::item:selected {{ background-color: {t.surface_top}; color: {t.text}; }} +QMenu {{ + background-color: {t.surface_high}; + border: 1px solid {t.outline}; + border-radius: 8px; + padding: 5px; +}} +QMenu::item {{ padding: 6px 26px 6px 12px; border-radius: 6px; }} +QMenu::item:selected {{ background-color: {t.accent_soft}; color: {t.text}; }} +QMenu::separator {{ height: 1px; background: {t.outline_soft}; margin: 5px 8px; }} +QToolBar {{ + background-color: {t.surface}; + border: none; + border-bottom: 1px solid {t.outline_soft}; + spacing: 3px; + padding: 5px 8px; +}} +QToolBar#rail {{ border-bottom: none; border-right: 1px solid {t.outline_soft}; padding: 8px 6px; spacing: 4px; }} +QToolBar::separator {{ background: {t.outline_soft}; width: 1px; height: 1px; margin: 4px 6px; }} +QToolButton {{ + background: transparent; + border: 1px solid transparent; + border-radius: 8px; + padding: 5px 9px; + color: {t.text}; +}} +QToolBar#rail QToolButton {{ padding: 7px; }} +QToolButton:hover {{ background-color: {t.surface_top}; }} +QToolButton:pressed {{ background-color: {t.outline}; }} +QToolButton:checked {{ background-color: {t.accent_soft}; color: {t.accent}; }} +QToolButton:disabled {{ color: {t.text_faint}; }} +QToolButton#accentTool {{ background-color: {t.accent_fill}; color: #ffffff; font-weight: 600; padding: 5px 14px; }} +QToolButton#accentTool:hover {{ background-color: {t.accent}; color: {t.on_accent}; }} +QPushButton {{ + background-color: {t.surface_high}; + border: 1px solid {t.outline}; + border-radius: 8px; + padding: 6px 12px; + color: {t.text}; +}} +QPushButton:hover {{ background-color: {t.surface_top}; border-color: {t.accent}; }} +QPushButton:pressed {{ background-color: {t.outline}; }} +QPushButton:checked {{ background-color: {t.accent_soft}; border-color: {t.accent}; color: {t.accent}; }} +QPushButton:disabled {{ color: {t.text_faint}; border-color: {t.outline_soft}; }} +QPushButton:focus, QToolButton:focus, QComboBox:focus, QLineEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus, +QListWidget:focus {{ border-color: {t.accent}; }} +QPushButton#primaryBtn {{ + background-color: {t.accent_fill}; + border: 1px solid {t.accent_fill}; + color: #ffffff; + font-weight: 600; +}} +QPushButton#primaryBtn:hover {{ background-color: {t.accent}; border-color: {t.accent}; color: {t.on_accent}; }} +QDialogButtonBox QPushButton:default {{ + background-color: {t.accent_fill}; + border: 1px solid {t.accent_fill}; + color: #ffffff; + font-weight: 600; +}} +QDialogButtonBox QPushButton:default:hover {{ background-color: {t.accent}; border-color: {t.accent}; color: {t.on_accent}; }} +QPushButton#iconBtn {{ padding: 5px; min-width: 22px; }} +QPushButton#startCard {{ + background-color: {t.surface}; + border: 1px solid {t.outline_soft}; + border-radius: 14px; + padding: 16px; + text-align: left; + font-size: 10.5pt; + font-weight: 600; +}} +QPushButton#startCard:hover {{ border-color: {t.accent}; background-color: {t.surface_high}; }} +QPushButton#linkBtn {{ + background: transparent; + border: none; + color: {t.accent}; + padding: 3px 2px; + text-align: left; +}} +QPushButton#linkBtn:hover {{ text-decoration: underline; }} +QDockWidget {{ font-weight: 600; color: {t.text_dim}; }} +QDockWidget::title {{ + background-color: {t.surface}; + border-bottom: 1px solid {t.outline_soft}; + padding: 7px 12px; + text-align: left; +}} +QMainWindow::separator {{ background: {t.outline_soft}; width: 1px; height: 1px; }} +QMainWindow::separator:hover {{ background: {t.accent}; }} +QSplitter::handle {{ background: {t.outline_soft}; height: 1px; }} +QFrame#card {{ + background-color: {t.surface}; + border: 1px solid {t.outline_soft}; + border-radius: 10px; +}} +QFrame#ctxBar, QFrame#simBar {{ background-color: {t.surface}; border: none; }} +QFrame#ctxBar {{ border-bottom: 1px solid {t.outline_soft}; }} +QFrame#simBar {{ border-top: 1px solid {t.outline_soft}; }} +QFrame#ctxBar QLabel, QFrame#simBar QLabel {{ background: transparent; }} +QWidget#startPage {{ background-color: {t.window}; }} +QListWidget, QLineEdit, QComboBox, QSpinBox, QDoubleSpinBox, QTextEdit, QPlainTextEdit {{ + background-color: {t.surface_high}; + border: 1px solid {t.outline_soft}; + border-radius: 8px; + padding: 4px 8px; + color: {t.text}; + selection-background-color: {t.accent_fill}; + selection-color: #ffffff; +}} +QComboBox::drop-down {{ border: none; width: 20px; }} +QComboBox::down-arrow {{ image: url({down}); width: 13px; height: 13px; }} +QSpinBox, QDoubleSpinBox {{ padding-left: 8px; padding-right: 18px; }} +QSpinBox::up-button, QDoubleSpinBox::up-button, QSpinBox::down-button, QDoubleSpinBox::down-button {{ + background: transparent; + border: none; + width: 16px; +}} +QSpinBox::up-button:hover, QDoubleSpinBox::up-button:hover, +QSpinBox::down-button:hover, QDoubleSpinBox::down-button:hover {{ background: {t.surface_top}; border-radius: 4px; }} +QSpinBox::up-arrow, QDoubleSpinBox::up-arrow {{ image: url({up}); width: 11px; height: 11px; }} +QSpinBox::down-arrow, QDoubleSpinBox::down-arrow {{ image: url({down}); width: 11px; height: 11px; }} +QCheckBox {{ spacing: 7px; }} +QCheckBox::indicator {{ + width: 16px; + height: 16px; + border: 1px solid {t.outline}; + border-radius: 5px; + background: {t.surface_high}; +}} +QCheckBox::indicator:hover {{ border-color: {t.accent}; }} +QCheckBox::indicator:checked {{ background: {t.accent_fill}; border-color: {t.accent_fill}; image: url({check}); }} +QComboBox QAbstractItemView {{ + background-color: {t.surface_high}; + border: 1px solid {t.outline}; + selection-background-color: {t.accent_soft}; + selection-color: {t.text}; +}} +QComboBox:hover, QSpinBox:hover, QDoubleSpinBox:hover, QLineEdit:hover {{ border-color: {t.outline}; }} +QListWidget {{ padding: 3px; outline: none; }} +QListWidget::item {{ padding: 5px 6px; border-radius: 6px; margin: 1px; }} +QListWidget::item:selected {{ background-color: {t.accent_soft}; color: {t.text}; }} +QListWidget::item:hover:!selected {{ background-color: {t.surface_top}; }} +QScrollArea {{ border: none; background: transparent; }} +QScrollBar:vertical {{ background: transparent; width: 8px; margin: 0; }} +QScrollBar::handle:vertical {{ background: {t.outline}; min-height: 24px; border-radius: 4px; }} +QScrollBar::handle:vertical:hover {{ background: {t.text_faint}; }} +QScrollBar:horizontal {{ background: transparent; height: 8px; margin: 0; }} +QScrollBar::handle:horizontal {{ background: {t.outline}; min-width: 24px; border-radius: 4px; }} +QScrollBar::add-line, QScrollBar::sub-line {{ width: 0; height: 0; }} +QScrollBar::add-page, QScrollBar::sub-page {{ background: transparent; }} +QSlider::groove:horizontal {{ height: 4px; background: {t.surface_top}; border-radius: 2px; }} +QSlider::sub-page:horizontal {{ background: {t.accent}; border-radius: 2px; }} +QSlider::handle:horizontal {{ + background: {t.accent}; + width: 14px; + height: 14px; + margin: -5px 0; + border-radius: 7px; +}} +QGroupBox {{ + background-color: {t.surface}; + border: 1px solid {t.outline_soft}; + border-radius: 10px; + margin-top: 12px; + padding: 12px 10px 8px 10px; + font-weight: 600; +}} +QGroupBox QLabel, QGroupBox QCheckBox {{ font-weight: 400; }} +QGroupBox::title {{ subcontrol-origin: margin; left: 12px; padding: 0 4px; color: {t.text_dim}; }} +QProgressBar {{ + background: {t.surface_top}; + border: none; + border-radius: 3px; + max-height: 6px; + text-align: center; + color: transparent; +}} +QProgressBar::chunk {{ background: {t.accent}; border-radius: 3px; }} +QTabBar::tab {{ + background: transparent; + padding: 7px 14px; + color: {t.text_dim}; + border-bottom: 2px solid transparent; +}} +QTabBar::tab:selected {{ color: {t.accent}; border-bottom-color: {t.accent}; }} +QTabWidget::pane {{ border: none; }} +QStatusBar {{ + background-color: {t.surface}; + color: {t.text_dim}; + border-top: 1px solid {t.outline_soft}; + font-size: 9pt; +}} +QStatusBar::item {{ border: none; }} +QLabel[role="caption"] {{ color: {t.text_faint}; font-size: 8pt; }} +QLabel[role="section"] {{ color: {t.text_dim}; font-weight: 600; }} +QLabel[role="muted"] {{ color: {t.text_faint}; }} +QLabel[role="title"] {{ font-size: 19pt; font-weight: 600; }} +QLabel[role="subtitle"] {{ color: {t.text_dim}; font-size: 10.5pt; }} +QLabel[role="cardText"] {{ color: {t.text_dim}; font-size: 9pt; }} +QLabel[role="strong"] {{ font-weight: 600; }} +QLabel[severity="error"] {{ color: {t.err}; font-weight: 600; }} +QLabel[severity="warning"] {{ color: {t.warn}; font-weight: 600; }} +QLabel[severity="info"] {{ color: {t.text_dim}; font-weight: 600; }} +QLabel[severity="ok"] {{ color: {t.ok}; font-weight: 600; }} +""" + + +def init_theme() -> Theme: + tid = QSettings("OpenStitch", "OpenStitchStudio").value("ui/theme", "dark", type=str) + _current[0] = _THEMES.get(tid, DARK) + return _current[0] + + +def set_theme(tid: str) -> Theme: + _current[0] = _THEMES.get(tid, DARK) + QSettings("OpenStitch", "OpenStitchStudio").setValue("ui/theme", _current[0].id) + apply_to_app() + return _current[0] + + +def apply_to_app() -> None: + app = QApplication.instance() + if app is not None: + app.setStyleSheet(stylesheet()) diff --git a/pyproject.toml b/pyproject.toml index 10b6200..2da8c23 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "openstitch" -version = "0.3.0" +version = "0.4.0" description = "OpenStitch Studio — Universal Open-Source Embroidery & Digitizing Suite (DST, PES, EXP, JEF, VP3, U01)" readme = "README.md" license = {text = "AGPL-3.0-or-later"} @@ -23,6 +23,9 @@ dependencies = [ "fonttools>=4.40", ] +[project.optional-dependencies] +dev = ["pytest", "hypothesis==6.135.0"] + [project.urls] Homepage = "https://github.com/lb2002/openstitch" Repository = "https://github.com/lb2002/openstitch" @@ -31,5 +34,9 @@ Issues = "https://github.com/lb2002/openstitch/issues" [project.scripts] openstitch = "openstitch.__main__:main" +[tool.pytest.ini_options] +# Hängt ein Test (z. B. ein ungeschlossener Dialog), zeigt das den Stack statt endlos zu warten +faulthandler_timeout = 240 + [tool.setuptools.packages.find] include = ["openstitch*"] diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..16bf7fc --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,15 @@ +"""Tests dürfen die echten Benutzereinstellungen nicht berühren.""" +import os +import sys +import tempfile + +from PySide6.QtCore import QSettings + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +if sys.platform == "win32": # die Offscreen-Ausgabe findet Windows-Schriften nicht von selbst + os.environ.setdefault("QT_QPA_FONTDIR", "C:/Windows/Fonts") + +_tmp = tempfile.TemporaryDirectory(prefix="openstitch-tests-") +QSettings.setDefaultFormat(QSettings.IniFormat) +QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, _tmp.name) +QSettings("OpenStitch", "OpenStitchStudio").setValue("ui/lang", "de") diff --git a/tests/test_bad_files.py b/tests/test_bad_files.py new file mode 100644 index 0000000..21f3f5c --- /dev/null +++ b/tests/test_bad_files.py @@ -0,0 +1,141 @@ +"""Beschädigte Dateien: Lesen darf scheitern, aber nie hängen, abstürzen oder Unsinn laden.""" +from __future__ import annotations + +import json +import math +import os +import random +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import pytest +from PySide6.QtWidgets import QApplication + +from openstitch.analysis import corpus +from openstitch.core.stitchplan import Cmd +from openstitch.engine.pro_tools import import_svg +from openstitch.io.fat12 import Fat12Image +from openstitch.io.formats import export_plan, import_file +from openstitch.io.project import load_project, save_project + +_app = QApplication.instance() or QApplication(sys.argv) +ROUNDS = int(os.environ.get("OPENSTITCH_BADFILE_ROUNDS", "12")) +FORMATS = ("dst", "exp", "pes", "pec", "jef", "vp3", "xxx", "u01", "tbf") + + +def _mutate(data: bytes, rng: random.Random) -> bytes: + b = bytearray(data) + style = rng.randrange(4) + if style == 0: + return bytes(b[: rng.randrange(len(b) + 1)]) # abgeschnitten + if style == 1: + for _ in range(max(1, len(b) // 50)): # verstreute Bitfehler + b[rng.randrange(len(b))] = rng.randrange(256) + return bytes(b) + if style == 2: + k = rng.randrange(max(len(b) - 64, 1)) # zerstörter Block + b[k:k + 64] = bytes(rng.randrange(256) for _ in range(64)) + return bytes(b) + return bytes(b[: min(512, len(b))]) * rng.randrange(1, 4) + bytes(rng.randrange(256) for _ in range(64)) + + +@pytest.mark.parametrize("ext", FORMATS) +def test_damaged_embroidery_files(ext, tmp_path): + plan = corpus.build("fill_islands").build_plan() + good = tmp_path / f"good.{ext}" + export_plan(plan, str(good)) + data = good.read_bytes() + rng = random.Random(ext) + for i in range(ROUNDS): + bad = tmp_path / f"bad{i}.{ext}" + bad.write_bytes(_mutate(data, rng)) + try: + d = import_file(str(bad)) + except Exception: # noqa: BLE001 - die Oberfläche fängt das ab und zeigt eine Meldung + continue + p = d.build_plan() + for b in p.blocks: + for s in b.stitches: + assert math.isfinite(s.x) and math.isfinite(s.y) + + +def test_damaged_project_files(tmp_path): + good = tmp_path / "good.ostitch" + save_project(corpus.build("stack_badge"), str(good)) + data = good.read_bytes() + rng = random.Random(7) + for i in range(ROUNDS * 4): + bad = tmp_path / f"bad{i}.ostitch" + bad.write_bytes(_mutate(data, rng)) + try: + load_project(str(bad)).build_plan() + except ValueError: + continue + + +@pytest.mark.parametrize("patch", [ + {"objects": [{"kind": "unknown"}]}, + {"objects": [{"kind": "fill", "thread": {"hex": "#zzzzzz"}, "geom": "POLYGON ((0 0, 1 0, 1 1, 0 0))"}]}, + {"objects": [{"kind": "fill", "thread": {"hex": "#ff0000"}, "geom": "not wkt"}]}, + {"objects": [{"kind": "fill", "thread": {"hex": "#ff0000"}, "geom": "POLYGON ((0 0, 1 0, 1 1, 0 0))", "spacing": 0}]}, + {"objects": "nope"}, + {"hoop": None}, +]) +def test_hostile_project_values_are_refused_cleanly(tmp_path, patch): + good = tmp_path / "good.ostitch" + save_project(corpus.build("fill_circle"), str(good)) + doc = json.loads(good.read_text(encoding="utf-8")) + doc.update(patch) + bad = tmp_path / "bad.ostitch" + bad.write_text(json.dumps(doc), encoding="utf-8") + try: + load_project(str(bad)).build_plan() + except ValueError as exc: + assert "bad.ostitch" in str(exc) + + +def test_damaged_svg(tmp_path): + svg = ('' + '' + 'x').encode() + rng = random.Random(3) + for i in range(ROUNDS * 6): + bad = tmp_path / f"bad{i}.svg" + bad.write_bytes(_mutate(svg, rng)) + try: + import_svg(str(bad)).build_plan() + except (ValueError, ET.ParseError, KeyError, IndexError, TypeError, OverflowError, ZeroDivisionError): + continue + + +def test_damaged_floppy_images(): + img = Fat12Image() + img.add_file("TEST.EXP", b"x" * 2000) + data = img.to_bytes() + rng = random.Random(5) + for _ in range(ROUNDS * 3): + b = bytearray(data) + for _ in range(200): + b[rng.randrange(0, 40_000)] = rng.randrange(256) + try: + im = Fat12Image(bytes(b)) + for name, _size in im.list_files(): + im.read_file(name) + im.add_file("NEW.DST", b"y" * 700) + except (ValueError, IndexError, KeyError, OSError): + continue + + +def test_import_centres_stitches_and_keeps_cmds(tmp_path): + plan = corpus.build("fill_islands").build_plan() + path = tmp_path / "a.dst" + export_plan(plan, str(path)) + d = import_file(str(path)) + p2 = d.build_plan() + x0, y0, x1, y1 = p2.bounds() + assert abs(x0 + x1) < 0.5 and abs(y0 + y1) < 0.5 + assert sum(1 for b in p2.blocks for s in b.stitches if s.cmd == Cmd.TRIM) >= plan.trim_count - 1 diff --git a/tests/test_fuzz.py b/tests/test_fuzz.py new file mode 100644 index 0000000..0135667 --- /dev/null +++ b/tests/test_fuzz.py @@ -0,0 +1,126 @@ +"""Zufallstests: Der Stich-Motor muss jede Form überstehen und dabei seine Grundregeln einhalten.""" +from __future__ import annotations + +import math +import os +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import pytest + +hypothesis = pytest.importorskip("hypothesis") +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st +from PySide6.QtWidgets import QApplication +from shapely import affinity +from shapely.geometry import LineString, MultiPoint, Point, Polygon, box +from shapely.ops import unary_union + +from openstitch.core.design import ColumnObject, Design, FillObject, RunObject, SatinObject +from openstitch.core.stitchplan import Cmd, Thread +from openstitch.engine.geom import polygons_of +from openstitch.text import TextObject + +_app = QApplication.instance() or QApplication(sys.argv) +RUNS = int(os.environ.get("OPENSTITCH_FUZZ_RUNS", "25")) +RED = Thread((200, 30, 30), "r") + +coord = st.floats(min_value=-45, max_value=45, allow_nan=False) +points = st.lists(st.tuples(coord, coord), min_size=3, max_size=14, unique=True) + + +def _shape(pts, kind: int, r: float): + """Gültige, oft unangenehme Formen: Hüllen, Blobs, gepufferte Linien, Ringe.""" + if kind == 0: + g = MultiPoint(pts).convex_hull + elif kind == 1: + g = unary_union([Point(p).buffer(r) for p in pts]) + elif kind == 2: + g = LineString(pts).buffer(r) + else: + g = MultiPoint(pts).convex_hull + g = g.difference(g.buffer(-r)) + return g if not g.is_empty and g.is_valid else None + + +def _check_plan(d: Design, geom=None): + plan = d.build_plan() + max_stitch = d.settings.max_stitch + for b in plan.blocks: + prev = None + for s in b.stitches: + assert math.isfinite(s.x) and math.isfinite(s.y) + if s.cmd == Cmd.STITCH and prev is not None: + assert math.hypot(s.x - prev[0], s.y - prev[1]) <= max_stitch + 1e-6 + if s.cmd in (Cmd.STITCH, Cmd.JUMP): + prev = (s.x, s.y) + if geom is not None and s.cmd == Cmd.STITCH: + # Niemals ausserhalb der Form sticken (Zugkompensation + Vernähen als Zugabe) + assert geom.distance(Point(s.x, s.y)) < 3.0 + return plan + + +@settings(max_examples=RUNS, deadline=None, suppress_health_check=[HealthCheck.too_slow]) +@given(points, st.integers(0, 3), st.floats(0.4, 12), st.floats(-180, 180), + st.sampled_from(["standard", "diagonal", "ziegel", "wellen", "kontur"]), st.booleans()) +def test_fill_never_escapes(pts, kind, r, angle, pattern, underlay): + g = _shape(pts, kind, r) + if g is None or not polygons_of(g): + return + d = Design(objects=[FillObject(RED, geom=g, angle=angle, pattern=pattern, underlay=underlay)]) + _check_plan(d, g) + + +@settings(max_examples=RUNS, deadline=None, suppress_health_check=[HealthCheck.too_slow]) +@given(points, st.integers(0, 3), st.floats(0.3, 8), st.booleans(), st.sampled_from( + ["auto", "mitte", "kante", "zickzack", "kante+zickzack"])) +def test_satin_never_escapes(pts, kind, r, underlay, style): + g = _shape(pts, kind, r) + if g is None or not polygons_of(g): + return + d = Design(objects=[SatinObject(RED, geom=g, underlay=underlay, underlay_style=style)]) + _check_plan(d, g) + + +@settings(max_examples=RUNS, deadline=None, suppress_health_check=[HealthCheck.too_slow]) +@given(st.lists(st.tuples(coord, coord), min_size=2, max_size=14, unique=True), st.floats(0.6, 12), + st.floats(0.2, 1.2), st.booleans()) +def test_column_on_any_line(pts, width, spacing, underlay): + line = LineString(pts) + if line.length < 0.1: + return + d = Design(objects=[ColumnObject(RED, geom=line, width=width, spacing=spacing, underlay=underlay)]) + # Gehrungen dürfen an spitzen Ecken bis 2.5 × halbe Breite hinausragen (siehe column.MAX_REACH) + _check_plan(d, line.buffer(width * 1.25)) + + +@settings(max_examples=RUNS, deadline=None, suppress_health_check=[HealthCheck.too_slow]) +@given(st.lists(st.tuples(coord, coord), min_size=2, max_size=14, unique=True), st.integers(0, 3), + st.floats(1.0, 6.0)) +def test_run_on_any_line(pts, repeats, stitch_len): + line = LineString(pts) + if line.length < 0.1: + return + _check_plan(Design(objects=[RunObject(RED, geom=line, repeats=repeats, stitch_len=stitch_len)]), line) + + +@settings(max_examples=RUNS, deadline=None, suppress_health_check=[HealthCheck.too_slow]) +@given(st.text(st.characters(codec="utf-8", exclude_categories=("Cs", "Cc")), min_size=0, max_size=12), + st.floats(1.0, 40.0)) +def test_micro_text_handles_any_string(text, height): + _check_plan(Design(objects=[TextObject(RED, text=text, height=height, font="builtin:micro")])) + + +@settings(max_examples=RUNS, deadline=None, suppress_health_check=[HealthCheck.too_slow]) +@given(points, st.floats(0.5, 2.0), st.floats(-180, 180), st.floats(-30, 30), st.floats(-30, 30), st.booleans()) +def test_transforms_keep_stitches_on_shape(pts, scale, rot, dx, dy, mirror): + g = MultiPoint(pts).convex_hull + if g.is_empty or not polygons_of(g): + return + o = FillObject(RED, geom=g) + a = math.radians(rot) + sx = -scale if mirror else scale + o.transform = (sx * math.cos(a), -scale * math.sin(a), sx * math.sin(a), scale * math.cos(a), dx, dy) + _check_plan(Design(objects=[o]), o.world_geom()) diff --git a/tests/test_i18n_coverage.py b/tests/test_i18n_coverage.py index 0ddb2bc..9da05b1 100644 --- a/tests/test_i18n_coverage.py +++ b/tests/test_i18n_coverage.py @@ -8,6 +8,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +import pytest from PySide6.QtGui import QAction from PySide6.QtWidgets import QAbstractButton, QApplication, QComboBox, QDockWidget, QGroupBox, QLabel from shapely.geometry import LineString, box @@ -159,7 +160,7 @@ def test_main_window_and_inspector_fully_translated(): idx = next(i for i in range(win.cmb_lang.count()) if win.cmb_lang.itemData(i) == "en") win.cmb_lang.setCurrentIndex(idx) assert i18n.current_lang() == "en" - assert win.lbl_hoop_strategy.text().startswith("Strategy: ") + assert win.cmb_hoop.toolTip().startswith("Strategy: ") assert "Fit to hoop" in [a.text() for a in win.left_rail.actions()] for obj in (fill, satin, run, text, None): win.canvas.selected = obj @@ -224,3 +225,74 @@ def test_dialogs_and_pdf_translated(tmp_path): assert out.stat().st_size > 1000 finally: set_lang("de") + + +# Wörter aus dem Rundgang, die GERMAN_ONLY nicht abdeckt, plus der alte Name der Design-Prüfung +TOUR_STALE = ("Weiter", "Zurück", "Loslegen", "Fertig", "Beim Start", "Rundgang", "Leinwand", "Stoff", "Doktor", + "Doctor", "Docteur") + + +def _tour_texts(tour) -> list[str]: + return _dialog_texts(tour) + [w.toolTip() for w in tour.findChildren(QAbstractButton) if w.toolTip()] + + +def test_onboarding_tour_translated_and_follows_language(): + from openstitch.ui.onboarding import InAppTourOverlay + + for st in InAppTourOverlay.STEPS: # Schlüssel in STEPS sieht der tr()-Scan nicht + for key in (st["badge"], st["title"], st["body"], st["action_label"]): + assert key is None or key in _TABLE, key + + win = MainWindow(show_tour_on_init=False, defer_starter=True) + win.show() + overlay = InAppTourOverlay(win) + overlay.start_tour() + try: + for lang in ("en", "fr", "es"): + # Wechsel über die Sprachauswahl: Beide Rundgänge müssen ohne eigenes Weiterklicken folgen + win.cmb_lang.setCurrentIndex(next(i for i in range(win.cmb_lang.count()) if win.cmb_lang.itemData(i) == lang)) + assert i18n.current_lang() == lang + assert overlay.lbl_title.text() == tr(overlay.STEPS[overlay.idx]["title"]) + for tour in (overlay,): + for i in range(len(tour.STEPS)): + tour.idx = i + tour._refresh() + texts = _tour_texts(tour) + _assert_no_german(texts, f"{type(tour).__name__} Schritt {i + 1} ({lang})") + hits = sorted({w for t in texts for w in TOUR_STALE if w in t}) + assert not hits, f"{type(tour).__name__} Schritt {i + 1} ({lang}): {hits}" + tour.idx = 0 + finally: + set_lang("de") + overlay.close_tour() + win._dirty = False + win.close() + + +EXTRA_LANGS = ("it", "pt", "nl", "pl", "tr") + + +def _placeholders(text: str) -> list[str]: + return sorted(re.findall(r"\{[a-z_0-9]*\}", text)) + + +@pytest.mark.parametrize("lang", EXTRA_LANGS) +def test_extra_languages_are_complete_and_keep_placeholders(lang): + table = i18n.extra_table(lang) + assert table, f"locales/{lang}.py fehlt" + assert set(_TABLE) - set(table) == set() + assert set(table) - set(_TABLE) == set() + for key, text in table.items(): + assert _placeholders(text) == _placeholders(_TABLE[key][1]), key + assert text.strip(), key + + +def test_unknown_key_in_extra_language_falls_back_to_english(): + i18n._cur_lang[0] = "it" + try: + with_gap = dict(i18n.extra_table("it")) + i18n._extra_cache["it"] = {} + assert tr("tb_open") == _TABLE["tb_open"][1] + i18n._extra_cache["it"] = with_gap + finally: + i18n._cur_lang[0] = "de" diff --git a/tests/test_micro_font.py b/tests/test_micro_font.py index 2a497da..cc023e8 100644 --- a/tests/test_micro_font.py +++ b/tests/test_micro_font.py @@ -145,3 +145,12 @@ def test_micro_text_save_load_roundtrip(): assert (t2.text, t2.font, t2.height, t2.letter_spacing, t2.arc_radius, t2.density) == \ ("Grüße", MICRO_SPEC, 4.0, 0.2, -40.0, 0.38) assert t2.runs() == t.runs() + + +def test_small_letters_stay_distinguishable(): + from openstitch.analysis.legibility import measure + chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + m = measure(chars, 3.0, "builtin:micro") + assert m.blocked_counters == [] # ab 3 mm bleibt jeder Innenraum offen + pairs = {frozenset(p[:2]): p[2] for p in m.worst_pairs} + assert pairs.get(frozenset("lI"), 0.0) < 0.97 # l und I dürfen nicht identisch sein diff --git a/tests/test_monkey.py b/tests/test_monkey.py new file mode 100644 index 0000000..89c721b --- /dev/null +++ b/tests/test_monkey.py @@ -0,0 +1,194 @@ +"""Affentest: zufällige Klicks, Tasten und Mausgesten auf das echte Hauptfenster. + +Keine Aktion darf eine Ausnahme auslösen, egal in welcher Reihenfolge sie kommt. Dialoge werden +gebaut, aber sofort geschlossen.""" +from __future__ import annotations + +import os +import random +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import pytest +from PySide6.QtCore import QEvent, QPoint, QPointF, Qt +from PySide6.QtGui import QAction, QDesktopServices, QKeyEvent, QMouseEvent, QWheelEvent +from PySide6.QtWidgets import ( + QApplication, + QCheckBox, + QComboBox, + QDialog, + QDoubleSpinBox, + QFileDialog, + QInputDialog, + QLineEdit, + QListWidget, + QMessageBox, + QSlider, + QSpinBox, + QToolButton, +) + +from openstitch.analysis import corpus +from openstitch.io.formats import export_plan +from openstitch.io.project import save_project +from openstitch.ui.main_window import MainWindow + +_app = QApplication.instance() or QApplication(sys.argv) +STEPS = int(os.environ.get("OPENSTITCH_MONKEY_STEPS", "150")) +SEEDS = [int(s) for s in os.environ.get("OPENSTITCH_MONKEY_SEEDS", "1").split(",")] + +# Beenden und Fensterschliessen würden den Test beenden +SKIP_TEXT = ("beenden", "quit", "exit", "quitter", "salir") + + +class _Mouse: + def __init__(self, canvas, rng): + self.c, self.rng = canvas, rng + + def _send(self, kind, x, y, button, buttons): + p = QPointF(x, y) + ev = QMouseEvent(kind, p, self.c.mapToGlobal(p.toPoint()).toPointF(), button, buttons, Qt.NoModifier) + QApplication.sendEvent(self.c, ev) + + def gesture(self): + w, h = max(self.c.width(), 50), max(self.c.height(), 50) + x, y = self.rng.randrange(w), self.rng.randrange(h) + button = self.rng.choice((Qt.LeftButton, Qt.LeftButton, Qt.LeftButton, Qt.RightButton, Qt.MiddleButton)) + self._send(QEvent.MouseButtonPress, x, y, button, button) + for _ in range(self.rng.randrange(0, 6)): + x += self.rng.randrange(-80, 80) + y += self.rng.randrange(-80, 80) + self._send(QEvent.MouseMove, x, y, Qt.NoButton, button) + self._send(QEvent.MouseButtonRelease, x, y, button, Qt.NoButton) + if self.rng.random() < 0.3: + self._send(QEvent.MouseButtonDblClick, x, y, Qt.LeftButton, Qt.LeftButton) + self._send(QEvent.MouseButtonRelease, x, y, Qt.LeftButton, Qt.NoButton) + + def wheel(self): + p = QPointF(self.rng.randrange(max(self.c.width(), 1)), self.rng.randrange(max(self.c.height(), 1))) + ev = QWheelEvent(p, self.c.mapToGlobal(p.toPoint()).toPointF(), QPoint(0, 0), + QPoint(0, self.rng.choice((-240, -120, 120, 240))), Qt.NoButton, Qt.NoModifier, + Qt.NoScrollPhase, False) + QApplication.sendEvent(self.c, ev) + + +def _safe_actions(win): + out = [] + for a in win.findChildren(QAction): + t = a.text().lower().replace("&", "") + if a.menu() is not None or a.isSeparator() or not t or any(k in t for k in SKIP_TEXT): + continue + out.append(a) + return out + + +@pytest.fixture() +def dialogs_closed(monkeypatch, tmp_path): + """Dialoge öffnen nicht wirklich; Dateiauswahl liefert abwechselnd echte Dateien oder Abbruch.""" + d = corpus.build("stack_badge") + plan = d.build_plan() + files = {".ostitch": str(tmp_path / "a.ostitch"), ".dst": str(tmp_path / "a.dst"), ".pes": str(tmp_path / "a.pes")} + save_project(d, files[".ostitch"]) + export_plan(plan, files[".dst"]) + export_plan(plan, files[".pes"]) + svg = tmp_path / "a.svg" + svg.write_text('') + png = tmp_path / "a.png" + from PySide6.QtGui import QImage + img = QImage(64, 64, QImage.Format_RGB32) + img.fill(Qt.red) + img.save(str(png)) + rng = random.Random(0) + + def pick_open(self, title, name_filter): + f = name_filter.lower() + for ext, path in ((".svg", str(svg)), (".png", str(png)), (".ostitch", files[".ostitch"]), (".dst", files[".dst"])): + if ext[1:] in f and rng.random() < 0.8: + return path + return "" + + def pick_save(self, title, default_filename, name_filter): + return "" if rng.random() < 0.4 else str(tmp_path / default_filename) + + monkeypatch.setattr(MainWindow, "_ask_open_file", pick_open) + monkeypatch.setattr(MainWindow, "_ask_save_file", pick_save) + monkeypatch.setattr(QDialog, "exec", lambda self: 0) + monkeypatch.setattr(QMessageBox, "exec", lambda self: QMessageBox.Discard) + monkeypatch.setattr(QMessageBox, "about", staticmethod(lambda *a, **k: None)) + monkeypatch.setattr(QDesktopServices, "openUrl", staticmethod(lambda *a, **k: True)) + monkeypatch.setattr(QMessageBox, "information", staticmethod(lambda *a, **k: QMessageBox.Ok)) + monkeypatch.setattr(QMessageBox, "warning", staticmethod(lambda *a, **k: QMessageBox.Ok)) + monkeypatch.setattr(QMessageBox, "critical", staticmethod(lambda *a, **k: QMessageBox.Ok)) + monkeypatch.setattr(QMessageBox, "question", staticmethod(lambda *a, **k: QMessageBox.Yes)) + monkeypatch.setattr(QInputDialog, "getDouble", staticmethod(lambda *a, **k: (120.0, True))) + monkeypatch.setattr(QInputDialog, "getItem", staticmethod(lambda *a, **k: ("100", True))) + monkeypatch.setattr(QInputDialog, "getText", staticmethod(lambda *a, **k: ("Test", True))) + return files + + +@pytest.mark.parametrize("seed", SEEDS) +def test_monkey(seed, dialogs_closed): + errors: list[str] = [] + old_hook = sys.excepthook + + def hook(tp, val, tb): + import traceback + errors.append("".join(traceback.format_exception(tp, val, tb))) + + sys.excepthook = hook + rng = random.Random(seed) + win = MainWindow(defer_starter=False, show_tour_on_init=False) + win.resize(1400, 860) + win.show() + log: list[str] = [] + try: + mouse = _Mouse(win.canvas, rng) + actions = _safe_actions(win) + for step in range(STEPS): + roll = rng.random() + if roll < 0.40: + mouse.gesture() + log.append("gesture") + elif roll < 0.45: + mouse.wheel() + log.append("wheel") + elif roll < 0.72: + a = rng.choice(actions) + log.append(f"action:{a.text()}") + a.trigger() + elif roll < 0.82: + key = rng.choice((Qt.Key_V, Qt.Key_N, Qt.Key_F, Qt.Key_S, Qt.Key_R, Qt.Key_Delete, Qt.Key_Escape, + Qt.Key_Return, Qt.Key_Backspace, Qt.Key_Left, Qt.Key_Up)) + log.append(f"key:{key}") + for kind in (QEvent.KeyPress, QEvent.KeyRelease): + QApplication.sendEvent(win.canvas, QKeyEvent(kind, key, Qt.NoModifier)) + else: + widgets = [w for cls in (QComboBox, QSpinBox, QDoubleSpinBox, QCheckBox, QListWidget, QSlider, + QLineEdit, QToolButton) for w in win.findChildren(cls) if w.isEnabled()] + w = rng.choice(widgets) + log.append(f"widget:{type(w).__name__}:{w.objectName()}") + if isinstance(w, QComboBox) and w.count(): + w.setCurrentIndex(rng.randrange(w.count())) + elif isinstance(w, (QSpinBox, QDoubleSpinBox, QSlider)): + w.setValue(rng.uniform(w.minimum(), w.maximum())) + elif isinstance(w, QCheckBox): + w.toggle() + elif isinstance(w, QListWidget) and w.count(): + w.setCurrentRow(rng.randrange(w.count())) + elif isinstance(w, QLineEdit): + w.setText(rng.choice(("", "x", "Hällo", "42", "‮abc"))) + elif isinstance(w, QToolButton) and w.isVisible(): + w.click() + QApplication.processEvents() + if step % 40 == 0: + win.wait_for_plan() + assert not errors, "\n".join(log[-12:]) + "\n" + errors[0] + win.wait_for_plan() + QApplication.processEvents() + assert not errors, "\n".join(log[-12:]) + "\n" + errors[0] + finally: + sys.excepthook = old_hook + win._dirty = False + win.close() diff --git a/tests/test_openstitch.py b/tests/test_openstitch.py index 46489d1..25c5e4c 100644 --- a/tests/test_openstitch.py +++ b/tests/test_openstitch.py @@ -15,6 +15,7 @@ from openstitch.auto.digitize import AutoParams, auto_digitize from openstitch.core.design import Design, FillObject, RunObject, SatinObject from openstitch.core.stitchplan import Thread +from openstitch.analysis import simulate_stitchout from openstitch.io.exp import exp_bytes from openstitch.io.fat12 import IMAGE_SIZE, Fat12Image from openstitch.io.formats import export_plan, import_file, verify_exported_file @@ -22,7 +23,7 @@ from openstitch.text import TextObject from openstitch.ui.main_window import MainWindow from openstitch.core.machines import MACHINE_PROFILES -from openstitch.engine.pro_tools import create_applique_objects, import_svg, run_quality_doctor +from openstitch.engine.pro_tools import create_applique_objects, import_svg from openstitch.auto.photostitch import PhotoStitchParams, generate_photostitch _app = QApplication.instance() or QApplication(sys.argv) @@ -83,8 +84,7 @@ def test_auto_digitizer_and_gui(): win = MainWindow() win.wait_for_plan() assert win.canvas.plan.stitch_count > 500 - issues = run_quality_doctor(win.canvas.design, win.canvas.plan, max_needles=10) - assert len(issues) >= 1 + assert simulate_stitchout(win.canvas.design, win.canvas.plan, needles=10).score > 0 app_objs = create_applique_objects(win.canvas.design.objects[0]) assert len(app_objs) == 3 assert len(MACHINE_PROFILES) >= 8 @@ -364,8 +364,7 @@ def test_quality_doctor_round_hoop_uses_real_radius(): from openstitch.core.design import HOOPS d = Design(objects=[FillObject(Thread((1, 1, 1)), geom=Point(0, 0).buffer(64))]) d.hoop = HOOPS[2] # rund 15 cm → Radius 75 mm; Kreis r=64 passt (Bounding-Box-Ecke wäre 90 mm) - issues = run_quality_doctor(d, d.build_plan(), max_needles=10) - assert len(issues) == 1 and issues[0].startswith("✅") + assert "outside_hoop" not in {f.code for f in simulate_stitchout(d, d.build_plan(), physics=False).findings} def test_column_object_stitches_perpendicular_and_round_trips(tmp_path): diff --git a/tests/test_parameters.py b/tests/test_parameters.py new file mode 100644 index 0000000..d1eff9e --- /dev/null +++ b/tests/test_parameters.py @@ -0,0 +1,116 @@ +"""Jeder Regler muss wirken: Mehr Dichte heisst mehr Stiche, mehr Zugausgleich heisst breiter. + +Solche Fehler sieht kein normaler Test: Die Stiche sind gültig, nur die Einstellung ist wirkungslos.""" +from __future__ import annotations + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import numpy as np +import pytest +from PySide6.QtWidgets import QApplication +from shapely.geometry import LineString, Point, box + +from openstitch.analysis.stitches import Trace +from openstitch.core.design import ColumnObject, Design, FillObject, RunObject, SatinObject +from openstitch.core.stitchplan import Thread +from openstitch.text import TextObject + +_app = QApplication.instance() or QApplication(sys.argv) +R = Thread((200, 30, 30), "r") +BAR = LineString([(-20, 0), (20, 0)]) +RING = Point(0, 0).buffer(30).difference(Point(0, 0).buffer(25)) + + +def _count(obj) -> int: + return Design(objects=[obj]).build_plan().stitch_count + + +def _falls(values: list[int], min_drop: float = 0.05): + """Jeder Schritt muss spürbar weniger Stiche ergeben.""" + for a, b in zip(values, values[1:]): + assert b < a * (1 - min_drop), values + + +def test_fill_spacing_controls_density(): + _falls([_count(FillObject(R, geom=box(-20, -20, 20, 20), spacing=s, underlay=False)) for s in (0.3, 0.4, 0.5, 0.6, 0.8)]) + + +def test_fill_stitch_length_controls_count(): + _falls([_count(FillObject(R, geom=box(-20, -20, 20, 20), stitch_len=s, underlay=False)) for s in (2, 3, 4, 5, 6)]) + + +@pytest.mark.parametrize("geom", [BAR.buffer(2.5, cap_style=2), RING], ids=["straight", "ring"]) +def test_satin_density_controls_stitches(geom): + """Lief lange Zeit ins Leere: Abstände über ~0.4 mm änderten bei Satin gar nichts.""" + _falls([_count(SatinObject(R, geom=geom, spacing=s, underlay=False)) for s in (0.3, 0.4, 0.5, 0.6, 0.8)]) + + +def test_satin_edge_spacing_is_even(): + d = Design(objects=[SatinObject(R, geom=BAR.buffer(2.0, cap_style=2), spacing=0.5, underlay=False, pull_comp=0.0)]) + t = Trace.of(d.build_plan()) + mid = np.abs(t.x) < 12 + edge = np.sort(t.x[mid & (t.y > 1.5)]) + gaps = np.diff(edge) + gaps = gaps[gaps > 0.02] + assert abs(np.median(gaps) - 0.5) < 0.06 + assert gaps.std() < 0.08 + + +def test_column_density_controls_stitches(): + _falls([_count(ColumnObject(R, geom=BAR, width=4, spacing=s, underlay=False)) for s in (0.3, 0.4, 0.5, 0.6, 0.8)]) + + +def test_run_stitch_length_controls_count(): + _falls([_count(RunObject(R, geom=BAR, stitch_len=s)) for s in (1, 2, 3, 4)]) + + +@pytest.mark.parametrize("font", ["builtin:micro", None], ids=["micro", "truetype"]) +def test_text_density_controls_stitches(font): + kw = {"font": font} if font else {} + _falls([_count(TextObject(R, text="AB", height=12, density=s, **kw)) for s in (0.3, 0.4, 0.5, 0.6)]) + + +@pytest.mark.parametrize("obj", [ + lambda pc: FillObject(R, geom=box(-20, -20, 20, 20), pull_comp=pc, angle=0, underlay=False), + lambda pc: SatinObject(R, geom=BAR.buffer(2.0, cap_style=2), pull_comp=pc, underlay=False), + lambda pc: ColumnObject(R, geom=BAR, width=4, pull_comp=pc, underlay=False), +], ids=["fill", "satin", "column"]) +def test_pull_compensation_widens_the_stitched_shape(obj): + sizes = [] + for pc in (0.0, 0.3, 0.6): + x0, y0, x1, y1 = Design(objects=[obj(pc)]).build_plan().bounds() + # Füllung wächst in Stichrichtung (Winkel 0 = x), Satin quer zur Säule + sizes.append(x1 - x0 if isinstance(obj(0.0), FillObject) else y1 - y0) + assert sizes[0] < sizes[1] < sizes[2] + + +def test_column_width_is_what_was_asked_for(): + for w in (1.0, 2.0, 4.0, 8.0): + x0, y0, x1, y1 = Design(objects=[ColumnObject(R, geom=BAR, width=w, underlay=False, pull_comp=0)]).build_plan().bounds() + assert abs((y1 - y0) - w) < 0.05 + + +def test_angle_turns_fill_rows(): + def direction(angle): + d = Design(objects=[FillObject(R, geom=box(-20, -20, 20, 20), angle=angle, underlay=False, pull_comp=0)]) + seg, _ = Trace.of(d.build_plan()).sewn_segments() + dx, dy = seg[:, 2] - seg[:, 0], seg[:, 3] - seg[:, 1] + long_ = np.hypot(dx, dy) > 2 + return np.median(np.degrees(np.arctan2(dy[long_], dx[long_])) % 180) + assert abs(direction(0) - 0) < 3 or abs(direction(0) - 180) < 3 + assert abs(direction(90) - 90) < 3 + + +def test_underlay_adds_stitches_everywhere(): + for mk in (lambda u: FillObject(R, geom=box(-15, -15, 15, 15), underlay=u), + lambda u: SatinObject(R, geom=BAR.buffer(2.5, cap_style=2), underlay=u), + lambda u: ColumnObject(R, geom=BAR, width=4, underlay=u)): + assert _count(mk(True)) > _count(mk(False)) + + +def test_triple_run_sews_each_stitch_three_times(): + locks = 8 # Vernähstiche an beiden Enden werden nicht verdreifacht + assert 2.7 < (_count(RunObject(R, geom=BAR, repeats=1)) - locks) / (_count(RunObject(R, geom=BAR, repeats=0)) - locks) < 3.3 diff --git a/tests/test_stitchout.py b/tests/test_stitchout.py new file mode 100644 index 0000000..9026757 --- /dev/null +++ b/tests/test_stitchout.py @@ -0,0 +1,263 @@ +"""Virtueller Probestick: Jeder Detektor muss absichtlich kaputte Stiche finden und gute in Ruhe lassen.""" +from __future__ import annotations + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import numpy as np +import pytest +from PySide6.QtWidgets import QApplication +from shapely.geometry import LineString, Point, box + +from openstitch.analysis import DEFAULT_FABRIC, fabric_by_id, simulate_stitchout +from openstitch.analysis import corpus +from openstitch.analysis.legibility import measure +from openstitch.analysis.roundtrip import MACHINE_FORMATS, check_format +from openstitch.analysis.stitches import Trace +from openstitch.core.design import Design, FillObject, SatinObject +from openstitch.core.stitchplan import Cmd, ColorBlock, Stitch, StitchPlan, Thread +from openstitch.io.formats import export_plan +from openstitch.engine.density_guard import optimize_stitches_for_melco +from openstitch.engine.satin import _zigzag + +_app = QApplication.instance() or QApplication(sys.argv) +RED = Thread((200, 30, 30), "r") + + +def _plan(*coords, cmds=None) -> StitchPlan: + st = [Stitch(x, y, Cmd.JUMP if i == 0 else Cmd.STITCH) for i, (x, y) in enumerate(coords)] + for i, c in (cmds or {}).items(): + st[i].cmd = c + return StitchPlan([ColorBlock(RED, st)]) + + +def _locked_line(n=30, step=2.0): + """Sauberer Lauf mit Vernähung an beiden Enden.""" + pts = [(0, 0), (0.6, 0), (0, 0), (0.6, 0), (0, 0)] + pts += [(step * i, 0) for i in range(1, n)] + e = pts[-1] + pts += [(e[0] - 0.6, 0), e, (e[0] - 0.6, 0), e] + return pts + + +def _codes(plan, **kw): + return {f.code for f in simulate_stitchout(None, plan, physics=False, **kw).findings} + + +def test_clean_run_has_no_findings(): + assert _codes(_plan(*_locked_line())) == set() + + +def test_detects_short_stitches(): + pts = _locked_line() + pts[8:8] = [(pts[7][0] + 0.1 * i, 0) for i in range(1, 12)] + assert "short_stitch" in _codes(_plan(*pts)) + + +def test_detects_stitch_over_machine_limit(): + assert "over_max_stitch" in _codes(_plan(*_locked_line(step=13.0))) + + +def test_detects_long_floats(): + assert "long_float" in _codes(_plan(*_locked_line(step=9.0))) + + +def test_detects_missing_lock_stitches(): + assert "no_lock" in _codes(_plan(*[(i * 2.0, 0) for i in range(20)])) + + +def test_detects_runs_too_short_to_hold(): + plan = _plan((0, 0), (1, 0), (2, 0)) + assert "orphan_run" in _codes(plan) + + +def test_detects_jump_without_trim(): + pts = _locked_line(10) + n = len(pts) + pts += [(40, 0)] + [(40 + i * 2.0, 0) for i in range(1, 8)] + assert "untrimmed_jump" in _codes(_plan(*pts, cmds={n: Cmd.JUMP})) + + +def test_detects_needle_pileup(): + pts = _locked_line() + pts[8:8] = [(pts[7][0] + (i % 2) * 0.05, 0.03) for i in range(14)] + assert "needle_pileup" in _codes(_plan(*pts)) + + +def test_detects_overdense_area(): + d = Design(objects=[FillObject(RED, geom=box(-8, -8, 8, 8), spacing=0.25, underlay=True) for _ in range(5)]) + r = simulate_stitchout(d, d.build_plan(), physics=False) + assert "too_dense" in {f.code for f in r.findings} + + +def test_detects_design_outside_hoop(): + d = Design(objects=[FillObject(RED, geom=box(-90, -20, 90, 20))]) + r = simulate_stitchout(d, d.build_plan(), physics=False) + assert "outside_hoop" in {f.code for f in r.findings} and not r.ok + + +def test_detects_uncovered_area(): + d = Design(objects=[FillObject(RED, geom=box(-20, -20, 20, 20), spacing=0.4)]) + plan = d.build_plan() + # Die Form ist nachträglich gewachsen: ein grosser Teil davon hat keine Stiche + d.objects[0].geom = box(-30, -30, 30, 30) + r = simulate_stitchout(d, plan, physics=False) + assert "low_coverage" in {f.code for f in r.findings} + + +def test_pull_shrinks_satin_more_on_stretchy_fabric(): + d = Design(objects=[SatinObject(RED, geom=LineString([(-15, 0), (15, 0)]).buffer(2.0, cap_style=2), + pull_comp=0.0, underlay=False)]) + plan = d.build_plan() + t = Trace.of(plan) + + def width(fabric): + p = simulate_stitchout(None, plan, fabric).pull + y, x = t.y[p.idx] + p.dy, t.x[p.idx] + m = np.abs(x) < 8 + return np.percentile(y[m], 99) - np.percentile(y[m], 1) + + woven, jersey, denim = width(fabric_by_id("woven")), width(fabric_by_id("jersey")), width(fabric_by_id("denim")) + assert 3.55 < woven < 3.85 # Erfahrungswert: ca. 0.3 mm Einzug bei 4 mm Satin + assert jersey < woven < denim + + +def test_pull_comp_counteracts_pull(): + def edge_error(pc): + d = Design(objects=[SatinObject(RED, geom=LineString([(-15, 0), (15, 0)]).buffer(2.0, cap_style=2), + pull_comp=pc, underlay=False)]) + plan = d.build_plan() + t = Trace.of(plan) + p = simulate_stitchout(None, plan).pull + y = t.y[p.idx] + p.dy + m = np.abs(t.x[p.idx]) < 8 + return abs((np.percentile(y[m], 99) - np.percentile(y[m], 1)) - 4.0) + + assert edge_error(0.15) < edge_error(0.0) + + +def test_later_stitching_shifts_earlier_objects(): + """Füllung zuerst, Kontur danach: die Füllung wandert, die Kontur trifft sie nicht mehr exakt.""" + f = FillObject(RED, geom=box(-30, -30, 30, 30), pull_comp=0.0) + s = SatinObject(Thread((20, 20, 200), "b"), geom=box(-31.5, -31.5, 31.5, 31.5).difference(box(-28.5, -28.5, 28.5, 28.5))) + d = Design(objects=[f, s]) + r = simulate_stitchout(d, d.build_plan(), fabric_by_id("jersey")) + assert r.metrics["misregistration"] > 0.1 + + +def test_every_corpus_design_builds_and_exports_cleanly(): + for name in ("stack_badge", "text_micro_25", "fill_islands", "satin_curve", "many_colors"): + plan = corpus.build(name).build_plan() + for ext in MACHINE_FORMATS: + r = check_format(plan, ext) + assert r.ok, (name, ext, r.problems) + + +@pytest.mark.parametrize("name", ["fill_circle", "satin_straight", "column_arc", "text_micro_25", "run_triple"]) +def test_corpus_scores_stay_high(name): + d = corpus.build(name) + r = simulate_stitchout(d, d.build_plan(), needles=d.settings.needles) + assert r.ok and r.score >= 90, [(f.code, f.count) for f in r.findings] + + +def test_split_satin_respects_max_stitch(): + d = corpus.build("satin_wide") + plan = d.build_plan() + seg, _ = Trace.of(plan).sewn_segments() + assert np.hypot(seg[:, 2] - seg[:, 0], seg[:, 3] - seg[:, 1]).max() <= 7.05 + + +def test_density_guard_never_creates_long_stitches(): + """Mehrfach abgefahrene Linie: Überspringen gesättigter Zellen darf keinen Riesenstich erzeugen.""" + pts = [Stitch(0, 0.25 + i * 1.0, Cmd.STITCH) for i in range(13)] * 3 + st = [Stitch(0, 0, Cmd.JUMP)] + pts + out = [s for s in optimize_stitches_for_melco(st) if s.cmd == Cmd.STITCH] + assert max(abs(a.y - b.y) for a, b in zip(out, out[1:])) < 13.0 + + +@pytest.mark.parametrize("name", ["Grün", "Weiß", "Çelik ı", "Żółty", "緑"]) +def test_accented_thread_names_do_not_corrupt_files(name): + """VP3: pyembroidery zählt Zeichen statt Bytes, ein einziges ü machte die Datei unlesbar.""" + d = Design(objects=[FillObject(Thread((30, 150, 70), name, name, name), geom=box(-10, -10, 10, 10))]) + plan = d.build_plan() + for ext in MACHINE_FORMATS: + r = check_format(plan, ext) + assert r.ok, (ext, r.problems) + + +def test_hidden_travel_keeps_the_corner_at_the_ring_start(): + """Der Weg entlang einer Kante darf die Ecke am Ringanfang nicht abschneiden (Stich quer durchs Loch).""" + from shapely.geometry import LinearRing, Point as P + from openstitch.engine.geom import path_along_ring + ring = LinearRing([(0, 0), (20, 0), (20, 20), (0, 20)]) # Start in der Ecke (0, 0) + for a, b in (((0, 5), (5, 0)), ((5, 0), (0, 5))): + path = path_along_ring(ring, a, b) + assert (0.0, 0.0) in [tuple(p) for p in path] + assert all(ring.distance(P(p)) < 1e-6 for p in path) + + +def test_fill_on_thin_triangle_ring_does_not_cross_the_hole(): + from shapely.geometry import MultiPoint, Point as P + g = MultiPoint([(11.0, 0.0), (16.0, 16.0), (-27.0, 0.0)]).convex_hull + g = g.difference(g.buffer(-1.5)) + d = Design(objects=[FillObject(RED, geom=g, angle=0)]) + t = Trace.of(d.build_plan()) + pts = [P(x, y) for x, y, c in zip(t.x, t.y, t.cmd) if c == Cmd.STITCH] + assert max(g.distance(p) for p in pts) < 1.0 + + +def test_calibration_makes_the_model_match_the_measurement(): + from openstitch.analysis.calibrate import BAR_WIDTH, calibration_design, fit_scale, predicted_shrink + from openstitch.core.fabric import set_pull_scale, pull_scale + fab = fabric_by_id("jersey") + measured_shrink = 0.9 + scale = fit_scale("jersey", BAR_WIDTH - measured_shrink) + assert abs(scale * predicted_shrink(fab) - measured_shrink) < 0.01 + plan = calibration_design("jersey").build_plan() + t = Trace.of(plan) + set_pull_scale("jersey", scale) + try: + p = simulate_stitchout(None, plan, fab).pull + y = t.y[p.idx] + p.dy + m = np.abs(t.x[p.idx]) < 10 + width = np.percentile(y[m], 99) - np.percentile(y[m], 1) + assert abs(width - (BAR_WIDTH - measured_shrink)) < 0.1 # Modell trifft jetzt den Messwert + finally: + set_pull_scale("jersey", None) + assert pull_scale("jersey") == 1.0 + + +def test_calibration_scales_pull_compensation(): + from openstitch.core.fabric import set_pull_scale + def height(scale): + d = Design(fabric="jersey", objects=[SatinObject(RED, geom=LineString([(-9, 0), (9, 0)]).buffer(2, cap_style=2), pull_comp=0.2, underlay=False)]) + set_pull_scale("jersey", scale) + try: + b = d.build_plan().bounds() + finally: + set_pull_scale("jersey", None) + return b[3] - b[1] + assert height(2.0) > height(None) + 0.5 + + +def test_fixed_rules_and_estimates_are_labelled(): + from openstitch.analysis.report import Finding + assert Finding("registration_gap", "warning").is_estimate + assert not Finding("over_max_stitch", "error").is_estimate + + +def test_legibility_measure_separates_distinct_letters(): + m = measure("OIX", 6.0, "builtin:micro") + assert m.worst_pairs and m.worst_pairs[0][2] < 0.95 + + +def test_analysis_runs_on_imported_files(tmp_path): + from openstitch.io.formats import import_file + plan = corpus.build("stack_badge").build_plan() + path = tmp_path / "x.dst" + export_plan(plan, str(path)) + d = import_file(str(path)) + r = simulate_stitchout(d, d.build_plan()) + assert r.score > 0 and r.metrics["stitches"] > 1000 diff --git a/tests/test_ui_flows.py b/tests/test_ui_flows.py new file mode 100644 index 0000000..683e004 --- /dev/null +++ b/tests/test_ui_flows.py @@ -0,0 +1,334 @@ +"""Neue Oberfläche: Startseite, Design-Prüfung, Stoff, Sicherung, Fenstergrösse.""" +from __future__ import annotations + +import os +import sys +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import pytest +from PySide6.QtCore import QSettings +from PySide6.QtWidgets import QApplication, QMessageBox +from shapely.geometry import LineString, box + +from openstitch.analysis import FABRICS, corpus, simulate_stitchout +from openstitch.core.design import Design, FillObject, SatinObject +from openstitch.core.stitchplan import Cmd, Thread +from openstitch.io.project import load_project, save_project +from openstitch.samples import SAMPLES +from openstitch.ui import theme +from openstitch.ui.main_window import MainWindow + +_app = QApplication.instance() or QApplication(sys.argv) +RED = Thread((200, 30, 30), "r") +BLUE = Thread((30, 30, 200), "b") + + +@pytest.fixture() +def win(): + w = MainWindow(defer_starter=True, show_tour_on_init=False) + w.show() + yield w + w._dirty = False + w.close() + + +def _pump(cond, timeout=30.0): + end = time.time() + timeout + while time.time() < end and not cond(): + QApplication.processEvents() + time.sleep(0.01) + assert cond() + + +def test_window_fits_small_laptops_in_every_language(win): + from openstitch.i18n import LANGUAGES, set_lang + try: + for code, _ in LANGUAGES: + win.cmb_lang.setCurrentIndex(win.cmb_lang.findData(code)) + QApplication.processEvents() + hint = win.minimumSizeHint() + assert hint.width() <= 1280, (code, hint.width()) + assert hint.height() <= 700, (code, hint.height()) + finally: + win.cmb_lang.setCurrentIndex(win.cmb_lang.findData("de")) + set_lang("de") + + +def test_start_page_offers_samples_and_hides_editor(win): + win.show_start_page() + assert win.stack.currentWidget() is win.start_page + assert not win.left_dock.isVisible() + win._open_sample("heart") + assert win.stack.currentWidget() is win.editor_page + assert win.left_dock.isVisible() + win.wait_for_plan() + assert win.canvas.plan.stitch_count > 500 + + +@pytest.mark.parametrize("sid", [s for s, _k, _f in SAMPLES]) +def test_samples_are_good_examples(sid): + d = next(f for s, _k, f in SAMPLES if s == sid)() + r = simulate_stitchout(d, d.build_plan(), needles=d.settings.needles) + assert r.ok and r.score >= 70, [(f.code, f.count) for f in r.findings] + + +def test_recent_files_and_open_path(win, tmp_path): + p = tmp_path / "a.ostitch" + save_project(corpus.build("fill_circle"), str(p)) + win.open_path(str(p)) + assert win._recent_files()[0] == str(p) + assert len(win.canvas.design.objects) == 1 + win._fill_recent_menu() + assert win.m_recent.actions() + + +def test_missing_recent_file_is_forgotten(win, tmp_path, monkeypatch): + monkeypatch.setattr(QMessageBox, "warning", staticmethod(lambda *a, **k: QMessageBox.Ok)) + gone = str(tmp_path / "gone.ostitch") + QSettings("OpenStitch", "OpenStitchStudio").setValue("recent/files", [gone]) + win.open_path(gone) + assert gone not in win._recent_files() + + +def test_autosave_recovers_after_crash(win, monkeypatch): + win._dirty = True + win.canvas.design.name = "Rettung" + win._autosave() + assert os.path.isfile(win._autosave_path()) + monkeypatch.setattr(QMessageBox, "question", staticmethod(lambda *a, **k: QMessageBox.Yes)) + win._dirty = False + assert win._offer_recovery() + assert win.canvas.design.name == "Rettung" + win._clear_autosave() + assert not win._offer_recovery() + + +def test_clean_exit_leaves_no_autosave(): + w = MainWindow(defer_starter=False, show_tour_on_init=False) + w.show() + w._dirty = True + w._autosave() + w._dirty = False + path = w._autosave_path() + assert os.path.isfile(path) + w.close() + assert not os.path.isfile(path) + + +def test_fabric_changes_stitching_and_is_saved(win, tmp_path): + d = Design(objects=[SatinObject(RED, geom=LineString([(-20, 0), (20, 0)]).buffer(2.5, cap_style=2))]) + win.set_design(d, reset_undo=True) + win.wait_for_plan() + woven = win.canvas.plan.stitch_count + win.cmb_fabric.setCurrentIndex(win.cmb_fabric.findData("jersey")) + win.wait_for_plan() + assert d.fabric == "jersey" + assert win.canvas.plan.stitch_count < woven # lockerer auf dehnbarem Stoff + path = tmp_path / "f.ostitch" + save_project(d, str(path)) + assert load_project(str(path)).fabric == "jersey" + + +def test_every_fabric_builds(): + for fab in FABRICS: + d = corpus.build("stack_badge") + d.fabric = fab.id + r = simulate_stitchout(d, d.build_plan()) + assert r.metrics["stitches"] > 1000 + assert fab.id == d.fabric + + +def test_hidden_stitches_are_removed_only_when_fully_covered(): + under = FillObject(RED, geom=box(-30, -30, 30, 30)) + over = FillObject(BLUE, geom=box(-15, -15, 15, 15), angle=0) + d = Design(objects=[under, over]) + with_knockout = d.build_plan() + pts = [(s.x, s.y) for s in with_knockout.blocks[0].stitches if s.cmd == Cmd.STITCH] + # Mitte frei, aber der Rand läuft 1 mm unter das obere Objekt: sonst entstünden Lücken + assert not any(abs(x) < 13.5 and abs(y) < 13.5 for x, y in pts) + assert any(abs(x) < 14.8 and abs(y) < 14.8 for x, y in pts) + under.knockout = False + without = d.build_plan() + assert without.stitch_count > with_knockout.stitch_count * 1.1 + + +def test_thin_lettering_keeps_its_fill_underneath(): + from openstitch.text import TextObject + fill = FillObject(RED, geom=box(-30, -10, 30, 10)) + d = Design(objects=[fill, TextObject(BLUE, text="ABC", height=7.0, font="builtin:micro")]) + d.build_plan() + assert fill._hidden is None + + +def test_check_dialog_runs_and_fixes(win): + d = Design(objects=[FillObject(RED, geom=box(-90, -20, 90, 20))]) + win.set_design(d, reset_undo=True) + win.action_quality_doctor() + dlg = win._check_dlg + _pump(lambda: dlg._report is not None and not dlg._worker.isRunning()) + QApplication.processEvents() + codes = {f.code for f in dlg._report.findings} + assert "outside_hoop" in codes and not dlg._report.ok + assert dlg.ring.score is not None + assert win.fix_for("outside_hoop") is not None + win.fix_for("outside_hoop")() + win.wait_for_plan() + dlg.start() + _pump(lambda: not dlg._worker.isRunning()) + QApplication.processEvents() + assert "outside_hoop" not in {f.code for f in dlg._report.findings} + win.canvas.show_spots([(1.0, 2.0)]) + assert win.canvas._spots + + +def test_export_dialog_writes_and_verifies(win, tmp_path, monkeypatch): + from openstitch.ui import export_dialog as ed + monkeypatch.setattr(ed, "removable_drives", lambda: [(str(tmp_path), "STICK")]) + win.set_design(corpus.build("fill_islands"), reset_undo=True) + win.wait_for_plan() + dlg = ed.ExportDialog(win) + assert dlg.cmb_where.currentData() == str(tmp_path) # USB-Stick zuerst + assert dlg.cmb_format.currentData() == win.cmb_machine.currentData().native_ext + dlg.ed_name.setText("Müller: Logo/2") + dlg.cb_short.setChecked(True) + dlg.save() + assert dlg.saved_path and os.path.isfile(dlg.saved_path) + assert os.path.basename(dlg.saved_path) == "MLLERLOG." + dlg.cmb_format.currentData().upper() + assert dlg.lbl_result.property("severity") == "ok" + dlg.cb_short.setChecked(False) + assert "Logo_2" in dlg.target_path().replace("Müller_ ", "") + dlg.close() + + +def test_export_dialog_never_overwrites_silently(win, tmp_path, monkeypatch): + from openstitch.ui import export_dialog as ed + monkeypatch.setattr(ed, "removable_drives", lambda: [(str(tmp_path), "STICK")]) + win.set_design(corpus.build("fill_islands"), reset_undo=True) + win.wait_for_plan() + dlg = ed.ExportDialog(win) + existing = Path(dlg.target_path()) + existing.write_bytes(b"wertvoll") + monkeypatch.setattr(QMessageBox, "question", staticmethod(lambda *a, **k: QMessageBox.No)) + dlg.save() + assert existing.read_bytes() == b"wertvoll" and dlg.saved_path is None + monkeypatch.setattr(QMessageBox, "question", staticmethod(lambda *a, **k: QMessageBox.Yes)) + # Schlägt das Schreiben fehl, bleibt die alte Datei erhalten und kein Rest liegt herum + monkeypatch.setattr(ed, "verify_exported_file", lambda *a, **k: (_ for _ in ()).throw(ValueError("kaputt"))) + dlg.save() + assert existing.read_bytes() == b"wertvoll" and len(list(tmp_path.iterdir())) == 1 + monkeypatch.undo() + monkeypatch.setattr(QMessageBox, "question", staticmethod(lambda *a, **k: QMessageBox.Yes)) + dlg.save() + assert existing.read_bytes() != b"wertvoll" and dlg.saved_path == str(existing) + dlg.close() + + +def test_export_dialog_reports_write_errors(win, tmp_path, monkeypatch): + from openstitch.ui import export_dialog as ed + monkeypatch.setattr(ed, "removable_drives", lambda: [(str(tmp_path / "nicht-da"), "WEG")]) + win.set_design(corpus.build("fill_islands"), reset_undo=True) + win.wait_for_plan() + dlg = ed.ExportDialog(win) + dlg.save() + assert dlg.saved_path is None + assert dlg.lbl_result.property("severity") == "error" + dlg.close() + + +def test_text_dialog_allows_small_lettering_and_suggests_micro(win): + from openstitch.fonts_micro import MICRO_SPEC + from openstitch.ui.dialogs import TextDialog + dlg = TextDialog(win.canvas.active_thread, parent=win) + dlg.show() + dlg.sp_height.setValue(2.5) + assert dlg.sp_height.value() == 2.5 # 2.5 mm ist das Versprechen der Micro-Schrift + dlg.cmb_font.setCurrentIndex(max(0, dlg.cmb_font.findText("Arial"))) + if dlg.cmb_font.currentData() != MICRO_SPEC: + assert dlg.lbl_font_tip.isVisible() + dlg._use_micro() + assert dlg.cmb_font.currentData() == MICRO_SPEC and not dlg.lbl_font_tip.isVisible() + dlg.ed_text.setText("Test") + assert dlg.preview.obj is not None + dlg.grab() + dlg._apply() + assert dlg.created_object.height == 2.5 + dlg.close() + + +def test_crash_report_is_written(win, monkeypatch): + from openstitch.ui import crash + shown = [] + monkeypatch.setattr(QMessageBox, "critical", staticmethod(lambda *a, **k: shown.append(a))) + old = sys.excepthook + try: + crash.install(win) + try: + raise RuntimeError("Testfehler") + except RuntimeError: + tp, val, tb = sys.exc_info() + sys.excepthook(tp, val, tb) + assert shown + with open(crash.log_path(), encoding="utf-8") as f: + assert "Testfehler" in f.read() + finally: + sys.excepthook = old + + +def test_small_outline_text_is_flagged_but_micro_is_not(): + from openstitch.text import TextObject + small = TextObject(RED, text="Ab", height=3.0) + micro = TextObject(RED, text="Ab", height=3.0, font="builtin:micro") + codes = lambda o: {f.code for f in simulate_stitchout(Design(objects=[o]), Design(objects=[o]).build_plan(), physics=False).findings} + assert "small_text" in codes(small) + assert "small_text" not in codes(micro) + + +def test_calibration_dialog_stores_measurement(win): + from openstitch.core.fabric import pull_scale, set_pull_scale + from openstitch.ui.check_dialog import CalibrationDialog + win.cmb_fabric.setCurrentIndex(win.cmb_fabric.findData("fleece")) + win._dirty = False # sonst fragt das Laden des Testbalkens nach ungespeicherter Arbeit + dlg = CalibrationDialog(win) + dlg.load_patch() + win.wait_for_plan() + assert win.canvas.design.objects[0].pull_comp == 0.0 + dlg.sp_width.setValue(4.2) + dlg.apply() + assert pull_scale("fleece") != 1.0 + assert QSettings("OpenStitch", "OpenStitchStudio").value("calibration/fleece") is not None + fresh = MainWindow(defer_starter=True, show_tour_on_init=False) # bleibt über Neustarts erhalten + assert pull_scale("fleece") != 1.0 + fresh.close() + dlg.reset() + assert pull_scale("fleece") == 1.0 + dlg.close() + + +def test_packaged_app_selftest_passes(tmp_path, monkeypatch): + from openstitch import selftest + monkeypatch.chdir(tmp_path) + assert selftest.run() == 0 + report = (tmp_path / selftest.REPORT_FILE).read_text(encoding="utf-8") + assert "languages" in report and "FAIL" not in report + + +def test_all_finding_codes_have_texts(): + from openstitch.i18n import _TABLE + for code in ("short_stitch", "over_max_stitch", "long_float", "no_lock", "orphan_run", "untrimmed_jump", + "needle_pileup", "too_dense", "outside_hoop", "low_coverage", "too_many_colors", + "registration_gap", "puckering", "small_text"): + assert f"chk_{code}_t" in _TABLE and f"chk_{code}_d" in _TABLE + + +@pytest.mark.parametrize("tid", ["dark", "light"]) +def test_themes_switch_and_stay_readable(win, tid): + win.set_theme(tid) + try: + assert theme.current().id == tid + assert "QMainWindow" in QApplication.instance().styleSheet() + win.grab() + finally: + win.set_theme("dark")