Linter for inkscape extension

This commit is contained in:
Alex committed 2026-10-24 21:38:03 +02:00
1 parent 00e9ba3434
commit 247ecc3f5a
17 files changed
+1002 -249

No files matched your search

+50 -41
View File
@@ -1,16 +1,21 @@
#!/usr/bin/env python3
# coding=utf-8
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 Alex
"""
Extension Inkscape : remplit les formes selectionnees d'un labyrinthe de
Turing (motif « Dog Bandana »), trace en lignes centrales a bouts ronds.
Inkscape extension: fills the selected shapes with a Turing maze ("Dog
Bandana" pattern), drawn as round-capped center lines.
Le motif est calcule par l'equation de Swift-Hohenberg sur une grille qui
couvre la forme, puis reduit a la ligne centrale de chaque bande : un trait
par « vermicelle », pret pour la gravure laser en mode ligne.
The pattern is computed with the Swift-Hohenberg equation on a grid covering
the shape, then reduced to the center line of each band: one stroke per
"noodle", ready for line engraving on a laser cutter.
La logique vit dans `dog_bandana_core`, sans dependance a inkex.
The logic lives in `dog_bandana_core`, which does not depend on inkex.
"""
import builtins
import ctypes
import locale
import os
import sys
@@ -19,60 +24,60 @@ from inkex.bezier import cspsubdiv
from inkex.localization import localize
from inkex.units import convert_unit
# L'extension vit dans son propre sous-dossier des extensions Inkscape, qui
# n'est pas forcement dans sys.path : on l'y ajoute pour trouver dog_bandana_core.
# The extension lives in its own subfolder of Inkscape's extensions, which is
# not necessarily in sys.path: add it so that dog_bandana_core can be found.
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# pylint: disable-next=wrong-import-position
from dog_bandana_core import (MAX_PIXELS, grid_pixels, laser_order, # noqa: E402
parse_color, polylines_to_d, turing_pattern)
def use_system_language():
"""Renseigne LANGUAGE avec la langue du systeme si rien ne la fixe.
"""Set LANGUAGE to the system language if nothing sets it already.
Sous Windows, Inkscape regle sur « langue du systeme » ne transmet aucune
variable de langue au script : gettext retomberait sur l'anglais alors que
la boite de dialogue, traduite par Inkscape lui-meme, est dans la langue
de l'utilisateur.
On Windows, Inkscape set to "system language" passes no language
variable to the script: gettext would fall back to English while the
dialog, translated by Inkscape itself, is in the user's language.
"""
if any(os.environ.get(name) for name in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG")):
return
try:
import ctypes
import locale
language = locale.windows_locale.get(
ctypes.windll.kernel32.GetUserDefaultUILanguage())
except Exception: # pylint: disable=broad-except
return # hors Windows : LANG est toujours defini
return # outside Windows, LANG is always set
if language:
os.environ["LANGUAGE"] = language
# Installe _() dans les builtins : catalogue « dogbandana » de la langue
# de l'interface (Inkscape transmet domaine et dossier par l'environnement),
# textes anglais d'origine sinon.
# Installs _() in the builtins: "dogbandana" catalog of the interface
# language (Inkscape passes domain and folder through the environment),
# original English texts otherwise.
use_system_language()
localize()
# Explicit module-level name for the function localize() installed, so that
# linters do not report _ as undefined.
_ = builtins.__dict__["_"]
# Elements qui delimitent une surface a remplir.
# Elements that delimit an area to fill.
SHAPES = (inkex.PathElement, inkex.Rectangle, inkex.Circle, inkex.Ellipse,
inkex.Polygon)
def uu_per_mm(svg):
"""Unites utilisateur par millimetre, comme Inkscape les affiche.
"""User units per millimeter, as Inkscape displays them.
svg.unittouu() devine l'unite du document par arrondi a l'unite connue la
plus proche : il se trompe des que l'echelle n'est pas standard (page
redimensionnee). On prend le rapport reel page / viewBox ; Inkscape
applique une echelle uniforme (preserveAspectRatio « meet »), soit la
plus petite des deux.
svg.unittouu() guesses the document unit by rounding to the nearest
known unit: it is wrong as soon as the scale is not standard (resized
page). We take the actual page / viewBox ratio; Inkscape applies a
uniform scale (preserveAspectRatio "meet"), i.e. the smaller of the two.
"""
try:
vb_w, vb_h = svg.viewbox_width, svg.viewbox_height
page_w = svg.to_dimensional(svg.viewport_width, "mm")
page_h = svg.to_dimensional(svg.viewport_height, "mm")
except AttributeError: # inkex anterieur a 1.2
except AttributeError: # inkex older than 1.2
return svg.unittouu("1mm")
if not (vb_w and vb_h and page_w and page_h):
return svg.unittouu("1mm")
@@ -80,14 +85,14 @@ def uu_per_mm(svg):
def length_to_uu(svg, value, unit="mm"):
"""Longueur reelle (valeur + unite) -> unites utilisateur du document."""
"""Real length (value + unit) -> document user units."""
return convert_unit("{}{}".format(value, unit), "mm") * uu_per_mm(svg)
def element_rings(elem, flatness):
"""Contour de l'element en coordonnees absolues : liste d'anneaux.
"""Outline of the element in absolute coordinates: list of rings.
Les courbes sont aplaties en polylignes (ecart maximal `flatness`).
Curves are flattened into polylines (maximum deviation `flatness`).
"""
path = elem.path.transform(elem.composed_transform())
csp = path.to_superpath()
@@ -103,10 +108,16 @@ def element_rings(elem, flatness):
class DogBandana(inkex.EffectExtension):
"""Remplit chaque forme selectionnee d'un labyrinthe de Turing."""
"""Fills each selected shape with a Turing maze."""
def __init__(self):
super().__init__()
# Position of the laser head: each drawing starts where the previous
# one stopped (see path_element).
self.head = (0.0, 0.0)
def add_arguments(self, pars):
# Un argument par <param> du .inx, memes noms et memes valeurs par defaut.
# One argument per <param> of the .inx, same names and same defaults.
pars.add_argument("--tab", default="pattern")
pars.add_argument("--period", type=float, default=4.0)
pars.add_argument("--line_width", type=float, default=2.0)
@@ -154,8 +165,6 @@ class DogBandana(inkex.EffectExtension):
"stroke-linejoin": "round",
})
# Position de la tete du laser : chaque trace demarre la ou le
# precedent s'est arrete (voir path_element).
self.head = (0.0, 0.0)
empty = 0
for elem in shapes:
@@ -172,11 +181,11 @@ class DogBandana(inkex.EffectExtension):
"line width, the period or the margin.").format(empty))
def path_element(self, polylines, style):
"""Chemin SVG des traits, dans l'ordre de gravure optimise.
"""SVG path of the strokes, in optimized engraving order.
Les traits qui se touchent sont enchaines, puis ordonnes au plus pres
de la position de la tete : moins de deplacements a vide du laser.
Tout trait genere passe par ici.
Touching strokes are chained, then ordered as close as possible to
the head position: less idle travel for the laser. Every generated
stroke goes through here.
"""
polylines = laser_order(polylines, self.head)
if polylines:
@@ -187,7 +196,7 @@ class DogBandana(inkex.EffectExtension):
return node
def process(self, elem, rings, period, width, margin, style):
"""Remplit un element ; renvoie False si la forme est trop etroite."""
"""Fill one element; return False if the shape is too narrow."""
opt = self.options
polylines = turing_pattern(rings, period, width, margin, seed=opt.seed,
edge=opt.edge, steps=opt.iterations)
@@ -198,8 +207,8 @@ class DogBandana(inkex.EffectExtension):
group = inkex.Group()
group.label = _("Dog Bandana pattern")
if parent is not None:
# Resultat calcule en coordonnees absolues du document : on
# neutralise la transformation heritee du parent d'accueil.
# The result is computed in absolute document coordinates: cancel
# the transform inherited from the host parent.
parent_transform = parent.composed_transform()
if parent_transform != inkex.Transform():
group.transform = -parent_transform