Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FEATURE: Setting preferred locale and fallback manually #5026

Draft
wants to merge 15 commits into
base: release/v2.5.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 56 additions & 1 deletion lang/lang.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"embed"
"encoding/json"
"log"
"sort"
"strings"
"text/template"

Expand Down Expand Up @@ -35,6 +36,12 @@ var (
// More info available on the `LocalizePluralKey` function.
XN = LocalizePluralKey

// This defines an order in which it will try to find a fallback in case localizer does not find a match.
// All other languages will be in alphabetical order.
languageOrder = []string{"en"}

preferredLanguage string

bundle *i18n.Bundle
localizer *i18n.Localizer

Expand Down Expand Up @@ -159,6 +166,21 @@ func AddTranslationsFS(fs embed.FS, dir string) (retErr error) {
return retErr
}

// SetLanguageOrder allows an app to set the order in which translations are checked in case no locale matches.
// Since 2.6
func SetLanguageOrder(order []string) {
languageOrder = order
updateLocalizer()
}

// SetPreferredLocale allows an app to set the preferred locale for translations, overwriting the System Locale.
// locale can be in format en_US_someVariant, en_US, en-US-someVariant, en-US, en
// Since 2.6
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't the right format for a since line, missing : and the blank comment line above - see https://github.com/fyne-io/fyne/wiki/Contributing (or other Since: lines in the codebase).

func SetPreferredLocale(locale string) {
preferredLanguage = locale
updateLocalizer()
}

func addLanguage(data []byte, name string) error {
f, err := bundle.ParseMessageFileBytes(data, name)
translated = append(translated, f.Tag)
Expand All @@ -169,7 +191,6 @@ func init() {
bundle = i18n.NewBundle(language.English)
bundle.RegisterUnmarshalFunc("json", json.Unmarshal)

translated = []language.Tag{language.Make("en")} // the first item in this list will be the fallback if none match
err := AddTranslationsFS(translations, "translations")
if err != nil {
fyne.LogError("Error occurred loading built-in translations", err)
Expand All @@ -187,18 +208,52 @@ func fallbackWithData(key, fallback string, data any) string {
return str.String()
}

func orderLanguages(a, b language.Tag) bool {
indexA := -1
indexB := -1
for i, l := range languageOrder {
if a.String() == l {
indexA = i
}
if b.String() == l {
indexB = i
}
}
// Order both languages as defined in languageOrder
if indexA != -1 && indexB != -1 {
return indexA < indexB
}
// If it is the only language in languageOrder, it comes first
if indexA != -1 {
return true
}
if indexB != -1 {
return false
}
// If no language is in languageOrder, sort alphabetically
return strings.Compare(a.String(), b.String()) < 0
}

// A utility for setting up languages - available to unit tests for overriding system
func setupLang(lang string) {
localizer = i18n.NewLocalizer(bundle, lang)
}

// updateLocalizer Finds the closest translation from the user's locale list and sets it up
func updateLocalizer() {
// Sort the translated slice using the orderLanguages function
sort.SliceStable(translated, func(i, j int) bool {
return orderLanguages(translated[i], translated[j])
})

all, err := locale.GetLocales()
if err != nil {
fyne.LogError("Failed to load user locales", err)
all = []string{"en"}
}
if preferredLanguage != "" {
all = []string{preferredLanguage}
}
str := closestSupportedLocale(all).LanguageString()
setupLang(str)
localizer = i18n.NewLocalizer(bundle, str)
Expand Down
33 changes: 28 additions & 5 deletions lang/lang_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,6 @@ func TestAddTranslations(t *testing.T) {
assert.Equal(t, "Match2", L("Test2"))
}

func TestLocalize_Default(t *testing.T) {
fallback := closestSupportedLocale([]string{"xx"})
assert.Equal(t, fyne.Locale("en"), fallback[0:2])
}

func TestLocalize_Fallback(t *testing.T) {
assert.Equal(t, "Missing", L("Missing"))
}
Expand Down Expand Up @@ -81,3 +76,31 @@ func TestLocalizePluralKey_Fallback(t *testing.T) {
assert.Equal(t, "Apple", XN("appleID", "Apple", 1))
assert.Equal(t, "Apples", XN("appleID", "Apple", 2))
}

func TestSetPreferredLocale(t *testing.T) {
_ = AddTranslations(fyne.NewStaticResource("en.json", []byte(`{
"Test": "Match"
}`)))
_ = AddTranslations(fyne.NewStaticResource("fr.json", []byte(`{
"Test2": "Match2"
}`)))
setupLang("fr")
assert.Equal(t, "Match2", L("Test2"))
SetPreferredLocale("en")
assert.Equal(t, "Match", L("Test"))
}

func TestSetLanguageOrder(t *testing.T) {
_ = AddTranslations(fyne.NewStaticResource("en.json", []byte(`{
"Test": "Match"
}`)))
_ = AddTranslations(fyne.NewStaticResource("fr.json", []byte(`{
"Test2": "Match2"
}`)))
setupLang("en")
SetPreferredLocale("xyz") // invalid language to test fallback
SetLanguageOrder([]string{"fr", "en"})
assert.Equal(t, "Match2", L("Test2"))
SetLanguageOrder([]string{"en", "fr"})
assert.Equal(t, "Match", L("Test"))
}