瀏覽代碼

Fix setting up locale for Android and such

Michał Zaremba 6 月之前
父節點
當前提交
f0ee3b8257
共有 2 個文件被更改,包括 26 次插入9 次删除
  1. 24 7
      lib/texts/TextOperations.cpp
  2. 2 2
      lib/texts/TextOperations.h

+ 24 - 7
lib/texts/TextOperations.cpp

@@ -301,24 +301,41 @@ int TextOperations::getLevenshteinDistance(std::string_view s, std::string_view
 	return v0[n];
 }
 
-DLL_LINKAGE std::string TextOperations::getLocaleName()
+DLL_LINKAGE const std::locale & TextOperations::getLocale()
 {
-	return Languages::getLanguageOptions(LIBRARY->generaltexth->getPreferredLanguage()).localeName;
+    static std::locale loc;
+
+    const std::string & localeName = Languages::getLanguageOptions(LIBRARY->generaltexth->getPreferredLanguage()).localeName;
+    try
+    {
+        loc = std::locale(localeName); // might fail on Android
+    }
+    catch (const std::exception & e)
+    {
+        logGlobal->warn("Failed to set locale '%s'. Falling back to 'en_US.UTF-8'", localeName);
+        try
+        {
+            loc = std::locale("en_US.UTF-8");
+        }
+        catch (...)
+        {
+            logGlobal->warn("Fallback locale 'en_US.UTF-8' failed. Using default 'C' locale.");
+            loc = std::locale::classic();
+        }
+    }
+    return loc;
 }
 
 DLL_LINKAGE bool TextOperations::compareLocalizedStrings(std::string_view str1, std::string_view str2)
 {
-	static const std::locale loc(getLocaleName());
-	static const std::collate<char> & col = std::use_facet<std::collate<char>>(loc);
-
+    static const std::collate<char> & col = std::use_facet<std::collate<char>>(getLocale());
 	return col.compare(str1.data(), str1.data() + str1.size(),
 					   str2.data(), str2.data() + str2.size()) < 0;
 }
 
 std::optional<int> TextOperations::textSearchSimilarityScore(const std::string & s, const std::string & t)
 {
-	static const std::locale loc(getLocaleName());
-	static const std::collate<char> & col = std::use_facet<std::collate<char>>(loc);
+    static const std::collate<char> & col = std::use_facet<std::collate<char>>(getLocale());
 
 	auto haystack = col.transform(t.data(), t.data() + t.size());
 	auto needle = col.transform(s.data(), s.data() + s.size());

+ 2 - 2
lib/texts/TextOperations.h

@@ -76,8 +76,8 @@ namespace TextOperations
 	/// https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows
 	DLL_LINKAGE int getLevenshteinDistance(std::string_view s, std::string_view t);
 
-	/// Retrieves the locale name based on the selected (in config) game language.
-	DLL_LINKAGE std::string getLocaleName();
+    /// Retrieves the locale based on the selected (in config) game language.
+    DLL_LINKAGE const std::locale & getLocale();
 
 	/// Compares two strings using locale-aware collation based on the selected game language.
 	DLL_LINKAGE bool compareLocalizedStrings(std::string_view str1, std::string_view str2);