resource_mapper.cc 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2020 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. #include "weblayer/browser/android/resource_mapper.h"
  5. #include <map>
  6. #include "base/android/jni_android.h"
  7. #include "base/android/jni_array.h"
  8. #include "base/check_op.h"
  9. #include "base/no_destructor.h"
  10. #include "base/notreached.h"
  11. #include "components/resources/android/theme_resources.h"
  12. #include "weblayer/browser/java/jni/ResourceMapper_jni.h"
  13. namespace weblayer {
  14. namespace {
  15. using ResourceMap = std::map<int, int>;
  16. ResourceMap* GetIdMap() {
  17. static base::NoDestructor<ResourceMap> id_map;
  18. return id_map.get();
  19. }
  20. // Create the mapping. IDs start at 0 to correspond to the array that gets
  21. // built in the corresponding ResourceID Java class.
  22. void ConstructMap() {
  23. DCHECK(GetIdMap()->empty());
  24. JNIEnv* env = base::android::AttachCurrentThread();
  25. base::android::ScopedJavaLocalRef<jintArray> java_id_array =
  26. Java_ResourceMapper_getResourceIdList(env);
  27. std::vector<int> resource_id_list;
  28. base::android::JavaIntArrayToIntVector(env, java_id_array, &resource_id_list);
  29. size_t next_id = 0;
  30. #define LINK_RESOURCE_ID(c_id, java_id) \
  31. (*GetIdMap())[c_id] = resource_id_list[next_id++];
  32. #define DECLARE_RESOURCE_ID(c_id, java_id) \
  33. (*GetIdMap())[c_id] = resource_id_list[next_id++];
  34. #include "components/resources/android/blocked_content_resource_id.h"
  35. #include "components/resources/android/page_info_resource_id.h"
  36. #include "components/resources/android/permissions_resource_id.h"
  37. #include "components/resources/android/sms_resource_id.h"
  38. #include "components/resources/android/webxr_resource_id.h"
  39. #undef LINK_RESOURCE_ID
  40. #undef DECLARE_RESOURCE_ID
  41. // Make sure ID list sizes match up.
  42. DCHECK_EQ(next_id, resource_id_list.size());
  43. }
  44. } // namespace
  45. int MapToJavaDrawableId(int resource_id) {
  46. if (GetIdMap()->empty()) {
  47. ConstructMap();
  48. }
  49. ResourceMap::iterator iterator = GetIdMap()->find(resource_id);
  50. if (iterator != GetIdMap()->end()) {
  51. return iterator->second;
  52. }
  53. // The resource couldn't be found.
  54. // If you've landed here, please ensure that the header that declares the
  55. // mapping of your native resource to Java resource is listed both in
  56. // ResourceId.tempalate and in this file, next to other *resource_id.h
  57. // headers.
  58. NOTREACHED();
  59. return 0;
  60. }
  61. } // namespace weblayer