clang formatting
[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 <bits/signum.h>
32 #include <csignal>
33 #include <fstream>
34 #include <json.hpp>
35
36 namespace wm {
37
38 namespace {
39 App *g_app;
40
41 using json = nlohmann::json;
42
43 struct wm::area area_from_json(json const &j) {
44    DB(j);
45    return wm::area{
46       j["name"].get<std::string>(),
47       {
48          get<int32_t>(j["width"]), get<int32_t>(j["height"]),
49          get<int32_t>(j["x"]), get<int32_t>(j["y"]),
50       },
51       get<uint32_t>(j["zorder"]),
52    };
53 }
54
55 result<struct layout> layout_from_json(json const &j) {
56    DB(j);
57    auto &ja = j["areas"];
58
59    auto l = layout{j["name"].get<std::string>(), uint32_t(ja.size()), {}};
60
61    if (ja.size() > layout::MAX_N_AREAS) {
62       return Err<struct layout>("Invalid number of areas in layout");
63    }
64
65    logdebug("Loading layout '%s' with %u areas", l.name.c_str(),
66             unsigned(ja.size()));
67
68    std::transform(std::cbegin(ja), std::cend(ja), std::begin(l.areas),
69                   area_from_json);
70
71    return Ok(l);
72 }
73
74 result<json> file_to_json(char const *filename) {
75    std::ifstream i(filename);
76    if (i.fail()) {
77       return Err<json>("Could not open config file");
78    }
79    json j;
80    i >> j;
81    return Ok(j);
82 }
83
84 // Will throw if parsing fails
85 struct result<layouts_type> load_layout(char const *filename) {
86    DB("loading layout from " << filename);
87
88    auto j = file_to_json(filename);
89    if (j.is_err()) {
90       return Err<layouts_type>(j.unwrap_err());
91    }
92    json jlayouts = j.unwrap();
93
94    auto layouts = layouts_type();
95    layouts.reserve(jlayouts.size());
96    std::transform(std::cbegin(jlayouts), std::cend(jlayouts),
97                   std::back_inserter(layouts), layout_from_json);
98
99    return Ok(layouts);
100 }
101
102 struct result<layer_map>
103    load_layer_map(char const *filename) {
104    DB("loading IDs from " << filename);
105
106    auto j = file_to_json(filename);
107    if (j.is_err()) {
108       return Err<layer_map>(j.unwrap_err());
109    }
110    json jids = j.unwrap();
111
112    return to_layer_map(jids);
113 }
114
115 }  // namespace
116
117 //       _                    _                  _                 _
118 //   ___| | __ _ ___ ___     / \   _ __  _ __   (_)_ __ ___  _ __ | |
119 //  / __| |/ _` / __/ __|   / _ \ | '_ \| '_ \  | | '_ ` _ \| '_ \| |
120 // | (__| | (_| \__ \__ \  / ___ \| |_) | |_) | | | | | | | | |_) | |
121 //  \___|_|\__,_|___/___/ /_/   \_\ .__/| .__/  |_|_| |_| |_| .__/|_|
122 //                                |_|   |_|                 |_|
123 App::App(wl::display *d)
124    : api{this},
125      chooks{this},
126      display{d},
127      controller{},
128      outputs(),
129      config(),
130      layouts(),
131      layers() {
132    assert(g_app == nullptr);
133    g_app = this;
134
135    try {
136       {
137          auto l = load_layer_map(
138             this->config.get_string("layers.json").value().c_str());
139          if (l.is_ok()) {
140             this->layers = l.unwrap();
141          } else {
142             logerror("%s", l.err().value());
143          }
144       }
145
146       {
147          auto l =
148             load_layout(this->config.get_string("layout.json").value().c_str());
149          if (l.is_ok()) {
150             this->layouts = l.unwrap();
151          } else {
152             logerror("%s", l.err().value());
153          }
154       }
155    } catch (std::exception &e) {
156       logerror("Loading of configuration failed: %s", e.what());
157    }
158 }
159
160 App::~App() { g_app = nullptr; }
161
162 int App::init() {
163    if (!this->display->ok()) {
164       return -1;
165    }
166
167    if (this->layers.mapping.empty()) {
168       logerror("No surface -> layer mapping loaded");
169       return -1;
170    }
171
172    this->display->add_global_handler(
173       "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
174          this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
175       });
176
177    this->display->add_global_handler(
178       "ivi_controller", [this](wl_registry *r, uint32_t name, uint32_t v) {
179          this->controller = std::make_unique<genivi::controller>(r, name, v);
180
181          // Init controller hooks
182          this->controller->chooks = &this->chooks;
183
184          // XXX: This protocol needs the output, so lets just add our mapping
185          // here...
186          this->controller->add_proxy_to_id_mapping(
187             this->outputs.back()->proxy.get(),
188             wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
189                this->outputs.back()->proxy.get())));
190       });
191
192    // First level objects
193    this->display->roundtrip();
194    // Second level objects
195    this->display->roundtrip();
196    // Third level objects
197    this->display->roundtrip();
198
199    return init_layout();
200 }
201
202 int App::dispatch_events() {
203    int ret = this->display->dispatch();
204    if (ret == -1) {
205       logerror("wl_display_dipatch() returned error %d",
206                this->display->get_error());
207       return -1;
208    }
209    this->display->flush();
210
211    // execute pending tasks, that is layout changes etc.
212    this->execute_pending();
213
214    return 0;
215 }
216
217 //  _       _ _       _                         _    ____
218 // (_)_ __ (_) |_    | | __ _ _   _  ___  _   _| |_ / /\ \
219 // | | '_ \| | __|   | |/ _` | | | |/ _ \| | | | __| |  | |
220 // | | | | | | |_    | | (_| | |_| | (_) | |_| | |_| |  | |
221 // |_|_| |_|_|\__|___|_|\__,_|\__, |\___/ \__,_|\__| |  | |
222 //              |_____|       |___/                 \_\/_/
223 int App::init_layout() {
224    if (!this->controller) {
225       logerror("ivi_controller global not available");
226       return -1;
227    }
228
229    if (this->outputs.empty()) {
230       logerror("no output was set up!");
231       return -1;
232    }
233
234    auto &c = this->controller;
235
236    auto &o = this->outputs.front();
237    auto &s = c->screens.begin()->second;
238    auto &layers = c->layers;
239
240    // XXX: Write output dimensions to ivi controller...
241    c->output_size = genivi::size{uint32_t(o->width), uint32_t(o->height)};
242
243    // Clear scene
244    layers.clear();
245
246    // Clear screen
247    s->clear();
248
249    // Quick and dirty setup of layers
250    // XXX: This likely needs to be sorted by order (note, we don't (yet?)
251    // do any zorder arrangement).
252    for (auto const &i : this->layers.mapping) {
253       c->layer_create(i.layer_id, o->width, o->height);
254       auto &l = layers[i.layer_id];
255       l->set_destination_rectangle(0, 0, o->width, o->height);
256       l->set_visibility(1);
257       logdebug("Setting up layer %s (%d) for surfaces %d-%d", i.name.c_str(),
258                i.layer_id, i.id_min, i.id_max);
259    }
260
261    // Add layers to screen (XXX: are they sorted correctly?)
262    s->set_render_order(this->layers.layers);
263
264    c->commit_changes();
265
266    this->display->flush();
267
268    return 0;
269 }
270
271 void App::surface_set_layout(uint32_t surface_id) {
272    auto o_layer_id = this->layers.get_layer_id(surface_id);
273
274    if (!o_layer_id) {
275       logerror("Surface %d is not associated with any layer!", int(surface_id));
276       return;
277    }
278
279    if (!this->controller->surface_exists(surface_id)) {
280       logerror("Surface %d does not exist", int(surface_id));
281       return;
282    }
283
284    uint32_t layer_id = o_layer_id.value();
285
286    auto rect = this->layers.get_layer_rect(surface_id).value();
287    auto &s = this->controller->surfaces[surface_id];
288
289    int x = rect.x;
290    int y = rect.y;
291    int w = rect.w;
292    int h = rect.h;
293
294    // less-than-0 values refer to MAX + 1 - $VALUE
295    // e.g. MAX is either screen width or height
296    if (w < 0) {
297       w = this->controller->output_size.w + 1 + w;
298    }
299    if (h < 0) {
300       h = this->controller->output_size.h + 1 + h;
301    }
302    logdebug("Computed rect={ %d, %d, %d, %d }", x, y, w, h);
303
304    // configure surface to wxh dimensions
305    s->set_configuration(w, h);
306    // set destination to the display rectangle
307    s->set_destination_rectangle(x, y, w, h);
308
309    // XXX: visibility should be determined independently of our
310    //      layer + geometry setup.
311    s->set_visibility(1);
312    this->controller->layers[layer_id]->add_surface(s.get());
313
314    logdebug("Surface %u now on layer %u with rect { %d, %d, %d, %d }",
315             surface_id, layer_id, x, y, w, h);
316 }
317
318 char const *App::activate_surface(uint32_t surface_id) {
319    if (!this->controller->surface_exists(surface_id)) {
320       return "Surface does not exist";
321    }
322
323    // This shouild involve a policy check, but as we do not (yet) have
324    // such a thing, we will just switch to this surface.
325    // XXX: input focus missing!!1
326
327    // Make it visible, no (or little effect) if already visible
328    auto &s = this->controller->surfaces[surface_id];
329
330    // Set all others invisible
331    for (auto &i : this->controller->surfaces) {
332       auto &si = this->controller->sprops[i.second->id];
333       if (si.visibility == 1 && si.id != s->id &&
334           int(si.id) != this->layers.main_surface) {
335          i.second->set_visibility(0);
336       }
337    }
338    s->set_visibility(1);
339
340    // commit changes
341    this->controller->commit_changes();
342    this->display->flush();
343
344    // no error
345    return nullptr;
346 }
347
348 void App::add_task(char const *name, std::function<void()> &&f) {
349    this->pending.emplace_back(std::make_pair(name, f));
350 }
351
352 void App::execute_pending() {
353    if (!this->pending.empty()) {
354       for (auto &t : this->pending) {
355          logdebug("executing task '%s'", t.first);
356          t.second();
357       }
358       this->pending.clear();
359       this->controller->commit_changes();
360       this->display->flush();
361    }
362 }
363
364 //                      _          _   _____                 _
365 //  _ __  _ __ _____  _(_) ___  __| | | ____|_   _____ _ __ | |_ ___
366 // | '_ \| '__/ _ \ \/ / |/ _ \/ _` | |  _| \ \ / / _ \ '_ \| __/ __|
367 // | |_) | | | (_) >  <| |  __/ (_| | | |___ \ V /  __/ | | | |_\__ \
368 // | .__/|_|  \___/_/\_\_|\___|\__,_| |_____| \_/ \___|_| |_|\__|___/
369 // |_|
370 void App::surface_created(uint32_t surface_id) {
371    DB("surface_id is " << surface_id);
372
373    // We need to execute the surface setup after its creation.
374    this->add_task("surface_set_layout",
375                   [surface_id, this] { this->surface_set_layout(surface_id); });
376 }
377
378 void App::surface_removed(uint32_t surface_id) {
379    DB("surface_id is " << surface_id);
380 }
381
382 //  _     _           _ _                            _   _                 _
383 // | |__ (_)_ __   __| (_)_ __   __ _     __ _ _ __ (_) (_)_ __ ___  _ __ | |
384 // | '_ \| | '_ \ / _` | | '_ \ / _` |   / _` | '_ \| | | | '_ ` _ \| '_ \| |
385 // | |_) | | | | | (_| | | | | | (_| |  | (_| | |_) | | | | | | | | | |_) | |
386 // |_.__/|_|_| |_|\__,_|_|_| |_|\__, |___\__,_| .__/|_| |_|_| |_| |_| .__/|_|
387 //                              |___/_____|   |_|                   |_|
388 binding_api::result_type binding_api::register_surface(uint32_t appid,
389                                                        uint32_t surfid) {
390    logdebug("%s appid %u surfid %u", __func__, appid, surfid);
391    if (appid > 0xff) {
392       return Err<json_object *>("invalid appid");
393    }
394
395    if (surfid > 0xffff) {
396       return Err<json_object *>("invalid surfaceid");
397    }
398
399    return Ok(json_object_new_int((appid << 16) + surfid));
400 }
401
402 binding_api::result_type binding_api::debug_layers() {
403    logdebug("%s", __func__);
404    return Ok(json_tokener_parse(this->app->layers.to_json().dump().c_str()));
405 }
406
407 binding_api::result_type binding_api::debug_surfaces() {
408    logdebug("%s", __func__);
409    return Ok(to_json(this->app->controller->sprops));
410 }
411
412 binding_api::result_type binding_api::debug_status() {
413    logdebug("%s", __func__);
414    json_object *jr = json_object_new_object();
415    json_object_object_add(jr, "surfaces",
416                           to_json(this->app->controller->sprops));
417    json_object_object_add(jr, "layers", to_json(this->app->controller->lprops));
418    return Ok(jr);
419 }
420
421 binding_api::result_type binding_api::debug_terminate() {
422    logdebug("%s", __func__);
423    raise(SIGKILL);  // XXX afb-daemon kills it's pgroup using TERM, which
424                     // doesn't play well with perf
425    return Ok(json_object_new_object());
426 }
427
428 binding_api::result_type binding_api::demo_activate_surface(
429    uint32_t surfaceid) {
430    char const *e = this->app->activate_surface(surfaceid);
431    if (e) {
432       return Err<json_object *>(e);
433    }
434    return Ok(json_object_new_object());
435 }
436
437 binding_api::result_type binding_api::demo_activate_all() {
438    for (auto &s : this->app->controller->surfaces) {
439       s.second->set_visibility(1);
440    }
441    this->app->controller->commit_changes();
442    this->app->display->flush();
443    return Ok(json_object_new_object());
444 }
445
446 //                  _             _ _            _                 _
447 //   ___ ___  _ __ | |_ _ __ ___ | | | ___ _ __ | |__   ___   ___ | | _____
448 //  / __/ _ \| '_ \| __| '__/ _ \| | |/ _ \ '__|| '_ \ / _ \ / _ \| |/ / __|
449 // | (_| (_) | | | | |_| | | (_) | | |  __/ |   | | | | (_) | (_) |   <\__ \
450 //  \___\___/|_| |_|\__|_|  \___/|_|_|\___|_|___|_| |_|\___/ \___/|_|\_\___/
451 //                                         |_____|
452 void controller_hooks::surface_created(uint32_t surface_id) {
453    this->app->surface_created(surface_id);
454 }
455
456 void controller_hooks::surface_removed(uint32_t surface_id) {
457    this->app->surface_removed(surface_id);
458 }
459
460 void controller_hooks::add_task(char const *name, std::function<void()> &&f) {
461    this->app->add_task(name, std::move(f));
462 }
463
464 }  // namespace wm