Browse Source

Add love.system.getPreferredLocales()

Miku AuahDark 3 years ago
parent
commit
c2104f896a

+ 13 - 0
src/modules/system/System.h

@@ -114,6 +114,19 @@ public:
 	 **/
 	bool hasBackgroundMusic() const;
 
+	/**
+	 * Gets the list of locales in order of user preference.
+	 * 
+	 * The returned string from this function has format of
+	 * xx_YY where 'xx' is ISO-639 language code and 'YY' is
+	 * the ISO-3166 country code if available. If country
+	 * code is unavailable, then it simply returns the language.
+	 * 
+	 * @return List user preferred locales or empty if the current
+	 * platform does not support this function.
+	 */
+	virtual std::vector<std::string> getPreferredLocales() const = 0;
+
 	static bool getConstant(const char *in, PowerState &out);
 	static bool getConstant(PowerState in, const char *&out);
 

+ 26 - 0
src/modules/system/sdl/System.cpp

@@ -25,6 +25,8 @@
 // SDL
 #include <SDL_clipboard.h>
 #include <SDL_cpuinfo.h>
+#include <SDL_locale.h>
+#include <SDL_version.h>
 
 namespace love
 {
@@ -88,6 +90,30 @@ love::system::System::PowerState System::getPowerInfo(int &seconds, int &percent
 	powerStates.find(sdlstate, state);
 
 	return state;
+}
+
+std::vector<std::string> System::getPreferredLocales() const
+{
+	std::vector<std::string> result;
+
+#if SDL_VERSION_ATLEAST(2, 0, 14)
+	SDL_Locale *locales = SDL_GetPreferredLocales();
+
+	if (locales)
+	{
+		for (SDL_Locale* locale = locales; locale->language != nullptr; locale++)
+		{
+			if (locale->country)
+				result.push_back(std::string(locale->language) + "_" + std::string(locale->country));
+			else
+				result.push_back(locale->language);
+		}
+
+		SDL_free(locales);
+	}
+#endif
+
+	return result;
 }
 
 EnumMap<System::PowerState, SDL_PowerState, System::POWER_MAX_ENUM>::Entry System::powerEntries[] =

+ 1 - 0
src/modules/system/sdl/System.h

@@ -51,6 +51,7 @@ public:
 	std::string getClipboardText() const;
 
 	PowerState getPowerInfo(int &seconds, int &percent) const;
+	std::vector<std::string> getPreferredLocales() const override;
 
 private:
 

+ 17 - 0
src/modules/system/wrap_System.cpp

@@ -101,6 +101,22 @@ int w_hasBackgroundMusic(lua_State *L)
 	return 1;
 }
 
+int w_getPreferredLocales(lua_State* L)
+{
+	int i = 1;
+	std::vector<std::string> locales = instance()->getPreferredLocales();
+
+	lua_createtable(L, locales.size(), 0);
+
+	for (const std::string& str: locales)
+	{
+		luax_pushstring(L, str);
+		lua_rawseti(L, -2, i++);
+	}
+
+	return 1;
+}
+
 static const luaL_Reg functions[] =
 {
 	{ "getOS", w_getOS },
@@ -111,6 +127,7 @@ static const luaL_Reg functions[] =
 	{ "openURL", w_openURL },
 	{ "vibrate", w_vibrate },
 	{ "hasBackgroundMusic", w_hasBackgroundMusic },
+	{ "getPreferredLocales", w_getPreferredLocales },
 	{ 0, 0 }
 };