michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: "use strict"; michael@0: michael@0: const { Cu } = require("chrome"); michael@0: const { newURI } = require('../../url/utils') michael@0: const { getRulesForLocale } = require("../plural-rules"); michael@0: const { getPreferedLocales } = require('../locale'); michael@0: const { rootURI } = require("@loader/options"); michael@0: const { Services } = Cu.import("resource://gre/modules/Services.jsm", {}); michael@0: michael@0: const baseURI = rootURI + "locale/"; michael@0: const preferedLocales = getPreferedLocales(true); michael@0: michael@0: function getLocaleURL(locale) { michael@0: // if the locale is a valid chrome URI, return it michael@0: try { michael@0: let uri = newURI(locale); michael@0: if (uri.scheme == 'chrome') michael@0: return uri.spec; michael@0: } michael@0: catch(_) {} michael@0: // otherwise try to construct the url michael@0: return baseURI + locale + ".properties"; michael@0: } michael@0: michael@0: function getKey(locale, key) { michael@0: let bundle = Services.strings.createBundle(getLocaleURL(locale)); michael@0: try { michael@0: return bundle.GetStringFromName(key) + ""; michael@0: } michael@0: catch (_) {} michael@0: return undefined; michael@0: } michael@0: michael@0: function get(key, n, locales) { michael@0: // try this locale michael@0: let locale = locales.shift(); michael@0: let localized; michael@0: michael@0: if (typeof n == 'number') { michael@0: if (n == 0) { michael@0: localized = getKey(locale, key + '[zero]'); michael@0: } michael@0: else if (n == 1) { michael@0: localized = getKey(locale, key + '[one]'); michael@0: } michael@0: else if (n == 2) { michael@0: localized = getKey(locale, key + '[two]'); michael@0: } michael@0: michael@0: if (!localized) { michael@0: // Retrieve the plural mapping function michael@0: let pluralForm = (getRulesForLocale(locale.split("-")[0].toLowerCase()) || michael@0: getRulesForLocale("en"))(n); michael@0: localized = getKey(locale, key + '[' + pluralForm + ']'); michael@0: } michael@0: michael@0: if (!localized) { michael@0: localized = getKey(locale, key + '[other]'); michael@0: } michael@0: } michael@0: michael@0: if (!localized) { michael@0: localized = getKey(locale, key); michael@0: } michael@0: michael@0: if (localized) { michael@0: return localized; michael@0: } michael@0: michael@0: // try next locale michael@0: if (locales.length) michael@0: return get(key, n, locales); michael@0: michael@0: return undefined; michael@0: } michael@0: exports.get = function(k, n) get(k, n, Array.slice(preferedLocales));