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