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