app: simplify config loading code, handle errors too
[staging/windowmanager.git] / src / app.cpp
1 //
2 // Created by mfritzsc on 7/11/17.
3 //
4
5 #include "app.hpp"
6 #include "json_helper.hpp"
7 #include "layers.hpp"
8 #include "layout.hpp"
9 #include "util.hpp"
10 #include "wayland.hpp"
11
12 #include <cstdio>
13 #include <memory>
14
15 #include <cassert>
16
17 #include <json-c/json.h>
18
19 #include <bits/signum.h>
20 #include <csignal>
21 #include <fstream>
22 #include <json.hpp>
23
24 namespace wm {
25
26 namespace {
27 App *g_app;
28
29 using json = nlohmann::json;
30
31 struct wm::area area_from_json(json const &j) {
32    DB(j);
33    return wm::area{
34       j["name"].get<std::string>(),
35       {
36          get<int32_t>(j["width"]), get<int32_t>(j["height"]),
37          get<int32_t>(j["x"]), get<int32_t>(j["y"]),
38       },
39       get<uint32_t>(j["zorder"]),
40    };
41 }
42
43 result<struct layout> layout_from_json(json const &j) {
44    DB(j);
45    auto &ja = j["areas"];
46
47    auto l = layout{j["name"].get<std::string>(), uint32_t(ja.size()), {}};
48
49    if (ja.size() > layout::MAX_N_AREAS) {
50       return Err<struct layout>("Invalid number of areas in layout");
51    }
52
53    logdebug("Loading layout '%s' with %u areas", l.name.c_str(),
54             unsigned(ja.size()));
55
56    std::transform(std::cbegin(ja), std::cend(ja), std::begin(l.areas),
57                   area_from_json);
58
59    return Ok(l);
60 }
61
62 result<json> file_to_json(char const *filename) {
63    std::ifstream i(filename);
64    if (i.fail()) {
65       return Err<json>("Could not open config file");
66    }
67    json j;
68    i >> j;
69    return Ok(j);
70 }
71
72 struct result<layouts_type> load_layout(char const *filename) {
73    DB("loading layout from " << filename);
74
75    auto j = file_to_json(filename);
76    if (j.is_err()) {
77       return Err<layouts_type>(j.unwrap_err());
78    }
79    json jlayouts = j.unwrap();
80
81    auto layouts = layouts_type();
82    layouts.reserve(jlayouts.size());
83    std::transform(std::cbegin(jlayouts), std::cend(jlayouts),
84                   std::back_inserter(layouts), layout_from_json);
85
86    return Ok(layouts);
87 }
88
89 struct result<surface_id_to_layer_map>
90    load_layer_ids(char const *filename) {
91    DB("loading IDs from " << filename);
92
93    auto j = file_to_json(filename);
94    if (j.is_err()) {
95       return Err<surface_id_to_layer_map>(j.unwrap_err());
96    }
97    json jids = j.unwrap();
98
99    return to_surface_id_to_layer_map(jids);
100 }
101
102 }  // namespace
103
104 //       _                    _                  _                 _
105 //   ___| | __ _ ___ ___     / \   _ __  _ __   (_)_ __ ___  _ __ | |
106 //  / __| |/ _` / __/ __|   / _ \ | '_ \| '_ \  | | '_ ` _ \| '_ \| |
107 // | (__| | (_| \__ \__ \  / ___ \| |_) | |_) | | | | | | | | |_) | |
108 //  \___|_|\__,_|___/___/ /_/   \_\ .__/| .__/  |_|_| |_| |_| .__/|_|
109 //                                |_|   |_|                 |_|
110 App::App(wl::display *d)
111    : api{this},
112      chooks{this},
113      display{d},
114      controller{},
115      outputs(),
116      layouts(),  // load_layout("../layout.json").unwrap()),
117      surface2layer(load_layer_ids("../ids.json").unwrap()) {
118    // layouts(load_layout("../layout.json").unwrap()) {
119    assert(g_app == nullptr);
120    g_app = this;
121
122    try {
123       auto l = load_layout("../layout.json");
124       if (l.is_err()) {
125          logerror("Coult not load layout configuration: %s", l.err().value());
126       }
127    } catch (std::exception &e) {
128       logerror("Coult not load layout configuration: %s", e.what());
129    }
130 }
131
132 App::~App() { g_app = nullptr; }
133
134 int App::init() {
135    if (!this->display->ok()) {
136       return -1;
137    }
138
139    this->display->add_global_handler(
140       "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
141          this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
142       });
143
144    this->display->add_global_handler(
145       "ivi_controller", [this](wl_registry *r, uint32_t name, uint32_t v) {
146          this->controller = std::make_unique<genivi::controller>(r, name, v);
147
148          // Init controller hooks
149          this->controller->chooks = &this->chooks;
150
151          // XXX: This protocol needs the output, so lets just add our mapping
152          // here...
153          this->controller->add_proxy_to_id_mapping(
154             this->outputs.back()->proxy.get(),
155             wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
156                this->outputs.back()->proxy.get())));
157       });
158
159    // First level objects
160    this->display->roundtrip();
161    // Second level objects
162    this->display->roundtrip();
163    // Third level objects
164    this->display->roundtrip();
165
166    return init_layout();
167 }
168
169 int App::dispatch_events() {
170    int ret = this->display->dispatch();
171    if (ret == -1) {
172       logerror("wl_display_dipatch() returned error %d",
173                this->display->get_error());
174       return -1;
175    }
176    this->display->flush();
177
178    // execute pending tasks, that is layout changes etc.
179    this->controller->execute_pending();
180    this->display->roundtrip();
181
182    return 0;
183 }
184
185 //  _       _ _       _                         _    ____
186 // (_)_ __ (_) |_    | | __ _ _   _  ___  _   _| |_ / /\ \
187 // | | '_ \| | __|   | |/ _` | | | |/ _ \| | | | __| |  | |
188 // | | | | | | |_    | | (_| | |_| | (_) | |_| | |_| |  | |
189 // |_|_| |_|_|\__|___|_|\__,_|\__, |\___/ \__,_|\__| |  | |
190 //              |_____|       |___/                 \_\/_/
191 int App::init_layout() {
192    if (!this->controller) {
193       logerror("ivi_controller global not available");
194       return -1;
195    }
196
197    if (this->outputs.empty()) {
198       logerror("no output was set up!");
199       return -1;
200    }
201
202    auto &c = this->controller;
203
204    auto &o = this->outputs.front();
205    auto &s = c->screens.begin()->second;
206    auto &layers = c->layers;
207
208    // XXX: Write output dimensions to ivi controller...
209    c->output_size = genivi::size{uint32_t(o->width), uint32_t(o->height)};
210
211    // Clear scene
212    layers.clear();
213
214    // Clear screen
215    s->clear();
216
217    // Quick and dirty setup of layers
218    // XXX: This likely needs to be sorted by order (note, we don't (yet?)
219    // do any zorder arrangement).
220    for (auto const &i : this->surface2layer.mapping) {
221       c->layer_create(i.layer_id, o->width, o->height);
222       auto &l = layers[i.layer_id];
223       l->set_destination_rectangle(0, 0, o->width, o->height);
224       l->set_visibility(1);
225       logdebug("Setting up layer %s (%d) for surfaces %d-%d", i.name.c_str(),
226                i.layer_id, i.id_min, i.id_max);
227    }
228
229    // Add layers to screen (XXX: are they sorted correctly?)
230    s->set_render_order(this->surface2layer.layers);
231
232    c->commit_changes();
233
234    this->display->flush();
235
236    return 0;
237 }
238
239 //                      _          _   _____                 _
240 //  _ __  _ __ _____  _(_) ___  __| | | ____|_   _____ _ __ | |_ ___
241 // | '_ \| '__/ _ \ \/ / |/ _ \/ _` | |  _| \ \ / / _ \ '_ \| __/ __|
242 // | |_) | | | (_) >  <| |  __/ (_| | | |___ \ V /  __/ | | | |_\__ \
243 // | .__/|_|  \___/_/\_\_|\___|\__,_| |_____| \_/ \___|_| |_|\__|___/
244 // |_|
245 void App::surface_created(uint32_t surface_id) {
246    DB("surface_id is " << surface_id);
247    int layer_id =
248       this->surface2layer.get_layer_for_surface(surface_id).value_or(-1);
249    if (layer_id == -1) {
250       logerror("Surface %d (0x%x) is not part of any layer!", surface_id,
251                surface_id);
252    } else {
253       auto rect = this->surface2layer.get_rect_for_surface(surface_id).value();
254       this->controller->add_task(
255          "fullscreen surface",
256          [layer_id, surface_id, rect](struct genivi::controller *c) {
257             auto &s = c->surfaces[surface_id];
258
259             int x = rect.x;
260             int y = rect.y;
261             int w = rect.w;
262             int h = rect.h;
263
264             if (w < 0) {
265                w = c->output_size.w + 1 + w;
266             }
267             if (h < 0) {
268                h = c->output_size.h + 1 + h;
269             }
270             logdebug("Computed rect={ %d, %d, %d, %d }", x, y, w, h);
271
272             s->set_configuration(w, h);
273             s->set_source_rectangle(0, 0, w, h);
274             s->set_destination_rectangle(x, y, w, h);
275
276             s->set_visibility(1);
277             c->layers[layer_id]->add_surface(s.get());
278             logdebug("Surface %u now on layer %u", surface_id, layer_id);
279          });
280    }
281 }
282
283 void App::surface_removed(uint32_t surface_id) {
284    DB("surface_id is " << surface_id);
285 }
286
287 //  _     _           _ _                            _   _                 _
288 // | |__ (_)_ __   __| (_)_ __   __ _     __ _ _ __ (_) (_)_ __ ___  _ __ | |
289 // | '_ \| | '_ \ / _` | | '_ \ / _` |   / _` | '_ \| | | | '_ ` _ \| '_ \| |
290 // | |_) | | | | | (_| | | | | | (_| |  | (_| | |_) | | | | | | | | | |_) | |
291 // |_.__/|_|_| |_|\__,_|_|_| |_|\__, |___\__,_| .__/|_| |_|_| |_| |_| .__/|_|
292 //                              |___/_____|   |_|                   |_|
293 binding_api::result_type binding_api::register_surface(uint32_t appid,
294                                                        uint32_t surfid) {
295    logdebug("%s appid %u surfid %u", __func__, appid, surfid);
296    if (appid > 0xff) {
297       return Err<json_object *>("invalid appid");
298    }
299
300    if (surfid > 0xffff) {
301       return Err<json_object *>("invalid surfaceid");
302    }
303
304    return Ok(json_object_new_int((appid << 16) + surfid));
305 }
306
307 binding_api::result_type binding_api::debug_layers() {
308    logdebug("%s", __func__);
309    return Ok(to_json(this->app->controller->lprops));
310 }
311
312 binding_api::result_type binding_api::debug_surfaces() {
313    logdebug("%s", __func__);
314    return Ok(to_json(this->app->controller->sprops));
315 }
316
317 binding_api::result_type binding_api::debug_status() {
318    logdebug("%s", __func__);
319    json_object *jr = json_object_new_object();
320    json_object_object_add(jr, "surfaces",
321                           to_json(this->app->controller->sprops));
322    json_object_object_add(jr, "layers", to_json(this->app->controller->lprops));
323    return Ok(jr);
324 }
325
326 binding_api::result_type binding_api::debug_terminate() {
327    logdebug("%s", __func__);
328    raise(SIGKILL);  // XXX afb-daemon kills it's pgroup using TERM, which
329                     // doesn't play well with perf
330    return Ok(json_object_new_object());
331 }
332
333 //                  _             _ _            _                 _
334 //   ___ ___  _ __ | |_ _ __ ___ | | | ___ _ __ | |__   ___   ___ | | _____
335 //  / __/ _ \| '_ \| __| '__/ _ \| | |/ _ \ '__|| '_ \ / _ \ / _ \| |/ / __|
336 // | (_| (_) | | | | |_| | | (_) | | |  __/ |   | | | | (_) | (_) |   <\__ \
337 //  \___\___/|_| |_|\__|_|  \___/|_|_|\___|_|___|_| |_|\___/ \___/|_|\_\___/
338 //                                         |_____|
339 void controller_hooks::surface_created(uint32_t surface_id) {
340    this->app->surface_created(surface_id);
341 }
342
343 void controller_hooks::surface_removed(uint32_t surface_id) {
344    this->app->surface_removed(surface_id);
345 }
346
347 }  // namespace wm