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