60470b4dc4c1516dabfc11c00e5ce08705416708
[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 result<json_object *> WindowManager::api_get_display_info()
518 {
519     Screen screen = this->lc->getScreenInfo();
520
521     json_object *object = json_object_new_object();
522     json_object_object_add(object, kKeyWidthPixel, json_object_new_int(screen.width()));
523     json_object_object_add(object, kKeyHeightPixel, json_object_new_int(screen.height()));
524     // TODO: set size
525     json_object_object_add(object, kKeyWidthMm, json_object_new_int(0));
526     json_object_object_add(object, kKeyHeightMm, json_object_new_int(0));
527     json_object_object_add(object, kKeyScale, json_object_new_double(this->lc->scale()));
528
529     return Ok<json_object *>(object);
530 }
531
532 result<json_object *> WindowManager::api_get_area_info(char const *drawing_name)
533 {
534     HMI_DEBUG("called");
535
536     // TODO: application requests by old role,
537     //       so convert role old to new
538     const char *role = this->convertRoleOldToNew(drawing_name);
539
540     // Check drawing name, surface/layer id
541     auto const &surface_id = this->id_alloc.lookup(string(role));
542     if (!surface_id)
543     {
544         return Err<json_object *>("Surface does not exist");
545     }
546
547     // Set area rectangle
548     rect area_info = this->area_info[*surface_id];
549     json_object *object = json_object_new_object();
550     json_object_object_add(object, kKeyX, json_object_new_int(area_info.x));
551     json_object_object_add(object, kKeyY, json_object_new_int(area_info.y));
552     json_object_object_add(object, kKeyWidth, json_object_new_int(area_info.w));
553     json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
554
555     return Ok<json_object *>(object);
556 }
557
558 void WindowManager::send_event(char const *evname, char const *label)
559 {
560     HMI_DEBUG("%s: %s(%s)", __func__, evname, label);
561
562     json_object *j = json_object_new_object();
563     json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
564
565     int ret = afb_event_push(this->map_afb_event[evname], j);
566     if (ret != 0)
567     {
568         HMI_DEBUG("afb_event_push failed: %m");
569     }
570 }
571
572 void WindowManager::send_event(char const *evname, char const *label, char const *area,
573                      int x, int y, int w, int h)
574 {
575     HMI_DEBUG("%s: %s(%s, %s) x:%d y:%d w:%d h:%d",
576               __func__, evname, label, area, x, y, w, h);
577
578     json_object *j_rect = json_object_new_object();
579     json_object_object_add(j_rect, kKeyX, json_object_new_int(x));
580     json_object_object_add(j_rect, kKeyY, json_object_new_int(y));
581     json_object_object_add(j_rect, kKeyWidth, json_object_new_int(w));
582     json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
583
584     json_object *j = json_object_new_object();
585     json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
586     json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area));
587     json_object_object_add(j, kKeyDrawingRect, j_rect);
588
589     int ret = afb_event_push(this->map_afb_event[evname], j);
590     if (ret != 0)
591     {
592         HMI_DEBUG("afb_event_push failed: %m");
593     }
594 }
595
596 /**
597  * proxied events
598  */
599 void WindowManager::surface_created(unsigned pid, unsigned surface_id)
600 {
601     if(this->tmp_surface2app.count(surface_id) != 0)
602     {
603         string appid = this->tmp_surface2app[surface_id].appid;
604         auto client = g_app_list.lookUpClient(appid);
605         if(client != nullptr)
606         {
607             WMError ret = client->addSurface(surface_id);
608             HMI_INFO("Add surface %d to \"%s\"", surface_id, appid.c_str());
609             if(ret != WMError::SUCCESS)
610             {
611                 HMI_ERROR("Failed to add surface to client %s", client->appID().c_str());
612             }
613         }
614         this->tmp_surface2app.erase(surface_id);
615     }
616     else
617     {
618         HMI_NOTICE("Unknown surface %d", surface_id);
619         // retrieve ppid
620         std::ostringstream os;
621         os << pid ;
622         string path = "/proc/" + os.str() + "/stat";
623         std::ifstream ifs(path.c_str());
624         string str;
625         unsigned ppid = 0;
626         if(!ifs.fail() && std::getline(ifs, str))
627         {
628             std::sscanf(str.data(), "%*d %*s %*c %d", &ppid);
629             HMI_INFO("Retrieve ppid %d", ppid);
630         }
631         else
632         {
633             HMI_ERROR("Failed to open /proc/%d/stat", pid);
634             HMI_ERROR("File system may be different");
635             return;
636         }
637         // search pid from surfaceID
638         json_object *response;
639         afb_service_call_sync("afm-main", "runners", nullptr, &response);
640
641         // retrieve appid from pid from application manager
642         string appid = "";
643         if(response == nullptr)
644         {
645             HMI_ERROR("No runners");
646         }
647         else
648         {
649             // check appid then add it to the client
650             HMI_INFO("Runners:%s", json_object_get_string(response));
651             int size = json_object_array_length(response);
652             for(int i = 0; i < size; i++)
653             {
654                 json_object *j = json_object_array_get_idx(response, i);
655                 const char* id = jh::getStringFromJson(j, "id");
656                 int runid      = jh::getIntFromJson(j, "runid");
657                 if(id && (runid > 0))
658                 {
659                     if(runid == ppid)
660                     {
661                         appid = id;
662                         break;
663                     }
664                 }
665             }
666             if(appid == "")
667             {
668                 HMI_ERROR("Not found");
669             }
670         }
671         json_object_put(response);
672         auto client = g_app_list.lookUpClient(appid);
673         if(client != nullptr)
674         {
675             client->addSurface(surface_id);
676             this->id_alloc.register_name_id(client->role(), surface_id);
677         }
678         else
679         {
680             /*
681              * Store tmp surface and appid for application
682              * who requests setRole after creating shell surface
683              */
684             this->tmp_surface2app.emplace(surface_id, TmpClient{appid, ppid});
685         }
686     }
687 }
688
689 void WindowManager::surface_removed(unsigned surface_id)
690 {
691     HMI_DEBUG("Delete surface_id %u", surface_id);
692     this->id_alloc.remove_id(surface_id);
693     // this->layers.remove_surface(surface_id);
694     g_app_list.removeSurface(surface_id);
695 }
696
697 void WindowManager::removeClient(const string &appid)
698 {
699     HMI_DEBUG("Remove clinet %s from list", appid.c_str());
700     auto client = g_app_list.lookUpClient(appid);
701     this->lc->terminateApp(client);
702     g_app_list.removeClient(appid);
703 }
704
705 void WindowManager::exceptionProcessForTransition()
706 {
707     unsigned req_num = g_app_list.currentRequestNumber();
708     HMI_SEQ_NOTICE(req_num, "Process exception handling for request. Remove current request %d", req_num);
709     g_app_list.removeRequest(req_num);
710     HMI_SEQ_NOTICE(g_app_list.currentRequestNumber(), "Process next request if exists");
711     this->processNextRequest();
712 }
713
714 void WindowManager::timerHandler()
715 {
716     unsigned req_num = g_app_list.currentRequestNumber();
717     HMI_SEQ_DEBUG(req_num, "Timer expired remove Request");
718     g_app_list.reqDump();
719     g_app_list.removeRequest(req_num);
720     this->processNextRequest();
721 }
722
723 void WindowManager::startTransitionWrapper(vector<WMAction> &actions)
724 {
725     WMError ret;
726     // req_num is guaranteed by Window Manager
727     unsigned req_num = g_app_list.currentRequestNumber();
728
729     if (actions.empty())
730     {
731         if (g_app_list.haveRequest())
732         {
733             HMI_SEQ_DEBUG(req_num, "There is no WMAction for this request");
734             goto proc_remove_request;
735         }
736         else
737         {
738             HMI_SEQ_DEBUG(req_num, "There is no request");
739             return;
740         }
741     }
742
743     for (auto &act : actions)
744     {
745         if ("" != act.role)
746         {
747             bool found;
748             auto const &surface_id = this->id_alloc.lookup(act.role.c_str());
749             if(surface_id == nullopt)
750             {
751                 goto proc_remove_request;
752             }
753             std::string appid = g_app_list.getAppID(*surface_id, &found);
754             if (!found)
755             {
756                 if (TaskVisible::INVISIBLE == act.visible)
757                 {
758                     // App is killed, so do not set this action
759                     continue;
760                 }
761                 else
762                 {
763                     HMI_SEQ_ERROR(req_num, "appid which is visible is not found");
764                     ret = WMError::FAIL;
765                     goto error;
766                 }
767             }
768             auto client = g_app_list.lookUpClient(appid);
769             act.req_num = req_num;
770             act.client = client;
771         }
772
773         ret = g_app_list.setAction(req_num, act);
774         if (ret != WMError::SUCCESS)
775         {
776             HMI_SEQ_ERROR(req_num, "Setting action is failed");
777             goto error;
778         }
779     }
780
781     HMI_SEQ_DEBUG(req_num, "Start transition.");
782     ret = this->startTransition(req_num);
783     if (ret != WMError::SUCCESS)
784     {
785         if (ret == WMError::NO_LAYOUT_CHANGE)
786         {
787             goto proc_remove_request;
788         }
789         else
790         {
791             HMI_SEQ_ERROR(req_num, "Transition state is failed");
792             goto error;
793         }
794     }
795
796     return;
797
798 error:
799     //this->emit_error()
800     HMI_SEQ_ERROR(req_num, errorDescription(ret));
801     this->pmw.undoState();
802
803 proc_remove_request:
804     g_app_list.removeRequest(req_num);
805     this->processNextRequest();
806 }
807
808 void WindowManager::processError(WMError error)
809 {
810     unsigned req_num = g_app_list.currentRequestNumber();
811
812     //this->emit_error()
813     HMI_SEQ_ERROR(req_num, errorDescription(error));
814     g_app_list.removeRequest(req_num);
815     this->processNextRequest();
816 }
817
818 /*
819  ******* Private Functions *******
820  */
821
822 void WindowManager::emit_activated(char const *label)
823 {
824     this->send_event(kListEventName[Event_Active], label);
825 }
826
827 void WindowManager::emit_deactivated(char const *label)
828 {
829     this->send_event(kListEventName[Event_Inactive], label);
830 }
831
832 void WindowManager::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h)
833 {
834     this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
835 }
836
837 void WindowManager::emit_syncdraw(const string &role, const string &area)
838 {
839     rect rect = this->lc->getAreaSize(area);
840     this->send_event(kListEventName[Event_SyncDraw],
841         role.c_str(), area.c_str(), rect.x, rect.y, rect.w, rect.h);
842 }
843
844 void WindowManager::emit_flushdraw(char const *label)
845 {
846     this->send_event(kListEventName[Event_FlushDraw], label);
847 }
848
849 void WindowManager::emit_visible(char const *label, bool is_visible)
850 {
851     this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
852 }
853
854 void WindowManager::emit_invisible(char const *label)
855 {
856     return emit_visible(label, false);
857 }
858
859 void WindowManager::emit_visible(char const *label) { return emit_visible(label, true); }
860
861 void WindowManager::activate(int id)
862 {
863     // TODO: application requests by old role,
864     //       so convert role new to old for emitting event
865     /* const char* old_role = this->rolenew2old[label].c_str();
866
867     this->emit_visible(old_role);
868     this->emit_activated(old_role); */
869 }
870
871 void WindowManager::deactivate(int id)
872 {
873     // TODO: application requests by old role,
874     //       so convert role new to old for emitting event
875     /* const char* old_role = this->rolenew2old[label].c_str();
876
877     this->emit_deactivated(old_role);
878     this->emit_invisible(old_role); */
879 }
880
881 WMError WindowManager::setRequest(const string& appid, const string &role, const string &area,
882                             Task task, unsigned* req_num)
883 {
884     if (!g_app_list.contains(appid))
885     {
886         return WMError::NOT_REGISTERED;
887     }
888
889     auto client = g_app_list.lookUpClient(appid);
890
891     /*
892      * Queueing Phase
893      */
894     unsigned current = g_app_list.currentRequestNumber();
895     unsigned requested_num = g_app_list.getRequestNumber(appid);
896     if (requested_num != 0)
897     {
898         HMI_SEQ_INFO(requested_num,
899             "%s %s %s request is already queued", appid.c_str(), role.c_str(), area.c_str());
900         return REQ_REJECTED;
901     }
902
903     WMRequest req = WMRequest(appid, role, area, task);
904     unsigned new_req = g_app_list.addRequest(req);
905     *req_num = new_req;
906     g_app_list.reqDump();
907
908     HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", appid.c_str(), role.c_str(), area.c_str());
909
910     return WMError::SUCCESS;
911 }
912
913 WMError WindowManager::checkPolicy(unsigned req_num)
914 {
915     /*
916     * Check Policy
917     */
918     // get current trigger
919     bool found = false;
920     WMError ret = WMError::LAYOUT_CHANGE_FAIL;
921     auto trigger = g_app_list.getRequest(req_num, &found);
922     if (!found)
923     {
924         ret = WMError::NO_ENTRY;
925         return ret;
926     }
927     string req_area = trigger.area;
928
929     if (trigger.task == Task::TASK_ALLOCATE)
930     {
931         const char *msg = this->check_surface_exist(trigger.role.c_str());
932
933         if (msg)
934         {
935             HMI_SEQ_ERROR(req_num, msg);
936             return ret;
937         }
938     }
939
940     // Input event data to PolicyManager
941     if (0 > this->pmw.setInputEventData(trigger.task, trigger.role, trigger.area))
942     {
943         HMI_SEQ_ERROR(req_num, "Failed to set input event data to PolicyManager");
944         return ret;
945     }
946
947     // Execute state transition of PolicyManager
948     if (0 > this->pmw.executeStateTransition())
949     {
950         HMI_SEQ_ERROR(req_num, "Failed to execute state transition of PolicyManager");
951         return ret;
952     }
953
954     ret = WMError::SUCCESS;
955
956     g_app_list.reqDump();
957
958     return ret;
959 }
960
961 WMError WindowManager::startTransition(unsigned req_num)
962 {
963     bool sync_draw_happen = false;
964     bool found = false;
965     WMError ret = WMError::SUCCESS;
966     auto actions = g_app_list.getActions(req_num, &found);
967     if (!found)
968     {
969         ret = WMError::NO_ENTRY;
970         HMI_SEQ_ERROR(req_num,
971             "Window Manager bug :%s : Action is not set", errorDescription(ret));
972         return ret;
973     }
974
975     g_app_list.reqDump();
976     for (const auto &action : actions)
977     {
978         if (action.visible == TaskVisible::VISIBLE)
979         {
980             sync_draw_happen = true;
981
982             // TODO: application requests by old role,
983             //       so convert role new to old for emitting event
984             string old_role = this->rolenew2old[action.role];
985
986             this->emit_syncdraw(old_role, action.area);
987             /* TODO: emit event for app not subscriber
988             if(g_app_list.contains(y.appid))
989                 g_app_list.lookUpClient(y.appid)->emit_syncdraw(y.role, y.area); */
990         }
991     }
992
993     if (sync_draw_happen)
994     {
995         this->setTimer();
996     }
997     else
998     {
999         // deactivate only, no syncDraw
1000         // Make it deactivate here
1001         for (const auto &x : actions)
1002         {
1003             this->lc->visibilityChange(x);
1004             string old_role = this->rolenew2old[x.role];
1005             emit_deactivated(old_role.c_str());
1006
1007             /* if (g_app_list.contains(x.appid))
1008             {
1009                 auto client = g_app_list.lookUpClient(x.appid);
1010                 //this->deactivate(client->surfaceID(x.role));
1011             } */
1012         }
1013         this->lc->renderLayers();
1014         ret = WMError::NO_LAYOUT_CHANGE;
1015     }
1016     return ret;
1017 }
1018
1019 WMError WindowManager::doEndDraw(unsigned req_num)
1020 {
1021     // get actions
1022     bool found;
1023     auto actions = g_app_list.getActions(req_num, &found);
1024     WMError ret = WMError::SUCCESS;
1025     if (!found)
1026     {
1027         ret = WMError::NO_ENTRY;
1028         return ret;
1029     }
1030
1031     HMI_SEQ_INFO(req_num, "do endDraw");
1032
1033     // layout change and make it visible
1034     for (const auto &act : actions)
1035     {
1036         if(act.visible != TaskVisible::NO_CHANGE)
1037         {
1038             // layout change
1039             ret = this->lc->layoutChange(act);
1040             if(ret != WMError::SUCCESS)
1041             {
1042                 HMI_SEQ_WARNING(req_num,
1043                     "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1044                 return ret;
1045             }
1046             ret = this->lc->visibilityChange(act);
1047
1048             // Emit active/deactive event
1049             string old_role = this->rolenew2old[act.role];
1050             if(act.visible == VISIBLE)
1051             {
1052                 emit_activated(old_role.c_str());
1053             }
1054             else
1055             {
1056                 emit_deactivated(old_role.c_str());
1057             }
1058
1059             if (ret != WMError::SUCCESS)
1060             {
1061                 HMI_SEQ_WARNING(req_num,
1062                     "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1063                 return ret;
1064             }
1065             HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str());
1066         }
1067     }
1068     this->lc->renderLayers();
1069
1070     HMI_SEQ_INFO(req_num, "emit flushDraw");
1071
1072     for(const auto &act_flush : actions)
1073     {
1074         if(act_flush.visible == TaskVisible::VISIBLE)
1075         {
1076             // TODO: application requests by old role,
1077             //       so convert role new to old for emitting event
1078             string old_role = this->rolenew2old[act_flush.role];
1079
1080             this->emit_flushdraw(old_role.c_str());
1081         }
1082     }
1083
1084     return ret;
1085 }
1086
1087 void WindowManager::emitScreenUpdated(unsigned req_num)
1088 {
1089     // Get visible apps
1090     HMI_SEQ_DEBUG(req_num, "emit screen updated");
1091     bool found = false;
1092     auto actions = g_app_list.getActions(req_num, &found);
1093
1094     // create json object
1095     json_object *j = json_object_new_object();
1096     json_object *jarray = json_object_new_array();
1097
1098     for(const auto& action: actions)
1099     {
1100         if(action.visible != TaskVisible::INVISIBLE)
1101         {
1102             json_object_array_add(jarray, json_object_new_string(action.client->appID().c_str()));
1103         }
1104     }
1105     json_object_object_add(j, kKeyIds, jarray);
1106     HMI_SEQ_INFO(req_num, "Visible app: %s", json_object_get_string(j));
1107
1108     int ret = afb_event_push(
1109         this->map_afb_event[kListEventName[Event_ScreenUpdated]], j);
1110     if (ret != 0)
1111     {
1112         HMI_DEBUG("afb_event_push failed: %m");
1113     }
1114 }
1115
1116 void WindowManager::setTimer()
1117 {
1118     struct timespec ts;
1119     if (clock_gettime(CLOCK_BOOTTIME, &ts) != 0) {
1120         HMI_ERROR("Could't set time (clock_gettime() returns with error");
1121         return;
1122     }
1123
1124     HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Timer set activate");
1125     if (g_timer_ev_src == nullptr)
1126     {
1127         // firsttime set into sd_event
1128         int ret = sd_event_add_time(afb_daemon_get_event_loop(), &g_timer_ev_src,
1129             CLOCK_BOOTTIME, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL, 1, processTimerHandler, this);
1130         if (ret < 0)
1131         {
1132             HMI_ERROR("Could't set timer");
1133         }
1134     }
1135     else
1136     {
1137         // update timer limitation after second time
1138         sd_event_source_set_time(g_timer_ev_src, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL);
1139         sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT);
1140     }
1141 }
1142
1143 void WindowManager::stopTimer()
1144 {
1145     unsigned req_num = g_app_list.currentRequestNumber();
1146     HMI_SEQ_DEBUG(req_num, "Timer stop");
1147     int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF);
1148     if (rc < 0)
1149     {
1150         HMI_SEQ_ERROR(req_num, "Timer stop failed");
1151     }
1152 }
1153
1154 void WindowManager::processNextRequest()
1155 {
1156     g_app_list.next();
1157     g_app_list.reqDump();
1158     unsigned req_num = g_app_list.currentRequestNumber();
1159     if (g_app_list.haveRequest())
1160     {
1161         HMI_SEQ_DEBUG(req_num, "Process next request");
1162         WMError rc = checkPolicy(req_num);
1163         if (rc != WMError::SUCCESS)
1164         {
1165             HMI_SEQ_ERROR(req_num, errorDescription(rc));
1166         }
1167     }
1168     else
1169     {
1170         HMI_SEQ_DEBUG(req_num, "Nothing Request. Waiting Request");
1171     }
1172 }
1173
1174 const char* WindowManager::convertRoleOldToNew(char const *old_role)
1175 {
1176     const char *new_role = nullptr;
1177
1178     for (auto const &on : this->roleold2new)
1179     {
1180         std::regex regex = std::regex(on.first);
1181         if (std::regex_match(old_role, regex))
1182         {
1183             // role is old. So convert to new.
1184             new_role = on.second.c_str();
1185             break;
1186         }
1187     }
1188
1189     if (nullptr == new_role)
1190     {
1191         // role is new or fallback.
1192         new_role = old_role;
1193     }
1194
1195     HMI_DEBUG("old:%s -> new:%s", old_role, new_role);
1196
1197     return new_role;
1198 }
1199
1200 int WindowManager::loadOldRoleDb()
1201 {
1202     // Get afm application installed dir
1203     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1204     HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
1205
1206     string file_name;
1207     if (!afm_app_install_dir)
1208     {
1209         HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
1210     }
1211     else
1212     {
1213         file_name = string(afm_app_install_dir) + string("/etc/old_roles.db");
1214     }
1215
1216     // Load old_role.db
1217     json_object* json_obj;
1218     int ret = jh::inputJsonFilie(file_name.c_str(), &json_obj);
1219     if (0 > ret)
1220     {
1221         HMI_ERROR("Could not open old_role.db, so use default old_role information");
1222         json_obj = json_tokener_parse(kDefaultOldRoleDb);
1223     }
1224     HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
1225
1226     // Perse apps
1227     json_object* json_cfg;
1228     if (!json_object_object_get_ex(json_obj, "old_roles", &json_cfg))
1229     {
1230         HMI_ERROR("Parse Error!!");
1231         return -1;
1232     }
1233
1234     int len = json_object_array_length(json_cfg);
1235     HMI_DEBUG("json_cfg len:%d", len);
1236     HMI_DEBUG("json_cfg dump:%s", json_object_get_string(json_cfg));
1237
1238     for (int i=0; i<len; i++)
1239     {
1240         json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
1241
1242         const char* old_role = jh::getStringFromJson(json_tmp, "name");
1243         if (nullptr == old_role)
1244         {
1245             HMI_ERROR("Parse Error!!");
1246             return -1;
1247         }
1248
1249         const char* new_role = jh::getStringFromJson(json_tmp, "new");
1250         if (nullptr == new_role)
1251         {
1252             HMI_ERROR("Parse Error!!");
1253             return -1;
1254         }
1255
1256         this->roleold2new[old_role] = string(new_role);
1257     }
1258
1259     // Check
1260     for(auto itr = this->roleold2new.begin();
1261       itr != this->roleold2new.end(); ++itr)
1262     {
1263         HMI_DEBUG(">>> role old:%s new:%s",
1264                   itr->first.c_str(), itr->second.c_str());
1265     }
1266
1267     // Release json_object
1268     json_object_put(json_obj);
1269
1270     return 0;
1271 }
1272
1273 const char *WindowManager::check_surface_exist(const char *drawing_name)
1274 {
1275     auto const &surface_id = this->id_alloc.lookup(string(drawing_name));
1276     if (!surface_id)
1277     {
1278         return "Surface does not exist";
1279     }
1280
1281     /* if (!this->controller->surface_exists(*surface_id))
1282     {
1283         return "Surface does not exist in controller!";
1284     } */
1285
1286     /* auto layer_id = this->layers.get_layer_id(*surface_id);
1287
1288     if (!layer_id)
1289     {
1290         return "Surface is not on any layer!";
1291     } */
1292
1293     HMI_DEBUG("surface %d is detected", *surface_id);
1294     return nullptr;
1295 }
1296
1297 const char* WindowManager::kDefaultOldRoleDb = "{ \
1298     \"old_roles\": [ \
1299         { \
1300             \"name\": \"HomeScreen\", \
1301             \"new\": \"homescreen\" \
1302         }, \
1303         { \
1304             \"name\": \"Music\", \
1305             \"new\": \"music\" \
1306         }, \
1307         { \
1308             \"name\": \"MediaPlayer\", \
1309             \"new\": \"music\" \
1310         }, \
1311         { \
1312             \"name\": \"Video\", \
1313             \"new\": \"video\" \
1314         }, \
1315         { \
1316             \"name\": \"VideoPlayer\", \
1317             \"new\": \"video\" \
1318         }, \
1319         { \
1320             \"name\": \"WebBrowser\", \
1321             \"new\": \"browser\" \
1322         }, \
1323         { \
1324             \"name\": \"Radio\", \
1325             \"new\": \"radio\" \
1326         }, \
1327         { \
1328             \"name\": \"Phone\", \
1329             \"new\": \"phone\" \
1330         }, \
1331         { \
1332             \"name\": \"Navigation\", \
1333             \"new\": \"map\" \
1334         }, \
1335         { \
1336             \"name\": \"HVAC\", \
1337             \"new\": \"hvac\" \
1338         }, \
1339         { \
1340             \"name\": \"Settings\", \
1341             \"new\": \"settings\" \
1342         }, \
1343         { \
1344             \"name\": \"Dashboard\", \
1345             \"new\": \"dashboard\" \
1346         }, \
1347         { \
1348             \"name\": \"POI\", \
1349             \"new\": \"poi\" \
1350         }, \
1351         { \
1352             \"name\": \"Mixer\", \
1353             \"new\": \"mixer\" \
1354         }, \
1355         { \
1356             \"name\": \"Restriction\", \
1357             \"new\": \"restriction\" \
1358         }, \
1359         { \
1360             \"name\": \"^OnScreen.*\", \
1361             \"new\": \"on_screen\" \
1362         } \
1363     ] \
1364 }";
1365
1366 } // namespace wm