Skip to content

Commit

Permalink
Use macOS APIs to get preferred localization and keep defaults as fal…
Browse files Browse the repository at this point in the history
…lback
  • Loading branch information
sdassow authored Dec 4, 2024
1 parent 3de5a96 commit 75469e9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
24 changes: 24 additions & 0 deletions locale_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@

package locale

/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Foundation
#include <AppKit/AppKit.h>
const char * preferredLocalization();
const char * preferredLocalizations();
*/
import "C"
import (
"fmt"
"os/exec"
Expand Down Expand Up @@ -32,6 +42,11 @@ func execCommand(cmd string, args ...string) (status int, out string, err error)

// GetLocale retrieves the IETF BCP 47 language tag set on the system.
func GetLocale() (string, error) {
str := C.preferredLocalization()
if output := C.GoString(str); output != "" {
return strings.Replace(output, "_", "-", 1), nil
}

_, output, err := execCommand("defaults", "read", "-g", "AppleLocale")
if err != nil {
return "", fmt.Errorf("cannot determine locale: %v (output: %s)", err, output)
Expand All @@ -53,6 +68,15 @@ var appleLanguagesRegex = regexp.MustCompile(`([a-z]{2}(?:-[A-Z]{2})?)`)

// GetLocales retrieves the IETF BCP 47 language tags set on the system.
func GetLocales() ([]string, error) {
str := C.preferredLocalizations()
if output := C.GoString(str); output != "" {
r := []string{}
for _, s := range strings.Split(output, ",") {
r = append(r, strings.Replace(s, "_", "-", 1))
}
return r, nil
}

_, output, err := execCommand("defaults", "read", "-g", "AppleLanguages")
if err != nil {
return nil, fmt.Errorf("cannot determine locale: %v (output: %s)", err, output)
Expand Down
16 changes: 16 additions & 0 deletions locale_darwin.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//go:build darwin && !ios
// +build darwin,!ios

#import <Foundation/Foundation.h>

const char * preferredLocalization() {
NSString *locale = [[[NSBundle mainBundle] preferredLocalizations] firstObject];

return [locale UTF8String];
}

const char * preferredLocalizations() {
NSString *locales = [[[NSBundle mainBundle] preferredLocalizations] componentsJoinedByString:@","];

return [locales UTF8String];
}

0 comments on commit 75469e9

Please sign in to comment.