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