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