app: workaround for visibility setting; use system()
[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(200ms);
359       char *buf;
360       asprintf(&buf, "LayerManagerControl set surface %d visibility %d", id, vis);
361       //system("LayerManagerControl get scene");
362       //system("sleep 0.1");
363       system(buf);
364
365       //s->set_visibility(vis);
366       //this->controller->commit_changes();
367       //this->display->roundtrip();
368    };
369    set_vis(s->id, 0);
370    set_vis(s->id, 1);
371
372    // Current active surface is the first in last_active
373    this->last_active.push_front(s->id);
374    /// // XXX: I am not sure I even need 5 elements...
375    /// this->last_active.resize(std::min(int(this->last_active.size()), 5));
376
377    // no error
378    return nullptr;
379 }
380
381 char const *App::deactivate_surface(uint32_t surface_id) {
382    if (surface_id == this->layers.main_surface) {
383       return "Cannot deactivate main_surface";
384    }
385
386    if (this->last_active.empty()) {
387       return "Cannot deactivate surface (not active)";
388    }
389
390    // XXX: should an active surface not alsways be front() or
391    // front+1() of last_active?!
392
393    // XXX: Should I really be able to deactivate a surface that is not
394    // front() of last_active?
395    auto is = std::find(this->last_active.begin(),
396                        this->last_active.end(),
397                        surface_id);
398
399    if (is == this->last_active.end()) {
400       return "Cannot deactivate surface (not active)";
401    }
402
403    this->last_active.erase(is);
404
405    if (! this->last_active.empty()) {
406       // Should be active already, shouldn't it?
407       this->activate_surface(this->last_active.front());
408    } else {
409       this->activate_surface(this->layers.main_surface);
410    }
411
412    return nullptr;
413 }
414
415 void App::add_task(char const *name, std::function<void()> &&f) {
416    this->pending.emplace_back(std::make_pair(name, f));
417 }
418
419 void App::execute_pending() {
420    if (!this->pending.empty()) {
421       for (auto &t : this->pending) {
422          logdebug("executing task '%s'", t.first);
423          t.second();
424       }
425       this->pending.clear();
426       this->controller->commit_changes();
427       this->display->flush();
428    }
429 }
430
431 //                      _          _   _____                 _
432 //  _ __  _ __ _____  _(_) ___  __| | | ____|_   _____ _ __ | |_ ___
433 // | '_ \| '__/ _ \ \/ / |/ _ \/ _` | |  _| \ \ / / _ \ '_ \| __/ __|
434 // | |_) | | | (_) >  <| |  __/ (_| | | |___ \ V /  __/ | | | |_\__ \
435 // | .__/|_|  \___/_/\_\_|\___|\__,_| |_____| \_/ \___|_| |_|\__|___/
436 // |_|
437 void App::surface_created(uint32_t surface_id) {
438    //surface_id >>= id_allocator::id_shift;
439
440    logdebug("surface_id is %u", surface_id);
441
442    // We need to execute the surface setup after its creation.
443    this->add_task("surface_set_layout",
444                   [surface_id, this] { this->surface_set_layout(surface_id); });
445 }
446
447 void App::surface_removed(uint32_t surface_id) {
448    //surface_id >>= id_allocator::id_shift;
449
450    logdebug("surface_id is %u", surface_id);
451
452    this->add_task("remove surface ID",
453                   [surface_id, this] {
454                      this->id_alloc.remove_id(surface_id);
455
456                      // Also remove from last_active, if found
457                      auto i = std::find(this->last_active.begin(),
458                                         this->last_active.end(), surface_id);
459                      if (i != this->last_active.end()) {
460                         this->last_active.erase(i);
461                      }
462                   });
463 }
464
465 void App::emit_activated(char const *label) {
466    this->api.send_event("activated", json_object_new_string(label));
467 }
468
469 void App::emit_deactivated(char const *label) {
470    this->api.send_event("deactivated", json_object_new_string(label));
471 }
472
473 void App::emit_syncdraw(char const *label) {
474    this->api.send_event("syncdraw", json_object_new_string(label));
475 }
476
477 void App::emit_visible(char const *label, bool is_visible) {
478    this->api.send_event(is_visible ? "visible" : "invisible", json_object_new_string(label));
479 }
480
481 result<int> App::request_surface(char const *drawing_name) {
482    auto lid = this->layers.get_layer_id(std::string(drawing_name));
483    if (!lid) {
484       // XXX: to we need to put these applications on the App layer?
485       return Err<int>("Drawing name does not match any role");
486    }
487
488    auto rname = this->id_alloc.lookup(drawing_name);
489    if (!rname) {
490       // name does not exist yet, allocate surface id...
491       auto id = int(this->id_alloc.generate_id(drawing_name));
492       this->layers.add_surface(id, lid.value());
493
494       // XXX: you should fix this!
495       if (!this->layers.main_surface_name.empty() &&
496           this->layers.main_surface_name == drawing_name) {
497          this->layers.main_surface = id;
498          this->activate_surface(id);
499          logdebug("Set main_surface id to %u", id);
500       }
501
502       return Ok<int>(id);
503    }
504
505    // Check currently registered drawing names if it is already there.
506    return Err<int>("Surface already present");
507 }
508
509 char const *App::activate_surface(char const *drawing_name) {
510    auto osid = this->id_alloc.lookup(drawing_name);
511
512    if (osid) {
513       logdebug("ativate surface with name %s and id %u", drawing_name,
514                osid.value());
515       auto ret = this->activate_surface(osid.value());
516       if (!ret) {
517          this->emit_activated(drawing_name);
518       }
519       return ret;
520    }
521
522    logerror("surface %s unknown", drawing_name);
523    return "Surface unknown";
524 }
525
526 char const *App::deactivate_surface(char const *drawing_name) {
527    auto osid = this->id_alloc.lookup(drawing_name);
528
529    if (osid) {
530       logdebug("deativate surface with name %s and id %u", drawing_name,
531                osid.value());
532       return this->deactivate_surface(osid.value());
533    }
534
535    logerror("surface %s unknown", drawing_name);
536    return "Surface unknown";
537 }
538
539 //  _     _           _ _                            _   _                 _
540 // | |__ (_)_ __   __| (_)_ __   __ _     __ _ _ __ (_) (_)_ __ ___  _ __ | |
541 // | '_ \| | '_ \ / _` | | '_ \ / _` |   / _` | '_ \| | | | '_ ` _ \| '_ \| |
542 // | |_) | | | | | (_| | | | | | (_| |  | (_| | |_) | | | | | | | | | |_) | |
543 // |_.__/|_|_| |_|\__,_|_|_| |_|\__, |___\__,_| .__/|_| |_|_| |_| |_| .__/|_|
544 //                              |___/_____|   |_|                   |_|
545 binding_api::result_type binding_api::request_surface(
546    char const *drawing_name) {
547    auto r = this->app->request_surface(drawing_name);
548    if (r.is_err()) {
549       return Err<json_object *>(r.unwrap_err());
550    }
551    return Ok(json_object_new_int(r.unwrap()));
552 }
553
554 binding_api::result_type binding_api::activate_surface(
555    char const *drawing_name) {
556    logdebug("%s drawing_name %s", __func__, drawing_name);
557    auto r = this->app->activate_surface(drawing_name);
558    if (r != nullptr) {
559       return Err<json_object *>(r);
560    }
561    return Ok(json_object_new_object());
562 }
563
564 binding_api::result_type binding_api::deactivate_surface(char const* drawing_name) {
565    logdebug("%s drawing_name %s", __func__, drawing_name);
566    auto r = this->app->deactivate_surface(drawing_name);
567    if (r != nullptr) {
568       return Err<json_object *>(r);
569    }
570    return Ok(json_object_new_object());
571 }
572
573 binding_api::result_type binding_api::enddraw(char const* drawing_name) {
574    logdebug("%s drawing_name %s", __func__, drawing_name);
575    return Err<json_object*>("not implemented");
576 }
577
578 binding_api::result_type binding_api::list_drawing_names() {
579    logdebug("%s", __func__);
580    json j = this->app->id_alloc.names;
581    return Ok(json_tokener_parse(j.dump().c_str()));
582 }
583
584 binding_api::result_type binding_api::debug_layers() {
585    logdebug("%s", __func__);
586    return Ok(json_tokener_parse(this->app->layers.to_json().dump().c_str()));
587 }
588
589 binding_api::result_type binding_api::debug_surfaces() {
590    logdebug("%s", __func__);
591    return Ok(to_json(this->app->controller->sprops));
592 }
593
594 binding_api::result_type binding_api::debug_status() {
595    logdebug("%s", __func__);
596    json_object *jr = json_object_new_object();
597    json_object_object_add(jr, "surfaces",
598                           to_json(this->app->controller->sprops));
599    json_object_object_add(jr, "layers", to_json(this->app->controller->lprops));
600    return Ok(jr);
601 }
602
603 binding_api::result_type binding_api::debug_terminate() {
604    logdebug("%s", __func__);
605    raise(SIGKILL);  // XXX afb-daemon kills it's pgroup using TERM, which
606                     // doesn't play well with perf
607    return Ok(json_object_new_object());
608 }
609
610 binding_api::result_type binding_api::demo_activate_surface(
611    uint32_t surfaceid) {
612    char const *e = this->app->activate_surface(surfaceid);
613    if (e != nullptr) {
614       return Err<json_object *>(e);
615    }
616    return Ok(json_object_new_object());
617 }
618
619 binding_api::result_type binding_api::demo_activate_all() {
620    for (auto &s : this->app->controller->surfaces) {
621       s.second->set_visibility(1);
622    }
623    this->app->controller->commit_changes();
624    this->app->display->flush();
625    return Ok(json_object_new_object());
626 }
627
628 //                  _             _ _            _                 _
629 //   ___ ___  _ __ | |_ _ __ ___ | | | ___ _ __ | |__   ___   ___ | | _____
630 //  / __/ _ \| '_ \| __| '__/ _ \| | |/ _ \ '__|| '_ \ / _ \ / _ \| |/ / __|
631 // | (_| (_) | | | | |_| | | (_) | | |  __/ |   | | | | (_) | (_) |   <\__ \
632 //  \___\___/|_| |_|\__|_|  \___/|_|_|\___|_|___|_| |_|\___/ \___/|_|\_\___/
633 //                                         |_____|
634 void controller_hooks::surface_created(uint32_t surface_id) {
635    this->app->surface_created(surface_id);
636 }
637
638 void controller_hooks::surface_removed(uint32_t surface_id) {
639    this->app->surface_removed(surface_id);
640 }
641
642 void controller_hooks::add_task(char const *name, std::function<void()> &&f) {
643    this->app->add_task(name, std::move(f));
644 }
645
646 }  // namespace wm