clang-tidy
[staging/windowmanager.git] / src / app.cpp
1 /*
2  * Copyright (C) 2017 Mentor Graphics Development (Deutschland) GmbH
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "app.hpp"
18 #include "json_helper.hpp"
19 #include "layers.hpp"
20 #include "layout.hpp"
21 #include "util.hpp"
22 #include "wayland.hpp"
23
24 #include <cstdio>
25 #include <memory>
26
27 #include <cassert>
28
29 #include <json-c/json.h>
30
31 #include <algorithm>
32 #include <bits/signum.h>
33 #include <csignal>
34 #include <fstream>
35 #include <json.hpp>
36
37 namespace wm {
38
39 namespace {
40 App *g_app;
41
42 using json = nlohmann::json;
43
44 struct wm::area area_from_json(json const &j) {
45    return wm::area{
46       j["name"],
47       {
48          j["width"], j["height"], j["x"], j["y"],
49       },
50       j["zorder"],
51    };
52 }
53
54 result<struct layout> layout_from_json(json const &j) {
55    auto &ja = j["areas"];
56
57    auto l = layout{j["name"], uint32_t(ja.size()), {}};
58
59    if (ja.size() > layout::MAX_N_AREAS) {
60       return Err<struct layout>("Invalid number of areas in layout");
61    }
62
63    logdebug("Loading layout '%s' with %u areas", l.name.c_str(),
64             unsigned(ja.size()));
65
66    std::transform(std::cbegin(ja), std::cend(ja), std::begin(l.areas),
67                   area_from_json);
68
69    return Ok(l);
70 }
71
72 result<json> file_to_json(char const *filename) {
73    std::ifstream i(filename);
74    if (i.fail()) {
75       return Err<json>("Could not open config file");
76    }
77    json j;
78    i >> j;
79    return Ok(j);
80 }
81
82 // Will throw if parsing fails
83 struct result<layouts_type> load_layout(char const *filename) {
84    logdebug("loading layout from %s", filename);
85
86    auto j = file_to_json(filename);
87    if (j.is_err()) {
88       return Err<layouts_type>(j.unwrap_err());
89    }
90    json jlayouts = j.unwrap();
91
92    auto layouts = layouts_type();
93    layouts.reserve(jlayouts.size());
94    std::transform(std::cbegin(jlayouts), std::cend(jlayouts),
95                   std::back_inserter(layouts), layout_from_json);
96
97    return Ok(layouts);
98 }
99
100 struct result<layer_map>
101    load_layer_map(char const *filename) {
102    logdebug("loading IDs from %s", filename);
103
104    auto j = file_to_json(filename);
105    if (j.is_err()) {
106       return Err<layer_map>(j.unwrap_err());
107    }
108    json jids = j.unwrap();
109
110    return to_layer_map(jids);
111 }
112
113 }  // namespace
114
115 //       _                    _                  _                 _
116 //   ___| | __ _ ___ ___     / \   _ __  _ __   (_)_ __ ___  _ __ | |
117 //  / __| |/ _` / __/ __|   / _ \ | '_ \| '_ \  | | '_ ` _ \| '_ \| |
118 // | (__| | (_| \__ \__ \  / ___ \| |_) | |_) | | | | | | | | |_) | |
119 //  \___|_|\__,_|___/___/ /_/   \_\ .__/| .__/  |_|_| |_| |_| .__/|_|
120 //                                |_|   |_|                 |_|
121 App::App(wl::display *d)
122    : api{this},
123      chooks{this},
124      display{d},
125      controller{},
126      outputs(),
127      config(),
128      layouts(),
129      layers(),
130      pending(),
131      name_mapping(),
132      id_alloc{} {
133    assert(g_app == nullptr);
134    g_app = this;
135
136    try {
137       {
138          auto l = load_layer_map(
139             this->config.get_string("layers.json").value().c_str());
140          if (l.is_ok()) {
141             this->layers = l.unwrap();
142          } else {
143             logerror("%s", l.err().value());
144          }
145       }
146
147       {
148          auto l =
149             load_layout(this->config.get_string("layout.json").value().c_str());
150          if (l.is_ok()) {
151             this->layouts = l.unwrap();
152          } else {
153             logerror("%s", l.err().value());
154          }
155       }
156    } catch (std::exception &e) {
157       logerror("Loading of configuration failed: %s", e.what());
158    }
159 }
160
161 App::~App() { g_app = nullptr; }
162
163 int App::init() {
164    if (!this->display->ok()) {
165       return -1;
166    }
167
168    if (this->layers.mapping.empty()) {
169       logerror("No surface -> layer mapping loaded");
170       return -1;
171    }
172
173    this->display->add_global_handler(
174       "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
175          this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
176       });
177
178    this->display->add_global_handler(
179       "ivi_controller", [this](wl_registry *r, uint32_t name, uint32_t v) {
180          this->controller = std::make_unique<genivi::controller>(r, name, v);
181
182          // Init controller hooks
183          this->controller->chooks = &this->chooks;
184
185          // XXX: This protocol needs the output, so lets just add our mapping
186          // here...
187          this->controller->add_proxy_to_id_mapping(
188             this->outputs.back()->proxy.get(),
189             wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
190                this->outputs.back()->proxy.get())));
191       });
192
193    // First level objects
194    this->display->roundtrip();
195    // Second level objects
196    this->display->roundtrip();
197    // Third level objects
198    this->display->roundtrip();
199
200    return init_layout();
201 }
202
203 int App::dispatch_events() {
204    int ret = this->display->dispatch();
205    if (ret == -1) {
206       logerror("wl_display_dipatch() returned error %d",
207                this->display->get_error());
208       return -1;
209    }
210    this->display->flush();
211
212    // execute pending tasks, that is layout changes etc.
213    this->execute_pending();
214
215    return 0;
216 }
217
218 //  _       _ _       _                         _    ____
219 // (_)_ __ (_) |_    | | __ _ _   _  ___  _   _| |_ / /\ \
220 // | | '_ \| | __|   | |/ _` | | | |/ _ \| | | | __| |  | |
221 // | | | | | | |_    | | (_| | |_| | (_) | |_| | |_| |  | |
222 // |_|_| |_|_|\__|___|_|\__,_|\__, |\___/ \__,_|\__| |  | |
223 //              |_____|       |___/                 \_\/_/
224 int App::init_layout() {
225    if (!this->controller) {
226       logerror("ivi_controller global not available");
227       return -1;
228    }
229
230    if (this->outputs.empty()) {
231       logerror("no output was set up!");
232       return -1;
233    }
234
235    auto &c = this->controller;
236
237    auto &o = this->outputs.front();
238    auto &s = c->screens.begin()->second;
239    auto &layers = c->layers;
240
241    // XXX: Write output dimensions to ivi controller...
242    c->output_size = genivi::size{uint32_t(o->width), uint32_t(o->height)};
243
244    // Clear scene
245    layers.clear();
246
247    // Clear screen
248    s->clear();
249
250    // Quick and dirty setup of layers
251    // XXX: This likely needs to be sorted by order (note, we don't (yet?)
252    // do any zorder arrangement).
253    for (auto const &i : this->layers.mapping) {
254       c->layer_create(i.layer_id, o->width, o->height);
255       auto &l = layers[i.layer_id];
256       l->set_destination_rectangle(0, 0, o->width, o->height);
257       l->set_visibility(1);
258       logdebug("Setting up layer %s (%d) for surfaces %d-%d", i.name.c_str(),
259                i.layer_id, i.id_min, i.id_max);
260    }
261
262    // Add layers to screen (XXX: are they sorted correctly?)
263    s->set_render_order(this->layers.layers);
264
265    c->commit_changes();
266
267    this->display->flush();
268
269    return 0;
270 }
271
272 void App::surface_set_layout(uint32_t surface_id) {
273    auto o_layer_id = this->layers.get_layer_id(surface_id);
274
275    if (!o_layer_id) {
276       logerror("Surface %d is not associated with any layer!", int(surface_id));
277       return;
278    }
279
280    if (!this->controller->surface_exists(surface_id)) {
281       logerror("Surface %d does not exist", int(surface_id));
282       return;
283    }
284
285    uint32_t layer_id = o_layer_id.value();
286    logdebug("surface_set_layout for surface %u on layer %u", surface_id,
287             layer_id);
288
289    auto const &layer = this->layers.get_layer(layer_id);
290    auto rect = layer.value().rect;
291    auto &s = this->controller->surfaces[surface_id];
292
293    int x = rect.x;
294    int y = rect.y;
295    int w = rect.w;
296    int h = rect.h;
297
298    // less-than-0 values refer to MAX + 1 - $VALUE
299    // e.g. MAX is either screen width or height
300    if (w < 0) {
301       w = this->controller->output_size.w + 1 + w;
302    }
303    if (h < 0) {
304       h = this->controller->output_size.h + 1 + h;
305    }
306
307    // configure surface to wxh dimensions
308    s->set_configuration(w, h);
309    // set destination to the display rectangle
310    s->set_destination_rectangle(x, y, w, h);
311
312    // XXX: visibility should be determined independently of our
313    //      layer + geometry setup.
314    s->set_visibility(
315       surface_id == static_cast<unsigned>(this->layers.main_surface) ? 1 : 0);
316    this->controller->layers[layer_id]->add_surface(s.get());
317
318    logdebug("Surface %u now on layer %u with rect { %d, %d, %d, %d }",
319             surface_id, layer_id, x, y, w, h);
320 }
321
322 char const *App::activate_surface(uint32_t surface_id) {
323    if (!this->controller->surface_exists(surface_id)) {
324       return "Surface does not exist";
325    }
326
327    // This should involve a policy check, but as we do not (yet) have
328    // such a thing, we will just switch to this surface.
329    // XXX: input focus missing!!1
330
331    // Make it visible, no (or little effect) if already visible
332    auto &s = this->controller->surfaces[surface_id];
333
334    // Set all others invisible
335    for (auto &i : this->controller->surfaces) {
336       auto &si = this->controller->sprops[i.second->id];
337       if (si.visibility == 1 && si.id != s->id &&
338           int(si.id) != this->layers.main_surface) {
339          i.second->set_visibility(0);
340       }
341    }
342    s->set_visibility(1);
343
344    // commit changes
345    this->controller->commit_changes();
346    this->display->flush();
347
348    // no error
349    return nullptr;
350 }
351
352 void App::add_task(char const *name, std::function<void()> &&f) {
353    this->pending.emplace_back(std::make_pair(name, f));
354 }
355
356 void App::execute_pending() {
357    if (!this->pending.empty()) {
358       for (auto &t : this->pending) {
359          logdebug("executing task '%s'", t.first);
360          t.second();
361       }
362       this->pending.clear();
363       this->controller->commit_changes();
364       this->display->flush();
365    }
366 }
367
368 //                      _          _   _____                 _
369 //  _ __  _ __ _____  _(_) ___  __| | | ____|_   _____ _ __ | |_ ___
370 // | '_ \| '__/ _ \ \/ / |/ _ \/ _` | |  _| \ \ / / _ \ '_ \| __/ __|
371 // | |_) | | | (_) >  <| |  __/ (_| | | |___ \ V /  __/ | | | |_\__ \
372 // | .__/|_|  \___/_/\_\_|\___|\__,_| |_____| \_/ \___|_| |_|\__|___/
373 // |_|
374 void App::surface_created(uint32_t surface_id) {
375    logdebug("surface_id is %u", surface_id);
376
377    // We need to execute the surface setup after its creation.
378    this->add_task("surface_set_layout",
379                   [surface_id, this] { this->surface_set_layout(surface_id); });
380 }
381
382 void App::surface_removed(uint32_t surface_id) {
383    logdebug("surface_id is %u", surface_id);
384 }
385
386 result<int> App::request_surface(char const *drawing_name) {
387    auto lid = this->layers.get_layer_id(std::string(drawing_name));
388    if (!lid) {
389       // XXX: to we need to put these applications on the App layer?
390       return Err<int>("Drawing name does not match any role");
391    }
392
393    auto rname = this->id_alloc[drawing_name];
394    if (!rname) {
395       // name does not exist yet, allocate surface id...
396       // XXX: how to allocate surface IDs?
397       // * allocate by running a counter for each layer?
398       // * allocate IDs globally, i.e. do not have layers contain
399       //   ID ranges (only define the surfaces on the layer by
400       //   role?)
401       auto id = int(this->id_alloc(drawing_name));
402       this->layers.add_surface(id, lid.value());
403
404       // XXX: you should fix this!
405       if (!this->layers.main_surface_name.empty() &&
406           this->layers.main_surface_name == drawing_name) {
407          this->layers.main_surface = id;
408          this->activate_surface(id);
409          logdebug("Set main_surface id to %u", id);
410       }
411
412       return Ok<int>(id);
413    }
414
415    // Check currently registered drawing names if it is already there.
416    return Err<int>("Surface already present");
417 }
418
419 char const *App::activate_surface(char const *drawing_name) {
420    auto osid = this->id_alloc[drawing_name];
421
422    if (osid) {
423       logdebug("ativate surface with name %s and id %u", drawing_name,
424                osid.value());
425       this->activate_surface(osid.value());
426       return nullptr;
427    }
428
429    logerror("surface %s unknown", drawing_name);
430    return "Surface unknown";
431 }
432
433 //  _     _           _ _                            _   _                 _
434 // | |__ (_)_ __   __| (_)_ __   __ _     __ _ _ __ (_) (_)_ __ ___  _ __ | |
435 // | '_ \| | '_ \ / _` | | '_ \ / _` |   / _` | '_ \| | | | '_ ` _ \| '_ \| |
436 // | |_) | | | | | (_| | | | | | (_| |  | (_| | |_) | | | | | | | | | |_) | |
437 // |_.__/|_|_| |_|\__,_|_|_| |_|\__, |___\__,_| .__/|_| |_|_| |_| |_| .__/|_|
438 //                              |___/_____|   |_|                   |_|
439 binding_api::result_type binding_api::request_surface(
440    char const *drawing_name) {
441    auto r = this->app->request_surface(drawing_name);
442    if (r.is_err()) {
443       return Err<json_object *>(r.unwrap_err());
444    }
445    return Ok(json_object_new_int(r.unwrap()));
446 }
447
448 binding_api::result_type binding_api::activate_surface(
449    char const *drawing_name) {
450    logdebug("%s drawing_name %s", __func__, drawing_name);
451    auto r = this->app->activate_surface(drawing_name);
452    if (r != nullptr) {
453       return Err<json_object *>(r);
454    }
455    return Ok(json_object_new_object());
456 }
457
458 binding_api::result_type binding_api::list_drawing_names() {
459    json j = this->app->id_alloc.names;
460    return Ok(json_tokener_parse(j.dump().c_str()));
461 }
462
463 binding_api::result_type binding_api::debug_layers() {
464    logdebug("%s", __func__);
465    return Ok(json_tokener_parse(this->app->layers.to_json().dump().c_str()));
466 }
467
468 binding_api::result_type binding_api::debug_surfaces() {
469    logdebug("%s", __func__);
470    return Ok(to_json(this->app->controller->sprops));
471 }
472
473 binding_api::result_type binding_api::debug_status() {
474    logdebug("%s", __func__);
475    json_object *jr = json_object_new_object();
476    json_object_object_add(jr, "surfaces",
477                           to_json(this->app->controller->sprops));
478    json_object_object_add(jr, "layers", to_json(this->app->controller->lprops));
479    return Ok(jr);
480 }
481
482 binding_api::result_type binding_api::debug_terminate() {
483    logdebug("%s", __func__);
484    raise(SIGKILL);  // XXX afb-daemon kills it's pgroup using TERM, which
485                     // doesn't play well with perf
486    return Ok(json_object_new_object());
487 }
488
489 binding_api::result_type binding_api::demo_activate_surface(
490    uint32_t surfaceid) {
491    char const *e = this->app->activate_surface(surfaceid);
492    if (e != nullptr) {
493       return Err<json_object *>(e);
494    }
495    return Ok(json_object_new_object());
496 }
497
498 binding_api::result_type binding_api::demo_activate_all() {
499    for (auto &s : this->app->controller->surfaces) {
500       s.second->set_visibility(1);
501    }
502    this->app->controller->commit_changes();
503    this->app->display->flush();
504    return Ok(json_object_new_object());
505 }
506
507 //                  _             _ _            _                 _
508 //   ___ ___  _ __ | |_ _ __ ___ | | | ___ _ __ | |__   ___   ___ | | _____
509 //  / __/ _ \| '_ \| __| '__/ _ \| | |/ _ \ '__|| '_ \ / _ \ / _ \| |/ / __|
510 // | (_| (_) | | | | |_| | | (_) | | |  __/ |   | | | | (_) | (_) |   <\__ \
511 //  \___\___/|_| |_|\__|_|  \___/|_|_|\___|_|___|_| |_|\___/ \___/|_|\_\___/
512 //                                         |_____|
513 void controller_hooks::surface_created(uint32_t surface_id) {
514    this->app->surface_created(surface_id);
515 }
516
517 void controller_hooks::surface_removed(uint32_t surface_id) {
518    this->app->surface_removed(surface_id);
519 }
520
521 void controller_hooks::add_task(char const *name, std::function<void()> &&f) {
522    this->app->add_task(name, std::move(f));
523 }
524
525 }  // namespace wm