From 430eefbe550253e3307d1ab04f1015d2e2e19d88 Mon Sep 17 00:00:00 2001 From: levovix0 Date: Sat, 4 Dec 2021 23:50:15 +0300 Subject: [PATCH] add: system locale detection --- README.md | 7 +++++++ localize.nimble | 2 +- src/localize.nim | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d07b1b7..088a8b1 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,13 @@ echo tr"Hi, {name}" } ``` +## detecting system language +```nim +var lang = case systemLocale().lang +of "ru": Language.ru +else: Language.en +``` +system locale values bases on linux's LANG env variable ## known issues * recompilation without changing code is not updating translations diff --git a/localize.nimble b/localize.nimble index e6c5906..8a47466 100644 --- a/localize.nimble +++ b/localize.nimble @@ -1,4 +1,4 @@ -version = "0.1.0" +version = "0.2.0" author = "levovix0" description = "Compile time localization for applications" license = "MIT" diff --git a/src/localize.nim b/src/localize.nim index 0d05efb..004eb9f 100644 --- a/src/localize.nim +++ b/src/localize.nim @@ -50,3 +50,45 @@ template initLocalize*(Language: type, langVar) = r{x.file, x.s, x.comment} = newJString f{x.file, x.s, x.comment}.getStr(x.s) writeFile("translations" / ($lang & ".json"), r.pretty) + + +when defined(windows): + const + Chinese = 4 + German = 7 + English = 9 + Spanish = 10 + Japanese = 11 + French = 12 + Italian = 16 + Polish = 21 + Russian = 25 + + # TODO: seems like this method is deprecated + proc GetUserDefaultLangID(): int {.importc, dynlib: "Kernel32.dll".} + + proc systemLocale*: tuple[lang, variant: string] = + let lang = GetUserDefaultLangID() and 0x00FF + case lang + of Chinese: ("zh", "") + of German: ("de", "") + of English: ("en", "") + of Spanish: ("es", "") + of Japanese: ("ja", "") + of French: ("fr", "") + of Italian: ("it", "") + of Polish: ("pl", "") + of Russian: ("ru", "") + else: ("en", "") + +else: + import os, strutils + + proc systemLocale*: tuple[lang, variant: string] = + ## returns system locale + ## parses "en_US.UTF-8" as ("en", "us") + var lang = getEnv("LANG", "en_US.UTF-8") + if lang.endsWith(".UTF-8"): + lang = lang[0..^7] + let l = lang.split("_") + (l[0].toLower, l[1..^1].join("_").toLower)