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"];
34 std::cbegin(m), std::cend(m),
35 std::inserter(stl.mapping, stl.mapping.end()),
36 [](nlohmann::json const &j) { return surface_id_to_layer(j); });
37 for (auto i : stl.mapping) {
39 return Err<struct surface_id_to_layer_map>(
40 "Found mapping w/o name");
42 if (i.layer_id == -1 || i.id_min == -1 || i.id_max == -1) {
43 return Err<struct surface_id_to_layer_map>(
44 "Found invalid/unset IDs in mapping");
49 auto jtests = j.value("tests", json());
51 if (! jtests.empty()) {
52 DB("Embedded tests...");
53 std::vector<std::pair<int, int>> tests;
54 tests.reserve(jtests.size());
55 std::transform(std::cbegin(jtests), std::cend(jtests),
56 std::back_inserter(tests), [](json const &j) {
57 return std::make_pair(get<int>(j["surface_id"]),
58 get<int>(j["expect_layer_id"]));
61 for (auto sid : tests) {
62 int lid = stl.get_layer_for_surface(sid.first).value_or(-1);
63 DB("this=" << sid.first << ", that=" << lid
64 << ", expect=" << sid.second);
65 if (lid != sid.second) {
66 return Err<surface_id_to_layer_map>(
67 "ID Map embedded test failed!");
73 } catch (std::exception &e) {
74 return Err<struct surface_id_to_layer_map>(e.what());
78 // Helper to allow std::lower_bound with a int key only
80 operator<(struct surface_id_to_layer const &a, int b) {
84 optional<int> surface_id_to_layer_map::get_layer_for_surface(int surface_id) {
85 auto i = std::lower_bound(std::cbegin(this->mapping),
86 std::cend(this->mapping), surface_id);
88 if (i != this->mapping.end()) {
89 // std::less only checks for surface_id_to_layer::id_max, so check
90 // that we are actually inside of an interval here.
91 if (i->id_min <= surface_id) {
92 return optional<int>(i->layer_id);