DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (2b8364cfdb04)

VCS Links

Line Code
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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * This is a shared part of the OSPreferences API implementation.
 * It defines helper methods and public methods that are calling
 * platform-specific private methods.
 */

#include "OSPreferences.h"

#include "mozilla/ClearOnShutdown.h"
#include "mozilla/Services.h"
#include "nsIObserverService.h"
#include "unicode/udat.h"
#include "unicode/udatpg.h"

using namespace mozilla::intl;

NS_IMPL_ISUPPORTS(OSPreferences, mozIOSPreferences)

mozilla::StaticRefPtr<OSPreferences> OSPreferences::sInstance;

OSPreferences* OSPreferences::GetInstance() {
  if (!sInstance) {
    sInstance = new OSPreferences();
    ClearOnShutdown(&sInstance);
  }
  return sInstance;
}

void OSPreferences::Refresh() {
  nsTArray<nsCString> newLocales;
  ReadSystemLocales(newLocales);

  if (mSystemLocales != newLocales) {
    mSystemLocales = std::move(newLocales);
    nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
    if (obs) {
      obs->NotifyObservers(nullptr, "intl:system-locales-changed", nullptr);
    }
  }
}

/**
 * This method should be called by every method of OSPreferences that
 * retrieves a locale id from external source.
 *
 * It attempts to retrieve as much of the locale ID as possible, cutting
 * out bits that are not understood (non-strict behavior of ICU).
 *
 * It returns true if the canonicalization was successful.
 */
bool OSPreferences::CanonicalizeLanguageTag(nsCString& aLoc) {
  char langTag[512];

  UErrorCode status = U_ZERO_ERROR;

  int32_t langTagLen = uloc_toLanguageTag(aLoc.get(), langTag,
                                          sizeof(langTag) - 1, false, &status);

  if (U_FAILURE(status)) {
    return false;
  }

  aLoc.Assign(langTag, langTagLen);
  return true;
}

/**
 * This method retrieves from ICU the best pattern for a given date/time style.
 */
bool OSPreferences::GetDateTimePatternForStyle(DateTimeFormatStyle aDateStyle,
                                               DateTimeFormatStyle aTimeStyle,
                                               const nsACString& aLocale,
                                               nsAString& aRetVal) {
  UDateFormatStyle timeStyle = UDAT_NONE;
  UDateFormatStyle dateStyle = UDAT_NONE;

  switch (aTimeStyle) {
    case DateTimeFormatStyle::None:
      timeStyle = UDAT_NONE;
      break;
    case DateTimeFormatStyle::Short:
      timeStyle = UDAT_SHORT;
      break;
    case DateTimeFormatStyle::Medium:
      timeStyle = UDAT_MEDIUM;
      break;
    case DateTimeFormatStyle::Long:
      timeStyle = UDAT_LONG;
      break;
    case DateTimeFormatStyle::Full:
      timeStyle = UDAT_FULL;
      break;
    case DateTimeFormatStyle::Invalid:
      timeStyle = UDAT_NONE;
      break;
  }

  switch (aDateStyle) {
    case DateTimeFormatStyle::None:
      dateStyle = UDAT_NONE;
      break;
    case DateTimeFormatStyle::Short:
      dateStyle = UDAT_SHORT;
      break;
    case DateTimeFormatStyle::Medium:
      dateStyle = UDAT_MEDIUM;
      break;
    case DateTimeFormatStyle::Long:
      dateStyle = UDAT_LONG;
      break;
    case DateTimeFormatStyle::Full:
      dateStyle = UDAT_FULL;
      break;
    case DateTimeFormatStyle::Invalid:
      dateStyle = UDAT_NONE;
      break;
  }

  const int32_t kPatternMax = 160;
  UChar pattern[kPatternMax];

  nsAutoCString locale;
  if (aLocale.IsEmpty()) {
    AutoTArray<nsCString, 10> regionalPrefsLocales;
    LocaleService::GetInstance()->GetRegionalPrefsLocales(regionalPrefsLocales);
    locale.Assign(regionalPrefsLocales[0]);
  } else {
    locale.Assign(aLocale);
  }

  UErrorCode status = U_ZERO_ERROR;
  UDateFormat* df = udat_open(timeStyle, dateStyle, locale.get(), nullptr, -1,
                              nullptr, -1, &status);
  if (U_FAILURE(status)) {
    return false;
  }

  int32_t patsize = udat_toPattern(df, false, pattern, kPatternMax, &status);
  udat_close(df);
  if (U_FAILURE(status)) {
    return false;
  }
  aRetVal.Assign((const char16_t*)pattern, patsize);
  return true;
}

