fix bug
[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 #include <sstream>
20
21 #include "window_manager.hpp"
22 #include "json_helper.hpp"
23 #include "applist.hpp"
24
25 extern "C"
26 {
27 #include <systemd/sd-event.h>
28 }
29
30 using std::string;
31 using std::vector;
32
33 namespace wm
34 {
35
36 static const uint64_t kTimeOut = 3ULL; /* 3s */
37
38 /* DrawingArea name used by "{layout}.{area}" */
39 const char kNameLayoutNormal[] = "normal";
40 const char kNameLayoutSplit[]  = "split";
41 const char kNameAreaFull[]     = "full";
42 const char kNameAreaMain[]     = "main";
43 const char kNameAreaSub[]      = "sub";
44
45 /* Key for json obejct */
46 const char kKeyDrawingName[] = "drawing_name";
47 const char kKeyDrawingArea[] = "drawing_area";
48 const char kKeyDrawingRect[] = "drawing_rect";
49 const char kKeyX[]           = "x";
50 const char kKeyY[]           = "y";
51 const char kKeyWidth[]       = "width";
52 const char kKeyHeight[]      = "height";
53 const char kKeyWidthPixel[]  = "width_pixel";
54 const char kKeyHeightPixel[] = "height_pixel";
55 const char kKeyWidthMm[]     = "width_mm";
56 const char kKeyHeightMm[]    = "height_mm";
57 const char kKeyScale[]       = "scale";
58 const char kKeyIds[]         = "ids";
59
60 static sd_event_source *g_timer_ev_src = nullptr;
61 static AppList g_app_list;
62 static WindowManager *g_context;
63
64 struct AfbClosure {
65 public:
66     AfbClosure(unsigned pid, unsigned ppid, unsigned surface)
67         : pid(pid), ppid(ppid), surface(surface) {}
68     ~AfbClosure() = default;
69     unsigned pid;
70     unsigned ppid;
71     unsigned surface;
72 };
73
74 namespace
75 {
76
77 static int processTimerHandler(sd_event_source *s, uint64_t usec, void *userdata)
78 {
79     HMI_NOTICE("Time out occurs because the client replys endDraw slow, so revert the request");
80     reinterpret_cast<wm::WindowManager *>(userdata)->timerHandler();
81     return 0;
82 }
83
84 static void onStateTransitioned(vector<WMAction> actions)
85 {
86     g_context->startTransitionWrapper(actions);
87 }
88
89 static void onError()
90 {
91     g_context->processError(WMError::LAYOUT_CHANGE_FAIL);
92 }
93 } // namespace
94
95 /**
96  * WindowManager Impl
97  */
98 WindowManager::WindowManager()
99     : id_alloc{}
100 {
101     const char *path = getenv("AFM_APP_INSTALL_DIR");
102     if (!path)
103     {
104         HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
105     }
106     string root = path;
107
108     this->lc = std::make_shared<LayerControl>(root);
109
110     HMI_DEBUG("Layer Controller initialized");
111 }
112
113 int WindowManager::init()
114 {
115     // TODO: application requests by old role,
116     //       so create role map (old, new)
117     // Load old_role.db
118     LayerControlCallbacks lmcb;
119     lmcb.surfaceCreated = [&](unsigned pid, unsigned surface){
120         this->surface_created(pid, surface);
121         };
122     lmcb.surfaceDestroyed = [&](unsigned surface){
123         this->surface_removed(surface);
124     };
125     this->lc->init(lmcb);
126     this->loadOldRoleDb();
127
128     // Store my context for calling callback from PolicyManager
129     g_context = this;
130
131     // Initialize PMWrapper
132     this->pmw.initialize();
133
134     // Register callback to PolicyManager
135     this->pmw.registerCallback(onStateTransitioned, onError);
136
137     // Make afb event
138     for (int i = Event_Val_Min; i <= Event_Val_Max; i++)
139     {
140         map_afb_event[kListEventName[i]] = afb_daemon_make_event(kListEventName[i]);
141     }
142
143     const struct rect css_bg = this->lc->getAreaSize("fullscreen");
144     Screen screen = this->lc->getScreenInfo();
145     rectangle dp_bg(screen.width(), screen.height());
146
147     dp_bg.set_aspect(static_cast<double>(css_bg.w) / css_bg.h);
148     dp_bg.fit(screen.width(), screen.height());
149     dp_bg.center(screen.width(), screen.height());
150     HMI_DEBUG("SCALING: CSS BG(%dx%d) -> DDP %dx%d,(%dx%d)",
151               css_bg.w, css_bg.h, dp_bg.left(), dp_bg.top(), dp_bg.width(), dp_bg.height());
152
153     double scale = static_cast<double>(dp_bg.height()) / css_bg.h;
154     this->lc->setupArea(dp_bg, scale);
155
156     return 0; //init_layers();
157 }
158
159 result<int> WindowManager::api_request_surface(char const *appid, char const *drawing_name)
160 {
161     // TODO: application requests by old role,
162     //       so convert role old to new
163     const char *role = this->convertRoleOldToNew(drawing_name);
164     string l_name;
165     string s_appid = appid;
166     string s_role = role;
167
168     if(!g_app_list.contains(s_appid))
169     {
170         // auto lid = this->layers.get_layer_id(string(role));
171         unsigned l_id = this->lc->getNewLayerID(s_role, &l_name);
172         if (l_id == 0)
173         {
174             /**
175              * register drawing_name as fallback and make it displayed.
176              */
177             l_id = this->lc->getNewLayerID("fallback", &l_name);
178             HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
179             if (l_id == 0)
180             {
181                 return Err<int>("Designated role does not match any role, fallback is disabled");
182             }
183         }
184         this->lc->createNewLayer(l_id);
185         // add client into the db
186         g_app_list.addClient(s_appid, l_id, s_role);
187     }
188
189     // generate surface ID for ivi-shell application
190
191     auto rname = this->id_alloc.lookup(string(role));
192     if (!rname)
193     {
194         // name does not exist yet, allocate surface id...
195         auto id = int(this->id_alloc.generate_id(role));
196         this->tmp_surface2app[id] = {s_appid, 0};
197
198         // Set role map of (new, old)
199         this->rolenew2old[role] = string(drawing_name);
200
201         return Ok<int>(id);
202     }
203
204     // Check currently registered drawing names if it is already there.
205     return Err<int>("Surface already present");
206 }
207
208 char const *WindowManager::api_request_surface(char const *appid, char const *drawing_name,
209                                      char const *ivi_id)
210 {
211     unsigned sid = std::stol(ivi_id);
212
213     HMI_DEBUG("This API(requestSurfaceXDG) is for XDG Application using runXDG");
214     /*
215      * IVI-shell doesn't send surface_size event via ivi-wm protocol
216      * if the application is using XDG surface.
217      * So WM has to set surface size with original size here
218      */
219     WMError ret = this->lc->setXDGSurfaceOriginSize(sid);
220     if(ret != SUCCESS)
221     {
222         HMI_ERROR("%s", errorDescription(ret));
223         HMI_WARNING("The main user of this API is runXDG");
224         return "fail";
225     }
226
227     // TODO: application requests by old role,
228     //       so convert role old to new
229     const char *role = this->convertRoleOldToNew(drawing_name);
230     string s_role = role;
231     string s_appid = appid;
232     string l_name;
233
234     if(!g_app_list.contains(s_appid))
235     {
236         // auto lid = this->layers.get_layer_id(string(role));
237         unsigned l_id = this->lc->getNewLayerID(s_role, &l_name);
238         if (l_id == 0)
239         {
240             /**
241              * register drawing_name as fallback and make it displayed.
242              */
243             l_id = this->lc->getNewLayerID("fallback", &l_name);
244             HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
245             if (l_id == 0)
246             {
247                 return "Designated role does not match any role, fallback is disabled";
248             }
249         }
250         this->lc->createNewLayer(l_id);
251         // add client into the db
252         g_app_list.addClient(s_appid, l_id, s_role);
253     }
254
255     auto rname = this->id_alloc.lookup(s_role);
256     if (rname)
257     {
258         return "Surface already present";
259     }
260
261     // register pair drawing_name and ivi_id
262     this->id_alloc.register_name_id(role, sid);
263
264     auto client = g_app_list.lookUpClient(s_appid);
265     client->addSurface(sid);
266
267     // Set role map of (new, old)
268     this->rolenew2old[role] = string(drawing_name);
269
270     return nullptr;
271 }
272
273 bool WindowManager::api_set_role(char const *appid, char const *drawing_name)
274 {
275     bool ret = false;
276
277     // TODO: application requests by old role,
278     //       so convert role old to new
279     const char *role = this->convertRoleOldToNew(drawing_name);
280     string s_role = role;
281     string s_appid = appid;
282     string l_name;
283
284     // Create WMClient
285     if(!g_app_list.contains(s_appid))
286     {
287         // auto lid = this->layers.get_layer_id(string(role));
288         unsigned l_id = this->lc->getNewLayerID(s_role, &l_name);
289         if (l_id == 0)
290         {
291             /**
292              * register drawing_name as fallback and make it displayed.
293              */
294             l_id = this->lc->getNewLayerID("fallback", &l_name);
295             HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
296             if (l_id == 0)
297             {
298                 HMI_ERROR("Designated role does not match any role, fallback is disabled");
299                 return ret;
300             }
301         }
302         this->lc->createNewLayer(l_id);
303         // add client into the db
304         g_app_list.addClient(s_appid, l_id, s_role);
305         // Set role map of (new, old)
306         this->rolenew2old[role] = string(drawing_name);
307     }
308
309     // for(auto itr = this->tmp_surface2app.begin();
310     //         itr != this->tmp_surface2app.end() ; ++itr)
311     // {
312     for(auto& x : this->tmp_surface2app)
313     {
314         if(x.second.appid == s_appid)
315         {
316             unsigned surface = x.first;
317             auto client = g_app_list.lookUpClient(s_appid);
318             client->addSurface(surface);
319             this->tmp_surface2app.erase(surface);
320             this->id_alloc.register_name_id(s_role, surface);
321             break;
322         }
323     }
324
325 /*     if(0 != pid){
326         // search floating surfaceID from pid if pid is designated.
327         wm_err = g_app_list.popFloatingSurface(pid, &surface);
328     }
329     else{
330         // get floating surface with appid. If WM queries appid from pid,
331         // WM can bind surface and role with appid(not implemented yet)
332         //wm_err = g_app_list.popFloatingSurface(id);
333     }
334     if(wm_err != WMError::SUCCESS){
335         HMI_ERROR("No floating surface for app: %s", id.c_str());
336         g_app_list.addFloatingClient(id, lid, role);
337         HMI_NOTICE("%s : Waiting for surface creation", id.c_str());
338         return ret;
339     }
340
341     ret = true;
342     if (g_app_list.contains(id))
343     {
344         HMI_INFO("Add role: %s with surface: %d. Client %s has multi surfaces.",
345                  role.c_str(), surface, id.c_str());
346         auto client = g_app_list.lookUpClient(id);
347         client->appendRole(role);
348     }
349     else{
350         HMI_INFO("Create new client: %s, surface: %d into layer: %d with role: %s",
351                  id.c_str(), surface, lid, role.c_str());
352         g_app_list.addClient(id, lid, role);
353     } */
354
355     // register pair drawing_name and ivi_id
356
357     return true;
358 }
359
360 void WindowManager::api_activate_surface(char const *appid, char const *drawing_name,
361                                char const *drawing_area, const reply_func &reply)
362 {
363     // TODO: application requests by old role,
364     //       so convert role old to new
365     const char *c_role = this->convertRoleOldToNew(drawing_name);
366
367     string id = appid;
368     string role = c_role;
369     string area = drawing_area;
370
371     if(!g_app_list.contains(id))
372     {
373         reply("app doesn't request 'requestSurface' or 'setRole' yet");
374         return;
375     }
376     auto client = g_app_list.lookUpClient(id);
377
378     // unsigned srfc = client->surfaceID(role);
379     // unsigned layer = client->layerID();
380
381     // g_app_list.removeFloatingSurface(client->surfaceID());
382     // g_app_list.removeFloatingSurface(client);
383
384     Task task = Task::TASK_ALLOCATE;
385     unsigned req_num = 0;
386     WMError ret = WMError::UNKNOWN;
387
388     ret = this->setRequest(id, role, area, task, &req_num);
389
390     //vector<WMLayerState> current_states = this->lc->getCurrentStates();
391     // ret = this->setRequest(id, role, area, task, current_states, &req_num);
392
393     if(ret != WMError::SUCCESS)
394     {
395         HMI_ERROR(errorDescription(ret));
396         reply("Failed to set request");
397         return;
398     }
399
400     reply(nullptr);
401     if (req_num != g_app_list.currentRequestNumber())
402     {
403         // Add request, then invoked after the previous task is finished
404         HMI_SEQ_DEBUG(req_num, "request is accepted");
405         return;
406     }
407
408     /*
409      * Do allocate tasks
410      */
411     ret = this->checkPolicy(req_num);
412
413     if (ret != WMError::SUCCESS)
414     {
415         //this->emit_error()
416         HMI_SEQ_ERROR(req_num, errorDescription(ret));
417         g_app_list.removeRequest(req_num);
418         this->processNextRequest();
419     }
420 }
421
422 void WindowManager::api_deactivate_surface(char const *appid, char const *drawing_name,
423                                  const reply_func &reply)
424 {
425     // TODO: application requests by old role,
426     //       so convert role old to new
427     const char *c_role = this->convertRoleOldToNew(drawing_name);
428
429     /*
430     * Check Phase
431     */
432     string id = appid;
433     string role = c_role;
434     string area = ""; //drawing_area;
435     Task task = Task::TASK_RELEASE;
436     unsigned req_num = 0;
437     WMError ret = WMError::UNKNOWN;
438
439     ret = this->setRequest(id, role, area, task, &req_num);
440
441     if (ret != WMError::SUCCESS)
442     {
443         HMI_ERROR(errorDescription(ret));
444         reply("Failed to set request");
445         return;
446     }
447
448     reply(nullptr);
449     if (req_num != g_app_list.currentRequestNumber())
450     {
451         // Add request, then invoked after the previous task is finished
452         HMI_SEQ_DEBUG(req_num, "request is accepted");
453         return;
454     }
455
456     /*
457     * Do allocate tasks
458     */
459     ret = this->checkPolicy(req_num);
460
461     if (ret != WMError::SUCCESS)
462     {
463         //this->emit_error()
464         HMI_SEQ_ERROR(req_num, errorDescription(ret));
465         g_app_list.removeRequest(req_num);
466         this->processNextRequest();
467     }
468 }
469
470 void WindowManager::api_enddraw(char const *appid, char const *drawing_name)
471 {
472     // TODO: application requests by old role,
473     //       so convert role old to new
474     const char *c_role = this->convertRoleOldToNew(drawing_name);
475
476     string id = appid;
477     string role = c_role;
478     unsigned current_req = g_app_list.currentRequestNumber();
479     bool result = g_app_list.setEndDrawFinished(current_req, id, role);
480
481     if (!result)
482     {
483         HMI_ERROR("%s is not in transition state", id.c_str());
484         return;
485     }
486
487     if (g_app_list.endDrawFullfilled(current_req))
488     {
489         // do task for endDraw
490         this->stopTimer();
491         WMError ret = this->doEndDraw(current_req);
492
493         if(ret != WMError::SUCCESS)
494         {
495             //this->emit_error();
496
497             // Undo state of PolicyManager
498             this->pmw.undoState();
499             this->lc->undoUpdate();
500         }
501         this->emitScreenUpdated(current_req);
502         HMI_SEQ_INFO(current_req, "Finish request status: %s", errorDescription(ret));
503
504         g_app_list.removeRequest(current_req);
505
506         this->processNextRequest();
507     }
508     else
509     {
510         HMI_SEQ_INFO(current_req, "Wait other App call endDraw");
511         return;
512     }
513 }
514
515 bool WindowManager::api_client_set_render_order(char const* appid, const vector<string>& render_order)
516 {
517     bool ret = false;
518     string id = appid;
519     auto client = g_app_list.lookUpClient(id);
520     if(client)
521     {
522         client->setRenderOrder(render_order);
523     }
524     return ret;
525 }
526
527 string WindowManager::api_client_attach_service_surface
528     (const char* appid, const char* dest, const char* service_surface)
529 {
530     string uuid, s_dest = dest;
531     auto client = g_app_list.lookUpClient(s_dest);
532     if(!client)
533     {
534         HMI_ERROR("Failed to look up destination [%s]", dest);
535         return uuid;
536     }
537     uuid = client->attachTmpServiceSurface(appid, service_surface);
538     this->tmp_services.emplace_back(TmpService{appid, dest, service_surface, uuid});
539     return uuid;
540 }
541
542 result<json_object *> WindowManager::api_get_display_info()
543 {
544     Screen screen = this->lc->getScreenInfo();
545
546     json_object *object = json_object_new_object();
547     json_object_object_add(object, kKeyWidthPixel, json_object_new_int(screen.width()));
548     json_object_object_add(object, kKeyHeightPixel, json_object_new_int(screen.height()));
549     // TODO: set size
550     json_object_object_add(object, kKeyWidthMm, json_object_new_int(0));
551     json_object_object_add(object, kKeyHeightMm, json_object_new_int(0));
552     json_object_object_add(object, kKeyScale, json_object_new_double(this->lc->scale()));
553
554     return Ok<json_object *>(object);
555 }
556
557 result<json_object *> WindowManager::api_get_area_info(char const *drawing_name)
558 {
559     HMI_DEBUG("called");
560
561     // TODO: application requests by old role,
562     //       so convert role old to new
563     const char *role = this->convertRoleOldToNew(drawing_name);
564
565     // Check drawing name, surface/layer id
566     auto const &surface_id = this->id_alloc.lookup(string(role));
567     if (!surface_id)
568     {
569         return Err<json_object *>("Surface does not exist");
570     }
571
572     // Set area rectangle
573     rect area_info = this->area_info[*surface_id];
574     json_object *object = json_object_new_object();
575     json_object_object_add(object, kKeyX, json_object_new_int(area_info.x));
576     json_object_object_add(object, kKeyY, json_object_new_int(area_info.y));
577     json_object_object_add(object, kKeyWidth, json_object_new_int(area_info.w));
578     json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
579
580     return Ok<json_object *>(object);
581 }
582
583 void WindowManager::send_event(char const *evname, char const *label)
584 {
585     HMI_DEBUG("%s: %s(%s)", __func__, evname, label);
586
587     json_object *j = json_object_new_object();
588     json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
589
590     int ret = afb_event_push(this->map_afb_event[evname], j);
591     if (ret != 0)
592     {
593         HMI_DEBUG("afb_event_push failed: %m");
594     }
595 }
596
597 void WindowManager::send_event(char const *evname, char const *label, char const *area,
598                      int x, int y, int w, int h)
599 {
600     HMI_DEBUG("%s: %s(%s, %s) x:%d y:%d w:%d h:%d",
601               __func__, evname, label, area, x, y, w, h);
602
603     json_object *j_rect = json_object_new_object();
604     json_object_object_add(j_rect, kKeyX, json_object_new_int(x));
605     json_object_object_add(j_rect, kKeyY, json_object_new_int(y));
606     json_object_object_add(j_rect, kKeyWidth, json_object_new_int(w));
607     json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
608
609     json_object *j = json_object_new_object();
610     json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
611     json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area));
612     json_object_object_add(j, kKeyDrawingRect, j_rect);
613
614     int ret = afb_event_push(this->map_afb_event[evname], j);
615     if (ret != 0)
616     {
617         HMI_DEBUG("afb_event_push failed: %m");
618     }
619 }
620
621 string WindowManager::searchApp(unsigned pid, unsigned ppid, unsigned surface, json_object* resp)
622 {
623     // retrieve appid from pid from application manager
624     string appid;
625     // check appid then add it to the client
626     HMI_INFO("Runners:%s", json_object_get_string(resp));
627     int size = json_object_array_length(resp);
628     HMI_INFO("pid %d, ppid %d, surface %d",pid, ppid, surface);
629     for(int i = 0; i < size; i++)
630     {
631         json_object *j = json_object_array_get_idx(resp, i);
632         int runid      = jh::getIntFromJson(j, "runid");
633         const char* id = jh::getStringFromJson(j, "id");
634         HMI_DEBUG("Appid %s, runid %d", id, runid);
635         if(id && (runid == ppid))
636         {
637             string s_id = id;
638             s_id.erase(s_id.find('@'));
639             appid = s_id;
640             HMI_INFO("App found %s", appid.c_str());
641             break;
642         }
643     }
644     if(appid.empty())
645     {
646         HMI_WARNING("Failed to retrieve id");
647     }
648     return appid;
649 }
650
651 void WindowManager::storeSurface(const string& appid, unsigned ppid, unsigned surface)
652 {
653     auto elem = std::find_if(this->tmp_services.begin(), this->tmp_services.end(),
654                 [&appid](TmpService& ts){
655                     return (ts.dest == appid );
656                 });
657
658     if(elem != this->tmp_services.end())
659     {
660         // attachApp
661         auto client = g_app_list.lookUpClient(elem->dest);
662         if(client == nullptr)
663         {
664             return;
665         }
666         HMI_INFO("Attach surface %d (service %s) to app %s", surface, elem->service.c_str(), elem->dest.c_str());
667         client->attachServiceSurface(elem->service, surface);
668     }
669     else
670     {
671         // setRole
672         auto client = g_app_list.lookUpClient(appid);
673         if(client != nullptr)
674         {
675             client->addSurface(surface);
676             this->id_alloc.register_name_id(client->role(), surface);
677         }
678         else
679         {
680             // Store tmp surface and appid for application
681             // who requests setRole after creating shell surface
682             this->tmp_surface2app.emplace(surface, TmpClient{appid, ppid});
683         }
684     }
685 }
686
687 /**
688  * proxied events
689  */
690 void WindowManager::surface_created(unsigned pid, unsigned surface_id)
691 {
692     // requestSurface
693     if(this->tmp_surface2app.count(surface_id) != 0)
694     {
695         string appid = this->tmp_surface2app[surface_id].appid;
696         auto client = g_app_list.lookUpClient(appid);
697         if(client != nullptr)
698         {
699             WMError ret = client->addSurface(surface_id);
700             HMI_INFO("Add surface %d to \"%s\"", surface_id, appid.c_str());
701             if(ret != WMError::SUCCESS)
702             {
703                 HMI_ERROR("Failed to add surface to client %s", client->appID().c_str());
704             }
705         }
706         this->tmp_surface2app.erase(surface_id);
707     }
708     else
709     {
710         HMI_NOTICE("Unknown surface %d", surface_id);
711         // retrieve ppid
712         std::ostringstream os;
713         os << pid ;
714         string path = "/proc/" + os.str() + "/stat";
715         std::ifstream ifs(path.c_str());
716         string str;
717         unsigned ppid = 0;
718         if(!ifs.fail() && std::getline(ifs, str))
719         {
720             std::sscanf(str.data(), "%*d %*s %*c %d", &ppid);
721             HMI_INFO("Retrieve ppid %d", ppid);
722         }
723         else
724         {
725             HMI_ERROR("Failed to open /proc/%d/stat", pid);
726             HMI_ERROR("File system may be different");
727             return;
728         }
729         struct AfbClosure* c = new struct AfbClosure(pid, ppid, surface_id);
730         // search pid from surfaceID
731         afb_service_call("afm-main", "runners", json_object_new_object(),
732             [](void* closure, int stat, json_object* resp){
733                 HMI_DEBUG("check %s", json_object_get_string(resp));
734                 struct AfbClosure* c = static_cast<struct AfbClosure*>(closure);
735                 HMI_DEBUG("check");
736                 if(stat != 0)
737                 {
738                     HMI_ERROR("Failed to call runners");
739                 }
740                 else
741                 {
742                     json_object* j;
743                     json_object_object_get_ex(resp, "response", &j);
744                     string appid = g_context->searchApp(c->pid, c->ppid, c->surface, j);
745                     if(!appid.empty())
746                     {
747                         g_context->storeSurface(appid, c->ppid, c->surface);
748                     }
749                 }
750                 json_object_put(resp);
751                 delete c;
752             }, c);
753     }
754 }
755
756 void WindowManager::surface_removed(unsigned surface_id)
757 {
758     HMI_DEBUG("Delete surface_id %u", surface_id);
759     this->id_alloc.remove_id(surface_id);
760     // this->layers.remove_surface(surface_id);
761     g_app_list.removeSurface(surface_id);
762 }
763
764 void WindowManager::removeClient(const string &appid)
765 {
766     HMI_DEBUG("Remove clinet %s from list", appid.c_str());
767     auto client = g_app_list.lookUpClient(appid);
768     this->lc->terminateApp(client);
769     g_app_list.removeClient(appid);
770 }
771
772 void WindowManager::exceptionProcessForTransition()
773 {
774     unsigned req_num = g_app_list.currentRequestNumber();
775     HMI_SEQ_NOTICE(req_num, "Process exception handling for request. Remove current request %d", req_num);
776     g_app_list.removeRequest(req_num);
777     HMI_SEQ_NOTICE(g_app_list.currentRequestNumber(), "Process next request if exists");
778     this->processNextRequest();
779 }
780
781 void WindowManager::timerHandler()
782 {
783     unsigned req_num = g_app_list.currentRequestNumber();
784     HMI_SEQ_DEBUG(req_num, "Timer expired remove Request");
785     g_app_list.reqDump();
786     g_app_list.removeRequest(req_num);
787     this->processNextRequest();
788 }
789
790 void WindowManager::startTransitionWrapper(vector<WMAction> &actions)
791 {
792     WMError ret;
793     // req_num is guaranteed by Window Manager
794     unsigned req_num = g_app_list.currentRequestNumber();
795
796     if (actions.empty())
797     {
798         if (g_app_list.haveRequest())
799         {
800             HMI_SEQ_DEBUG(req_num, "There is no WMAction for this request");
801             goto proc_remove_request;
802         }
803         else
804         {
805             HMI_SEQ_DEBUG(req_num, "There is no request");
806             return;
807         }
808     }
809
810     for (auto &act : actions)
811     {
812         if ("" != act.role)
813         {
814             bool found;
815             auto const &surface_id = this->id_alloc.lookup(act.role.c_str());
816             if(surface_id == nullopt)
817             {
818                 goto proc_remove_request;
819             }
820             std::string appid = g_app_list.getAppID(*surface_id, &found);
821             if (!found)
822             {
823                 if (TaskVisible::INVISIBLE == act.visible)
824                 {
825                     // App is killed, so do not set this action
826                     continue;
827                 }
828                 else
829                 {
830                     HMI_SEQ_ERROR(req_num, "appid which is visible is not found");
831                     ret = WMError::FAIL;
832                     goto error;
833                 }
834             }
835             auto client = g_app_list.lookUpClient(appid);
836             act.req_num = req_num;
837             act.client = client;
838         }
839
840         ret = g_app_list.setAction(req_num, act);
841         if (ret != WMError::SUCCESS)
842         {
843             HMI_SEQ_ERROR(req_num, "Setting action is failed");
844             goto error;
845         }
846     }
847
848     HMI_SEQ_DEBUG(req_num, "Start transition.");
849     ret = this->startTransition(req_num);
850     if (ret != WMError::SUCCESS)
851     {
852         if (ret == WMError::NO_LAYOUT_CHANGE)
853         {
854             goto proc_remove_request;
855         }
856         else
857         {
858             HMI_SEQ_ERROR(req_num, "Transition state is failed");
859             goto error;
860         }
861     }
862
863     return;
864
865 error:
866     //this->emit_error()
867     HMI_SEQ_ERROR(req_num, errorDescription(ret));
868     this->pmw.undoState();
869
870 proc_remove_request:
871     g_app_list.removeRequest(req_num);
872     this->processNextRequest();
873 }
874
875 void WindowManager::processError(WMError error)
876 {
877     unsigned req_num = g_app_list.currentRequestNumber();
878
879     //this->emit_error()
880     HMI_SEQ_ERROR(req_num, errorDescription(error));
881     g_app_list.removeRequest(req_num);
882     this->processNextRequest();
883 }
884
885 /*
886  ******* Private Functions *******
887  */
888
889 void WindowManager::emit_activated(char const *label)
890 {
891     this->send_event(kListEventName[Event_Active], label);
892 }
893
894 void WindowManager::emit_deactivated(char const *label)
895 {
896     this->send_event(kListEventName[Event_Inactive], label);
897 }
898
899 void WindowManager::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h)
900 {
901     this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
902 }
903
904 void WindowManager::emit_syncdraw(const string &role, const string &area)
905 {
906     rect rect = this->lc->getAreaSize(area);
907     this->send_event(kListEventName[Event_SyncDraw],
908         role.c_str(), area.c_str(), rect.x, rect.y, rect.w, rect.h);
909 }
910
911 void WindowManager::emit_flushdraw(char const *label)
912 {
913     this->send_event(kListEventName[Event_FlushDraw], label);
914 }
915
916 void WindowManager::emit_visible(char const *label, bool is_visible)
917 {
918     this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
919 }
920
921 void WindowManager::emit_invisible(char const *label)
922 {
923     return emit_visible(label, false);
924 }
925
926 void WindowManager::emit_visible(char const *label) { return emit_visible(label, true); }
927
928 void WindowManager::activate(int id)
929 {
930     // TODO: application requests by old role,
931     //       so convert role new to old for emitting event
932     /* const char* old_role = this->rolenew2old[label].c_str();
933
934     this->emit_visible(old_role);
935     this->emit_activated(old_role); */
936 }
937
938 void WindowManager::deactivate(int id)
939 {
940     // TODO: application requests by old role,
941     //       so convert role new to old for emitting event
942     /* const char* old_role = this->rolenew2old[label].c_str();
943
944     this->emit_deactivated(old_role);
945     this->emit_invisible(old_role); */
946 }
947
948 WMError WindowManager::setRequest(const string& appid, const string &role, const string &area,
949                             Task task, unsigned* req_num)
950 {
951     if (!g_app_list.contains(appid))
952     {
953         return WMError::NOT_REGISTERED;
954     }
955
956     auto client = g_app_list.lookUpClient(appid);
957
958     /*
959      * Queueing Phase
960      */
961     unsigned current = g_app_list.currentRequestNumber();
962     unsigned requested_num = g_app_list.getRequestNumber(appid);
963     if (requested_num != 0)
964     {
965         HMI_SEQ_INFO(requested_num,
966             "%s %s %s request is already queued", appid.c_str(), role.c_str(), area.c_str());
967         return REQ_REJECTED;
968     }
969
970     WMRequest req = WMRequest(appid, role, area, task);
971     unsigned new_req = g_app_list.addRequest(req);
972     *req_num = new_req;
973     g_app_list.reqDump();
974
975     HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", appid.c_str(), role.c_str(), area.c_str());
976
977     return WMError::SUCCESS;
978 }
979
980 WMError WindowManager::checkPolicy(unsigned req_num)
981 {
982     /*
983     * Check Policy
984     */
985     // get current trigger
986     bool found = false;
987     WMError ret = WMError::LAYOUT_CHANGE_FAIL;
988     auto trigger = g_app_list.getRequest(req_num, &found);
989     if (!found)
990     {
991         ret = WMError::NO_ENTRY;
992         return ret;
993     }
994     string req_area = trigger.area;
995
996     if (trigger.task == Task::TASK_ALLOCATE)
997     {
998         const char *msg = this->check_surface_exist(trigger.role.c_str());
999
1000         if (msg)
1001         {
1002             HMI_SEQ_ERROR(req_num, msg);
1003             return ret;
1004         }
1005     }
1006
1007     // Input event data to PolicyManager
1008     if (0 > this->pmw.setInputEventData(trigger.task, trigger.role, trigger.area))
1009     {
1010         HMI_SEQ_ERROR(req_num, "Failed to set input event data to PolicyManager");
1011         return ret;
1012     }
1013
1014     // Execute state transition of PolicyManager
1015     if (0 > this->pmw.executeStateTransition())
1016     {
1017         HMI_SEQ_ERROR(req_num, "Failed to execute state transition of PolicyManager");
1018         return ret;
1019     }
1020
1021     ret = WMError::SUCCESS;
1022
1023     g_app_list.reqDump();
1024
1025     return ret;
1026 }
1027
1028 WMError WindowManager::startTransition(unsigned req_num)
1029 {
1030     bool sync_draw_happen = false;
1031     bool found = false;
1032     WMError ret = WMError::SUCCESS;
1033     auto actions = g_app_list.getActions(req_num, &found);
1034     if (!found)
1035     {
1036         ret = WMError::NO_ENTRY;
1037         HMI_SEQ_ERROR(req_num,
1038             "Window Manager bug :%s : Action is not set", errorDescription(ret));
1039         return ret;
1040     }
1041
1042     g_app_list.reqDump();
1043     for (const auto &action : actions)
1044     {
1045         if (action.visible == TaskVisible::VISIBLE)
1046         {
1047             sync_draw_happen = true;
1048
1049             // TODO: application requests by old role,
1050             //       so convert role new to old for emitting event
1051             string old_role = this->rolenew2old[action.role];
1052
1053             this->emit_syncdraw(old_role, action.area);
1054             /* TODO: emit event for app not subscriber
1055             if(g_app_list.contains(y.appid))
1056                 g_app_list.lookUpClient(y.appid)->emit_syncdraw(y.role, y.area); */
1057         }
1058     }
1059
1060     if (sync_draw_happen)
1061     {
1062         this->setTimer();
1063     }
1064     else
1065     {
1066         // deactivate only, no syncDraw
1067         // Make it deactivate here
1068         for (const auto &x : actions)
1069         {
1070             this->lc->visibilityChange(x);
1071             string old_role = this->rolenew2old[x.role];
1072             emit_deactivated(old_role.c_str());
1073
1074             /* if (g_app_list.contains(x.appid))
1075             {
1076                 auto client = g_app_list.lookUpClient(x.appid);
1077                 //this->deactivate(client->surfaceID(x.role));
1078             } */
1079         }
1080         this->lc->renderLayers();
1081         ret = WMError::NO_LAYOUT_CHANGE;
1082     }
1083     return ret;
1084 }
1085
1086 WMError WindowManager::doEndDraw(unsigned req_num)
1087 {
1088     // get actions
1089     bool found;
1090     auto actions = g_app_list.getActions(req_num, &found);
1091     WMError ret = WMError::SUCCESS;
1092     if (!found)
1093     {
1094         ret = WMError::NO_ENTRY;
1095         return ret;
1096     }
1097
1098     HMI_SEQ_INFO(req_num, "do endDraw");
1099
1100     // layout change and make it visible
1101     for (const auto &act : actions)
1102     {
1103         if(act.visible != TaskVisible::NO_CHANGE)
1104         {
1105             // layout change
1106             ret = this->lc->layoutChange(act);
1107             if(ret != WMError::SUCCESS)
1108             {
1109                 HMI_SEQ_WARNING(req_num,
1110                     "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1111                 return ret;
1112             }
1113             ret = this->lc->visibilityChange(act);
1114
1115             // Emit active/deactive event
1116             string old_role = this->rolenew2old[act.role];
1117             if(act.visible == VISIBLE)
1118             {
1119                 emit_activated(old_role.c_str());
1120             }
1121             else
1122             {
1123                 emit_deactivated(old_role.c_str());
1124             }
1125
1126             if (ret != WMError::SUCCESS)
1127             {
1128                 HMI_SEQ_WARNING(req_num,
1129                     "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1130                 return ret;
1131             }
1132             HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str());
1133         }
1134     }
1135     this->lc->renderLayers();
1136
1137     HMI_SEQ_INFO(req_num, "emit flushDraw");
1138
1139     for(const auto &act_flush : actions)
1140     {
1141         if(act_flush.visible == TaskVisible::VISIBLE)
1142         {
1143             // TODO: application requests by old role,
1144             //       so convert role new to old for emitting event
1145             string old_role = this->rolenew2old[act_flush.role];
1146
1147             this->emit_flushdraw(old_role.c_str());
1148         }
1149     }
1150
1151     return ret;
1152 }
1153
1154 void WindowManager::emitScreenUpdated(unsigned req_num)
1155 {
1156     // Get visible apps
1157     HMI_SEQ_DEBUG(req_num, "emit screen updated");
1158     bool found = false;
1159     auto actions = g_app_list.getActions(req_num, &found);
1160
1161     // create json object
1162     json_object *j = json_object_new_object();
1163     json_object *jarray = json_object_new_array();
1164
1165     for(const auto& action: actions)
1166     {
1167         if(action.visible != TaskVisible::INVISIBLE)
1168         {
1169             json_object_array_add(jarray, json_object_new_string(action.client->appID().c_str()));
1170         }
1171     }
1172     json_object_object_add(j, kKeyIds, jarray);
1173     HMI_SEQ_INFO(req_num, "Visible app: %s", json_object_get_string(j));
1174
1175     int ret = afb_event_push(
1176         this->map_afb_event[kListEventName[Event_ScreenUpdated]], j);
1177     if (ret != 0)
1178     {
1179         HMI_DEBUG("afb_event_push failed: %m");
1180     }
1181 }
1182
1183 void WindowManager::setTimer()
1184 {
1185     struct timespec ts;
1186     if (clock_gettime(CLOCK_BOOTTIME, &ts) != 0) {
1187         HMI_ERROR("Could't set time (clock_gettime() returns with error");
1188         return;
1189     }
1190
1191     HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Timer set activate");
1192     if (g_timer_ev_src == nullptr)
1193     {
1194         // firsttime set into sd_event
1195         int ret = sd_event_add_time(afb_daemon_get_event_loop(), &g_timer_ev_src,
1196             CLOCK_BOOTTIME, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL, 1, processTimerHandler, this);
1197         if (ret < 0)
1198         {
1199             HMI_ERROR("Could't set timer");
1200         }
1201     }
1202     else
1203     {
1204         // update timer limitation after second time
1205         sd_event_source_set_time(g_timer_ev_src, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL);
1206         sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT);
1207     }
1208 }
1209
1210 void WindowManager::stopTimer()
1211 {
1212     unsigned req_num = g_app_list.currentRequestNumber();
1213     HMI_SEQ_DEBUG(req_num, "Timer stop");
1214     int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF);
1215     if (rc < 0)
1216     {
1217         HMI_SEQ_ERROR(req_num, "Timer stop failed");
1218     }
1219 }
1220
1221 void WindowManager::processNextRequest()
1222 {
1223     g_app_list.next();
1224     g_app_list.reqDump();
1225     unsigned req_num = g_app_list.currentRequestNumber();
1226     if (g_app_list.haveRequest())
1227     {
1228         HMI_SEQ_DEBUG(req_num, "Process next request");
1229         WMError rc = checkPolicy(req_num);
1230         if (rc != WMError::SUCCESS)
1231         {
1232             HMI_SEQ_ERROR(req_num, errorDescription(rc));
1233         }
1234     }
1235     else
1236     {
1237         HMI_SEQ_DEBUG(req_num, "Nothing Request. Waiting Request");
1238     }
1239 }
1240
1241 const char* WindowManager::convertRoleOldToNew(char const *old_role)
1242 {
1243     const char *new_role = nullptr;
1244
1245     for (auto const &on : this->roleold2new)
1246     {
1247         std::regex regex = std::regex(on.first);
1248         if (std::regex_match(old_role, regex))
1249         {
1250             // role is old. So convert to new.
1251             new_role = on.second.c_str();
1252             break;
1253         }
1254     }
1255
1256     if (nullptr == new_role)
1257     {
1258         // role is new or fallback.
1259         new_role = old_role;
1260     }
1261
1262     HMI_DEBUG("old:%s -> new:%s", old_role, new_role);
1263
1264     return new_role;
1265 }
1266
1267 int WindowManager::loadOldRoleDb()
1268 {
1269     // Get afm application installed dir
1270     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1271     HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
1272
1273     string file_name;
1274     if (!afm_app_install_dir)
1275     {
1276         HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
1277     }
1278     else
1279     {
1280         file_name = string(afm_app_install_dir) + string("/etc/old_roles.db");
1281     }
1282
1283     // Load old_role.db
1284     json_object* json_obj;
1285     int ret = jh::inputJsonFilie(file_name.c_str(), &json_obj);
1286     if (0 > ret)
1287     {
1288         HMI_ERROR("Could not open old_role.db, so use default old_role information");
1289         json_obj = json_tokener_parse(kDefaultOldRoleDb);
1290     }
1291     HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
1292
1293     // Perse apps
1294     json_object* json_cfg;
1295     if (!json_object_object_get_ex(json_obj, "old_roles", &json_cfg))
1296     {
1297         HMI_ERROR("Parse Error!!");
1298         return -1;
1299     }
1300
1301     int len = json_object_array_length(json_cfg);
1302     HMI_DEBUG("json_cfg len:%d", len);
1303     HMI_DEBUG("json_cfg dump:%s", json_object_get_string(json_cfg));
1304
1305     for (int i=0; i<len; i++)
1306     {
1307         json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
1308
1309         const char* old_role = jh::getStringFromJson(json_tmp, "name");
1310         if (nullptr == old_role)
1311         {
1312             HMI_ERROR("Parse Error!!");
1313             return -1;
1314         }
1315
1316         const char* new_role = jh::getStringFromJson(json_tmp, "new");
1317         if (nullptr == new_role)
1318         {
1319             HMI_ERROR("Parse Error!!");
1320             return -1;
1321         }
1322
1323         this->roleold2new[old_role] = string(new_role);
1324     }
1325
1326     // Check
1327     for(auto itr = this->roleold2new.begin();
1328       itr != this->roleold2new.end(); ++itr)
1329     {
1330         HMI_DEBUG(">>> role old:%s new:%s",
1331                   itr->first.c_str(), itr->second.c_str());
1332     }
1333
1334     // Release json_object
1335     json_object_put(json_obj);
1336
1337     return 0;
1338 }
1339
1340 const char *WindowManager::check_surface_exist(const char *drawing_name)
1341 {
1342     auto const &surface_id = this->id_alloc.lookup(string(drawing_name));
1343     if (!surface_id)
1344     {
1345         return "Surface does not exist";
1346     }
1347
1348     /* if (!this->controller->surface_exists(*surface_id))
1349     {
1350         return "Surface does not exist in controller!";
1351     } */
1352
1353     /* auto layer_id = this->layers.get_layer_id(*surface_id);
1354
1355     if (!layer_id)
1356     {
1357         return "Surface is not on any layer!";
1358     } */
1359
1360     HMI_DEBUG("surface %d is detected", *surface_id);
1361     return nullptr;
1362 }
1363
1364 const char* WindowManager::kDefaultOldRoleDb = "{ \
1365     \"old_roles\": [ \
1366         { \
1367             \"name\": \"HomeScreen\", \
1368             \"new\": \"homescreen\" \
1369         }, \
1370         { \
1371             \"name\": \"Music\", \
1372             \"new\": \"music\" \
1373         }, \
1374         { \
1375             \"name\": \"MediaPlayer\", \
1376             \"new\": \"music\" \
1377         }, \
1378         { \
1379             \"name\": \"Video\", \
1380             \"new\": \"video\" \
1381         }, \
1382         { \
1383             \"name\": \"VideoPlayer\", \
1384             \"new\": \"video\" \
1385         }, \
1386         { \
1387             \"name\": \"WebBrowser\", \
1388             \"new\": \"browser\" \
1389         }, \
1390         { \
1391             \"name\": \"Radio\", \
1392             \"new\": \"radio\" \
1393         }, \
1394         { \
1395             \"name\": \"Phone\", \
1396             \"new\": \"phone\" \
1397         }, \
1398         { \
1399             \"name\": \"Navigation\", \
1400             \"new\": \"map\" \
1401         }, \
1402         { \
1403             \"name\": \"HVAC\", \
1404             \"new\": \"hvac\" \
1405         }, \
1406         { \
1407             \"name\": \"Settings\", \
1408             \"new\": \"settings\" \
1409         }, \
1410         { \
1411             \"name\": \"Dashboard\", \
1412             \"new\": \"dashboard\" \
1413         }, \
1414         { \
1415             \"name\": \"POI\", \
1416             \"new\": \"poi\" \
1417         }, \
1418         { \
1419             \"name\": \"Mixer\", \
1420             \"new\": \"mixer\" \
1421         }, \
1422         { \
1423             \"name\": \"Restriction\", \
1424             \"new\": \"restriction\" \
1425         }, \
1426         { \
1427             \"name\": \"^OnScreen.*\", \
1428             \"new\": \"on_screen\" \
1429         } \
1430     ] \
1431 }";
1432
1433 } // namespace wm