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