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