Exemplo n.º 1
0
// Returns true if both of these conditions are true:
//  1. ICU has resources for that locale (which also ensures it's a valid locale string) 
//  2. Either a dictionary for language_country or for language is available.
bool L10n::ValidateLocale(const Locale& locale) const
{
	if (locale.isBogus())
		return false;

	return !GetFallbackToAvailableDictLocale(locale).empty();
}
Exemplo n.º 2
0
Collator* U_EXPORT2 Collator::createInstance(const Locale& desiredLocale,
                                   UErrorCode& status)
{
    if (U_FAILURE(status))
        return 0;
    if (desiredLocale.isBogus()) {
        // Locale constructed from malformed locale ID or language tag.
        status = U_ILLEGAL_ARGUMENT_ERROR;
        return NULL;
    }

    Collator* coll;
#if !UCONFIG_NO_SERVICE
    if (hasService()) {
        Locale actualLoc;
        coll = (Collator*)gService->get(desiredLocale, &actualLoc, status);
    } else
#endif
    {
        coll = makeInstance(desiredLocale, status);
        // Either returns NULL with U_FAILURE(status), or non-NULL with U_SUCCESS(status)
    }
    // The use of *coll in setAttributesFromKeywords can cause the NULL check to be
    // optimized out of the delete even though setAttributesFromKeywords returns
    // immediately if U_FAILURE(status), so we add a check here.
    if (U_FAILURE(status)) {
        return NULL;
    }
    setAttributesFromKeywords(desiredLocale, *coll, status);
    if (U_FAILURE(status)) {
        delete coll;
        return NULL;
    }
    return coll;
}
Exemplo n.º 3
0
Collator* U_EXPORT2 Collator::createInstance(const Locale& desiredLocale,
                                   UErrorCode& status)
{
    if (U_FAILURE(status)) 
        return 0;
    if (desiredLocale.isBogus()) {
        // Locale constructed from malformed locale ID or language tag.
        status = U_ILLEGAL_ARGUMENT_ERROR;
        return NULL;
    }

    Collator* coll;
#if !UCONFIG_NO_SERVICE
    if (hasService()) {
        Locale actualLoc;
        coll = (Collator*)gService->get(desiredLocale, &actualLoc, status);
    } else
#endif
    {
        coll = makeInstance(desiredLocale, status);
    }
    setAttributesFromKeywords(desiredLocale, *coll, status);
    if (U_FAILURE(status)) {
        delete coll;
        return NULL;
    }
    return coll;
}
Exemplo n.º 4
0
/*
Function:
GetCalendars

Returns the list of CalendarIds that are available for the specified locale.
*/
extern "C" int32_t GetCalendars(const UChar* localeName, CalendarId* calendars, int32_t calendarsCapacity)
{
	Locale locale = GetLocale(localeName);
	if (locale.isBogus())
		return 0;

	UErrorCode err = U_ZERO_ERROR;
	LocalPointer<StringEnumeration> stringEnumerator(Calendar::getKeywordValuesForLocale("calendar", locale, TRUE, err));

	if (stringEnumerator.isNull() || U_FAILURE(err))
		return 0;

	int stringEnumeratorCount = stringEnumerator->count(err);
	if (U_FAILURE(err))
		return 0;

	int calendarsReturned = 0;
	for (int i = 0; i < stringEnumeratorCount && calendarsReturned < calendarsCapacity; i++)
	{
		int32_t calendarNameLength = 0;
		const char* calendarName = stringEnumerator->next(&calendarNameLength, err);
		if (U_SUCCESS(err))
		{
			CalendarId calendarId = GetCalendarId(calendarName);
			if (calendarId != UNINITIALIZED_VALUE)
			{
				calendars[calendarsReturned] = calendarId;
				calendarsReturned++;
			}
		}
	}

	return calendarsReturned;
}
Exemplo n.º 5
0
Boolean IndicationFormatter::_canLocalize(
    const ContentLanguages & contentLangs,
    Locale & locale)
{
    PEG_METHOD_ENTER (TRC_IND_FORMATTER,
	"IndicationFormatter::_canLocalize");

    if (!InitializeICU::initICUSuccessful())
    {
	return (false);
    }

    Array<ContentLanguageElement> elements;
    contentLangs.getAllLanguageElements(elements);

    // If the Content-Languages has multiple language tag, do not localize
    if (elements.size() > 1)
    {
        // there is more then one language tags
	PEG_METHOD_EXIT();
	return (false);
    }
    else if (elements.size() == 1)
    {
        // get the locale
        String language = elements[0].getLanguage();
        String country = elements[0].getCountry();
        String variant = elements[0].getVariant();

        locale = Locale((const char *) language.getCString(),
			(const char *) country.getCString(),
			(const char *) variant.getCString());

        // the locale is bogus state
        if (locale.isBogus())
        {
	    PEG_METHOD_EXIT();
	    return (false);
        }
        else
        {
	    PEG_METHOD_EXIT();
	    return (true);
        }
    }
    else
    {
	locale = Locale::getDefault();

        PEG_METHOD_EXIT();
        return (true);
    }

}
Exemplo n.º 6
0
/*
Function:
EnumCalendarInfo

Retrieves a collection of calendar string data specified by the locale, calendar, and data type.
Allows for a collection of calendar string data to be retrieved by invoking
the callback for each value in the collection.
The context parameter is passed through to the callback along with each string.
*/
extern "C" int32_t EnumCalendarInfo(
	EnumCalendarInfoCallback callback,
	const UChar* localeName,
	CalendarId calendarId,
	CalendarDataType dataType,
	const void* context)
{
	Locale locale = GetLocale(localeName);
	if (locale.isBogus())
		return false;

	switch (dataType)
	{
		case ShortDates:
			// ShortDates to map kShort and kMedium in ICU, but also adding the "yMd" skeleton as well, as this
			// closely matches what is used on Windows
			return InvokeCallbackForDateTimePattern(locale, UDAT_YEAR_NUM_MONTH_DAY, callback, context) &&
				InvokeCallbackForDatePattern(locale, DateFormat::kShort, callback, context) &&
				InvokeCallbackForDatePattern(locale, DateFormat::kMedium, callback, context);
		case LongDates:
			// LongDates map to kFull and kLong in ICU.
			return InvokeCallbackForDatePattern(locale, DateFormat::kFull, callback, context) &&
				InvokeCallbackForDatePattern(locale, DateFormat::kLong, callback, context);
		case YearMonths:
			return InvokeCallbackForDateTimePattern(locale, UDAT_YEAR_MONTH, callback, context);
		case DayNames:
			return EnumWeekdays(locale, calendarId, DateFormatSymbols::STANDALONE, DateFormatSymbols::WIDE, callback, context);
		case AbbrevDayNames:
			return EnumWeekdays(locale, calendarId, DateFormatSymbols::STANDALONE, DateFormatSymbols::ABBREVIATED, callback, context);
		case MonthNames:
			return EnumMonths(locale, calendarId, DateFormatSymbols::STANDALONE, DateFormatSymbols::WIDE, callback, context);
		case AbbrevMonthNames:
			return EnumMonths(locale, calendarId, DateFormatSymbols::STANDALONE, DateFormatSymbols::ABBREVIATED, callback, context);
		case SuperShortDayNames:
#ifdef HAVE_DTWIDTHTYPE_SHORT
			return EnumWeekdays(locale, calendarId, DateFormatSymbols::STANDALONE, DateFormatSymbols::SHORT, callback, context);
#else
			// Currently CentOS-7 uses ICU-50 and ::SHORT was added in ICU-51, so use ::NARROW instead
			return EnumWeekdays(locale, calendarId, DateFormatSymbols::STANDALONE, DateFormatSymbols::NARROW, callback, context);
#endif
		case MonthGenitiveNames:
			return EnumMonths(locale, calendarId, DateFormatSymbols::FORMAT, DateFormatSymbols::WIDE, callback, context);
		case AbbrevMonthGenitiveNames:
			return EnumMonths(locale, calendarId, DateFormatSymbols::FORMAT, DateFormatSymbols::ABBREVIATED, callback, context);
		case EraNames:
		case AbbrevEraNames:
			return EnumEraNames(locale, calendarId, dataType, callback, context);
		default:
			assert(false);
			return false;
	}
}
Exemplo n.º 7
0
/* static */ Locale
ICUUtils::BCP47CodeToLocale(const nsAString& aBCP47Code)
{
  MOZ_ASSERT(!aBCP47Code.IsEmpty(), "Don't pass an empty BCP 47 code");

  Locale locale;
  locale.setToBogus();

  // BCP47 codes are guaranteed to be ASCII, so lossy conversion is okay
  NS_LossyConvertUTF16toASCII bcp47code(aBCP47Code);

  UErrorCode status = U_ZERO_ERROR;
  int32_t needed;

  char localeID[256];
  needed = uloc_forLanguageTag(bcp47code.get(), localeID,
                               PR_ARRAY_SIZE(localeID) - 1, nullptr,
                               &status);
  MOZ_ASSERT(needed < int32_t(PR_ARRAY_SIZE(localeID)) - 1,
             "Need a bigger buffer");
  if (needed <= 0 || U_FAILURE(status)) {
    return locale;
  }

  char lang[64];
  needed = uloc_getLanguage(localeID, lang, PR_ARRAY_SIZE(lang) - 1,
                            &status);
  MOZ_ASSERT(needed < int32_t(PR_ARRAY_SIZE(lang)) - 1,
             "Need a bigger buffer");
  if (needed <= 0 || U_FAILURE(status)) {
    return locale;
  }

  char country[64];
  needed = uloc_getCountry(localeID, country, PR_ARRAY_SIZE(country) - 1,
                           &status);
  MOZ_ASSERT(needed < int32_t(PR_ARRAY_SIZE(country)) - 1,
             "Need a bigger buffer");
  if (needed > 0 && U_SUCCESS(status)) {
    locale = Locale(lang, country);
  }

  if (locale.isBogus()) {
    // Using the country resulted in a bogus Locale, so try with only the lang
    locale = Locale(lang);
  }

  return locale;
}
status_t
LocaleRosterData::_SetDefaultFormattingConventions(
	const BFormattingConventions& newFormattingConventions)
{
	fDefaultLocale.SetFormattingConventions(newFormattingConventions);

	UErrorCode icuError = U_ZERO_ERROR;
	Locale icuLocale = Locale::createCanonical(newFormattingConventions.ID());
	if (icuLocale.isBogus())
		return B_ERROR;

	Locale::setDefault(icuLocale, icuError);
	if (!U_SUCCESS(icuError))
		return B_ERROR;

	return B_OK;
}
Exemplo n.º 9
0
/*
Function:
GetCalendarInfo

Gets a single string of calendar information by filling the result parameter with the requested value.
*/
extern "C" CalendarDataResult GetCalendarInfo(const UChar* localeName, CalendarId calendarId, CalendarDataType dataType, UChar* result, int32_t resultCapacity)
{
	Locale locale = GetLocale(localeName);
	if (locale.isBogus())
		return UnknownError;

	switch (dataType)
	{
		case NativeName:
			return GetNativeCalendarName(locale, calendarId, result, resultCapacity);
		case MonthDay:
			return GetMonthDayPattern(locale, result, resultCapacity);
		default:
			assert(false);
			return UnknownError;
	}
}
Exemplo n.º 10
0
extern "C" int32_t GetLocaleName(const UChar* localeName, UChar* value, int32_t valueLength)
{
	Locale locale = GetLocale(localeName, true);

	if (locale.isBogus())
	{
		// localeName not properly formatted
		return UErrorCodeToBool(U_ILLEGAL_ARGUMENT_ERROR);
	}

	// other validation done on managed side

	UErrorCode status = u_charsToUChars_safe(locale.getName(), value, valueLength);
	if (U_SUCCESS(status))
	{
		FixupLocaleName(value, valueLength);
	}

	return UErrorCodeToBool(status);
}
Exemplo n.º 11
0
UnicodeString&
LocaleDisplayNamesImpl::localeDisplayName(const Locale& locale,
                                          UnicodeString& result) const {
  if (locale.isBogus()) {
    result.setToBogus();
    return result;
  }
  UnicodeString resultName;

  const char* lang = locale.getLanguage();
  if (uprv_strlen(lang) == 0) {
    lang = "root";
  }
  const char* script = locale.getScript();
  const char* country = locale.getCountry();
  const char* variant = locale.getVariant();

  UBool hasScript = uprv_strlen(script) > 0;
  UBool hasCountry = uprv_strlen(country) > 0;
  UBool hasVariant = uprv_strlen(variant) > 0;

  if (dialectHandling == ULDN_DIALECT_NAMES) {
    char buffer[ULOC_FULLNAME_CAPACITY];
    do { // loop construct is so we can break early out of search
      if (hasScript && hasCountry) {
        ncat(buffer, ULOC_FULLNAME_CAPACITY, lang, "_", script, "_", country, (char *)0);
        localeIdName(buffer, resultName);
        if (!resultName.isBogus()) {
          hasScript = FALSE;
          hasCountry = FALSE;
          break;
        }
      }
      if (hasScript) {
        ncat(buffer, ULOC_FULLNAME_CAPACITY, lang, "_", script, (char *)0);
        localeIdName(buffer, resultName);
        if (!resultName.isBogus()) {
          hasScript = FALSE;
          break;
        }
      }
      if (hasCountry) {
        ncat(buffer, ULOC_FULLNAME_CAPACITY, lang, "_", country, (char*)0);
        localeIdName(buffer, resultName);
        if (!resultName.isBogus()) {
          hasCountry = FALSE;
          break;
        }
      }
    } while (FALSE);
  }
  if (resultName.isBogus() || resultName.isEmpty()) {
    localeIdName(lang, resultName);
  }

  UnicodeString resultRemainder;
  UnicodeString temp;
  UErrorCode status = U_ZERO_ERROR;

  if (hasScript) {
    resultRemainder.append(scriptDisplayName(script, temp, TRUE));
  }
  if (hasCountry) {
    appendWithSep(resultRemainder, regionDisplayName(country, temp, TRUE));
  }
  if (hasVariant) {
    appendWithSep(resultRemainder, variantDisplayName(variant, temp, TRUE));
  }
  resultRemainder.findAndReplace(formatOpenParen, formatReplaceOpenParen);
  resultRemainder.findAndReplace(formatCloseParen, formatReplaceCloseParen);

  LocalPointer<StringEnumeration> e(locale.createKeywords(status));
  if (e.isValid() && U_SUCCESS(status)) {
    UnicodeString temp2;
    char value[ULOC_KEYWORD_AND_VALUES_CAPACITY]; // sigh, no ULOC_VALUE_CAPACITY
    const char* key;
    while ((key = e->next((int32_t *)0, status)) != NULL) {
      locale.getKeywordValue(key, value, ULOC_KEYWORD_AND_VALUES_CAPACITY, status);
      if (U_FAILURE(status)) {
        return result;
      }
      keyDisplayName(key, temp, TRUE);
      temp.findAndReplace(formatOpenParen, formatReplaceOpenParen);
      temp.findAndReplace(formatCloseParen, formatReplaceCloseParen);
      keyValueDisplayName(key, value, temp2, TRUE);
      temp2.findAndReplace(formatOpenParen, formatReplaceOpenParen);
      temp2.findAndReplace(formatCloseParen, formatReplaceCloseParen);
      if (temp2 != UnicodeString(value, -1, US_INV)) {
        appendWithSep(resultRemainder, temp2);
      } else if (temp != UnicodeString(key, -1, US_INV)) {
        UnicodeString temp3;
        keyTypeFormat.format(temp, temp2, temp3, status);
        appendWithSep(resultRemainder, temp3);
      } else {
        appendWithSep(resultRemainder, temp)
          .append((UChar)0x3d /* = */)
          .append(temp2);
      }
    }
  }

  if (!resultRemainder.isEmpty()) {
    format.format(resultName, resultRemainder, result.remove(), status);
    return adjustForUsageAndContext(kCapContextUsageLanguage, result);
  }

  result = resultName;
  return adjustForUsageAndContext(kCapContextUsageLanguage, result);
}
void NUMBER_Format(sLONG_PTR *pResult, PackagePtr pParams)
{
	C_REAL Param1;
	C_TEXT Param2;
	C_LONGINT Param3;
	C_TEXT Param4;
	C_TEXT Param5;
	C_LONGINT returnValue;
	
	Param1.fromParamAtIndex(pParams, 1);
	Param3.fromParamAtIndex(pParams, 3);
	Param4.fromParamAtIndex(pParams, 4);
	Param5.fromParamAtIndex(pParams, 5);
	
	// --- write the code of NUMBER_Format here...
	
	UErrorCode	status = U_ZERO_ERROR;
	UParseError	perror;
	
	Locale locale;
	
	if(Param4.getUTF16Length()){
		
		CUTF8String u;
		Param4.copyUTF8String(&u);
		
		Locale inLocale = Locale((const char *)u.c_str());
		
		if(!inLocale.isBogus()){
			locale = Locale(inLocale);
		}else{
			status = U_ILLEGAL_ARGUMENT_ERROR;
		}
		
	}
	
	if(status == U_ZERO_ERROR){
		
		int mode = Param3.getIntValue();
		
		if(mode == NUMBER_FORMAT_CUSTOM){
			
			if(Param5.getUTF16Length()){
				
				UnicodeString rules = UnicodeString((const UChar *)Param5.getUTF16StringPtr());
				RuleBasedNumberFormat fmt = RuleBasedNumberFormat(rules, locale, perror, status);
				
				if(status == U_ZERO_ERROR || status == U_USING_DEFAULT_WARNING || status == U_USING_FALLBACK_WARNING){
					
					UnicodeString numberString;
					fmt.format(Param1.getDoubleValue(), numberString);
					DT::setUnicodeString(Param2, numberString);
					status = U_ZERO_ERROR;
					
				}
				
			}else{
				status = U_ILLEGAL_ARGUMENT_ERROR;
			}
			
		}else{
			
			switch (mode) {
				case NUMBER_FORMAT_SPELLOUT:
				case NUMBER_FORMAT_ORDINAL:
				case NUMBER_FORMAT_DURATION:
				case NUMBER_FORMAT_NUMBERING_SYSTEM:
				case NUMBER_FORMAT_COUNT:
				{
					RuleBasedNumberFormat fmt = RuleBasedNumberFormat((URBNFRuleSetTag)mode, locale, status);
					
					if(status == U_ZERO_ERROR || status == U_USING_DEFAULT_WARNING || status == U_USING_FALLBACK_WARNING){
						
						UnicodeString numberString;
						fmt.format(Param1.getDoubleValue(), numberString);
						DT::setUnicodeString(Param2, numberString);
						status = U_ZERO_ERROR;
						
					}
					
				}
					break;
					
				default:
					status = U_ILLEGAL_ARGUMENT_ERROR;
					break;
			}
			
		}
		
	}
	
	Param2.toParamAtIndex(pParams, 2);
	
	returnValue.setIntValue(status);
	returnValue.setReturn(pResult);
}