1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "ui/base/l10n/l10n_util_plurals.h"
6
7#include "base/logging.h"
8#include "base/memory/scoped_ptr.h"
9#include "ui/base/l10n/l10n_util.h"
10
11namespace l10n_util {
12
13scoped_ptr<icu::PluralRules> BuildPluralRules() {
14  UErrorCode err = U_ZERO_ERROR;
15  scoped_ptr<icu::PluralRules> rules(
16      icu::PluralRules::forLocale(icu::Locale::getDefault(), err));
17  if (U_FAILURE(err)) {
18    err = U_ZERO_ERROR;
19    icu::UnicodeString fallback_rules("one: n is 1", -1, US_INV);
20    rules.reset(icu::PluralRules::createRules(fallback_rules, err));
21    DCHECK(U_SUCCESS(err));
22  }
23  return rules.Pass();
24}
25
26scoped_ptr<icu::PluralFormat> BuildPluralFormat(
27    const std::vector<int>& message_ids) {
28  const icu::UnicodeString kKeywords[] = {
29      UNICODE_STRING_SIMPLE("other"),
30      UNICODE_STRING_SIMPLE("one"),
31      UNICODE_STRING_SIMPLE("zero"),
32      UNICODE_STRING_SIMPLE("two"),
33      UNICODE_STRING_SIMPLE("few"),
34      UNICODE_STRING_SIMPLE("many"),
35  };
36  DCHECK_EQ(message_ids.size(), arraysize(kKeywords));
37  UErrorCode err = U_ZERO_ERROR;
38  scoped_ptr<icu::PluralRules> rules(BuildPluralRules());
39
40  icu::UnicodeString pattern;
41  for (size_t i = 0; i < arraysize(kKeywords); ++i) {
42    int msg_id = message_ids[i];
43    std::string sub_pattern = GetStringUTF8(msg_id);
44    // NA means this keyword is not used in the current locale.
45    // Even if a translator translated for this keyword, we do not
46    // use it unless it's 'other' (i=0) or it's defined in the rules
47    // for the current locale. Special-casing of 'other' will be removed
48    // once ICU's isKeyword is fixed to return true for isKeyword('other').
49    if (sub_pattern.compare("NA") != 0 &&
50        (i == 0 || rules->isKeyword(kKeywords[i]))) {
51      pattern += kKeywords[i];
52      pattern += UNICODE_STRING_SIMPLE("{");
53      pattern += icu::UnicodeString(sub_pattern.c_str(), "UTF-8");
54      pattern += UNICODE_STRING_SIMPLE("}");
55    }
56  }
57  scoped_ptr<icu::PluralFormat> format = scoped_ptr<icu::PluralFormat>(
58      new icu::PluralFormat(*rules, pattern, err));
59  if (!U_SUCCESS(err)) {
60    return scoped_ptr<icu::PluralFormat>();
61  }
62  return format.Pass();
63}
64
65}  // namespace l10n_util
66