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