1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "nsLanguageAtomService.h"
7 #include "nsILocaleService.h"
8 #include "nsUnicharUtils.h"
10 #include "mozilla/Services.h"
11 #include "nsServiceManagerUtils.h"
12 #include "mozilla/dom/EncodingUtils.h"
14 NS_IMPL_ISUPPORTS(nsLanguageAtomService
, nsILanguageAtomService
)
16 nsLanguageAtomService::nsLanguageAtomService()
21 nsLanguageAtomService::InitLangGroupTable()
26 nsCOMPtr
<nsIStringBundleService
> bundleService
=
27 mozilla::services::GetStringBundleService();
29 return NS_ERROR_FAILURE
;
31 return bundleService
->CreateBundle("resource://gre/res/langGroups.properties",
32 getter_AddRefs(mLangGroups
));
36 nsLanguageAtomService::LookupLanguage(const nsACString
&aLanguage
,
39 nsAutoCString
lowered(aLanguage
);
42 nsCOMPtr
<nsIAtom
> lang
= do_GetAtom(lowered
);
43 return GetLanguageGroup(lang
, aError
);
46 already_AddRefed
<nsIAtom
>
47 nsLanguageAtomService::LookupCharSet(const nsACString
& aCharSet
)
50 mozilla::dom::EncodingUtils::LangGroupForEncoding(aCharSet
, group
);
51 return do_GetAtom(group
);
55 nsLanguageAtomService::GetLocaleLanguage(nsresult
*aError
)
60 if (!mLocaleLanguage
) {
61 nsCOMPtr
<nsILocaleService
> localeService
;
62 localeService
= do_GetService(NS_LOCALESERVICE_CONTRACTID
);
64 res
= NS_ERROR_FAILURE
;
68 nsCOMPtr
<nsILocale
> locale
;
69 res
= localeService
->GetApplicationLocale(getter_AddRefs(locale
));
74 res
= locale
->GetCategory(NS_LITERAL_STRING(NSILOCALE_MESSAGE
), loc
);
78 ToLowerCase(loc
); // use lowercase for all language atoms
79 mLocaleLanguage
= do_GetAtom(loc
);
86 return mLocaleLanguage
;
90 nsLanguageAtomService::GetLanguageGroup(nsIAtom
*aLanguage
,
96 retVal
= mLangToGroup
.GetWeak(aLanguage
);
100 if (NS_FAILED(InitLangGroupTable())) {
102 *aError
= NS_ERROR_FAILURE
;
109 aLanguage
->ToString(langStr
);
111 nsXPIDLString langGroupStr
;
112 res
= mLangGroups
->GetStringFromName(langStr
.get(),
113 getter_Copies(langGroupStr
));
114 if (NS_FAILED(res
)) {
115 int32_t hyphen
= langStr
.FindChar('-');
117 nsAutoString
truncated(langStr
);
118 truncated
.Truncate(hyphen
);
119 res
= mLangGroups
->GetStringFromName(truncated
.get(),
120 getter_Copies(langGroupStr
));
121 if (NS_FAILED(res
)) {
122 langGroupStr
.AssignLiteral("x-unicode");
125 langGroupStr
.AssignLiteral("x-unicode");
129 nsCOMPtr
<nsIAtom
> langGroup
= do_GetAtom(langGroupStr
);
131 // The hashtable will keep an owning reference to the atom
132 mLangToGroup
.Put(aLanguage
, langGroup
);
133 retVal
= langGroup
.get();