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