f4dbba661ed8f7ec32486860a55329f1b6e54d76
[apps/agl-service-windowmanager-2017.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 <json.hpp>
36 #include <regex>
37 #include <thread>
38
39 namespace wm {
40
41 namespace {
42
43 using nlohmann::json;
44
45 result<json> file_to_json(char const *filename) {
46    std::ifstream i(filename);
47    if (i.fail()) {
48       return Err<json>("Could not open config file");
49    }
50    json j;
51    i >> j;
52    return Ok(j);
53 }
54
55 struct result<layer_map> load_layer_map(char const *filename) {
56    logdebug("loading IDs from %s", filename);
57
58    auto j = file_to_json(filename);
59    if (j.is_err()) {
60       return Err<layer_map>(j.unwrap_err());
61    }
62    json jids = j.unwrap();
63
64    return to_layer_map(jids);
65 }
66
67 }  // namespace
68
69 /**
70  * App Impl
71  */
72 App::App(wl::display *d)
73    : api{this},
74      chooks{this},
75      display{d},
76      controller{},
77      outputs(),
78      config(),
79      layers(),
80      id_alloc{},
81      pending_events(false),
82      policy{} {
83    try {
84       {
85          auto l = load_layer_map(
86             this->config.get_string("layers.json").value().c_str());
87          if (l.is_ok()) {
88             this->layers = l.unwrap();
89          } else {
90             logerror("%s", l.err().value());
91          }
92       }
93    } catch (std::exception &e) {
94       logerror("Loading of configuration failed: %s", e.what());
95    }
96 }
97
98 int App::init() {
99    if (!this->display->ok()) {
100       return -1;
101    }
102
103    if (this->layers.mapping.empty()) {
104       logerror("No surface -> layer mapping loaded");
105       return -1;
106    }
107
108    // Make afb event
109    for (int i=Event_Val_Min; i<=Event_Val_Max; i++) {
110       map_afb_event[kListEventName[i]] = afb_daemon_make_event(kListEventName[i]);
111    }
112
113    this->display->add_global_handler(
114       "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
115          this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
116       });
117
118    this->display->add_global_handler(
119       "ivi_controller", [this](wl_registry *r, uint32_t name, uint32_t v) {
120          this->controller =
121             std::make_unique<struct genivi::controller>(r, name, v);
122
123          // Init controller hooks
124          this->controller->chooks = &this->chooks;
125
126          // This protocol needs the output, so lets just add our mapping here...
127          this->controller->add_proxy_to_id_mapping(
128             this->outputs.back()->proxy.get(),
129             wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
130                this->outputs.back()->proxy.get())));
131       });
132
133    // First level objects
134    this->display->roundtrip();
135    // Second level objects
136    this->display->roundtrip();
137    // Third level objects
138    this->display->roundtrip();
139
140    return init_layers();
141 }
142
143 int App::dispatch_events() {
144    if (this->dispatch_events() == 0) {
145       return 0;
146    }
147
148    int ret = this->display->dispatch();
149    if (ret == -1) {
150       logerror("wl_display_dipatch() returned error %d",
151                this->display->get_error());
152       return -1;
153    }
154    this->display->flush();
155
156    return 0;
157 }
158
159 int App::dispatch_pending_events() {
160    if (this->pop_pending_events()) {
161       this->display->dispatch_pending();
162       return 0;
163    }
164    return -1;
165 }
166
167 bool App::pop_pending_events() {
168    bool x{true};
169    return this->pending_events.compare_exchange_strong(
170       x, false, std::memory_order_consume);
171 }
172
173 void App::set_pending_events() {
174    this->pending_events.store(true, std::memory_order_release);
175 }
176
177 optional<int> App::lookup_id(char const *name) {
178    return this->id_alloc.lookup(std::string(name));
179 }
180 optional<std::string> App::lookup_name(int id) {
181    return this->id_alloc.lookup(id);
182 }
183
184 /**
185  * init_layers()
186  */
187 int App::init_layers() {
188    if (!this->controller) {
189       logerror("ivi_controller global not available");
190       return -1;
191    }
192
193    if (this->outputs.empty()) {
194       logerror("no output was set up!");
195       return -1;
196    }
197
198    auto &c = this->controller;
199
200    auto &o = this->outputs.front();
201    auto &s = c->screens.begin()->second;
202    auto &layers = c->layers;
203
204    // Write output dimensions to ivi controller...
205    c->output_size = genivi::size{uint32_t(o->width), uint32_t(o->height)};
206
207    // Clear scene
208    layers.clear();
209
210    // Clear screen
211    s->clear();
212
213    // Quick and dirty setup of layers
214    for (auto const &i : this->layers.mapping) {
215       c->layer_create(i.second.layer_id, o->width, o->height);
216       auto &l = layers[i.second.layer_id];
217       l->set_destination_rectangle(0, 0, o->width, o->height);
218       l->set_visibility(1);
219       logdebug("Setting up layer %s (%d) for surface role match \"%s\"",
220                i.second.name.c_str(), i.second.layer_id, i.second.role.c_str());
221    }
222
223    // Add layers to screen
224    s->set_render_order(this->layers.layers);
225
226    this->layout_commit();
227
228    return 0;
229 }
230
231 void App::surface_set_layout(int surface_id, optional<int> sub_surface_id) {
232    if (!this->controller->surface_exists(surface_id)) {
233       logerror("Surface %d does not exist", surface_id);
234       return;
235    }
236
237    auto o_layer_id = this->layers.get_layer_id(surface_id);
238
239    if (!o_layer_id) {
240       logerror("Surface %d is not associated with any layer!", surface_id);
241       return;
242    }
243
244    uint32_t layer_id = *o_layer_id;
245
246    auto const &layer = this->layers.get_layer(layer_id);
247    auto rect = layer.value().rect;
248    auto &s = this->controller->surfaces[surface_id];
249
250    int x = rect.x;
251    int y = rect.y;
252    int w = rect.w;
253    int h = rect.h;
254
255    // less-than-0 values refer to MAX + 1 - $VALUE
256    // e.g. MAX is either screen width or height
257    if (w < 0) {
258       w = this->controller->output_size.w + 1 + w;
259    }
260    if (h < 0) {
261       h = this->controller->output_size.h + 1 + h;
262    }
263
264    if (sub_surface_id) {
265       if (o_layer_id != this->layers.get_layer_id(*sub_surface_id)) {
266          logerror(
267             "surface_set_layout: layers of surfaces (%d and %d) don't match!",
268             surface_id, *sub_surface_id);
269          return;
270       }
271
272       int x_off = 0;
273       int y_off = 0;
274
275       // split along major axis
276       if (w > h) {
277          w /= 2;
278          x_off = w;
279       } else {
280          h /= 2;
281          y_off = h;
282       }
283
284       auto &ss = this->controller->surfaces[*sub_surface_id];
285
286       logdebug("surface_set_layout for sub surface %u on layer %u",
287                *sub_surface_id, layer_id);
288
289       // configure surface to wxh dimensions
290       ss->set_configuration(w, h);
291       // set source reactangle, even if we should not need to set it.
292       ss->set_source_rectangle(0, 0, w, h);
293       // set destination to the display rectangle
294       ss->set_destination_rectangle(x + x_off, y + y_off, w, h);
295    }
296
297    logdebug("surface_set_layout for surface %u on layer %u", surface_id,
298             layer_id);
299
300    // configure surface to wxh dimensions
301    s->set_configuration(w, h);
302    // set source reactangle, even if we should not need to set it.
303    s->set_source_rectangle(0, 0, w, h);
304
305    // set destination to the display rectangle
306    s->set_destination_rectangle(x, y, w, h);
307
308    logdebug("Surface %u now on layer %u with rect { %d, %d, %d, %d }",
309             surface_id, layer_id, x, y, w, h);
310 }
311
312 void App::layout_commit() {
313    this->controller->commit_changes();
314    this->display->flush();
315 }
316
317 char const *App::api_activate_surface(char const *drawing_name, char const *drawing_area) {
318    ST();
319    auto const &surface_id = this->lookup_id(drawing_name);
320
321    if (!surface_id) {
322       return "Surface does not exist";
323    }
324
325    if (!this->controller->surface_exists(*surface_id)) {
326       return "Surface does not exist in controller!";
327    }
328
329    auto layer_id = this->layers.get_layer_id(*surface_id);
330
331    if (!layer_id) {
332       return "Surface is not on any layer!";
333    }
334
335    auto o_state = *this->layers.get_layout_state(*surface_id);
336
337    if (o_state == nullptr) {
338       return "Could not find layer for surface";
339    }
340
341    struct LayoutState &state = *o_state;
342
343    // disable layers that are above our current layer
344    for (auto const &l : this->layers.mapping) {
345       if (l.second.layer_id <= *layer_id) {
346          continue;
347       }
348
349       bool flush = false;
350       if (l.second.state.main != -1) {
351          this->deactivate(l.second.state.main);
352          l.second.state.main = -1;
353          flush = true;
354       }
355
356       if (l.second.state.sub != -1) {
357          this->deactivate(l.second.state.sub);
358          l.second.state.sub = -1;
359          flush = true;
360       }
361
362       if (flush) {
363          this->layout_commit();
364       }
365    }
366
367    if (state.main == *surface_id || state.sub == *surface_id) {
368       return "Surface already active";
369    }
370
371    if (state.main == -1) {
372       this->try_layout(
373          state, LayoutState{*surface_id}, [&] (LayoutState const &nl) {
374             this->surface_set_layout(*surface_id);
375             state = nl;
376             std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
377             this->emit_syncdraw(drawing_name, str_area.c_str());
378             this->enqueue_flushdraw(state.main);
379          });
380    } else {
381       bool can_split = this->can_split(state, *surface_id);
382
383          if (can_split) {
384             this->try_layout(
385                state,
386                LayoutState{state.main, *surface_id},
387                [&] (LayoutState const &nl) {
388                   std::string main =
389                      std::move(*this->lookup_name(state.main));
390
391                   this->surface_set_layout(state.main, surface_id);
392                   if (state.sub != -1) {
393                      this->deactivate(state.sub);
394                   }
395                   state = nl;
396
397                   std::string str_area_main = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaMain);
398                   std::string str_area_sub = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaSub);
399                   this->emit_syncdraw(main.c_str(), str_area_main.c_str());
400                   this->emit_syncdraw(drawing_name, str_area_sub.c_str());
401                   this->enqueue_flushdraw(state.main);
402                   this->enqueue_flushdraw(state.sub);
403                });
404          } else {
405             this->try_layout(
406                state, LayoutState{*surface_id}, [&] (LayoutState const &nl) {
407                   this->surface_set_layout(*surface_id);
408                   this->deactivate(state.main);
409                   if (state.sub != -1) {
410                      this->deactivate(state.sub);
411                   }
412                   state = nl;
413
414
415                   std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
416                   this->emit_syncdraw(drawing_name, str_area.c_str());
417                   this->enqueue_flushdraw(state.main);
418                });
419          }
420    }
421
422    // no error
423    return nullptr;
424 }
425
426 char const *App::api_deactivate_surface(char const *drawing_name) {
427    ST();
428    auto const &surface_id = this->lookup_id(drawing_name);
429
430    if (!surface_id) {
431          return "Surface does not exist";
432       }
433
434    if (*surface_id == this->layers.main_surface) {
435       return "Cannot deactivate main_surface";
436    }
437
438    auto o_state = *this->layers.get_layout_state(*surface_id);
439
440    if (o_state == nullptr) {
441       return "Could not find layer for surface";
442    }
443
444    struct LayoutState &state = *o_state;
445
446    if (state.main == -1) {
447       return "No surface active";
448    }
449
450    // XXX: check against main_surface, main_surface_name is the configuration
451    // item.
452    if (*surface_id == this->layers.main_surface) {
453       logdebug("Refusing to deactivate main_surface %d", *surface_id);
454       return nullptr;
455    }
456
457    if (state.main == *surface_id) {
458       if (state.sub != -1) {
459          this->try_layout(
460             state, LayoutState{state.sub, -1}, [&] (LayoutState const &nl) {
461                std::string sub = std::move(*this->lookup_name(state.sub));
462
463                this->deactivate(*surface_id);
464                this->surface_set_layout(state.sub);
465                state = nl;
466
467                this->layout_commit();
468                std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
469                this->emit_syncdraw(sub.c_str(), str_area.c_str());
470                this->enqueue_flushdraw(state.sub);
471             });
472       } else {
473          this->try_layout(state, LayoutState{-1, -1}, [&] (LayoutState const &nl) {
474             this->deactivate(*surface_id);
475             state = nl;
476             this->layout_commit();
477          });
478       }
479    } else if (state.sub == *surface_id) {
480       this->try_layout(
481          state, LayoutState{state.main, -1}, [&] (LayoutState const &nl) {
482             std::string main = std::move(*this->lookup_name(state.main));
483
484             this->deactivate(*surface_id);
485             this->surface_set_layout(state.main);
486             state = nl;
487
488             this->layout_commit();
489             std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
490             this->emit_syncdraw(main.c_str(), str_area.c_str());
491             this->enqueue_flushdraw(state.main);
492          });
493    } else {
494       return "Surface is not active";
495    }
496
497    return nullptr;
498 }
499
500 void App::enqueue_flushdraw(int surface_id) {
501    this->check_flushdraw(surface_id);
502    logdebug("Enqueuing EndDraw for surface_id %d", surface_id);
503    this->pending_end_draw.push_back(surface_id);
504 }
505
506 void App::check_flushdraw(int surface_id) {
507    auto i = std::find(std::begin(this->pending_end_draw),
508                       std::end(this->pending_end_draw), surface_id);
509    if (i != std::end(this->pending_end_draw)) {
510       auto n = this->lookup_name(surface_id);
511       logerror("Application %s (%d) has pending EndDraw call(s)!",
512                n ? n->c_str() : "unknown-name", surface_id);
513       std::swap(this->pending_end_draw[std::distance(
514                    std::begin(this->pending_end_draw), i)],
515                 this->pending_end_draw.back());
516       this->pending_end_draw.resize(this->pending_end_draw.size() - 1);
517    }
518 }
519
520 char const *App::api_enddraw(char const *drawing_name) {
521    for (unsigned i = 0, iend = this->pending_end_draw.size(); i < iend; i++) {
522       auto n = this->lookup_name(this->pending_end_draw[i]);
523       if (n && *n == drawing_name) {
524          std::swap(this->pending_end_draw[i], this->pending_end_draw[iend - 1]);
525          this->pending_end_draw.resize(iend - 1);
526          // XXX: Please tell the compositor to thaw the surface...
527          this->activate(this->pending_end_draw[i]);
528          this->layout_commit();
529          this->emit_flushdraw(drawing_name);
530          return nullptr;
531       }
532    }
533    return "No EndDraw pending for surface";
534 }
535
536 void App::api_ping() { this->dispatch_pending_events(); }
537
538 /**
539  * proxied events
540  */
541 void App::surface_created(uint32_t surface_id) {
542    auto layer_id = this->layers.get_layer_id(surface_id);
543    if (!layer_id) {
544       logdebug("Newly created surfce %d is not associated with any layer!",
545                surface_id);
546       return;
547    }
548
549    logdebug("surface_id is %u, layer_id is %u", surface_id, *layer_id);
550
551    this->controller->layers[*layer_id]->add_surface(
552       this->controller->surfaces[surface_id].get());
553
554    // activate the main_surface right away
555    /*if (surface_id == static_cast<unsigned>(this->layers.main_surface)) {
556       logdebug("Activating main_surface (%d)", surface_id);
557
558       this->api_activate_surface(
559          this->lookup_name(surface_id).value_or("unknown-name").c_str());
560    }*/
561 }
562
563 void App::surface_removed(uint32_t surface_id) {
564    logdebug("surface_id is %u", surface_id);
565
566    // We cannot normally deactivate the main_surface, so be explicit
567    // about it:
568    if (int(surface_id) == this->layers.main_surface) {
569       this->deactivate_main_surface();
570    } else {
571       auto drawing_name = this->lookup_name(surface_id);
572       if (drawing_name) {
573          this->api_deactivate_surface(drawing_name->c_str());
574       }
575    }
576
577    this->id_alloc.remove_id(surface_id);
578    this->layers.remove_surface(surface_id);
579 }
580
581 void App::emit_activated(char const *label) {
582    this->api.send_event(kListEventName[Event_Active], label);
583 }
584
585 void App::emit_deactivated(char const *label) {
586    this->api.send_event(kListEventName[Event_Inactive], label);
587 }
588
589 void App::emit_syncdraw(char const *label, char const *area) {
590     this->api.send_event(kListEventName[Event_SyncDraw], label, area);
591 }
592
593 void App::emit_flushdraw(char const *label) {
594    this->api.send_event(kListEventName[Event_FlushDraw], label);
595 }
596
597 void App::emit_visible(char const *label, bool is_visible) {
598    this->api.send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
599 }
600
601 void App::emit_invisible(char const *label) {
602    return emit_visible(label, false);
603 }
604
605 void App::emit_visible(char const *label) { return emit_visible(label, true); }
606
607 result<int> App::api_request_surface(char const *drawing_name) {
608    auto lid = this->layers.get_layer_id(std::string(drawing_name));
609    if (!lid) {
610       // TODO: Do we need to put these applications on the App layer?
611       return Err<int>("Drawing name does not match any role");
612    }
613
614    auto rname = this->lookup_id(drawing_name);
615    if (!rname) {
616       // name does not exist yet, allocate surface id...
617       auto id = int(this->id_alloc.generate_id(drawing_name));
618       this->layers.add_surface(id, *lid);
619
620       // set the main_surface[_name] here and now
621       if (!this->layers.main_surface_name.empty() &&
622           this->layers.main_surface_name == drawing_name) {
623          this->layers.main_surface = id;
624          logdebug("Set main_surface id to %u", id);
625       }
626
627       return Ok<int>(id);
628    }
629
630    // Check currently registered drawing names if it is already there.
631    return Err<int>("Surface already present");
632 }
633
634 void App::activate(int id) {
635    auto ip = this->controller->sprops.find(id);
636    if (ip != this->controller->sprops.end() && ip->second.visibility == 0) {
637       this->controller->surfaces[id]->set_visibility(1);
638       char const *label =
639          this->lookup_name(id).value_or("unknown-name").c_str();
640       this->emit_visible(label);
641       this->emit_activated(label);
642    }
643 }
644
645 void App::deactivate(int id) {
646    auto ip = this->controller->sprops.find(id);
647    if (ip != this->controller->sprops.end() && ip->second.visibility != 0) {
648       this->controller->surfaces[id]->set_visibility(0);
649       char const *label =
650          this->lookup_name(id).value_or("unknown-name").c_str();
651       this->emit_deactivated(label);
652       this->emit_invisible(label);
653    }
654 }
655
656 void App::deactivate_main_surface() {
657    this->layers.main_surface = -1;
658    this->api_deactivate_surface(this->layers.main_surface_name.c_str());
659 }
660
661 bool App::can_split(struct LayoutState const &state, int new_id) {
662    if (state.main != -1 && state.main != new_id) {
663       auto new_id_layer = this->layers.get_layer_id(new_id).value();
664       auto current_id_layer = this->layers.get_layer_id(state.main).value();
665
666       // surfaces are on separate layers, don't bother.
667       if (new_id_layer != current_id_layer) {
668          return false;
669       }
670
671       std::string const &new_id_str = this->lookup_name(new_id).value();
672       std::string const &cur_id_str = this->lookup_name(state.main).value();
673
674       auto const &layer = this->layers.get_layer(new_id_layer);
675
676       logdebug("layer info name: %s", layer->name.c_str());
677
678       if (layer->layouts.empty()) {
679          return false;
680       }
681
682       for (auto i = layer->layouts.cbegin(); i != layer->layouts.cend(); i++) {
683          logdebug("%d main_match '%s'", new_id_layer, i->main_match.c_str());
684          auto rem = std::regex(i->main_match);
685          if (std::regex_match(cur_id_str, rem)) {
686             // build the second one only if the first already matched
687             logdebug("%d sub_match '%s'", new_id_layer, i->sub_match.c_str());
688             auto res = std::regex(i->sub_match);
689             if (std::regex_match(new_id_str, res)) {
690                logdebug("layout matched!");
691                return true;
692             }
693          }
694       }
695    }
696
697    return false;
698 }
699
700 void App::try_layout(struct LayoutState & /*state*/,
701                      struct LayoutState const &new_layout,
702                      std::function<void(LayoutState const &nl)> apply) {
703    if (this->policy.layout_is_valid(new_layout)) {
704       apply(new_layout);
705    }
706 }
707
708 /**
709  * controller_hooks
710  */
711 void controller_hooks::surface_created(uint32_t surface_id) {
712    this->app->surface_created(surface_id);
713 }
714
715 void controller_hooks::surface_removed(uint32_t surface_id) {
716    this->app->surface_removed(surface_id);
717 }
718
719 void controller_hooks::surface_visibility(uint32_t /*surface_id*/,
720                                           uint32_t /*v*/) {}
721
722 void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/,
723                                                      uint32_t /*x*/,
724                                                      uint32_t /*y*/,
725                                                      uint32_t /*w*/,
726                                                      uint32_t /*h*/) {}
727
728 }  // namespace wm