2 // Created by m on 7/27/17.
7 #include "json_helper.hpp"
13 using json = nlohmann::json;
15 surface_id_to_layer::surface_id_to_layer(nlohmann::json const &j) {
17 if (j["type"] == "range") {
18 this->id_min = get<int>(j["first_surface_id"]);
19 this->id_max = get<int>(j["last_surface_id"]);
21 this->id_min = this->id_max = get<int>(j["surface_id"]);
23 this->name = j["name"].get<std::string>();
24 this->layer_id = get<int>(j["layer_id"]);
27 struct result<struct surface_id_to_layer_map> to_surface_id_to_layer_map(
28 nlohmann::json const &j) {
31 surface_id_to_layer_map stl{};
32 auto m = j["mappings"];
33 stl.layers.reserve(m.size());
34 std::transform(std::cbegin(m), std::cend(m),
35 std::inserter(stl.mapping, stl.mapping.end()),
36 [&stl](nlohmann::json const &j) {
37 auto k = surface_id_to_layer(j);
38 stl.layers.push_back(unsigned(k.layer_id));
41 // XXX need to sort layers?
42 for (auto i : stl.mapping) {
44 return Err<struct surface_id_to_layer_map>(
45 "Found mapping w/o name");
47 if (i.layer_id == -1 || i.id_min == -1 || i.id_max == -1) {
48 return Err<struct surface_id_to_layer_map>(
49 "Found invalid/unset IDs in mapping");
54 auto jtests = j.value("tests", json());
56 if (!jtests.empty()) {
57 DB("Embedded tests...");
58 std::vector<std::pair<int, int>> tests;
59 tests.reserve(jtests.size());
60 std::transform(std::cbegin(jtests), std::cend(jtests),
61 std::back_inserter(tests), [](json const &j) {
62 return std::make_pair(
63 get<int>(j["surface_id"]),
64 get<int>(j["expect_layer_id"]));
67 for (auto sid : tests) {
68 int lid = stl.get_layer_for_surface(sid.first).value_or(-1);
69 DB("this=" << sid.first << ", that=" << lid
70 << ", expect=" << sid.second);
71 if (lid != sid.second) {
72 return Err<surface_id_to_layer_map>(
73 "ID Map embedded test failed!");
79 } catch (std::exception &e) {
80 return Err<struct surface_id_to_layer_map>(e.what());
84 // Helper to allow std::lower_bound with a int key only
86 operator<(struct surface_id_to_layer const &a, int b) {
90 optional<int> surface_id_to_layer_map::get_layer_for_surface(int surface_id) {
91 auto i = std::lower_bound(std::cbegin(this->mapping),
92 std::cend(this->mapping), surface_id);
94 if (i != this->mapping.end()) {
95 // std::less only checks for surface_id_to_layer::id_max, so check
96 // that we are actually inside of an interval here.
97 if (i->id_min <= surface_id) {
98 return optional<int>(i->layer_id);