App: be a little more thorough when activating a surface
[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    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<struct 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_layers();
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_layers() {
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 namespace {
272
273 // This can fix the HomeScreen...
274 void redraw_fix(App *app, std::unique_ptr<genivi::surface> &s, int x, int y, int w, int h) {
275    { // XXX: Work around weston redraw issues
276       // trigger an update by changing the source dimensions!
277       s->set_configuration(w + 1, h);
278       s->set_source_rectangle(0, 0, w + 1, h);
279       s->set_destination_rectangle(x, y, w + 1, h);
280       app->controller->commit_changes();
281       app->display->roundtrip();
282
283       // wait some time, for the process to do its thing...
284       using namespace std::chrono_literals;
285       std::this_thread::sleep_for(100ms);
286
287       // Set a different size then what we actually want.
288       s->set_configuration(w, h);
289       s->set_source_rectangle(0, 0, w, h);
290       s->set_destination_rectangle(x, y, w, h);
291       app->controller->commit_changes();
292       app->display->roundtrip();
293    }
294 }
295
296 }  // namespace
297
298 void App::surface_init_layout(uint32_t surface_id) {
299    if (!this->controller->surface_exists(surface_id)) {
300       logerror("Surface %d does not exist", int(surface_id));
301       return;
302    }
303
304    auto o_layer_id = this->layers.get_layer_id(surface_id);
305
306    if (!o_layer_id) {
307       logerror("Surface %d is not associated with any layer!", int(surface_id));
308       return;
309    }
310
311    uint32_t layer_id = o_layer_id.value();
312    logdebug("surface_set_layout for surface %u on layer %u", surface_id,
313             layer_id);
314
315    auto const &layer = this->layers.get_layer(layer_id);
316    auto rect = layer.value().rect;
317    auto &s = this->controller->surfaces[surface_id];
318
319    int x = rect.x;
320    int y = rect.y;
321    int w = rect.w;
322    int h = rect.h;
323
324    // less-than-0 values refer to MAX + 1 - $VALUE
325    // e.g. MAX is either screen width or height
326    if (w < 0) {
327       w = this->controller->output_size.w + 1 + w;
328    }
329    if (h < 0) {
330       h = this->controller->output_size.h + 1 + h;
331    }
332
333    // configure surface to wxh dimensions
334    s->set_configuration(w, h);
335
336    // set source reactangle, even if we should not need to set it.
337    s->set_source_rectangle(0, 0, w, h);
338
339    // set destination to the display rectangle
340    s->set_destination_rectangle(x, y, w, h);
341
342    s->set_visibility(0);
343    s->set_opacity(256);
344
345    this->controller->commit_changes();
346    this->display->roundtrip();
347
348    redraw_fix(this, s, x, y, w, h);
349
350    this->controller->layers[layer_id]->add_surface(s.get());
351
352    // activate the main_surface right away
353    if (surface_id == static_cast<unsigned>(this->layers.main_surface)) {
354       logdebug("Activating main_surface (%d)", surface_id);
355
356       this->activate_surface(this->lookup_name(surface_id).value_or("unknown-name").c_str());
357    }
358
359    logdebug("Surface %u now on layer %u with rect { %d, %d, %d, %d }",
360             surface_id, layer_id, x, y, w, h);
361 }
362
363 char const *App::activate_surface(char const *drawing_name) {
364    int surface_id = -1;
365
366    {
367       auto oid = this->lookup_id(drawing_name);
368       if (oid) {
369          surface_id = oid.value();
370       } else {
371          return "Surface does not exist";
372       }
373    }
374
375    if (!this->controller->surface_exists(surface_id)) {
376       return "Surface does not exist";
377    }
378
379    // This should involve a policy check, but as we do not (yet) have
380    // such a thing, we will just switch to this surface.
381    // XXX: input focus missing!!1
382
383    // Make it visible, no (or little effect) if already visible
384    auto &s = this->controller->surfaces[surface_id];
385
386    // Set all others invisible
387    for (auto &i : this->controller->surfaces) {
388       auto &si = this->controller->sprops[i.second->id];
389       if (si.visibility != 0 &&
390           int(si.id) != this->layers.main_surface) {
391          this->deactivate(i.second->id);
392       }
393    }
394    this->activate(s->id);
395
396    // commit changes
397    this->controller->commit_changes();
398    this->display->flush();
399
400    // no error
401    return nullptr;
402 }
403
404 char const *App::deactivate_surface(char const *drawing_name) {
405    int surface_id = -1;
406
407    {
408       auto oid = this->lookup_id(drawing_name);
409       if (oid) {
410          surface_id = oid.value();
411       } else {
412          return "Surface does not exist";
413       }
414    }
415
416    if (surface_id == this->layers.main_surface) {
417       return "Cannot deactivate main_surface";
418    }
419
420    this->deactivate(surface_id);
421
422    this->controller->commit_changes();
423    this->display->flush();
424
425    return nullptr;
426 }
427
428 //                      _          _   _____                 _
429 //  _ __  _ __ _____  _(_) ___  __| | | ____|_   _____ _ __ | |_ ___
430 // | '_ \| '__/ _ \ \/ / |/ _ \/ _` | |  _| \ \ / / _ \ '_ \| __/ __|
431 // | |_) | | | (_) >  <| |  __/ (_| | | |___ \ V /  __/ | | | |_\__ \
432 // | .__/|_|  \___/_/\_\_|\___|\__,_| |_____| \_/ \___|_| |_|\__|___/
433 // |_|
434 void App::surface_created(uint32_t surface_id) {
435    logdebug("surface_id is %u", surface_id);
436
437    this->surface_init_layout(surface_id);
438 }
439
440 void App::surface_removed(uint32_t surface_id) {
441    logdebug("surface_id is %u", surface_id);
442
443    this->id_alloc.remove_id(surface_id);
444 }
445
446 void App::emit_activated(char const *label) {
447    this->api.send_event("activated", label);
448 }
449
450 void App::emit_deactivated(char const *label) {
451    this->api.send_event("deactivated", label);
452 }
453
454 void App::emit_syncdraw(char const *label) {
455    this->api.send_event("syncdraw", label);
456 }
457
458 void App::emit_flushdraw(char const *label) {
459    this->api.send_event("syncdraw", label);
460 }
461
462 void App::emit_visible(char const *label, bool is_visible) {
463    this->api.send_event(is_visible ? "visible" : "invisible", label);
464 }
465
466 result<int> App::request_surface(char const *drawing_name) {
467    auto lid = this->layers.get_layer_id(std::string(drawing_name));
468    if (!lid) {
469       // XXX: to we need to put these applications on the App layer?
470       return Err<int>("Drawing name does not match any role");
471    }
472
473    auto rname = this->lookup_id(drawing_name);
474    if (!rname) {
475       // name does not exist yet, allocate surface id...
476       auto id = int(this->id_alloc.generate_id(drawing_name));
477       this->layers.add_surface(id, lid.value());
478
479       // XXX: we set the main_surface[_name] here and now,
480       // not sure if we want this, but it worked so far.
481       if (!this->layers.main_surface_name.empty() &&
482           this->layers.main_surface_name == drawing_name) {
483          this->layers.main_surface = id;
484          logdebug("Set main_surface id to %u", id);
485       }
486
487       return Ok<int>(id);
488    }
489
490    // Check currently registered drawing names if it is already there.
491    return Err<int>("Surface already present");
492 }
493
494 void App::activate(unsigned id) {
495    if (this->controller->sprops[id].visibility == 0) {
496       this->controller->surfaces[id]->set_visibility(1);
497       this->emit_activated(
498               this->lookup_name(id).value_or("unknown-name").c_str());
499    }
500 }
501
502 void App::deactivate(unsigned id) {
503    if (this->controller->sprops[id].visibility != 0) {
504       this->controller->surfaces[id]->set_visibility(0);
505       this->emit_deactivated(
506               this->lookup_name(id).value_or("unknown-name").c_str());
507    }
508 }
509
510 //  _     _           _ _                            _   _                 _
511 // | |__ (_)_ __   __| (_)_ __   __ _     __ _ _ __ (_) (_)_ __ ___  _ __ | |
512 // | '_ \| | '_ \ / _` | | '_ \ / _` |   / _` | '_ \| | | | '_ ` _ \| '_ \| |
513 // | |_) | | | | | (_| | | | | | (_| |  | (_| | |_) | | | | | | | | | |_) | |
514 // |_.__/|_|_| |_|\__,_|_|_| |_|\__, |___\__,_| .__/|_| |_|_| |_| |_| .__/|_|
515 //                              |___/_____|   |_|                   |_|
516 binding_api::result_type binding_api::request_surface(
517    char const *drawing_name) {
518    auto r = this->app->request_surface(drawing_name);
519    if (r.is_err()) {
520       return Err<json_object *>(r.unwrap_err());
521    }
522    return Ok(json_object_new_int(r.unwrap()));
523 }
524
525 binding_api::result_type binding_api::activate_surface(
526    char const *drawing_name) {
527    logdebug("%s drawing_name %s", __func__, drawing_name);
528    auto r = this->app->activate_surface(drawing_name);
529    if (r != nullptr) {
530       logdebug("%s failed with error: %s", __func__, r);
531       return Err<json_object *>(r);
532    }
533    return Ok(json_object_new_object());
534 }
535
536 binding_api::result_type binding_api::deactivate_surface(char const* drawing_name) {
537    logdebug("%s drawing_name %s", __func__, drawing_name);
538    auto r = this->app->deactivate_surface(drawing_name);
539    if (r != nullptr) {
540       logdebug("%s failed with error: %s", __func__, r);
541       return Err<json_object *>(r);
542    }
543    return Ok(json_object_new_object());
544 }
545
546 binding_api::result_type binding_api::enddraw(char const* drawing_name) {
547    logdebug("%s drawing_name %s", __func__, drawing_name);
548    return Err<json_object*>("not implemented");
549 }
550
551 binding_api::result_type binding_api::list_drawing_names() {
552    logdebug("%s", __func__);
553    json j = this->app->id_alloc.name2id;
554    return Ok(json_tokener_parse(j.dump().c_str()));
555 }
556
557 binding_api::result_type binding_api::debug_layers() {
558    logdebug("%s", __func__);
559    return Ok(json_tokener_parse(this->app->layers.to_json().dump().c_str()));
560 }
561
562 binding_api::result_type binding_api::debug_surfaces() {
563    logdebug("%s", __func__);
564    return Ok(to_json(this->app->controller->sprops));
565 }
566
567 binding_api::result_type binding_api::debug_status() {
568    logdebug("%s", __func__);
569    json_object *jr = json_object_new_object();
570    json_object_object_add(jr, "surfaces",
571                           to_json(this->app->controller->sprops));
572    json_object_object_add(jr, "layers", to_json(this->app->controller->lprops));
573    return Ok(jr);
574 }
575
576 binding_api::result_type binding_api::debug_terminate() {
577    logdebug("%s", __func__);
578    raise(SIGKILL);  // XXX afb-daemon kills it's pgroup using TERM, which
579                     // doesn't play well with perf
580    return Ok(json_object_new_object());
581 }
582
583 //                  _             _ _            _                 _
584 //   ___ ___  _ __ | |_ _ __ ___ | | | ___ _ __ | |__   ___   ___ | | _____
585 //  / __/ _ \| '_ \| __| '__/ _ \| | |/ _ \ '__|| '_ \ / _ \ / _ \| |/ / __|
586 // | (_| (_) | | | | |_| | | (_) | | |  __/ |   | | | | (_) | (_) |   <\__ \
587 //  \___\___/|_| |_|\__|_|  \___/|_|_|\___|_|___|_| |_|\___/ \___/|_|\_\___/
588 //                                         |_____|
589 void controller_hooks::surface_created(uint32_t surface_id) {
590    this->app->surface_created(surface_id);
591 }
592
593 void controller_hooks::surface_removed(uint32_t surface_id) {
594    this->app->surface_removed(surface_id);
595 }
596
597 }  // namespace wm