Skip to content

Commit

Permalink
Merge pull request #5158 from rzats/fix/invalid-locale
Browse files Browse the repository at this point in the history
Fix crash when system locale is complex
  • Loading branch information
rzats authored Nov 7, 2023
2 parents d3bbd77 + dc4cb4c commit e679a98
Showing 1 changed file with 28 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@
import org.terasology.engine.config.flexible.constraints.LocaleConstraint;
import org.terasology.engine.config.flexible.constraints.NumberRangeConstraint;

import java.util.Arrays;
import java.util.Locale;
import java.util.Locale.Category;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.lang.Math.max;
import static org.terasology.engine.config.flexible.SettingArgument.constraint;
Expand Down Expand Up @@ -81,13 +86,34 @@ public class SystemConfig extends AutoConfig {

public final Setting<Locale> locale = setting(
type(Locale.class),
defaultValue(Locale.getDefault(Category.DISPLAY)),
defaultValue(getAdjustedLocale()),
name("${engine:menu#settings-language}"),
constraint(new LocaleConstraint(Locale.getAvailableLocales())) // TODO provide translate project's locales (Pirate lang don't works)
constraint(new LocaleConstraint(
// Locale.getAvailableLocales() + non-standard "pr" (pirate) tag
Stream.concat(Arrays.stream(Locale.getAvailableLocales()), Stream.of(Locale.forLanguageTag("pr")))
.collect(Collectors.toSet())))
);

@Override
public String getName() {
return "${engine:menu#system-settings-title}";
}

private static Locale getAdjustedLocale() {
Locale systemLocale = Locale.getDefault(Category.DISPLAY);

// Matches unusual locales on Mac OS created from the user's language and location, e.g. en_UA
if (!Arrays.asList(Locale.getAvailableLocales()).contains(systemLocale)) {
final Pattern langRegionPattern = Pattern.compile("[a-z]{2}_[A-Z]{2}");

String input = systemLocale.toString();
Matcher matcher = langRegionPattern.matcher(input);

// If the locale is like that, convert it to just the language, e.g. en_UA -> en
if (matcher.find()) {
systemLocale = Locale.forLanguageTag(systemLocale.getLanguage());
}
}
return systemLocale;
}
}

0 comments on commit e679a98

Please sign in to comment.