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