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