5b86af847d0b559947d7dc6814365dc9b5aaa1ac
[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_destination_rectangle(x, y, w, h);
742
743     // update area information
744     this->area_info[surface_id].x = x;
745     this->area_info[surface_id].y = y;
746     this->area_info[surface_id].w = w;
747     this->area_info[surface_id].h = h;
748
749     HMI_DEBUG("wm", "Surface %u now on layer %u with rect { %d, %d, %d, %d }",
750               surface_id, layer_id, x, y, w, h);
751 }
752
753 void WindowManager::layout_commit()
754 {
755     this->controller->commit_changes();
756     this->display->flush();
757 }
758
759 void WindowManager::emit_activated(char const *label)
760 {
761     this->send_event(kListEventName[Event_Active], label);
762 }
763
764 void WindowManager::emit_deactivated(char const *label)
765 {
766     this->send_event(kListEventName[Event_Inactive], label);
767 }
768
769 void WindowManager::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h)
770 {
771     this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
772 }
773
774 void WindowManager::emit_syncdraw(const std::string &role, const std::string &area)
775 {
776     compositor::rect rect = this->layers.getAreaSize(area);
777     this->send_event(kListEventName[Event_SyncDraw],
778         role.c_str(), area.c_str(), rect.x, rect.y, rect.w, rect.h);
779 }
780
781 void WindowManager::emit_flushdraw(char const *label)
782 {
783     this->send_event(kListEventName[Event_FlushDraw], label);
784 }
785
786 void WindowManager::emit_visible(char const *label, bool is_visible)
787 {
788     this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
789 }
790
791 void WindowManager::emit_invisible(char const *label)
792 {
793     return emit_visible(label, false);
794 }
795
796 void WindowManager::emit_visible(char const *label) { return emit_visible(label, true); }
797
798 void WindowManager::activate(int id)
799 {
800     auto ip = this->controller->sprops.find(id);
801     if (ip != this->controller->sprops.end())
802     {
803         this->controller->surfaces[id]->set_visibility(1);
804         char const *label =
805             this->lookup_name(id).value_or("unknown-name").c_str();
806
807          // FOR CES DEMO >>>
808         if ((0 == strcmp(label, "radio")) ||
809             (0 == strcmp(label, "music")) ||
810             (0 == strcmp(label, "video")) ||
811             (0 == strcmp(label, "map")))
812         {
813             for (auto i = surface_bg.begin(); i != surface_bg.end(); ++i)
814             {
815                 if (id == *i)
816                 {
817                     // Remove id
818                     this->surface_bg.erase(i);
819
820                     // Remove from BG layer (999)
821                     HMI_DEBUG("wm", "Remove %s(%d) from BG layer", label, id);
822                     this->controller->layers[999]->remove_surface(id);
823
824                     // Add to FG layer (1001)
825                     HMI_DEBUG("wm", "Add %s(%d) to FG layer", label, id);
826                     this->controller->layers[1001]->add_surface(id);
827
828                     for (int j : this->surface_bg)
829                     {
830                         HMI_DEBUG("wm", "Stored id:%d", j);
831                     }
832                     break;
833                 }
834             }
835         }
836         // <<< FOR CES DEMO
837
838         this->layout_commit();
839
840         // TODO: application requests by old role,
841         //       so convert role new to old for emitting event
842         const char* old_role = this->rolenew2old[label].c_str();
843
844         this->emit_visible(old_role);
845         this->emit_activated(old_role);
846     }
847 }
848
849 void WindowManager::deactivate(int id)
850 {
851     auto ip = this->controller->sprops.find(id);
852     if (ip != this->controller->sprops.end())
853     {
854         char const *label =
855             this->lookup_name(id).value_or("unknown-name").c_str();
856
857         // FOR CES DEMO >>>
858         if ((0 == strcmp(label, "radio")) ||
859             (0 == strcmp(label, "music")) ||
860             (0 == strcmp(label, "video")) ||
861             (0 == strcmp(label, "map")))
862         {
863
864             // Store id
865             this->surface_bg.push_back(id);
866
867             // Remove from FG layer (1001)
868             HMI_DEBUG("wm", "Remove %s(%d) from FG layer", label, id);
869             this->controller->layers[1001]->remove_surface(id);
870
871             // Add to BG layer (999)
872             HMI_DEBUG("wm", "Add %s(%d) to BG layer", label, id);
873             this->controller->layers[999]->add_surface(id);
874
875             for (int j : surface_bg)
876             {
877                 HMI_DEBUG("wm", "Stored id:%d", j);
878             }
879         }
880         else
881         {
882             this->controller->surfaces[id]->set_visibility(0);
883         }
884         // <<< FOR CES DEMO
885
886         this->layout_commit();
887
888         // TODO: application requests by old role,
889         //       so convert role new to old for emitting event
890         const char* old_role = this->rolenew2old[label].c_str();
891
892         this->emit_deactivated(old_role);
893         this->emit_invisible(old_role);
894     }
895 }
896
897 WMError WindowManager::setRequest(const std::string& appid, const std::string &role, const std::string &area,
898                             Task task, unsigned* req_num)
899 {
900     if (!g_app_list.contains(appid))
901     {
902         return WMError::NOT_REGISTERED;
903     }
904
905     auto client = g_app_list.lookUpClient(appid);
906
907     /*
908      * Queueing Phase
909      */
910     unsigned current = g_app_list.currentRequestNumber();
911     unsigned requested_num = g_app_list.getRequestNumber(appid);
912     if (requested_num != 0)
913     {
914         HMI_SEQ_INFO(requested_num,
915             "%s %s %s request is already queued", appid.c_str(), role.c_str(), area.c_str());
916         return REQ_REJECTED;
917     }
918
919     WMRequest req = WMRequest(appid, role, area, task);
920     unsigned new_req = g_app_list.addRequest(req);
921     *req_num = new_req;
922     g_app_list.reqDump();
923
924     HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", appid.c_str(), role.c_str(), area.c_str());
925
926     return WMError::SUCCESS;
927 }
928
929 WMError WindowManager::doTransition(unsigned req_num)
930 {
931     HMI_SEQ_DEBUG(req_num, "check policy");
932     WMError ret = this->checkPolicy(req_num);
933     if (ret != WMError::SUCCESS)
934     {
935         return ret;
936     }
937     HMI_SEQ_DEBUG(req_num, "Start transition.");
938     ret = this->startTransition(req_num);
939     return ret;
940 }
941
942 WMError WindowManager::checkPolicy(unsigned req_num)
943 {
944     /*
945     * Check Policy
946     */
947     // get current trigger
948     bool found = false;
949     bool split = false;
950     WMError ret = WMError::LAYOUT_CHANGE_FAIL;
951     auto trigger = g_app_list.getRequest(req_num, &found);
952     if (!found)
953     {
954         ret = WMError::NO_ENTRY;
955         return ret;
956     }
957     std::string req_area = trigger.area;
958
959     // >>>> Compatible with current window manager until policy manager coming
960     if (trigger.task == Task::TASK_ALLOCATE)
961     {
962         HMI_SEQ_DEBUG(req_num, "Check split or not");
963         const char *msg = this->check_surface_exist(trigger.role.c_str());
964
965         if (msg)
966         {
967             HMI_SEQ_ERROR(req_num, msg);
968             ret = WMError::LAYOUT_CHANGE_FAIL;
969             return ret;
970         }
971
972         auto const &surface_id = this->lookup_id(trigger.role.c_str());
973         auto o_state = *this->layers.get_layout_state(*surface_id);
974         struct LayoutState &state = *o_state;
975
976         unsigned curernt_sid = state.main;
977         split = this->can_split(state, *surface_id);
978
979         if (split)
980         {
981             HMI_SEQ_DEBUG(req_num, "Split happens");
982             // Get current visible role
983             std::string add_role = this->lookup_name(state.main).value();
984             // Set next area
985             std::string add_area = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaMain);
986             // Change request area
987             req_area = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaSub);
988             HMI_SEQ_NOTICE(req_num, "Change request area from %s to %s, because split happens",
989                                 trigger.area.c_str(), req_area.c_str());
990             // set another action
991             std::string add_name = g_app_list.getAppID(curernt_sid, add_role, &found);
992             if (!found)
993             {
994                 HMI_SEQ_ERROR(req_num, "Couldn't widhdraw with surfaceID : %d", curernt_sid);
995                 ret = WMError::NOT_REGISTERED;
996                 return ret;
997             }
998             HMI_SEQ_INFO(req_num, "Additional split app %s, role: %s, area: %s",
999                          add_name.c_str(), add_role.c_str(), add_area.c_str());
1000             // Set split action
1001             bool end_draw_finished = false;
1002             WMAction split_action{
1003                 add_name,
1004                 add_role,
1005                 add_area,
1006                 TaskVisible::VISIBLE,
1007                 end_draw_finished};
1008             WMError ret = g_app_list.setAction(req_num, split_action);
1009             if (ret != WMError::SUCCESS)
1010             {
1011                 HMI_SEQ_ERROR(req_num, "Failed to set action");
1012                 return ret;
1013             }
1014             g_app_list.reqDump();
1015         }
1016     }
1017     else
1018     {
1019         HMI_SEQ_DEBUG(req_num, "split doesn't happen");
1020     }
1021
1022     // Set invisible task(Remove if policy manager finish)
1023     ret = this->setInvisibleTask(trigger.role, split);
1024     if(ret != WMError::SUCCESS)
1025     {
1026         HMI_SEQ_ERROR(req_num, "Failed to set invisible task: %s", errorDescription(ret));
1027         return ret;
1028     }
1029
1030     /*  get new status from Policy Manager */
1031     HMI_SEQ_NOTICE(req_num, "ATM, Policy manager does't exist, then set WMAction as is");
1032     if(trigger.role == "homescreen")
1033     {
1034         // TODO : Remove when Policy Manager completed
1035         HMI_SEQ_NOTICE(req_num, "Hack. This process will be removed. Change HomeScreen code!!");
1036         req_area = "fullscreen";
1037     }
1038     TaskVisible task_visible =
1039         (trigger.task == Task::TASK_ALLOCATE) ? TaskVisible::VISIBLE : TaskVisible::INVISIBLE;
1040
1041     ret = g_app_list.setAction(req_num, trigger.appid, trigger.role, req_area, task_visible);
1042     g_app_list.reqDump();
1043
1044     return ret;
1045 }
1046
1047 WMError WindowManager::startTransition(unsigned req_num)
1048 {
1049     bool sync_draw_happen = false;
1050     bool found = false;
1051     WMError ret = WMError::SUCCESS;
1052     auto actions = g_app_list.getActions(req_num, &found);
1053     if (!found)
1054     {
1055         ret = WMError::NO_ENTRY;
1056         HMI_SEQ_ERROR(req_num,
1057             "Window Manager bug :%s : Action is not set", errorDescription(ret));
1058         return ret;
1059     }
1060
1061     for (const auto &action : actions)
1062     {
1063         if (action.visible != TaskVisible::INVISIBLE)
1064         {
1065             sync_draw_happen = true;
1066
1067             // TODO: application requests by old role,
1068             //       so convert role new to old for emitting event
1069             std::string old_role = this->rolenew2old[action.role];
1070
1071             this->emit_syncdraw(old_role, action.area);
1072             /* TODO: emit event for app not subscriber
1073             if(g_app_list.contains(y.appid))
1074                 g_app_list.lookUpClient(y.appid)->emit_syncdraw(y.role, y.area); */
1075         }
1076     }
1077
1078     if (sync_draw_happen)
1079     {
1080         this->setTimer();
1081     }
1082     else
1083     {
1084         // deactivate only, no syncDraw
1085         // Make it deactivate here
1086         for (const auto &x : actions)
1087         {
1088             if (g_app_list.contains(x.appid))
1089             {
1090                 auto client = g_app_list.lookUpClient(x.appid);
1091                 this->deactivate(client->surfaceID(x.role));
1092             }
1093         }
1094         ret = NO_LAYOUT_CHANGE;
1095     }
1096     return ret;
1097 }
1098
1099 WMError WindowManager::setInvisibleTask(const std::string &role, bool split)
1100 {
1101     unsigned req_num = g_app_list.currentRequestNumber();
1102     HMI_SEQ_DEBUG(req_num, "set current visible app to invisible task");
1103     // This task is copied from original actiavete surface
1104     const char *drawing_name = this->rolenew2old[role].c_str();
1105     auto const &surface_id = this->lookup_id(role.c_str());
1106     auto layer_id = this->layers.get_layer_id(*surface_id);
1107     auto o_state = *this->layers.get_layout_state(*surface_id);
1108     struct LayoutState &state = *o_state;
1109     std::string add_name, add_role;
1110     std::string add_area = "";
1111     int surface;
1112     TaskVisible task_visible = TaskVisible::INVISIBLE;
1113     bool end_draw_finished = true;
1114     bool found = false;
1115
1116     for (auto const &l : this->layers.mapping)
1117     {
1118         if (l.second.layer_id <= *layer_id)
1119         {
1120             continue;
1121         }
1122         HMI_DEBUG("wm", "debug: main %d , sub : %d", l.second.state.main, l.second.state.sub);
1123         if (l.second.state.main != -1)
1124         {
1125             //this->deactivate(l.second.state.main);
1126             surface = l.second.state.main;
1127             add_role = *this->id_alloc.lookup(surface);
1128             add_name = g_app_list.getAppID(surface, add_role, &found);
1129             if(!found){
1130                 return WMError::NOT_REGISTERED;
1131             }
1132             HMI_SEQ_INFO(req_num, "Invisible %s", add_name.c_str());
1133             WMAction act{add_name, add_role, add_area, task_visible, end_draw_finished};
1134             g_app_list.setAction(req_num, act);
1135             l.second.state.main = -1;
1136         }
1137
1138         if (l.second.state.sub != -1)
1139         {
1140             //this->deactivate(l.second.state.sub);
1141             surface = l.second.state.sub;
1142             add_role = *this->id_alloc.lookup(surface);
1143             add_name = g_app_list.getAppID(surface, add_role, &found);
1144             if (!found)
1145             {
1146                 return WMError::NOT_REGISTERED;
1147             }
1148             HMI_SEQ_INFO(req_num, "Invisible %s", add_name.c_str());
1149             WMAction act{add_name, add_role, add_area, task_visible, end_draw_finished};
1150             g_app_list.setAction(req_num, act);
1151             l.second.state.sub = -1;
1152         }
1153     }
1154
1155     // change current state here, but this is hack
1156     auto layer = this->layers.get_layer(*layer_id);
1157
1158     if (state.main == -1)
1159     {
1160         HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
1161     }
1162     else
1163     {
1164         if (0 != strcmp(drawing_name, "HomeScreen"))
1165         {
1166             if (split)
1167             {
1168                 if (state.sub != *surface_id)
1169                 {
1170                     if (state.sub != -1)
1171                     {
1172                         //this->deactivate(state.sub);
1173                         WMAction deact_sub;
1174                         deact_sub.role =
1175                             std::move(*this->id_alloc.lookup(state.sub));
1176                         deact_sub.area = add_area;
1177                         deact_sub.appid = g_app_list.getAppID(state.sub, deact_sub.role, &found);
1178                         if (!found)
1179                         {
1180                             HMI_SEQ_ERROR(req_num, "App doesn't exist for role : %s",
1181                                             deact_sub.role.c_str());
1182                             return WMError::NOT_REGISTERED;
1183                         }
1184                         deact_sub.visible = task_visible;
1185                         deact_sub.end_draw_finished = end_draw_finished;
1186                         HMI_SEQ_DEBUG(req_num, "Set invisible task for %s", deact_sub.appid.c_str());
1187                         g_app_list.setAction(req_num, deact_sub);
1188                     }
1189                 }
1190                 //state = LayoutState{state.main, *surface_id};
1191             }
1192             else
1193             {
1194                 HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
1195
1196                 //this->surface_set_layout(*surface_id);
1197                 if (state.main != *surface_id)
1198                 {
1199                     // this->deactivate(state.main);
1200                     WMAction deact_main;
1201                     deact_main.role = std::move(*this->id_alloc.lookup(state.main));
1202                     ;
1203                     deact_main.area = add_area;
1204                     deact_main.appid = g_app_list.getAppID(state.main, deact_main.role, &found);
1205                     if (!found)
1206                     {
1207                         HMI_SEQ_DEBUG(req_num, "sub surface ddoesn't exist");
1208                         return WMError::NOT_REGISTERED;
1209                     }
1210                     deact_main.visible = task_visible;
1211                     deact_main.end_draw_finished = end_draw_finished;
1212                     HMI_SEQ_DEBUG(req_num, "sub surface doesn't exist");
1213                     g_app_list.setAction(req_num, deact_main);
1214                 }
1215                 if (state.sub != -1)
1216                 {
1217                     if (state.sub != *surface_id)
1218                     {
1219                         //this->deactivate(state.sub);
1220                         WMAction deact_sub;
1221                         deact_sub.role = std::move(*this->id_alloc.lookup(state.sub));
1222                         ;
1223                         deact_sub.area = add_area;
1224                         deact_sub.appid = g_app_list.getAppID(state.sub, deact_sub.role, &found);
1225                         if (!found)
1226                         {
1227                             HMI_SEQ_DEBUG(req_num, "sub surface ddoesn't exist");
1228                             return WMError::NOT_REGISTERED;
1229                         }
1230                         deact_sub.visible = task_visible;
1231                         deact_sub.end_draw_finished = end_draw_finished;
1232                         HMI_SEQ_DEBUG(req_num, "sub surface doesn't exist");
1233                         g_app_list.setAction(req_num, deact_sub);
1234                     }
1235                 }
1236                 //state = LayoutState{*surface_id};
1237             }
1238         }
1239     }
1240     return WMError::SUCCESS;
1241 }
1242
1243 WMError WindowManager::doEndDraw(unsigned req_num)
1244 {
1245     // get actions
1246     bool found;
1247     auto actions = g_app_list.getActions(req_num, &found);
1248     WMError ret = WMError::SUCCESS;
1249     if (!found)
1250     {
1251         ret = WMError::NO_ENTRY;
1252         return ret;
1253     }
1254
1255     HMI_SEQ_INFO(req_num, "do endDraw");
1256
1257     // layout change and make it visible
1258     for (const auto &act : actions)
1259     {
1260         // layout change
1261         if(!g_app_list.contains(act.appid)){
1262             ret = WMError::NOT_REGISTERED;
1263         }
1264         ret = this->layoutChange(act);
1265         if(ret != WMError::SUCCESS)
1266         {
1267             HMI_SEQ_WARNING(req_num,
1268                 "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1269             return ret;
1270         }
1271         ret = this->visibilityChange(act);
1272         if (ret != WMError::SUCCESS)
1273         {
1274             HMI_SEQ_WARNING(req_num,
1275                 "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1276             return ret;
1277         }
1278         HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str());
1279         //this->lm_enddraw(act.role.c_str());
1280     }
1281
1282     // Change current state
1283     this->changeCurrentState(req_num);
1284
1285     HMI_SEQ_INFO(req_num, "emit flushDraw");
1286
1287     for(const auto &act_flush : actions)
1288     {
1289         if(act_flush.visible != TaskVisible::INVISIBLE)
1290         {
1291             // TODO: application requests by old role,
1292             //       so convert role new to old for emitting event
1293             std::string old_role = this->rolenew2old[act_flush.role];
1294
1295             this->emit_flushdraw(old_role.c_str());
1296         }
1297     }
1298
1299     return ret;
1300 }
1301
1302 WMError WindowManager::layoutChange(const WMAction &action)
1303 {
1304     if (action.visible == TaskVisible::INVISIBLE)
1305     {
1306         // Visibility is not change -> no redraw is required
1307         return WMError::SUCCESS;
1308     }
1309     auto client = g_app_list.lookUpClient(action.appid);
1310     unsigned surface = client->surfaceID(action.role);
1311     if (surface == 0)
1312     {
1313         HMI_SEQ_ERROR(g_app_list.currentRequestNumber(),
1314                       "client doesn't have surface with role(%s)", action.role.c_str());
1315         return WMError::NOT_REGISTERED;
1316     }
1317     // Layout Manager
1318     WMError ret = this->setSurfaceSize(surface, action.area);
1319     return ret;
1320 }
1321
1322 WMError WindowManager::visibilityChange(const WMAction &action)
1323 {
1324     HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Change visibility");
1325     if(!g_app_list.contains(action.appid)){
1326         return WMError::NOT_REGISTERED;
1327     }
1328     auto client = g_app_list.lookUpClient(action.appid);
1329     unsigned surface = client->surfaceID(action.role);
1330     if(surface == 0)
1331     {
1332         HMI_SEQ_ERROR(g_app_list.currentRequestNumber(),
1333                       "client doesn't have surface with role(%s)", action.role.c_str());
1334         return WMError::NOT_REGISTERED;
1335     }
1336
1337     if (action.visible != TaskVisible::INVISIBLE)
1338     {
1339         this->activate(surface); // Layout Manager task
1340     }
1341     else
1342     {
1343         this->deactivate(surface); // Layout Manager task
1344     }
1345     return WMError::SUCCESS;
1346 }
1347
1348 WMError WindowManager::setSurfaceSize(unsigned surface, const std::string &area)
1349 {
1350     this->surface_set_layout(surface, area);
1351
1352     return WMError::SUCCESS;
1353 }
1354
1355 WMError WindowManager::changeCurrentState(unsigned req_num)
1356 {
1357     HMI_SEQ_DEBUG(req_num, "Change current layout state");
1358     bool trigger_found = false, action_found = false;
1359     auto trigger = g_app_list.getRequest(req_num, &trigger_found);
1360     auto actions = g_app_list.getActions(req_num, &action_found);
1361     if (!trigger_found || !action_found)
1362     {
1363         HMI_SEQ_ERROR(req_num, "Action not found");
1364         return WMError::LAYOUT_CHANGE_FAIL;
1365     }
1366
1367     // Layout state reset
1368     struct LayoutState reset_state{-1, -1};
1369     HMI_SEQ_DEBUG(req_num,"Reset layout state");
1370     for (const auto &action : actions)
1371     {
1372         if(!g_app_list.contains(action.appid)){
1373             return WMError::NOT_REGISTERED;
1374         }
1375         auto client = g_app_list.lookUpClient(action.appid);
1376         auto pCurState = *this->layers.get_layout_state((int)client->surfaceID(action.role));
1377         if(pCurState == nullptr)
1378         {
1379             HMI_SEQ_ERROR(req_num, "Counldn't find current status");
1380             continue;
1381         }
1382         pCurState->main = reset_state.main;
1383         pCurState->sub = reset_state.sub;
1384     }
1385
1386     HMI_SEQ_DEBUG(req_num, "Change state");
1387     for (const auto &action : actions)
1388     {
1389         auto client = g_app_list.lookUpClient(action.appid);
1390         auto pLayerCurState = *this->layers.get_layout_state((int)client->surfaceID(action.role));
1391         if (pLayerCurState == nullptr)
1392         {
1393             HMI_SEQ_ERROR(req_num, "Counldn't find current status");
1394             continue;
1395         }
1396         int surface = -1;
1397
1398         if (action.visible != TaskVisible::INVISIBLE)
1399         {
1400             surface = (int)client->surfaceID(action.role);
1401             HMI_SEQ_INFO(req_num, "Change %s surface : %d, state visible area : %s",
1402                             action.role.c_str(), surface, action.area.c_str());
1403             // visible == true -> layout changes
1404             if(action.area == "normal.full" || action.area == "split.main")
1405             {
1406                 pLayerCurState->main = surface;
1407             }
1408             else if (action.area == "split.sub")
1409             {
1410                 pLayerCurState->sub = surface;
1411             }
1412             else
1413             {
1414                 // normalfull
1415                 pLayerCurState->main = surface;
1416             }
1417         }
1418     }
1419
1420     return WMError::SUCCESS;
1421 }
1422
1423 void WindowManager::emitScreenUpdated(unsigned req_num)
1424 {
1425     // Get visible apps
1426     HMI_SEQ_DEBUG(req_num, "emit screen updated");
1427     bool found = false;
1428     auto actions = g_app_list.getActions(req_num, &found);
1429
1430     // create json object
1431     json_object *j = json_object_new_object();
1432     json_object *jarray = json_object_new_array();
1433
1434     for(const auto& action: actions)
1435     {
1436         if(action.visible != TaskVisible::INVISIBLE)
1437         {
1438             json_object_array_add(jarray, json_object_new_string(action.appid.c_str()));
1439         }
1440     }
1441     json_object_object_add(j, kKeyIds, jarray);
1442     HMI_SEQ_INFO(req_num, "Visible app: %s", json_object_get_string(j));
1443
1444     int ret = afb_event_push(
1445         this->map_afb_event[kListEventName[Event_ScreenUpdated]], j);
1446     if (ret != 0)
1447     {
1448         HMI_DEBUG("wm", "afb_event_push failed: %m");
1449     }
1450     json_object_put(jarray);
1451 }
1452
1453 void WindowManager::setTimer()
1454 {
1455     struct timespec ts;
1456     if (clock_gettime(CLOCK_BOOTTIME, &ts) != 0) {
1457         HMI_ERROR("wm", "Could't set time (clock_gettime() returns with error");
1458         return;
1459     }
1460
1461     HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Timer set activate");
1462     if (g_timer_ev_src == nullptr)
1463     {
1464         // firsttime set into sd_event
1465         int ret = sd_event_add_time(afb_daemon_get_event_loop(), &g_timer_ev_src,
1466             CLOCK_BOOTTIME, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL, 1, processTimerHandler, this);
1467         if (ret < 0)
1468         {
1469             HMI_ERROR("wm", "Could't set timer");
1470         }
1471     }
1472     else
1473     {
1474         // update timer limitation after second time
1475         sd_event_source_set_time(g_timer_ev_src, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL);
1476         sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT);
1477     }
1478 }
1479
1480 void WindowManager::stopTimer()
1481 {
1482     unsigned req_num = g_app_list.currentRequestNumber();
1483     HMI_SEQ_DEBUG(req_num, "Timer stop");
1484     int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF);
1485     if (rc < 0)
1486     {
1487         HMI_SEQ_ERROR(req_num, "Timer stop failed");
1488     }
1489 }
1490
1491 void WindowManager::processNextRequest()
1492 {
1493     g_app_list.next();
1494     g_app_list.reqDump();
1495     unsigned req_num = g_app_list.currentRequestNumber();
1496     if (g_app_list.haveRequest())
1497     {
1498         HMI_SEQ_DEBUG(req_num, "Process next request");
1499         WMError rc = doTransition(req_num);
1500         if (rc != WMError::SUCCESS)
1501         {
1502             HMI_SEQ_ERROR(req_num, errorDescription(rc));
1503         }
1504     }
1505     else
1506     {
1507         HMI_SEQ_DEBUG(req_num, "Nothing Request. Waiting Request");
1508     }
1509 }
1510
1511 const char* WindowManager::convertRoleOldToNew(char const *old_role)
1512 {
1513     const char *new_role = nullptr;
1514
1515     for (auto const &on : this->roleold2new)
1516     {
1517         std::regex regex = std::regex(on.first);
1518         if (std::regex_match(old_role, regex))
1519         {
1520             // role is old. So convert to new.
1521             new_role = on.second.c_str();
1522             break;
1523         }
1524     }
1525
1526     if (nullptr == new_role)
1527     {
1528         // role is new or fallback.
1529         new_role = old_role;
1530     }
1531
1532     HMI_DEBUG("wm", "old:%s -> new:%s", old_role, new_role);
1533
1534     return new_role;
1535 }
1536
1537 int WindowManager::loadOldRoleDb()
1538 {
1539     // Get afm application installed dir
1540     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1541     HMI_DEBUG("wm", "afm_app_install_dir:%s", afm_app_install_dir);
1542
1543     std::string file_name;
1544     if (!afm_app_install_dir)
1545     {
1546         HMI_ERROR("wm", "AFM_APP_INSTALL_DIR is not defined");
1547     }
1548     else
1549     {
1550         file_name = std::string(afm_app_install_dir) + std::string("/etc/old_roles.db");
1551     }
1552
1553     // Load old_role.db
1554     json_object* json_obj;
1555     int ret = jh::inputJsonFilie(file_name.c_str(), &json_obj);
1556     if (0 > ret)
1557     {
1558         HMI_ERROR("wm", "Could not open old_role.db, so use default old_role information");
1559         json_obj = json_tokener_parse(kDefaultOldRoleDb);
1560     }
1561     HMI_DEBUG("wm", "json_obj dump:%s", json_object_get_string(json_obj));
1562
1563     // Perse apps
1564     json_object* json_cfg;
1565     if (!json_object_object_get_ex(json_obj, "old_roles", &json_cfg))
1566     {
1567         HMI_ERROR("wm", "Parse Error!!");
1568         return -1;
1569     }
1570
1571     int len = json_object_array_length(json_cfg);
1572     HMI_DEBUG("wm", "json_cfg len:%d", len);
1573     HMI_DEBUG("wm", "json_cfg dump:%s", json_object_get_string(json_cfg));
1574
1575     for (int i=0; i<len; i++)
1576     {
1577         json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
1578
1579         const char* old_role = jh::getStringFromJson(json_tmp, "name");
1580         if (nullptr == old_role)
1581         {
1582             HMI_ERROR("wm", "Parse Error!!");
1583             return -1;
1584         }
1585
1586         const char* new_role = jh::getStringFromJson(json_tmp, "new");
1587         if (nullptr == new_role)
1588         {
1589             HMI_ERROR("wm", "Parse Error!!");
1590             return -1;
1591         }
1592
1593         this->roleold2new[old_role] = std::string(new_role);
1594     }
1595
1596     // Check
1597     for(auto itr = this->roleold2new.begin();
1598       itr != this->roleold2new.end(); ++itr)
1599     {
1600         HMI_DEBUG("wm", ">>> role old:%s new:%s",
1601                   itr->first.c_str(), itr->second.c_str());
1602     }
1603
1604     // Release json_object
1605     json_object_put(json_obj);
1606
1607     return 0;
1608 }
1609
1610 const char *WindowManager::check_surface_exist(const char *drawing_name)
1611 {
1612     auto const &surface_id = this->lookup_id(drawing_name);
1613     if (!surface_id)
1614     {
1615         return "Surface does not exist";
1616     }
1617
1618     if (!this->controller->surface_exists(*surface_id))
1619     {
1620         return "Surface does not exist in controller!";
1621     }
1622
1623     auto layer_id = this->layers.get_layer_id(*surface_id);
1624
1625     if (!layer_id)
1626     {
1627         return "Surface is not on any layer!";
1628     }
1629
1630     auto o_state = *this->layers.get_layout_state(*surface_id);
1631
1632     if (o_state == nullptr)
1633     {
1634         return "Could not find layer for surface";
1635     }
1636
1637     HMI_DEBUG("wm", "surface %d is detected", *surface_id);
1638     return nullptr;
1639 }
1640
1641 bool WindowManager::can_split(struct LayoutState const &state, int new_id)
1642 {
1643     if (state.main != -1 && state.main != new_id)
1644     {
1645         auto new_id_layer = this->layers.get_layer_id(new_id).value();
1646         auto current_id_layer = this->layers.get_layer_id(state.main).value();
1647
1648         // surfaces are on separate layers, don't bother.
1649         if (new_id_layer != current_id_layer)
1650         {
1651             return false;
1652         }
1653
1654         std::string const &new_id_str = this->lookup_name(new_id).value();
1655         std::string const &cur_id_str = this->lookup_name(state.main).value();
1656
1657         auto const &layer = this->layers.get_layer(new_id_layer);
1658
1659         HMI_DEBUG("wm", "layer info name: %s", layer->name.c_str());
1660
1661         if (layer->layouts.empty())
1662         {
1663             return false;
1664         }
1665
1666         for (auto i = layer->layouts.cbegin(); i != layer->layouts.cend(); i++)
1667         {
1668             HMI_DEBUG("wm", "%d main_match '%s'", new_id_layer, i->main_match.c_str());
1669             auto rem = std::regex(i->main_match);
1670             if (std::regex_match(cur_id_str, rem))
1671             {
1672                 // build the second one only if the first already matched
1673                 HMI_DEBUG("wm", "%d sub_match '%s'", new_id_layer, i->sub_match.c_str());
1674                 auto res = std::regex(i->sub_match);
1675                 if (std::regex_match(new_id_str, res))
1676                 {
1677                     HMI_DEBUG("wm", "layout matched!");
1678                     return true;
1679                 }
1680             }
1681         }
1682     }
1683
1684     return false;
1685 }
1686
1687 const char* WindowManager::kDefaultOldRoleDb = "{ \
1688     \"old_roles\": [ \
1689         { \
1690             \"name\": \"HomeScreen\", \
1691             \"new\": \"homescreen\" \
1692         }, \
1693         { \
1694             \"name\": \"Music\", \
1695             \"new\": \"music\" \
1696         }, \
1697         { \
1698             \"name\": \"MediaPlayer\", \
1699             \"new\": \"music\" \
1700         }, \
1701         { \
1702             \"name\": \"Video\", \
1703             \"new\": \"video\" \
1704         }, \
1705         { \
1706             \"name\": \"VideoPlayer\", \
1707             \"new\": \"video\" \
1708         }, \
1709         { \
1710             \"name\": \"WebBrowser\", \
1711             \"new\": \"browser\" \
1712         }, \
1713         { \
1714             \"name\": \"Radio\", \
1715             \"new\": \"radio\" \
1716         }, \
1717         { \
1718             \"name\": \"Phone\", \
1719             \"new\": \"phone\" \
1720         }, \
1721         { \
1722             \"name\": \"Navigation\", \
1723             \"new\": \"map\" \
1724         }, \
1725         { \
1726             \"name\": \"HVAC\", \
1727             \"new\": \"hvac\" \
1728         }, \
1729         { \
1730             \"name\": \"Settings\", \
1731             \"new\": \"settings\" \
1732         }, \
1733         { \
1734             \"name\": \"Dashboard\", \
1735             \"new\": \"dashboard\" \
1736         }, \
1737         { \
1738             \"name\": \"POI\", \
1739             \"new\": \"poi\" \
1740         }, \
1741         { \
1742             \"name\": \"Mixer\", \
1743             \"new\": \"mixer\" \
1744         }, \
1745         { \
1746             \"name\": \"Restriction\", \
1747             \"new\": \"restriction\" \
1748         }, \
1749         { \
1750             \"name\": \"^OnScreen.*\", \
1751             \"new\": \"on_screen\" \
1752         } \
1753     ] \
1754 }";
1755
1756 /**
1757  * controller_hooks
1758  */
1759 void controller_hooks::surface_created(uint32_t surface_id)
1760 {
1761     this->app->surface_created(surface_id);
1762 }
1763
1764 void controller_hooks::surface_removed(uint32_t surface_id)
1765 {
1766     this->app->surface_removed(surface_id);
1767 }
1768
1769 void controller_hooks::surface_visibility(uint32_t /*surface_id*/,
1770                                           uint32_t /*v*/) {}
1771
1772 void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/,
1773                                                      uint32_t /*x*/,
1774                                                      uint32_t /*y*/,
1775                                                      uint32_t /*w*/,
1776                                                      uint32_t /*h*/) {}
1777
1778 } // namespace wm