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