767 lines
30 KiB
Python
767 lines
30 KiB
Python
#!/usr/bin/env python3
|
||
# FWS — « Signaler un problème » : envoi OPTIONNEL et validé par l'utilisateur
|
||
# de logs aux développeurs. Rien n'est collecté ni envoyé sans action
|
||
# explicite : l'utilisateur remplit le formulaire, voit le payload JSON EXACT
|
||
# qui partira (infos système + extrait du journal inclus si la case est
|
||
# cochée), puis confirme l'envoi. Aucun daemon, aucune collecte en
|
||
# arrière-plan, aucun envoi automatique.
|
||
#
|
||
# L'envoi passe par curl vers l'API bugs du projet — tout part par CE curl,
|
||
# rien d'autre ne quitte la machine :
|
||
# curl -X POST https://fws.laxacube.ch/api/bugs.php
|
||
# -H "Content-Type: application/json"
|
||
# -d '{"app":"FWS","version":"0.7.0","type":"bug","title":"…","description":"…"}'
|
||
#
|
||
# Usages :
|
||
# fws-bugreport → fenêtre GTK (menu « Signaler un problème »)
|
||
# fws-bugreport --file <chemin> → pré-remplit la description avec un fichier
|
||
# de logs existant (écran de debug du live)
|
||
# fws-bugreport --tui → assistant console (repli sans X / SSH)
|
||
#
|
||
# Vérifier qu'un envoi est bien parti : la réponse du serveur (code HTTP +
|
||
# message, ex. « HTTP 201 — Signalement enregistré. Merci ! (id 13) ») est
|
||
# affichée et tracée dans /tmp/fws-bugreport.log.
|
||
#
|
||
# GTK3 : présent sur tous les bureaux FWS et sur le live (via Anaconda) ;
|
||
# sans GTK joignable, l'assistant console prend le relais automatiquement.
|
||
|
||
import json
|
||
import os
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
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
|
||
# serveur) — la façon de vérifier qu'un rapport est bien parti :
|
||
# cat /tmp/fws-bugreport.log
|
||
_LOG_PATH = "/tmp/fws-bugreport.log"
|
||
|
||
_URL = "https://fws.laxacube.ch/api/bugs.php"
|
||
_APP = "FWS"
|
||
|
||
# (value sent to the server, key of the label shown)
|
||
_TYPES = [
|
||
("bug", "bugreport.type_bug"),
|
||
("question", "bugreport.type_question"),
|
||
("suggestion", "bugreport.type_suggestion"),
|
||
("other", "bugreport.type_other"),
|
||
]
|
||
|
||
try:
|
||
import gi
|
||
|
||
gi.require_version("Gtk", "3.0")
|
||
gi.require_version("Gdk", "3.0") # sinon gi charge Gdk 4.0 (conflit Gtk3)
|
||
from gi.repository import Gdk, GLib, Gtk # noqa: E402
|
||
|
||
_HAS_GTK = True
|
||
except Exception: # noqa: BLE001 — pas de GTK (système CLI, live minimal…)
|
||
_HAS_GTK = False
|
||
|
||
|
||
# ── Informations système (mêmes sources que fws-about) ───────────────────────
|
||
|
||
def _osrelease():
|
||
data = {}
|
||
for path in ("/etc/os-release", "/usr/lib/os-release",
|
||
"/usr/local/share/fws/os-release"):
|
||
try:
|
||
with open(path) as fh:
|
||
for line in fh:
|
||
m = re.match(r'^([A-Z_]+)=(.*)$', line.strip())
|
||
if m:
|
||
data[m.group(1)] = m.group(2).strip('"')
|
||
if data:
|
||
break
|
||
except OSError:
|
||
continue
|
||
return data
|
||
|
||
|
||
def _cmd(*argv):
|
||
try:
|
||
return subprocess.check_output(
|
||
argv, text=True, errors="replace",
|
||
stderr=subprocess.DEVNULL, timeout=10).strip()
|
||
except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired):
|
||
return ""
|
||
|
||
|
||
def _cpu():
|
||
try:
|
||
with open("/proc/cpuinfo") as fh:
|
||
for line in fh:
|
||
if line.startswith("model name"):
|
||
return line.split(":", 1)[1].strip()
|
||
except OSError:
|
||
pass
|
||
return "inconnu"
|
||
|
||
|
||
def _mem():
|
||
try:
|
||
with open("/proc/meminfo") as fh:
|
||
for line in fh:
|
||
if line.startswith("MemTotal"):
|
||
return f"{int(line.split()[1]) / 1048576:.1f} Gio"
|
||
except OSError:
|
||
pass
|
||
return "inconnue"
|
||
|
||
|
||
def _gpus():
|
||
out = []
|
||
for line in _cmd("lspci").splitlines():
|
||
low = line.lower()
|
||
if "vga" in low or "3d" in low or "display" in low:
|
||
out.append(line.split(":", 2)[-1].strip())
|
||
return out or ["inconnu"]
|
||
|
||
|
||
def _disks():
|
||
out = []
|
||
for line in _cmd("lsblk", "-dno", "NAME,SIZE,MODEL,TYPE").splitlines():
|
||
f = line.split()
|
||
if f and f[-1] == "disk":
|
||
out.append(" ".join(f[:-1]))
|
||
return out or ["inconnu"]
|
||
|
||
|
||
def _desktop():
|
||
if os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"):
|
||
return "Hyprland"
|
||
return (os.environ.get("XDG_CURRENT_DESKTOP")
|
||
or os.environ.get("DESKTOP_SESSION") or "inconnu")
|
||
|
||
|
||
def _session_type():
|
||
session_type = os.environ.get("XDG_SESSION_TYPE", "")
|
||
return {"wayland": "Wayland", "x11": "X11"}.get(
|
||
session_type, session_type or "inconnu")
|
||
|
||
|
||
def _tail(path, max_lines):
|
||
try:
|
||
with open(path, errors="replace") as fh:
|
||
lines = fh.readlines()
|
||
if len(lines) > max_lines:
|
||
lines = lines[-max_lines:]
|
||
return "".join(lines).rstrip()
|
||
except OSError:
|
||
return ""
|
||
|
||
|
||
def _system_summary(osr):
|
||
rows = [
|
||
("Système", osr.get("PRETTY_NAME") or "FWS Linux"),
|
||
("Version", osr.get("VERSION_ID") or "inconnue"),
|
||
("Build", osr.get("BUILD_ID", "rolling")),
|
||
("Noyau", _cmd("uname", "-r") or "inconnu"),
|
||
("Bureau", _desktop()),
|
||
("Affichage", _session_type()),
|
||
("Processeur", _cpu()),
|
||
("Mémoire", _mem()),
|
||
("Carte(s) graphique(s)", " ; ".join(_gpus())),
|
||
("Disque(s)", " ; ".join(_disks())),
|
||
]
|
||
return "\n".join(f"{k}: {v}" for k, v in rows)
|
||
|
||
|
||
def _journal_excerpt(max_lines=200):
|
||
"""Extrait du journal (avertissements/erreurs) du dernier démarrage.
|
||
|
||
Retourne (accessible, texte) : accessible=False si le journal n'a pas pu
|
||
être lu ; sinon le texte filtré, éventuellement vide si le démarrage ne
|
||
contenait aucun warning/erreur utile.
|
||
"""
|
||
try:
|
||
out = subprocess.check_output(
|
||
["journalctl", "-b", "-p", "warning", "--no-pager"],
|
||
text=True, errors="replace",
|
||
stderr=subprocess.DEVNULL, timeout=20).strip()
|
||
except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired):
|
||
return False, ""
|
||
lines = out.splitlines()
|
||
# BRUIT DE L'INSTALLATEUR (vu en réel sur bare metal, 2 ISO successives) :
|
||
# les modules D-Bus d'Anaconda journalisent leur debug SANS marqueur de
|
||
# priorité exploitable — dumps parted (PedPartition 0x…), rapports JSON LVM,
|
||
# listing des 42 tâches, sortie mkfs (« Superblock backups stored on… ») —
|
||
# en INFO/DEBUG journald, donc journalctl -p warning les renvoie quand même,
|
||
# et un filtre à marqueur INFO:/DEBUG: les laisse passer. Un filtre général
|
||
# risquerait d'écraser de VRAIS problèmes d'autres services → on cible :
|
||
# pour les unités org.fedoraproject.Anaconda.* on garde UNIQUEMENT les
|
||
# messages marqués ERROR:/WARNING: — plus les lignes non marquées d'un
|
||
# traceback Python toujours signifiantes (« Traceback (most recent call
|
||
# last): », cadres « File "…", line … » et exception finale, ex.
|
||
# « FileNotFoundError: [Errno 2] … ») — tout le reste du journal passe
|
||
# sans toucher.
|
||
def _jbody(line):
|
||
m = re.search(r"\[\d+\]: ", line)
|
||
return line[m.end():] if m else line
|
||
|
||
kept = []
|
||
for ln in lines:
|
||
if "org.fedoraproject.Anaconda." not in ln:
|
||
kept.append(ln)
|
||
continue
|
||
body = _jbody(ln).lstrip()
|
||
if (re.search(r"\b(?:ERROR|WARNING):", ln)
|
||
or body.startswith("Traceback (most recent call last):")
|
||
or body.startswith('File "')
|
||
or re.match(r"^\w[\w.]*(?:Error|Exception)\b", body)):
|
||
kept.append(ln)
|
||
lines = kept
|
||
|
||
# « WARNING:py.warnings:… DeprecationWarning: … » : bruit de développement
|
||
# de l'installateur (la même ligne est répétée par chacun des ~12 modules
|
||
# D-Bus d'Anaconda), pas un problème machine — retiré, sauf côté noyau où
|
||
# un warning resterait significatif.
|
||
lines = [ln for ln in lines
|
||
if "DeprecationWarning:" not in ln or re.search(r" kernel: ", ln)]
|
||
|
||
# « kernel: ntfs3… » : flot massif émis par le pilote ntfs3 quand
|
||
# l'installateur SONDE la partition Windows (« Correct links count -> N »
|
||
# pour des centaines d'inodes, « N callbacks suppressed »). C'est la
|
||
# correction de liens du système de fichiers Windows pendant la détection
|
||
# des disques — pas un problème FWS, inexploitable dans un rapport (vu en
|
||
# réel sur bare metal : des dizaines de lignes). Retiré ; un vrai problème
|
||
# de disque reste signalé ailleurs (kernel: ata/ahci/nvme…).
|
||
lines = [ln for ln in lines if " kernel: ntfs3" not in ln]
|
||
|
||
# Reliques du build (checkout Windows → fichiers PLATS à la place des
|
||
# symlinks systemd, corrigées à la source dans build.sh mais présentes
|
||
# dans les anciennes ISO) : « Failed to preset all unit … already
|
||
# exists » et « … is not a symlink, ignoring » — bruit sans valeur de
|
||
# diagnostic.
|
||
lines = [ln for ln in lines
|
||
if ("Failed to preset all unit" not in ln
|
||
and "is not a symlink, ignoring" not in ln
|
||
and "Wants dependency dropin" not in ln)]
|
||
|
||
# « anaconda: kickstart: Command X will be parsed in DBus module. » :
|
||
# trace de debug du parseur de kickstart, sans information.
|
||
lines = [ln for ln in lines
|
||
if "will be parsed in DBus module" not in ln]
|
||
|
||
# 1) DÉDUPLICATION GLOBALE (vu en réel sur bare metal) : un service en
|
||
# échec boucle (xdg-desktop-portal-gtk sans session graphique) et les
|
||
# modules D-Bus répètent les mêmes warnings — le rapport se noie sous les
|
||
# doublons. Clé = ligne sans horodatage NI chiffres (« 125 »/« 11 » et
|
||
# [pids] s'effacent) : les répétitions à variable numérique près se
|
||
# fusionnent (ex. « fan_curve… (0x110024/25/32) failed » → 1 ligne [×3]),
|
||
# la 1re occurrence garde sa place, marquée « [×N] » — rien n'est perdu,
|
||
# le compte reste lisible.
|
||
_stamp_re = re.compile(r"^[A-Z][a-z]{2} +\d+ +\d\d:\d\d:\d\d +")
|
||
|
||
seen = {}
|
||
order = []
|
||
out = []
|
||
for ln in lines:
|
||
m = _stamp_re.match(ln)
|
||
key = re.sub(r"\d+", "#", (ln[m.end():] if m else ln).strip())
|
||
if key in seen:
|
||
seen[key] += 1
|
||
continue
|
||
seen[key] = 1
|
||
order.append(key)
|
||
out.append(ln)
|
||
lines = [ln + (f" [×{seen[k]}]" if seen[k] > 1 else "")
|
||
for ln, k in zip(out, order)]
|
||
|
||
# 2) PLAFOND PAR SOURCE : même uniques, les lignes d'une source en tempête
|
||
# restent des dizaines (xdg-desktop-portal essaie chaque interface du
|
||
# portail l'une après l'autre) — au-delà de 8 lignes de la même source, la
|
||
# suite est omise avec une note explicite. Le noyau n'est pas concerné
|
||
# (pas de [pid] journald dans ses lignes). L'identifiant journald peut
|
||
# être un chemin (« /usr/lib/xdg-desktop-portal[856] ») → l'hostname et
|
||
# l'ident sont séparés par une espace, d'où « \S+ +(.+?)\[pid\] ».
|
||
def _src(line):
|
||
m = re.match(r"^[A-Z][a-z]{2} +\d+ +\d\d:\d\d:\d\d +\S+ +(.+?)\[\d+\]: ", line)
|
||
return m.group(1) if m else None
|
||
|
||
capped, counts, omitted = [], {}, {}
|
||
|
||
def _note(src, n):
|
||
return (f" (… +{n} autres lignes de « {src} » omises — "
|
||
"spam répétitif ; journal complet : journalctl -b -p warning)")
|
||
|
||
for ln in lines:
|
||
src = _src(ln)
|
||
if src is not None and counts.get(src, 0) >= 8:
|
||
omitted[src] = omitted.get(src, 0) + 1
|
||
continue
|
||
if src is not None:
|
||
counts[src] = counts.get(src, 0) + 1
|
||
if omitted.get(src):
|
||
capped.append(_note(src, omitted[src]))
|
||
omitted[src] = 0
|
||
capped.append(ln)
|
||
for src, n in omitted.items():
|
||
if n:
|
||
capped.append(_note(src, n))
|
||
lines = capped
|
||
if len(lines) > max_lines:
|
||
lines = lines[-max_lines:]
|
||
return True, "\n".join(lines)
|
||
|
||
|
||
def _anaconda_traceback():
|
||
"""Le fichier /tmp/anaconda-tb-* le plus récent, s'il existe.
|
||
|
||
Quand l'installateur plante, la boîte de dialogue n'affiche que les cadres
|
||
d'appel de l'enveloppe dasbus : la véritable exception n'est QUE dans ce
|
||
fichier. Sans lui, un plantage d'installation est indiagnosticable à
|
||
distance — et comme le live tourne en tmpfs, tout disparaît au redémarrage.
|
||
"""
|
||
try:
|
||
names = [os.path.join("/tmp", f) for f in os.listdir("/tmp")
|
||
if f.startswith("anaconda-tb-")]
|
||
except OSError:
|
||
return ""
|
||
newest, newest_mtime = "", -1.0
|
||
for name in names:
|
||
try:
|
||
if not os.path.isfile(name):
|
||
continue
|
||
mtime = os.path.getmtime(name)
|
||
except OSError:
|
||
continue
|
||
if mtime > newest_mtime:
|
||
newest, newest_mtime = name, mtime
|
||
return newest
|
||
|
||
|
||
def _collect_diagnostics(osr):
|
||
parts = ["===== Informations système =====", _system_summary(osr)]
|
||
# Deux emplacements, et il FAUT les deux : sur le système installé le log
|
||
# est dans /var/log, mais pendant l'installation c'est le %post --nochroot
|
||
# qui le recopie dans le /tmp du live (le disque cible est démonté au moment
|
||
# où on en a besoin). N'en chercher qu'un revenait à envoyer, depuis le live,
|
||
# un rapport SANS le log qui dit si le disque va booter.
|
||
for post_log in ("/var/log/fws-post.log", "/tmp/fws-post-chroot.log"):
|
||
if not os.path.isfile(post_log):
|
||
continue
|
||
tail = _tail(post_log, 100)
|
||
if tail:
|
||
parts += ["", "===== Log d'installation FWS (%s, fin) =====" % post_log,
|
||
tail]
|
||
break
|
||
|
||
tb_path = _anaconda_traceback()
|
||
if tb_path:
|
||
tb = _tail(tb_path, 80)
|
||
if tb:
|
||
parts += ["", "===== Plantage de l'installateur (%s, fin) ====="
|
||
% tb_path, tb]
|
||
journal_ok, journal = _journal_excerpt()
|
||
if journal:
|
||
parts += ["", "===== Journal du dernier démarrage "
|
||
"(avertissements / erreurs) =====", journal]
|
||
elif journal_ok:
|
||
# Journal lisible mais rien d'utile après filtrage du bruit : mieux
|
||
# vaut le dire que d'insinuer que le journal était inaccessible.
|
||
parts += ["", "===== Journal du dernier démarrage "
|
||
"(avertissements / erreurs) =====",
|
||
"(aucune entrée warning/erreur utile dans le journal)"]
|
||
else:
|
||
parts += ["", "(journal du dernier démarrage inaccessible — "
|
||
"lance fws-bugreport depuis un terminal avec sudo "
|
||
"pour l'inclure)"]
|
||
return "\n".join(parts)
|
||
|
||
|
||
def _build_payload(osr, typ, title, description, include_diag):
|
||
description = description.strip()
|
||
if include_diag:
|
||
diag = _collect_diagnostics(osr)
|
||
description = f"{description}\n\n{diag}" if description else diag
|
||
return {
|
||
"app": _APP,
|
||
"version": osr.get("VERSION_ID") or "unknown",
|
||
"type": typ,
|
||
"title": title,
|
||
"description": description,
|
||
}
|
||
|
||
|
||
# ── Envoi (un seul curl, comme spécifié) ─────────────────────────────────────
|
||
|
||
def _trace(lines):
|
||
try:
|
||
with open(_LOG_PATH, "a",
|
||
encoding="utf-8", errors="replace") as fh:
|
||
fh.write("\n".join(lines) + "\n")
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
def _send(payload):
|
||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8", "replace")
|
||
# Le corps passe par stdin (--data-binary @-) : pas de limite de taille
|
||
# d'argument (le journal peut faire des centaines de Ko) et aucun souci
|
||
# de quoting. -w ajoute le code HTTP en dernière ligne de stdout.
|
||
try:
|
||
proc = subprocess.run(
|
||
["curl", "-sS", "--max-time", "30", "-X", "POST", _URL,
|
||
"-H", "Content-Type: application/json",
|
||
"--data-binary", "@-",
|
||
"-w", "\n%{http_code}"],
|
||
input=data, capture_output=True, timeout=45)
|
||
except OSError as exc:
|
||
_trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC — "
|
||
f"curl introuvable : {exc}"])
|
||
return False, t("bugreport.curl_missing", error=exc)
|
||
except subprocess.TimeoutExpired:
|
||
_trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC — délai "
|
||
"dépassé (30 s)"])
|
||
return False, t("bugreport.timeout")
|
||
|
||
out = proc.stdout.decode("utf-8", "replace")
|
||
err = proc.stderr.decode("utf-8", "replace")
|
||
parts = out.rsplit("\n", 1)
|
||
body = parts[0] if len(parts) == 2 else out
|
||
code = parts[-1].strip()
|
||
|
||
if proc.returncode != 0:
|
||
detail = err.strip() or body.strip()
|
||
_trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ÉCHEC curl "
|
||
f"(code {proc.returncode}) : {detail[:300]}"])
|
||
return False, detail or t("bugreport.curl_failed",
|
||
code=proc.returncode)
|
||
|
||
# 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
|
||
# verrait « envoyé ✔ » alors que rien n'a été enregistré.
|
||
ok = code.startswith("2")
|
||
msg = body.strip()
|
||
rid = ""
|
||
try:
|
||
j = json.loads(body)
|
||
if isinstance(j, dict):
|
||
ok = bool(j.get("ok")) and code.startswith("2")
|
||
if j.get("message"):
|
||
msg = str(j["message"])
|
||
if j.get("id"):
|
||
rid = f" (id {j['id']})"
|
||
except ValueError:
|
||
pass
|
||
|
||
_trace([f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {_URL} "
|
||
f"app={payload.get('app')} type={payload.get('type')} "
|
||
f"titre={payload.get('title')!r} payload={len(data)} o "
|
||
f"→ HTTP {code or '?'} ok={ok} {msg[:200]}{rid}"])
|
||
|
||
if ok:
|
||
return True, f"HTTP {code or '?'} — {msg}{rid}"
|
||
return False, t("bugreport.server_refused", code=code or "?",
|
||
message=msg or t("bugreport.empty_response"))
|
||
|
||
|
||
# ── Assistant console (repli sans X) ─────────────────────────────────────────
|
||
|
||
def _tui(preload_path):
|
||
# Robustesse locale : l'assistant console peut tourner dans une console
|
||
# non-UTF-8 (Windows…). On force UTF-8 avec remplacement plutôt que de
|
||
# crasher sur les caractères accentués/boîtes.
|
||
try:
|
||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||
sys.stdin.reconfigure(encoding="utf-8", errors="replace")
|
||
except (AttributeError, ValueError, OSError):
|
||
pass
|
||
|
||
def ask(prompt, default=""):
|
||
try:
|
||
return input(prompt).strip() or default
|
||
except EOFError:
|
||
return default
|
||
|
||
def is_yes(answer):
|
||
# 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:
|
||
try:
|
||
with open(preload_path, errors="replace") as fh:
|
||
description = fh.read().strip()
|
||
print(t("bugreport.console_logs_loaded", path=preload_path,
|
||
count=len(description)))
|
||
except OSError as exc:
|
||
print(" ⚠ " + t("bugreport.read_error", path=preload_path,
|
||
error=exc))
|
||
description = ""
|
||
else:
|
||
description = ""
|
||
|
||
valid_types = [v for v, _l in _TYPES]
|
||
if not description:
|
||
print(t("bugreport.console_type_choices", default="bug",
|
||
types=", ".join(valid_types)))
|
||
typ = ask("> ", "bug")
|
||
if typ not in valid_types:
|
||
typ = "bug"
|
||
title = ask(t("bugreport.title_label") + " ")
|
||
print(t("bugreport.console_description_prompt"))
|
||
lines = []
|
||
while True:
|
||
line = ask("> ")
|
||
if not line:
|
||
break
|
||
lines.append(line)
|
||
description = "\n".join(lines)
|
||
else:
|
||
typ = ask(t("bugreport.console_type_prompt", default="bug") + " ",
|
||
"bug")
|
||
if typ not in valid_types:
|
||
typ = "bug"
|
||
title = ask(t("bugreport.title_label") + " ")
|
||
|
||
if not title:
|
||
print(" ⚠ " + t("bugreport.console_title_required"))
|
||
return 1
|
||
|
||
osr = _osrelease()
|
||
payload = _build_payload(osr, typ, title, description, include_diag=True)
|
||
print("\n─── " + t("bugreport.console_preview_header", url=_URL) + " ───")
|
||
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
||
answer = ask(f"\n{t('bugreport.console_send_prompt')} "
|
||
f"{t('common.yes_no')} ", "n")
|
||
if not is_yes(answer):
|
||
print(t("bugreport.console_cancelled"))
|
||
return 0
|
||
ok, msg = _send(payload)
|
||
print(("✔ " if ok else "✖ ") + msg)
|
||
if not ok:
|
||
print(t("bugreport.details", path=_LOG_PATH))
|
||
return 0 if ok else 1
|
||
|
||
|
||
# ── Fenêtre GTK (uniquement si GTK est disponible) ───────────────────────────
|
||
|
||
if _HAS_GTK:
|
||
def _preview_dialog(parent, payload):
|
||
dlg = Gtk.Dialog(title=t("bugreport.confirm_title"),
|
||
transient_for=parent, modal=True,
|
||
destroy_with_parent=True)
|
||
dlg.set_default_size(680, 520)
|
||
dlg.set_position(Gtk.WindowPosition.CENTER)
|
||
dlg.add_buttons(t("bugreport.cancel_button"), Gtk.ResponseType.CANCEL,
|
||
t("bugreport.confirm_button"), Gtk.ResponseType.OK)
|
||
|
||
box = dlg.get_content_area()
|
||
box.set_spacing(10)
|
||
box.set_border_width(14)
|
||
|
||
note = Gtk.Label()
|
||
note.set_markup(t("bugreport.preview_note",
|
||
url=GLib.markup_escape_text(_URL)))
|
||
note.set_line_wrap(True)
|
||
note.set_xalign(0)
|
||
box.pack_start(note, False, False, 0)
|
||
|
||
scroll = Gtk.ScrolledWindow()
|
||
scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
|
||
view = Gtk.TextView()
|
||
view.set_editable(False)
|
||
view.set_cursor_visible(False)
|
||
view.set_monospace(True)
|
||
view.get_buffer().set_text(
|
||
json.dumps(payload, ensure_ascii=False, indent=2))
|
||
scroll.add(view)
|
||
box.pack_start(scroll, True, True, 0)
|
||
|
||
dlg.show_all()
|
||
response = dlg.run()
|
||
dlg.destroy()
|
||
return response == Gtk.ResponseType.OK
|
||
|
||
def _message(parent, kind, title, text):
|
||
msg_type = (Gtk.MessageType.ERROR if kind == "error"
|
||
else Gtk.MessageType.INFO)
|
||
dlg = Gtk.MessageDialog(transient_for=parent, modal=True,
|
||
message_type=msg_type,
|
||
buttons=Gtk.ButtonsType.CLOSE,
|
||
text=title)
|
||
if text:
|
||
dlg.format_secondary_text(text)
|
||
dlg.run()
|
||
dlg.destroy()
|
||
|
||
class BugReportWindow(Gtk.Window):
|
||
def __init__(self, preload_path=None):
|
||
super().__init__(title=t("bugreport.window_title"))
|
||
self.set_icon_name("fws-bugreport")
|
||
self.set_default_size(580, -1)
|
||
self.set_position(Gtk.WindowPosition.CENTER)
|
||
self.set_border_width(18)
|
||
# DIALOGUE : les tuileurs (i3/Hyprland) gardent les dialogues en
|
||
# flottant → taille naturelle au lieu d'être étirée.
|
||
self.set_type_hint(Gdk.WindowTypeHint.DIALOG)
|
||
self.set_resizable(False)
|
||
self.connect("destroy", Gtk.main_quit)
|
||
|
||
self._osr = _osrelease()
|
||
|
||
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
|
||
self.add(box)
|
||
|
||
title = Gtk.Label()
|
||
title.set_markup(
|
||
"<span size='x-large' weight='bold'>"
|
||
f"{GLib.markup_escape_text(t('bugreport.title'))}</span>")
|
||
box.pack_start(title, False, False, 0)
|
||
|
||
subtitle = Gtk.Label(label=t("bugreport.subtitle"))
|
||
subtitle.set_line_wrap(True)
|
||
subtitle.set_xalign(0)
|
||
box.pack_start(subtitle, False, False, 0)
|
||
|
||
grid = Gtk.Grid(column_spacing=10, row_spacing=8)
|
||
grid.set_halign(Gtk.Align.FILL)
|
||
|
||
grid.attach(Gtk.Label(label=t("bugreport.type_label"), xalign=1),
|
||
0, 0, 1, 1)
|
||
self._type = Gtk.ComboBoxText()
|
||
for value, label in _TYPES:
|
||
self._type.append(value, t(label))
|
||
self._type.set_active(0)
|
||
grid.attach(self._type, 1, 0, 1, 1)
|
||
|
||
grid.attach(Gtk.Label(label=t("bugreport.title_label"), xalign=1),
|
||
0, 1, 1, 1)
|
||
self._title = Gtk.Entry()
|
||
self._title.set_placeholder_text(t("bugreport.title_placeholder"))
|
||
grid.attach(self._title, 1, 1, 1, 1)
|
||
|
||
box.pack_start(grid, False, False, 0)
|
||
|
||
desc_label = Gtk.Label(label=t("bugreport.description_label"),
|
||
xalign=0)
|
||
box.pack_start(desc_label, False, False, 0)
|
||
scroll = Gtk.ScrolledWindow()
|
||
scroll.set_min_content_height(130)
|
||
scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
|
||
self._description = Gtk.TextView()
|
||
self._description.set_wrap_mode(Gtk.WrapMode.WORD)
|
||
self._description.set_placeholder_text(
|
||
t("bugreport.description_placeholder"))
|
||
scroll.add(self._description)
|
||
box.pack_start(scroll, False, False, 0)
|
||
|
||
if preload_path:
|
||
try:
|
||
with open(preload_path, errors="replace") as fh:
|
||
content = fh.read()
|
||
self._description.get_buffer().set_text(content)
|
||
loaded = Gtk.Label()
|
||
path = GLib.markup_escape_text(preload_path)
|
||
loaded.set_markup(
|
||
"<span size='small' foreground='#89b4fa'>"
|
||
f"{t('bugreport.logs_loaded', path=path)}</span>")
|
||
loaded.set_line_wrap(True)
|
||
loaded.set_xalign(0)
|
||
box.pack_start(loaded, False, False, 0)
|
||
except OSError as exc:
|
||
_message(self, "error", t("bugreport.file_unreadable"),
|
||
t("bugreport.read_error", path=preload_path,
|
||
error=exc))
|
||
|
||
self._include = Gtk.CheckButton(
|
||
label=t("bugreport.include_diagnostics"))
|
||
self._include.set_active(True)
|
||
self._include.set_tooltip_text(
|
||
t("bugreport.include_diagnostics_tooltip"))
|
||
box.pack_start(self._include, False, False, 4)
|
||
|
||
footer = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
|
||
cancel = Gtk.Button(label=t("common.close"))
|
||
cancel.connect("clicked", lambda _b: self.close())
|
||
send = Gtk.Button(label=t("bugreport.send_button"))
|
||
send.get_style_context().add_class("suggested-action")
|
||
send.connect("clicked", self._on_send)
|
||
footer.pack_end(send, False, False, 0)
|
||
footer.pack_end(cancel, False, False, 0)
|
||
box.pack_start(footer, False, False, 6)
|
||
|
||
self._title.connect("activate", self._on_send)
|
||
|
||
def _on_send(self, _widget=None):
|
||
# Un crash ne doit JAMAIS mourir en silence (le lancement depuis
|
||
# l'écran de debug du live redirige stderr vers /dev/null) : on
|
||
# trace et on affiche.
|
||
try:
|
||
self._do_send()
|
||
except Exception as exc: # noqa: BLE001
|
||
_trace(["=== CRASH fws-bugreport ===",
|
||
traceback.format_exc()])
|
||
_message(self, "error", t("bugreport.unexpected_error"),
|
||
f"{exc}\n\n{t('bugreport.details', path=_LOG_PATH)}")
|
||
|
||
def _do_send(self):
|
||
title = self._title.get_text().strip()
|
||
buf = self._description.get_buffer()
|
||
description = buf.get_text(buf.get_start_iter(),
|
||
buf.get_end_iter(), True).strip()
|
||
include = self._include.get_active()
|
||
if not title:
|
||
_message(self, "error", t("bugreport.title_missing"),
|
||
t("bugreport.title_missing_detail"))
|
||
return
|
||
if not description and not include:
|
||
_message(self, "error", t("bugreport.report_empty"),
|
||
t("bugreport.report_empty_detail"))
|
||
return
|
||
|
||
typ = self._type.get_active_id() or "bug"
|
||
payload = _build_payload(self._osr, typ, title, description, include)
|
||
if not _preview_dialog(self, payload):
|
||
return
|
||
ok, msg = _send(payload)
|
||
if ok:
|
||
_message(self, "info", t("bugreport.sent_title"),
|
||
f"{msg}\n\n{t('bugreport.sent_thanks')}\n"
|
||
f"{t('bugreport.log_path', path=_LOG_PATH)}")
|
||
else:
|
||
_message(self, "error", t("bugreport.send_failed_title"),
|
||
f"{msg}\n\n{t('bugreport.send_failed_detail')}\n"
|
||
f"{t('bugreport.details', path=_LOG_PATH)}")
|
||
|
||
|
||
def main():
|
||
args = sys.argv[1:]
|
||
preload = None
|
||
if "--file" in args:
|
||
i = args.index("--file")
|
||
if i + 1 < len(args):
|
||
preload = args[i + 1]
|
||
if _HAS_GTK and "--tui" not in args and Gtk.init_check()[0]:
|
||
GLib.set_prgname("fws-bugreport")
|
||
win = BugReportWindow(preload)
|
||
win.show_all()
|
||
Gtk.main()
|
||
return 0
|
||
return _tui(preload)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main()) |