/**
 * This method retrieves from ICU the best skeleton for a given date/time style.
 *
 * This is useful for cases where an OS does not provide its own patterns,
 * but provide ability to customize the skeleton, like alter hourCycle setting.
 *
 * The returned value is a skeleton that matches the styles.
 */
bool OSPreferences::GetDateTimeSkeletonForStyle(DateTimeFormatStyle aDateStyle,
                                                DateTimeFormatStyle aTimeStyle,
                                                const nsACString& aLocale,
                                                nsAString& aRetVal) {
  nsAutoString pattern;
  if (!GetDateTimePatternForStyle(aDateStyle, aTimeStyle, aLocale, pattern)) {
    return false;
  }

  const int32_t kSkeletonMax = 160;
  UChar skeleton[kSkeletonMax];

  UErrorCode status = U_ZERO_ERROR;
  int32_t skelsize =
      udatpg_getSkeleton(nullptr, (const UChar*)pattern.BeginReading(),
                         pattern.Length(), skeleton, kSkeletonMax, &status);
  if (U_FAILURE(status)) {
    return false;
  }

  aRetVal.Assign((const char16_t*)skeleton, skelsize);
  return true;
}

/**
 * This function is a counterpart to GetDateTimeSkeletonForStyle.
 *
 * It takes a skeleton and returns the best available pattern for a given locale
 * that represents the provided skeleton.
 *
 * For example:
 * "Hm" skeleton for "en-US" will return "H:m"
 */
bool OSPreferences::GetPatternForSkeleton(const nsAString& aSkeleton,
                                          const nsACString& aLocale,
                                          nsAString& aRetVal) {
  UErrorCode status = U_ZERO_ERROR;
  UDateTimePatternGenerator* pg =
      udatpg_open(PromiseFlatCString(aLocale).get(), &status);
  if (U_FAILURE(status)) {
    return false;
  }

  int32_t len =
      udatpg_getBestPattern(pg, (const UChar*)aSkeleton.BeginReading(),
                            aSkeleton.Length(), nullptr, 0, &status);
  if (status == U_BUFFER_OVERFLOW_ERROR) {  // expected
    aRetVal.SetLength(len);
    status = U_ZERO_ERROR;
    udatpg_getBestPattern(pg, (const UChar*)aSkeleton.BeginReading(),
                          aSkeleton.Length(), (UChar*)aRetVal.BeginWriting(),
                          len, &status);
  }

  udatpg_close(pg);

  return U_SUCCESS(status);
}

/**
 * This function returns a pattern that should be used to join date and time
 * patterns into a single date/time pattern string.
 *
 * It's useful for OSes that do not provide an API to retrieve such combined
 * pattern.
 *
 * An example output is "{1}, {0}".
 */
bool OSPreferences::GetDateTimeConnectorPattern(const nsACString& aLocale,
                                                nsAString& aRetVal) {
  bool result = false;
  UErrorCode status = U_ZERO_ERROR;
  UDateTimePatternGenerator* pg =
      udatpg_open(PromiseFlatCString(aLocale).get(), &status);
  if (U_SUCCESS(status)) {
    int32_t resultSize;
    const UChar* value = udatpg_getDateTimeFormat(pg, &resultSize);
    MOZ_ASSERT(resultSize >= 0);

    aRetVal.Assign((char16_t*)value, resultSize);
    result = true;
  }
  udatpg_close(pg);
  return result;
}

/**
 * mozIOSPreferences methods
 */
