App: cleanup name/id mapping and its reverse
[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 <thread>
36 #include <json.hpp>
37
38 namespace wm {
39
40 namespace {
41 App *g_app;
42
43 using json = nlohmann::json;
44
45 struct wm::area area_from_json(json const &j) {
46    return wm::area{
47       j["name"],
48       {
49          j["width"], j["height"], j["x"], j["y"],
50       },
51       j["zorder"],
52    };
53 }
54
55 result<struct layout> layout_from_json(json const &j) {
56    auto &ja = j["areas"];
57
58    auto l = layout{j["name"], uint32_t(ja.size()), {}};
59
60    if (ja.size() > layout::MAX_N_AREAS) {
61       return Err<struct layout>("Invalid number of areas in layout");
62    }
63
64    logdebug("Loading layout '%s' with %u areas", l.name.c_str(),
65             unsigned(ja.size()));
66
67    std::transform(std::cbegin(ja), std::cend(ja), std::begin(l.areas),
68                   area_from_json);
69
70    return Ok(l);
71 }
72
73 result<json> file_to_json(char const *filename) {
74    std::ifstream i(filename);
75    if (i.fail()) {
76       return Err<json>("Could not open config file");
77    }
78    json j;
79    i >> j;
80    return Ok(j);
81 }
82
83 // Will throw if parsing fails
84 struct result<layouts_type> load_layout(char const *filename) {
85    logdebug("loading layout from %s", filename);
86
87    auto j = file_to_json(filename);
88    if (j.is_err()) {
89       return Err<layouts_type>(j.unwrap_err());
90    }
91    json jlayouts = j.unwrap();
92
93    auto layouts = layouts_type();
94    layouts.reserve(jlayouts.size());
95    std::transform(std::cbegin(jlayouts), std::cend(jlayouts),
96                   std::back_inserter(layouts), layout_from_json);
97
98    return Ok(layouts);
99 }
100
101 struct result<layer_map>
102    load_layer_map(char const *filename) {
103    logdebug("loading IDs from %s", filename);
104
105    auto j = file_to_json(filename);
106    if (j.is_err()) {
107       return Err<layer_map>(j.unwrap_err());
108    }
109    json jids = j.unwrap();
110
111    return to_layer_map(jids);
112 }
113
114 }  // namespace
115
116 //       _                    _                  _                 _
117 //   ___| | __ _ ___ ___     / \   _ __  _ __   (_)_ __ ___  _ __ | |
118 //  / __| |/ _` / __/ __|   / _ \ | '_ \| '_ \  | | '_ ` _ \| '_ \| |
119 // | (__| | (_| \__ \__ \  / ___ \| |_) | |_) | | | | | | | | |_) | |
120 //  \___|_|\__,_|___/___/ /_/   \_\ .__/| .__/  |_|_| |_| |_| .__/|_|
121 //                                |_|   |_|                 |_|
122 App::App(wl::display *d)
123    : api{this},
124      chooks{this},
125      display{d},
126      controller{},
127      outputs(),
128      config(),
129      layouts(),
130      layers(),
131      id_alloc{},
132      last_active() {
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<struct 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 namespace {
273
274 // This can fix the HomeScreen...
275 void redraw_fix(App *app, std::unique_ptr<genivi::surface> &s, int x, int y, int w, int h) {
276    { // XXX: Work around weston redraw issues
277       // trigger an update by changing the source dimensions!
278       s->set_configuration(w, h);
279       s->set_source_rectangle(0, 0, w, h);
280       s->set_destination_rectangle(x, y, w, h);
281       app->controller->commit_changes();
282       app->display->roundtrip();
283
284       // wait some time, for the process to do its thing...
285       using namespace std::chrono_literals;
286       std::this_thread::sleep_for(100ms);
287
288       // Set a different size then what we actually want.
289       s->set_configuration(w + 1, h);
290       s->set_source_rectangle(0, 0, w + 1, h);
291       s->set_destination_rectangle(x, y, w + 1, h);
292       app->controller->commit_changes();
293       app->display->roundtrip();
294
295       std::this_thread::sleep_for(100ms);
296    }
297 }
298
299 }  // namespace
300
301 void App::surface_set_layout(uint32_t surface_id) {
302    if (!this->controller->surface_exists(surface_id)) {
303       logerror("Surface %d does not exist", int(surface_id));
304       return;
305    }
306
307    auto o_layer_id = this->layers.get_layer_id(surface_id);
308
309    if (!o_layer_id) {
310       logerror("Surface %d is not associated with any layer!", int(surface_id));
311       return;
312    }
313
314    uint32_t layer_id = o_layer_id.value();
315    logdebug("surface_set_layout for surface %u on layer %u", surface_id,
316             layer_id);
317
318    auto const &layer = this->layers.get_layer(layer_id);
319    auto rect = layer.value().rect;
320    auto &s = this->controller->surfaces[surface_id];
321
322    int x = rect.x;
323    int y = rect.y;
324    int w = rect.w;
325    int h = rect.h;
326
327    // less-than-0 values refer to MAX + 1 - $VALUE
328    // e.g. MAX is either screen width or height
329    if (w < 0) {
330       w = this->controller->output_size.w + 1 + w;
331    }
332    if (h < 0) {
333       h = this->controller->output_size.h + 1 + h;
334    }
335
336    redraw_fix(this, s, x, y, w, h);
337
338    // configure surface to wxh dimensions
339    s->set_configuration(w, h);
340
341    // set source reactangle, even if we should not need to set it.
342    s->set_source_rectangle(0, 0, w, h);
343
344    // set destination to the display rectangle
345    s->set_destination_rectangle(x, y, w, h);
346
347    s->set_visibility(0);
348    s->set_opacity(256);
349
350    this->controller->commit_changes();
351    this->display->roundtrip();
352
353    this->controller->layers[layer_id]->add_surface(s.get());
354
355    // activate the main_surface right away
356    if (surface_id == static_cast<unsigned>(this->layers.main_surface)) {
357       logdebug("Activating main_surface (%d)", surface_id);
358
359       this->activate_surface(this->lookup_name(surface_id).value_or("unknown-name").c_str());
360    }
361
362    logdebug("Surface %u now on layer %u with rect { %d, %d, %d, %d }",
363             surface_id, layer_id, x, y, w, h);
364 }
365
366 char const *App::activate_surface(char const *drawing_name) {
367    int surface_id = -1;
368
369    {
370       auto oid = this->lookup_id(drawing_name);
371       if (oid) {
372          surface_id = oid.value();
373       } else {
374          return "Surface does not exist";
375       }
376    }
377
378    if (!this->controller->surface_exists(surface_id)) {
379       return "Surface does not exist";
380    }
381
382    // This should involve a policy check, but as we do not (yet) have
383    // such a thing, we will just switch to this surface.
384    // XXX: input focus missing!!1
385
386    // Make it visible, no (or little effect) if already visible
387    auto &s = this->controller->surfaces[surface_id];
388
389    // Set all others invisible
390    for (auto &i : this->controller->surfaces) {
391       auto &si = this->controller->sprops[i.second->id];
392       if (int(si.id) != this->layers.main_surface) {
393          i.second->set_visibility(0);
394          this->controller->commit_changes();
395          this->display->flush();
396       }
397    }
398    s->set_visibility(1);
399
400    // commit changes
401    this->controller->commit_changes();
402    this->display->flush();
403
404    // Current active surface is the first in last_active
405    this->last_active.push_front(s->id);
406    /// // XXX: I am not sure I even need 5 elements...
407    /// this->last_active.resize(std::min(int(this->last_active.size()), 5));
408
409    // no error
410    return nullptr;
411 }
412
413 char const *App::deactivate_surface(char const *drawing_name) {
414    int surface_id = -1;
415
416    {
417       auto oid = this->lookup_id(drawing_name);
418       if (oid) {
419          surface_id = oid.value();
420       } else {
421          return "Surface does not exist";
422       }
423    }
424
425    if (surface_id == this->layers.main_surface) {
426       return "Cannot deactivate main_surface";
427    }
428
429    if (this->last_active.empty()) {
430       return "Cannot deactivate surface (not active)";
431    }
432
433    // XXX: should an active surface not alsways be front() or
434    // front+1() of last_active?!
435
436    // XXX: Should I really be able to deactivate a surface that is not
437    // front() of last_active?
438    auto is = std::find(this->last_active.begin(),
439                        this->last_active.end(),
440                        surface_id);
441
442    if (is == this->last_active.end()) {
443       return "Cannot deactivate surface (not active)";
444    }
445
446    this->last_active.erase(is);
447
448    if (! this->last_active.empty()) {
449       // Should be active already, shouldn't it?
450       this->activate_surface(this->lookup_name(this->last_active.front()).value_or("unknown-name").c_str());
451    } else {
452       this->activate_surface(this->layers.main_surface_name.c_str());
453    }
454
455    return nullptr;
456 }
457
458 //                      _          _   _____                 _
459 //  _ __  _ __ _____  _(_) ___  __| | | ____|_   _____ _ __ | |_ ___
460 // | '_ \| '__/ _ \ \/ / |/ _ \/ _` | |  _| \ \ / / _ \ '_ \| __/ __|
461 // | |_) | | | (_) >  <| |  __/ (_| | | |___ \ V /  __/ | | | |_\__ \
462 // | .__/|_|  \___/_/\_\_|\___|\__,_| |_____| \_/ \___|_| |_|\__|___/
463 // |_|
464 void App::surface_created(uint32_t surface_id) {
465    //surface_id >>= id_allocator::id_shift;
466
467    logdebug("surface_id is %u", surface_id);
468
469    this->surface_set_layout(surface_id);
470 }
471
472 void App::surface_removed(uint32_t surface_id) {
473    //surface_id >>= id_allocator::id_shift;
474
475    logdebug("surface_id is %u", surface_id);
476
477    this->id_alloc.remove_id(surface_id);
478
479    // Also remove from last_active, if found
480    auto i = std::find(this->last_active.begin(),
481                       this->last_active.end(), surface_id);
482    if (i != this->last_active.end()) {
483       this->last_active.erase(i);
484    }
485 }
486
487 void App::emit_activated(char const *label) {
488    this->api.send_event("activated", label);
489 }
490
491 void App::emit_deactivated(char const *label) {
492    this->api.send_event("deactivated", label);
493 }
494
495 void App::emit_syncdraw(char const *label) {
496    this->api.send_event("syncdraw", label);
497 }
498
499 void App::emit_flushdraw(char const *label) {
500    this->api.send_event("syncdraw", label);
501 }
502
503 void App::emit_visible(char const *label, bool is_visible) {
504    this->api.send_event(is_visible ? "visible" : "invisible", label);
505 }
506
507 result<int> App::request_surface(char const *drawing_name) {
508    auto lid = this->layers.get_layer_id(std::string(drawing_name));
509    if (!lid) {
510       // XXX: to we need to put these applications on the App layer?
511       return Err<int>("Drawing name does not match any role");
512    }
513
514    auto rname = this->id_alloc.lookup(drawing_name);
515    if (!rname) {
516       // name does not exist yet, allocate surface id...
517       auto id = int(this->id_alloc.generate_id(drawing_name));
518       this->layers.add_surface(id, lid.value());
519
520       // XXX: you should fix this!
521       if (!this->layers.main_surface_name.empty() &&
522           this->layers.main_surface_name == drawing_name) {
523          this->layers.main_surface = id;
524          this->activate_surface(drawing_name);
525          logdebug("Set main_surface id to %u", id);
526       }
527
528       return Ok<int>(id);
529    }
530
531    // Check currently registered drawing names if it is already there.
532    return Err<int>("Surface already present");
533 }
534
535 //  _     _           _ _                            _   _                 _
536 // | |__ (_)_ __   __| (_)_ __   __ _     __ _ _ __ (_) (_)_ __ ___  _ __ | |
537 // | '_ \| | '_ \ / _` | | '_ \ / _` |   / _` | '_ \| | | | '_ ` _ \| '_ \| |
538 // | |_) | | | | | (_| | | | | | (_| |  | (_| | |_) | | | | | | | | | |_) | |
539 // |_.__/|_|_| |_|\__,_|_|_| |_|\__, |___\__,_| .__/|_| |_|_| |_| |_| .__/|_|
540 //                              |___/_____|   |_|                   |_|
541 binding_api::result_type binding_api::request_surface(
542    char const *drawing_name) {
543    auto r = this->app->request_surface(drawing_name);
544    if (r.is_err()) {
545       return Err<json_object *>(r.unwrap_err());
546    }
547    return Ok(json_object_new_int(r.unwrap()));
548 }
549
550 binding_api::result_type binding_api::activate_surface(
551    char const *drawing_name) {
552    logdebug("%s drawing_name %s", __func__, drawing_name);
553    auto r = this->app->activate_surface(drawing_name);
554    if (r != nullptr) {
555       return Err<json_object *>(r);
556    }
557    return Ok(json_object_new_object());
558 }
559
560 binding_api::result_type binding_api::deactivate_surface(char const* drawing_name) {
561    logdebug("%s drawing_name %s", __func__, drawing_name);
562    auto r = this->app->deactivate_surface(drawing_name);
563    if (r != nullptr) {
564       return Err<json_object *>(r);
565    }
566    return Ok(json_object_new_object());
567 }
568
569 binding_api::result_type binding_api::enddraw(char const* drawing_name) {
570    logdebug("%s drawing_name %s", __func__, drawing_name);
571    return Err<json_object*>("not implemented");
572 }
573
574 binding_api::result_type binding_api::list_drawing_names() {
575    logdebug("%s", __func__);
576    json j = this->app->id_alloc.name2id;
577    return Ok(json_tokener_parse(j.dump().c_str()));
578 }
579
580 binding_api::result_type binding_api::debug_layers() {
581    logdebug("%s", __func__);
582    return Ok(json_tokener_parse(this->app->layers.to_json().dump().c_str()));
583 }
584
585 binding_api::result_type binding_api::debug_surfaces() {
586    logdebug("%s", __func__);
587    return Ok(to_json(this->app->controller->sprops));
588 }
589
590 binding_api::result_type binding_api::debug_status() {
591    logdebug("%s", __func__);
592    json_object *jr = json_object_new_object();
593    json_object_object_add(jr, "surfaces",
594                           to_json(this->app->controller->sprops));
595    json_object_object_add(jr, "layers", to_json(this->app->controller->lprops));
596    return Ok(jr);
597 }
598
599 binding_api::result_type binding_api::debug_terminate() {
600    logdebug("%s", __func__);
601    raise(SIGKILL);  // XXX afb-daemon kills it's pgroup using TERM, which
602                     // doesn't play well with perf
603    return Ok(json_object_new_object());
604 }
605
606 binding_api::result_type binding_api::demo_activate_surface(uint32_t s) {
607    return Err<json_object *>("not implemented");
608 }
609
610 binding_api::result_type binding_api::demo_activate_all() {
611    return Err<json_object *>("not implemented");
612 }
613
614 //                  _             _ _            _                 _
615 //   ___ ___  _ __ | |_ _ __ ___ | | | ___ _ __ | |__   ___   ___ | | _____
616 //  / __/ _ \| '_ \| __| '__/ _ \| | |/ _ \ '__|| '_ \ / _ \ / _ \| |/ / __|
617 // | (_| (_) | | | | |_| | | (_) | | |  __/ |   | | | | (_) | (_) |   <\__ \
618 //  \___\___/|_| |_|\__|_|  \___/|_|_|\___|_|___|_| |_|\___/ \___/|_|\_\___/
619 //                                         |_____|
620 void controller_hooks::surface_created(uint32_t surface_id) {
621    this->app->surface_created(surface_id);
622 }
623
624 void controller_hooks::surface_removed(uint32_t surface_id) {
625    this->app->surface_removed(surface_id);
626 }
627
628 }  // namespace wm