1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/addon-sdk/source/lib/sdk/l10n/properties/core.js Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,79 @@ 1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.7 +"use strict"; 1.8 + 1.9 +const { Cu } = require("chrome"); 1.10 +const { newURI } = require('../../url/utils') 1.11 +const { getRulesForLocale } = require("../plural-rules"); 1.12 +const { getPreferedLocales } = require('../locale'); 1.13 +const { rootURI } = require("@loader/options"); 1.14 +const { Services } = Cu.import("resource://gre/modules/Services.jsm", {}); 1.15 + 1.16 +const baseURI = rootURI + "locale/"; 1.17 +const preferedLocales = getPreferedLocales(true); 1.18 + 1.19 +function getLocaleURL(locale) { 1.20 + // if the locale is a valid chrome URI, return it 1.21 + try { 1.22 + let uri = newURI(locale); 1.23 + if (uri.scheme == 'chrome') 1.24 + return uri.spec; 1.25 + } 1.26 + catch(_) {} 1.27 + // otherwise try to construct the url 1.28 + return baseURI + locale + ".properties"; 1.29 +} 1.30 + 1.31 +function getKey(locale, key) { 1.32 + let bundle = Services.strings.createBundle(getLocaleURL(locale)); 1.33 + try { 1.34 + return bundle.GetStringFromName(key) + ""; 1.35 + } 1.36 + catch (_) {} 1.37 + return undefined; 1.38 +} 1.39 + 1.40 +function get(key, n, locales) { 1.41 + // try this locale 1.42 + let locale = locales.shift(); 1.43 + let localized; 1.44 + 1.45 + if (typeof n == 'number') { 1.46 + if (n == 0) { 1.47 + localized = getKey(locale, key + '[zero]'); 1.48 + } 1.49 + else if (n == 1) { 1.50 + localized = getKey(locale, key + '[one]'); 1.51 + } 1.52 + else if (n == 2) { 1.53 + localized = getKey(locale, key + '[two]'); 1.54 + } 1.55 + 1.56 + if (!localized) { 1.57 + // Retrieve the plural mapping function 1.58 + let pluralForm = (getRulesForLocale(locale.split("-")[0].toLowerCase()) || 1.59 + getRulesForLocale("en"))(n); 1.60 + localized = getKey(locale, key + '[' + pluralForm + ']'); 1.61 + } 1.62 + 1.63 + if (!localized) { 1.64 + localized = getKey(locale, key + '[other]'); 1.65 + } 1.66 + } 1.67 + 1.68 + if (!localized) { 1.69 + localized = getKey(locale, key); 1.70 + } 1.71 + 1.72 + if (localized) { 1.73 + return localized; 1.74 + } 1.75 + 1.76 + // try next locale 1.77 + if (locales.length) 1.78 + return get(key, n, locales); 1.79 + 1.80 + return undefined; 1.81 +} 1.82 +exports.get = function(k, n) get(k, n, Array.slice(preferedLocales));