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