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