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