Files
screenreader-common/i18n/i18n.go
T

134 lines
4.3 KiB
Go

// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
// Package i18n loads a reader's gettext catalogs: installed catalogs first,
// then catalogs bundled into the binary, for each language in the user's
// preference order. Each reader keeps its own domain ("fenrir", "cthulhu")
// and decides which strings are user-facing. Screen contents and internal
// identifiers must never pass through it.
package i18n
import (
"io/fs"
"os"
"strconv"
"strings"
"sync/atomic"
"github.com/leonelquinteros/gotext"
)
// LocaleDir is the conventional root for installed catalogs.
const LocaleDir = "/usr/share/locale"
// Catalog is an immutable set of loaded translations. Lookups on a nil
// Catalog return the English message.
type Catalog struct{ locales []*gotext.Locale }
// Language follows Python gettext's environment precedence. LANGUAGE may list
// several languages separated by colons; C/POSIX stop catalog fallback.
func Language() string {
for _, name := range []string{"LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"} {
if value := os.Getenv(name); value != "" {
return value
}
}
return "C"
}
// New loads domain for a colon-separated language list. For each language it
// reads root/<lang>/LC_MESSAGES/<domain>.{mo,po} (installed contributor
// translations), then bundledDir/<lang>/LC_MESSAGES/<domain>.po inside
// bundled. Codesets are dropped and @modifiers kept (de_DE.UTF-8@euro is
// de_DE@euro). bundled may be nil.
func New(domain, root, languages string, bundled fs.FS, bundledDir string) *Catalog {
catalog := &Catalog{}
for _, language := range strings.Split(languages, ":") {
language = strings.TrimSpace(language)
if index := strings.IndexByte(language, '.'); index >= 0 {
modifier := ""
if at := strings.IndexByte(language[index:], '@'); at >= 0 {
modifier = language[index+at:]
}
language = language[:index] + modifier
}
if language == "C" || language == "POSIX" {
break
}
if language == "" || strings.ContainsAny(language, "/\\") {
continue
}
installed := gotext.NewLocale(root, language)
installed.AddDomain(domain)
catalog.locales = append(catalog.locales, installed)
// Keep each language's bundled catalog ahead of the next LANGUAGE
// fallback; installed translations keep priority within a language.
if bundled != nil {
local := gotext.NewLocaleFSWithPath(language, bundled, bundledDir)
local.AddDomain(domain)
catalog.locales = append(catalog.locales, local)
}
}
return catalog
}
// T returns the translation of message, or message itself.
func (c *Catalog) T(message string) string {
if c != nil {
for _, locale := range c.locales {
if locale.IsTranslated(message) {
return locale.Get(message)
}
}
}
return message
}
// N returns the plural form for count.
func (c *Catalog) N(singular, plural string, count int) string {
if c != nil {
for _, locale := range c.locales {
if locale.IsTranslatedN(singular, count) {
return locale.GetN(singular, plural, count)
}
}
}
if count == 1 {
return singular
}
return plural
}
// Format translates message, then substitutes Python-style positional fields
// {0}, {1}, ... with fields; {{ and }} are literal braces. Keeping the
// fields in the message ID lets translators reorder them.
func (c *Catalog) Format(message string, fields ...string) string {
return format(c.T(message), fields)
}
func format(message string, fields []string) string {
replacements := []string{"{{", "{", "}}", "}"}
for index, value := range fields {
replacements = append(replacements, "{"+strconv.Itoa(index)+"}", value)
}
return strings.NewReplacer(replacements...).Replace(message)
}
// Active holds the catalog a reader uses process-wide. Configure it once at
// startup; catalog loading never belongs on the input or event path. The
// zero value returns English.
type Active struct{ current atomic.Pointer[Catalog] }
// Use installs catalog and returns the previous one.
func (a *Active) Use(catalog *Catalog) *Catalog { return a.current.Swap(catalog) }
func (a *Active) T(message string) string { return a.current.Load().T(message) }
func (a *Active) N(singular, plural string, count int) string {
return a.current.Load().N(singular, plural, count)
}
func (a *Active) Format(message string, fields ...string) string {
return a.current.Load().Format(message, fields...)
}