Skip to content

Commit 428af89

Browse files
authored
Fix resources regionCode crash before macOS 14; Use first of preferred locales instead of current (#5180)
`NSLocale.regionCode` is only available on macOS 14 and higher. This PR changes the code so it works on older versions, similar to #4473 but for macOS instead of iOS https://developer.apple.com/documentation/foundation/nslocale/4172868-regioncode?language=objc In addition to the fix explained above, I also applied the another fix as on iOS here: #4507. I tested it with these settings: ![Screenshot 2024-12-09 at 21 27 11](https://github.com/user-attachments/assets/4673ff41-1c0e-46dc-9292-ab8da57b6e53) Resulting in: ``` println(NSLocale.currentLocale().localeIdentifier) -> en_NL println(NSLocale.preferredLanguages().first().let { NSLocale(it as String) }.localeIdentifier) -> en-GB ``` In this case I think `preferredLanguages` is the better option as compose is interested in the actual set language, which is English (UK). Note that there are still some additional issues explained in detail here: https://youtrack.jetbrains.com/issue/CMP-6614/iOS-Localization-strings-for-language-qualifiers-that-are-not-the-same-between-platforms-appear-not-translated For this PR, I decided to just match the iOS behaviour for now, so at least it is consistent. In the future I guess some locale mapping is required (see my comment in YouTrack)
1 parent 5870305 commit 428af89

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

components/resources/library/src/macosMain/kotlin/org/jetbrains/compose/resources/ResourceEnvironment.macos.kt

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,12 @@ import platform.CoreGraphics.CGDisplayScreenSize
77
import platform.Foundation.*
88

99
internal actual fun getSystemEnvironment(): ResourceEnvironment {
10-
val locale = NSLocale.currentLocale()
10+
val locale = NSLocale.preferredLanguages.firstOrNull()
11+
?.let { NSLocale(it as String) }
12+
?: NSLocale.currentLocale
13+
14+
val languageCode = locale.languageCode
15+
val regionCode = locale.objectForKey(NSLocaleCountryCode) as? String
1116
val isDarkTheme = NSUserDefaults.standardUserDefaults.stringForKey("AppleInterfaceStyle") == "Dark"
1217

1318
val dpi = NSScreen.mainScreen?.let { screen ->
@@ -24,8 +29,8 @@ internal actual fun getSystemEnvironment(): ResourceEnvironment {
2429
} ?: 0
2530

2631
return ResourceEnvironment(
27-
language = LanguageQualifier(locale.languageCode),
28-
region = RegionQualifier(locale.regionCode.orEmpty()),
32+
language = LanguageQualifier(languageCode),
33+
region = RegionQualifier(regionCode.orEmpty()),
2934
theme = ThemeQualifier.selectByValue(isDarkTheme),
3035
density = DensityQualifier.selectByValue(dpi)
3136
)

0 commit comments

Comments
 (0)