-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiroSim.py
More file actions
3801 lines (3270 loc) · 134 KB
/
SpiroSim.py
File metadata and controls
3801 lines (3270 loc) · 134 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import importlib
import importlib.util
import sys
import math
import copy
import json
import re
import colorsys
import time
import os
import subprocess
from pathlib import Path
from html import escape # <-- AJOUT ICI
from generated_colors import COLOR_NAME_TO_HEX
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple
import modular_tracks_2 as modular_tracks
import modular_tracks_2_demo as modular_track_demo
import localisation
from localisation import gear_type_label, relation_label, tr
from PySide6.QtWidgets import (
QApplication,
QWidget,
QVBoxLayout,
QHBoxLayout,
QPushButton,
QDialog,
QTreeWidget,
QTreeWidgetItem,
QFormLayout,
QLineEdit,
QDoubleSpinBox,
QSpinBox,
QCheckBox,
QMessageBox,
QLabel,
QComboBox,
QMenuBar,
QMenu,
QFileDialog,
QSlider, # <-- AJOUT
QListWidget, # <-- AJOUT
QListWidgetItem, # <-- AJOUT
QStyle,
QSizePolicy,
)
from PySide6.QtGui import (
QAction,
QPainter,
QColor,
QImage,
QIcon,
QFont,
QPixmap,
QDesktopServices,
QPen, # <-- AJOUT ICI
)
from PySide6.QtCore import (
QByteArray,
Qt,
Signal,
QPoint,
QPointF,
QSize,
QUrl,
QTimer,
QStandardPaths,
)
from PySide6.QtSvgWidgets import QSvgWidget
from PySide6.QtSvg import QSvgRenderer # <-- AJOUTÉ
# ----- Constante : unités normalisées -----
# Les tailles et distances sont désormais exprimées en unités abstraites,
# sans conversion réelle.
UNIT_LENGTH = 1.0
def _load_app_version() -> str:
spec = importlib.util.find_spec("spirosim._version")
if spec is None:
return "0.0.0-dev"
version_module = importlib.import_module("spirosim._version")
return getattr(version_module, "__version__", "0.0.0-dev")
APP_VERSION = _load_app_version()
GITHUB_REPO_URL = "https://github.com/alyndiar/SpiroSim"
def split_valid_modular_notation(text: str) -> Tuple[str, str, bool]:
"""
Analyse "mollement" une notation de piste modulaire (nouvelle syntaxe).
Retourne (valid, rest, has_piece) où :
- valid : partie comprise (offsets + suites de +a, -d, * ...)
- rest : le reste (non compris ou incomplet)
- has_piece : True s'il y a au moins une pièce (a, d, b, y)
"""
s = "".join(ch.lower() for ch in text if not ch.isspace())
n = len(s)
idx = 0
has_piece = False
if n == 0:
return "", "", False
def _consume_number(pos: int) -> int:
start = pos
while pos < n and (s[pos].isdigit() or s[pos] == "."):
pos += 1
return pos if pos > start else start
# opérateur initial optionnel
if idx < n and s[idx] in "+-*":
idx += 1
while idx < n:
if s[idx] in "+-*":
op = s[idx]
idx += 1
if op == "*":
continue
else:
op = "+"
if idx >= n:
break
if s[idx].isdigit():
next_idx = _consume_number(idx)
if next_idx == idx:
break
idx = next_idx
continue
letter = s[idx]
if letter not in modular_tracks.PIECES:
break
idx += 1
if letter in {"a", "d", "n", "o"}:
next_idx = _consume_number(idx)
if next_idx == idx:
break
idx = next_idx
elif letter in {"b", "y"}:
pass
if letter in {"a", "d", "b", "y"}:
has_piece = True
valid = s[:idx]
rest = s[idx:]
return valid, rest, has_piece
def wavelength_to_rgb(nm: float) -> Tuple[int, int, int]:
"""
Convertit une longueur d'onde en nm (≈ 380–780) en RGB sRGB 0–255.
Approximation standard (gamma 0.8).
"""
w = float(nm)
if w < 380 or w > 780:
return (0, 0, 0)
if 380 <= w < 440:
r = -(w - 440.0) / (440.0 - 380.0)
g = 0.0
b = 1.0
elif 440 <= w < 490:
r = 0.0
g = (w - 440.0) / (490.0 - 440.0)
b = 1.0
elif 490 <= w < 510:
r = 0.0
g = 1.0
b = -(w - 510.0) / (510.0 - 490.0)
elif 510 <= w < 580:
r = (w - 510.0) / (580.0 - 510.0)
g = 1.0
b = 0.0
elif 580 <= w < 645:
r = 1.0
g = -(w - 645.0) / (645.0 - 580.0)
b = 0.0
else: # 645–780
r = 1.0
g = 0.0
b = 0.0
# facteur de sensibilité de l'œil
if 380 <= w < 420:
factor = 0.3 + 0.7 * (w - 380.0) / (420.0 - 380.0)
elif 420 <= w < 700:
factor = 1.0
else: # 700–780
factor = 0.3 + 0.7 * (780.0 - w) / (780.0 - 700.0)
gamma = 0.8
def conv(c: float) -> int:
if c <= 0.0:
return 0
return int(round(255.0 * ((c * factor) ** gamma)))
return (conv(r), conv(g), conv(b))
def kelvin_to_rgb(temp_k: float) -> Tuple[int, int, int]:
"""
Approximation classique de la couleur d'un corps noir en Kelvin.
Intervalle utile ~ 1000K–40000K.
"""
t = max(1000.0, min(40000.0, float(temp_k))) / 100.0
# Rouge
if t <= 66.0:
r = 255
else:
r = 329.698727446 * ((t - 60.0) ** -0.1332047592)
r = max(0, min(255, int(round(r))))
# Vert
if t <= 66.0:
g = 99.4708025861 * math.log(t) - 161.1195681661
else:
g = 288.1221695283 * ((t - 60.0) ** -0.0755148492)
g = max(0, min(255, int(round(g))))
# Bleu
if t >= 66.0:
b = 255
elif t <= 19.0:
b = 0
else:
b = 138.5177312231 * math.log(t - 10.0) - 305.0447927307
b = max(0, min(255, int(round(b))))
return (r, g, b)
# ---------- 1) Modèle de données : engrenages & paths ----------
GEAR_TYPES = [
"anneau", # ring
"roue", # wheel
"triangle",
"carré",
"barre",
"croix",
"oeil",
"modulaire", # piste modulaire virtuelle (uniquement engrenage 1)
]
RELATIONS = [
"stationnaire", # pour le premier (au centre)
"dedans", # gear inside (hypotrochoïde)
"dehors", # gear outside (épitrochoïde)
]
@dataclass
class GearConfig:
name: str = "Engrenage"
gear_type: str = "anneau" # anneau, roue, triangle, carré, barre, croix, oeil, modulaire
size: int = 96 # taille de la roue / taille intérieure de l'anneau
outer_size: int = 144 # anneau : taille extérieure / anneau modulaire
relation: str = "stationnaire" # stationnaire / dedans / dehors
modular_notation: Optional[str] = None # notation de piste si gear_type == "modulaire"
@dataclass
class PathConfig:
name: str = "Tracé"
enable: bool = True
hole_offset: float = 1.0
phase_offset: float = 0.0
color: str = "blue" # chaîne telle que saisie / affichée
color_norm: Optional[str] = None # valeur normalisée (#rrggbb) pour le dessin
stroke_width: float = 1.2
zoom: float = 1.0
translate_x: float = 0.0
translate_y: float = 0.0
rotate_deg: float = 0.0
@dataclass
class LayerConfig:
name: str = "Couche"
enable: bool = True
zoom: float = 1.0 # zoom de la couche
translate_x: float = 0.0
translate_y: float = 0.0
rotate_deg: float = 0.0
gears: List[GearConfig] = field(default_factory=list) # 2 ou 3 engrenages
paths: List[PathConfig] = field(default_factory=list)
# ---------- 2) GÉOMÉTRIE ----------
def radius_from_size(size: int) -> float:
"""
Calcule le rayon d’un cercle de pas ayant une taille donnée.
"""
if size <= 0:
return 0.0
return float(size) / (2.0 * math.pi)
def contact_size_for_relation(gear: GearConfig, relation: str) -> int:
"""
Taille utilisée pour le contact, selon la relation.
- anneau + 'dedans' : on utilise la taille intérieure (gear.size)
- anneau + 'dehors' : on utilise la taille extérieure (gear.outer_size)
- roue / autres : gear.size
"""
if gear.gear_type == "anneau":
if relation == "dehors":
return gear.outer_size or gear.size
else:
return gear.size
return gear.size
def phase_offset_turns(offset: float, size: int) -> float:
"""
Convertit un décalage en unités (O) en fraction de tour (O/S).
"""
if size <= 0:
return 0.0
return float(offset) / float(size)
def contact_radius_for_relation(gear: GearConfig, relation: str) -> float:
"""
Rayon de contact pour un engrenage donné, selon la relation.
"""
size = contact_size_for_relation(gear, relation)
return radius_from_size(size)
def generate_simple_circle_for_index(
hole_offset: float,
steps: int,
):
"""
Fallback si on n’a pas assez d’engrenages : on simule un cercle
dont le rayon dépend du trou indexé.
On prend un rayon "référence" R_tip = 50 mm.
Trou 0 : rayon = R_tip
Trou n : R = R_tip - n
R est clampé à >= 0.
"""
R_tip = 50.0
d = R_tip - hole_offset
if d < 0:
d = 0.0
pts = []
for i in range(steps):
t = 2.0 * math.pi * i / (steps - 1)
x = d * math.cos(t)
y = d * math.sin(t)
pts.append((x, y))
return pts
def generate_trochoid_points_for_layer_path(
layer: LayerConfig,
path: PathConfig,
steps: int = 5000,
):
"""
Génère la courbe pour un path donné, en utilisant la configuration
du layer (engrenages + organisation).
Convention :
- Le PREMIER engrenage de la couche (gears[0]) est stationnaire
et centré en (0, 0).
- Le DEUXIÈME engrenage (gears[1]) est mobile et porte les trous du path.
- path.hole_offset est un float, peut être négatif.
Si le premier engrenage est de type "modulaire", il représente une
piste virtuelle SuperSpirograph, définie par :
- g0.size => taille intérieure de l’anneau de base
- g0.outer_size => taille extérieure de l’anneau de base
- g0.modular_notation => notation de pièce (ex: "+a60+d144-b*d72")
Dans ce cas, on délègue à modular_tracks.generate_track_base_points.
"""
hole_offset = float(path.hole_offset)
# Pas assez d’engrenages : cercle simple + rotation
if len(layer.gears) < 2:
base_points = generate_simple_circle_for_index(hole_offset, steps)
phase_turns = phase_offset_turns(path.phase_offset, 1)
total_angle = math.pi / 2.0 - (2.0 * math.pi * phase_turns)
cos_a = math.cos(total_angle)
sin_a = math.sin(total_angle)
rotated = []
for (x, y) in base_points:
xr = x * cos_a - y * sin_a
yr = x * sin_a + y * cos_a
rotated.append((xr, yr))
return rotated
g0 = layer.gears[0] # stationnaire, au centre
g1 = layer.gears[1] # mobile, porte les trous
relation = g1.relation
# Taille de contact pour chaque engrenage
T0 = max(1, contact_size_for_relation(g0, relation))
T1 = max(1, contact_size_for_relation(g1, relation))
# --- Cas 1 : piste modulaire comme premier engrenage ---
if g0.gear_type == "modulaire" and g0.modular_notation:
inner_size = g0.size if g0.size > 0 else 1
outer_size = g0.outer_size if g0.outer_size > 0 else inner_size
_, bundle = modular_tracks.build_track_and_bundle_from_notation(
notation=g0.modular_notation,
wheel_size=T1,
hole_offset=hole_offset,
steps=steps,
relation=relation,
phase_offset=path.phase_offset,
inner_size=inner_size,
outer_size=outer_size,
)
return bundle.stylo
# --- Cas 2 : comportement standard (anneau / roue ... ) ---
# Rayons de contact
R = contact_radius_for_relation(g0, relation)
r = contact_radius_for_relation(g1, relation)
if R <= 0 or r <= 0:
base_points = generate_simple_circle_for_index(hole_offset, steps)
phase_turns = phase_offset_turns(path.phase_offset, max(1, T0))
total_angle = math.pi / 2.0 - (2.0 * math.pi * phase_turns)
cos_a = math.cos(total_angle)
sin_a = math.sin(total_angle)
rotated_points = []
for (x, y) in base_points:
xr = x * cos_a - y * sin_a
yr = x * sin_a + y * cos_a
rotated_points.append((xr, yr))
return rotated_points
# Distance du stylo au centre de l’engrenage mobile
if g1.gear_type == "anneau":
R_tip_size = g1.outer_size or g1.size
else:
R_tip_size = g1.size
R_tip = radius_from_size(R_tip_size)
d = R_tip - hole_offset
if d < 0:
d = 0.0
# Durée t_max pour "fermer" la courbe (basée sur le ratio des tailles)
if T0 >= 1 and T1 >= 1:
g = math.gcd(int(T0), int(T1))
# La période correcte dépend du petit engrenage (mobile) :
t_max = 2.0 * math.pi * (T1 / g)
else:
t_max = 20.0 * math.pi
base_points = []
for i in range(steps):
t = t_max * i / (steps - 1)
if relation == "dedans":
# Hypotrochoïde : centre mobile à rayon (R - r)
R_minus_r = R - r
k = R_minus_r / r
x = R_minus_r * math.cos(t) + d * math.cos(k * t)
y = R_minus_r * math.sin(t) - d * math.sin(k * t)
elif relation == "dehors":
# Épitrochoïde : centre mobile à rayon (R + r)
R_plus_r = R + r
k = R_plus_r / r
x = R_plus_r * math.cos(t) - d * math.cos(k * t)
y = R_plus_r * math.sin(t) - d * math.sin(k * t)
else:
# Fallback : simple cercle autour de l’origine de rayon d
x = d * math.cos(t)
y = d * math.sin(t)
base_points.append((x, y))
# Rotation globale selon le décalage de phase.
phase_turns = phase_offset_turns(path.phase_offset, max(1, T0))
angle_from_phase = 2.0 * math.pi * phase_turns
# 0 => motif pointant vers le haut (π/2),
# positif => tourne vers la droite (horaire),
# négatif => vers la gauche (anti-horaire).
total_angle = math.pi / 2.0 - angle_from_phase
cos_a = math.cos(total_angle)
sin_a = math.sin(total_angle)
rotated_points = []
for (x, y) in base_points:
xr = x * cos_a - y * sin_a
yr = x * sin_a + y * cos_a
rotated_points.append((xr, yr))
return rotated_points
# ---------- 3) Validation de couleur ----------
def normalize_color_name(name: str) -> str:
import re
return re.sub(r"\s+", "", name.strip().lower())
def is_valid_color_name(name: str) -> bool:
return normalize_color_name(name) in COLOR_NAME_TO_HEX
def resolve_color_to_hex(name: str) -> str:
key = normalize_color_name(name)
return COLOR_NAME_TO_HEX[key] # KeyError if unknown
def normalize_color_string(s: str) -> Optional[str]:
"""
Renvoie une version normalisée de la couleur en hex :
- #rrggbb ou #rrggbbaa
ou None si la couleur est invalide.
Règles :
- Si ça commence par # -> valeur hex, validée par regex.
- Si c'est du type (H, S, L) -> HSL, H en degrés, S et L dans [0, 1].
- Sinon -> nom de couleur passé par COLOR_NAME_TO_HEX.
"""
if s is None:
return None
s = s.strip()
if not s:
return None
# 1) Hex direct (#rgb, #rgba, #rrggbb, #rrggbbaa)
if s.startswith("#"):
m = re.fullmatch(r"#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})", s)
if not m:
return None
return s.lower()
# 2) HSL : (Hue, Saturation, Luminance)
# Exemple : (120, 0.5, 0.4)
m = re.fullmatch(
r"\(\s*([+-]?\d*\.?\d+)\s*,\s*([+-]?\d*\.?\d+)\s*,\s*([+-]?\d*\.?\d+)\s*\)",
s,
)
if m:
try:
h = float(m.group(1))
sat = float(m.group(2))
lum = float(m.group(3))
# Hue en degrés -> [0, 360)
h = h % 360.0
# Saturation et luminance clampées à [0, 1]
sat = max(0.0, min(1.0, sat))
lum = max(0.0, min(1.0, lum))
# colorsys.hls_to_rgb attend (h, l, s) avec h dans [0,1]
r_f, g_f, b_f = colorsys.hls_to_rgb(h / 360.0, lum, sat)
r = int(round(r_f * 255))
g = int(round(g_f * 255))
b = int(round(b_f * 255))
return f"#{r:02x}{g:02x}{b:02x}"
except ValueError:
return None
# 3) Nom de couleur via ton dictionnaire
try:
hexv = resolve_color_to_hex(s)
return hexv.lower()
except KeyError:
return None
return None
def is_valid_color_string(s: str) -> bool:
"""Couleur valide si normalize_color_string(s) ne renvoie pas None."""
return normalize_color_string(s) is not None
class ColorSquare(QWidget):
"""
Carré Hue / Saturation (H/S) avec Value (V) gérée par un slider externe.
- Horizontal : Hue [0..1] (0 = 0°, 1 = 360°)
- Vertical : Saturation [0..1] (1 en haut, 0 en bas)
Le signal colorChanged émet (h, s) dans [0,1] quand on clique/drag.
"""
colorChanged = Signal(float, float) # (h, s)
def __init__(self, parent=None):
super().__init__(parent)
self._h = 0.0 # 0..1
self._s = 1.0 # 0..1
self._v = 0.5 # 0..1 (géré par un slider externe, mais stocké ici pour dessiner)
def set_hsv(self, h: float, s: float, v: float):
self._h = max(0.0, min(1.0, h))
self._s = max(0.0, min(1.0, s))
self._v = max(0.0, min(1.0, v))
self.update()
def get_hsv(self):
return self._h, self._s, self._v
def _update_from_pos(self, pt: QPoint):
w = max(1, self.width())
h = max(1, self.height())
x = min(max(pt.x(), 0), w - 1)
y = min(max(pt.y(), 0), h - 1)
# H = horizontal, S = vertical (1 en haut -> 0 en bas)
self._h = x / (w - 1) if w > 1 else 0.0
self._s = 1.0 - (y / (h - 1) if h > 1 else 0.0)
self.colorChanged.emit(self._h, self._s)
self.update()
def mousePressEvent(self, event):
pos = event.position().toPoint() if hasattr(event, "position") else event.pos()
self._update_from_pos(pos)
def mouseMoveEvent(self, event):
if event.buttons() & Qt.LeftButton:
pos = event.position().toPoint() if hasattr(event, "position") else event.pos()
self._update_from_pos(pos)
class ColorPickerDialog(QDialog):
"""
Sélecteur de couleur évolué :
- Carré H/S + slider de Value (V)
- Champ texte (nom, #hex, (H, S, L))
- Liste filtrable de noms (COLOR_NAME_TO_HEX)
- Harmonies : complémentaire, analogues, triadique, tétradique, tints & shades
- Sélection par longueur d'onde (nm) et température (K)
"""
def __init__(self, initial_text: str = "", lang: str = "fr", parent=None):
super().__init__(parent)
self.lang = localisation.normalize_language(lang) or "fr"
self.setWindowTitle(tr(self.lang, "color_picker_title"))
self.resize(820, 460)
self._updating = False
self._h = 0.0 # 0..1
self._s = 1.0 # 0..1
self._v = 0.5 # 0..1 (50 % par défaut)
self._hex = "#ffffff"
self._scheme_colors: List[str] = []
main_layout = QHBoxLayout(self)
# --- zone gauche : carré + slider V + prévisualisation + champs numériques ---
left_layout = QVBoxLayout()
# carré H/S + slider de Value
sv_layout = QHBoxLayout()
self.square = ColorSquare()
self.value_slider = QSlider(Qt.Vertical)
self.value_slider.setRange(0, 100) # 0..100 -> V 0..1
self.value_slider.setValue(50) # V = 50%
sv_layout.addWidget(self.square, 1)
sv_layout.addWidget(self.value_slider)
left_layout.addLayout(sv_layout)
# prévisualisation + champ texte
prev_layout = QHBoxLayout()
self.preview_label = QLabel()
self.preview_label.setFixedSize(60, 30)
self.preview_label.setAutoFillBackground(True)
self.text_edit = QLineEdit()
self.text_edit.setPlaceholderText(tr(self.lang, "color_picker_text_placeholder"))
prev_layout.addWidget(self.preview_label)
prev_layout.addWidget(self.text_edit, 1)
left_layout.addLayout(prev_layout)
# ligne RGB + Wavelength + Kelvin
numeric_layout = QHBoxLayout()
def make_spin(label_txt: str):
box = QVBoxLayout()
lab = QLabel(label_txt)
spin = QSpinBox()
box.addWidget(lab)
box.addWidget(spin)
return box, spin
rgb_r_box, self.r_spin = make_spin("R")
rgb_g_box, self.g_spin = make_spin("G")
rgb_b_box, self.b_spin = make_spin("B")
self.r_spin.setRange(0, 255)
self.g_spin.setRange(0, 255)
self.b_spin.setRange(0, 255)
# Wavelength (nm)
wave_box = QVBoxLayout()
wave_label = QLabel("λ (nm)")
self.wave_spin = QDoubleSpinBox()
self.wave_spin.setRange(380.0, 780.0)
self.wave_spin.setDecimals(1)
self.wave_spin.setSingleStep(1.0)
wave_box.addWidget(wave_label)
wave_box.addWidget(self.wave_spin)
# Température (K)
temp_box = QVBoxLayout()
temp_label = QLabel("T (K)")
self.temp_spin = QSpinBox()
self.temp_spin.setRange(1000, 40000)
self.temp_spin.setSingleStep(100)
temp_box.addWidget(temp_label)
temp_box.addWidget(self.temp_spin)
numeric_layout.addLayout(rgb_r_box)
numeric_layout.addLayout(rgb_g_box)
numeric_layout.addLayout(rgb_b_box)
numeric_layout.addSpacing(12)
numeric_layout.addLayout(wave_box)
numeric_layout.addLayout(temp_box)
left_layout.addLayout(numeric_layout)
# --- Harmonies : combo + 5 pastilles cliquables ---
harmony_layout = QVBoxLayout()
scheme_row = QHBoxLayout()
scheme_label = QLabel(tr(self.lang, "color_picker_harmony_label"))
self.scheme_combo = QComboBox()
scheme_options = [
("none", tr(self.lang, "color_picker_scheme_none")),
("complementary", tr(self.lang, "color_picker_scheme_complementary")),
("analogous", tr(self.lang, "color_picker_scheme_analogous")),
("triadic", tr(self.lang, "color_picker_scheme_triadic")),
("tetradic", tr(self.lang, "color_picker_scheme_tetradic")),
("tints_shades", tr(self.lang, "color_picker_scheme_tints_shades")),
]
for key, label in scheme_options:
self.scheme_combo.addItem(label, key)
scheme_row.addWidget(scheme_label)
scheme_row.addWidget(self.scheme_combo, 1)
harmony_layout.addLayout(scheme_row)
self.scheme_buttons: List[QPushButton] = []
btn_row = QHBoxLayout()
for _ in range(5):
b = QPushButton()
b.setFixedSize(32, 32)
b.setFlat(True)
b.clicked.connect(self.on_scheme_button_clicked)
self.scheme_buttons.append(b)
btn_row.addWidget(b)
harmony_layout.addLayout(btn_row)
left_layout.addLayout(harmony_layout)
main_layout.addLayout(left_layout, 2)
# --- zone droite : liste de noms de couleurs ---
right_layout = QVBoxLayout()
search_layout = QHBoxLayout()
self.search_edit = QLineEdit()
self.search_edit.setPlaceholderText(tr(self.lang, "color_picker_search_placeholder"))
btn_clear = QPushButton(tr(self.lang, "color_picker_clear"))
btn_clear.clicked.connect(self.search_edit.clear)
search_layout.addWidget(self.search_edit, 1)
search_layout.addWidget(btn_clear)
right_layout.addLayout(search_layout)
self.list_widget = QListWidget()
right_layout.addWidget(self.list_widget, 1)
main_layout.addLayout(right_layout, 1)
# --- boutons OK / Annuler ---
btn_layout = QHBoxLayout()
btn_ok = QPushButton(tr(self.lang, "dlg_ok"))
btn_cancel = QPushButton(tr(self.lang, "dlg_cancel"))
btn_ok.clicked.connect(self.accept)
btn_cancel.clicked.connect(self.reject)
btn_layout.addStretch(1)
btn_layout.addWidget(btn_ok)
btn_layout.addWidget(btn_cancel)
main_layout.addLayout(btn_layout)
# Connexions
self.value_slider.valueChanged.connect(self.on_value_changed)
self.square.colorChanged.connect(self.on_hs_changed)
self.text_edit.editingFinished.connect(self.on_text_edited)
self.r_spin.valueChanged.connect(self.on_rgb_spin_changed)
self.g_spin.valueChanged.connect(self.on_rgb_spin_changed)
self.b_spin.valueChanged.connect(self.on_rgb_spin_changed)
self.wave_spin.valueChanged.connect(self.on_wave_changed)
self.temp_spin.valueChanged.connect(self.on_temp_changed)
self.search_edit.textChanged.connect(self.on_search_changed)
self.list_widget.itemDoubleClicked.connect(self.on_list_double_clicked)
self.scheme_combo.currentIndexChanged.connect(self.update_scheme_palette)
self.populate_color_list()
self.set_from_text(initial_text or "#ffffff")
# -------- utilitaires liste de couleurs --------
def populate_color_list(self):
self.list_widget.clear()
from PySide6.QtGui import QPixmap
for name in sorted(COLOR_NAME_TO_HEX.keys()):
hexv = COLOR_NAME_TO_HEX[name]
item = QListWidgetItem(name)
item.setData(Qt.UserRole, hexv)
pix = QImage(16, 16, QImage.Format_RGB32)
pix.fill(QColor(hexv))
item.setIcon(QPixmap.fromImage(pix))
self.list_widget.addItem(item)
def on_search_changed(self, text: str):
t = text.strip().lower()
for i in range(self.list_widget.count()):
item = self.list_widget.item(i)
name = item.text().lower()
item.setHidden(t not in name)
def on_list_double_clicked(self, item: QListWidgetItem):
if not item:
return
name = item.text()
hexv = item.data(Qt.UserRole)
self._set_from_hex_and_text(hexv, name)
# -------- Harmonies --------
def update_scheme_palette(self, _index: int = 0):
scheme = self.scheme_combo.currentData()
c = QColor()
c.setHsvF(self._h, self._s, self._v)
base_h, base_s, base_v, _ = c.getHsvF()
colors: List[str] = []
def add_h_offset(deg_offset: float, s_mult: float = 1.0, v_mult: float = 1.0):
h = (base_h + deg_offset / 360.0) % 1.0
s = max(0.0, min(1.0, base_s * s_mult))
v = max(0.0, min(1.0, base_v * v_mult))
cc = QColor()
cc.setHsvF(h, s, v)
colors.append(f"#{cc.red():02x}{cc.green():02x}{cc.blue():02x}")
if scheme == "none":
colors = []
elif scheme == "complementary":
add_h_offset(0)
add_h_offset(180)
elif scheme == "analogous":
add_h_offset(-30)
add_h_offset(0)
add_h_offset(30)
elif scheme == "triadic":
add_h_offset(0)
add_h_offset(120)
add_h_offset(240)
elif scheme == "tetradic":
add_h_offset(0)
add_h_offset(90)
add_h_offset(180)
add_h_offset(270)
elif scheme == "tints_shades":
for v_mult in (1.2, 1.0, 0.8, 0.6, 0.4):
v = max(0.0, min(1.0, base_v * v_mult))
cc = QColor()
cc.setHsvF(base_h, base_s, v)
colors.append(f"#{cc.red():02x}{cc.green():02x}{cc.blue():02x}")
self._scheme_colors = colors[:5]
for i, btn in enumerate(self.scheme_buttons):
if i < len(self._scheme_colors):
hexv = self._scheme_colors[i]
btn.setEnabled(True)
btn.setStyleSheet(f"background-color: {hexv}; border: 1px solid #202020;")
else:
btn.setEnabled(False)
btn.setStyleSheet("background-color: none; border: none;")
def on_scheme_button_clicked(self):
if self._updating:
return
btn = self.sender()
if not isinstance(btn, QPushButton):
return
if btn not in self.scheme_buttons:
return
idx = self.scheme_buttons.index(btn)
if idx >= len(self._scheme_colors):
return
hexv = self._scheme_colors[idx]
self._set_from_hex_and_text(hexv, hexv)
# -------- Réactions aux changements numériques / HSV --------
def on_value_changed(self, value: int):
if self._updating:
return
self._v = value / 100.0
self._update_from_hsv()
def on_hs_changed(self, h: float, s: float):
if self._updating:
return
self._h = h
self._s = s
self._update_from_hsv()
def on_rgb_spin_changed(self, _value: int):
if self._updating:
return
r = self.r_spin.value()
g = self.g_spin.value()
b = self.b_spin.value()
c = QColor(r, g, b)
h, s, v, _ = c.getHsvF()
self._h, self._s, self._v = h, s, v
self._update_from_hsv()
self.text_edit.setText(self._hex)
def on_wave_changed(self, value: float):
if self._updating:
return
r, g, b = wavelength_to_rgb(value)
c = QColor(r, g, b)
h, s, v, _ = c.getHsvF()
self._h, self._s, self._v = h, s, v
self._update_from_hsv()
self.text_edit.setText(self._hex)
def on_temp_changed(self, value: int):
if self._updating:
return
r, g, b = kelvin_to_rgb(value)
c = QColor(r, g, b)
h, s, v, _ = c.getHsvF()
self._h, self._s, self._v = h, s, v
self._update_from_hsv()
self.text_edit.setText(self._hex)
def on_text_edited(self):
if self._updating:
return
text = self.text_edit.text().strip()
if not text:
return
hexv = normalize_color_string(text)
if hexv is None:
self.text_edit.setText(self._hex)
return
self._set_from_hex_and_text(hexv, text)
def _set_from_hex_and_text(self, hexv: str, text_repr: str):
c = QColor(hexv)
h, s, v, _ = c.getHsvF()
self._h, self._s, self._v = h, s, v
self._hex = hexv
self._updating = True
try:
self.square.set_hsv(self._h, self._s, self._v)
self.value_slider.setValue(int(round(self._v * 100)))
self._update_widgets_from_color(c, keep_text=False)
self.text_edit.setText(text_repr)
self._update_preview()
self.update_scheme_palette()
finally:
self._updating = False
def _update_from_hsv(self):
c = QColor()
c.setHsvF(self._h, self._s, self._v)
self._hex = f"#{c.red():02x}{c.green():02x}{c.blue():02x}"