diff --git a/README.md b/README.md index 175d969..2bfa5fa 100644 --- a/README.md +++ b/README.md @@ -596,6 +596,17 @@ mid_value = sg.lerp(start=0, end=10, factor=0.5) # Returns 5.0 smooth_value = sg.smooth_step(edge0=0, edge1=10, x=5) # Smooth transition ``` +### Translations + +The text the library speaks itself, such as the text box's "Submitted" and "Beginning of text", the text window's instructions, menu items and high scores, can be translated. The library has its own gettext domain, `libstormgames`, so one translation serves every game. By default it follows the system's language settings. A game that lets players choose a language tells the library too, so both speak the same one: + +```python +# "de", "pt_BR" and so on; None follows the system again. +sg.set_language("de") +``` + +Without a translation for that language, the library speaks English. Translations live in `locales//LC_MESSAGES/libstormgames.po`. `tools/update-translations.sh` extracts the text into `locales/libstormgames.pot` and compiles every translation, and `tools/update-translations.sh new de` starts one. It needs GNU gettext. A game bundled with PyInstaller must include the `locales` folder next to the library's code, as `libstormgames/locales`. + ## Advanced Examples diff --git a/__init__.py b/__init__.py index 720c433..20734aa 100755 --- a/__init__.py +++ b/__init__.py @@ -39,6 +39,9 @@ from .sound import ( calculate_volume_and_pan ) +# Translations of the library's own text +from .i18n import set_language + # Import Speech class and functions from .speech import (messagebox, speak, Speech, speak_previous, speak_current, speak_next, set_text_display, add_speech_listener, remove_speech_listener) @@ -111,6 +114,9 @@ __all__ = [ 'add_speech_listener', 'remove_speech_listener', + # Translations + 'set_language', + # Scoreboard 'Scoreboard', diff --git a/display.py b/display.py index 72bc385..6d4c5b1 100644 --- a/display.py +++ b/display.py @@ -16,6 +16,7 @@ import random from xdg import BaseDirectory from setproctitle import setproctitle from .speech import Speech +from .i18n import _ from .services import PathService, VolumeService # Keep track of the instructions for navigating display_text has been shown @@ -166,14 +167,14 @@ def display_text(text): # Add instructions at the start on the first display global displayTextUsageInstructions if not displayTextUsageInstructions: - instructions = ("Press space to read the whole text. Use up and down arrows to navigate " - "the text line by line. Press c to copy the current line to the clipboard " - "or t to copy the entire text. Press enter or escape when you are done reading.") + instructions = _("Press space to read the whole text. Use up and down arrows to navigate " + "the text line by line. Press c to copy the current line to the clipboard " + "or t to copy the entire text. Press enter or escape when you are done reading.") navText.insert(0, instructions) displayTextUsageInstructions = True # Add end marker - navText.append("End of text.") + navText.append(_("End of text.")) currentIndex = 0 speech.speak(navText[currentIndex]) @@ -221,16 +222,16 @@ def display_text(text): if event.key == pygame.K_c: try: pyperclip.copy(navText[currentIndex]) - speech.speak("Copied " + navText[currentIndex] + " to the clipboard.") + speech.speak(_("Copied {text} to the clipboard.").format(text=navText[currentIndex])) except: - speech.speak("Failed to copy the text to the clipboard.") + speech.speak(_("Failed to copy the text to the clipboard.")) if event.key == pygame.K_t: try: # Join with newlines to preserve blank lines in full text pyperclip.copy('\n'.join(originalText)) - speech.speak("Copied entire message to the clipboard.") + speech.speak(_("Copied entire message to the clipboard.")) except: - speech.speak("Failed to copy the text to the clipboard.") + speech.speak(_("Failed to copy the text to the clipboard.")) # Keys pressed quickly wait in pygame's queue, and event.wait() takes the next one, # so nothing is cleared here: clearing would lose them. diff --git a/i18n.py b/i18n.py new file mode 100644 index 0000000..e0bd1f7 --- /dev/null +++ b/i18n.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Translations for the text libstormgames itself speaks and shows. + +The library has its own gettext domain, "libstormgames", separate from any +game's, so one translation of the library serves every game that uses it. +Translations live in locales//LC_MESSAGES/libstormgames.po inside +the library, and tools/update-translations.sh extracts the text and +compiles them. + +By default the library follows the system's language settings. A game +that lets players choose a language calls set_language() with the same +code it uses for its own text, so the library and the game always speak +the same language. + +Mark text with _() where it is spoken, ngettext() where it depends on a +number, and N_() for tables defined before the language is chosen, passed +through _() when spoken. Placeholders are always named, as in +"{name} deleted", so a translation can put them in any order. +""" + +import gettext +import os + +domain = "libstormgames" +localeDirectory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "locales") +translation = gettext.NullTranslations() + + +def set_language(language=None, directory=None): + """Choose the language the library speaks. + + Args: + language (str): A language code such as "de" or "pt_BR", or None to + follow the system's settings. Without a translation for it, the + library speaks English. + directory (str): Where to find translations, for testing one that is + not part of the library yet. Defaults to the library's own locales. + """ + global translation + languages = [language] if language else None + translation = gettext.translation(domain, directory or localeDirectory, languages=languages, fallback=True) + + +def _(message): + return translation.gettext(message) + + +def ngettext(singular, plural, count): + return translation.ngettext(singular, plural, count) + + +def pgettext(context, message): + return translation.pgettext(context, message) + + +def N_(message): + """Marks text for translation without translating it yet.""" + return message + + +set_language() diff --git a/input.py b/input.py index 8a424b6..4239cfe 100644 --- a/input.py +++ b/input.py @@ -11,8 +11,46 @@ Provides functionality for: import pygame import time from .speech import speak +from .i18n import _, ngettext, N_ -def get_input(prompt="Enter text:", text="", password=False): +# Translators: names of symbols, spoken as they are typed, since speech often skips punctuation. +symbolNames = { + ' ': N_('space'), + '\\': N_('backslash'), + '/': N_('slash'), + '!': N_('exclamation mark'), + '"': N_('quotation mark'), + '#': N_('hash'), + '$': N_('dollar sign'), + '%': N_('percent'), + '&': N_('ampersand'), + "'": N_('apostrophe'), + '(': N_('left parenthesis'), + ')': N_('right parenthesis'), + '*': N_('asterisk'), + '+': N_('plus'), + ',': N_('comma'), + '-': N_('minus'), + '.': N_('period'), + ':': N_('colon'), + ';': N_('semicolon'), + '<': N_('less than'), + '=': N_('equals'), + '>': N_('greater than'), + '?': N_('question mark'), + '@': N_('at sign'), + '[': N_('left bracket'), + ']': N_('right bracket'), + '^': N_('caret'), + '_': N_('underscore'), + '`': N_('grave accent'), + '{': N_('left brace'), + '|': N_('pipe'), + '}': N_('right brace'), + '~': N_('tilde'), +} + +def get_input(prompt=None, text="", password=False): """Display an accessible text input dialog using pygame. Features: @@ -28,7 +66,7 @@ def get_input(prompt="Enter text:", text="", password=False): says only "Submitted" Args: - prompt (str): Prompt text to display (default: "Enter text:") + prompt (str): Prompt text to display (default: "Enter text:" in the chosen language) text (str): Initial text in input box (default: "") password (bool): Keep the text secret, for passwords (default: False) @@ -36,23 +74,26 @@ def get_input(prompt="Enter text:", text="", password=False): str: User input text, or None if cancelled """ + if prompt is None: + prompt = _("Enter text:") + # Initialize text buffer and cursor text_buffer = list(text) # Use list for easier character manipulation cursor_pos = len(text_buffer) # Start at end of initial text def length_message(): count = len(text_buffer) - return "1 character" if count == 1 else f"{count} characters" + return ngettext("{count} character", "{count} characters", count).format(count=count) # Announce the prompt and initial text as a single message if text and password: - initial_message = f"{prompt} Password field, {length_message()}" + initial_message = _("{prompt} Password field, {length}").format(prompt=prompt, length=length_message()) elif text: - initial_message = f"{prompt} Default text: {text}" + initial_message = _("{prompt} Default text: {text}").format(prompt=prompt, text=text) elif password: - initial_message = f"{prompt} Empty password field" + initial_message = _("{prompt} Empty password field").format(prompt=prompt) else: - initial_message = f"{prompt} Empty text field" + initial_message = _("{prompt} Empty text field").format(prompt=prompt) speak(initial_message) # Clear any pending events @@ -67,14 +108,16 @@ def get_input(prompt="Enter text:", text="", password=False): # Submit the input result = ''.join(text_buffer) if password: - speak("Submitted" if result else "Submitted: empty") + speak(_("Submitted") if result else _("Submitted: empty")) + elif result: + speak(_("Submitted: {text}").format(text=result)) else: - speak(f"Submitted: {result if result else 'empty'}") + speak(_("Submitted: empty")) return result elif event.key == pygame.K_ESCAPE: # Cancel input - speak("Cancelled") + speak(_("Cancelled")) return None elif event.key == pygame.K_BACKSPACE: @@ -82,38 +125,38 @@ def get_input(prompt="Enter text:", text="", password=False): if cursor_pos > 0: deleted_char = text_buffer.pop(cursor_pos - 1) cursor_pos -= 1 - speak("star deleted" if password else f"{deleted_char} deleted") + speak(_("star deleted") if password else _("{character} deleted").format(character=character_name(deleted_char))) else: - speak("Nothing to delete") + speak(_("Nothing to delete")) elif event.key == pygame.K_DELETE: # Delete character at cursor if cursor_pos < len(text_buffer): deleted_char = text_buffer.pop(cursor_pos) - speak("star deleted" if password else f"{deleted_char} deleted") + speak(_("star deleted") if password else _("{character} deleted").format(character=character_name(deleted_char))) else: - speak("Nothing to delete") + speak(_("Nothing to delete")) elif event.key == pygame.K_LEFT: # Move cursor left and speak character if cursor_pos > 0: cursor_pos -= 1 if cursor_pos == 0: - speak("Beginning of text") + speak(_("Beginning of text")) else: - speak("star" if password else text_buffer[cursor_pos]) + speak(_("star") if password else character_name(text_buffer[cursor_pos])) else: - speak("Beginning of text") + speak(_("Beginning of text")) elif event.key == pygame.K_RIGHT: # Move cursor right and speak character if cursor_pos < len(text_buffer): - speak("star" if password else text_buffer[cursor_pos]) + speak(_("star") if password else character_name(text_buffer[cursor_pos])) cursor_pos += 1 if cursor_pos == len(text_buffer): - speak("End of text") + speak(_("End of text")) else: - speak("End of text") + speak(_("End of text")) elif event.key == pygame.K_UP or event.key == pygame.K_DOWN: # Read entire text content @@ -122,17 +165,17 @@ def get_input(prompt="Enter text:", text="", password=False): elif text_buffer: speak(''.join(text_buffer)) else: - speak("Empty text field") + speak(_("Empty text field")) elif event.key == pygame.K_HOME: # Move to beginning cursor_pos = 0 - speak("Beginning of text") + speak(_("Beginning of text")) elif event.key == pygame.K_END: # Move to end cursor_pos = len(text_buffer) - speak("End of text") + speak(_("End of text")) elif event.key == pygame.K_LCTRL or event.key == pygame.K_RCTRL: # Repeat the original prompt message @@ -146,84 +189,20 @@ def get_input(prompt="Enter text:", text="", password=False): text_buffer.insert(cursor_pos, char) cursor_pos += 1 - # Speak the character name - if password: - speak("star") - elif char == ' ': - speak("space") - elif char == '\\': - speak("backslash") - elif char == '/': - speak("slash") - elif char == '!': - speak("exclamation mark") - elif char == '"': - speak("quotation mark") - elif char == '#': - speak("hash") - elif char == '$': - speak("dollar sign") - elif char == '%': - speak("percent") - elif char == '&': - speak("ampersand") - elif char == "'": - speak("apostrophe") - elif char == '(': - speak("left parenthesis") - elif char == ')': - speak("right parenthesis") - elif char == '*': - speak("asterisk") - elif char == '+': - speak("plus") - elif char == ',': - speak("comma") - elif char == '-': - speak("minus") - elif char == '.': - speak("period") - elif char == ':': - speak("colon") - elif char == ';': - speak("semicolon") - elif char == '<': - speak("less than") - elif char == '=': - speak("equals") - elif char == '>': - speak("greater than") - elif char == '?': - speak("question mark") - elif char == '@': - speak("at sign") - elif char == '[': - speak("left bracket") - elif char == ']': - speak("right bracket") - elif char == '^': - speak("caret") - elif char == '_': - speak("underscore") - elif char == '`': - speak("grave accent") - elif char == '{': - speak("left brace") - elif char == '|': - speak("pipe") - elif char == '}': - speak("right brace") - elif char == '~': - speak("tilde") - else: - # For regular letters, numbers, and other characters - speak(char) + # Speak the character, or the name of a symbol + speak(_("star") if password else character_name(char)) # Keys typed quickly wait in pygame's queue, and event.wait() takes the next one, # so nothing is cleared here: clearing would lose letters typed in a burst. +def character_name(character): + """A typed character as it should be spoken: symbols by name, everything else as itself.""" + name = symbolNames.get(character) + return _(name) if name else character + + def pause_game(): """Pauses the game until user presses backspace.""" - speak("Game paused, press backspace to resume.") + speak(_("Game paused, press backspace to resume.")) pygame.event.clear() try: pygame.mixer.pause() diff --git a/locales/libstormgames.pot b/locales/libstormgames.pot new file mode 100644 index 0000000..eaa9ff5 --- /dev/null +++ b/locales/libstormgames.pot @@ -0,0 +1,400 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the libstormgames package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: libstormgames\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-11-24 00:01-0500\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=CHARSET\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" + +#: display.py:170 utils.py:260 +msgid "" +"Press space to read the whole text. Use up and down arrows to navigate the " +"text line by line. Press c to copy the current line to the clipboard or t to " +"copy the entire text. Press enter or escape when you are done reading." +msgstr "" + +#: display.py:177 utils.py:267 +msgid "End of text." +msgstr "" + +#: display.py:225 utils.py:313 +#, python-brace-format +msgid "Copied {text} to the clipboard." +msgstr "" + +#: display.py:227 display.py:235 utils.py:315 utils.py:324 +msgid "Failed to copy the text to the clipboard." +msgstr "" + +#: display.py:233 utils.py:322 +msgid "Copied entire message to the clipboard." +msgstr "" + +#: input.py:18 +msgid "space" +msgstr "" + +#: input.py:19 +msgid "backslash" +msgstr "" + +#: input.py:20 +msgid "slash" +msgstr "" + +#: input.py:21 +msgid "exclamation mark" +msgstr "" + +#: input.py:22 +msgid "quotation mark" +msgstr "" + +#: input.py:23 +msgid "hash" +msgstr "" + +#: input.py:24 +msgid "dollar sign" +msgstr "" + +#: input.py:25 +msgid "percent" +msgstr "" + +#: input.py:26 +msgid "ampersand" +msgstr "" + +#: input.py:27 +msgid "apostrophe" +msgstr "" + +#: input.py:28 +msgid "left parenthesis" +msgstr "" + +#: input.py:29 +msgid "right parenthesis" +msgstr "" + +#: input.py:30 +msgid "asterisk" +msgstr "" + +#: input.py:31 +msgid "plus" +msgstr "" + +#: input.py:32 +msgid "comma" +msgstr "" + +#: input.py:33 +msgid "minus" +msgstr "" + +#: input.py:34 +msgid "period" +msgstr "" + +#: input.py:35 +msgid "colon" +msgstr "" + +#: input.py:36 +msgid "semicolon" +msgstr "" + +#: input.py:37 +msgid "less than" +msgstr "" + +#: input.py:38 +msgid "equals" +msgstr "" + +#: input.py:39 +msgid "greater than" +msgstr "" + +#: input.py:40 +msgid "question mark" +msgstr "" + +#: input.py:41 +msgid "at sign" +msgstr "" + +#: input.py:42 +msgid "left bracket" +msgstr "" + +#: input.py:43 +msgid "right bracket" +msgstr "" + +#: input.py:44 +msgid "caret" +msgstr "" + +#: input.py:45 +msgid "underscore" +msgstr "" + +#: input.py:46 +msgid "grave accent" +msgstr "" + +#: input.py:47 +msgid "left brace" +msgstr "" + +#: input.py:48 +msgid "pipe" +msgstr "" + +#: input.py:49 +msgid "right brace" +msgstr "" + +#: input.py:50 +msgid "tilde" +msgstr "" + +#: input.py:78 +msgid "Enter text:" +msgstr "" + +#: input.py:86 +#, python-brace-format +msgid "{count} character" +msgid_plural "{count} characters" +msgstr[0] "" +msgstr[1] "" + +#: input.py:90 +#, python-brace-format +msgid "{prompt} Password field, {length}" +msgstr "" + +#: input.py:92 +#, python-brace-format +msgid "{prompt} Default text: {text}" +msgstr "" + +#: input.py:94 +#, python-brace-format +msgid "{prompt} Empty password field" +msgstr "" + +#: input.py:96 +#, python-brace-format +msgid "{prompt} Empty text field" +msgstr "" + +#: input.py:111 +msgid "Submitted" +msgstr "" + +#: input.py:111 input.py:115 +msgid "Submitted: empty" +msgstr "" + +#: input.py:113 +#, python-brace-format +msgid "Submitted: {text}" +msgstr "" + +#: input.py:120 +msgid "Cancelled" +msgstr "" + +#: input.py:128 input.py:136 +msgid "star deleted" +msgstr "" + +#: input.py:128 input.py:136 +#, python-brace-format +msgid "{character} deleted" +msgstr "" + +#: input.py:130 input.py:138 +msgid "Nothing to delete" +msgstr "" + +#: input.py:145 input.py:149 input.py:173 +msgid "Beginning of text" +msgstr "" + +#: input.py:147 input.py:154 input.py:193 +msgid "star" +msgstr "" + +#: input.py:157 input.py:159 input.py:178 +msgid "End of text" +msgstr "" + +#: input.py:168 +msgid "Empty text field" +msgstr "" + +#: input.py:205 +msgid "Game paused, press backspace to resume." +msgstr "" + +#: menu.py:32 +msgid "play" +msgstr "" + +#: menu.py:33 +msgid "high scores" +msgstr "" + +#: menu.py:34 +msgid "learn sounds" +msgstr "" + +#: menu.py:35 +msgid "instructions" +msgstr "" + +#: menu.py:36 +msgid "credits" +msgstr "" + +#: menu.py:37 +msgid "donate" +msgstr "" + +#: menu.py:38 +msgid "exit game" +msgstr "" + +#: menu.py:448 +msgid "No sounds available to learn." +msgstr "" + +#: menu.py:463 +msgid "" +"Starting with root directory sounds. Use left and right arrows or page up " +"and page down to navigate categories." +msgstr "" + +#: menu.py:466 +#, python-brace-format +msgid "" +"Starting with {category} sounds. Use left and right arrows or page up and " +"page down to navigate categories." +msgstr "" + +#. Translators: a sound's name and what it is, as in "bell: the lap bell". +#: menu.py:493 +#, python-brace-format +msgid "{sound}: {description}" +msgstr "" + +#: menu.py:499 +#, python-brace-format +msgid "Root directory: {sound}, {number} of {total}" +msgstr "" + +#: menu.py:502 +#, python-brace-format +msgid "{category}: {sound}, {number} of {total}" +msgstr "" + +#: menu.py:506 +#, python-brace-format +msgid "{sound}, {number} of {total}" +msgstr "" + +#: menu.py:553 +msgid "Could not play sound." +msgstr "" + +#: menu.py:571 +msgid "Instructions file is missing." +msgstr "" + +#: menu.py:589 +msgid "Credits file is missing." +msgstr "" + +#: menu.py:599 +msgid "The donation page has been opened in your browser." +msgstr "" + +#: scoreboard.py:170 +msgid "New high score! Enter your name:" +msgstr "" + +#: scoreboard.py:172 +msgid "Player" +msgstr "" + +#: scoreboard.py:211 scoreboard.py:215 +#, python-brace-format +msgid "Congratulations {name}! You got position {position} on the scoreboard!" +msgstr "" + +#: scoreboard.py:315 +#, python-brace-format +msgid "High Scores for {game}:" +msgstr "" + +#. Translators: one line of the high scores, as in "1. Username: 500". +#: scoreboard.py:321 +#, python-brace-format +msgid "{place}. {name}: {score}" +msgstr "" + +#: scoreboard.py:324 +msgid "No high scores yet." +msgstr "" + +#: scoreboard.py:330 +msgid "Could not display high scores." +msgstr "" + +#: speech.py:304 speech.py:311 +msgid "Press any key to repeat or enter to continue." +msgstr "" + +#: speech.py:470 +#, python-brace-format +msgid "First: {message}" +msgstr "" + +#: speech.py:473 +msgid "No previous messages" +msgstr "" + +#: speech.py:475 speech.py:489 speech.py:506 +msgid "Speech history not available" +msgstr "" + +#: speech.py:487 +msgid "No messages in history" +msgstr "" + +#: speech.py:501 +#, python-brace-format +msgid "Last: {message}" +msgstr "" + +#: speech.py:504 +msgid "No next messages" +msgstr "" diff --git a/menu.py b/menu.py index da457e9..9b24dcf 100644 --- a/menu.py +++ b/menu.py @@ -24,6 +24,19 @@ from .sound import adjust_master_volume, adjust_bgm_volume, adjust_sfx_volume, p from .display import display_text from .scoreboard import Scoreboard from .services import PathService, ConfigService +from .i18n import _, N_ + +# What game_menu() says for its own items. A game's own items are spoken +# as they are given, with underscores read as spaces. +standardItemNames = { + "play": N_("play"), + "high_scores": N_("high scores"), + "learn_sounds": N_("learn sounds"), + "instructions": N_("instructions"), + "credits": N_("credits"), + "donate": N_("donate"), + "exit_game": N_("exit game"), +} def instruction_menu(sounds, instruction_text, *options): """Display a menu with an instruction announcement at the top. @@ -192,7 +205,8 @@ def game_menu(sounds, playCallback=None, *customOptions, soundDescriptions=None) while loop: if currentIndex != lastSpoken: - speech.speak(allOptions[currentIndex].replace("_", " ")) + option = allOptions[currentIndex] + speech.speak(_(standardItemNames[option]) if option in standardItemNames else option.replace("_", " ")) lastSpoken = currentIndex event = pygame.event.wait() @@ -431,7 +445,7 @@ def learn_sounds(sounds, descriptions=None): # If no sounds found, inform the user and return if not soundsByDir: - speech.speak("No sounds available to learn.") + speech.speak(_("No sounds available to learn.")) return "menu" # Get list of directories in sorted order @@ -445,7 +459,12 @@ def learn_sounds(sounds, descriptions=None): # Display appropriate message based on number of directories if len(directories) > 1: - messagebox(f"Starting with {currentDir if currentDir != 'root' else 'root directory'} sounds. Use left and right arrows or page up and page down to navigate categories.") + if currentDir == 'root': + messagebox(_("Starting with root directory sounds. Use left and right arrows or page up and page down " + "to navigate categories.")) + else: + messagebox(_("Starting with {category} sounds. Use left and right arrows or page up and page down " + "to navigate categories.").format(category=currentDir)) # Track last spoken to avoid repetition lastSpoken = -1 @@ -470,15 +489,22 @@ def learn_sounds(sounds, descriptions=None): description = find_sound_description(soundName, descriptions) if description: # A final full stop would run into the comma before the count. - displayName = f"{displayName}: {description.strip().rstrip('.')}" + # Translators: a sound's name and what it is, as in "bell: the lap bell". + displayName = _("{sound}: {description}").format(sound=displayName, + description=description.strip().rstrip('.')) # If directory just changed, include directory name in announcement if directoryChanged: - dirDescription = "Root directory" if currentDir == 'root' else currentDir - announcement = f"{dirDescription}: {displayName}, {currentSoundIndex + 1} of {totalSounds}" + if currentDir == 'root': + announcement = _("Root directory: {sound}, {number} of {total}").format( + sound=displayName, number=currentSoundIndex + 1, total=totalSounds) + else: + announcement = _("{category}: {sound}, {number} of {total}").format( + category=currentDir, sound=displayName, number=currentSoundIndex + 1, total=totalSounds) directoryChanged = False # Reset flag after announcement else: - announcement = f"{displayName}, {currentSoundIndex + 1} of {totalSounds}" + announcement = _("{sound}, {number} of {total}").format( + sound=displayName, number=currentSoundIndex + 1, total=totalSounds) speech.speak(announcement) lastSpoken = currentSoundIndex @@ -524,7 +550,7 @@ def learn_sounds(sounds, descriptions=None): sounds[soundName].play() except Exception as e: print(f"Error playing sound: {e}") - speech.speak("Could not play sound.") + speech.speak(_("Could not play sound.")) event = pygame.event.clear() pygame.event.pump() # Process pygame's internal events @@ -542,7 +568,7 @@ def instructions(): with open('files/instructions.txt', 'r') as f: info = f.readlines() except: - info = ["Instructions file is missing."] + info = [_("Instructions file is missing.")] display_text(info) def credits(): @@ -560,7 +586,7 @@ def credits(): info.insert(0, pathService.gameName + "\n") except Exception as e: print(f"Error in credits: {e}") - info = ["Credits file is missing."] + info = [_("Credits file is missing.")] display_text(info) @@ -570,7 +596,7 @@ def donate(): Opens the donation page. """ webbrowser.open('https://www.paypal.com/donate/?business=stormdragon2976@gmail.com&no_recurring=0¤cy_code=USD') - messagebox("The donation page has been opened in your browser.") + messagebox(_("The donation page has been opened in your browser.")) def exit_game(fade=0): """Clean up and exit the game properly. diff --git a/scoreboard.py b/scoreboard.py index 95fa67f..2dc368b 100644 --- a/scoreboard.py +++ b/scoreboard.py @@ -12,6 +12,7 @@ import os from .services import ConfigService, PathService from .speech import Speech from .display import display_text +from .i18n import _ # For backward compatibility from .config import localConfig, write_config, read_config @@ -166,9 +167,9 @@ class Scoreboard: if name is None: # Import get_input here to avoid circular imports from .input import get_input - name = get_input("New high score! Enter your name:", "") + name = get_input(_("New high score! Enter your name:"), "") if name is None or name.strip() == "": # User cancelled or entered empty - name = "Player" + name = _("Player") # Insert new score at correct position self.highScores.insert(position - 1, { @@ -207,11 +208,11 @@ class Scoreboard: # Announce success try: - self.speech.messagebox(f"Congratulations {name}! You got position {position} on the scoreboard!") + self.speech.messagebox(_("Congratulations {name}! You got position {position} on the scoreboard!").format(name=name, position=position)) except: # Fallback to global speak function from .speech import speak - speak(f"Congratulations {name}! You got position {position} on the scoreboard!") + speak(_("Congratulations {name}! You got position {position} on the scoreboard!").format(name=name, position=position)) time.sleep(1) return True @@ -311,21 +312,22 @@ class Scoreboard: validScores = [score for score in scores if score['score'] > 0] # Prepare the lines to display - lines = [f"High Scores for {gameName}:"] + lines = [_("High Scores for {game}:").format(game=gameName)] # Add scores to the display list if validScores: for i, entry in enumerate(validScores, 1): - scoreStr = f"{i}. {entry['name']}: {entry['score']}" + # Translators: one line of the high scores, as in "1. Username: 500". + scoreStr = _("{place}. {name}: {score}").format(place=i, name=entry['name'], score=entry['score']) lines.append(scoreStr) else: - lines.append("No high scores yet.") + lines.append(_("No high scores yet.")) # Display the high scores display_text(lines) except Exception as e: print(f"Error displaying high scores: {e}") - info = ["Could not display high scores."] + info = [_("Could not display high scores.")] display_text(info) # For backward compatibility with older code that might call displayHigh_scores diff --git a/speech.py b/speech.py index 7fb08c8..ab2de1e 100644 --- a/speech.py +++ b/speech.py @@ -14,6 +14,8 @@ import time from contextlib import contextmanager from sys import exit +from .i18n import _ + # Keep track of whether dialog instructions have been shown dialogUsageInstructions = False @@ -299,14 +301,14 @@ def _suspend_message_music(): def _show_simple_message(speech, text): """Show a simple text message (original messagebox behavior).""" - speech.speak(text + "\nPress any key to repeat or enter to continue.") + speech.speak(text + "\n" + _("Press any key to repeat or enter to continue.")) while True: event = pygame.event.wait() if event.type == pygame.KEYDOWN: if event.key in (pygame.K_ESCAPE, pygame.K_RETURN): speech.speak(" ") return - speech.speak(text + "\nPress any key to repeat or enter to continue.") + speech.speak(text + "\n" + _("Press any key to repeat or enter to continue.")) def _show_dialog_sequence(speech, dialog_config, sounds): @@ -464,14 +466,13 @@ def speak_previous(): message = history_service.move_previous() if message: # Add position indicator - prefix = "" if history_service.is_at_first(): - prefix = "First: " - speak(prefix + message, interrupt=True, priority="important", add_to_history=False) + message = _("First: {message}").format(message=message) + speak(message, interrupt=True, priority="important", add_to_history=False) else: - speak("No previous messages", interrupt=True, priority="important", add_to_history=False) + speak(_("No previous messages"), interrupt=True, priority="important", add_to_history=False) except ImportError: - speak("Speech history not available", interrupt=True, priority="important", add_to_history=False) + speak(_("Speech history not available"), interrupt=True, priority="important", add_to_history=False) def speak_current(): @@ -483,9 +484,9 @@ def speak_current(): if message: speak(message, interrupt=True, priority="important", add_to_history=False) else: - speak("No messages in history", interrupt=True, priority="important", add_to_history=False) + speak(_("No messages in history"), interrupt=True, priority="important", add_to_history=False) except ImportError: - speak("Speech history not available", interrupt=True, priority="important", add_to_history=False) + speak(_("Speech history not available"), interrupt=True, priority="important", add_to_history=False) def speak_next(): @@ -496,11 +497,10 @@ def speak_next(): message = history_service.move_next() if message: # Add position indicator - prefix = "" if history_service.is_at_last(): - prefix = "Last: " - speak(prefix + message, interrupt=True, priority="important", add_to_history=False) + message = _("Last: {message}").format(message=message) + speak(message, interrupt=True, priority="important", add_to_history=False) else: - speak("No next messages", interrupt=True, priority="important", add_to_history=False) + speak(_("No next messages"), interrupt=True, priority="important", add_to_history=False) except ImportError: - speak("Speech history not available", interrupt=True, priority="important", add_to_history=False) + speak(_("Speech history not available"), interrupt=True, priority="important", add_to_history=False) diff --git a/tools/update-translations.sh b/tools/update-translations.sh new file mode 100755 index 0000000..db5f7cb --- /dev/null +++ b/tools/update-translations.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Keep the translations of libstormgames' own text up to date. +# +# tools/update-translations.sh extract the text, merge it into +# every translation and compile them +# tools/update-translations.sh new de start a translation, for example de or pt_BR +# +# The text to translate goes to locales/libstormgames.pot. Each translation is +# locales//LC_MESSAGES/libstormgames.po, compiled next to it as +# libstormgames.mo, which is what the library reads. Games choose the language +# with set_language(). Needs GNU gettext. + +set -euo pipefail + +libraryDir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +localeDir="$libraryDir/locales" +templateFile="$localeDir/libstormgames.pot" + +cd "$libraryDir" +mkdir -p "$localeDir" + +sourceFiles=(./*.py) +xgettext --language=Python --from-code=UTF-8 \ + --keyword=_ --keyword=N_ --keyword=ngettext:1,2 --keyword=pgettext:1c,2 \ + --add-comments=Translators --package-name="libstormgames" --sort-by-file \ + --output="$templateFile" "${sourceFiles[@]}" +echo "Extracted the text to translate into $templateFile" + +if [[ "${1:-}" == "new" ]]; then + language="${2:?Name the language, for example: tools/update-translations.sh new de}" + newFile="$localeDir/$language/LC_MESSAGES/libstormgames.po" + if [[ -e "$newFile" ]]; then + echo "$newFile already exists, so it was left alone." + exit 1 + fi + mkdir -p "$(dirname "$newFile")" + msginit --no-translator --locale="$language" --input="$templateFile" --output-file="$newFile" + # msginit often picks ASCII, which cannot hold accented letters, so switch to UTF-8. + msgconv --to-code=UTF-8 --output-file="$newFile" "$newFile" + echo "Started $newFile" +fi + +shopt -s nullglob +for translationFile in "$localeDir"/*/LC_MESSAGES/libstormgames.po; do + msgmerge --quiet --update --backup=none "$translationFile" "$templateFile" + msgfmt --check --output-file="${translationFile%.po}.mo" "$translationFile" + echo "Compiled $translationFile" +done diff --git a/utils.py b/utils.py index d72967e..9a40314 100644 --- a/utils.py +++ b/utils.py @@ -17,6 +17,7 @@ import re import requests import os from .input import check_for_exit +from .i18n import _ from setproctitle import setproctitle from .services import PathService, ConfigService, VolumeService @@ -256,14 +257,14 @@ class Game: # Add instructions at the start on the first display if not self.displayTextUsageInstructions: - instructions = ("Press space to read the whole text. Use up and down arrows to navigate " - "the text line by line. Press c to copy the current line to the clipboard " - "or t to copy the entire text. Press enter or escape when you are done reading.") + instructions = _("Press space to read the whole text. Use up and down arrows to navigate " + "the text line by line. Press c to copy the current line to the clipboard " + "or t to copy the entire text. Press enter or escape when you are done reading.") navText.insert(0, instructions) self.displayTextUsageInstructions = True # Add end marker - navText.append("End of text.") + navText.append(_("End of text.")) currentIndex = 0 self.speech.speak(navText[currentIndex]) @@ -303,24 +304,24 @@ class Game: if event.key == pygame.K_SPACE: # Join with newlines to preserve spacing in speech - self.speech.speak('\n'.join(originalText[1:-1])) + self.speech.speak('\n'.join(originalText)) if event.key == pygame.K_c: try: import pyperclip pyperclip.copy(navText[currentIndex]) - self.speech.speak("Copied " + navText[currentIndex] + " to the clipboard.") + self.speech.speak(_("Copied {text} to the clipboard.").format(text=navText[currentIndex])) except: - self.speech.speak("Failed to copy the text to the clipboard.") + self.speech.speak(_("Failed to copy the text to the clipboard.")) if event.key == pygame.K_t: try: import pyperclip # Join with newlines to preserve blank lines in full text - pyperclip.copy(''.join(originalText[2:-1])) - self.speech.speak("Copied entire message to the clipboard.") + pyperclip.copy('\n'.join(originalText)) + self.speech.speak(_("Copied entire message to the clipboard.")) except: - self.speech.speak("Failed to copy the text to the clipboard.") + self.speech.speak(_("Failed to copy the text to the clipboard.")) pygame.event.clear() time.sleep(0.001)