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