-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.py
More file actions
executable file
·2253 lines (1926 loc) · 76.1 KB
/
setup.py
File metadata and controls
executable file
·2253 lines (1926 loc) · 76.1 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
"""
Mediarecode — Setup & Dependency Installer
==========================================
Installs Python dependencies and external tools required by the application.
Linux (Debian/Ubuntu) → pip + apt packages + GitHub binaries
Linux (Fedora/RHEL) → pip + dnf packages + GitHub binaries
macOS → pip + Homebrew packages + GitHub binaries
Windows → pip + winget packages + GitHub binaries (user-local)
Usage:
See platform-specific command shown by --help output.
Options:
--no-github Skip downloading dovi_tool / hdr10plus_tool from GitHub
--prefix PATH Installation prefix for GitHub binaries
Default: /usr/local on Linux/macOS,
<mediarecode folder>\\tools on Windows
--dry-run Print what would be done without executing anything
--force Retry installs and regenerate Windows tool paths
"""
from __future__ import annotations
import argparse
import ctypes
import configparser
import json
import locale
import os
import platform
import re
import shutil
import stat
import subprocess
import sys
import tarfile
import tempfile
import urllib.error
import urllib.request
import zipfile
from pathlib import Path
from typing import Any, Optional
from core.lang_tags import Rfc5646LanguageTags
# ---------------------------------------------------------------------------
# Terminal colours (no external deps)
# ---------------------------------------------------------------------------
def _ensure_text_stream(name: str, mode: str) -> None:
"""Provide a valid stdio stream when running without a console."""
if getattr(sys, name, None) is None:
setattr(sys, name, open(os.devnull, mode, encoding="utf-8"))
def _stream_isatty(stream: object) -> bool:
isatty = getattr(stream, "isatty", None)
if not callable(isatty):
return False
try:
return bool(isatty())
except OSError:
return False
_ensure_text_stream("stdout", "w")
_ensure_text_stream("stderr", "w")
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 platform.system() != "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()
_USE_COLOR = _stream_isatty(sys.stdout) and platform.system() != "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_STEP = "▸" if _UI_UNICODE else ">"
_UI_BAR = "─" if _UI_UNICODE else "-"
def _c(code: str, text: str) -> str:
return f"\033[{code}m{text}\033[0m" if _USE_COLOR else text
def ok(msg: str) -> None: print(_c("32", f" {_UI_OK} {msg}"))
def info(msg: str) -> None: print(_c("36", f" {_UI_INFO} {msg}"))
def warn(msg: str) -> None: print(_c("33", f" {_UI_WARN} {msg}"))
def error(msg: str) -> None: print(_c("31", f" {_UI_ERR} {msg}"), file=sys.stderr)
def title(msg: str) -> None: print(_c("1;34", f"\n{_UI_BAR*60}\n {msg}\n{_UI_BAR*60}"))
def step(msg: str) -> None: print(_c("1;37", f"\n {_UI_STEP} {msg}"))
# ---------------------------------------------------------------------------
# OS detection
# ---------------------------------------------------------------------------
OS = platform.system() # "Linux" | "Windows" | "Darwin"
MACHINE = platform.machine().lower() # "x86_64" | "aarch64" | "arm64" | "amd64"
PYTHON_CMD = "py" if OS == "Windows" else "python3"
WINDOWS_TOOL_FILENAMES: dict[str, tuple[str, ...]] = {
"ffmpeg": ("ffmpeg.exe",),
"ffprobe": ("ffprobe.exe",),
"mediainfo": ("MediaInfo.exe", "mediainfo.exe"),
"dovi_tool": ("dovi_tool.exe",),
"hdr10plus_tool": ("hdr10plus_tool.exe",),
"eac3to": ("eac3to.exe",),
}
WINDOWS_WINGET_PATTERNS: dict[str, tuple[str, ...]] = {
"ffmpeg": ("Gyan.FFmpeg*",),
"ffprobe": ("Gyan.FFmpeg*",),
"mediainfo": ("MediaArea.MediaInfo_*",),
}
WINDOWS_CONFIG_TOOL_ORDER: tuple[str, ...] = (
"ffmpeg",
"ffprobe",
"mediainfo",
"dovi_tool",
"hdr10plus_tool",
"eac3to",
)
# Outils qui écrivent dans les dossiers protégés (Windows CFA allowlist).
WINDOWS_CFA_WRITER_TOOLS: tuple[str, ...] = (
"ffmpeg",
)
def detect_linux_distro() -> str:
"""Return 'debian', 'fedora', or 'unknown'."""
try:
with open("/etc/os-release") as f:
text = f.read().lower()
if any(k in text for k in ("ubuntu", "debian", "linuxmint", "pop!_os", "kali", "raspbian")):
return "debian"
if any(k in text for k in ("fedora", "rhel", "centos", "rocky", "almalinux", "nobara")):
return "fedora"
except FileNotFoundError:
pass
if shutil.which("apt-get"):
return "debian"
if shutil.which("dnf") or shutil.which("yum"):
return "fedora"
return "unknown"
# ---------------------------------------------------------------------------
# Python requirements
# ---------------------------------------------------------------------------
PYTHON_PACKAGES = [
"PySide6",
"pymediainfo>=6.1.0",
]
# ---------------------------------------------------------------------------
# External tools definition
# ---------------------------------------------------------------------------
# Tools available via system package managers
# format: { "executable": {"apt": "pkg", "dnf": "pkg", "brew": "pkg",
# "winget": "id", "desc": "..."} }
SYSTEM_TOOLS: dict[str, dict] = {
"pip": {
"apt": "python3-pip",
"dnf": "python3-pip",
"brew": "python",
"winget": "buyukakyuz.install-nothing",
"desc": "Python Package Installer",
},
"openGL": {
"apt": "libegl1-mesa",
"dnf": "mesa-libEGL",
"brew": "xquartz",
"winget": "",
"desc": "OpenGL libraries",
"path_check": False,
},
"ffmpeg": {
"apt": "ffmpeg",
"dnf": "ffmpeg",
"brew": "ffmpeg",
"winget": "Gyan.FFmpeg",
"desc": "Video/audio encoder and converter",
"dnf_note": "Requires RPM Fusion (handled automatically)",
},
"ffprobe": {
"apt": "ffmpeg",
"dnf": "ffmpeg",
"brew": "ffmpeg",
"winget": "Gyan.FFmpeg",
"desc": "Media file analyser (ships with ffmpeg)",
},
"mediainfo": {
"apt": "mediainfo",
"dnf": "mediainfo",
"brew": "mediainfo",
"winget": "MediaArea.MediaInfo",
"desc": "Media metadata tool",
},
}
# Tools distributed as GitHub release binaries.
#
# asset_patterns keys: (OS, arch_key)
# OS — "Linux" | "Darwin" | "Windows"
# arch_key — "x86_64" | "arm64"
#
# Each value:
# suffix — substring that uniquely identifies the asset filename
# fmt — "tar.gz" or "zip"
GITHUB_TOOLS: dict[str, dict] = {
"dovi_tool": {
"repo": "quietvoid/dovi_tool",
"desc": "Dolby Vision RPU extraction and injection",
"binary_name": {
"Linux": "dovi_tool",
"Darwin": "dovi_tool",
"Windows": "dovi_tool.exe",
},
"asset_patterns": {
("Linux", "x86_64"): {"suffix": "x86_64-unknown-linux-musl.tar.gz", "fmt": "tar.gz"},
("Linux", "arm64"): {"suffix": "aarch64-unknown-linux-musl.tar.gz", "fmt": "tar.gz"},
("Darwin", "x86_64"): {"suffix": "universal-macOS.zip", "fmt": "zip"},
("Darwin", "arm64"): {"suffix": "universal-macOS.zip", "fmt": "zip"},
("Windows", "x86_64"): {"suffix": "x86_64-pc-windows-msvc.zip", "fmt": "zip"},
("Windows", "arm64"): {"suffix": "aarch64-pc-windows-msvc.zip", "fmt": "zip"},
},
},
"hdr10plus_tool": {
"repo": "quietvoid/hdr10plus_tool",
"desc": "HDR10+ metadata extraction and injection",
"binary_name": {
"Linux": "hdr10plus_tool",
"Darwin": "hdr10plus_tool",
"Windows": "hdr10plus_tool.exe",
},
"asset_patterns": {
("Linux", "x86_64"): {"suffix": "x86_64-unknown-linux-musl.tar.gz", "fmt": "tar.gz"},
("Linux", "arm64"): {"suffix": "aarch64-unknown-linux-musl.tar.gz", "fmt": "tar.gz"},
("Darwin", "x86_64"): {"suffix": "universal-macOS.zip", "fmt": "zip"},
("Darwin", "arm64"): {"suffix": "universal-macOS.zip", "fmt": "zip"},
("Windows", "x86_64"): {"suffix": "x86_64-pc-windows-msvc.zip", "fmt": "zip"},
("Windows", "arm64"): {"suffix": "aarch64-pc-windows-msvc.zip", "fmt": "zip"},
},
},
}
# Tools with no automated install path (optional)
MANUAL_TOOLS: dict[str, dict] = {
"eac3to": {
"desc": "Advanced audio conversion (Windows only, optional)",
"note": "Download from: https://forum.doom9.org/showthread.php?t=125966",
"platforms": ["Windows"],
},
}
# ---------------------------------------------------------------------------
# Command runner
# ---------------------------------------------------------------------------
def _windows_no_window_subprocess_kwargs() -> dict[str, Any]:
"""Return subprocess kwargs that hide console windows on Windows."""
if OS != "Windows":
return {}
# If a console is already visible (first-launch setup), keep child process
# output in that same console.
try:
if bool(ctypes.windll.kernel32.GetConsoleWindow()): # type: ignore[attr-defined]
return {}
except Exception:
pass
if not getattr(sys, "frozen", False):
# CLI execution from a terminal should keep standard behavior.
return {}
kwargs: dict[str, Any] = {}
create_no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0)
if create_no_window:
kwargs["creationflags"] = create_no_window
startupinfo_cls = getattr(subprocess, "STARTUPINFO", None)
if startupinfo_cls is not None:
startupinfo = startupinfo_cls()
startf_use_showwindow = getattr(subprocess, "STARTF_USESHOWWINDOW", 0)
if startf_use_showwindow:
startupinfo.dwFlags |= startf_use_showwindow
startupinfo.wShowWindow = getattr(subprocess, "SW_HIDE", 0)
kwargs["startupinfo"] = startupinfo
return kwargs
def run(cmd: list[str], dry_run: bool = False, check: bool = True,
capture: bool = False) -> Optional[subprocess.CompletedProcess]:
"""Run a shell command, optionally printing only (dry_run)."""
display = " ".join(str(c) for c in cmd)
info(f"$ {display}")
if dry_run:
return None
result = subprocess.run(
cmd,
capture_output=capture,
text=True,
check=False,
**_windows_no_window_subprocess_kwargs(),
)
if check and result.returncode != 0:
stderr = getattr(result, "stderr", "")
raise RuntimeError(
f"Command failed (exit {result.returncode}): {display}"
+ (f"\n{stderr.strip()}" if stderr else "")
)
return result
# ---------------------------------------------------------------------------
# Privilege helpers
# ---------------------------------------------------------------------------
def is_root() -> bool:
return os.getuid() == 0 if hasattr(os, "getuid") else False
def sudo_prefix(dry_run: bool = False) -> list[str]:
"""Return ['sudo'] if not root and sudo is available, else [].
In dry-run mode never raises — returns ['sudo'] as a placeholder."""
if is_root():
return []
if shutil.which("sudo"):
return ["sudo"]
if dry_run:
return ["sudo"]
raise RuntimeError(
"This step requires root privileges. "
"Re-run as root or install sudo."
)
# ---------------------------------------------------------------------------
# Architecture helpers
# ---------------------------------------------------------------------------
def _arch_key() -> str:
"""Normalise platform.machine() to 'x86_64' or 'arm64'."""
m = MACHINE
if m in ("x86_64", "amd64"):
return "x86_64"
if m in ("aarch64", "arm64"):
return "arm64"
raise RuntimeError(
f"Unsupported architecture '{platform.machine()}'. "
"Install dovi_tool and hdr10plus_tool manually."
)
def _is_msix_install() -> bool:
"""
True si l'application tourne depuis un package MSIX installé
(dossier Program Files\\WindowsApps, lecture seule).
"""
if OS != "Windows":
return False
try:
exe = Path(sys.executable).resolve()
except Exception:
return False
lower = str(exe).lower()
return "\\windowsapps\\" in lower or "/windowsapps/" in lower
def _exe_dir_is_readonly() -> bool:
"""
True si le dossier contenant l'exécutable n'est pas writable
(cas typique : installation admin dans Program Files).
"""
if OS != "Windows":
return False
try:
exe_dir = Path(sys.executable).resolve().parent
except Exception:
return False
try:
probe = exe_dir / ".mediarecode_write_probe"
probe.write_text("", encoding="utf-8")
probe.unlink(missing_ok=True)
return False
except Exception:
return True
def _windows_user_tools_dir() -> Path:
"""
Dossier d'installation des outils binaires côté utilisateur.
Sous MSIX, %LOCALAPPDATA%\\Mediarecode\\tools est la seule
localisation writable sans élévation.
"""
local_appdata = os.environ.get("LOCALAPPDATA")
base = Path(local_appdata) if local_appdata else Path.home() / "AppData" / "Local"
return base / "Mediarecode" / "tools"
def _default_prefix() -> Path:
"""Return a sensible default install prefix for the current OS."""
if OS == "Windows":
# Sous MSIX, Program Files\\WindowsApps est read-only pour l'utilisateur
# → on installe dans %LOCALAPPDATA%\\Mediarecode\\tools.
# En dev / installeur classique : tools/ à côté de setup.py.
if _is_msix_install() or _exe_dir_is_readonly():
return _windows_user_tools_dir()
return Path(__file__).parent / "tools"
return Path("/usr/local")
def _windows_config_dir() -> Path:
appdata = os.environ.get("APPDATA")
if appdata:
return Path(appdata) / "mediarecode"
return Path.home() / "AppData" / "Roaming" / "mediarecode"
def _is_windows_frozen() -> bool:
return OS == "Windows" and bool(getattr(sys, "frozen", False))
def _windows_frozen_runtime_dir() -> Path | None:
"""
Return the frozen runtime directory containing python extension modules/DLLs.
Supports onedir (`_internal`) and onefile (`_MEIPASS`) layouts.
"""
if not _is_windows_frozen():
return None
candidates: list[Path] = []
meipass = getattr(sys, "_MEIPASS", None)
if meipass:
candidates.append(Path(str(meipass)))
exe_dir = Path(sys.executable).resolve().parent
candidates.append(exe_dir / "_internal")
candidates.append(exe_dir)
for candidate in candidates:
if candidate.is_dir():
return candidate
return None
def verify_windows_frozen_python_runtime() -> None:
"""
Ensure critical Python runtime pieces are present in frozen Windows bundles.
We explicitly check `_ctypes.pyd` + `libffi-*.dll`.
"""
runtime_dir = _windows_frozen_runtime_dir()
if runtime_dir is None:
return
required_patterns: dict[str, str] = {
"_ctypes.pyd": "_ctypes.pyd",
"libffi": "libffi-*.dll",
}
missing: list[str] = []
for label, pattern in required_patterns.items():
if not any(runtime_dir.glob(pattern)):
missing.append(f"{label} ({pattern})")
if missing:
raise RuntimeError(
"Bundle Python Windows incomplet (runtime manquant): "
+ ", ".join(missing)
+ ". Rebuild requis."
)
ok(f"Frozen Python runtime OK ({runtime_dir})")
def _config_ini_path() -> Path:
"""Return the config.ini path used by the application on the current OS."""
if OS == "Windows":
if getattr(sys, "frozen", False):
return _windows_config_dir() / "config.ini"
return Path(__file__).parent / "config.ini"
xdg = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
return xdg / "mediarecode" / "config.ini"
def _dedupe_paths(paths: list[Path]) -> list[Path]:
seen: set[str] = set()
unique: list[Path] = []
for path in paths:
key = str(path).lower()
if key in seen:
continue
seen.add(key)
unique.append(path)
return unique
def _tools_section_bounds(lines: list[str]) -> tuple[int, int]:
start = -1
end = len(lines)
for index, line in enumerate(lines):
if line.strip().lower() == "[tools]":
start = index
break
if start == -1:
return -1, len(lines)
for index in range(start + 1, len(lines)):
stripped = lines[index].strip()
if stripped.startswith("[") and stripped.endswith("]"):
end = index
break
return start, end
def _section_bounds(lines: list[str], section: str) -> tuple[int, int]:
start = -1
end = len(lines)
target = f"[{section.lower()}]"
for index, line in enumerate(lines):
if line.strip().lower() == target:
start = index
break
if start == -1:
return -1, len(lines)
for index in range(start + 1, len(lines)):
stripped = lines[index].strip()
if stripped.startswith("[") and stripped.endswith("]"):
end = index
break
return start, end
def _normalize_windows_backslashes(value: str) -> str:
"""Collapse repeated Windows path separators while preserving UNC prefixes."""
text = str(value)
if OS != "Windows" or "\\" not in text:
return text
leading = len(text) - len(text.lstrip("\\"))
body = text[leading:]
body = re.sub(r"\\{2,}", r"\\", body)
if leading >= 2:
prefix = "\\\\"
elif leading == 1:
prefix = "\\"
else:
prefix = ""
return prefix + body
def _sanitize_windows_tools_lines(lines: list[str]) -> list[str]:
if OS != "Windows":
return lines
start, end = _tools_section_bounds(lines)
if start == -1:
return lines
for index in range(start + 1, end):
stripped = lines[index].strip()
if not stripped or stripped.startswith(("#", ";")) or "=" not in stripped:
continue
lhs, rhs = stripped.split("=", 1)
normalized = _normalize_windows_backslashes(rhs.strip())
if normalized != rhs.strip():
lines[index] = f"{lhs.strip()} = {normalized}"
return lines
def _update_ini_tools_section(
path: Path,
tool_values: dict[str, str],
dry_run: bool = False,
replace_keys: set[str] | None = None,
prune_keys: set[str] | None = None,
) -> None:
"""Ajoute les chemins détectés dans [tools] sans écraser une valeur explicite."""
if not tool_values and not prune_keys:
return
replace_keys = {key.lower() for key in (replace_keys or set())}
prune_keys = {key.lower() for key in (prune_keys or set())}
text = path.read_text(encoding="utf-8") if path.exists() else ""
lines = _sanitize_windows_tools_lines(text.splitlines())
start, end = _tools_section_bounds(lines)
if start == -1:
if lines and lines[-1].strip():
lines.append("")
lines.extend(["[tools]"])
start = len(lines) - 1
end = len(lines)
if prune_keys:
for index in range(end - 1, start, -1):
stripped = lines[index].strip()
if not stripped or stripped.startswith(("#", ";")) or "=" not in stripped:
continue
lhs, _rhs = stripped.split("=", 1)
if lhs.strip().lower() not in prune_keys:
continue
del lines[index]
end -= 1
insert_at = end
for key, value in tool_values.items():
rendered = _normalize_windows_backslashes(value)
updated = False
for index in range(start + 1, end):
stripped = lines[index].strip()
if not stripped or stripped.startswith(("#", ";")) or "=" not in stripped:
continue
lhs, rhs = stripped.split("=", 1)
if lhs.strip().lower() != key.lower():
continue
if not rhs.strip() or key.lower() in replace_keys:
lines[index] = f"{key} = {rendered}"
updated = True
break
if not updated:
lines.insert(insert_at, f"{key} = {rendered}")
insert_at += 1
end += 1
lines = _sanitize_windows_tools_lines(lines)
if dry_run:
return
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
def _system_language_code() -> str:
candidates: list[str | None] = [
os.environ.get("LC_ALL"),
(os.environ.get("LANGUAGE") or "").split(":", 1)[0] or None,
os.environ.get("LANG"),
]
try:
candidates.append(locale.getlocale()[0])
except (TypeError, ValueError):
pass
for candidate in candidates:
code = Rfc5646LanguageTags.from_locale_name(candidate)
if code:
return code
return "eng"
def _available_ui_languages() -> list[tuple[str, str]]:
"""
Return the list of UI languages available in locales.json as
(iso639-2 code, display name) pairs, sorted by display name.
"""
iso_names: dict[str, str] = {
"eng": "English",
"fra": "Français",
"deu": "Deutsch",
"spa": "Español",
"ita": "Italiano",
"por": "Português",
"nld": "Nederlands",
"pol": "Polski",
"rus": "Русский",
"jpn": "日本語",
"zho": "中文",
"kor": "한국어",
"ara": "العربية",
}
try:
locales_path = Path(__file__).parent / "locales.json"
data: dict = json.loads(locales_path.read_text(encoding="utf-8"))
codes: set[str] = set()
for values in data.values():
if isinstance(values, dict):
codes.update(str(key).lower() for key in values)
if codes:
items = [(code, iso_names.get(code, code)) for code in sorted(codes)]
return sorted(items, key=lambda item: item[1].lower())
except Exception:
pass
return [("eng", "English"), ("fra", "Français")]
def _ask_language_dialog_qt_in_process(languages: list[tuple[str, str]]) -> str | None:
"""Show the language dialog in-process and return the selected code."""
try:
from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
QApplication,
QComboBox,
QDialog,
QDialogButtonBox,
QLabel,
QVBoxLayout,
)
except Exception:
return None
_app = QApplication.instance() or QApplication(sys.argv[:1])
dlg = QDialog()
dlg.setWindowTitle("Mediarecode - Interface Language")
dlg.setWindowFlags(dlg.windowFlags() | Qt.WindowType.WindowStaysOnTopHint)
dlg.setMinimumWidth(380)
layout = QVBoxLayout(dlg)
layout.setContentsMargins(16, 16, 16, 16)
layout.setSpacing(10)
label = QLabel("Select the interface language / Choisissez la langue:")
label.setWordWrap(True)
layout.addWidget(label)
combo = QComboBox()
for code, name in languages:
combo.addItem(name, code)
layout.addWidget(combo)
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)
buttons.accepted.connect(dlg.accept)
layout.addWidget(buttons)
if dlg.exec() == QDialog.DialogCode.Accepted:
selected = combo.currentData()
if isinstance(selected, str):
return selected.strip().lower()
return None
def _python_executable_for_qt_subprocess() -> str | None:
"""Return a Python interpreter suitable for `python -c` subprocess calls."""
candidates = [getattr(sys, "executable", ""), getattr(sys, "_base_executable", "")]
for candidate in candidates:
if not candidate:
continue
name = Path(candidate).name.lower()
if name.startswith("python") or name in {"py", "py.exe"}:
return candidate
for command in ("python3", "python", "py"):
found = shutil.which(command)
if found:
return found
return None
def _ask_language_dialog(languages: list[tuple[str, str]]) -> str | None:
"""Show a language picker and return the chosen ISO 639-2 code."""
if not languages:
return None
valid_codes = {code for code, _ in languages}
if getattr(sys, "frozen", False):
# In PyInstaller bundles, sys.executable is mediarecode.exe, not python.exe.
code = _ask_language_dialog_qt_in_process(languages)
if code in valid_codes:
return code
else:
qt_script = """\
import sys, json
from PySide6.QtWidgets import (
QApplication, QDialog, QVBoxLayout, QLabel, QComboBox, QDialogButtonBox,
)
from PySide6.QtCore import Qt
languages = json.loads(sys.argv[1])
app = QApplication.instance() or QApplication(sys.argv[:1])
dlg = QDialog()
dlg.setWindowTitle("Mediarecode - Interface Language")
dlg.setWindowFlags(dlg.windowFlags() | Qt.WindowType.WindowStaysOnTopHint)
dlg.setMinimumWidth(380)
layout = QVBoxLayout(dlg)
layout.setContentsMargins(16, 16, 16, 16)
layout.setSpacing(10)
label = QLabel("Select the interface language / Choisissez la langue:")
label.setWordWrap(True)
layout.addWidget(label)
combo = QComboBox()
for code, name in languages:
combo.addItem(name, code)
layout.addWidget(combo)
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)
buttons.accepted.connect(dlg.accept)
layout.addWidget(buttons)
if dlg.exec() == QDialog.DialogCode.Accepted:
print(combo.currentData(), end="")
"""
python_exe = _python_executable_for_qt_subprocess()
if python_exe:
try:
result = subprocess.run(
[python_exe, "-c", qt_script, json.dumps(languages)],
capture_output=True,
text=True,
check=False,
timeout=120,
**_windows_no_window_subprocess_kwargs(),
)
if result.returncode == 0:
code = result.stdout.strip().lower()
if code in valid_codes:
return code
except Exception:
pass
if not _stream_isatty(sys.stdin) or not _stream_isatty(sys.stdout):
return None
bar = _UI_BAR * 40
print(f"\n {bar}")
print(" Select interface language / Choisissez la langue :")
for index, (code, name) in enumerate(languages, 1):
print(f" {index:2d}. {name} ({code})")
print(f" {bar}")
try:
raw = input(f" Choice [1-{len(languages)}] (Enter = auto-detect): ").strip()
except (EOFError, RuntimeError):
return None
if not raw:
return None
if raw.isdigit():
selected_index = int(raw) - 1
if 0 <= selected_index < len(languages):
return languages[selected_index][0]
return None
def initialize_config_ini_language(
dry_run: bool,
force: bool = False,
ini_path: Path | None = None,
) -> None:
"""
Initialise la langue UI dans config.ini.
- Windows : popup de sélection de langue.
- Linux / macOS : détection automatique depuis la locale système.
"""
title("Step 5 — config.ini UI language")
if ini_path is None:
ini_path = _config_ini_path()
parser = configparser.ConfigParser(
inline_comment_prefixes=("#",),
default_section="DEFAULT",
)
if ini_path.exists():
parser.read(ini_path, encoding="utf-8")
existing = ""
if parser.has_option("ui", "language"):
existing = parser.get("ui", "language").strip()
if existing and not force:
ok(f"config.ini already defines ui.language = {existing}")
return
chosen: str | None = None
if not dry_run and OS == "Windows":
chosen = _ask_language_dialog(_available_ui_languages())
if chosen:
info(f"Language selected by user: {chosen}")
else:
info("Language dialog cancelled or unavailable — falling back to system detection")
detected = chosen or _system_language_code()
info(f"UI language: {detected}")
text = ini_path.read_text(encoding="utf-8") if ini_path.exists() else ""
lines = text.splitlines()
start, end = _section_bounds(lines, "ui")
if start == -1:
if lines and lines[-1].strip():
lines.append("")
lines.extend(["[ui]"])
start = len(lines) - 1
end = len(lines)
updated = False
for index in range(start + 1, end):
stripped = lines[index].strip()
if not stripped or stripped.startswith(("#", ";")) or "=" not in stripped:
continue
lhs, _rhs = stripped.split("=", 1)
if lhs.strip().lower() != "language":
continue
lines[index] = f"language = {detected}"
updated = True
break
if not updated:
lines.insert(end, f"language = {detected}")
if dry_run:
ok(f"[dry-run] config.ini UI language would be set to {detected}")
return
ini_path.parent.mkdir(parents=True, exist_ok=True)
ini_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
ok(f"config.ini UI language set to {detected}")
def _windows_winget_root() -> Path:
local_app_data = os.environ.get("LOCALAPPDATA")
if local_app_data:
return Path(local_app_data) / "Microsoft" / "WinGet" / "Packages"
return Path.home() / "AppData" / "Local" / "Microsoft" / "WinGet" / "Packages"
def _windows_program_files_dirs() -> list[Path]:
dirs: list[Path] = []
for env_name, default in (
("ProgramFiles", r"C:\Program Files"),
("ProgramFiles(x86)", r"C:\Program Files (x86)"),
):
raw = os.environ.get(env_name, default)
if raw:
dirs.append(Path(raw))
return _dedupe_paths(dirs)
def _is_windows_mediainfo_cli_path(path: str) -> bool:
raw = (path or "").strip()
if not raw:
return False
lower = raw.lower()
if lower in ("mediainfo", "mediainfo.exe"):
return True
if lower == "mediaarea.mediainfo":
return True
if "mediaarea.mediainfo.cli" in lower:
return True
if "\\mediainfo cli\\" in lower or "\\mediainfocli\\" in lower:
return True
return False
def _windows_default_tool_candidates(tool_name: str, prefix: Path) -> list[Path]:
exe_names = WINDOWS_TOOL_FILENAMES.get(tool_name, (f"{tool_name}.exe",))
candidates: list[Path] = []
include_prefix_dirs = tool_name != "mediainfo"
if include_prefix_dirs:
user_tools = _windows_user_tools_dir()
for directory in (
prefix,
prefix / "bin",
user_tools,
user_tools / "bin",
Path(__file__).parent / "tools",