NS_IMETHODIMP
OSPreferences::GetSystemLocales(nsTArray<nsCString>& aRetVal) {
  if (!mSystemLocales.IsEmpty()) {
    aRetVal = mSystemLocales;
    return NS_OK;
  }

  if (ReadSystemLocales(aRetVal)) {
    mSystemLocales = aRetVal;
    return NS_OK;
  }

  // If we failed to get the system locale, we still need
  // to return something because there are tests out there that
  // depend on system locale to be set.
  aRetVal.AppendElement(NS_LITERAL_CSTRING("en-US"));
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP
OSPreferences::GetSystemLocale(nsACString& aRetVal) {
  if (!mSystemLocales.IsEmpty()) {
    aRetVal = mSystemLocales[0];
  } else {
    AutoTArray<nsCString, 10> locales;
    GetSystemLocales(locales);
    if (!locales.IsEmpty()) {
      aRetVal = locales[0];
    }
  }
  return NS_OK;
}

NS_IMETHODIMP
OSPreferences::GetRegionalPrefsLocales(nsTArray<nsCString>& aRetVal) {
  if (!mRegionalPrefsLocales.IsEmpty()) {
    aRetVal = mRegionalPrefsLocales;
    return NS_OK;
  }

  if (ReadRegionalPrefsLocales(aRetVal)) {
    mRegionalPrefsLocales = aRetVal;
    return NS_OK;
  }

  return NS_ERROR_FAILURE;
}

static OSPreferences::DateTimeFormatStyle ToDateTimeFormatStyle(
    int32_t aTimeFormat) {
  switch (aTimeFormat) {
    // See mozIOSPreferences.idl for the integer values here.
    case 0:
      return OSPreferences::DateTimeFormatStyle::None;
    case 1:
      return OSPreferences::DateTimeFormatStyle::Short;
    case 2:
      return OSPreferences::DateTimeFormatStyle::Medium;
    case 3:
      return OSPreferences::DateTimeFormatStyle::Long;
    case 4:
      return OSPreferences::DateTimeFormatStyle::Full;
  }
  return OSPreferences::DateTimeFormatStyle::Invalid;
}

NS_IMETHODIMP
OSPreferences::GetDateTimePattern(int32_t aDateFormatStyle,
                                  int32_t aTimeFormatStyle,
                                  const nsACString& aLocale,
                                  nsAString& aRetVal) {
  DateTimeFormatStyle dateStyle = ToDateTimeFormatStyle(aDateFormatStyle);
  if (dateStyle == DateTimeFormatStyle::Invalid) {
    return NS_ERROR_INVALID_ARG;
  }
  DateTimeFormatStyle timeStyle = ToDateTimeFormatStyle(aTimeFormatStyle);
  if (timeStyle == DateTimeFormatStyle::Invalid) {
    return NS_ERROR_INVALID_ARG;
  }

  // If the user is asking for None on both, date and time style,
  // let's exit early.
  if (timeStyle == DateTimeFormatStyle::None &&
      dateStyle == DateTimeFormatStyle::None) {
    return NS_OK;
  }

  // Create a cache key from the locale + style options
  nsAutoCString key(aLocale);
  key.Append(':');
  key.AppendInt(aDateFormatStyle);
  key.Append(':');
  key.AppendInt(aTimeFormatStyle);

  nsString pattern;
  if (mPatternCache.Get(key, &pattern)) {
    aRetVal = pattern;
    return NS_OK;
  }

  if (!ReadDateTimePattern(dateStyle, timeStyle, aLocale, pattern)) {
    if (!GetDateTimePatternForStyle(dateStyle, timeStyle, aLocale, pattern)) {
      return NS_ERROR_FAILURE;
    }
  }

  if (mPatternCache.Count() == kMaxCachedPatterns) {
    // Don't allow unlimited cache growth; just throw it away in the case of
    // pathological behavior where a page keeps requesting different formats
    // and locales.
    NS_WARNING("flushing DateTimePattern cache");
    mPatternCache.Clear();
  }
  mPatternCache.Put(key, pattern);

  aRetVal = pattern;
  return NS_OK;
}