59131438d1853ff594234f5995a2c0714f6e40cb
[apps/agl-service-windowmanager.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 "applist.hpp"
18 #include "app.hpp"
19 #include "json_helper.hpp"
20 #include "layers.hpp"
21 #include "layout.hpp"
22 #include "util.hpp"
23 #include "wayland_ivi_wm.hpp"
24
25 #include <cstdio>
26 #include <memory>
27
28 #include <cassert>
29
30 #include <json-c/json.h>
31
32 #include <algorithm>
33 #include <csignal>
34 #include <fstream>
35 #include <json.hpp>
36 #include <regex>
37 #include <thread>
38
39 #include "wm_client.hpp"
40
41
42 extern "C"
43 {
44 #include <systemd/sd-event.h>
45 }
46
47 namespace wm
48 {
49
50 const unsigned kTimeOut = 10000000UL; /* 10s */
51
52 /* DrawingArea name used by "{layout}.{area}" */
53 const char kNameLayoutNormal[] = "normal";
54 const char kNameLayoutSplit[] = "split";
55 const char kNameAreaFull[] = "full";
56 const char kNameAreaMain[] = "main";
57 const char kNameAreaSub[] = "sub";
58
59 /* Key for json obejct */
60 const char kKeyDrawingName[] = "drawing_name";
61 const char kKeyDrawingArea[] = "drawing_area";
62 const char kKeyDrawingRect[] = "drawing_rect";
63 const char kKeyX[] = "x";
64 const char kKeyY[] = "y";
65 const char kKeyWidth[] = "width";
66 const char kKeyHeight[] = "height";
67 const char kKeyWidthPixel[] = "width_pixel";
68 const char kKeyHeightPixel[] = "height_pixel";
69 const char kKeyWidthMm[] = "width_mm";
70 const char kKeyHeightMm[] = "height_mm";
71
72 static sd_event_source *g_timer_ev_src = nullptr;
73
74 namespace
75 {
76
77 using nlohmann::json;
78
79 result<json> file_to_json(char const *filename)
80 {
81     json j;
82     std::ifstream i(filename);
83     if (i.fail())
84     {
85         HMI_DEBUG("wm", "Could not open config file, so use default layer information");
86         j = default_layers_json;
87     }
88     else
89     {
90         i >> j;
91     }
92
93     return Ok(j);
94 }
95
96 struct result<layer_map> load_layer_map(char const *filename)
97 {
98     HMI_DEBUG("wm", "loading IDs from %s", filename);
99
100     auto j = file_to_json(filename);
101     if (j.is_err())
102     {
103         return Err<layer_map>(j.unwrap_err());
104     }
105     json jids = j.unwrap();
106
107     return to_layer_map(jids);
108 }
109
110 static int
111 processTimerHandler(sd_event_source *s, uint64_t usec, void *userdata)
112 {
113     HMI_NOTICE("wm", "Time out occurs because the client replys endDraw slow, so revert the request");
114     reinterpret_cast<wm::App *>(userdata)->timerHandler();
115     return 0;
116 }
117
118 } // namespace
119
120 void App::timerHandler()
121 {
122     unsigned req_num = app_list->currentRequestNumber();
123     HMI_SEQ_DEBUG(req_num, "Timer expired remove Request");
124     app_list->reqDump();
125     app_list->removeRequest(req_num);
126     app_list->next();
127     app_list->reqDump();
128     if (app_list->haveRequest())
129     {
130         this->process_request();
131     }
132 }
133
134 void App::removeClient(const std::string &appid)
135 {
136     HMI_DEBUG("wm", "Remove clinet %s from list", appid.c_str());
137     app_list->removeClient(appid);
138 }
139
140 bool App::subscribeEventForApp(const std::string &appid, afb_req req, const std::string &evname)
141 {
142     if(!app_list->contains(appid)){
143         HMI_DEBUG("wm", "Client %s is not registered", appid.c_str());
144         return false;
145     }
146     auto client = app_list->lookUpClient(appid);
147     return client->subscribe(req, evname);
148 }
149
150 /**
151  * App Impl
152  */
153 App::App(wl::display *d)
154     : chooks{this},
155       display{d},
156       controller{},
157       outputs(),
158       config(),
159       layers(),
160       id_alloc{},
161       pending_events(false),
162       policy{},
163       app_list(std::make_unique<AppList>())
164 {
165     try
166     {
167         {
168             auto l = load_layer_map(
169                 this->config.get_string("layers.json").value().c_str());
170             if (l.is_ok())
171             {
172                 this->layers = l.unwrap();
173             }
174             else
175             {
176                 HMI_ERROR("wm", "%s", l.err().value());
177             }
178         }
179     }
180     catch (std::exception &e)
181     {
182         HMI_ERROR("wm", "Loading of configuration failed: %s", e.what());
183     }
184 }
185
186 int App::init()
187 {
188     if (!this->display->ok())
189     {
190         return -1;
191     }
192
193     if (this->layers.mapping.empty())
194     {
195         HMI_ERROR("wm", "No surface -> layer mapping loaded");
196         return -1;
197     }
198
199     // Make afb event
200     for (int i = Event_Val_Min; i <= Event_Val_Max; i++)
201     {
202         map_afb_event[kListEventName[i]] = afb_daemon_make_event(kListEventName[i]);
203     }
204
205     this->display->add_global_handler(
206         "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
207             this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
208         });
209
210     this->display->add_global_handler(
211         "ivi_wm", [this](wl_registry *r, uint32_t name, uint32_t v) {
212             this->controller =
213                 std::make_unique<struct compositor::controller>(r, name, v);
214
215             // Init controller hooks
216             this->controller->chooks = &this->chooks;
217
218             // This protocol needs the output, so lets just add our mapping here...
219             this->controller->add_proxy_to_id_mapping(
220                 this->outputs.back()->proxy.get(),
221                 wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
222                     this->outputs.back()->proxy.get())));
223
224             // Create screen
225             this->controller->create_screen(this->outputs.back()->proxy.get());
226
227             // Set display to controller
228             this->controller->display = this->display;
229         });
230
231     // First level objects
232     this->display->roundtrip();
233     // Second level objects
234     this->display->roundtrip();
235     // Third level objects
236     this->display->roundtrip();
237
238     return init_layers();
239 }
240
241 App::~App() = default;
242
243 int App::dispatch_pending_events()
244 {
245     if (this->pop_pending_events())
246     {
247         this->display->dispatch_pending();
248         return 0;
249     }
250     return -1;
251 }
252
253 bool App::pop_pending_events()
254 {
255     bool x{true};
256     return this->pending_events.compare_exchange_strong(
257         x, false, std::memory_order_consume);
258 }
259
260 void App::set_pending_events()
261 {
262     this->pending_events.store(true, std::memory_order_release);
263 }
264
265 optional<int> App::lookup_id(char const *name)
266 {
267     return this->id_alloc.lookup(std::string(name));
268 }
269 optional<std::string> App::lookup_name(int id)
270 {
271     return this->id_alloc.lookup(id);
272 }
273
274 /**
275  * init_layers()
276  */
277 int App::init_layers()
278 {
279     if (!this->controller)
280     {
281         HMI_ERROR("wm", "ivi_controller global not available");
282         return -1;
283     }
284
285     if (this->outputs.empty())
286     {
287         HMI_ERROR("wm", "no output was set up!");
288         return -1;
289     }
290
291     auto &c = this->controller;
292
293     auto &o = this->outputs.front();
294     auto &s = c->screens.begin()->second;
295     auto &layers = c->layers;
296
297     // Write output dimensions to ivi controller...
298     c->output_size = compositor::size{uint32_t(o->width), uint32_t(o->height)};
299     c->physical_size = compositor::size{uint32_t(o->physical_width),
300                                         uint32_t(o->physical_height)};
301
302     // Clear scene
303     layers.clear();
304
305     // Clear screen
306     s->clear();
307
308     // Quick and dirty setup of layers
309     for (auto const &i : this->layers.mapping)
310     {
311         c->layer_create(i.second.layer_id, o->width, o->height);
312         auto &l = layers[i.second.layer_id];
313         l->set_destination_rectangle(0, 0, o->width, o->height);
314         l->set_visibility(1);
315         HMI_DEBUG("wm", "Setting up layer %s (%d) for surface role match \"%s\"",
316                   i.second.name.c_str(), i.second.layer_id, i.second.role.c_str());
317     }
318
319     // Add layers to screen
320     s->set_render_order(this->layers.layers);
321
322     this->layout_commit();
323
324     return 0;
325 }
326
327 void App::surface_set_layout(int surface_id, optional<int> sub_surface_id)
328 {
329     if (!this->controller->surface_exists(surface_id))
330     {
331         HMI_ERROR("wm", "Surface %d does not exist", surface_id);
332         return;
333     }
334
335     auto o_layer_id = this->layers.get_layer_id(surface_id);
336
337     if (!o_layer_id)
338     {
339         HMI_ERROR("wm", "Surface %d is not associated with any layer!", surface_id);
340         return;
341     }
342
343     uint32_t layer_id = *o_layer_id;
344
345     auto const &layer = this->layers.get_layer(layer_id);
346     auto rect = layer.value().rect;
347     auto &s = this->controller->surfaces[surface_id];
348
349     int x = rect.x;
350     int y = rect.y;
351     int w = rect.w;
352     int h = rect.h;
353
354     // less-than-0 values refer to MAX + 1 - $VALUE
355     // e.g. MAX is either screen width or height
356     if (w < 0)
357     {
358         w = this->controller->output_size.w + 1 + w;
359     }
360     if (h < 0)
361     {
362         h = this->controller->output_size.h + 1 + h;
363     }
364
365     if (sub_surface_id)
366     {
367         if (o_layer_id != this->layers.get_layer_id(*sub_surface_id))
368         {
369             HMI_ERROR("wm",
370                       "surface_set_layout: layers of surfaces (%d and %d) don't match!",
371                       surface_id, *sub_surface_id);
372             return;
373         }
374
375         int x_off = 0;
376         int y_off = 0;
377
378         // split along major axis
379         if (w > h)
380         {
381             w /= 2;
382             x_off = w;
383         }
384         else
385         {
386             h /= 2;
387             y_off = h;
388         }
389
390         auto &ss = this->controller->surfaces[*sub_surface_id];
391
392         HMI_DEBUG("wm", "surface_set_layout for sub surface %u on layer %u",
393                   *sub_surface_id, layer_id);
394
395         // set destination to the display rectangle
396         ss->set_destination_rectangle(x + x_off, y + y_off, w, h);
397
398         this->area_info[*sub_surface_id].x = x;
399         this->area_info[*sub_surface_id].y = y;
400         this->area_info[*sub_surface_id].w = w;
401         this->area_info[*sub_surface_id].h = h;
402     }
403
404     HMI_DEBUG("wm", "surface_set_layout for surface %u on layer %u", surface_id,
405               layer_id);
406
407     // set destination to the display rectangle
408     s->set_destination_rectangle(x, y, w, h);
409
410     // update area information
411     this->area_info[surface_id].x = x;
412     this->area_info[surface_id].y = y;
413     this->area_info[surface_id].w = w;
414     this->area_info[surface_id].h = h;
415
416     HMI_DEBUG("wm", "Surface %u now on layer %u with rect { %d, %d, %d, %d }",
417               surface_id, layer_id, x, y, w, h);
418 }
419
420 void App::layout_commit()
421 {
422     this->controller->commit_changes();
423     this->display->flush();
424 }
425
426 void App::set_timer()
427 {
428     HMI_SEQ_DEBUG(app_list->currentRequestNumber(), "Timer set activate");
429     if (g_timer_ev_src == nullptr)
430     {
431         // firsttime set into sd_event
432         int ret = sd_event_add_time(afb_daemon_get_event_loop(), &g_timer_ev_src,
433                                     CLOCK_REALTIME, time(NULL) * (1000000UL) + kTimeOut, 1, processTimerHandler, this);
434         if (ret < 0)
435         {
436             HMI_ERROR("wm", "Could't set timer");
437         }
438     }
439     else
440     {
441         // update timer limitation after second time
442         sd_event_source_set_time(g_timer_ev_src, time(NULL) * (1000000UL) + kTimeOut);
443         sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT);
444     }
445 }
446
447 void App::stop_timer()
448 {
449     unsigned req_num = app_list->currentRequestNumber();
450     HMI_SEQ_DEBUG(req_num, "Timer stop");
451     int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF);
452     if (rc < 0)
453     {
454         HMI_SEQ_ERROR(req_num, "Timer stop failed");
455     }
456 }
457
458 WMError App::lm_release(const struct WMAction &action)
459 {
460     //auto const &surface_id = this->lookup_id(drawing_name);
461     WMError ret = WMError::LAYOUT_CHANGE_FAIL;
462     unsigned req_num = app_list->currentRequestNumber();
463     auto const &surface_id = this->lookup_id(action.role.c_str());
464     if (!surface_id)
465     {
466         HMI_SEQ_ERROR(req_num, "Surface does not exist");
467         return ret;
468     }
469
470     if (*surface_id == this->layers.main_surface)
471     {
472         HMI_SEQ_ERROR(req_num, "Cannot deactivate main_surface");
473         return ret;
474     }
475
476     auto o_state = *this->layers.get_layout_state(*surface_id);
477
478     if (o_state == nullptr)
479     {
480         HMI_SEQ_ERROR(req_num, "Could not find layer for surface");
481         return ret;
482     }
483
484     struct LayoutState &state = *o_state;
485
486     if (state.main == -1)
487     {
488         HMI_SEQ_ERROR(req_num, "No surface active");
489         return ret;
490     }
491
492     // Check against main_surface, main_surface_name is the configuration item.
493     if (*surface_id == this->layers.main_surface)
494     {
495         HMI_SEQ_DEBUG(req_num, "Refusing to deactivate main_surface %d", *surface_id);
496         //reply(nullptr);
497         return WMError::SUCCESS;
498     }
499     if ((state.main == *surface_id) && (state.sub == *surface_id))
500     {
501         HMI_SEQ_ERROR(req_num, "Surface is not active");
502         return ret;
503     }
504
505     if (state.main == *surface_id)
506     {
507         if (state.sub != -1)
508         {
509             this->try_layout(
510                 state, LayoutState{state.sub, -1}, [&](LayoutState const &nl) {
511                     std::string sub = std::move(*this->lookup_name(state.sub));
512
513                     this->deactivate(*surface_id);
514                     this->surface_set_layout(state.sub);
515                     state = nl;
516
517                     this->layout_commit();
518                     std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
519                     compositor::rect area_rect = this->area_info[state.sub];
520                     this->emit_syncdraw(sub.c_str(), str_area.c_str(),
521                                         area_rect.x, area_rect.y, area_rect.w, area_rect.h);
522                     this->enqueue_flushdraw(state.sub);
523                 });
524         }
525         else
526         {
527             this->try_layout(state, LayoutState{-1, -1}, [&](LayoutState const &nl) {
528                 this->deactivate(*surface_id);
529                 state = nl;
530                 this->layout_commit();
531             });
532         }
533     }
534     else if (state.sub == *surface_id)
535     {
536         this->try_layout(
537             state, LayoutState{state.main, -1}, [&](LayoutState const &nl) {
538                 std::string main = std::move(*this->lookup_name(state.main));
539
540                 this->deactivate(*surface_id);
541                 this->surface_set_layout(state.main);
542                 state = nl;
543
544                 this->layout_commit();
545                 std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
546                 compositor::rect area_rect = this->area_info[state.main];
547                 this->emit_syncdraw(main.c_str(), str_area.c_str(),
548                                     area_rect.x, area_rect.y, area_rect.w, area_rect.h);
549                 this->enqueue_flushdraw(state.main);
550             });
551     }
552     return WMError::SUCCESS;
553 }
554
555 WMError App::lm_layout_change(const struct WMAction &action)
556 {
557     const char *msg = this->check_surface_exist(action.role.c_str());
558
559     /*
560     lm_.updateLayout(action);
561     TODO: emit syncDraw with application*/
562     if (msg)
563     {
564         HMI_SEQ_DEBUG(app_list->currentRequestNumber(), msg);
565         return WMError::LAYOUT_CHANGE_FAIL;
566     }
567     this->lm_layout_change(action.role.c_str());
568     return WMError::SUCCESS;
569 }
570
571 WMError App::do_transition(unsigned req_num)
572 {
573     /*
574     * Check Policy
575     */
576     // get current trigger
577     bool found;
578     bool is_activate = true;
579     auto trigger = app_list->getRequest(req_num, &found);
580     if(!found)
581     {
582         WMError err = WMError::NO_ENTRY;
583         HMI_SEQ_ERROR(req_num, errorDescription(err));
584         return err;
585     }
586
587     /*  get new status from Policy Manager
588
589     (json_object*?) newLayout = checkPolicy(trigger);
590     (vector<struct WMAction>&) auto actions = translator.inputActionFromLayout(newLayout, currentLayout)
591     for(const auto& x : actions){
592         app_list->setAciton(req_num, x)
593     }
594
595     or
596
597     translator.inputActionFromLayout(newLayout, currentLayout, &app_list, req_num);
598
599     /* The following error check is not necessary because main.cpp will reject the message form not registered object
600    } */
601     HMI_SEQ_NOTICE(req_num, "ATM, Policy manager does't exist, then set WMAction as is");
602
603     if (trigger.task == Task::TASK_RELEASE)
604     {
605         is_activate = false;
606     }
607     WMError ret = app_list->setAction(req_num, trigger.appid, trigger.role, trigger.area, is_activate);
608     app_list->reqDump();
609
610     if (ret != WMError::SUCCESS)
611     {
612         HMI_SEQ_ERROR(req_num, "Failed to set action");
613         return ret;
614     }
615
616     // layer manager task
617     bool sync_draw_happen = false;
618     for (const auto &y : app_list->getActions(req_num, &found))
619     {
620         if (!found)
621         {
622             WMError err = WMError::NO_ENTRY;
623             HMI_SEQ_ERROR(req_num, "%s : Action is not set", errorDescription(err));
624             return err;
625         }
626         /*
627         do_task(y);
628         */
629         /*  TODO
630            but current we can't do do_task,
631            so divide the processing into lm_layout_change and lm_release
632         */
633         if (y.visible)
634         {
635             sync_draw_happen = true;
636             ret = lm_layout_change(y);
637             if (ret != WMError::SUCCESS)
638             {
639                 HMI_SEQ_ERROR(req_num, "%s: appid: %s, role: %s, area: %s",
640                     errorDescription(ret), y.appid.c_str(), y.role.c_str(), y.area.c_str());
641                 app_list->removeRequest(req_num);
642                 break;
643                 // TODO: if transition fails, what should we do?
644             }
645             /* app_list->lookUpClient(y.appid)->emit_syncdraw(y.role, y.area); */
646         }
647         else
648         {
649             ret = lm_release(y);
650             if (!ret)
651             {
652                 HMI_SEQ_ERROR(req_num, "Failed release resource: %s", y.appid.c_str());
653                 app_list->removeRequest(req_num);
654                 break;
655                 // TODO: if transition fails, what should we do?
656             }
657             /* app_list->lookUpClient(y.appid)->emit_invisible(y.role, y.area); */
658         }
659     }
660
661     if (ret != WMError::SUCCESS)
662     {
663         //this->emit_error(req_num, 0 /*error_num*/, "error happens"); // test
664     }
665     else if (sync_draw_happen)
666     {
667         this->set_timer();
668     }
669     else
670     {
671         app_list->removeRequest(req_num); // HACK!!!
672     }
673     return ret;
674 }
675
676 void App::lm_layout_change(const char *drawing_name)
677 {
678     auto const &surface_id = this->lookup_id(drawing_name);
679     auto layer_id = this->layers.get_layer_id(*surface_id);
680     auto o_state = *this->layers.get_layout_state(*surface_id);
681     struct LayoutState &state = *o_state;
682
683     // disable layers that are above our current layer
684     for (auto const &l : this->layers.mapping)
685     {
686         if (l.second.layer_id <= *layer_id)
687         {
688             continue;
689         }
690
691         bool flush = false;
692         if (l.second.state.main != -1)
693         {
694             this->deactivate(l.second.state.main);
695             l.second.state.main = -1;
696             flush = true;
697         }
698
699         if (l.second.state.sub != -1)
700         {
701             this->deactivate(l.second.state.sub);
702             l.second.state.sub = -1;
703             flush = true;
704         }
705
706         if (flush)
707         {
708             this->layout_commit();
709         }
710     }
711
712     auto layer = this->layers.get_layer(*layer_id);
713
714     if (state.main == -1)
715     {
716         this->try_layout(
717             state, LayoutState{*surface_id}, [&](LayoutState const &nl) {
718                 HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
719                 this->surface_set_layout(*surface_id);
720                 state = nl;
721
722                 // Commit for configuraton
723                 this->layout_commit();
724
725                 std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
726                 compositor::rect area_rect = this->area_info[*surface_id];
727                 this->emit_syncdraw(drawing_name, str_area.c_str(),
728                                     area_rect.x, area_rect.y, area_rect.w, area_rect.h);
729                 this->enqueue_flushdraw(state.main);
730             });
731     }
732     else
733     {
734         if (0 == strcmp(drawing_name, "HomeScreen"))
735         {
736             this->try_layout(
737                 state, LayoutState{*surface_id}, [&](LayoutState const &nl) {
738                     HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
739                     std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
740                     compositor::rect area_rect = this->area_info[*surface_id];
741                     this->emit_syncdraw(drawing_name, str_area.c_str(),
742                                         area_rect.x, area_rect.y, area_rect.w, area_rect.h);
743                     this->enqueue_flushdraw(state.main);
744                 });
745         }
746         else
747         {
748             bool can_split = this->can_split(state, *surface_id);
749
750             if (can_split)
751             {
752                 this->try_layout(
753                     state,
754                     LayoutState{state.main, *surface_id},
755                     [&](LayoutState const &nl) {
756                         HMI_DEBUG("wm", "Layout: %s", kNameLayoutSplit);
757                         std::string main =
758                             std::move(*this->lookup_name(state.main));
759
760                         this->surface_set_layout(state.main, surface_id);
761                         if (state.sub != *surface_id)
762                         {
763                             if (state.sub != -1)
764                             {
765                                 this->deactivate(state.sub);
766                             }
767                         }
768                         state = nl;
769
770                         // Commit for configuration and visibility(0)
771                         this->layout_commit();
772
773                         std::string str_area_main = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaMain);
774                         std::string str_area_sub = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaSub);
775                         compositor::rect area_rect_main = this->area_info[state.main];
776                         compositor::rect area_rect_sub = this->area_info[*surface_id];
777                         // >>> HACK
778                         HMI_WARNING("wm", "HACK!!! mediaplayer and hvac is only supported for split");
779                         std::string request_role = drawing_name;
780                         //std::string request_app = transform(request_role.begin(), request_role.end(), request_role.begin(), tolower); //hvac or mediaplayer
781                         std::string hack_appid = "navigation";
782                         std::string hack_role = main;
783                         std::string hack_area = str_area_main;
784                         app_list->setAction(app_list->currentRequestNumber(), hack_appid, hack_role, hack_area, true);
785                         //app_list->setEndDrawFinished(app_list->currentRequestNumber(), request_role, request_role);
786                         //app_list->setEndDrawFinished(app_list->currentRequestNumber(), hack_appid, hack_role); // This process is illegal
787                         // >>> HACK
788                         this->emit_syncdraw(main.c_str(), str_area_main.c_str(),
789                                             area_rect_main.x, area_rect_main.y,
790                                             area_rect_main.w, area_rect_main.h);
791                         this->emit_syncdraw(request_role.c_str(), str_area_sub.c_str(),
792                                             area_rect_sub.x, area_rect_sub.y,
793                                             area_rect_sub.w, area_rect_sub.h);
794                         this->enqueue_flushdraw(state.main);
795                         this->enqueue_flushdraw(state.sub);
796                     });
797             }
798             else
799             {
800                 this->try_layout(
801                     state, LayoutState{*surface_id}, [&](LayoutState const &nl) {
802                         HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
803
804                         this->surface_set_layout(*surface_id);
805                         if (state.main != *surface_id)
806                         {
807                             this->deactivate(state.main);
808                         }
809                         if (state.sub != -1)
810                         {
811                             if (state.sub != *surface_id)
812                             {
813                                 this->deactivate(state.sub);
814                             }
815                         }
816                         state = nl;
817
818                         // Commit for configuraton and visibility(0)
819                         this->layout_commit();
820
821                         std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
822                         compositor::rect area_rect = this->area_info[*surface_id];
823                         this->emit_syncdraw(drawing_name, str_area.c_str(),
824                                             area_rect.x, area_rect.y, area_rect.w, area_rect.h);
825                         this->enqueue_flushdraw(state.main);
826                     });
827             }
828         }
829     }
830 }
831
832 const char *App::check_surface_exist(const char *drawing_name)
833 {
834     auto const &surface_id = this->lookup_id(drawing_name);
835     if (!surface_id)
836     {
837         //reply("Surface does not exist");
838         return "Surface does not exist";
839     }
840
841     if (!this->controller->surface_exists(*surface_id))
842     {
843         //reply("Surface does not exist in controller!");
844         return "Surface does not exist in controller!";
845     }
846
847     auto layer_id = this->layers.get_layer_id(*surface_id);
848
849     if (!layer_id)
850     {
851         //reply("Surface is not on any layer!");
852         return "Surface is not on any layer!";
853     }
854
855     auto o_state = *this->layers.get_layout_state(*surface_id);
856
857     if (o_state == nullptr)
858     {
859         //reply("Could not find layer for surface");
860         return "Could not find layer for surface";
861     }
862
863     HMI_DEBUG("wm", "surface %d is detected", *surface_id);
864     return nullptr;
865     //reply(nullptr);
866 }
867
868 void App::api_activate_surface(char const *appid, char const *drawing_name, char const *drawing_area, const reply_func &reply)
869 {
870     ST();
871
872     /*
873    * Check Phase
874    */
875
876     std::string id = appid;
877     std::string role = drawing_name;
878     std::string area = drawing_area;
879
880     if (!app_list->contains(id))
881     {
882         reply("app doesn't request 'requestSurface' yet");
883         return;
884     }
885
886     auto client = app_list->lookUpClient(id);
887
888     unsigned srfc = client->surfaceID(role);
889     if(srfc == INVALID_SURFACE_ID){
890         HMI_ERROR("wm", "role should be set with surface");
891         reply("role should be set with surface");
892         return;
893     }
894     app_list->removeFloatingSurface(client->surfaceID(role));
895
896     /*
897    * Queueing Phase
898    */
899     unsigned current = app_list->currentRequestNumber();
900     unsigned requested_num = app_list->getRequestNumber(id);
901     if (requested_num != 0)
902     {
903         HMI_SEQ_INFO(requested_num, "%s %s %s request is already queued", id.c_str(), role.c_str(), area.c_str());
904         reply("already requested");
905         return;
906     }
907
908     WMRequest req = WMRequest(id, role, area, Task::TASK_ALLOCATE);
909     unsigned new_req = app_list->addAllocateRequest(req);
910     app_list->reqDump();
911
912     HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", id.c_str(), role.c_str(), area.c_str());
913
914     reply(nullptr);
915     if (new_req != current)
916     {
917         // Add request, then invoked after the previous task is finished
918         HMI_SEQ_DEBUG(new_req, "request is accepted");
919         return;
920     }
921
922     /*
923     * Do allocate tasks
924     */
925     WMError ret = this->do_transition(new_req);
926
927     if (ret != WMError::SUCCESS)
928     {
929         HMI_SEQ_ERROR(new_req, errorDescription(ret));
930         //this->emit_error()
931     }
932 }
933
934 void App::api_deactivate_surface(char const *appid, char const *drawing_name, const reply_func &reply)
935 {
936     ST();
937
938     /*
939    * Check Phase
940    */
941     std::string id = appid;
942     std::string role = drawing_name;
943     std::string area = ""; //drawing_area;
944
945     if (!app_list->contains(id))
946     {
947         reply("app doesn't request 'requestSurface' yet");
948         return;
949     }
950     auto client = app_list->lookUpClient(id);
951
952     /*
953    * Queueing Phase
954    */
955     unsigned current = app_list->currentRequestNumber();
956     unsigned requested_num = app_list->getRequestNumber(id);
957     if (requested_num != 0)
958     {
959         HMI_SEQ_INFO(requested_num, "%s %s %s request is already queued", id.c_str(), role.c_str(), area.c_str());
960         reply("already requested");
961         return;
962     }
963
964     WMRequest req = WMRequest(id, role, area, Task::TASK_RELEASE);
965     unsigned new_req = app_list->addAllocateRequest(req);
966     app_list->reqDump();
967
968     HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", id.c_str(), role.c_str(), area.c_str());
969
970     reply(nullptr);
971     if (new_req != current)
972     {
973         // Add request, then invoked after the previous task is finished
974         HMI_SEQ_DEBUG(new_req, "request is accepted");
975         return;
976     }
977
978     /*
979     * Do allocate tasks
980     */
981     WMError ret = this->do_transition(new_req);
982
983     if (ret != WMError::SUCCESS)
984     {
985         HMI_SEQ_ERROR(new_req, errorDescription(ret));
986         //this->emit_error()
987     }
988 }
989
990 void App::enqueue_flushdraw(int surface_id)
991 {
992     this->check_flushdraw(surface_id);
993     HMI_DEBUG("wm", "Enqueuing EndDraw for surface_id %d", surface_id);
994     this->pending_end_draw.push_back(surface_id);
995 }
996
997 void App::check_flushdraw(int surface_id)
998 {
999     auto i = std::find(std::begin(this->pending_end_draw),
1000                        std::end(this->pending_end_draw), surface_id);
1001     if (i != std::end(this->pending_end_draw))
1002     {
1003         auto n = this->lookup_name(surface_id);
1004         HMI_ERROR("wm", "Application %s (%d) has pending EndDraw call(s)!",
1005                   n ? n->c_str() : "unknown-name", surface_id);
1006         std::swap(this->pending_end_draw[std::distance(
1007                       std::begin(this->pending_end_draw), i)],
1008                   this->pending_end_draw.back());
1009         this->pending_end_draw.resize(this->pending_end_draw.size() - 1);
1010     }
1011 }
1012
1013 void App::lm_enddraw(const char *drawing_name)
1014 {
1015     HMI_DEBUG("wm", "end draw %s", drawing_name);
1016     for (unsigned i = 0, iend = this->pending_end_draw.size(); i < iend; i++)
1017     {
1018         auto n = this->lookup_name(this->pending_end_draw[i]);
1019         if (n && *n == drawing_name)
1020         {
1021             std::swap(this->pending_end_draw[i], this->pending_end_draw[iend - 1]);
1022             this->pending_end_draw.resize(iend - 1);
1023             this->activate(this->pending_end_draw[i]);
1024             this->emit_flushdraw(drawing_name);
1025         }
1026     }
1027 }
1028
1029 void App::do_enddraw(unsigned req_num)
1030 {
1031     // get actions
1032     bool found;
1033     auto actions = app_list->getActions(req_num, &found);
1034     if (!found)
1035     {
1036         WMError err = WMError::NO_ENTRY;
1037         HMI_SEQ_ERROR(req_num, errorDescription(err));
1038         return;
1039     }
1040
1041     HMI_SEQ_INFO(req_num, "do endDraw");
1042
1043     for (const auto &act : actions)
1044     {
1045         HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str());
1046         this->lm_enddraw(act.role.c_str());
1047     }
1048
1049     HMI_SEQ_INFO(req_num, "emit flushDraw");
1050     /*     do
1051     {
1052         // emit flush Draw
1053         //emitFlushDrawToAll(&app_list, req_num);
1054         // emit status change event
1055     } while (!app_list->requestFinished());*/
1056 }
1057
1058 void App::process_request()
1059 {
1060     unsigned req = app_list->currentRequestNumber();
1061     HMI_SEQ_DEBUG(req, "Do next request");
1062     WMError rc = do_transition(req);
1063     if(rc != WMError::SUCCESS){
1064         HMI_SEQ_ERROR(req, errorDescription(rc));
1065     }
1066 }
1067
1068 void App::api_enddraw(char const *appid, char const *drawing_name)
1069 {
1070     std::string id(appid);
1071     std::string role(drawing_name);
1072     unsigned current_req = app_list->currentRequestNumber();
1073     bool result = app_list->setEndDrawFinished(current_req, id, role);
1074
1075     if (!result)
1076     {
1077         HMI_ERROR("wm", "%s doesn't have Window Resource", id.c_str());
1078         return;
1079     }
1080
1081     if (app_list->endDrawFullfilled(current_req))
1082     {
1083         // do task for endDraw
1084         //this->stop_timer();
1085         this->do_enddraw(current_req);
1086
1087         this->stop_timer();
1088
1089         app_list->removeRequest(current_req);
1090         HMI_SEQ_INFO(current_req, "Finish request");
1091         app_list->next();
1092         if (app_list->haveRequest())
1093         {
1094             this->process_request();
1095         }
1096     }
1097     else
1098     {
1099         HMI_SEQ_INFO(current_req, "Wait other App call endDraw");
1100         return;
1101     }
1102 }
1103
1104 void App::api_ping() { this->dispatch_pending_events(); }
1105
1106 void App::send_event(char const *evname, char const *label)
1107 {
1108     HMI_DEBUG("wm", "%s: %s(%s)", __func__, evname, label);
1109
1110     json_object *j = json_object_new_object();
1111     json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
1112
1113     int ret = afb_event_push(this->map_afb_event[evname], j);
1114     if (ret != 0)
1115     {
1116         HMI_DEBUG("wm", "afb_event_push failed: %m");
1117     }
1118 }
1119
1120 void App::send_event(char const *evname, char const *label, char const *area,
1121                      int x, int y, int w, int h)
1122 {
1123     HMI_DEBUG("wm", "%s: %s(%s, %s) x:%d y:%d w:%d h:%d",
1124               __func__, evname, label, area, x, y, w, h);
1125
1126     json_object *j_rect = json_object_new_object();
1127     json_object_object_add(j_rect, kKeyX, json_object_new_int(x));
1128     json_object_object_add(j_rect, kKeyY, json_object_new_int(y));
1129     json_object_object_add(j_rect, kKeyWidth, json_object_new_int(w));
1130     json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
1131
1132     json_object *j = json_object_new_object();
1133     json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
1134     json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area));
1135     json_object_object_add(j, kKeyDrawingRect, j_rect);
1136
1137     int ret = afb_event_push(this->map_afb_event[evname], j);
1138     if (ret != 0)
1139     {
1140         HMI_DEBUG("wm", "afb_event_push failed: %m");
1141     }
1142 }
1143
1144 /**
1145  * proxied events
1146  */
1147 void App::surface_created(uint32_t surface_id)
1148 {
1149     auto layer_id = this->layers.get_layer_id(surface_id);
1150     if (!layer_id)
1151     {
1152         HMI_DEBUG("wm", "Newly created surfce %d is not associated with any layer!",
1153                   surface_id);
1154         return;
1155     }
1156
1157     HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", surface_id, *layer_id);
1158
1159     this->controller->layers[*layer_id]->add_surface(surface_id);
1160     this->layout_commit();
1161     // For set role function
1162     HMI_DEBUG("wm", "Get surface pid");
1163     this->controller->get_surface_properties(surface_id);
1164
1165     // activate the main_surface right away
1166     /*if (surface_id == static_cast<unsigned>(this->layers.main_surface)) {
1167       HMI_DEBUG("wm", "Activating main_surface (%d)", surface_id);
1168
1169       this->api_activate_surface(
1170          this->lookup_name(surface_id).value_or("unknown-name").c_str());
1171    }*/
1172
1173     // search pid from surfaceID
1174
1175     // pick up appid from pid from application manager
1176
1177     // check appid then add it to the client
1178 }
1179
1180 void App::surface_removed(uint32_t surface_id)
1181 {
1182     HMI_DEBUG("wm", "surface_id is %u", surface_id);
1183
1184     app_list->removeSurface(surface_id);
1185 }
1186
1187 void App::surface_properties(unsigned surface_id, unsigned pid)
1188 {
1189     HMI_DEBUG("wm", "get surface properties");
1190     this->app_list->addFloatingSurface(surface_id, pid);
1191 }
1192
1193 void App::emit_activated(char const *label)
1194 {
1195     this->send_event(kListEventName[Event_Active], label);
1196 }
1197
1198 void App::emit_deactivated(char const *label)
1199 {
1200     this->send_event(kListEventName[Event_Inactive], label);
1201 }
1202
1203 void App::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h)
1204 {
1205     this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
1206 }
1207
1208 void App::emit_flushdraw(char const *label)
1209 {
1210     this->send_event(kListEventName[Event_FlushDraw], label);
1211 }
1212
1213 void App::emit_visible(char const *label, bool is_visible)
1214 {
1215     this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
1216 }
1217
1218 void App::emit_invisible(char const *label)
1219 {
1220     return emit_visible(label, false);
1221 }
1222
1223 void App::emit_visible(char const *label) { return emit_visible(label, true); }
1224
1225 result<int> App::api_request_surface(char const *appid, char const *drawing_name)
1226 {
1227     auto lid = this->layers.get_layer_id(std::string(drawing_name));
1228     if (!lid)
1229     {
1230         /**
1231        * register drawing_name as fallback and make it displayed.
1232        */
1233         lid = this->layers.get_layer_id(std::string("Fallback"));
1234         HMI_DEBUG("wm", "%s is not registered in layers.json, then fallback as normal app", drawing_name);
1235         if (!lid)
1236         {
1237             return Err<int>("Drawing name does not match any role, Fallback is disabled");
1238         }
1239     }
1240
1241     auto rname = this->lookup_id(drawing_name);
1242     if (!rname)
1243     {
1244         // name does not exist yet, allocate surface id...
1245         auto id = int(this->id_alloc.generate_id(drawing_name));
1246         this->layers.add_surface(id, *lid);
1247
1248         // set the main_surface[_name] here and now
1249         if (!this->layers.main_surface_name.empty() &&
1250             this->layers.main_surface_name == drawing_name)
1251         {
1252             this->layers.main_surface = id;
1253             HMI_DEBUG("wm", "Set main_surface id to %u", id);
1254         }
1255
1256         // add client into the db
1257         std::string appid_str(appid);
1258         std::string role(drawing_name);
1259         //app_list->addClient(appid_str, role);
1260         app_list->addClient(appid_str, *lid, id, role);
1261
1262         return Ok<int>(id);
1263     }
1264
1265     // Check currently registered drawing names if it is already there.
1266     return Err<int>("Surface already present");
1267 }
1268
1269 char const *App::api_request_surface(char const *appid, char const *drawing_name,
1270                                      char const *ivi_id)
1271 {
1272     ST();
1273
1274     auto lid = this->layers.get_layer_id(std::string(drawing_name));
1275     unsigned sid = std::stol(ivi_id);
1276
1277     if (!lid)
1278     {
1279         /**
1280        * register drawing_name as fallback and make it displayed.
1281        */
1282         lid = this->layers.get_layer_id(std::string("Fallback"));
1283         HMI_DEBUG("wm", "%s is not registered in layers.json, then fallback as normal app", drawing_name);
1284         if (!lid)
1285         {
1286             return "Drawing name does not match any role, Fallback is disabled";
1287         }
1288     }
1289
1290     auto rname = this->lookup_id(drawing_name);
1291
1292     if (rname)
1293     {
1294         return "Surface already present";
1295     }
1296
1297     // register pair drawing_name and ivi_id
1298     this->id_alloc.register_name_id(drawing_name, sid);
1299     this->layers.add_surface(sid, *lid);
1300
1301     // this surface is already created
1302     HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", sid, *lid);
1303
1304     this->controller->layers[*lid]->add_surface(sid);
1305     this->layout_commit();
1306
1307     return nullptr;
1308 }
1309
1310 /**
1311  * This function is substitute of requestSurface
1312  * If surface creation is faster than application request of this function,
1313  * WM will bind surfaceID with application and role.
1314  * If surface creation is slower than application request of thie function,
1315  * WM will put Client into pending list.
1316  *
1317  * Note :
1318  * Application can request with pid but this is temporary solution for now.
1319  * This will be removed.
1320  * */
1321 bool App::api_set_role(char const *appid, char const *drawing_name, unsigned pid){
1322     std::string id = appid;
1323     std::string role = drawing_name;
1324     unsigned surface = 0;
1325     WMError wm_err = WMError::UNKNOWN;
1326     bool ret = false;
1327
1328     // get layer ID which role should be in
1329     auto lid = this->layers.get_layer_id(role);
1330     if (!lid)
1331     {
1332         /**
1333        * register drawing_name as fallback and make it displayed.
1334        */
1335         lid = this->layers.get_layer_id(std::string("Fallback"));
1336         HMI_DEBUG("wm", "%s is not registered in layers.json, then fallback as normal app", role.c_str());
1337         if (!lid)
1338         {
1339             HMI_ERROR("wm", "Drawing name does not match any role, Fallback is disabled");
1340             return ret;
1341         }
1342     }
1343
1344     if(0 != pid){
1345         // search floating surfaceID from pid if pid is designated.
1346         // It is not good that application request with its pid
1347         wm_err = app_list->popFloatingSurface(pid, &surface);
1348     }
1349     else{
1350         // get floating surface with appid. If WM queries appid from pid,
1351         // WM can bind surface and role with appid(not implemented yet)
1352         //wm_err = app_list->popFloatingSurface(id);
1353     }
1354     if(wm_err != WMError::SUCCESS){
1355         HMI_ERROR("wm", "No floating surface for app: %s", id.c_str());
1356         app_list->addFloatingClient(id, *lid, role);
1357         HMI_NOTICE("wm", "%s : Waiting for surface creation", id.c_str());
1358         return ret;
1359     }
1360
1361     ret = true;
1362     if (app_list->contains(id))
1363     {
1364         HMI_INFO("wm", "Add role: %s with surface: %d. Client %s has multi surfaces.",
1365                  role.c_str(), surface, id.c_str());
1366         wm_err = app_list->appendRole(id, role, surface);
1367         if(wm_err != WMError::SUCCESS){
1368             HMI_INFO("wm", errorDescription(wm_err));
1369         }
1370     }
1371     else{
1372         HMI_INFO("wm", "Create new client: %s, surface: %d into layer: %d with role: %s",
1373                  id.c_str(), surface, *lid, role.c_str());
1374         app_list->addClient(id, *lid, surface, role);
1375     }
1376
1377     // register pair drawing_name and ivi_id
1378     this->id_alloc.register_name_id(role.c_str(), surface);
1379     this->layers.add_surface(surface, *lid);
1380
1381     // this surface is already created
1382     HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", surface, *lid);
1383
1384     this->controller->layers[*lid]->add_surface(surface);
1385     this->layout_commit();
1386
1387     return ret;
1388 }
1389
1390 result<json_object *> App::api_get_display_info()
1391 {
1392     // Check controller
1393     if (!this->controller)
1394     {
1395         return Err<json_object *>("ivi_controller global not available");
1396     }
1397
1398     // Set display info
1399     compositor::size o_size = this->controller->output_size;
1400     compositor::size p_size = this->controller->physical_size;
1401
1402     json_object *object = json_object_new_object();
1403     json_object_object_add(object, kKeyWidthPixel, json_object_new_int(o_size.w));
1404     json_object_object_add(object, kKeyHeightPixel, json_object_new_int(o_size.h));
1405     json_object_object_add(object, kKeyWidthMm, json_object_new_int(p_size.w));
1406     json_object_object_add(object, kKeyHeightMm, json_object_new_int(p_size.h));
1407
1408     return Ok<json_object *>(object);
1409 }
1410
1411 result<json_object *> App::api_get_area_info(char const *drawing_name)
1412 {
1413     HMI_DEBUG("wm", "called");
1414
1415     // Check drawing name, surface/layer id
1416     auto const &surface_id = this->lookup_id(drawing_name);
1417     if (!surface_id)
1418     {
1419         return Err<json_object *>("Surface does not exist");
1420     }
1421
1422     if (!this->controller->surface_exists(*surface_id))
1423     {
1424         return Err<json_object *>("Surface does not exist in controller!");
1425     }
1426
1427     auto layer_id = this->layers.get_layer_id(*surface_id);
1428     if (!layer_id)
1429     {
1430         return Err<json_object *>("Surface is not on any layer!");
1431     }
1432
1433     auto o_state = *this->layers.get_layout_state(*surface_id);
1434     if (o_state == nullptr)
1435     {
1436         return Err<json_object *>("Could not find layer for surface");
1437     }
1438
1439     struct LayoutState &state = *o_state;
1440     if ((state.main != *surface_id) && (state.sub != *surface_id))
1441     {
1442         return Err<json_object *>("Surface is inactive");
1443     }
1444
1445     // Set area rectangle
1446     compositor::rect area_info = this->area_info[*surface_id];
1447     json_object *object = json_object_new_object();
1448     json_object_object_add(object, kKeyX, json_object_new_int(area_info.x));
1449     json_object_object_add(object, kKeyY, json_object_new_int(area_info.y));
1450     json_object_object_add(object, kKeyWidth, json_object_new_int(area_info.w));
1451     json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
1452
1453     return Ok<json_object *>(object);
1454 }
1455
1456 void App::activate(int id)
1457 {
1458     auto ip = this->controller->sprops.find(id);
1459     if (ip != this->controller->sprops.end())
1460     {
1461         this->controller->surfaces[id]->set_visibility(1);
1462         char const *label =
1463             this->lookup_name(id).value_or("unknown-name").c_str();
1464
1465         // FOR CES DEMO >>>
1466         if ((0 == strcmp(label, "Radio")) || (0 == strcmp(label, "MediaPlayer")) || (0 == strcmp(label, "Music")) || (0 == strcmp(label, "Navigation")))
1467         {
1468             for (auto i = surface_bg.begin(); i != surface_bg.end(); ++i)
1469             {
1470                 if (id == *i)
1471                 {
1472                     // Remove id
1473                     this->surface_bg.erase(i);
1474
1475                     // Remove from BG layer (999)
1476                     HMI_DEBUG("wm", "Remove %s(%d) from BG layer", label, id);
1477                     this->controller->layers[999]->remove_surface(id);
1478
1479                     // Add to FG layer (1001)
1480                     HMI_DEBUG("wm", "Add %s(%d) to FG layer", label, id);
1481                     this->controller->layers[1001]->add_surface(id);
1482
1483                     for (int j : this->surface_bg)
1484                     {
1485                         HMI_DEBUG("wm", "Stored id:%d", j);
1486                     }
1487                     break;
1488                 }
1489             }
1490         }
1491         // <<< FOR CES DEMO
1492         this->layout_commit();
1493
1494         this->emit_visible(label);
1495         this->emit_activated(label);
1496     }
1497 }
1498
1499 void App::deactivate(int id)
1500 {
1501     auto ip = this->controller->sprops.find(id);
1502     if (ip != this->controller->sprops.end())
1503     {
1504         char const *label =
1505             this->lookup_name(id).value_or("unknown-name").c_str();
1506
1507         // FOR CES DEMO >>>
1508         if ((0 == strcmp(label, "Radio")) || (0 == strcmp(label, "MediaPlayer")) || (0 == strcmp(label, "Music")) || (0 == strcmp(label, "Navigation")))
1509         {
1510
1511             // Store id
1512             this->surface_bg.push_back(id);
1513
1514             // Remove from FG layer (1001)
1515             HMI_DEBUG("wm", "Remove %s(%d) from FG layer", label, id);
1516             this->controller->layers[1001]->remove_surface(id);
1517
1518             // Add to BG layer (999)
1519             HMI_DEBUG("wm", "Add %s(%d) to BG layer", label, id);
1520             this->controller->layers[999]->add_surface(id);
1521
1522             for (int j : surface_bg)
1523             {
1524                 HMI_DEBUG("wm", "Stored id:%d", j);
1525             }
1526         }
1527         else
1528         {
1529             this->controller->surfaces[id]->set_visibility(0);
1530         }
1531         // <<< FOR CES DEMO
1532
1533         this->emit_deactivated(label);
1534         this->emit_invisible(label);
1535     }
1536 }
1537
1538 void App::deactivate_main_surface()
1539 {
1540     this->layers.main_surface = -1;
1541     std::string appid = "HomeScreen";
1542     this->api_deactivate_surface(appid.c_str(), this->layers.main_surface_name.c_str(), [](const char *) {});
1543 }
1544
1545 bool App::can_split(struct LayoutState const &state, int new_id)
1546 {
1547     if (state.main != -1 && state.main != new_id)
1548     {
1549         auto new_id_layer = this->layers.get_layer_id(new_id).value();
1550         auto current_id_layer = this->layers.get_layer_id(state.main).value();
1551
1552         // surfaces are on separate layers, don't bother.
1553         if (new_id_layer != current_id_layer)
1554         {
1555             return false;
1556         }
1557
1558         std::string const &new_id_str = this->lookup_name(new_id).value();
1559         std::string const &cur_id_str = this->lookup_name(state.main).value();
1560
1561         auto const &layer = this->layers.get_layer(new_id_layer);
1562
1563         HMI_DEBUG("wm", "layer info name: %s", layer->name.c_str());
1564
1565         if (layer->layouts.empty())
1566         {
1567             return false;
1568         }
1569
1570         for (auto i = layer->layouts.cbegin(); i != layer->layouts.cend(); i++)
1571         {
1572             HMI_DEBUG("wm", "%d main_match '%s'", new_id_layer, i->main_match.c_str());
1573             auto rem = std::regex(i->main_match);
1574             if (std::regex_match(cur_id_str, rem))
1575             {
1576                 // build the second one only if the first already matched
1577                 HMI_DEBUG("wm", "%d sub_match '%s'", new_id_layer, i->sub_match.c_str());
1578                 auto res = std::regex(i->sub_match);
1579                 if (std::regex_match(new_id_str, res))
1580                 {
1581                     HMI_DEBUG("wm", "layout matched!");
1582                     return true;
1583                 }
1584             }
1585         }
1586     }
1587
1588     return false;
1589 }
1590
1591 void App::try_layout(struct LayoutState & /*state*/,
1592                      struct LayoutState const &new_layout,
1593                      std::function<void(LayoutState const &nl)> apply)
1594 {
1595     if (this->policy.layout_is_valid(new_layout))
1596     {
1597         apply(new_layout);
1598     }
1599 }
1600
1601 /**
1602  * controller_hooks
1603  */
1604 void controller_hooks::surface_created(uint32_t surface_id)
1605 {
1606     this->app->surface_created(surface_id);
1607 }
1608
1609 void controller_hooks::surface_removed(uint32_t surface_id)
1610 {
1611     this->app->surface_removed(surface_id);
1612 }
1613
1614 void controller_hooks::surface_properties(uint32_t surface_id, uint32_t pid)
1615 {
1616     this->app->surface_properties(surface_id, pid);
1617 }
1618
1619 void controller_hooks::surface_visibility(uint32_t /*surface_id*/,
1620                                           uint32_t /*v*/) {}
1621
1622 void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/,
1623                                                      uint32_t /*x*/,
1624                                                      uint32_t /*y*/,
1625                                                      uint32_t /*w*/,
1626                                                      uint32_t /*h*/) {}
1627
1628 } // namespace wm