"""Internationalization (i18n) helper for Barcode Reader PC Server (IT / EN).""" from __future__ import annotations import locale import os _CURRENT_LANG = "en" TRANSLATIONS: dict[str, dict[str, str]] = { "en": { "app_subtitle": "Receive barcodes from Smartphone • Catelli Srl • v{version}", "update_available_btn": "Update available", "update_to_version_btn": "Update to v{version}", "tab_dashboard": "Dashboard & Devices", "tab_settings": "Settings", "card_qr_title": "QUICK CONNECT (QR)", "qr_hint": "Scan with the Android/iOS app", "card_server_title": "SERVER DETAILS", "lbl_local_ip": "Local IP Address:", "lbl_port": "Port:", "lbl_pc_name": "PC Name:", "lbl_pin": "Access PIN:", "pin_none": "None (Open)", "btn_copy_ip": "Copy IP", "btn_open_web": "Open Web Dashboard", "card_devices_title": "CONNECTED DEVICES", "no_devices_connected": "No mobile device connected.", "devices_connected_fmt": "{count} connected: {devices}", "card_history_title": "LIVE SCAN HISTORY", "btn_clear_log": "Clear Log", "col_time": "Time", "col_device": "Device", "col_code": "Scanned Code", "col_status": "Status", "scan_typed": "Typed ✓", "scan_failed": "Failed ✗", "status_listening_badge": "● LISTENING", "status_paused_badge": "○ PAUSED", "status_listening_short": "LISTENING", "status_paused_short": "PAUSED", "btn_pause": "Pause", "btn_resume": "Resume Listening", "sec_network": "NETWORK & IDENTIFICATION", "lbl_mobile_name": "Name shown in mobile app:", "lbl_pin_input": "Access PIN (e.g. 4 digits):", "placeholder_pin": "Leave empty for open access", "lbl_ws_port": "WebSocket Server Port:", "port_restart_hint": "(Changing port requires restart)", "sec_keyboard": "KEYBOARD BEHAVIOR", "lbl_suffix": "Trailing key after each scan:", "rb_suffix_enter": "Enter", "rb_suffix_tab": "Tab", "rb_suffix_none": "No key", "lbl_typing_mode": "Input mode:", "rb_mode_type": "Real keyboard typing (Recommended)", "rb_mode_paste": "Paste from clipboard (Ctrl+V / Cmd+V)", "sec_system": "AUTOSTART, TRAY, LANGUAGE & UPDATES", "chk_autostart": "Start automatically at OS login (Autostart)", "chk_tray": "Minimize to System Tray on close (X) instead of quitting", "chk_updates": "Check for updates automatically on startup", "lbl_language": "Interface language:", "lang_auto": "System default (Auto)", "lang_it": "Italiano", "lang_en": "English", "lbl_update_url": "Custom update URL (optional):", "placeholder_update_url": "Empty = Gitea Releases (gitea.catelli.it)", "btn_check_updates": "Check for Updates Now", "installed_version": "Installed version: v{version}", "btn_save_settings": "Save & Apply Settings", "msg_copy_title": "Copied", "msg_copy_body": "IP address ({ip}) copied to clipboard!", "msg_error_title": "Error", "msg_port_invalid": "Port must be a valid number (e.g. 8765).", "msg_settings_title": "Settings", "msg_settings_saved": "Settings saved and applied successfully!", "msg_settings_saved_restart_lang": "Settings saved! Restart the app to apply the new language everywhere.", "checking_updates": "Checking for updates...", "tray_show_window": "Show Window", "tray_pause": "Pause", "tray_resume": "Resume Listening", "tray_open_web": "Open Web Dashboard", "tray_check_updates": "Check for Updates...", "tray_quit": "Quit", "tray_update_title": "Update available (v{version})", "tray_update_body": "Open Barcode Reader Server to install it automatically.", "updates_dialog_title": "Updates", "updates_check_title": "Update Check", "update_win_title": "Update Available — v{version}", "update_new_version": "New version available: v{version}", "update_installed_sub": "Installed version: v{version} • {title}", "update_no_notes": "No release notes provided.", "update_no_asset": "No platform-specific package found in this release.", "update_ready_pkg": "Package ready to install: {name}{size}", "btn_later": "Later", "btn_open_release_page": "Open Release Page", "btn_update_restart": "Update & Restart", "update_downloading": "Downloading {name}...", "update_downloading_pct": "Downloading: {done:.1f} / {total:.1f} MB ({percent}%)", "update_downloading_mb": "Downloaded {done:.1f} MB...", "update_installing": "Installing update and restarting...", "update_apply_error": "Failed to launch update: {error}", "update_error_prefix": "Error: {error}", "update_error_title": "Update Error", }, "it": { "app_subtitle": "Ricezione codici a barre da Smartphone • Catelli Srl • v{version}", "update_available_btn": "Aggiornamento disponibile", "update_to_version_btn": "Aggiorna a v{version}", "tab_dashboard": "Dashboard & Dispositivi", "tab_settings": "Impostazioni", "card_qr_title": "CONNESSIONE RAPIDA (QR)", "qr_hint": "Inquadra con l'app Android/iOS", "card_server_title": "DETTAGLI SERVER", "lbl_local_ip": "Indirizzo IP Locale:", "lbl_port": "Porta:", "lbl_pc_name": "Nome PC:", "lbl_pin": "PIN di Accesso:", "pin_none": "Nessuno (Libero)", "btn_copy_ip": "Copia IP", "btn_open_web": "Apri Dashboard Web", "card_devices_title": "DISPOSITIVI CONNESSI", "no_devices_connected": "Nessun dispositivo mobile collegato.", "devices_connected_fmt": "{count} collegati: {devices}", "card_history_title": "CRONOLOGIA SCANSIONI LIVE", "btn_clear_log": "Pulisci Log", "col_time": "Ora", "col_device": "Dispositivo", "col_code": "Codice Letto", "col_status": "Esito", "scan_typed": "Digitato ✓", "scan_failed": "Fallito ✗", "status_listening_badge": "● IN ASCOLTO", "status_paused_badge": "○ IN PAUSA", "status_listening_short": "IN ASCOLTO", "status_paused_short": "IN PAUSA", "btn_pause": "Metti in Pausa", "btn_resume": "Riprendi Ricezione", "sec_network": "RETE E IDENTIFICAZIONE", "lbl_mobile_name": "Nome visualizzato nell'app mobile:", "lbl_pin_input": "PIN di accesso (es. 4 cifre):", "placeholder_pin": "Lascia vuoto per accesso libero", "lbl_ws_port": "Porta Server WebSocket:", "port_restart_hint": "(Il cambio porta richiede riavvio)", "sec_keyboard": "COMPORTAMENTO TASTIERA", "lbl_suffix": "Tasto finale dopo ogni scansione:", "rb_suffix_enter": "Invio (Enter)", "rb_suffix_tab": "Tabulatore (Tab)", "rb_suffix_none": "Nessun tasto", "lbl_typing_mode": "Modalità di scrittura:", "rb_mode_type": "Digitazione tastiera reale (Consigliato)", "rb_mode_paste": "Incolla da appunti (Ctrl+V / Cmd+V)", "sec_system": "AVVIO AUTOMATICO, TRAY, LINGUA E AGGIORNAMENTI", "chk_autostart": "Avvia automaticamente all'avvio del sistema operativo (Login / Boot)", "chk_tray": "Alla chiusura (X) riduci nella System Tray invece di terminare", "chk_updates": "Controlla automaticamente nuovi aggiornamenti all'avvio", "lbl_language": "Lingua interfaccia:", "lang_auto": "Predefinita di sistema (Auto)", "lang_it": "Italiano", "lang_en": "English", "lbl_update_url": "URL aggiornamento custom (opzionale):", "placeholder_update_url": "Vuoto = Gitea Releases (gitea.catelli.it)", "btn_check_updates": "Controlla Aggiornamenti Ora", "installed_version": "Versione installata: v{version}", "btn_save_settings": "Salva ed Applica Impostazioni", "msg_copy_title": "Copia", "msg_copy_body": "Indirizzo IP ({ip}) copiato negli appunti!", "msg_error_title": "Errore", "msg_port_invalid": "La porta deve essere un numero valido (es. 8765).", "msg_settings_title": "Impostazioni", "msg_settings_saved": "Impostazioni salvate ed applicate con successo!", "msg_settings_saved_restart_lang": "Impostazioni salvate! Riavvia l'app per applicare completamente la nuova lingua.", "checking_updates": "Ricerca aggiornamenti in corso...", "tray_show_window": "Mostra Finestra", "tray_pause": "Metti in Pausa", "tray_resume": "Riprendi Ascolto", "tray_open_web": "Apri Dashboard Web", "tray_check_updates": "Controlla Aggiornamenti...", "tray_quit": "Esci", "tray_update_title": "Aggiornamento disponibile (v{version})", "tray_update_body": "Apri la finestra di Barcode Reader Server per installarlo automaticamente.", "updates_dialog_title": "Aggiornamenti", "updates_check_title": "Controllo Aggiornamenti", "update_win_title": "Aggiornamento Disponibile — v{version}", "update_new_version": "Nuova versione disponibile: v{version}", "update_installed_sub": "Versione installata: v{version} • {title}", "update_no_notes": "Nessuna nota di rilascio specificata.", "update_no_asset": "Nessun pacchetto specifico trovato per questa piattaforma negli asset della release.", "update_ready_pkg": "Pacchetto pronto per l'installazione: {name}{size}", "btn_later": "Più Tardi", "btn_open_release_page": "Apri Pagina Release", "btn_update_restart": "Aggiorna e Riavvia", "update_downloading": "Scaricamento di {name}...", "update_downloading_pct": "Scaricamento: {done:.1f} / {total:.1f} MB ({percent}%)", "update_downloading_mb": "Scaricati {done:.1f} MB...", "update_installing": "Installazione aggiornamento e riavvio in corso...", "update_apply_error": "Errore avvio aggiornamento: {error}", "update_error_prefix": "Errore: {error}", "update_error_title": "Errore Aggiornamento", }, } def detect_system_language() -> str: """Detect OS locale and return 'it' for Italian, 'en' otherwise.""" try: from PySide6.QtCore import QLocale qt_lang = QLocale.system().name().lower() if qt_lang.startswith("it"): return "it" if qt_lang: return "en" except Exception: pass for candidate in ( os.environ.get("LC_ALL"), os.environ.get("LC_MESSAGES"), os.environ.get("LANG"), ): if candidate: return "it" if candidate.lower().startswith("it") else "en" try: loc, _ = locale.getlocale() if loc and loc.lower().startswith("it"): return "it" except Exception: pass return "en" def set_language(lang_code: str | None) -> str: """Set active language ('auto', 'it', 'en') and return the resolved language code.""" global _CURRENT_LANG normalized = (lang_code or "auto").strip().lower() if normalized in ("it", "en"): _CURRENT_LANG = normalized else: _CURRENT_LANG = detect_system_language() return _CURRENT_LANG def get_language() -> str: return _CURRENT_LANG def tr(key: str, **kwargs) -> str: table = TRANSLATIONS.get(_CURRENT_LANG, TRANSLATIONS["en"]) template = table.get(key, TRANSLATIONS["en"].get(key, key)) return template.format(**kwargs) if kwargs else template