app: visibility setting work around... peak software enfineering right here!!1
[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      pending(),
132      name_mapping(),
133      id_alloc{},
134      last_active() {
135    assert(g_app == nullptr);
136    g_app = this;
137
138    try {
139       {
140          auto l = load_layer_map(
141             this->config.get_string("layers.json").value().c_str());
142          if (l.is_ok()) {
143             this->layers = l.unwrap();
144          } else {
145             logerror("%s", l.err().value());
146          }
147       }
148
149       {
150          auto l =
151             load_layout(this->config.get_string("layout.json").value().c_str());
152          if (l.is_ok()) {
153             this->layouts = l.unwrap();
154          } else {
155             logerror("%s", l.err().value());
156          }
157       }
158    } catch (std::exception &e) {
159       logerror("Loading of configuration failed: %s", e.what());
160    }
161 }
162
163 App::~App() { g_app = nullptr; }
164
165 int App::init() {
166    if (!this->display->ok()) {
167       return -1;
168    }
169
170    if (this->layers.mapping.empty()) {
171       logerror("No surface -> layer mapping loaded");
172       return -1;
173    }
174
175    this->display->add_global_handler(
176       "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
177          this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
178       });
179
180    this->display->add_global_handler(
181       "ivi_controller", [this](wl_registry *r, uint32_t name, uint32_t v) {
182          this->controller = std::make_unique<struct genivi::controller>(r, name, v);
183
184          // Init controller hooks
185          this->controller->chooks = &this->chooks;
186
187          // XXX: This protocol needs the output, so lets just add our mapping
188          // here...
189          this->controller->add_proxy_to_id_mapping(
190             this->outputs.back()->proxy.get(),
191             wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
192                this->outputs.back()->proxy.get())));
193       });
194
195    // First level objects
196    this->display->roundtrip();
197    // Second level objects
198    this->display->roundtrip();
199    // Third level objects
200    this->display->roundtrip();
201
202    return init_layout();
203 }
204
205 int App::dispatch_events() {
206    int ret = this->display->dispatch();
207    if (ret == -1) {
208       logerror("wl_display_dipatch() returned error %d",
209                this->display->get_error());
210       return -1;
211    }
212    this->display->flush();
213
214    // execute pending tasks, that is layout changes etc.
215    this->execute_pending();
216
217    return 0;
218 }
219
220 //  _       _ _       _                         _    ____
221 // (_)_ __ (_) |_    | | __ _ _   _  ___  _   _| |_ / /\ \
222 // | | '_ \| | __|   | |/ _` | | | |/ _ \| | | | __| |  | |
223 // | | | | | | |_    | | (_| | |_| | (_) | |_| | |_| |  | |
224 // |_|_| |_|_|\__|___|_|\__,_|\__, |\___/ \__,_|\__| |  | |
225 //              |_____|       |___/                 \_\/_/
226 int App::init_layout() {
227    if (!this->controller) {
228       logerror("ivi_controller global not available");
229       return -1;
230    }
231
232    if (this->outputs.empty()) {
233       logerror("no output was set up!");
234       return -1;
235    }
236
237    auto &c = this->controller;
238
239    auto &o = this->outputs.front();
240    auto &s = c->screens.begin()->second;
241    auto &layers = c->layers;
242
243    // XXX: Write output dimensions to ivi controller...
244    c->output_size = genivi::size{uint32_t(o->width), uint32_t(o->height)};
245
246    // Clear scene
247    layers.clear();
248
249    // Clear screen
250    s->clear();
251
252    // Quick and dirty setup of layers
253    // XXX: This likely needs to be sorted by order (note, we don't (yet?)
254    // do any zorder arrangement).
255    for (auto const &i : this->layers.mapping) {
256       c->layer_create(i.layer_id, o->width, o->height);
257       auto &l = layers[i.layer_id];
258       l->set_destination_rectangle(0, 0, o->width, o->height);
259       l->set_visibility(1);
260       logdebug("Setting up layer %s (%d) for surfaces %d-%d", i.name.c_str(),
261                i.layer_id, i.id_min, i.id_max);
262    }
263
264    // Add layers to screen (XXX: are they sorted correctly?)
265    s->set_render_order(this->layers.layers);
266
267    c->commit_changes();
268
269    this->display->flush();
270
271    return 0;
272 }
273
274 void App::surface_set_layout(uint32_t surface_id) {
275    if (!this->controller->surface_exists(surface_id)) {
276       logerror("Surface %d does not exist", int(surface_id));
277       return;
278    }
279
280    auto o_layer_id = this->layers.get_layer_id(surface_id);
281
282    if (!o_layer_id) {
283       logerror("Surface %d is not associated with any layer!", int(surface_id));
284       return;
285    }
286
287    uint32_t layer_id = o_layer_id.value();
288    logdebug("surface_set_layout for surface %u on layer %u", surface_id,
289             layer_id);
290
291    auto const &layer = this->layers.get_layer(layer_id);
292    auto rect = layer.value().rect;
293    auto &s = this->controller->surfaces[surface_id];
294
295    int x = rect.x;
296    int y = rect.y;
297    int w = rect.w;
298    int h = rect.h;
299
300    // less-than-0 values refer to MAX + 1 - $VALUE
301    // e.g. MAX is either screen width or height
302    if (w < 0) {
303       w = this->controller->output_size.w + 1 + w;
304    }
305    if (h < 0) {
306       h = this->controller->output_size.h + 1 + h;
307    }
308
309    // configure surface to wxh dimensions
310    s->set_configuration(w, h);
311    // set source reactangle, even if we should not need to set it.
312    s->set_source_rectangle(0, 0, w, h);
313    // set destination to the display rectangle
314    s->set_destination_rectangle(x, y, w, h);
315
316    // XXX: The main_surface will be visible regardless
317    //s->set_visibility(
318    //   surface_id == static_cast<unsigned>(this->layers.main_surface) ? 1 : 0);
319    this->controller->layers[layer_id]->add_surface(s.get());
320
321    if (surface_id == static_cast<unsigned>(this->layers.main_surface)) {
322       logdebug("Activating main_surface (%d)", surface_id);
323       this->activate_surface(surface_id);
324    }
325
326    logdebug("Surface %u now on layer %u with rect { %d, %d, %d, %d }",
327             surface_id, layer_id, x, y, w, h);
328 }
329
330 char const *App::activate_surface(uint32_t surface_id) {
331    if (!this->controller->surface_exists(surface_id)) {
332       return "Surface does not exist";
333    }
334
335    // This should involve a policy check, but as we do not (yet) have
336    // such a thing, we will just switch to this surface.
337    // XXX: input focus missing!!1
338
339    // Make it visible, no (or little effect) if already visible
340    auto &s = this->controller->surfaces[surface_id];
341
342    // Set all others invisible
343    for (auto &i : this->controller->surfaces) {
344       auto &si = this->controller->sprops[i.second->id];
345       if (si.id != s->id && int(si.id) != this->layers.main_surface) {
346          i.second->set_visibility(0);
347       }
348    }
349    s->set_visibility(1);
350
351    // commit changes
352    this->controller->commit_changes();
353    this->display->flush();
354
355    auto set_vis = [&s, this](int id, int vis) {
356       using namespace std::chrono_literals;
357
358       std::this_thread::sleep_for(100ms);
359       s->set_visibility(vis);
360       this->controller->commit_changes();
361       this->display->roundtrip();
362    };
363    set_vis(s->id, 0);
364    set_vis(s->id, 1);
365
366    // Current active surface is the first in last_active
367    this->last_active.push_front(s->id);
368    /// // XXX: I am not sure I even need 5 elements...
369    /// this->last_active.resize(std::min(int(this->last_active.size()), 5));
370
371    // no error
372    return nullptr;
373 }
374
375 char const *App::deactivate_surface(uint32_t surface_id) {
376    if (surface_id == this->layers.main_surface) {
377       return "Cannot deactivate main_surface";
378    }
379
380    if (this->last_active.empty()) {
381       return "Cannot deactivate surface (not active)";
382    }
383
384    // XXX: should an active surface not alsways be front() or
385    // front+1() of last_active?!
386
387    // XXX: Should I really be able to deactivate a surface that is not
388    // front() of last_active?
389    auto is = std::find(this->last_active.begin(),
390                        this->last_active.end(),
391                        surface_id);
392
393    if (is == this->last_active.end()) {
394       return "Cannot deactivate surface (not active)";
395    }
396
397    this->last_active.erase(is);
398
399    if (! this->last_active.empty()) {
400       // Should be active already, shouldn't it?
401       this->activate_surface(this->last_active.front());
402    } else {
403       this->activate_surface(this->layers.main_surface);
404    }
405
406    return nullptr;
407 }
408
409 void App::add_task(char const *name, std::function<void()> &&f) {
410    this->pending.emplace_back(std::make_pair(name, f));
411 }
412
413 void App::execute_pending() {
414    if (!this->pending.empty()) {
415       for (auto &t : this->pending) {
416          logdebug("executing task '%s'", t.first);
417          t.second();
418       }
419       this->pending.clear();
420       this->controller->commit_changes();
421       this->display->flush();
422    }
423 }
424
425 //                      _          _   _____                 _
426 //  _ __  _ __ _____  _(_) ___  __| | | ____|_   _____ _ __ | |_ ___
427 // | '_ \| '__/ _ \ \/ / |/ _ \/ _` | |  _| \ \ / / _ \ '_ \| __/ __|
428 // | |_) | | | (_) >  <| |  __/ (_| | | |___ \ V /  __/ | | | |_\__ \
429 // | .__/|_|  \___/_/\_\_|\___|\__,_| |_____| \_/ \___|_| |_|\__|___/
430 // |_|
431 void App::surface_created(uint32_t surface_id) {
432    //surface_id >>= id_allocator::id_shift;
433
434    logdebug("surface_id is %u", surface_id);
435
436    // We need to execute the surface setup after its creation.
437    this->add_task("surface_set_layout",
438                   [surface_id, this] { this->surface_set_layout(surface_id); });
439 }
440
441 void App::surface_removed(uint32_t surface_id) {
442    //surface_id >>= id_allocator::id_shift;
443
444    logdebug("surface_id is %u", surface_id);
445
446    this->add_task("remove surface ID",
447                   [surface_id, this] {
448                      this->id_alloc.remove_id(surface_id);
449
450                      // Also remove from last_active, if found
451                      auto i = std::find(this->last_active.begin(),
452                                         this->last_active.end(), surface_id);
453                      if (i != this->last_active.end()) {
454                         this->last_active.erase(i);
455                      }
456                   });
457 }
458
459 void App::emit_activated(char const *label) {
460    this->api.send_event("activated", json_object_new_string(label));
461 }
462
463 void App::emit_deactivated(char const *label) {
464    this->api.send_event("deactivated", json_object_new_string(label));
465 }
466
467 void App::emit_syncdraw(char const *label) {
468    this->api.send_event("syncdraw", json_object_new_string(label));
469 }
470
471 void App::emit_visible(char const *label, bool is_visible) {
472    this->api.send_event(is_visible ? "visible" : "invisible", json_object_new_string(label));
473 }
474
475 result<int> App::request_surface(char const *drawing_name) {
476    auto lid = this->layers.get_layer_id(std::string(drawing_name));
477    if (!lid) {
478       // XXX: to we need to put these applications on the App layer?
479       return Err<int>("Drawing name does not match any role");
480    }
481
482    auto rname = this->id_alloc.lookup(drawing_name);
483    if (!rname) {
484       // name does not exist yet, allocate surface id...
485       auto id = int(this->id_alloc.generate_id(drawing_name));
486       this->layers.add_surface(id, lid.value());
487
488       // XXX: you should fix this!
489       if (!this->layers.main_surface_name.empty() &&
490           this->layers.main_surface_name == drawing_name) {
491          this->layers.main_surface = id;
492          this->activate_surface(id);
493          logdebug("Set main_surface id to %u", id);
494       }
495
496       return Ok<int>(id);
497    }
498
499    // Check currently registered drawing names if it is already there.
500    return Err<int>("Surface already present");
501 }
502
503 char const *App::activate_surface(char const *drawing_name) {
504    auto osid = this->id_alloc.lookup(drawing_name);
505
506    if (osid) {
507       logdebug("ativate surface with name %s and id %u", drawing_name,
508                osid.value());
509       auto ret = this->activate_surface(osid.value());
510       if (!ret) {
511          this->emit_activated(drawing_name);
512       }
513       return ret;
514    }
515
516    logerror("surface %s unknown", drawing_name);
517    return "Surface unknown";
518 }
519
520 char const *App::deactivate_surface(char const *drawing_name) {
521    auto osid = this->id_alloc.lookup(drawing_name);
522
523    if (osid) {
524       logdebug("deativate surface with name %s and id %u", drawing_name,
525                osid.value());
526       return this->deactivate_surface(osid.value());
527    }
528
529    logerror("surface %s unknown", drawing_name);
530    return "Surface unknown";
531 }
532
533 //  _     _           _ _                            _   _                 _
534 // | |__ (_)_ __   __| (_)_ __   __ _     __ _ _ __ (_) (_)_ __ ___  _ __ | |
535 // | '_ \| | '_ \ / _` | | '_ \ / _` |   / _` | '_ \| | | | '_ ` _ \| '_ \| |
536 // | |_) | | | | | (_| | | | | | (_| |  | (_| | |_) | | | | | | | | | |_) | |
537 // |_.__/|_|_| |_|\__,_|_|_| |_|\__, |___\__,_| .__/|_| |_|_| |_| |_| .__/|_|
538 //                              |___/_____|   |_|                   |_|
539 binding_api::result_type binding_api::request_surface(
540    char const *drawing_name) {
541    auto r = this->app->request_surface(drawing_name);
542    if (r.is_err()) {
543       return Err<json_object *>(r.unwrap_err());
544    }
545    return Ok(json_object_new_int(r.unwrap()));
546 }
547
548 binding_api::result_type binding_api::activate_surface(
549    char const *drawing_name) {
550    logdebug("%s drawing_name %s", __func__, drawing_name);
551    auto r = this->app->activate_surface(drawing_name);
552    if (r != nullptr) {
553       return Err<json_object *>(r);
554    }
555    return Ok(json_object_new_object());
556 }
557
558 binding_api::result_type binding_api::deactivate_surface(char const* drawing_name) {
559    logdebug("%s drawing_name %s", __func__, drawing_name);
560    auto r = this->app->deactivate_surface(drawing_name);
561    if (r != nullptr) {
562       return Err<json_object *>(r);
563    }
564    return Ok(json_object_new_object());
565 }
566
567 binding_api::result_type binding_api::enddraw(char const* drawing_name) {
568    logdebug("%s drawing_name %s", __func__, drawing_name);
569    return Err<json_object*>("not implemented");
570 }
571
572 binding_api::result_type binding_api::list_drawing_names() {
573    logdebug("%s", __func__);
574    json j = this->app->id_alloc.names;
575    return Ok(json_tokener_parse(j.dump().c_str()));
576 }
577
578 binding_api::result_type binding_api::debug_layers() {
579    logdebug("%s", __func__);
580    return Ok(json_tokener_parse(this->app->layers.to_json().dump().c_str()));
581 }
582
583 binding_api::result_type binding_api::debug_surfaces() {
584    logdebug("%s", __func__);
585    return Ok(to_json(this->app->controller->sprops));
586 }
587
588 binding_api::result_type binding_api::debug_status() {
589    logdebug("%s", __func__);
590    json_object *jr = json_object_new_object();
591    json_object_object_add(jr, "surfaces",
592                           to_json(this->app->controller->sprops));
593    json_object_object_add(jr, "layers", to_json(this->app->controller->lprops));
594    return Ok(jr);
595 }
596
597 binding_api::result_type binding_api::debug_terminate() {
598    logdebug("%s", __func__);
599    raise(SIGKILL);  // XXX afb-daemon kills it's pgroup using TERM, which
600                     // doesn't play well with perf
601    return Ok(json_object_new_object());
602 }
603
604 binding_api::result_type binding_api::demo_activate_surface(
605    uint32_t surfaceid) {
606    char const *e = this->app->activate_surface(surfaceid);
607    if (e != nullptr) {
608       return Err<json_object *>(e);
609    }
610    return Ok(json_object_new_object());
611 }
612
613 binding_api::result_type binding_api::demo_activate_all() {
614    for (auto &s : this->app->controller->surfaces) {
615       s.second->set_visibility(1);
616    }
617    this->app->controller->commit_changes();
618    this->app->display->flush();
619    return Ok(json_object_new_object());
620 }
621
622 //                  _             _ _            _                 _
623 //   ___ ___  _ __ | |_ _ __ ___ | | | ___ _ __ | |__   ___   ___ | | _____
624 //  / __/ _ \| '_ \| __| '__/ _ \| | |/ _ \ '__|| '_ \ / _ \ / _ \| |/ / __|
625 // | (_| (_) | | | | |_| | | (_) | | |  __/ |   | | | | (_) | (_) |   <\__ \
626 //  \___\___/|_| |_|\__|_|  \___/|_|_|\___|_|___|_| |_|\___/ \___/|_|\_\___/
627 //                                         |_____|
628 void controller_hooks::surface_created(uint32_t surface_id) {
629    this->app->surface_created(surface_id);
630 }
631
632 void controller_hooks::surface_removed(uint32_t surface_id) {
633    this->app->surface_removed(surface_id);
634 }
635
636 void controller_hooks::add_task(char const *name, std::function<void()> &&f) {
637    this->app->add_task(name, std::move(f));
638 }
639
640 }  // namespace wm