summaryrefslogtreecommitdiffstats
path: root/server/src/locale.cpp
blob: 92bc33b08b0e59d678885359cdf6a758c477d10e (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
module;

#include <boost/locale.hpp>
#include <unicode/localematcher.h>

module routemon:locale$impl;

import :locale;

namespace routemon::locale {

struct locale_priority
{
  float weight;
  std::size_t original_index;
};

auto operator<(locale_priority const& lhs, locale_priority const& rhs) -> bool
{
  if (lhs.weight != rhs.weight)
    return lhs.weight > rhs.weight;
  return lhs.original_index < rhs.original_index;
}

struct icu_locale_hash
{
  std::size_t operator()(icu::Locale const& l) const noexcept
  {
    static_assert(sizeof(std::int32_t) < sizeof(std::size_t));
    std::int32_t hash = l.hashCode();
    if (hash < 0)
    {
      return static_cast<std::size_t>(std::numeric_limits<int>::max())
             + static_cast<std::size_t>(-hash) + 1;
    }
    else
    {
      return static_cast<std::size_t>(hash);
    }
  }
};

using icu_locale_priority_map =
    std::unordered_map<icu::Locale, locale_priority, icu_locale_hash>;
using icu_priority_locale = std::pair<icu::Locale, locale_priority>;

auto operator<(icu_priority_locale const& lhs, icu_priority_locale const& rhs)
    -> bool
{
  return lhs.second < rhs.second;
}

class icu_priority_locale_vec_iterator : public icu::Locale::Iterator
{
  std::size_t i_ = 0uz;
  std::vector<icu_priority_locale> ls_;

public:
  explicit icu_priority_locale_vec_iterator(
      std::vector<icu_priority_locale>&& ls)
    : ls_(std::move(ls))
  {
  }

  auto hasNext() const -> UBool override { return i_ < ls_.size(); }

  auto next() -> icu::Locale const& override { return ls_[i_++].first; }

  ~icu_priority_locale_vec_iterator() override = default;
};

auto to_bcp47_lang_tag(std::locale locale) -> std::optional<std::string>
{
  auto const& locale_info = std::use_facet<blocale::info>(locale);
  auto ec = UErrorCode::U_ZERO_ERROR;
  auto bcp47_lang_tag =
      icu::Locale{locale_info.name().c_str()}.toLanguageTag<std::string>(ec);
  if (U_FAILURE(ec))
    return std::nullopt;
  return bcp47_lang_tag;
}

auto bcp47_tag::id = std::locale::id{};

bcp47_tag::bcp47_tag(std::locale locale)
{
  auto mtag = to_bcp47_lang_tag(locale);
  if (!mtag)
    throw std::invalid_argument{
      "locale name cannot be expressed as a BCP 47 language tag"
    };
  tag_ = *mtag;
}

auto bcp47_tag::tag() const -> std::string_view { return tag_; }

auto selector::make_matcher(std::vector<std::locale> const& supported_locales)
    -> icu::LocaleMatcher
{
  auto builder = icu::LocaleMatcher::Builder{};
  for (auto const& supported_locale : supported_locales)
  {
    auto const& supported_locale_info =
        std::use_facet<blocale::info>(supported_locale);
    auto supported_icu_locale =
        icu::Locale{supported_locale_info.name().c_str()};
    if (supported_icu_locale.isBogus())
      throw std::runtime_error{
        "supported locale gives rise to bogus ICU locale"
      };
    builder.addSupportedLocale(supported_icu_locale);
  }
  builder.setNoDefaultLocale();
  auto ec = UErrorCode::U_ZERO_ERROR;
  auto matcher = builder.build(ec);
  if (U_FAILURE(ec))
    throw std::runtime_error{"failed to build icu::LocaleMatcher"};
  return matcher;
}

// Trimming optional whitespace as defined in RFC 9110, § 12.4.2.
auto selector::ltrim_ows(std::string_view s) -> std::string_view
{
  if (auto i = s.find_first_not_of(" \t"); i != std::string_view::npos)
    s.remove_prefix(i);
  return s;
}
auto selector::rtrim_ows(std::string_view s) -> std::string_view
{
  if (auto i = s.find_last_not_of(" \t"); i != std::string_view::npos)
    return s.substr(0, i + 1);
  return s;
}
auto selector::trim_ows(std::string_view s) -> std::string_view
{
  return rtrim_ows(ltrim_ows(s));
}

auto selector::select(std::string_view accept_language) const -> std::locale
{
  using namespace std::literals::string_view_literals;
  // NOTE: can also contain a *;q=0.1
  // q should have at most 3 digits after period
  auto dlpm = icu_locale_priority_map{};
  for (auto const [i, lang_prio] :
       accept_language | std::views::split(","sv) | std::views::enumerate)
  {
    auto [lang_range_ut, mweight_ut] =
        util::split_on(std::string_view{lang_prio}, ';');
    auto lang_range_str = trim_ows(lang_range_ut);
    auto mweight_str = mweight_ut.transform(trim_ows);
    if (lang_range_str == "*")
      break;

    auto ec = UErrorCode::U_ZERO_ERROR;
    auto icu_locale = icu::Locale::forLanguageTag(lang_range_str, ec);
    if (U_FAILURE(ec) || icu_locale.isBogus())
      continue; // ignore this locale

    auto weight = 1.0f;
    if (mweight_str && mweight_str->starts_with("q="))
    {
      auto weight_str = mweight_str->substr(2, 4);
      if (auto mweight =
              util::parse_float(weight_str, std::chars_format::fixed);
          mweight && 0.0f < *mweight && *mweight < 1.0f)
      {
        weight = *mweight;
      }
    }

    if (weight > 0.0f)
    {
      dlpm[icu_locale] = {
        .weight = weight,
        .original_index = static_cast<std::size_t>(i),
      };
    }
    else
    {
      dlpm.erase(icu_locale);
    }
  }

  auto desired_locales =
      std::vector<icu_priority_locale>{dlpm.begin(), dlpm.end()};
  std::sort(desired_locales.begin(), desired_locales.end());
  auto it = icu_priority_locale_vec_iterator{std::move(desired_locales)};
  auto ec = UErrorCode::U_ZERO_ERROR;
  auto res = matcher_.getBestMatchResult(it, ec);
  if (U_FAILURE(ec))
    return default_;
  auto i = res.getSupportedIndex();
  if (i == -1)
    return default_;
  return supported_[util::size_from_int(i).value()];
}

#ifdef LOCALEDIR
#define LOCALEDIR_AUX_XSTR(s) LOCALEDIR_AUX_STR(s)
#define LOCALEDIR_AUX_STR(s) #s
constexpr auto messages_path = std::string_view{LOCALEDIR_AUX_XSTR(LOCALEDIR)};
#undef LOCALEDIR_AUX_STR
#undef LOCALEDIR_AUX_XSTR
#else  // ifdef LOCALEDIR
constexpr auto messages_path = std::string_view{"locale/dev"};
#endif // ifdef LOCALEDIR

export auto make_generator() -> std::shared_ptr<blocale::generator const>
{
  auto lgen = std::make_shared<blocale::generator>();
  lgen->add_messages_path(std::string{messages_path});
  lgen->add_messages_domain("routemon");
  return std::static_pointer_cast<blocale::generator const>(lgen);
}

} // namespace routemon::locale