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