-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackage.py
More file actions
executable file
·2984 lines (2538 loc) · 109 KB
/
package.py
File metadata and controls
executable file
·2984 lines (2538 loc) · 109 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
#!/usr/bin/env python3
"""
package.py — Script de packaging de Mediarecode.
Cibles :
Linux (défaut) → AppImage (Mediarecode-x86_64.AppImage dans dist/)
Windows natif → .exe / .msix
Windows cross → Mediarecode-Setup.exe via Wine + NSIS (--windows)
Workflow Linux :
1. PyInstaller --onedir → dist/mediarecode/
2. Construction du AppDir (AppRun + .desktop + icône)
3. appimagetool → dist/Mediarecode-<arch>.AppImage
Workflow Windows natif (exécuté sur Windows) :
1. PyInstaller --onedir → dist/mediarecode/
2. (optionnel) MSIX → Mediarecode.msix (nécessite --msix)
3. (optionnel) NSIS → Mediarecode-Setup.exe (nécessite --nsis)
Workflow Windows cross (depuis Linux avec --windows) :
1. Installe Wine + préfixe dédié si absent
2. Installe Python Windows + PyInstaller dans le préfixe Wine
3. PyInstaller via wine python.exe → dist/mediarecode-win/
4. Génère un script NSIS + makensis → Mediarecode-Setup.exe
Usage :
python3 package.py [options]
Options :
--onefile Produit un binaire monolithique (lent au démarrage, ignoré pour AppImage)
--exe Force le packaging .exe même sur Linux (PyInstaller natif, pas d'AppImage)
--windows Cross-compile un installateur Windows depuis Linux via Wine + NSIS
--msix Produit un package MSIX signé sur Windows natif
--skip-wine Réutilise dist/mediarecode-win/ existant (skip étape Wine/PyInstaller)
--version TAG Suffixe de version pour le fichier final (défaut: APP_VERSION)
--dest PATH Copie le fichier final vers un chemin personnalisé (dossier ou fichier)
--clean Nettoie tous les artefacts de build (build/, dist/, .wine_build/, *.AppImage…). Utilise sudo si nécessaire. Quitte sans builder.
"""
from __future__ import annotations
import argparse
import fnmatch
import importlib
import importlib.util
import json
import os
import platform
import re
import shutil
import stat
import struct
import subprocess
import sys
import tempfile
import time
import urllib.request
import zipfile
from pathlib import Path
from typing import Any, Iterable
from core.file_types import ACCEPTED_EXTENSIONS, build_desktop_mime_type_string
from core.version import APP_NAME, APP_VERSION
ROOT = Path(__file__).parent
DIST_RELEASES = ROOT / "dist" / "releases"
OS = platform.system()
# Préfixe Wine isolé (dans le projet, ignoré par .gitignore)
_WINE_PREFIX = ROOT / ".wine_build"
# Version Python Windows embarquée dans le préfixe Wine
_WIN_PY_VER = "3.11.9"
_WIN_PY_URL = f"https://www.python.org/ftp/python/{_WIN_PY_VER}/python-{_WIN_PY_VER}-amd64.exe"
# Chemin de python.exe à l'intérieur du préfixe Wine
_WIN_PY_EXE = _WINE_PREFIX / "drive_c" / "Python311" / "python.exe"
# Version PySide6 figée pour le build cross Wine.
# Un override ponctuel reste possible via l'environnement si besoin de tester
# une autre release sans modifier le dépôt.
_WIN_PYSIDE6_VER = os.environ.get("MEDIARECODE_WINE_PYSIDE6_VERSION", "6.10.2").strip() or "6.10.2"
# Runtime ICU Windows utilisé pour satisfaire les dépendances Qt sous Wine.
_WIN_ICU_NUGET_VERSION = os.environ.get("MEDIARECODE_WINE_ICU_VERSION", "72.1.0.3").strip() or "72.1.0.3"
_WIN_ICU_NUGET_URL = (
"https://www.nuget.org/api/v2/package/"
f"Microsoft.ICU.ICU4C.Runtime.win-x64/{_WIN_ICU_NUGET_VERSION}"
)
# Bundle PyInstaller Windows (dans dist/)
_WIN_BUNDLE = ROOT / "mediarecode-win" # hors de dist/ (owned by nfsnobody)
# Bundle macOS
_MACOS_BUNDLE_NAME = "Mediarecode.app"
_MACOS_BUNDLE_ID = os.environ.get("MEDIARECODE_MACOS_BUNDLE_ID", "com.hydro74000.mediarecode").strip() or "com.hydro74000.mediarecode"
_MACOS_MIN_VERSION = os.environ.get("MEDIARECODE_MACOS_MIN_VERSION", "11.0").strip() or "11.0"
_APPIMAGE_UPDATE_OWNER = os.environ.get("MEDIARECODE_APPIMAGE_UPDATE_OWNER", "Hydro74000").strip() or "Hydro74000"
_APPIMAGE_UPDATE_REPO = os.environ.get("MEDIARECODE_APPIMAGE_UPDATE_REPO", "mediarecode").strip() or "mediarecode"
_APPIMAGE_UPDATE_RELEASE = os.environ.get("MEDIARECODE_APPIMAGE_UPDATE_RELEASE", "latest").strip() or "latest"
_MSIX_IDENTITY = os.environ.get("MEDIARECODE_MSIX_IDENTITY", "AOTR.Mediarecode").strip() or "AOTR.Mediarecode"
_MSIX_PUBLISHER = os.environ.get("MEDIARECODE_MSIX_PUBLISHER", "CN=AOTR").strip() or "CN=AOTR"
_MSIX_PUBLISHER_DISPLAY_NAME = os.environ.get("MEDIARECODE_MSIX_PUBLISHER_DISPLAY_NAME", "AOTR").strip() or "AOTR"
_MSIX_DESCRIPTION = os.environ.get("MEDIARECODE_MSIX_DESCRIPTION", "AOTR Mediarecode is an independent video workflow tool. This software is not affiliated with, authorized, or endorsed by Nero AG or any other media software providers.").strip() or "AOTR Mediarecode is an independent video workflow tool. This software is not affiliated with, authorized, or endorsed by Nero AG or any other media software providers."
_MSIX_CERT_PFX = os.environ.get("MEDIARECODE_MSIX_CERT_PFX", "").strip()
_MSIX_CERT_PASSWORD = os.environ.get("MEDIARECODE_MSIX_CERT_PASSWORD", "").strip()
_MSIX_TIMESTAMP_URL = os.environ.get("MEDIARECODE_MSIX_TIMESTAMP_URL", "http://timestamp.digicert.com").strip() or "http://timestamp.digicert.com"
_MSIX_STORE_CONFIG = os.environ.get("MEDIARECODE_MSIX_STORE_CONFIG", "").strip()
_WINDOWS_SDK_WINGET_ID = os.environ.get("MEDIARECODE_WINDOWS_SDK_WINGET_ID", "Microsoft.WindowsSDK").strip() or "Microsoft.WindowsSDK"
_WINDOWS_SDK_INSTALLER = os.environ.get("MEDIARECODE_WINDOWS_SDK_INSTALLER", "").strip()
# Exception MSIX : nom technique distinct du branding/artefacts classiques.
_MSIX_PACKAGE_NAME = re.sub(
r"\s+",
"",
os.environ.get("MEDIARECODE_MSIX_PACKAGE_NAME", "AOTRMediarecode").strip(),
) or "AOTRMediarecode"
# ── Modules Python exclus du bundle ──────────────────────────────────────────
EXCLUDED_MODULES: list[str] = [
"tkinter",
"matplotlib",
"numpy",
"scipy",
"PIL",
"IPython",
"notebook",
# PySide6 deploy helper not used by the app; importing it can warn on
# some environments due to an internal absolute import ("project_lib").
"PySide6.scripts.deploy_lib",
]
# ── Fichiers/dossiers copiés comme données non-Python ────────────────────────
# Format : (source_relative_to_ROOT, dest_in_bundle)
DATA_FILES: list[tuple[str, str]] = [
("locales.json", "."),
("requirements.txt", "."),
("README.md", "."),
]
def _windows_version_tuple(version: str) -> tuple[int, int, int, int]:
"""Convertit `1.2` ou `1.2.3` vers un tuple PE à 4 entiers."""
parts = [int(p) for p in re.findall(r"\d+", version)]
while len(parts) < 4:
parts.append(0)
return tuple(parts[:4]) # type: ignore[return-value]
def _write_windows_version_file() -> Path:
"""Génère un fichier `--version-file` PyInstaller avec métadonnées PE."""
build_dir = ROOT / "build"
build_dir.mkdir(parents=True, exist_ok=True)
version_file = build_dir / "windows_version_info.txt"
version_tuple = _windows_version_tuple(APP_VERSION)
version_str = ".".join(str(p) for p in version_tuple)
content = f"""# UTF-8
VSVersionInfo(
ffi=FixedFileInfo(
filevers={version_tuple},
prodvers={version_tuple},
mask=0x3F,
flags=0x0,
OS=0x40004,
fileType=0x1,
subtype=0x0,
date=(0, 0)
),
kids=[
StringFileInfo([
StringTable(
'040C04B0',
[
StringStruct('CompanyName', 'Mediarecode'),
StringStruct('FileDescription', 'Mediarecode video workflow'),
StringStruct('FileVersion', '{version_str}'),
StringStruct('InternalName', 'mediarecode'),
StringStruct('OriginalFilename', 'mediarecode.exe'),
StringStruct('ProductName', '{APP_NAME}'),
StringStruct('ProductVersion', '{version_str}')
]
)
]),
VarFileInfo([VarStruct('Translation', [1036, 1200])])
]
)
"""
version_file.write_text(content, encoding="utf-8")
return version_file
# ── Icône (optionnelle) ───────────────────────────────────────────────────────
# Placez une icône 256×256 px à cet emplacement pour l'intégrer au bundle.
ICON_PNG = ROOT / "icon.png"
ICON_ICO = ROOT / "icon.ico"
ICON_ICO_GENERATED = ROOT / "build" / "icon.ico"
# ─────────────────────────────────────────────────────────────────────────────
# Utilitaires
# ─────────────────────────────────────────────────────────────────────────────
def _can_stream_encode(stream: object, text: str) -> bool:
encoding = getattr(stream, "encoding", None)
if not encoding:
return False
try:
text.encode(encoding)
return True
except Exception:
return False
def _configure_stdio_for_windows() -> None:
"""
Configure stdout/stderr on Windows so console output never crashes on
Unicode glyphs. If UTF-8 reconfigure is unavailable, fallback to
`errors=replace`.
"""
if OS != "Windows":
return
probe = "✔→⚠✘─"
for name in ("stdout", "stderr"):
stream = getattr(sys, name, None)
if stream is None:
continue
if _can_stream_encode(stream, probe):
continue
reconfigure = getattr(stream, "reconfigure", None)
if not callable(reconfigure):
continue
try:
reconfigure(encoding="utf-8", errors="replace")
except Exception:
try:
reconfigure(errors="replace")
except Exception:
pass
_configure_stdio_for_windows()
_UI_UNICODE = _can_stream_encode(sys.stdout, "✔→⚠✘─")
_UI_OK = "✔" if _UI_UNICODE else "OK"
_UI_INFO = "→" if _UI_UNICODE else "->"
_UI_WARN = "⚠" if _UI_UNICODE else "!"
_UI_ERR = "✘" if _UI_UNICODE else "X"
_UI_BAR = "─" if _UI_UNICODE else "-"
def _ok(msg: str) -> None: print(f" \033[32m{_UI_OK}\033[0m {msg}")
def _info(msg: str) -> None: print(f" \033[36m{_UI_INFO}\033[0m {msg}")
def _warn(msg: str) -> None: print(f" \033[33m{_UI_WARN}\033[0m {msg}")
def _err(msg: str) -> None: print(f" \033[31m{_UI_ERR}\033[0m {msg}", file=sys.stderr)
def _title(msg: str) -> None:
bar = _UI_BAR * 60
print(f"\n\033[1;34m{bar}\n {msg}\n{bar}\033[0m")
def _run(cmd: list[str], check: bool = True, **kwargs) -> subprocess.CompletedProcess:
_info("$ " + " ".join(str(c) for c in cmd))
return subprocess.run(cmd, check=check, **kwargs)
def _normalize_version_tag(version_tag: str | None) -> str:
"""
Normalise un tag de version pour un nom de fichier.
- fallback: APP_VERSION
- espaces -> '-'
- caractères autorisés: [A-Za-z0-9._-]
"""
raw = (version_tag or "").strip() or APP_VERSION
raw = re.sub(r"\s+", "-", raw)
cleaned = re.sub(r"[^A-Za-z0-9._-]+", "", raw)
return cleaned or APP_VERSION
def _versioned_output_path(path: Path, version_tag: str | None) -> Path:
"""
Retourne un path suffixé par '-<version>' avant l'extension.
Exemple: file.AppImage -> file-1.2.3.AppImage
"""
tag = _normalize_version_tag(version_tag)
stem = path.stem if path.suffix else path.name
if stem.endswith(f"-{tag}"):
return path
if path.suffix:
return path.with_name(f"{path.stem}-{tag}{path.suffix}")
return path.with_name(f"{path.name}-{tag}")
def _default_msix_store_config_path() -> Path:
return ROOT / "packaging" / "msix_store.json"
def _load_msix_store_metadata(config_path: Path | None = None) -> dict[str, str]:
"""
Charge les métadonnées Store/MSIX depuis un JSON optionnel.
Priorité:
1. valeurs intégrées/environnement
2. chemin explicite
3. `packaging/msix_store.json`
"""
metadata = {
"identity": _MSIX_IDENTITY,
"publisher": _MSIX_PUBLISHER,
"publisher_display_name": _MSIX_PUBLISHER_DISPLAY_NAME,
"description": _MSIX_DESCRIPTION,
"display_name": APP_NAME,
}
candidate = config_path
if candidate is None and _MSIX_STORE_CONFIG:
candidate = Path(_MSIX_STORE_CONFIG)
if candidate is None:
candidate = _default_msix_store_config_path()
if not candidate.exists():
return metadata
payload = json.loads(candidate.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
raise ValueError(f"Configuration MSIX invalide : {candidate}")
for key in metadata:
value = payload.get(key)
if isinstance(value, str) and value.strip():
metadata[key] = value.strip()
return metadata
def _resolve_dest_file(dest: str | None, default_output: Path, version_tag: str | None = None) -> Path:
"""
Résout le chemin de destination du fichier final.
- dest absent: place dans dist/releases/ (créé si besoin)
- dest dossier (existant, trailing slash, ou sans extension): utilise le nom auto
- dest fichier: utilise ce nom
"""
if not dest or not dest.strip():
return _versioned_output_path(DIST_RELEASES / default_output.name, version_tag)
raw = dest.strip()
target = Path(raw).expanduser()
if not target.is_absolute():
target = (Path.cwd() / target).resolve()
if target.exists() and target.is_dir():
return _versioned_output_path(target / default_output.name, version_tag)
if raw.endswith(("/", "\\")):
return _versioned_output_path(target / default_output.name, version_tag)
if target.suffix == "":
return _versioned_output_path(target / default_output.name, version_tag)
return _versioned_output_path(target, version_tag)
def _copy_final_file_if_requested(src: Path, dest: str | None, version_tag: str | None = None) -> Path:
"""Déplace le fichier final vers dist/releases/ (ou --dest si fourni)."""
target = _resolve_dest_file(dest, src, version_tag)
src_resolved = src.resolve()
target_resolved = target.resolve(strict=False)
if src_resolved == target_resolved:
return src
target.parent.mkdir(parents=True, exist_ok=True)
src.replace(target)
_ok(f"Fichier final : {target}")
return target
def _ensure_pyinstaller() -> None:
required: list[tuple[str, str]] = [
("PyInstaller", "pyinstaller"),
("PySide6", "PySide6>=6.6.0"),
("pymediainfo", "pymediainfo>=6.1.0"),
]
missing: list[str] = []
for module_name, pip_name in required:
if importlib.util.find_spec(module_name) is None:
missing.append(pip_name)
if not missing:
_ok("Dépendances de packaging Python disponibles")
return
_info(f"Installation des dépendances manquantes : {', '.join(missing)}")
_run([sys.executable, "-m", "pip", "install", *missing])
def _clean_dirs() -> None:
"""Supprime les artefacts de build avec sudo si nécessaire (fichiers nfsnobody)."""
to_remove: list[Path] = [
ROOT / "build",
ROOT / "dist",
ROOT / "Mediarecode.AppDir",
ROOT / "mediarecode-win",
ROOT / "mediarecode.nsi",
ROOT / ".wine_build",
*ROOT.glob("*.spec"),
]
for path in to_remove:
if not path.exists():
continue
try:
if path.is_dir():
shutil.rmtree(path)
else:
path.unlink()
_ok(f"Supprimé : {path.relative_to(ROOT)}")
except PermissionError:
_info(f"Permission refusée, tentative avec sudo : {path.relative_to(ROOT)}")
result = subprocess.run(["sudo", "rm", "-rf", str(path)])
if result.returncode == 0:
_ok(f"Supprimé (sudo) : {path.relative_to(ROOT)}")
else:
_warn(f"Impossible de supprimer : {path.relative_to(ROOT)}")
# ─────────────────────────────────────────────────────────────────────────────
# Étape 1 — PyInstaller
# ─────────────────────────────────────────────────────────────────────────────
def _png_dimensions(png_data: bytes) -> tuple[int, int]:
"""Retourne (largeur, hauteur) depuis l'en-tête IHDR du PNG."""
if len(png_data) < 24 or png_data[:8] != b"\x89PNG\r\n\x1a\n":
raise ValueError("icon.png est invalide (signature PNG absente)")
return struct.unpack(">II", png_data[16:24])
def _ico_dim(value: int) -> int:
"""Dans un répertoire ICO, 0 représente 256 px."""
return 0 if value >= 256 else value
def _write_ico_from_png_payload(png_data: bytes, width: int, height: int, dest: Path) -> None:
"""Écrit un .ico minimal contenant une image PNG."""
dest.parent.mkdir(parents=True, exist_ok=True)
header = struct.pack("<HHH", 0, 1, 1) # reserved, type=icon, count=1
entry = struct.pack(
"<BBBBHHII",
_ico_dim(width),
_ico_dim(height),
0,
0,
1,
32,
len(png_data),
6 + 16,
)
dest.write_bytes(header + entry + png_data)
def _build_ico_from_png(src_png: Path, dest_ico: Path) -> Path:
"""
Construit un .ico Windows depuis icon.png.
Si l'image n'est pas déjà "ICO-safe", redimensionne en 256×256 via Qt.
"""
png_data = src_png.read_bytes()
width, height = _png_dimensions(png_data)
needs_qt_resize = width != height or width > 256 or height > 256
if needs_qt_resize:
try:
qtcore = importlib.import_module("PySide6.QtCore")
qtgui = importlib.import_module("PySide6.QtGui")
Qt = qtcore.Qt
QImage = qtgui.QImage
except Exception:
_warn(
f"PySide6 indisponible pour redimensionner {src_png.name} ({width}x{height}) ; "
"fallback vers encapsulation PNG directe."
)
else:
image = QImage(str(src_png))
if not image.isNull():
image = image.scaled(
256, 256,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
dest_ico.parent.mkdir(parents=True, exist_ok=True)
if image.save(str(dest_ico), "ICO"):
_ok(f"Icône Windows générée depuis {src_png.name} → {dest_ico.relative_to(ROOT)}")
return dest_ico
_warn("Conversion ICO via Qt impossible ; fallback vers encapsulation PNG directe.")
_write_ico_from_png_payload(png_data, width, height, dest_ico)
_ok(f"Icône Windows générée depuis {src_png.name} → {dest_ico.relative_to(ROOT)}")
return dest_ico
def _resolve_windows_icon_ico() -> Path | None:
"""Retourne un .ico Windows prêt à l'emploi (généré depuis icon.png si besoin)."""
if ICON_ICO.exists():
return ICON_ICO
if not ICON_PNG.exists():
_warn(f"Icône Windows absente : {ICON_ICO.name} / {ICON_PNG.name}")
return None
regenerate = (
not ICON_ICO_GENERATED.exists()
or ICON_ICO_GENERATED.stat().st_mtime < ICON_PNG.stat().st_mtime
)
if regenerate:
_build_ico_from_png(ICON_PNG, ICON_ICO_GENERATED)
return ICON_ICO_GENERATED
def _windows_ssl_hidden_import_args() -> list[str]:
"""
Hidden imports needed so urllib HTTPS support is preserved in frozen builds.
`_ssl` is critical; `ssl` keeps the high-level API reachable.
"""
return [
"--hidden-import", "ssl",
"--hidden-import", "_ssl",
]
def _windows_ctypes_hidden_import_args() -> list[str]:
"""
Hidden imports needed by stdlib `ctypes` on Windows frozen builds.
`_ctypes` is the binary extension that depends on libffi runtime DLLs.
"""
return [
"--hidden-import", "ctypes",
"--hidden-import", "_ctypes",
]
def _windows_sqlite_hidden_import_args() -> list[str]:
"""
Hidden imports needed by stdlib `sqlite3` on Windows frozen builds.
`_sqlite3` may require sqlite3.dll at runtime.
"""
return [
"--hidden-import", "sqlite3",
"--hidden-import", "_sqlite3",
]
def _dedupe_paths(paths: Iterable[Path]) -> list[Path]:
unique: list[Path] = []
seen: set[Path] = set()
for path in paths:
resolved = path.resolve()
if resolved in seen:
continue
seen.add(resolved)
unique.append(resolved)
return unique
def _discover_windows_python_homes() -> list[Path]:
"""
Discover additional CPython homes installed on Windows.
Used after winget installs/repairs Python to refresh DLL discovery.
"""
if OS != "Windows":
return []
candidates: list[Path] = []
current_major = sys.version_info.major
current_minor = sys.version_info.minor
current_series = f"{current_major}.{current_minor}"
# 1) py launcher registry view
py_launcher = shutil.which("py")
if py_launcher:
result = subprocess.run(
[py_launcher, "-0p"],
capture_output=True,
text=True,
check=False,
)
for line in ((result.stdout or "") + "\n" + (result.stderr or "")).splitlines():
path_match = re.search(r"([A-Za-z]:\\[^\r\n]*python(?:\.exe)?)", line, flags=re.IGNORECASE)
if not path_match:
continue
ver_match = re.search(r"-V:(\d+\.\d+)", line)
if ver_match and ver_match.group(1) != current_series:
continue
exe = Path(path_match.group(1).strip())
home = exe.parent.parent if exe.parent.name.lower() == "scripts" else exe.parent
candidates.append(home)
# 2) common installation roots
local_appdata = Path(os.environ.get("LOCALAPPDATA", ""))
program_files = Path(os.environ.get("ProgramFiles", ""))
program_files_x86 = Path(os.environ.get("ProgramFiles(x86)", ""))
for base in (
local_appdata / "Programs" / "Python",
program_files,
program_files_x86,
):
if not base or not base.is_dir():
continue
for pattern in ("Python*",):
for home in base.glob(pattern):
if home.is_dir():
# Keep only the same interpreter series (ex: Python310 for 3.10).
m = re.fullmatch(r"python(\d+)", home.name.lower())
if not m:
continue
digits = m.group(1)
if len(digits) < 2:
continue
major = int(digits[0])
minor = int(digits[1:])
if major == current_major and minor == current_minor:
candidates.append(home)
existing = [p for p in candidates if p.is_dir()]
return _dedupe_paths(existing)
def _native_windows_runtime_roots(python_home: Path) -> list[Path]:
"""
Return likely CPython home roots on native Windows.
This handles virtualenv layouts where sys.executable lives in `.../Scripts/`.
"""
candidates: list[Path] = [python_home]
if python_home.name.lower() == "scripts":
candidates.append(python_home.parent)
for raw in (
sys.base_prefix,
sys.base_exec_prefix,
sys.prefix,
sys.exec_prefix,
os.environ.get("PYTHONHOME", ""),
):
if not raw:
continue
candidates.append(Path(raw))
candidates.extend(_discover_windows_python_homes())
existing = [p for p in candidates if p.is_dir()]
return _dedupe_paths(existing)
def _windows_runtime_search_dirs(roots: Iterable[Path]) -> list[Path]:
"""
Expand Python home roots into concrete DLL search directories.
"""
candidates: list[Path] = []
for root in roots:
candidates.extend(
[
root,
root / "DLLs",
root / "Library" / "bin", # conda-like layouts
root / "bin",
root / "libs",
]
)
existing = [p for p in candidates if p.is_dir()]
return _dedupe_paths(existing)
def _find_windows_runtime_dlls(search_dirs: Iterable[Path], patterns: tuple[str, ...]) -> list[Path]:
selected_by_name: dict[str, Path] = {}
for base in search_dirs:
for pattern in patterns:
for candidate in sorted(base.glob(pattern)):
key = candidate.name.lower()
if key in selected_by_name:
continue
selected_by_name[key] = candidate.resolve()
return list(selected_by_name.values())
def _find_windows_ssl_runtime_dlls(python_home: Path, *, include_native_roots: bool = False) -> list[Path]:
"""
Locate OpenSSL runtime DLLs required by `_ssl.pyd` on Windows.
We search both the interpreter root and its `DLLs/` subfolder.
"""
roots = _native_windows_runtime_roots(python_home) if include_native_roots else [python_home]
dirs = _windows_runtime_search_dirs(roots)
return _find_windows_runtime_dlls(dirs, ("libssl-*.dll", "libcrypto-*.dll"))
def _find_windows_ctypes_runtime_dlls(python_home: Path, *, include_native_roots: bool = False) -> list[Path]:
"""
Locate libffi runtime DLLs required by `_ctypes.pyd` on Windows.
We search both the interpreter root and its `DLLs/` subfolder.
"""
roots = _native_windows_runtime_roots(python_home) if include_native_roots else [python_home]
dirs = _windows_runtime_search_dirs(roots)
return _find_windows_runtime_dlls(dirs, ("libffi-*.dll", "libffi*.dll"))
def _find_windows_sqlite_runtime_dlls(python_home: Path, *, include_native_roots: bool = False) -> list[Path]:
"""
Locate sqlite runtime DLLs required by `_sqlite3.pyd` on Windows.
We search both the interpreter root and its `DLLs/` subfolder.
"""
roots = _native_windows_runtime_roots(python_home) if include_native_roots else [python_home]
dirs = _windows_runtime_search_dirs(roots)
return _find_windows_runtime_dlls(dirs, ("sqlite3.dll",))
def _missing_windows_runtime_labels(python_home: Path, *, include_native_roots: bool = False) -> list[str]:
"""
Return missing runtime labels among:
- ctypes/libffi
- sqlite3
- ssl/libssl+libcrypto
"""
missing: list[str] = []
ffi = _find_windows_ctypes_runtime_dlls(python_home, include_native_roots=include_native_roots)
if not ffi:
missing.append("ctypes/libffi (libffi-*.dll)")
sqlite = _find_windows_sqlite_runtime_dlls(python_home, include_native_roots=include_native_roots)
if not sqlite:
missing.append("sqlite3 (sqlite3.dll)")
ssl = _find_windows_ssl_runtime_dlls(python_home, include_native_roots=include_native_roots)
ssl_names = {p.name.lower() for p in ssl}
has_libssl = any(name.startswith("libssl-") and name.endswith(".dll") for name in ssl_names)
has_libcrypto = any(name.startswith("libcrypto-") and name.endswith(".dll") for name in ssl_names)
if not (has_libssl and has_libcrypto):
missing.append("ssl (libssl-*.dll + libcrypto-*.dll)")
return missing
def _ensure_windows_runtime_dlls_available() -> None:
"""
Ensure runtime DLLs required for frozen stdlib extensions are discoverable.
If missing, try to auto-install/repair current CPython via winget.
"""
if OS != "Windows":
return
python_home = Path(sys.executable).resolve().parent
missing = _missing_windows_runtime_labels(python_home, include_native_roots=True)
if not missing:
_ok("Runtime DLLs Windows détectées (libffi/sqlite3/OpenSSL)")
return
_warn("Runtime DLLs manquantes détectées : " + ", ".join(missing))
_info("Tentative de correction automatique via winget...")
winget = shutil.which("winget")
if winget:
py_ver = f"{sys.version_info.major}.{sys.version_info.minor}"
pkg = f"Python.Python.{py_ver}"
common_args = ["--id", pkg, "--silent", "--accept-package-agreements", "--accept-source-agreements"]
_run([winget, "install", *common_args], check=False)
_run([winget, "upgrade", *common_args], check=False)
else:
_warn("winget introuvable — correction automatique impossible sur cette machine.")
# Re-run verification after potential install/repair.
# Some installers finalize files a bit after process return.
missing_after: list[str] = []
for attempt in range(3):
if attempt > 0:
time.sleep(1.0)
missing_after = _missing_windows_runtime_labels(python_home, include_native_roots=True)
if not missing_after:
break
_info(f"Re-vérification runtime DLLs ({attempt + 1}/3) : encore manquant -> {', '.join(missing_after)}")
if missing_after:
joined = ", ".join(missing_after)
raise RuntimeError(
"DLLs runtime Windows toujours absentes après tentative automatique : "
f"{joined}. Réinstallez/réparez Python {sys.version_info.major}.{sys.version_info.minor}."
)
_ok("Runtime DLLs Windows installées et détectées")
def _add_windows_ssl_to_pyinstaller_native(cmd: list[str]) -> None:
"""Add SSL-related imports/binaries to a native Windows PyInstaller command."""
cmd.extend(_windows_ssl_hidden_import_args())
dlls = _find_windows_ssl_runtime_dlls(
Path(sys.executable).resolve().parent,
include_native_roots=True,
)
if not dlls:
_warn(
"DLLs OpenSSL introuvables près de l'interpréteur Python "
"(libssl/libcrypto) ; HTTPS pourrait rester indisponible dans le bundle."
)
return
for dll in dlls:
# --add-binary syntax on Windows: SRC;DEST_DIR_IN_BUNDLE
cmd += ["--add-binary", f"{dll};."]
_ok("Support SSL Windows ajouté au bundle PyInstaller")
def _add_windows_ctypes_to_pyinstaller_native(cmd: list[str]) -> None:
"""Add ctypes/libffi runtime support to a native Windows PyInstaller command."""
cmd.extend(_windows_ctypes_hidden_import_args())
dlls = _find_windows_ctypes_runtime_dlls(
Path(sys.executable).resolve().parent,
include_native_roots=True,
)
if not dlls:
_warn(
"DLL libffi introuvable près de l'interpréteur Python "
"(libffi-*.dll) ; ctypes peut échouer dans le bundle."
)
return
for dll in dlls:
cmd += ["--add-binary", f"{dll};."]
_ok("Support ctypes/libffi Windows ajouté au bundle PyInstaller")
def _add_windows_sqlite_to_pyinstaller_native(cmd: list[str]) -> None:
"""Add sqlite runtime support to a native Windows PyInstaller command."""
cmd.extend(_windows_sqlite_hidden_import_args())
dlls = _find_windows_sqlite_runtime_dlls(
Path(sys.executable).resolve().parent,
include_native_roots=True,
)
if not dlls:
_warn(
"DLL sqlite3 introuvable près de l'interpréteur Python "
"(sqlite3.dll) ; sqlite3 peut échouer dans le bundle."
)
return
for dll in dlls:
cmd += ["--add-binary", f"{dll};."]
_ok("Support sqlite3 Windows ajouté au bundle PyInstaller")
def _add_windows_icu_to_pyinstaller_native(cmd: list[str]) -> None:
"""Add ICU runtime DLLs to a native Windows PyInstaller command when found."""
pyside_dirs: list[Path] = []
try:
import PySide6 as _pyside6
except Exception:
pyside_dirs = []
else:
pyside_dirs.append(Path(_pyside6.__file__).resolve().parent)
pyside_dirs.append(Path(sys.executable).resolve().parent)
dlls = _select_windows_icu_runtime_dlls(pyside_dirs)
source = "PySide6/Python"
if not dlls:
dlls = _select_windows_icu_runtime_dlls(_native_windows_system_icu_search_dirs())
source = "Windows system runtime"
if not dlls:
_warn(
"DLLs ICU introuvables pres de PySide6 et dans le runtime Windows ; "
"le bundle Qt peut dependre du systeme."
)
return
for dll in dlls:
cmd += ["--add-binary", f"{dll};."]
_ok(f"Support ICU Windows ajoute au bundle PyInstaller ({source})")
def _add_windows_ssl_to_pyinstaller_wine(cmd: list[str], wine_env: dict[str, str]) -> None:
"""Add SSL-related imports/binaries to a Wine (Windows target) PyInstaller command."""
cmd.extend(_windows_ssl_hidden_import_args())
dlls = _find_windows_ssl_runtime_dlls(_WIN_PY_EXE.parent)
if not dlls:
_warn(
"DLLs OpenSSL introuvables dans le Python Wine "
"(libssl/libcrypto) ; HTTPS pourrait rester indisponible dans le bundle."
)
return
for dll in dlls:
win_dll = subprocess.check_output(
["winepath", "-w", str(dll)],
env=wine_env,
text=True,
).strip()
cmd += ["--add-binary", f"{win_dll};."]
_ok("Support SSL Windows ajouté au bundle PyInstaller (Wine)")
def _add_windows_ctypes_to_pyinstaller_wine(cmd: list[str], wine_env: dict[str, str]) -> None:
"""Add ctypes/libffi runtime support to a Wine (Windows target) PyInstaller command."""
cmd.extend(_windows_ctypes_hidden_import_args())
dlls = _find_windows_ctypes_runtime_dlls(_WIN_PY_EXE.parent)
if not dlls:
_warn(
"DLL libffi introuvable dans le Python Wine "
"(libffi-*.dll) ; ctypes peut échouer dans le bundle."
)
return
for dll in dlls:
win_dll = subprocess.check_output(
["winepath", "-w", str(dll)],
env=wine_env,
text=True,
).strip()
cmd += ["--add-binary", f"{win_dll};."]
_ok("Support ctypes/libffi Windows ajouté au bundle PyInstaller (Wine)")
def _add_windows_sqlite_to_pyinstaller_wine(cmd: list[str], wine_env: dict[str, str]) -> None:
"""Add sqlite runtime support to a Wine (Windows target) PyInstaller command."""
cmd.extend(_windows_sqlite_hidden_import_args())
dlls = _find_windows_sqlite_runtime_dlls(_WIN_PY_EXE.parent)
if not dlls:
_warn(
"DLL sqlite3 introuvable dans le Python Wine "
"(sqlite3.dll) ; sqlite3 peut échouer dans le bundle."
)
return
for dll in dlls:
win_dll = subprocess.check_output(
["winepath", "-w", str(dll)],
env=wine_env,
text=True,
).strip()
cmd += ["--add-binary", f"{win_dll};."]
_ok("Support sqlite3 Windows ajouté au bundle PyInstaller (Wine)")
def _ensure_windows_icu_runtime(wine_env: dict[str, str]) -> list[Path]:
"""
Vérifie la présence des DLL ICU dans le préfixe Wine.
Si absentes : télécharge le package NuGet Microsoft.ICU.ICU4C.Runtime.win-x64
et extrait les DLL nécessaires.
Retourne la liste des DLL ICU trouvées.
"""
icu_dir = _WINE_PREFIX / "drive_c" / "icu"
icu_dir.mkdir(parents=True, exist_ok=True)
expected = ["icudt*.dll", "icuin*.dll", "icuuc*.dll"]
found: list[Path] = []
# Recherche existante
for pattern in expected:
found.extend(icu_dir.glob(pattern))
if len(found) >= 3:
_ok(f"ICU Windows déjà présentes ({len(found)} DLL)")
return found
_warn("DLL ICU absentes — téléchargement du runtime ICU Windows…")
# Téléchargement du package NuGet
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".nupkg")
tmp.close()
urllib.request.urlretrieve(_WIN_ICU_NUGET_URL, tmp.name)
_ok(f"Package ICU téléchargé {tmp.name}")
#Extraction
with zipfile.ZipFile(tmp.name, "r") as z:
entries = z.namelist()
extracted_any = False
for member in entries:
normalized = member.replace("\\", "/")
lname = normalized.lower()
if not lname.endswith(".dll"):
continue
# compare sur le basename (ex: icudt72.dll) pour que "icudt*.dll" matche
base = Path(normalized).name.lower()
# expected doit contenir des motifs comme "icudt*.dll", "icuin*.dll", "icuuc*.dll"
if not any(fnmatch.fnmatch(base, pat) for pat in expected):
_info(f"SKIP DLL (no expected match): {member}")
continue
target = icu_dir / base
target.parent.mkdir(parents=True, exist_ok=True)
with z.open(member) as src, target.open("wb") as dst:
shutil.copyfileobj(src, dst)
found.append(target)
extracted_any = True
_ok(f"Extracted ICU DLL: {target.name}")
if not extracted_any:
_warn("Aucune DLL extraite du package NuGet. Aperçu des 40 premières entrées :")
for i, name in enumerate(entries[:40], 1):
_info(f" {i:02d}: {name}")
raise RuntimeError("Impossible d'extraire toutes les DLL ICU du package NuGet")
_ok(f"ICU Windows extraites dans {icu_dir.relative_to(ROOT)}")
os.unlink(tmp.name)
if len(found) < 3:
raise RuntimeError("Impossible d'extraire toutes les DLL ICU du package NuGet")
_ok(f"ICU Windows extraites ({len(found)} DLL)")
return found
def _add_windows_icu_to_pyinstaller_wine(cmd: list[str], wine_env: dict[str, str]) -> None:
"""Add ICU runtime DLLs to a Wine (Windows target) PyInstaller command."""
dlls = _find_windows_icu_dlls([_wine_pyside6_dir(), _WIN_PY_EXE.parent])
if not dlls:
_warn("DLLs ICU introuvables dans le Python Wine ; le bundle Qt risque d'être incomplet.")