e4083d534bffcf667b503c84580c658f175a479c
[apps/agl-service-windowmanager.git] / src / window_manager.cpp
1 /*
2  * Copyright (c) 2017 TOYOTA MOTOR CORPORATION
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <fstream>
18 #include <regex>
19
20 #include "window_manager.hpp"
21 #include "json_helper.hpp"
22 #include "applist.hpp"
23
24 extern "C"
25 {
26 #include <systemd/sd-event.h>
27 }
28
29 using std::string;
30 using std::vector;
31
32 namespace wm
33 {
34
35 static const uint64_t kTimeOut = 3ULL; /* 3s */
36
37 /* DrawingArea name used by "{layout}.{area}" */
38 const char kNameLayoutNormal[] = "normal";
39 const char kNameLayoutSplit[]  = "split";
40 const char kNameAreaFull[]     = "full";
41 const char kNameAreaMain[]     = "main";
42 const char kNameAreaSub[]      = "sub";
43
44 /* Key for json obejct */
45 const char kKeyDrawingName[] = "drawing_name";
46 const char kKeyDrawingArea[] = "drawing_area";
47 const char kKeyDrawingRect[] = "drawing_rect";
48 const char kKeyX[]           = "x";
49 const char kKeyY[]           = "y";
50 const char kKeyWidth[]       = "width";
51 const char kKeyHeight[]      = "height";
52 const char kKeyWidthPixel[]  = "width_pixel";
53 const char kKeyHeightPixel[] = "height_pixel";
54 const char kKeyWidthMm[]     = "width_mm";
55 const char kKeyHeightMm[]    = "height_mm";
56 const char kKeyScale[]       = "scale";
57 const char kKeyIds[]         = "ids";
58
59 static sd_event_source *g_timer_ev_src = nullptr;
60 static AppList g_app_list;
61 static WindowManager *g_context;
62
63 namespace
64 {
65
66 // using nlohmann::json;
67
68 /* result<json> file_to_json(char const *filename)
69 {
70     json j;
71     std::ifstream i(filename);
72     if (i.fail())
73     {
74         HMI_DEBUG("Could not open config file, so use default layer information");
75         j = default_layers_json;
76     }
77     else
78     {
79         i >> j;
80     }
81
82     return Ok(j);
83 }
84
85 struct result<layer_map> load_layer_map(char const *filename)
86 {
87     HMI_DEBUG("loading IDs from %s", filename);
88
89     auto j = file_to_json(filename);
90     if (j.is_err())
91     {
92         return Err<layer_map>(j.unwrap_err());
93     }
94     json jids = j.unwrap();
95
96     return to_layer_map(jids);
97 } */
98
99 static int processTimerHandler(sd_event_source *s, uint64_t usec, void *userdata)
100 {
101     HMI_NOTICE("Time out occurs because the client replys endDraw slow, so revert the request");
102     reinterpret_cast<wm::WindowManager *>(userdata)->timerHandler();
103     return 0;
104 }
105
106 static void onStateTransitioned(vector<WMAction> actions)
107 {
108     g_context->startTransitionWrapper(actions);
109 }
110
111 static void onError()
112 {
113     g_context->processError(WMError::LAYOUT_CHANGE_FAIL);
114 }
115 } // namespace
116
117 /**
118  * WindowManager Impl
119  */
120 WindowManager::WindowManager()
121     : chooks{this},
122       id_alloc{}
123 {
124     const char *path = getenv("AFM_APP_INSTALL_DIR");
125     if (!path)
126     {
127         HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
128     }
129     string root = path;
130
131     this->lc = std::make_shared<LayerControl>(root);
132
133     HMI_DEBUG("Layer Controller initialized");
134
135 /*     try
136     {
137         {
138             auto l = load_layer_map(path.c_str());
139             if (l.is_ok())
140             {
141                 this->layers = l.unwrap();
142             }
143             else
144             {
145                 HMI_ERROR("%s", l.err().value());
146             }
147         }
148     }
149     catch (std::exception &e)
150     {
151         HMI_ERROR("Loading of configuration failed: %s", e.what());
152     } */
153 }
154
155 int WindowManager::init()
156 {
157     /* if (!this->display->ok())
158     {
159         return -1;
160     }
161
162     if (this->layers.mapping.empty())
163     {
164         HMI_ERROR("No surface -> layer mapping loaded");
165         return -1;
166     } */
167
168     // TODO: application requests by old role,
169     //       so create role map (old, new)
170     // Load old_role.db
171     LayerControlCallbacks lmcb;
172     lmcb.surfaceCreated = [&](unsigned pid, unsigned surface){
173         this->surface_created(surface);
174         };
175     lmcb.surfaceDestroyed = [&](unsigned surface){
176         this->surface_removed(surface);
177     };
178     this->lc->init(lmcb);
179     this->loadOldRoleDb();
180
181     // Store my context for calling callback from PolicyManager
182     g_context = this;
183
184     // Initialize PMWrapper
185     this->pmw.initialize();
186
187     // Register callback to PolicyManager
188     this->pmw.registerCallback(onStateTransitioned, onError);
189
190     // Make afb event
191     for (int i = Event_Val_Min; i <= Event_Val_Max; i++)
192     {
193         map_afb_event[kListEventName[i]] = afb_daemon_make_event(kListEventName[i]);
194     }
195
196     const struct rect css_bg = this->lc->getAreaSize("fullscreen");
197     Screen screen = this->lc->getScreenInfo();
198     rectangle dp_bg(screen.width(), screen.height());
199
200     dp_bg.set_aspect(static_cast<double>(css_bg.w) / css_bg.h);
201     dp_bg.fit(screen.width(), screen.height());
202     dp_bg.center(screen.width(), screen.height());
203     HMI_DEBUG("SCALING: CSS BG(%dx%d) -> DDP %dx%d,(%dx%d)",
204               css_bg.w, css_bg.h, dp_bg.left(), dp_bg.top(), dp_bg.width(), dp_bg.height());
205
206     double scale = static_cast<double>(dp_bg.height()) / css_bg.h;
207     this->lc->setupArea(dp_bg, scale);
208
209     /* this->display->add_global_handler(
210         "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
211             this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
212         });
213
214     this->display->add_global_handler(
215         "ivi_wm", [this](wl_registry *r, uint32_t name, uint32_t v) {
216             this->controller =
217                 std::make_unique<struct compositor::controller>(r, name, v);
218
219             // Init controller hooks
220             this->controller->chooks = &this->chooks;
221
222             // This protocol needs the output, so lets just add our mapping here...
223             this->controller->add_proxy_to_id_mapping(
224                 this->outputs.front()->proxy.get(),
225                 wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
226                     this->outputs.front()->proxy.get())));
227
228             // Create screen
229             this->controller->create_screen(this->outputs.front()->proxy.get());
230
231             // Set display to controller
232             this->controller->display = this->display;
233         });
234
235     // First level objects
236     this->display->roundtrip();
237     // Second level objects
238     this->display->roundtrip();
239     // Third level objects
240     this->display->roundtrip(); */
241
242     return 0; //init_layers();
243 }
244
245 /* int WindowManager::dispatch_pending_events()
246 {
247     if (this->pop_pending_events())
248     {
249         this->display->dispatch_pending();
250         return 0;
251     }
252     return -1;
253 }
254
255 void WindowManager::set_pending_events()
256 {
257     this->pending_events.store(true, std::memory_order_release);
258 } */
259
260 result<int> WindowManager::api_request_surface(char const *appid, char const *drawing_name)
261 {
262     // TODO: application requests by old role,
263     //       so convert role old to new
264     const char *role = this->convertRoleOldToNew(drawing_name);
265     string l_name;
266     string s_appid = appid;
267     string s_role = role;
268
269     if(!g_app_list.contains(s_appid))
270     {
271         // auto lid = this->layers.get_layer_id(string(role));
272         unsigned l_id = this->lc->getNewLayerID(s_role, &l_name);
273         if (l_id == 0)
274         {
275             /**
276          * register drawing_name as fallback and make it displayed.
277          */
278             // lid = this->layers.get_layer_id(string("fallback"));
279             l_id = this->lc->getNewLayerID("fallback", &l_name);
280             HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
281             if (l_id == 0)
282             {
283                 return Err<int>("Designated role does not match any role, fallback is disabled");
284             }
285         }
286         this->lc->createNewLayer(l_id);
287         // add client into the db
288         g_app_list.addClient(s_appid, l_id, s_role);
289     }
290
291     // generate surface ID for ivi-shell application
292
293     auto rname = this->id_alloc.lookup(string(role));
294     if (!rname)
295     {
296         // name does not exist yet, allocate surface id...
297         auto id = int(this->id_alloc.generate_id(role));
298         this->tmp_surface2app[id] = s_appid;
299
300         // this->layers.add_surface(id, *lid);
301
302         // set the main_surface[_name] here and now
303         // if (!this->layers.main_surface_name.empty() &&
304         //     this->layers.main_surface_name == drawing_name)
305         // {
306         //     this->layers.main_surface = id;
307         //     HMI_DEBUG("Set main_surface id to %u", id);
308         // }
309
310
311
312         /* if(g_app_list.contains(appid_str))
313         {
314             // add surface into app
315             auto client = g_app_list.lookUpClient(appid_str);
316             // client.addSurface(id);
317         }
318         else
319         {
320             g_app_list.addClient(appid_str, l_id, id, string(role));
321         } */
322
323         // Set role map of (new, old)
324         this->rolenew2old[role] = string(drawing_name);
325
326         return Ok<int>(id);
327     }
328
329     // Check currently registered drawing names if it is already there.
330     return Err<int>("Surface already present");
331 }
332
333 char const *WindowManager::api_request_surface(char const *appid, char const *drawing_name,
334                                      char const *ivi_id)
335 {
336     // TODO: application requests by old role,
337     //       so convert role old to new
338     const char *role = this->convertRoleOldToNew(drawing_name);
339     string str = role;
340     string l_name;
341
342     // auto lid = this->layers.get_layer_id(string(role));
343     unsigned lid = this->lc->getNewLayerID(str, &l_name);
344     unsigned sid = std::stol(ivi_id);
345
346     if (lid == 0)
347     {
348         //register drawing_name as fallback and make it displayed.
349         lid = this->lc->getNewLayerID(str, &l_name);
350         HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
351         if (lid == 0)
352         {
353             return "Drawing name does not match any role, fallback is disabled";
354         }
355     }
356
357     this->lc->createNewLayer(lid);
358
359     auto rname = this->id_alloc.lookup(str);
360
361     if (rname)
362     {
363         return "Surface already present";
364     }
365
366     // register pair drawing_name and ivi_id
367     this->id_alloc.register_name_id(role, sid);
368     // this->layers.add_surface(sid, *lid);
369
370     // this surface is already created
371     // HMI_DEBUG("surface_id is %u, layer_id is %u", sid, *lid);
372
373     // this->controller->layers[*lid]->add_surface(sid);
374     // this->layout_commit();
375
376     // add client into the db
377     string appid_str(appid);
378     g_app_list.addClient(appid_str, lid, string(role));
379
380     // Set role map of (new, old)
381     this->rolenew2old[role] = string(drawing_name);
382
383     return nullptr;
384 }
385
386 /**
387  * This function is substitute of requestSurface
388  * If surface creation is faster than application request of this function,
389  * WM will bind surfaceID with application and role.
390  * If surface creation is slower than application request of thie function,
391  * WM will put Client into pending list.
392  *
393  * Note :
394  * Application can request with pid but this is temporary solution for now.
395  * This will be removed.
396  * */
397 bool WindowManager::api_set_role(char const *appid, char const *drawing_name, unsigned pid){
398     string id = appid;
399     string role = drawing_name;
400     string l_name;
401     unsigned surface = 0;
402     WMError wm_err = WMError::UNKNOWN;
403     bool ret = false;
404
405     // get layer ID which role should be in
406     // auto lid = this->layers.get_layer_id(role);
407     unsigned lid = this->lc->getNewLayerID(role, &l_name);
408     if (lid == 0)
409     {
410         // lid = this->layers.get_layer_id(string("fallback"));
411         HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role.c_str());
412         if (lid == 0)
413         {
414             HMI_ERROR("Drawing name does not match any role, fallback is disabled");
415             return ret;
416         }
417     }
418
419     if(0 != pid){
420         // search floating surfaceID from pid if pid is designated.
421         wm_err = g_app_list.popFloatingSurface(pid, &surface);
422     }
423     else{
424         // get floating surface with appid. If WM queries appid from pid,
425         // WM can bind surface and role with appid(not implemented yet)
426         //wm_err = g_app_list.popFloatingSurface(id);
427     }
428     if(wm_err != WMError::SUCCESS){
429         HMI_ERROR("No floating surface for app: %s", id.c_str());
430         g_app_list.addFloatingClient(id, lid, role);
431         HMI_NOTICE("%s : Waiting for surface creation", id.c_str());
432         return ret;
433     }
434
435     ret = true;
436     if (g_app_list.contains(id))
437     {
438         HMI_INFO("Add role: %s with surface: %d. Client %s has multi surfaces.",
439                  role.c_str(), surface, id.c_str());
440         auto client = g_app_list.lookUpClient(id);
441         client->appendRole(role);
442     }
443     else{
444         HMI_INFO("Create new client: %s, surface: %d into layer: %d with role: %s",
445                  id.c_str(), surface, lid, role.c_str());
446         g_app_list.addClient(id, lid, role);
447     }
448
449     // register pair drawing_name and ivi_id
450     this->id_alloc.register_name_id(role.c_str(), surface);
451     // this->layers.add_surface(surface, *lid);
452
453     // this surface is already created
454     HMI_DEBUG("surface_id is %u, layer_id is %u", surface, lid);
455
456     // const auto &o_layer = this->layers.get_layer(*lid);
457     /* auto rect = o_layer.value().rect;
458     if(rect.w < 0)
459     {
460         rect.w = this->controller->output_size.w + 1 + rect.w;
461     }
462     if(rect.h < 0)
463     {
464         rect.h = this->controller->output_size.h + 1 + rect.h;
465     } */
466
467     // this->controller->layers[*lid]->add_surface(surface);
468     // this->layout_commit();
469
470     return ret;
471 }
472
473 void WindowManager::api_activate_surface(char const *appid, char const *drawing_name,
474                                char const *drawing_area, const reply_func &reply)
475 {
476     ;
477
478     // TODO: application requests by old role,
479     //       so convert role old to new
480     const char *c_role = this->convertRoleOldToNew(drawing_name);
481
482     string id = appid;
483     string role = c_role;
484     string area = drawing_area;
485
486     if(!g_app_list.contains(id))
487     {
488         reply("app doesn't request 'requestSurface' or 'setRole' yet");
489         return;
490     }
491     auto client = g_app_list.lookUpClient(id);
492
493     // unsigned srfc = client->surfaceID(role);
494     // unsigned layer = client->layerID();
495
496     // g_app_list.removeFloatingSurface(client->surfaceID());
497     // g_app_list.removeFloatingSurface(client);
498
499     Task task = Task::TASK_ALLOCATE;
500     unsigned req_num = 0;
501     WMError ret = WMError::UNKNOWN;
502
503     ret = this->setRequest(id, role, area, task, &req_num);
504
505     //vector<WMLayerState> current_states = this->lc->getCurrentStates();
506     // ret = this->setRequest(id, role, area, task, current_states, &req_num);
507
508     if(ret != WMError::SUCCESS)
509     {
510         HMI_ERROR(errorDescription(ret));
511         reply("Failed to set request");
512         return;
513     }
514
515     reply(nullptr);
516     if (req_num != g_app_list.currentRequestNumber())
517     {
518         // Add request, then invoked after the previous task is finished
519         HMI_SEQ_DEBUG(req_num, "request is accepted");
520         return;
521     }
522
523     /*
524      * Do allocate tasks
525      */
526     ret = this->checkPolicy(req_num);
527
528     if (ret != WMError::SUCCESS)
529     {
530         //this->emit_error()
531         HMI_SEQ_ERROR(req_num, errorDescription(ret));
532         g_app_list.removeRequest(req_num);
533         this->processNextRequest();
534     }
535 }
536
537 void WindowManager::api_deactivate_surface(char const *appid, char const *drawing_name,
538                                  const reply_func &reply)
539 {
540     ;
541
542     // TODO: application requests by old role,
543     //       so convert role old to new
544     const char *c_role = this->convertRoleOldToNew(drawing_name);
545
546     /*
547     * Check Phase
548     */
549     string id = appid;
550     string role = c_role;
551     string area = ""; //drawing_area;
552     Task task = Task::TASK_RELEASE;
553     unsigned req_num = 0;
554     WMError ret = WMError::UNKNOWN;
555
556     ret = this->setRequest(id, role, area, task, &req_num);
557     //vector<WMLayerState> current_states = this->lc->getCurrentStates();
558     // ret = this->setRequest(id, role, area, task, current_states, &req_num);
559
560     if (ret != WMError::SUCCESS)
561     {
562         HMI_ERROR(errorDescription(ret));
563         reply("Failed to set request");
564         return;
565     }
566
567     reply(nullptr);
568     if (req_num != g_app_list.currentRequestNumber())
569     {
570         // Add request, then invoked after the previous task is finished
571         HMI_SEQ_DEBUG(req_num, "request is accepted");
572         return;
573     }
574
575     /*
576     * Do allocate tasks
577     */
578     ret = this->checkPolicy(req_num);
579
580     if (ret != WMError::SUCCESS)
581     {
582         //this->emit_error()
583         HMI_SEQ_ERROR(req_num, errorDescription(ret));
584         g_app_list.removeRequest(req_num);
585         this->processNextRequest();
586     }
587 }
588
589 void WindowManager::api_enddraw(char const *appid, char const *drawing_name)
590 {
591     // TODO: application requests by old role,
592     //       so convert role old to new
593     const char *c_role = this->convertRoleOldToNew(drawing_name);
594
595     string id = appid;
596     string role = c_role;
597     unsigned current_req = g_app_list.currentRequestNumber();
598     bool result = g_app_list.setEndDrawFinished(current_req, id, role);
599
600     if (!result)
601     {
602         HMI_ERROR("%s is not in transition state", id.c_str());
603         return;
604     }
605
606     if (g_app_list.endDrawFullfilled(current_req))
607     {
608         // do task for endDraw
609         this->stopTimer();
610         WMError ret = this->doEndDraw(current_req);
611
612         if(ret != WMError::SUCCESS)
613         {
614             //this->emit_error();
615
616             // Undo state of PolicyManager
617             this->pmw.undoState();
618             this->lc->undoUpdate();
619         }
620         this->emitScreenUpdated(current_req);
621         HMI_SEQ_INFO(current_req, "Finish request status: %s", errorDescription(ret));
622
623         g_app_list.removeRequest(current_req);
624
625         this->processNextRequest();
626     }
627     else
628     {
629         HMI_SEQ_INFO(current_req, "Wait other App call endDraw");
630         return;
631     }
632 }
633
634 result<json_object *> WindowManager::api_get_display_info()
635 {
636     /* if (!this->display->ok())
637     {
638         return Err<json_object *>("Wayland compositor is not available");
639     } */
640
641     // Set display info
642 /*     size o_size = this->controller->output_size;
643     size p_size = this->controller->physical_size; */
644     Screen screen = this->lc->getScreenInfo();
645
646     json_object *object = json_object_new_object();
647     json_object_object_add(object, kKeyWidthPixel, json_object_new_int(screen.width()));
648     json_object_object_add(object, kKeyHeightPixel, json_object_new_int(screen.height()));
649     // TODO: set size
650     json_object_object_add(object, kKeyWidthMm, json_object_new_int(0));
651     json_object_object_add(object, kKeyHeightMm, json_object_new_int(0));
652     json_object_object_add(object, kKeyScale, json_object_new_double(this->lc->scale()));
653
654     return Ok<json_object *>(object);
655 }
656
657 result<json_object *> WindowManager::api_get_area_info(char const *drawing_name)
658 {
659     HMI_DEBUG("called");
660
661     // TODO: application requests by old role,
662     //       so convert role old to new
663     const char *role = this->convertRoleOldToNew(drawing_name);
664
665     // Check drawing name, surface/layer id
666     auto const &surface_id = this->id_alloc.lookup(string(role));
667     if (!surface_id)
668     {
669         return Err<json_object *>("Surface does not exist");
670     }
671
672     /* if (!this->controller->surface_exists(*surface_id))
673     {
674         return Err<json_object *>("Surface does not exist in controller!");
675     } */
676
677     /* // auto layer_id = this->layers.get_layer_id(*surface_id);
678     if (!layer_id)
679     {
680         return Err<json_object *>("Surface is not on any layer!");
681     } */
682
683     // Set area rectangle
684     rect area_info = this->area_info[*surface_id];
685     json_object *object = json_object_new_object();
686     json_object_object_add(object, kKeyX, json_object_new_int(area_info.x));
687     json_object_object_add(object, kKeyY, json_object_new_int(area_info.y));
688     json_object_object_add(object, kKeyWidth, json_object_new_int(area_info.w));
689     json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
690
691     return Ok<json_object *>(object);
692 }
693
694 void WindowManager::api_ping() { /* this->dispatch_pending_events(); */ }
695
696 void WindowManager::send_event(char const *evname, char const *label)
697 {
698     HMI_DEBUG("%s: %s(%s)", __func__, evname, label);
699
700     json_object *j = json_object_new_object();
701     json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
702
703     int ret = afb_event_push(this->map_afb_event[evname], j);
704     if (ret != 0)
705     {
706         HMI_DEBUG("afb_event_push failed: %m");
707     }
708 }
709
710 void WindowManager::send_event(char const *evname, char const *label, char const *area,
711                      int x, int y, int w, int h)
712 {
713     HMI_DEBUG("%s: %s(%s, %s) x:%d y:%d w:%d h:%d",
714               __func__, evname, label, area, x, y, w, h);
715
716     json_object *j_rect = json_object_new_object();
717     json_object_object_add(j_rect, kKeyX, json_object_new_int(x));
718     json_object_object_add(j_rect, kKeyY, json_object_new_int(y));
719     json_object_object_add(j_rect, kKeyWidth, json_object_new_int(w));
720     json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
721
722     json_object *j = json_object_new_object();
723     json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
724     json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area));
725     json_object_object_add(j, kKeyDrawingRect, j_rect);
726
727     int ret = afb_event_push(this->map_afb_event[evname], j);
728     if (ret != 0)
729     {
730         HMI_DEBUG("afb_event_push failed: %m");
731     }
732 }
733
734 /**
735  * proxied events
736  */
737 void WindowManager::surface_created(uint32_t surface_id)
738 {
739     if(this->tmp_surface2app.count(surface_id) != 0)
740     {
741         string appid = this->tmp_surface2app[surface_id];
742         this->tmp_surface2app.erase(surface_id);
743         if(g_app_list.contains(appid))
744         {
745             auto client = g_app_list.lookUpClient(appid);
746             WMError ret = client->addSurface(surface_id);
747             HMI_INFO("Add surface %d to \"%s\"", surface_id, appid.c_str());
748             if(ret != WMError::SUCCESS)
749             {
750                 HMI_ERROR("Failed to add surface to client %s", client->appID().c_str());
751             }
752         }
753     }
754     else
755     {
756         HMI_NOTICE("Unknown surface %d", surface_id);
757     }
758     /* this->controller->get_surface_properties(surface_id, IVI_WM_PARAM_SIZE);
759
760     auto layer_id = this->layers.get_layer_id(surface_id);
761     if (!layer_id)
762     {
763         HMI_DEBUG("Newly created surfce %d is not associated with any layer!",
764                   surface_id);
765         return;
766     }
767
768     HMI_DEBUG("surface_id is %u, layer_id is %u", surface_id, *layer_id);
769
770     this->controller->layers[*layer_id]->add_surface(surface_id);
771     this->layout_commit(); */
772 }
773
774 void WindowManager::surface_removed(uint32_t surface_id)
775 {
776     HMI_DEBUG("Delete surface_id %u", surface_id);
777     this->id_alloc.remove_id(surface_id);
778     // this->layers.remove_surface(surface_id);
779     g_app_list.removeSurface(surface_id);
780 }
781
782 void WindowManager::surface_properties(unsigned surface_id, unsigned pid)
783 {
784     HMI_DEBUG("get surface properties");
785
786     // search pid from surfaceID
787     /*json_object *response;
788     afb_service_call_sync("afm-main", "runners", nullptr, &response);
789
790     // retrieve appid from pid from application manager
791     string appid = "";
792     if(response == nullptr)
793     {
794         HMI_ERROR("No runners");
795     }
796     else
797     {
798         // check appid then add it to the client
799         HMI_INFO("Runners:%s", json_object_get_string(response));
800         int size = json_object_array_length(response);
801         for(int i = 0; i < size; i++)
802         {
803             json_object *j = json_object_array_get_idx(response, i);
804             const char* id = jh::getStringFromJson(j, "id");
805             int runid      = jh::getIntFromJson(j, "runid");
806             if(id && (runid > 0))
807             {
808                 if(runid == pid)
809                 {
810                     appid = id;
811                     break;
812                 }
813             }
814         }
815     }
816     json_object_put(response);
817
818     g_app_list.addFloatingSurface(appid, surface_id, pid);*/
819 }
820
821 void WindowManager::removeClient(const string &appid)
822 {
823     HMI_DEBUG("Remove clinet %s from list", appid.c_str());
824     auto client = g_app_list.lookUpClient(appid);
825     this->lc->terminateApp(client);
826     g_app_list.removeClient(appid);
827 }
828
829 void WindowManager::exceptionProcessForTransition()
830 {
831     unsigned req_num = g_app_list.currentRequestNumber();
832     HMI_SEQ_NOTICE(req_num, "Process exception handling for request. Remove current request %d", req_num);
833     g_app_list.removeRequest(req_num);
834     HMI_SEQ_NOTICE(g_app_list.currentRequestNumber(), "Process next request if exists");
835     this->processNextRequest();
836 }
837
838 void WindowManager::timerHandler()
839 {
840     unsigned req_num = g_app_list.currentRequestNumber();
841     HMI_SEQ_DEBUG(req_num, "Timer expired remove Request");
842     g_app_list.reqDump();
843     g_app_list.removeRequest(req_num);
844     this->processNextRequest();
845 }
846
847 void WindowManager::startTransitionWrapper(vector<WMAction> &actions)
848 {
849     WMError ret;
850     // req_num is guaranteed by Window Manager
851     unsigned req_num = g_app_list.currentRequestNumber();
852
853     if (actions.empty())
854     {
855         if (g_app_list.haveRequest())
856         {
857             HMI_SEQ_DEBUG(req_num, "There is no WMAction for this request");
858             goto proc_remove_request;
859         }
860         else
861         {
862             HMI_SEQ_DEBUG(req_num, "There is no request");
863             return;
864         }
865     }
866
867     for (auto &act : actions)
868     {
869         if ("" != act.role)
870         {
871             bool found;
872             auto const &surface_id = this->id_alloc.lookup(act.role.c_str());
873             if(surface_id == nullopt)
874             {
875                 goto proc_remove_request;
876             }
877             std::string appid = g_app_list.getAppID(*surface_id, &found);
878             if (!found)
879             {
880                 if (TaskVisible::INVISIBLE == act.visible)
881                 {
882                     // App is killed, so do not set this action
883                     continue;
884                 }
885                 else
886                 {
887                     HMI_SEQ_ERROR(req_num, "appid which is visible is not found");
888                     ret = WMError::FAIL;
889                     goto error;
890                 }
891             }
892             auto client = g_app_list.lookUpClient(appid);
893             act.req_num = req_num;
894             act.client = client;
895         }
896
897         ret = g_app_list.setAction(req_num, act);
898         if (ret != WMError::SUCCESS)
899         {
900             HMI_SEQ_ERROR(req_num, "Setting action is failed");
901             goto error;
902         }
903     }
904
905     HMI_SEQ_DEBUG(req_num, "Start transition.");
906     ret = this->startTransition(req_num);
907     if (ret != WMError::SUCCESS)
908     {
909         if (ret == WMError::NO_LAYOUT_CHANGE)
910         {
911             goto proc_remove_request;
912         }
913         else
914         {
915             HMI_SEQ_ERROR(req_num, "Transition state is failed");
916             goto error;
917         }
918     }
919
920     return;
921
922 error:
923     //this->emit_error()
924     HMI_SEQ_ERROR(req_num, errorDescription(ret));
925     this->pmw.undoState();
926
927 proc_remove_request:
928     g_app_list.removeRequest(req_num);
929     this->processNextRequest();
930 }
931
932 void WindowManager::processError(WMError error)
933 {
934     unsigned req_num = g_app_list.currentRequestNumber();
935
936     //this->emit_error()
937     HMI_SEQ_ERROR(req_num, errorDescription(error));
938     g_app_list.removeRequest(req_num);
939     this->processNextRequest();
940 }
941
942 /*
943  ******* Private Functions *******
944  */
945
946 /**
947  * init_layers()
948  */
949 int WindowManager::init_layers()
950 {
951     /* if (!this->controller)
952     {
953         HMI_ERROR("ivi_controller global not available");
954         return -1;
955     }
956
957     if (this->outputs.empty())
958     {
959         HMI_ERROR("no output was set up!");
960         return -1;
961     }
962
963     auto &c = this->controller;
964
965     auto &o = this->outputs.front();
966     auto &s = c->screens.begin()->second;
967     auto &layers = c->layers;
968
969     // Write output dimensions to ivi controller...
970     c->output_size = compositor::size{uint32_t(o->width), uint32_t(o->height)};
971     c->physical_size = compositor::size{uint32_t(o->physical_width),
972                                         uint32_t(o->physical_height)};
973
974
975     HMI_DEBUG("SCALING: screen (%dx%d), physical (%dx%d)",
976               o->width, o->height, o->physical_width, o->physical_height);
977
978     // this->layers.loadAreaDb();
979
980     const compositor::rect css_bg = this->layers.getAreaSize("fullscreen");
981     rectangle dp_bg(o->width, o->height);
982
983     dp_bg.set_aspect(static_cast<double>(css_bg.w) / css_bg.h);
984     dp_bg.fit(o->width, o->height);
985     dp_bg.center(o->width, o->height);
986     HMI_DEBUG("SCALING: CSS BG(%dx%d) -> DDP %dx%d,(%dx%d)",
987               css_bg.w, css_bg.h, dp_bg.left(), dp_bg.top(), dp_bg.width(), dp_bg.height());
988
989     // Clear scene
990     // layers.clear();
991
992     // Clear screen
993     // s->clear();
994
995     // Quick and dirty setup of layers
996     for (auto const &i : this->layers.mapping)
997     {
998         c->layer_create(i.second.layer_id, dp_bg.width(), dp_bg.height());
999         auto &l = layers[i.second.layer_id];
1000         l->set_destination_rectangle(dp_bg.left(), dp_bg.top(), dp_bg.width(), dp_bg.height());
1001         l->set_visibility(1);
1002         HMI_DEBUG("Setting up layer %s (%d) for surface role match \"%s\"",
1003                   i.second.name.c_str(), i.second.layer_id, i.second.role.c_str());
1004     }
1005
1006     // Add layers to screen
1007     s->set_render_order(this->layers.layers);
1008
1009     this->layout_commit();
1010
1011     c->scale = static_cast<double>(dp_bg.height()) / css_bg.h;
1012     this->layers.setupArea(c->scale);
1013  */
1014     return 0;
1015 }
1016
1017 void WindowManager::surface_set_layout(int surface_id, const string& area)
1018 {
1019     /* if (!this->controller->surface_exists(surface_id))
1020     {
1021         HMI_ERROR("Surface %d does not exist", surface_id);
1022         return;
1023     }
1024
1025     auto o_layer_id = this->layers.get_layer_id(surface_id);
1026
1027     if (!o_layer_id)
1028     {
1029         HMI_ERROR("Surface %d is not associated with any layer!", surface_id);
1030         return;
1031     }
1032
1033     uint32_t layer_id = *o_layer_id;
1034
1035     auto const &layer = this->layers.get_layer(layer_id);
1036     auto rect = this->layers.getAreaSize(area);
1037     HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "%s : x:%d y:%d w:%d h:%d", area.c_str(),
1038                     rect.x, rect.y, rect.w, rect.h);
1039     auto &s = this->controller->surfaces[surface_id];
1040
1041     int x = rect.x;
1042     int y = rect.y;
1043     int w = rect.w;
1044     int h = rect.h;
1045
1046     HMI_DEBUG("surface_set_layout for surface %u on layer %u", surface_id,
1047               layer_id);
1048
1049     // set destination to the display rectangle
1050     s->set_destination_rectangle(x, y, w, h);
1051
1052     // update area information
1053     this->area_info[surface_id].x = x;
1054     this->area_info[surface_id].y = y;
1055     this->area_info[surface_id].w = w;
1056     this->area_info[surface_id].h = h;
1057
1058     HMI_DEBUG("Surface %u now on layer %u with rect { %d, %d, %d, %d }",
1059               surface_id, layer_id, x, y, w, h); */
1060 }
1061
1062 void WindowManager::layout_commit()
1063 {
1064 /*     this->controller->commit_changes();
1065     this->display->flush(); */
1066 }
1067
1068 void WindowManager::emit_activated(char const *label)
1069 {
1070     this->send_event(kListEventName[Event_Active], label);
1071 }
1072
1073 void WindowManager::emit_deactivated(char const *label)
1074 {
1075     this->send_event(kListEventName[Event_Inactive], label);
1076 }
1077
1078 void WindowManager::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h)
1079 {
1080     this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
1081 }
1082
1083 void WindowManager::emit_syncdraw(const string &role, const string &area)
1084 {
1085     rect rect = this->lc->getAreaSize(area);
1086     this->send_event(kListEventName[Event_SyncDraw],
1087         role.c_str(), area.c_str(), rect.x, rect.y, rect.w, rect.h);
1088 }
1089
1090 void WindowManager::emit_flushdraw(char const *label)
1091 {
1092     this->send_event(kListEventName[Event_FlushDraw], label);
1093 }
1094
1095 void WindowManager::emit_visible(char const *label, bool is_visible)
1096 {
1097     this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
1098 }
1099
1100 void WindowManager::emit_invisible(char const *label)
1101 {
1102     return emit_visible(label, false);
1103 }
1104
1105 void WindowManager::emit_visible(char const *label) { return emit_visible(label, true); }
1106
1107 void WindowManager::activate(int id)
1108 {
1109     /* auto ip = this->controller->sprops.find(id);
1110     if (ip != this->controller->sprops.end())
1111     {
1112         this->controller->surfaces[id]->set_visibility(1);
1113         */
1114         char const *label =
1115             this->id_alloc.lookup(id).value_or("unknown-name").c_str();
1116
1117         /* // FOR CES DEMO >>>
1118         if ((0 == strcmp(label, "radio")) ||
1119             (0 == strcmp(label, "music")) ||
1120             (0 == strcmp(label, "video")) ||
1121             (0 == strcmp(label, "map")))
1122         {
1123             for (auto i = surface_bg.begin(); i != surface_bg.end(); ++i)
1124             {
1125                 if (id == *i)
1126                 {
1127                     // Remove id
1128                     this->surface_bg.erase(i);
1129
1130                     // Remove from BG layer (999)
1131                     HMI_DEBUG("Remove %s(%d) from BG layer", label, id);
1132                     this->controller->layers[999]->remove_surface(id);
1133
1134                     // Add to FG layer (1001)
1135                     HMI_DEBUG("Add %s(%d) to FG layer", label, id);
1136                     this->controller->layers[1001]->add_surface(id);
1137
1138                     for (int j : this->surface_bg)
1139                     {
1140                         HMI_DEBUG("Stored id:%d", j);
1141                     }
1142                     break;
1143                 }
1144             }
1145         }
1146         // <<< FOR CES DEMO
1147
1148         this->layout_commit(); */
1149
1150         // TODO: application requests by old role,
1151         //       so convert role new to old for emitting event
1152         const char* old_role = this->rolenew2old[label].c_str();
1153
1154         this->emit_visible(old_role);
1155         this->emit_activated(old_role);
1156     // }
1157 }
1158
1159 void WindowManager::deactivate(int id)
1160 {
1161     /* auto ip = this->controller->sprops.find(id);
1162     if (ip != this->controller->sprops.end())
1163     {*/
1164         char const *label =
1165             this->id_alloc.lookup(id).value_or("unknown-name").c_str();
1166
1167         /*// FOR CES DEMO >>>
1168         if ((0 == strcmp(label, "radio")) ||
1169             (0 == strcmp(label, "music")) ||
1170             (0 == strcmp(label, "video")) ||
1171             (0 == strcmp(label, "map")))
1172         {
1173
1174             // Store id
1175             this->surface_bg.push_back(id);
1176
1177             // Remove from FG layer (1001)
1178             HMI_DEBUG("Remove %s(%d) from FG layer", label, id);
1179             this->controller->layers[1001]->remove_surface(id);
1180
1181             // Add to BG layer (999)
1182             HMI_DEBUG("Add %s(%d) to BG layer", label, id);
1183             this->controller->layers[999]->add_surface(id);
1184
1185             for (int j : surface_bg)
1186             {
1187                 HMI_DEBUG("Stored id:%d", j);
1188             }
1189         }
1190         else
1191         {
1192             this->controller->surfaces[id]->set_visibility(0);
1193         }
1194         // <<< FOR CES DEMO
1195
1196         this->layout_commit(); */
1197
1198         // TODO: application requests by old role,
1199         //       so convert role new to old for emitting event
1200         const char* old_role = this->rolenew2old[label].c_str();
1201
1202         this->emit_deactivated(old_role);
1203         this->emit_invisible(old_role);
1204     // }
1205 }
1206
1207 WMError WindowManager::setRequest(const string& appid, const string &role, const string &area,
1208                             Task task, unsigned* req_num)
1209 {
1210     if (!g_app_list.contains(appid))
1211     {
1212         return WMError::NOT_REGISTERED;
1213     }
1214
1215     auto client = g_app_list.lookUpClient(appid);
1216
1217     /*
1218      * Queueing Phase
1219      */
1220     unsigned current = g_app_list.currentRequestNumber();
1221     unsigned requested_num = g_app_list.getRequestNumber(appid);
1222     if (requested_num != 0)
1223     {
1224         HMI_SEQ_INFO(requested_num,
1225             "%s %s %s request is already queued", appid.c_str(), role.c_str(), area.c_str());
1226         return REQ_REJECTED;
1227     }
1228
1229     WMRequest req = WMRequest(appid, role, area, task);
1230     unsigned new_req = g_app_list.addRequest(req);
1231     *req_num = new_req;
1232     g_app_list.reqDump();
1233
1234     HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", appid.c_str(), role.c_str(), area.c_str());
1235
1236     return WMError::SUCCESS;
1237 }
1238
1239 WMError WindowManager::checkPolicy(unsigned req_num)
1240 {
1241     /*
1242     * Check Policy
1243     */
1244     // get current trigger
1245     bool found = false;
1246     WMError ret = WMError::LAYOUT_CHANGE_FAIL;
1247     auto trigger = g_app_list.getRequest(req_num, &found);
1248     if (!found)
1249     {
1250         ret = WMError::NO_ENTRY;
1251         return ret;
1252     }
1253     string req_area = trigger.area;
1254
1255     if (trigger.task == Task::TASK_ALLOCATE)
1256     {
1257         const char *msg = this->check_surface_exist(trigger.role.c_str());
1258
1259         if (msg)
1260         {
1261             HMI_SEQ_ERROR(req_num, msg);
1262             return ret;
1263         }
1264     }
1265
1266     // Input event data to PolicyManager
1267     if (0 > this->pmw.setInputEventData(trigger.task, trigger.role, trigger.area))
1268     {
1269         HMI_SEQ_ERROR(req_num, "Failed to set input event data to PolicyManager");
1270         return ret;
1271     }
1272
1273     // Execute state transition of PolicyManager
1274     if (0 > this->pmw.executeStateTransition())
1275     {
1276         HMI_SEQ_ERROR(req_num, "Failed to execute state transition of PolicyManager");
1277         return ret;
1278     }
1279
1280     ret = WMError::SUCCESS;
1281
1282     g_app_list.reqDump();
1283
1284     return ret;
1285 }
1286
1287 WMError WindowManager::startTransition(unsigned req_num)
1288 {
1289     bool sync_draw_happen = false;
1290     bool found = false;
1291     WMError ret = WMError::SUCCESS;
1292     auto actions = g_app_list.getActions(req_num, &found);
1293     if (!found)
1294     {
1295         ret = WMError::NO_ENTRY;
1296         HMI_SEQ_ERROR(req_num,
1297             "Window Manager bug :%s : Action is not set", errorDescription(ret));
1298         return ret;
1299     }
1300
1301     g_app_list.reqDump();
1302     for (const auto &action : actions)
1303     {
1304         if (action.visible == TaskVisible::VISIBLE)
1305         {
1306             sync_draw_happen = true;
1307
1308             // TODO: application requests by old role,
1309             //       so convert role new to old for emitting event
1310             string old_role = this->rolenew2old[action.role];
1311
1312             this->emit_syncdraw(old_role, action.area);
1313             /* TODO: emit event for app not subscriber
1314             if(g_app_list.contains(y.appid))
1315                 g_app_list.lookUpClient(y.appid)->emit_syncdraw(y.role, y.area); */
1316         }
1317     }
1318
1319     if (sync_draw_happen)
1320     {
1321         this->setTimer();
1322     }
1323     else
1324     {
1325         // deactivate only, no syncDraw
1326         // Make it deactivate here
1327         for (const auto &x : actions)
1328         {
1329             this->lc->visibilityChange(x);
1330             /* if (g_app_list.contains(x.appid))
1331             {
1332                 auto client = g_app_list.lookUpClient(x.appid);
1333                 //this->deactivate(client->surfaceID(x.role));
1334             } */
1335         }
1336         this->lc->renderLayers();
1337         ret = WMError::NO_LAYOUT_CHANGE;
1338     }
1339     return ret;
1340 }
1341
1342 WMError WindowManager::doEndDraw(unsigned req_num)
1343 {
1344     // get actions
1345     bool found;
1346     auto actions = g_app_list.getActions(req_num, &found);
1347     WMError ret = WMError::SUCCESS;
1348     if (!found)
1349     {
1350         ret = WMError::NO_ENTRY;
1351         return ret;
1352     }
1353
1354     HMI_SEQ_INFO(req_num, "do endDraw");
1355
1356     // layout change and make it visible
1357     for (const auto &act : actions)
1358     {
1359         if(act.visible != TaskVisible::NO_CHANGE)
1360         {
1361             // layout change
1362             ret = this->lc->layoutChange(act);
1363             if(ret != WMError::SUCCESS)
1364             {
1365                 HMI_SEQ_WARNING(req_num,
1366                     "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1367                 return ret;
1368             }
1369             ret = this->lc->visibilityChange(act);
1370             if (ret != WMError::SUCCESS)
1371             {
1372                 HMI_SEQ_WARNING(req_num,
1373                     "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1374                 return ret;
1375             }
1376             HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str());
1377             //this->lc_enddraw(act.role.c_str());
1378         }
1379     }
1380     this->lc->renderLayers();
1381
1382     HMI_SEQ_INFO(req_num, "emit flushDraw");
1383
1384     for(const auto &act_flush : actions)
1385     {
1386         if(act_flush.visible == TaskVisible::VISIBLE)
1387         {
1388             // TODO: application requests by old role,
1389             //       so convert role new to old for emitting event
1390             string old_role = this->rolenew2old[act_flush.role];
1391
1392             this->emit_flushdraw(old_role.c_str());
1393         }
1394     }
1395
1396     return ret;
1397 }
1398
1399 WMError WindowManager::layoutChange(const WMAction &action)
1400 {
1401     if (action.visible == TaskVisible::INVISIBLE)
1402     {
1403         // Visibility is not change -> no redraw is required
1404         return WMError::SUCCESS;
1405     }
1406     WMError ret = this->lc->layoutChange(action);
1407     /* auto client = g_app_list.lookUpClient(action.appid);
1408     unsigned surface = client->surfaceID(action.role);
1409     if (surface == 0)
1410     {
1411         HMI_SEQ_ERROR(g_app_list.currentRequestNumber(),
1412                       "client doesn't have surface with role(%s)", action.role.c_str());
1413         return WMError::NOT_REGISTERED;
1414     }
1415     // Layout Manager
1416     WMError ret = this->setSurfaceSize(surface, action.area); */
1417     return ret;
1418 }
1419
1420 WMError WindowManager::visibilityChange(const WMAction &action)
1421 {
1422     HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Change visibility");
1423     /* if(!g_app_list.contains(action.appid)){
1424         return WMError::NOT_REGISTERED;
1425     }
1426     auto client = g_app_list.lookUpClient(action.appid);
1427     unsigned surface = client->surfaceID(action.role);
1428     if(surface == 0)
1429     {
1430         HMI_SEQ_ERROR(g_app_list.currentRequestNumber(),
1431                       "client doesn't have surface with role(%s)", action.role.c_str());
1432         return WMError::NOT_REGISTERED;
1433     } */
1434     WMError ret = this->lc->visibilityChange(action);
1435
1436 /*     if (action.visible != TaskVisible::INVISIBLE)
1437     {
1438         this->activate(surface); // Layout Manager task
1439     }
1440     else
1441     {
1442         this->deactivate(surface); // Layout Manager task
1443     } */
1444     return ret;
1445 }
1446
1447 WMError WindowManager::setSurfaceSize(unsigned surface, const string &area)
1448 {
1449     this->surface_set_layout(surface, area);
1450
1451     return WMError::SUCCESS;
1452 }
1453
1454 void WindowManager::emitScreenUpdated(unsigned req_num)
1455 {
1456     // Get visible apps
1457     HMI_SEQ_DEBUG(req_num, "emit screen updated");
1458     bool found = false;
1459     auto actions = g_app_list.getActions(req_num, &found);
1460
1461     // create json object
1462     json_object *j = json_object_new_object();
1463     json_object *jarray = json_object_new_array();
1464
1465     for(const auto& action: actions)
1466     {
1467         if(action.visible != TaskVisible::INVISIBLE)
1468         {
1469             json_object_array_add(jarray, json_object_new_string(action.client->appID().c_str()));
1470         }
1471     }
1472     json_object_object_add(j, kKeyIds, jarray);
1473     HMI_SEQ_INFO(req_num, "Visible app: %s", json_object_get_string(j));
1474
1475     int ret = afb_event_push(
1476         this->map_afb_event[kListEventName[Event_ScreenUpdated]], j);
1477     if (ret != 0)
1478     {
1479         HMI_DEBUG("afb_event_push failed: %m");
1480     }
1481 }
1482
1483 void WindowManager::setTimer()
1484 {
1485     struct timespec ts;
1486     if (clock_gettime(CLOCK_BOOTTIME, &ts) != 0) {
1487         HMI_ERROR("Could't set time (clock_gettime() returns with error");
1488         return;
1489     }
1490
1491     HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Timer set activate");
1492     if (g_timer_ev_src == nullptr)
1493     {
1494         // firsttime set into sd_event
1495         int ret = sd_event_add_time(afb_daemon_get_event_loop(), &g_timer_ev_src,
1496             CLOCK_BOOTTIME, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL, 1, processTimerHandler, this);
1497         if (ret < 0)
1498         {
1499             HMI_ERROR("Could't set timer");
1500         }
1501     }
1502     else
1503     {
1504         // update timer limitation after second time
1505         sd_event_source_set_time(g_timer_ev_src, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL);
1506         sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT);
1507     }
1508 }
1509
1510 void WindowManager::stopTimer()
1511 {
1512     unsigned req_num = g_app_list.currentRequestNumber();
1513     HMI_SEQ_DEBUG(req_num, "Timer stop");
1514     int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF);
1515     if (rc < 0)
1516     {
1517         HMI_SEQ_ERROR(req_num, "Timer stop failed");
1518     }
1519 }
1520
1521 void WindowManager::processNextRequest()
1522 {
1523     g_app_list.next();
1524     g_app_list.reqDump();
1525     unsigned req_num = g_app_list.currentRequestNumber();
1526     if (g_app_list.haveRequest())
1527     {
1528         HMI_SEQ_DEBUG(req_num, "Process next request");
1529         WMError rc = checkPolicy(req_num);
1530         if (rc != WMError::SUCCESS)
1531         {
1532             HMI_SEQ_ERROR(req_num, errorDescription(rc));
1533         }
1534     }
1535     else
1536     {
1537         HMI_SEQ_DEBUG(req_num, "Nothing Request. Waiting Request");
1538     }
1539 }
1540
1541 const char* WindowManager::convertRoleOldToNew(char const *old_role)
1542 {
1543     const char *new_role = nullptr;
1544
1545     for (auto const &on : this->roleold2new)
1546     {
1547         std::regex regex = std::regex(on.first);
1548         if (std::regex_match(old_role, regex))
1549         {
1550             // role is old. So convert to new.
1551             new_role = on.second.c_str();
1552             break;
1553         }
1554     }
1555
1556     if (nullptr == new_role)
1557     {
1558         // role is new or fallback.
1559         new_role = old_role;
1560     }
1561
1562     HMI_DEBUG("old:%s -> new:%s", old_role, new_role);
1563
1564     return new_role;
1565 }
1566
1567 int WindowManager::loadOldRoleDb()
1568 {
1569     // Get afm application installed dir
1570     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1571     HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
1572
1573     string file_name;
1574     if (!afm_app_install_dir)
1575     {
1576         HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
1577     }
1578     else
1579     {
1580         file_name = string(afm_app_install_dir) + string("/etc/old_roles.db");
1581     }
1582
1583     // Load old_role.db
1584     json_object* json_obj;
1585     int ret = jh::inputJsonFilie(file_name.c_str(), &json_obj);
1586     if (0 > ret)
1587     {
1588         HMI_ERROR("Could not open old_role.db, so use default old_role information");
1589         json_obj = json_tokener_parse(kDefaultOldRoleDb);
1590     }
1591     HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
1592
1593     // Perse apps
1594     json_object* json_cfg;
1595     if (!json_object_object_get_ex(json_obj, "old_roles", &json_cfg))
1596     {
1597         HMI_ERROR("Parse Error!!");
1598         return -1;
1599     }
1600
1601     int len = json_object_array_length(json_cfg);
1602     HMI_DEBUG("json_cfg len:%d", len);
1603     HMI_DEBUG("json_cfg dump:%s", json_object_get_string(json_cfg));
1604
1605     for (int i=0; i<len; i++)
1606     {
1607         json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
1608
1609         const char* old_role = jh::getStringFromJson(json_tmp, "name");
1610         if (nullptr == old_role)
1611         {
1612             HMI_ERROR("Parse Error!!");
1613             return -1;
1614         }
1615
1616         const char* new_role = jh::getStringFromJson(json_tmp, "new");
1617         if (nullptr == new_role)
1618         {
1619             HMI_ERROR("Parse Error!!");
1620             return -1;
1621         }
1622
1623         this->roleold2new[old_role] = string(new_role);
1624     }
1625
1626     // Check
1627     for(auto itr = this->roleold2new.begin();
1628       itr != this->roleold2new.end(); ++itr)
1629     {
1630         HMI_DEBUG(">>> role old:%s new:%s",
1631                   itr->first.c_str(), itr->second.c_str());
1632     }
1633
1634     // Release json_object
1635     json_object_put(json_obj);
1636
1637     return 0;
1638 }
1639
1640 const char *WindowManager::check_surface_exist(const char *drawing_name)
1641 {
1642     auto const &surface_id = this->id_alloc.lookup(string(drawing_name));
1643     if (!surface_id)
1644     {
1645         return "Surface does not exist";
1646     }
1647
1648     /* if (!this->controller->surface_exists(*surface_id))
1649     {
1650         return "Surface does not exist in controller!";
1651     } */
1652
1653     /* auto layer_id = this->layers.get_layer_id(*surface_id);
1654
1655     if (!layer_id)
1656     {
1657         return "Surface is not on any layer!";
1658     } */
1659
1660     HMI_DEBUG("surface %d is detected", *surface_id);
1661     return nullptr;
1662 }
1663
1664 const char* WindowManager::kDefaultOldRoleDb = "{ \
1665     \"old_roles\": [ \
1666         { \
1667             \"name\": \"HomeScreen\", \
1668             \"new\": \"homescreen\" \
1669         }, \
1670         { \
1671             \"name\": \"Music\", \
1672             \"new\": \"music\" \
1673         }, \
1674         { \
1675             \"name\": \"MediaPlayer\", \
1676             \"new\": \"music\" \
1677         }, \
1678         { \
1679             \"name\": \"Video\", \
1680             \"new\": \"video\" \
1681         }, \
1682         { \
1683             \"name\": \"VideoPlayer\", \
1684             \"new\": \"video\" \
1685         }, \
1686         { \
1687             \"name\": \"WebBrowser\", \
1688             \"new\": \"browser\" \
1689         }, \
1690         { \
1691             \"name\": \"Radio\", \
1692             \"new\": \"radio\" \
1693         }, \
1694         { \
1695             \"name\": \"Phone\", \
1696             \"new\": \"phone\" \
1697         }, \
1698         { \
1699             \"name\": \"Navigation\", \
1700             \"new\": \"map\" \
1701         }, \
1702         { \
1703             \"name\": \"HVAC\", \
1704             \"new\": \"hvac\" \
1705         }, \
1706         { \
1707             \"name\": \"Settings\", \
1708             \"new\": \"settings\" \
1709         }, \
1710         { \
1711             \"name\": \"Dashboard\", \
1712             \"new\": \"dashboard\" \
1713         }, \
1714         { \
1715             \"name\": \"POI\", \
1716             \"new\": \"poi\" \
1717         }, \
1718         { \
1719             \"name\": \"Mixer\", \
1720             \"new\": \"mixer\" \
1721         }, \
1722         { \
1723             \"name\": \"Restriction\", \
1724             \"new\": \"restriction\" \
1725         }, \
1726         { \
1727             \"name\": \"^OnScreen.*\", \
1728             \"new\": \"on_screen\" \
1729         } \
1730     ] \
1731 }";
1732
1733 /**
1734  * controller_hooks
1735  */
1736 void controller_hooks::surface_created(uint32_t surface_id)
1737 {
1738     this->wmgr->surface_created(surface_id);
1739 }
1740
1741 void controller_hooks::surface_removed(uint32_t surface_id)
1742 {
1743     this->wmgr->surface_removed(surface_id);
1744 }
1745
1746 void controller_hooks::surface_visibility(uint32_t /*surface_id*/,
1747                                           uint32_t /*v*/) {}
1748
1749 void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/,
1750                                                      uint32_t /*x*/,
1751                                                      uint32_t /*y*/,
1752                                                      uint32_t /*w*/,
1753                                                      uint32_t /*h*/) {}
1754
1755 void controller_hooks::surface_properties(uint32_t surface_id, uint32_t pid)
1756 {
1757     this->wmgr->surface_properties(surface_id, pid);
1758 }
1759
1760 } // namespace wm