Skip to content

Commit

Permalink
add: system locale detection
Browse files Browse the repository at this point in the history
  • Loading branch information
levovix0 committed Dec 4, 2021
1 parent 87749d9 commit 430eefb
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion localize.nimble
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version = "0.1.0"
version = "0.2.0"
author = "levovix0"
description = "Compile time localization for applications"
license = "MIT"
Expand Down
42 changes: 42 additions & 0 deletions src/localize.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 430eefb

Please sign in to comment.