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