feat(i18n): translate fws-bugreport

This commit is contained in:
nocode committed 2026-11-26 18:18:27 +01:00
1 parent ccc94aad3d
commit 07827c3dbd
1 file changed
+96 -69
@@ -32,6 +32,16 @@ import subprocess
import sys import sys
import time import time
import traceback import traceback
import unicodedata
sys.path.insert(0, "/usr/local/lib/fws")
from fws_i18n import catalog # noqa: E402
# What the user sees comes from system-translations.toml (bugreport.* keys).
# The report itself (section titles, field names, notes inside the collected
# text, the local trace) stays in French whatever the session's language: it
# is read by the FWS team, not by the user.
t = catalog("system").t
# Trace locale de chaque tentative d'envoi (date, code HTTP, réponse du # Trace locale de chaque tentative d'envoi (date, code HTTP, réponse du
# serveur) — la façon de vérifier qu'un rapport est bien parti : # serveur) — la façon de vérifier qu'un rapport est bien parti :
@@ -41,12 +51,12 @@ _LOG_PATH = "/tmp/fws-bugreport.log"
_URL = "https://fws.laxacube.ch/api/bugs.php" _URL = "https://fws.laxacube.ch/api/bugs.php"
_APP = "FWS" _APP = "FWS"
# (valeur envoyée au serveur, libellé affiché) # (value sent to the server, key of the label shown)
_TYPES = [ _TYPES = [
("bug", "Bug / panne"), ("bug", "bugreport.type_bug"),
("question", "Question"), ("question", "bugreport.type_question"),
("suggestion", "Suggestion"), ("suggestion", "bugreport.type_suggestion"),
("other", "Autre"), ("other", "bugreport.type_other"),
] ]
try: try:
@@ -137,8 +147,9 @@ def _desktop():
def _session_type(): def _session_type():
t = os.environ.get("XDG_SESSION_TYPE", "") session_type = os.environ.get("XDG_SESSION_TYPE", "")
return {"wayland": "Wayland", "x11": "X11"}.get(t, t or "inconnu") return {"wayland": "Wayland", "x11": "X11"}.get(
session_type, session_type or "inconnu")
def _tail(path, max_lines): def _tail(path, max_lines):
@@ -411,11 +422,11 @@ def _send(payload):
except OSError as exc: except OSError as exc:
_trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC — " _trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC — "
f"curl introuvable : {exc}"]) f"curl introuvable : {exc}"])
return False, f"curl introuvable : {exc}" return False, t("bugreport.curl_missing", error=exc)
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
_trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC — délai " _trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC — délai "
"dépassé (30 s)"]) "dépassé (30 s)"])
return False, "Délai dépassé (30 s) — vérifie ta connexion réseau." return False, t("bugreport.timeout")
out = proc.stdout.decode("utf-8", "replace") out = proc.stdout.decode("utf-8", "replace")
err = proc.stderr.decode("utf-8", "replace") err = proc.stderr.decode("utf-8", "replace")
@@ -427,7 +438,8 @@ def _send(payload):
detail = err.strip() or body.strip() detail = err.strip() or body.strip()
_trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC curl " _trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC curl "
f"(code {proc.returncode}) : {detail[:300]}"]) f"(code {proc.returncode}) : {detail[:300]}"])
return False, detail or f"curl a échoué (code {proc.returncode})." return False, detail or t("bugreport.curl_failed",
code=proc.returncode)
# Le serveur répond en JSON : {"ok":true,"id":…,"message":…}. Un code # Le serveur répond en JSON : {"ok":true,"id":…,"message":…}. Un code
# HTTP ≥ 400 ne fait PAS échouer curl — on le détecte ici, sinon l'utilisateur # HTTP ≥ 400 ne fait PAS échouer curl — on le détecte ici, sinon l'utilisateur
@@ -453,8 +465,8 @@ def _send(payload):
if ok: if ok:
return True, f"HTTP {code or '?'} — {msg}{rid}" return True, f"HTTP {code or '?'} — {msg}{rid}"
return False, (f"HTTP {code or '?'} — {msg or 'réponse vide'}. " return False, t("bugreport.server_refused", code=code or "?",
"Le serveur a refusé le rapport.") message=msg or t("bugreport.empty_response"))
# ── Assistant console (repli sans X) ───────────────────────────────────────── # ── Assistant console (repli sans X) ─────────────────────────────────────────
@@ -475,29 +487,41 @@ def _tui(preload_path):
except EOFError: except EOFError:
return default return default
print("FWS — « Signaler un problème » (envoi optionnel de logs)") def is_yes(answer):
print("Rien ne sera envoyé sans ta confirmation.\n") # Same answers as t_is_yes (i18n.sh): the translated word, its first
# letter, the same without accents ("si" for "sí"), and the English
# ones that every keyboard can type.
answer = answer.lower()
yes = t("common.yes").lower()
plain = "".join(c for c in unicodedata.normalize("NFKD", yes)
if not unicodedata.combining(c))
return bool(answer) and answer in ("y", "yes", yes, yes[:1], plain, plain[:1])
print(t("bugreport.console_title"))
print(t("bugreport.console_confirmation_note") + "\n")
if preload_path: if preload_path:
try: try:
with open(preload_path, errors="replace") as fh: with open(preload_path, errors="replace") as fh:
description = fh.read().strip() description = fh.read().strip()
print(f"Logs chargés depuis {preload_path} " print(t("bugreport.console_logs_loaded", path=preload_path,
f"({len(description)} caractères).") count=len(description)))
except OSError as exc: except OSError as exc:
print(f" ⚠ Impossible de lire {preload_path} : {exc}") print(" ⚠ " + t("bugreport.read_error", path=preload_path,
error=exc))
description = "" description = ""
else: else:
description = "" description = ""
valid_types = [v for v, _l in _TYPES] valid_types = [v for v, _l in _TYPES]
if not description: if not description:
print("Type (défaut : bug) : " + ", ".join(valid_types)) print(t("bugreport.console_type_choices", default="bug",
types=", ".join(valid_types)))
typ = ask("> ", "bug") typ = ask("> ", "bug")
if typ not in valid_types: if typ not in valid_types:
typ = "bug" typ = "bug"
title = ask("Titre : ") title = ask(t("bugreport.title_label") + " ")
print("Description (ligne vide pour terminer) :") print(t("bugreport.console_description_prompt"))
lines = [] lines = []
while True: while True:
line = ask("> ") line = ask("> ")
@@ -506,26 +530,29 @@ def _tui(preload_path):
lines.append(line) lines.append(line)
description = "\n".join(lines) description = "\n".join(lines)
else: else:
typ = ask("Type (défaut : bug) : ", "bug") typ = ask(t("bugreport.console_type_prompt", default="bug") + " ",
"bug")
if typ not in valid_types: if typ not in valid_types:
typ = "bug" typ = "bug"
title = ask("Titre : ") title = ask(t("bugreport.title_label") + " ")
if not title: if not title:
print(" ⚠ Titre obligatoire — envoi annulé.") print(" ⚠ " + t("bugreport.console_title_required"))
return 1 return 1
osr = _osrelease() osr = _osrelease()
payload = _build_payload(osr, typ, title, description, include_diag=True) payload = _build_payload(osr, typ, title, description, include_diag=True)
print("\n─── Aperçu de ce qui sera envoyé à", _URL, "───") print("\n─── " + t("bugreport.console_preview_header", url=_URL) + " ───")
print(json.dumps(payload, ensure_ascii=False, indent=2)) print(json.dumps(payload, ensure_ascii=False, indent=2))
if ask("\nEnvoyer ? [o/N] ", "n").lower() not in ("o", "oui", "y", "yes"): answer = ask(f"\n{t('bugreport.console_send_prompt')} "
print("Envoi annulé.") f"{t('common.yes_no')} ", "n")
if not is_yes(answer):
print(t("bugreport.console_cancelled"))
return 0 return 0
ok, msg = _send(payload) ok, msg = _send(payload)
print(("✔ " if ok else "✖ ") + msg) print(("✔ " if ok else "✖ ") + msg)
if not ok: if not ok:
print(f"Détails : {_LOG_PATH}") print(t("bugreport.details", path=_LOG_PATH))
return 0 if ok else 1 return 0 if ok else 1
@@ -533,21 +560,21 @@ def _tui(preload_path):
if _HAS_GTK: if _HAS_GTK:
def _preview_dialog(parent, payload): def _preview_dialog(parent, payload):
dlg = Gtk.Dialog(title="Confirmer l'envoi", transient_for=parent, dlg = Gtk.Dialog(title=t("bugreport.confirm_title"),
modal=True, destroy_with_parent=True) transient_for=parent, modal=True,
destroy_with_parent=True)
dlg.set_default_size(680, 520) dlg.set_default_size(680, 520)
dlg.set_position(Gtk.WindowPosition.CENTER) dlg.set_position(Gtk.WindowPosition.CENTER)
dlg.add_buttons("Annuler", Gtk.ResponseType.CANCEL, dlg.add_buttons(t("bugreport.cancel_button"), Gtk.ResponseType.CANCEL,
"Confirmer l'envoi", Gtk.ResponseType.OK) t("bugreport.confirm_button"), Gtk.ResponseType.OK)
box = dlg.get_content_area() box = dlg.get_content_area()
box.set_spacing(10) box.set_spacing(10)
box.set_border_width(14) box.set_border_width(14)
note = Gtk.Label() note = Gtk.Label()
note.set_markup( note.set_markup(t("bugreport.preview_note",
"<b>Voici EXACTEMENT ce qui sera envoyé</b> à " url=GLib.markup_escape_text(_URL)))
"<span font_family='monospace'>https://fws.laxacube.ch/api/bugs.php</span> :")
note.set_line_wrap(True) note.set_line_wrap(True)
note.set_xalign(0) note.set_xalign(0)
box.pack_start(note, False, False, 0) box.pack_start(note, False, False, 0)
@@ -582,7 +609,7 @@ if _HAS_GTK:
class BugReportWindow(Gtk.Window): class BugReportWindow(Gtk.Window):
def __init__(self, preload_path=None): def __init__(self, preload_path=None):
super().__init__(title="Signaler un problème — FWS") super().__init__(title=t("bugreport.window_title"))
self.set_icon_name("fws-bugreport") self.set_icon_name("fws-bugreport")
self.set_default_size(580, -1) self.set_default_size(580, -1)
self.set_position(Gtk.WindowPosition.CENTER) self.set_position(Gtk.WindowPosition.CENTER)
@@ -600,13 +627,11 @@ if _HAS_GTK:
title = Gtk.Label() title = Gtk.Label()
title.set_markup( title.set_markup(
"<span size='x-large' weight='bold'>Signaler un problème</span>") "<span size='x-large' weight='bold'>"
f"{GLib.markup_escape_text(t('bugreport.title'))}</span>")
box.pack_start(title, False, False, 0) box.pack_start(title, False, False, 0)
subtitle = Gtk.Label( subtitle = Gtk.Label(label=t("bugreport.subtitle"))
label="Un souci avec FWS ? Décris-le ci-dessous. Les informations "
"système et les logs de diagnostic peuvent être joints pour "
"aider les développeurs. Rien ne part sans ta confirmation.")
subtitle.set_line_wrap(True) subtitle.set_line_wrap(True)
subtitle.set_xalign(0) subtitle.set_xalign(0)
box.pack_start(subtitle, False, False, 0) box.pack_start(subtitle, False, False, 0)
@@ -614,21 +639,24 @@ if _HAS_GTK:
grid = Gtk.Grid(column_spacing=10, row_spacing=8) grid = Gtk.Grid(column_spacing=10, row_spacing=8)
grid.set_halign(Gtk.Align.FILL) grid.set_halign(Gtk.Align.FILL)
grid.attach(Gtk.Label(label="Type :", xalign=1), 0, 0, 1, 1) grid.attach(Gtk.Label(label=t("bugreport.type_label"), xalign=1),
0, 0, 1, 1)
self._type = Gtk.ComboBoxText() self._type = Gtk.ComboBoxText()
for value, label in _TYPES: for value, label in _TYPES:
self._type.append(value, label) self._type.append(value, t(label))
self._type.set_active(0) self._type.set_active(0)
grid.attach(self._type, 1, 0, 1, 1) grid.attach(self._type, 1, 0, 1, 1)
grid.attach(Gtk.Label(label="Titre :", xalign=1), 0, 1, 1, 1) grid.attach(Gtk.Label(label=t("bugreport.title_label"), xalign=1),
0, 1, 1, 1)
self._title = Gtk.Entry() self._title = Gtk.Entry()
self._title.set_placeholder_text("Résumé court du problème") self._title.set_placeholder_text(t("bugreport.title_placeholder"))
grid.attach(self._title, 1, 1, 1, 1) grid.attach(self._title, 1, 1, 1, 1)
box.pack_start(grid, False, False, 0) box.pack_start(grid, False, False, 0)
desc_label = Gtk.Label(label="Description :", xalign=0) desc_label = Gtk.Label(label=t("bugreport.description_label"),
xalign=0)
box.pack_start(desc_label, False, False, 0) box.pack_start(desc_label, False, False, 0)
scroll = Gtk.ScrolledWindow() scroll = Gtk.ScrolledWindow()
scroll.set_min_content_height(130) scroll.set_min_content_height(130)
@@ -636,7 +664,7 @@ if _HAS_GTK:
self._description = Gtk.TextView() self._description = Gtk.TextView()
self._description.set_wrap_mode(Gtk.WrapMode.WORD) self._description.set_wrap_mode(Gtk.WrapMode.WORD)
self._description.set_placeholder_text( self._description.set_placeholder_text(
"Ce qui s'est passé, ce que tu attendais, ce que tu as essayé…") t("bugreport.description_placeholder"))
scroll.add(self._description) scroll.add(self._description)
box.pack_start(scroll, False, False, 0) box.pack_start(scroll, False, False, 0)
@@ -646,29 +674,29 @@ if _HAS_GTK:
content = fh.read() content = fh.read()
self._description.get_buffer().set_text(content) self._description.get_buffer().set_text(content)
loaded = Gtk.Label() loaded = Gtk.Label()
path = GLib.markup_escape_text(preload_path)
loaded.set_markup( loaded.set_markup(
f"<span size='small' foreground='#89b4fa'>Logs chargés " "<span size='small' foreground='#89b4fa'>"
f"depuis <span font_family='monospace'>{preload_path}" f"{t('bugreport.logs_loaded', path=path)}</span>")
f"</span> — tu peux les compléter ou les retirer.</span>")
loaded.set_line_wrap(True) loaded.set_line_wrap(True)
loaded.set_xalign(0) loaded.set_xalign(0)
box.pack_start(loaded, False, False, 0) box.pack_start(loaded, False, False, 0)
except OSError as exc: except OSError as exc:
_message(self, "error", "Fichier illisible", _message(self, "error", t("bugreport.file_unreadable"),
f"{preload_path} : {exc}") t("bugreport.read_error", path=preload_path,
error=exc))
self._include = Gtk.CheckButton( self._include = Gtk.CheckButton(
label="Joindre les informations système et les logs de diagnostic") label=t("bugreport.include_diagnostics"))
self._include.set_active(True) self._include.set_active(True)
self._include.set_tooltip_text( self._include.set_tooltip_text(
"Version FWS, matériel détecté, extrait du journal du dernier " t("bugreport.include_diagnostics_tooltip"))
"démarrage — à relire dans l'aperçu avant l'envoi")
box.pack_start(self._include, False, False, 4) box.pack_start(self._include, False, False, 4)
footer = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8) footer = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
cancel = Gtk.Button(label="Fermer") cancel = Gtk.Button(label=t("common.close"))
cancel.connect("clicked", lambda _b: self.close()) cancel.connect("clicked", lambda _b: self.close())
send = Gtk.Button(label="Envoyer…") send = Gtk.Button(label=t("bugreport.send_button"))
send.get_style_context().add_class("suggested-action") send.get_style_context().add_class("suggested-action")
send.connect("clicked", self._on_send) send.connect("clicked", self._on_send)
footer.pack_end(send, False, False, 0) footer.pack_end(send, False, False, 0)
@@ -686,8 +714,8 @@ if _HAS_GTK:
except Exception as exc: # noqa: BLE001 except Exception as exc: # noqa: BLE001
_trace(["=== CRASH fws-bugreport ===", _trace(["=== CRASH fws-bugreport ===",
traceback.format_exc()]) traceback.format_exc()])
_message(self, "error", "Erreur inattendue", _message(self, "error", t("bugreport.unexpected_error"),
f"{exc}\n\nDétails : {_LOG_PATH}") f"{exc}\n\n{t('bugreport.details', path=_LOG_PATH)}")
def _do_send(self): def _do_send(self):
title = self._title.get_text().strip() title = self._title.get_text().strip()
@@ -696,13 +724,12 @@ if _HAS_GTK:
buf.get_end_iter(), True).strip() buf.get_end_iter(), True).strip()
include = self._include.get_active() include = self._include.get_active()
if not title: if not title:
_message(self, "error", "Titre manquant", _message(self, "error", t("bugreport.title_missing"),
"Indique un titre court pour le problème.") t("bugreport.title_missing_detail"))
return return
if not description and not include: if not description and not include:
_message(self, "error", "Rapport vide", _message(self, "error", t("bugreport.report_empty"),
"Écris une description ou coche la jointure des " t("bugreport.report_empty_detail"))
"informations système et des logs.")
return return
typ = self._type.get_active_id() or "bug" typ = self._type.get_active_id() or "bug"
@@ -711,13 +738,13 @@ if _HAS_GTK:
return return
ok, msg = _send(payload) ok, msg = _send(payload)
if ok: if ok:
_message(self, "info", "Rapport envoyé ✔", _message(self, "info", t("bugreport.sent_title"),
f"{msg}\n\nMerci ! L'équipe FWS a reçu ton rapport.\n" f"{msg}\n\n{t('bugreport.sent_thanks')}\n"
f"(trace : {_LOG_PATH})") f"{t('bugreport.log_path', path=_LOG_PATH)}")
else: else:
_message(self, "error", "Envoi impossible", _message(self, "error", t("bugreport.send_failed_title"),
f"{msg}\n\nTon rapport n'a pas été envoyé. Vérifie ta " f"{msg}\n\n{t('bugreport.send_failed_detail')}\n"
f"connexion et réessaie.\nDétails : {_LOG_PATH}") f"{t('bugreport.details', path=_LOG_PATH)}")
def main(): def main():