edd3c12a77f46f5555ab6b3c4a28b5ac486aec04
[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 const vector<string> kListEventName{
60         "active",
61         "inactive",
62         "visible",
63         "invisible",
64         "syncDraw",
65         "flushDraw",
66         "screenUpdated",
67         "error"};
68
69 static sd_event_source *g_timer_ev_src = nullptr;
70 static AppList g_app_list;
71 static WindowManager *g_context;
72
73 namespace
74 {
75
76 static int processTimerHandler(sd_event_source *s, uint64_t usec, void *userdata)
77 {
78     HMI_NOTICE("Time out occurs because the client replys endDraw slow, so revert the request");
79     reinterpret_cast<wm::WindowManager *>(userdata)->timerHandler();
80     return 0;
81 }
82
83 static void onStateTransitioned(vector<WMAction> actions)
84 {
85     g_context->startTransitionWrapper(actions);
86 }
87
88 static void onError()
89 {
90     g_context->processError(WMError::LAYOUT_CHANGE_FAIL);
91 }
92 } // namespace
93
94 /**
95  * WindowManager Impl
96  */
97 WindowManager::WindowManager()
98     : id_alloc{}
99 {
100     const char *path = getenv("AFM_APP_INSTALL_DIR");
101     if (!path)
102     {
103         HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
104     }
105     string root = path;
106
107     this->lc = std::make_shared<LayerControl>(root);
108
109     HMI_DEBUG("Layer Controller initialized");
110 }
111
112 int WindowManager::init()
113 {
114     LayerControlCallbacks lmcb;
115     lmcb.surfaceCreated = [&](unsigned pid, unsigned surface){
116         this->surface_created(surface);
117         };
118     lmcb.surfaceDestroyed = [&](unsigned surface){
119         this->surface_removed(surface);
120     };
121
122     if(this->lc->init(lmcb) != WMError::SUCCESS)
123     {
124         return -1;
125     }
126
127     // TODO: application requests by old role,
128     //       so create role map (old, new)
129     // Load old_role.db
130     this->loadOldRoleDb();
131
132     // Store my context for calling callback from PolicyManager
133     g_context = this;
134
135     // Initialize PMWrapper
136     this->pmw.initialize();
137
138     // Register callback to PolicyManager
139     this->pmw.registerCallback(onStateTransitioned, onError);
140
141     // Make afb event
142     for (int i = Event_Val_Min; i <= Event_Val_Max; i++)
143     {
144         map_afb_event[kListEventName[i]] = afb_daemon_make_event(kListEventName[i].c_str());
145     }
146
147     const struct rect css_bg = this->lc->getAreaSize("fullscreen");
148     Screen screen = this->lc->getScreenInfo();
149     rectangle dp_bg(screen.width(), screen.height());
150
151     dp_bg.set_aspect(static_cast<double>(css_bg.w) / css_bg.h);
152     dp_bg.fit(screen.width(), screen.height());
153     dp_bg.center(screen.width(), screen.height());
154     HMI_DEBUG("SCALING: CSS BG(%dx%d) -> DDP %dx%d,(%dx%d)",
155               css_bg.w, css_bg.h, dp_bg.left(), dp_bg.top(), dp_bg.width(), dp_bg.height());
156
157     double scale = static_cast<double>(dp_bg.height()) / css_bg.h;
158     this->lc->setupArea(dp_bg, scale);
159
160     return 0;
161 }
162
163 result<int> WindowManager::api_request_surface(char const *appid, char const *drawing_name)
164 {
165     // TODO: application requests by old role,
166     //       so convert role old to new
167     const char *role = this->convertRoleOldToNew(drawing_name);
168     string str_id = appid;
169     string str_role = role;
170     unsigned lid = 0;
171
172     if(!g_app_list.contains(str_id))
173     {
174         lid = this->lc->getNewLayerID(str_role);
175         if (lid == 0)
176         {
177             // register drawing_name as fallback and make it displayed.
178             lid = this->lc->getNewLayerID(string("fallback"));
179             HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
180             if (lid == 0)
181             {
182                 return Err<int>("Designated role does not match any role, fallback is disabled");
183             }
184         }
185         this->lc->createNewLayer(lid);
186         // add client into the db
187         g_app_list.addClient(str_id, lid, str_role);
188     }
189
190     // generate surface ID for ivi-shell application
191     auto rname = this->id_alloc.lookup(str_role);
192     if (!rname)
193     {
194         // name does not exist yet, allocate surface id...
195         auto id = int(this->id_alloc.generate_id(str_role));
196         this->tmp_surface2app[id] = {str_id, lid};
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     // TODO: application requests by old role,
212     //       so convert role old to new
213     const char *role = this->convertRoleOldToNew(drawing_name);
214     string str_id   = appid;
215     string str_role = role;
216
217     unsigned sid = std::stol(ivi_id);
218     HMI_DEBUG("This API(requestSurfaceXDG) is for XDG Application using runXDG");
219     /*
220      * IVI-shell doesn't send surface_size event via ivi-wm protocol
221      * if the application is using XDG surface.
222      * So WM has to set surface size with original size here
223      */
224     WMError ret = this->lc->setXDGSurfaceOriginSize(sid);
225     if(ret != SUCCESS)
226     {
227         HMI_ERROR("%s", errorDescription(ret));
228         HMI_WARNING("The main user of this API is runXDG");
229         return "fail";
230     }
231
232     if(!g_app_list.contains(str_id))
233     {
234         unsigned l_id = this->lc->getNewLayerID(str_role);
235         if (l_id == 0)
236         {
237             // register drawing_name as fallback and make it displayed.
238             l_id = this->lc->getNewLayerID("fallback");
239             HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
240             if (l_id == 0)
241             {
242                 return "Designated role does not match any role, fallback is disabled";
243             }
244         }
245         this->lc->createNewLayer(l_id);
246         // add client into the db
247         g_app_list.addClient(str_id, l_id, str_role);
248     }
249
250     auto rname = this->id_alloc.lookup(str_role);
251
252     if (rname)
253     {
254         return "Surface already present";
255     }
256
257     // register pair drawing_name and ivi_id
258     this->id_alloc.register_name_id(str_role, sid);
259
260     auto client = g_app_list.lookUpClient(str_id);
261     client->addSurface(sid);
262
263     // Set role map of (new, old)
264     this->rolenew2old[role] = string(drawing_name);
265
266     return nullptr;
267 }
268
269 void WindowManager::api_activate_window(char const *appid, char const *drawing_name,
270                                char const *drawing_area, const reply_func &reply)
271 {
272     // TODO: application requests by old role,
273     //       so convert role old to new
274     const char *c_role = this->convertRoleOldToNew(drawing_name);
275
276     string id = appid;
277     string role = c_role;
278     string area = drawing_area;
279
280     if(!g_app_list.contains(id))
281     {
282         reply("app doesn't request 'requestSurface' or 'setRole' yet");
283         return;
284     }
285     auto client = g_app_list.lookUpClient(id);
286
287     Task task = Task::TASK_ALLOCATE;
288     unsigned req_num = 0;
289     WMError ret = WMError::UNKNOWN;
290
291     ret = this->setRequest(id, role, area, task, &req_num);
292
293     if(ret != WMError::SUCCESS)
294     {
295         HMI_ERROR(errorDescription(ret));
296         reply("Failed to set request");
297         return;
298     }
299
300     reply(nullptr);
301     if (req_num != g_app_list.currentRequestNumber())
302     {
303         // Add request, then invoked after the previous task is finished
304         HMI_SEQ_DEBUG(req_num, "request is accepted");
305         return;
306     }
307
308     /*
309      * Do allocate tasks
310      */
311     ret = this->checkPolicy(req_num);
312
313     if (ret != WMError::SUCCESS)
314     {
315         //this->emit_error()
316         HMI_SEQ_ERROR(req_num, errorDescription(ret));
317         g_app_list.removeRequest(req_num);
318         this->processNextRequest();
319     }
320 }
321
322 void WindowManager::api_deactivate_window(char const *appid, char const *drawing_name,
323                                  const reply_func &reply)
324 {
325     // TODO: application requests by old role,
326     //       so convert role old to new
327     const char *c_role = this->convertRoleOldToNew(drawing_name);
328
329     /*
330     * Check Phase
331     */
332     string id = appid;
333     string role = c_role;
334     string area = ""; //drawing_area;
335     Task task = Task::TASK_RELEASE;
336     unsigned req_num = 0;
337     WMError ret = WMError::UNKNOWN;
338
339     ret = this->setRequest(id, role, area, task, &req_num);
340
341     if (ret != WMError::SUCCESS)
342     {
343         HMI_ERROR(errorDescription(ret));
344         reply("Failed to set request");
345         return;
346     }
347
348     reply(nullptr);
349     if (req_num != g_app_list.currentRequestNumber())
350     {
351         // Add request, then invoked after the previous task is finished
352         HMI_SEQ_DEBUG(req_num, "request is accepted");
353         return;
354     }
355
356     /*
357     * Do allocate tasks
358     */
359     ret = this->checkPolicy(req_num);
360
361     if (ret != WMError::SUCCESS)
362     {
363         //this->emit_error()
364         HMI_SEQ_ERROR(req_num, errorDescription(ret));
365         g_app_list.removeRequest(req_num);
366         this->processNextRequest();
367     }
368 }
369
370 void WindowManager::api_enddraw(char const *appid, char const *drawing_name)
371 {
372     // TODO: application requests by old role,
373     //       so convert role old to new
374     const char *c_role = this->convertRoleOldToNew(drawing_name);
375
376     string id = appid;
377     string role = c_role;
378     unsigned current_req = g_app_list.currentRequestNumber();
379     bool result = g_app_list.setEndDrawFinished(current_req, id, role);
380
381     if (!result)
382     {
383         HMI_ERROR("%s is not in transition state", id.c_str());
384         return;
385     }
386
387     if (g_app_list.endDrawFullfilled(current_req))
388     {
389         // do task for endDraw
390         this->stopTimer();
391         WMError ret = this->doEndDraw(current_req);
392
393         if(ret != WMError::SUCCESS)
394         {
395             //this->emit_error();
396
397             // Undo state of PolicyManager
398             this->pmw.undoState();
399             this->lc->undoUpdate();
400         }
401         this->emitScreenUpdated(current_req);
402         HMI_SEQ_INFO(current_req, "Finish request status: %s", errorDescription(ret));
403
404         g_app_list.removeRequest(current_req);
405
406         this->processNextRequest();
407     }
408     else
409     {
410         HMI_SEQ_INFO(current_req, "Wait other App call endDraw");
411         return;
412     }
413 }
414
415 int WindowManager::api_subscribe(afb_req req, int event_id)
416 {
417     struct afb_event event = this->map_afb_event[kListEventName[event_id]];
418     return afb_req_subscribe(req, event);
419 }
420
421 result<json_object *> WindowManager::api_get_display_info()
422 {
423     Screen screen = this->lc->getScreenInfo();
424
425     json_object *object = json_object_new_object();
426     json_object_object_add(object, kKeyWidthPixel, json_object_new_int(screen.width()));
427     json_object_object_add(object, kKeyHeightPixel, json_object_new_int(screen.height()));
428     // TODO: set size
429     json_object_object_add(object, kKeyWidthMm, json_object_new_int(0));
430     json_object_object_add(object, kKeyHeightMm, json_object_new_int(0));
431     json_object_object_add(object, kKeyScale, json_object_new_double(this->lc->scale()));
432
433     return Ok<json_object *>(object);
434 }
435
436 result<json_object *> WindowManager::api_get_area_info(char const *drawing_name)
437 {
438     HMI_DEBUG("called");
439
440     // TODO: application requests by old role,
441     //       so convert role old to new
442     const char *role = this->convertRoleOldToNew(drawing_name);
443
444     // Check drawing name, surface/layer id
445     auto const &surface_id = this->id_alloc.lookup(role);
446     if (!surface_id)
447     {
448         return Err<json_object *>("Surface does not exist");
449     }
450
451     // Set area rectangle
452     struct rect area_info = this->area_info[*surface_id];
453     json_object *object = json_object_new_object();
454     json_object_object_add(object, kKeyX, json_object_new_int(area_info.x));
455     json_object_object_add(object, kKeyY, json_object_new_int(area_info.y));
456     json_object_object_add(object, kKeyWidth, json_object_new_int(area_info.w));
457     json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
458
459     return Ok<json_object *>(object);
460 }
461
462 void WindowManager::send_event(const string& evname, const string& role)
463 {
464     json_object *j = json_object_new_object();
465     json_object_object_add(j, kKeyDrawingName, json_object_new_string(role.c_str()));
466
467     int ret = afb_event_push(this->map_afb_event[evname], j);
468     if (ret != 0)
469     {
470         HMI_DEBUG("afb_event_push failed: %m");
471     }
472 }
473
474 void WindowManager::send_event(const string& evname, const string& role, const string& area,
475                      int x, int y, int w, int h)
476 {
477     json_object *j_rect = json_object_new_object();
478     json_object_object_add(j_rect, kKeyX, json_object_new_int(x));
479     json_object_object_add(j_rect, kKeyY, json_object_new_int(y));
480     json_object_object_add(j_rect, kKeyWidth, json_object_new_int(w));
481     json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
482
483     json_object *j = json_object_new_object();
484     json_object_object_add(j, kKeyDrawingName, json_object_new_string(role.c_str()));
485     json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area.c_str()));
486     json_object_object_add(j, kKeyDrawingRect, j_rect);
487
488     int ret = afb_event_push(this->map_afb_event[evname], j);
489     if (ret != 0)
490     {
491         HMI_DEBUG("afb_event_push failed: %m");
492     }
493 }
494
495 /**
496  * proxied events
497  */
498 void WindowManager::surface_created(unsigned surface_id)
499 {
500     // requestSurface
501     if(this->tmp_surface2app.count(surface_id) != 0)
502     {
503         string appid = this->tmp_surface2app[surface_id].appid;
504         auto client = g_app_list.lookUpClient(appid);
505         if(client != nullptr)
506         {
507             WMError ret = client->addSurface(surface_id);
508             HMI_INFO("Add surface %d to \"%s\"", surface_id, appid.c_str());
509             if(ret != WMError::SUCCESS)
510             {
511                 HMI_ERROR("Failed to add surface to client %s", client->appID().c_str());
512             }
513         }
514         this->tmp_surface2app.erase(surface_id);
515     }
516 }
517
518 void WindowManager::surface_removed(unsigned surface_id)
519 {
520     HMI_DEBUG("Delete surface_id %u", surface_id);
521     this->id_alloc.remove_id(surface_id);
522     g_app_list.removeSurface(surface_id);
523 }
524
525 void WindowManager::removeClient(const string &appid)
526 {
527     HMI_DEBUG("Remove clinet %s from list", appid.c_str());
528     auto client = g_app_list.lookUpClient(appid);
529     this->lc->appTerminated(client);
530     g_app_list.removeClient(appid);
531 }
532
533 void WindowManager::exceptionProcessForTransition()
534 {
535     unsigned req_num = g_app_list.currentRequestNumber();
536     HMI_SEQ_NOTICE(req_num, "Process exception handling for request. Remove current request %d", req_num);
537     g_app_list.removeRequest(req_num);
538     HMI_SEQ_NOTICE(g_app_list.currentRequestNumber(), "Process next request if exists");
539     this->processNextRequest();
540 }
541
542 void WindowManager::timerHandler()
543 {
544     unsigned req_num = g_app_list.currentRequestNumber();
545     HMI_SEQ_DEBUG(req_num, "Timer expired remove Request");
546     g_app_list.reqDump();
547     g_app_list.removeRequest(req_num);
548     this->processNextRequest();
549 }
550
551 void WindowManager::startTransitionWrapper(vector<WMAction> &actions)
552 {
553     WMError ret;
554     unsigned req_num = g_app_list.currentRequestNumber();
555
556     if (actions.empty())
557     {
558         if (g_app_list.haveRequest())
559         {
560             HMI_SEQ_DEBUG(req_num, "There is no WMAction for this request");
561             goto proc_remove_request;
562         }
563         else
564         {
565             HMI_SEQ_DEBUG(req_num, "There is no request");
566             return;
567         }
568     }
569
570     for (auto &act : actions)
571     {
572         if ("" != act.role)
573         {
574             bool found;
575             auto const &surface_id = this->id_alloc.lookup(act.role.c_str());
576             if(surface_id == nullopt)
577             {
578                 goto proc_remove_request;
579             }
580             string appid = g_app_list.getAppID(*surface_id, &found);
581             if (!found)
582             {
583                 if (TaskVisible::INVISIBLE == act.visible)
584                 {
585                     // App is killed, so do not set this action
586                     continue;
587                 }
588                 else
589                 {
590                     HMI_SEQ_ERROR(req_num, "appid which is visible is not found");
591                     ret = WMError::FAIL;
592                     goto error;
593                 }
594             }
595             auto client = g_app_list.lookUpClient(appid);
596             act.req_num = req_num;
597             act.client = client;
598         }
599
600         ret = g_app_list.setAction(req_num, act);
601         if (ret != WMError::SUCCESS)
602         {
603             HMI_SEQ_ERROR(req_num, "Setting action is failed");
604             goto error;
605         }
606     }
607
608     HMI_SEQ_DEBUG(req_num, "Start transition.");
609     ret = this->startTransition(req_num);
610     if (ret != WMError::SUCCESS)
611     {
612         if (ret == WMError::NO_LAYOUT_CHANGE)
613         {
614             goto proc_remove_request;
615         }
616         else
617         {
618             HMI_SEQ_ERROR(req_num, "Transition state is failed");
619             goto error;
620         }
621     }
622
623     return;
624
625 error:
626     //this->emit_error()
627     HMI_SEQ_ERROR(req_num, errorDescription(ret));
628     this->pmw.undoState();
629
630 proc_remove_request:
631     g_app_list.removeRequest(req_num);
632     this->processNextRequest();
633 }
634
635 void WindowManager::processError(WMError error)
636 {
637     unsigned req_num = g_app_list.currentRequestNumber();
638
639     //this->emit_error()
640     HMI_SEQ_ERROR(req_num, errorDescription(error));
641     g_app_list.removeRequest(req_num);
642     this->processNextRequest();
643 }
644
645 /*
646  ******* Private Functions *******
647  */
648
649 void WindowManager::emit_activated(const string& role)
650 {
651     this->send_event(kListEventName[Event_Active], role);
652 }
653
654 void WindowManager::emit_deactivated(const string& role)
655 {
656     this->send_event(kListEventName[Event_Inactive], role);
657 }
658
659 void WindowManager::emit_syncdraw(const string& role, char const *area, int x, int y, int w, int h)
660 {
661     this->send_event(kListEventName[Event_SyncDraw], role, area, x, y, w, h);
662 }
663
664 void WindowManager::emit_syncdraw(const string &role, const string &area)
665 {
666     struct rect rect = this->lc->getAreaSize(area);
667     this->send_event(kListEventName[Event_SyncDraw],
668         role.c_str(), area.c_str(), rect.x, rect.y, rect.w, rect.h);
669 }
670
671 void WindowManager::emit_flushdraw(const string& role)
672 {
673     this->send_event(kListEventName[Event_FlushDraw], role);
674 }
675
676 void WindowManager::emit_visible(const string& role, bool is_visible)
677 {
678     this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], role);
679 }
680
681 void WindowManager::emit_invisible(const string& role)
682 {
683     return emit_visible(role, false);
684 }
685
686 void WindowManager::emit_visible(const string& role) { return emit_visible(role, true); }
687
688 WMError WindowManager::setRequest(const string& appid, const string &role, const string &area,
689                             Task task, unsigned* req_num)
690 {
691     if (!g_app_list.contains(appid))
692     {
693         return WMError::NOT_REGISTERED;
694     }
695
696     auto client = g_app_list.lookUpClient(appid);
697
698     /*
699      * Queueing Phase
700      */
701     unsigned current = g_app_list.currentRequestNumber();
702     unsigned requested_num = g_app_list.getRequestNumber(appid);
703     if (requested_num != 0)
704     {
705         HMI_SEQ_INFO(requested_num,
706             "%s %s %s request is already queued", appid.c_str(), role.c_str(), area.c_str());
707         return REQ_REJECTED;
708     }
709
710     WMRequest req = WMRequest(appid, role, area, task);
711     unsigned new_req = g_app_list.addRequest(req);
712     *req_num = new_req;
713     g_app_list.reqDump();
714
715     HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", appid.c_str(), role.c_str(), area.c_str());
716
717     return WMError::SUCCESS;
718 }
719
720 WMError WindowManager::checkPolicy(unsigned req_num)
721 {
722     /*
723     * Check Policy
724     */
725     // get current trigger
726     bool found = false;
727     WMError ret = WMError::LAYOUT_CHANGE_FAIL;
728     auto trigger = g_app_list.getRequest(req_num, &found);
729     if (!found)
730     {
731         ret = WMError::NO_ENTRY;
732         return ret;
733     }
734     string req_area = trigger.area;
735
736     // Input event data to PolicyManager
737     if (0 > this->pmw.setInputEventData(trigger.task, trigger.role, trigger.area))
738     {
739         HMI_SEQ_ERROR(req_num, "Failed to set input event data to PolicyManager");
740         return ret;
741     }
742
743     // Execute state transition of PolicyManager
744     if (0 > this->pmw.executeStateTransition())
745     {
746         HMI_SEQ_ERROR(req_num, "Failed to execute state transition of PolicyManager");
747         return ret;
748     }
749
750     ret = WMError::SUCCESS;
751
752     g_app_list.reqDump();
753
754     return ret;
755 }
756
757 WMError WindowManager::startTransition(unsigned req_num)
758 {
759     bool sync_draw_happen = false;
760     bool found = false;
761     WMError ret = WMError::SUCCESS;
762     auto actions = g_app_list.getActions(req_num, &found);
763     if (!found)
764     {
765         ret = WMError::NO_ENTRY;
766         HMI_SEQ_ERROR(req_num,
767             "Window Manager bug :%s : Action is not set", errorDescription(ret));
768         return ret;
769     }
770
771     g_app_list.reqDump();
772     for (const auto &action : actions)
773     {
774         if (action.visible == TaskVisible::VISIBLE)
775         {
776             sync_draw_happen = true;
777
778             // TODO: application requests by old role,
779             //       so convert role new to old for emitting event
780             string old_role = this->rolenew2old[action.role];
781
782             this->emit_syncdraw(old_role, action.area);
783             /* TODO: emit event for app not subscriber
784             if(g_app_list.contains(y.appid))
785                 g_app_list.lookUpClient(y.appid)->emit_syncdraw(y.role, y.area); */
786         }
787     }
788
789     if (sync_draw_happen)
790     {
791         this->setTimer();
792     }
793     else
794     {
795         // deactivate only, no syncDraw
796         // Make it deactivate here
797         for (const auto &x : actions)
798         {
799             this->lc->visibilityChange(x);
800             string old_role = this->rolenew2old[x.role];
801             emit_deactivated(old_role.c_str());
802             /* if (g_app_list.contains(x.client->appID()))
803             {
804                 auto client = g_app_list.lookUpClient(x.client->appID());
805                 this->deactivate(client->surfaceID(x.role));
806             } */
807         }
808         this->lc->renderLayers();
809         ret = WMError::NO_LAYOUT_CHANGE;
810     }
811     return ret;
812 }
813
814 WMError WindowManager::doEndDraw(unsigned req_num)
815 {
816     // get actions
817     bool found;
818     auto actions = g_app_list.getActions(req_num, &found);
819     WMError ret = WMError::SUCCESS;
820     if (!found)
821     {
822         ret = WMError::NO_ENTRY;
823         return ret;
824     }
825
826     HMI_SEQ_INFO(req_num, "do endDraw");
827
828     // layout change and make it visible
829     for (const auto &act : actions)
830     {
831         if(act.visible != TaskVisible::NO_CHANGE)
832         {
833             // layout change
834             ret = this->lc->layoutChange(act);
835             if(ret != WMError::SUCCESS)
836             {
837                 HMI_SEQ_WARNING(req_num,
838                     "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
839                 return ret;
840             }
841             ret = this->lc->visibilityChange(act);
842
843             // Emit active/deactive event
844             string old_role = this->rolenew2old[act.role];
845             if(act.visible == VISIBLE)
846             {
847                 emit_visible(old_role.c_str());
848                 emit_activated(old_role.c_str());
849             }
850             else
851             {
852                 emit_invisible(old_role.c_str());
853                 emit_deactivated(old_role.c_str());
854             }
855
856             if (ret != WMError::SUCCESS)
857             {
858                 HMI_SEQ_WARNING(req_num,
859                     "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
860                 return ret;
861             }
862             HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str());
863         }
864     }
865     this->lc->renderLayers();
866
867     HMI_SEQ_INFO(req_num, "emit flushDraw");
868
869     for(const auto &act_flush : actions)
870     {
871         if(act_flush.visible == TaskVisible::VISIBLE)
872         {
873             // TODO: application requests by old role,
874             //       so convert role new to old for emitting event
875             string old_role = this->rolenew2old[act_flush.role];
876
877             this->emit_flushdraw(old_role.c_str());
878         }
879     }
880
881     return ret;
882 }
883
884 void WindowManager::emitScreenUpdated(unsigned req_num)
885 {
886     // Get visible apps
887     HMI_SEQ_DEBUG(req_num, "emit screen updated");
888     bool found = false;
889     auto actions = g_app_list.getActions(req_num, &found);
890
891     // create json object
892     json_object *j = json_object_new_object();
893     json_object *jarray = json_object_new_array();
894
895     for(const auto& action: actions)
896     {
897         if(action.visible != TaskVisible::INVISIBLE)
898         {
899             json_object_array_add(jarray, json_object_new_string(action.client->appID().c_str()));
900         }
901     }
902     json_object_object_add(j, kKeyIds, jarray);
903     HMI_SEQ_INFO(req_num, "Visible app: %s", json_object_get_string(j));
904
905     int ret = afb_event_push(
906         this->map_afb_event[kListEventName[Event_ScreenUpdated]], j);
907     if (ret != 0)
908     {
909         HMI_DEBUG("afb_event_push failed: %m");
910     }
911 }
912
913 void WindowManager::setTimer()
914 {
915     struct timespec ts;
916     if (clock_gettime(CLOCK_BOOTTIME, &ts) != 0) {
917         HMI_ERROR("Could't set time (clock_gettime() returns with error");
918         return;
919     }
920
921     HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Timer set activate");
922     if (g_timer_ev_src == nullptr)
923     {
924         // firsttime set into sd_event
925         int ret = sd_event_add_time(afb_daemon_get_event_loop(), &g_timer_ev_src,
926             CLOCK_BOOTTIME, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL, 1, processTimerHandler, this);
927         if (ret < 0)
928         {
929             HMI_ERROR("Could't set timer");
930         }
931     }
932     else
933     {
934         // update timer limitation after second time
935         sd_event_source_set_time(g_timer_ev_src, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL);
936         sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT);
937     }
938 }
939
940 void WindowManager::stopTimer()
941 {
942     unsigned req_num = g_app_list.currentRequestNumber();
943     HMI_SEQ_DEBUG(req_num, "Timer stop");
944     int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF);
945     if (rc < 0)
946     {
947         HMI_SEQ_ERROR(req_num, "Timer stop failed");
948     }
949 }
950
951 void WindowManager::processNextRequest()
952 {
953     g_app_list.next();
954     g_app_list.reqDump();
955     unsigned req_num = g_app_list.currentRequestNumber();
956     if (g_app_list.haveRequest())
957     {
958         HMI_SEQ_DEBUG(req_num, "Process next request");
959         WMError rc = checkPolicy(req_num);
960         if (rc != WMError::SUCCESS)
961         {
962             HMI_SEQ_ERROR(req_num, errorDescription(rc));
963         }
964     }
965     else
966     {
967         HMI_SEQ_DEBUG(req_num, "Nothing Request. Waiting Request");
968     }
969 }
970
971 const char* WindowManager::convertRoleOldToNew(char const *old_role)
972 {
973     const char *new_role = nullptr;
974
975     for (auto const &on : this->roleold2new)
976     {
977         std::regex regex = std::regex(on.first);
978         if (std::regex_match(old_role, regex))
979         {
980             // role is old. So convert to new.
981             new_role = on.second.c_str();
982             break;
983         }
984     }
985
986     if (nullptr == new_role)
987     {
988         // role is new or fallback.
989         new_role = old_role;
990     }
991
992     HMI_DEBUG("old:%s -> new:%s", old_role, new_role);
993
994     return new_role;
995 }
996
997 int WindowManager::loadOldRoleDb()
998 {
999     // Get afm application installed dir
1000     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1001     HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
1002
1003     string file_name;
1004     if (!afm_app_install_dir)
1005     {
1006         HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
1007     }
1008     else
1009     {
1010         file_name = string(afm_app_install_dir) + string("/etc/old_roles.db");
1011     }
1012
1013     // Load old_role.db
1014     json_object* json_obj;
1015     int ret = jh::inputJsonFilie(file_name.c_str(), &json_obj);
1016     if (0 > ret)
1017     {
1018         HMI_ERROR("Could not open old_role.db, so use default old_role information");
1019         json_obj = json_tokener_parse(kDefaultOldRoleDb);
1020     }
1021     HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
1022
1023     // Perse apps
1024     json_object* json_cfg;
1025     if (!json_object_object_get_ex(json_obj, "old_roles", &json_cfg))
1026     {
1027         HMI_ERROR("Parse Error!!");
1028         return -1;
1029     }
1030
1031     int len = json_object_array_length(json_cfg);
1032     HMI_DEBUG("json_cfg len:%d", len);
1033     HMI_DEBUG("json_cfg dump:%s", json_object_get_string(json_cfg));
1034
1035     for (int i=0; i<len; i++)
1036     {
1037         json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
1038
1039         const char* old_role = jh::getStringFromJson(json_tmp, "name");
1040         if (nullptr == old_role)
1041         {
1042             HMI_ERROR("Parse Error!!");
1043             return -1;
1044         }
1045
1046         const char* new_role = jh::getStringFromJson(json_tmp, "new");
1047         if (nullptr == new_role)
1048         {
1049             HMI_ERROR("Parse Error!!");
1050             return -1;
1051         }
1052
1053         this->roleold2new[old_role] = string(new_role);
1054     }
1055
1056     // Check
1057     for(auto itr = this->roleold2new.begin();
1058       itr != this->roleold2new.end(); ++itr)
1059     {
1060         HMI_DEBUG(">>> role old:%s new:%s",
1061                   itr->first.c_str(), itr->second.c_str());
1062     }
1063
1064     // Release json_object
1065     json_object_put(json_obj);
1066
1067     return 0;
1068 }
1069
1070 const char* WindowManager::kDefaultOldRoleDb = "{ \
1071     \"old_roles\": [ \
1072         { \
1073             \"name\": \"HomeScreen\", \
1074             \"new\": \"homescreen\" \
1075         }, \
1076         { \
1077             \"name\": \"Music\", \
1078             \"new\": \"music\" \
1079         }, \
1080         { \
1081             \"name\": \"MediaPlayer\", \
1082             \"new\": \"music\" \
1083         }, \
1084         { \
1085             \"name\": \"Video\", \
1086             \"new\": \"video\" \
1087         }, \
1088         { \
1089             \"name\": \"VideoPlayer\", \
1090             \"new\": \"video\" \
1091         }, \
1092         { \
1093             \"name\": \"WebBrowser\", \
1094             \"new\": \"browser\" \
1095         }, \
1096         { \
1097             \"name\": \"Radio\", \
1098             \"new\": \"radio\" \
1099         }, \
1100         { \
1101             \"name\": \"Phone\", \
1102             \"new\": \"phone\" \
1103         }, \
1104         { \
1105             \"name\": \"Navigation\", \
1106             \"new\": \"map\" \
1107         }, \
1108         { \
1109             \"name\": \"HVAC\", \
1110             \"new\": \"hvac\" \
1111         }, \
1112         { \
1113             \"name\": \"Settings\", \
1114             \"new\": \"settings\" \
1115         }, \
1116         { \
1117             \"name\": \"Dashboard\", \
1118             \"new\": \"dashboard\" \
1119         }, \
1120         { \
1121             \"name\": \"POI\", \
1122             \"new\": \"poi\" \
1123         }, \
1124         { \
1125             \"name\": \"Mixer\", \
1126             \"new\": \"mixer\" \
1127         }, \
1128         { \
1129             \"name\": \"Restriction\", \
1130             \"new\": \"restriction\" \
1131         }, \
1132         { \
1133             \"name\": \"^OnScreen.*\", \
1134             \"new\": \"on_screen\" \
1135         } \
1136     ] \
1137 }";
1138
1139 } // namespace wm