aboutsummaryrefslogtreecommitdiff
path: root/resources/src/main/java/org/robolectric/res/ResBundle.java
blob: a7b516bbce4c94cd3dafafb99f6f3222d45aecc8 (plain)
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
package org.robolectric.res;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.robolectric.res.android.ConfigDescription;
import org.robolectric.res.android.ResTable_config;

public class ResBundle {
  private final ResMap valuesMap = new ResMap();

  public void put(ResName resName, TypedResource value) {
    valuesMap.put(resName, value);
  }

  public TypedResource get(ResName resName, String qualifiers) {
    return valuesMap.pick(resName, qualifiers);
  }

  public void receive(ResourceTable.Visitor visitor) {
    for (final Map.Entry<ResName, List<TypedResource>> entry : valuesMap.map.entrySet()) {
      visitor.visit(entry.getKey(), entry.getValue());
    }
  }

  static class ResMap {
    private final Map<ResName, List<TypedResource>> map = new HashMap<>();

    public TypedResource pick(ResName resName, String qualifiersStr) {
      List<TypedResource> values = map.get(resName);
      if (values == null || values.size() == 0) return null;

      ResTable_config toMatch = new ResTable_config();
      new ConfigDescription().parse(qualifiersStr == null ? "" : qualifiersStr, toMatch);

      TypedResource bestMatchSoFar = null;
      for (TypedResource candidate : values) {
        ResTable_config candidateConfig = candidate.getConfig();
        if (candidateConfig.match(toMatch)) {
          if (bestMatchSoFar == null || candidateConfig.isBetterThan(bestMatchSoFar.getConfig(), toMatch)) {
            bestMatchSoFar = candidate;
          }
        }
      }

      return bestMatchSoFar;
    }

    public void put(ResName resName, TypedResource value) {
      List<TypedResource> values = map.get(resName);
      if (values == null) map.put(resName, values = new ArrayList<>());
      values.add(value);
    }

    public int size() {
      return map.size();
    }
  }
}