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