icu_util.cc 2.5 KB
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "flutter/fml/icu_util.h"

#include <memory>
#include <mutex>

10
#include "flutter/fml/build_config.h"
11
#include "flutter/fml/logging.h"
12
#include "flutter/fml/mapping.h"
13
#include "flutter/fml/paths.h"
14 15 16 17 18
#include "third_party/icu/source/common/unicode/udata.h"

namespace fml {
namespace icu {

19 20 21 22 23 24
#if OS_WIN
static constexpr char kPathSeparator = '\\';
#else
static constexpr char kPathSeparator = '/';
#endif

25 26 27 28 29 30 31 32 33 34
class ICUContext {
 public:
  ICUContext(const std::string& icu_data_path) : valid_(false) {
    valid_ = SetupMapping(icu_data_path) && SetupICU();
  }

  ~ICUContext() = default;

  bool SetupMapping(const std::string& icu_data_path) {
    // Check if the explicit path specified exists.
35 36 37
    auto path_mapping = std::make_unique<FileMapping>(icu_data_path, false);
    if (path_mapping->GetSize() != 0) {
      mapping_ = std::move(path_mapping);
38 39 40 41 42
      return true;
    }

    // Check if the mapping can by directly accessed via a file path. In this
    // case, the data file needs to be next to the executable.
43 44 45 46 47 48
    auto directory = fml::paths::GetExecutableDirectoryPath();

    if (!directory.first) {
      return false;
    }

49
    auto file = std::make_unique<FileMapping>(
50
        directory.second + kPathSeparator + icu_data_path, false);
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
    if (file->GetSize() != 0) {
      mapping_ = std::move(file);
      return true;
    }

    return false;
  }

  bool SetupICU() {
    if (GetSize() == 0) {
      return false;
    }

    UErrorCode err_code = U_ZERO_ERROR;
    udata_setCommonData(GetMapping(), &err_code);
    return (err_code == U_ZERO_ERROR);
  }

  const uint8_t* GetMapping() const {
    return mapping_ ? mapping_->GetMapping() : nullptr;
  }

  size_t GetSize() const { return mapping_ ? mapping_->GetSize() : 0; }

  bool IsValid() const { return valid_; }

 private:
  bool valid_;
  std::unique_ptr<Mapping> mapping_;

81
  FML_DISALLOW_COPY_AND_ASSIGN(ICUContext);
82 83 84 85
};

void InitializeICUOnce(const std::string& icu_data_path) {
  static ICUContext* context = new ICUContext(icu_data_path);
86
  FML_CHECK(context->IsValid())
87
      << "Must be able to initialize the ICU context. Tried: " << icu_data_path;
88 89 90 91 92 93 94 95 96 97
}

std::once_flag g_icu_init_flag;
void InitializeICU(const std::string& icu_data_path) {
  std::call_once(g_icu_init_flag,
                 [&icu_data_path]() { InitializeICUOnce(icu_data_path); });
}

}  // namespace icu
}  // namespace fml