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