98ebcf14df71d7d1e99d10cd8e06e7f51a73ae30
[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     bool found = false;
1106     auto trigger = g_app_list.getRequest(req_num, &found);
1107     // I don't check found == true here because this is checked in caller.
1108     if(trigger.role == "homescreen")
1109     {
1110         HMI_SEQ_INFO(req_num, "In case of 'homescreen' visible, don't change app to invisible");
1111         return WMError::SUCCESS;
1112     }
1113
1114     // This task is copied from original actiavete surface
1115     const char *drawing_name = this->rolenew2old[role].c_str();
1116     auto const &surface_id = this->lookup_id(role.c_str());
1117     auto layer_id = this->layers.get_layer_id(*surface_id);
1118     auto o_state = *this->layers.get_layout_state(*surface_id);
1119     struct LayoutState &state = *o_state;
1120     std::string add_name, add_role;
1121     std::string add_area = "";
1122     int surface;
1123     TaskVisible task_visible = TaskVisible::INVISIBLE;
1124     bool end_draw_finished = true;
1125
1126     for (auto const &l : this->layers.mapping)
1127     {
1128         if (l.second.layer_id <= *layer_id)
1129         {
1130             continue;
1131         }
1132         HMI_DEBUG("wm", "debug: main %d , sub : %d", l.second.state.main, l.second.state.sub);
1133         if (l.second.state.main != -1)
1134         {
1135             //this->deactivate(l.second.state.main);
1136             surface = l.second.state.main;
1137             add_role = *this->id_alloc.lookup(surface);
1138             add_name = g_app_list.getAppID(surface, add_role, &found);
1139             if(!found){
1140                 return WMError::NOT_REGISTERED;
1141             }
1142             HMI_SEQ_INFO(req_num, "Invisible %s", add_name.c_str());
1143             WMAction act{add_name, add_role, add_area, task_visible, end_draw_finished};
1144             g_app_list.setAction(req_num, act);
1145             l.second.state.main = -1;
1146         }
1147
1148         if (l.second.state.sub != -1)
1149         {
1150             //this->deactivate(l.second.state.sub);
1151             surface = l.second.state.sub;
1152             add_role = *this->id_alloc.lookup(surface);
1153             add_name = g_app_list.getAppID(surface, add_role, &found);
1154             if (!found)
1155             {
1156                 return WMError::NOT_REGISTERED;
1157             }
1158             HMI_SEQ_INFO(req_num, "Invisible %s", add_name.c_str());
1159             WMAction act{add_name, add_role, add_area, task_visible, end_draw_finished};
1160             g_app_list.setAction(req_num, act);
1161             l.second.state.sub = -1;
1162         }
1163     }
1164
1165     // change current state here, but this is hack
1166     auto layer = this->layers.get_layer(*layer_id);
1167
1168     if (state.main == -1)
1169     {
1170         HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
1171     }
1172     else
1173     {
1174         if (0 != strcmp(drawing_name, "HomeScreen"))
1175         {
1176             if (split)
1177             {
1178                 if (state.sub != *surface_id)
1179                 {
1180                     if (state.sub != -1)
1181                     {
1182                         //this->deactivate(state.sub);
1183                         WMAction deact_sub;
1184                         deact_sub.role =
1185                             std::move(*this->id_alloc.lookup(state.sub));
1186                         deact_sub.area = add_area;
1187                         deact_sub.appid = g_app_list.getAppID(state.sub, deact_sub.role, &found);
1188                         if (!found)
1189                         {
1190                             HMI_SEQ_ERROR(req_num, "App doesn't exist for role : %s",
1191                                             deact_sub.role.c_str());
1192                             return WMError::NOT_REGISTERED;
1193                         }
1194                         deact_sub.visible = task_visible;
1195                         deact_sub.end_draw_finished = end_draw_finished;
1196                         HMI_SEQ_DEBUG(req_num, "Set invisible task for %s", deact_sub.appid.c_str());
1197                         g_app_list.setAction(req_num, deact_sub);
1198                     }
1199                 }
1200                 //state = LayoutState{state.main, *surface_id};
1201             }
1202             else
1203             {
1204                 HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
1205
1206                 //this->surface_set_layout(*surface_id);
1207                 if (state.main != *surface_id)
1208                 {
1209                     // this->deactivate(state.main);
1210                     WMAction deact_main;
1211                     deact_main.role = std::move(*this->id_alloc.lookup(state.main));
1212                     ;
1213                     deact_main.area = add_area;
1214                     deact_main.appid = g_app_list.getAppID(state.main, deact_main.role, &found);
1215                     if (!found)
1216                     {
1217                         HMI_SEQ_DEBUG(req_num, "sub surface ddoesn't exist");
1218                         return WMError::NOT_REGISTERED;
1219                     }
1220                     deact_main.visible = task_visible;
1221                     deact_main.end_draw_finished = end_draw_finished;
1222                     HMI_SEQ_DEBUG(req_num, "sub surface doesn't exist");
1223                     g_app_list.setAction(req_num, deact_main);
1224                 }
1225                 if (state.sub != -1)
1226                 {
1227                     if (state.sub != *surface_id)
1228                     {
1229                         //this->deactivate(state.sub);
1230                         WMAction deact_sub;
1231                         deact_sub.role = std::move(*this->id_alloc.lookup(state.sub));
1232                         ;
1233                         deact_sub.area = add_area;
1234                         deact_sub.appid = g_app_list.getAppID(state.sub, deact_sub.role, &found);
1235                         if (!found)
1236                         {
1237                             HMI_SEQ_DEBUG(req_num, "sub surface ddoesn't exist");
1238                             return WMError::NOT_REGISTERED;
1239                         }
1240                         deact_sub.visible = task_visible;
1241                         deact_sub.end_draw_finished = end_draw_finished;
1242                         HMI_SEQ_DEBUG(req_num, "sub surface doesn't exist");
1243                         g_app_list.setAction(req_num, deact_sub);
1244                     }
1245                 }
1246                 //state = LayoutState{*surface_id};
1247             }
1248         }
1249     }
1250     return WMError::SUCCESS;
1251 }
1252
1253 WMError WindowManager::doEndDraw(unsigned req_num)
1254 {
1255     // get actions
1256     bool found;
1257     auto actions = g_app_list.getActions(req_num, &found);
1258     WMError ret = WMError::SUCCESS;
1259     if (!found)
1260     {
1261         ret = WMError::NO_ENTRY;
1262         return ret;
1263     }
1264
1265     HMI_SEQ_INFO(req_num, "do endDraw");
1266
1267     // layout change and make it visible
1268     for (const auto &act : actions)
1269     {
1270         // layout change
1271         if(!g_app_list.contains(act.appid)){
1272             ret = WMError::NOT_REGISTERED;
1273         }
1274         ret = this->layoutChange(act);
1275         if(ret != WMError::SUCCESS)
1276         {
1277             HMI_SEQ_WARNING(req_num,
1278                 "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1279             return ret;
1280         }
1281         ret = this->visibilityChange(act);
1282         if (ret != WMError::SUCCESS)
1283         {
1284             HMI_SEQ_WARNING(req_num,
1285                 "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1286             return ret;
1287         }
1288         HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str());
1289         //this->lm_enddraw(act.role.c_str());
1290     }
1291
1292     // Change current state
1293     this->changeCurrentState(req_num);
1294
1295     HMI_SEQ_INFO(req_num, "emit flushDraw");
1296
1297     for(const auto &act_flush : actions)
1298     {
1299         if(act_flush.visible != TaskVisible::INVISIBLE)
1300         {
1301             // TODO: application requests by old role,
1302             //       so convert role new to old for emitting event
1303             std::string old_role = this->rolenew2old[act_flush.role];
1304
1305             this->emit_flushdraw(old_role.c_str());
1306         }
1307     }
1308
1309     return ret;
1310 }
1311
1312 WMError WindowManager::layoutChange(const WMAction &action)
1313 {
1314     if (action.visible == TaskVisible::INVISIBLE)
1315     {
1316         // Visibility is not change -> no redraw is required
1317         return WMError::SUCCESS;
1318     }
1319     auto client = g_app_list.lookUpClient(action.appid);
1320     unsigned surface = client->surfaceID(action.role);
1321     if (surface == 0)
1322     {
1323         HMI_SEQ_ERROR(g_app_list.currentRequestNumber(),
1324                       "client doesn't have surface with role(%s)", action.role.c_str());
1325         return WMError::NOT_REGISTERED;
1326     }
1327     // Layout Manager
1328     WMError ret = this->setSurfaceSize(surface, action.area);
1329     return ret;
1330 }
1331
1332 WMError WindowManager::visibilityChange(const WMAction &action)
1333 {
1334     HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Change visibility");
1335     if(!g_app_list.contains(action.appid)){
1336         return WMError::NOT_REGISTERED;
1337     }
1338     auto client = g_app_list.lookUpClient(action.appid);
1339     unsigned surface = client->surfaceID(action.role);
1340     if(surface == 0)
1341     {
1342         HMI_SEQ_ERROR(g_app_list.currentRequestNumber(),
1343                       "client doesn't have surface with role(%s)", action.role.c_str());
1344         return WMError::NOT_REGISTERED;
1345     }
1346
1347     if (action.visible != TaskVisible::INVISIBLE)
1348     {
1349         this->activate(surface); // Layout Manager task
1350     }
1351     else
1352     {
1353         this->deactivate(surface); // Layout Manager task
1354     }
1355     return WMError::SUCCESS;
1356 }
1357
1358 WMError WindowManager::setSurfaceSize(unsigned surface, const std::string &area)
1359 {
1360     this->surface_set_layout(surface, area);
1361
1362     return WMError::SUCCESS;
1363 }
1364
1365 WMError WindowManager::changeCurrentState(unsigned req_num)
1366 {
1367     HMI_SEQ_DEBUG(req_num, "Change current layout state");
1368     bool trigger_found = false, action_found = false;
1369     auto trigger = g_app_list.getRequest(req_num, &trigger_found);
1370     auto actions = g_app_list.getActions(req_num, &action_found);
1371     if (!trigger_found || !action_found)
1372     {
1373         HMI_SEQ_ERROR(req_num, "Action not found");
1374         return WMError::LAYOUT_CHANGE_FAIL;
1375     }
1376
1377     // Layout state reset
1378     struct LayoutState reset_state{-1, -1};
1379     HMI_SEQ_DEBUG(req_num,"Reset layout state");
1380     for (const auto &action : actions)
1381     {
1382         if(!g_app_list.contains(action.appid)){
1383             return WMError::NOT_REGISTERED;
1384         }
1385         auto client = g_app_list.lookUpClient(action.appid);
1386         auto pCurState = *this->layers.get_layout_state((int)client->surfaceID(action.role));
1387         if(pCurState == nullptr)
1388         {
1389             HMI_SEQ_ERROR(req_num, "Counldn't find current status");
1390             continue;
1391         }
1392         pCurState->main = reset_state.main;
1393         pCurState->sub = reset_state.sub;
1394     }
1395
1396     HMI_SEQ_DEBUG(req_num, "Change state");
1397     for (const auto &action : actions)
1398     {
1399         auto client = g_app_list.lookUpClient(action.appid);
1400         auto pLayerCurState = *this->layers.get_layout_state((int)client->surfaceID(action.role));
1401         if (pLayerCurState == nullptr)
1402         {
1403             HMI_SEQ_ERROR(req_num, "Counldn't find current status");
1404             continue;
1405         }
1406         int surface = -1;
1407
1408         if (action.visible != TaskVisible::INVISIBLE)
1409         {
1410             surface = (int)client->surfaceID(action.role);
1411             HMI_SEQ_INFO(req_num, "Change %s surface : %d, state visible area : %s",
1412                             action.role.c_str(), surface, action.area.c_str());
1413             // visible == true -> layout changes
1414             if(action.area == "normal.full" || action.area == "split.main")
1415             {
1416                 pLayerCurState->main = surface;
1417             }
1418             else if (action.area == "split.sub")
1419             {
1420                 pLayerCurState->sub = surface;
1421             }
1422             else
1423             {
1424                 // normalfull
1425                 pLayerCurState->main = surface;
1426             }
1427         }
1428     }
1429
1430     return WMError::SUCCESS;
1431 }
1432
1433 void WindowManager::emitScreenUpdated(unsigned req_num)
1434 {
1435     // Get visible apps
1436     HMI_SEQ_DEBUG(req_num, "emit screen updated");
1437     bool found = false;
1438     auto actions = g_app_list.getActions(req_num, &found);
1439
1440     // create json object
1441     json_object *j = json_object_new_object();
1442     json_object *jarray = json_object_new_array();
1443
1444     for(const auto& action: actions)
1445     {
1446         if(action.visible != TaskVisible::INVISIBLE)
1447         {
1448             json_object_array_add(jarray, json_object_new_string(action.appid.c_str()));
1449         }
1450     }
1451     json_object_object_add(j, kKeyIds, jarray);
1452     HMI_SEQ_INFO(req_num, "Visible app: %s", json_object_get_string(j));
1453
1454     int ret = afb_event_push(
1455         this->map_afb_event[kListEventName[Event_ScreenUpdated]], j);
1456     if (ret != 0)
1457     {
1458         HMI_DEBUG("wm", "afb_event_push failed: %m");
1459     }
1460 }
1461
1462 void WindowManager::setTimer()
1463 {
1464     struct timespec ts;
1465     if (clock_gettime(CLOCK_BOOTTIME, &ts) != 0) {
1466         HMI_ERROR("wm", "Could't set time (clock_gettime() returns with error");
1467         return;
1468     }
1469
1470     HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Timer set activate");
1471     if (g_timer_ev_src == nullptr)
1472     {
1473         // firsttime set into sd_event
1474         int ret = sd_event_add_time(afb_daemon_get_event_loop(), &g_timer_ev_src,
1475             CLOCK_BOOTTIME, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL, 1, processTimerHandler, this);
1476         if (ret < 0)
1477         {
1478             HMI_ERROR("wm", "Could't set timer");
1479         }
1480     }
1481     else
1482     {
1483         // update timer limitation after second time
1484         sd_event_source_set_time(g_timer_ev_src, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL);
1485         sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT);
1486     }
1487 }
1488
1489 void WindowManager::stopTimer()
1490 {
1491     unsigned req_num = g_app_list.currentRequestNumber();
1492     HMI_SEQ_DEBUG(req_num, "Timer stop");
1493     int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF);
1494     if (rc < 0)
1495     {
1496         HMI_SEQ_ERROR(req_num, "Timer stop failed");
1497     }
1498 }
1499
1500 void WindowManager::processNextRequest()
1501 {
1502     g_app_list.next();
1503     g_app_list.reqDump();
1504     unsigned req_num = g_app_list.currentRequestNumber();
1505     if (g_app_list.haveRequest())
1506     {
1507         HMI_SEQ_DEBUG(req_num, "Process next request");
1508         WMError rc = doTransition(req_num);
1509         if (rc != WMError::SUCCESS)
1510         {
1511             HMI_SEQ_ERROR(req_num, errorDescription(rc));
1512         }
1513     }
1514     else
1515     {
1516         HMI_SEQ_DEBUG(req_num, "Nothing Request. Waiting Request");
1517     }
1518 }
1519
1520 const char* WindowManager::convertRoleOldToNew(char const *old_role)
1521 {
1522     const char *new_role = nullptr;
1523
1524     for (auto const &on : this->roleold2new)
1525     {
1526         std::regex regex = std::regex(on.first);
1527         if (std::regex_match(old_role, regex))
1528         {
1529             // role is old. So convert to new.
1530             new_role = on.second.c_str();
1531             break;
1532         }
1533     }
1534
1535     if (nullptr == new_role)
1536     {
1537         // role is new or fallback.
1538         new_role = old_role;
1539     }
1540
1541     HMI_DEBUG("wm", "old:%s -> new:%s", old_role, new_role);
1542
1543     return new_role;
1544 }
1545
1546 int WindowManager::loadOldRoleDb()
1547 {
1548     // Get afm application installed dir
1549     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1550     HMI_DEBUG("wm", "afm_app_install_dir:%s", afm_app_install_dir);
1551
1552     std::string file_name;
1553     if (!afm_app_install_dir)
1554     {
1555         HMI_ERROR("wm", "AFM_APP_INSTALL_DIR is not defined");
1556     }
1557     else
1558     {
1559         file_name = std::string(afm_app_install_dir) + std::string("/etc/old_roles.db");
1560     }
1561
1562     // Load old_role.db
1563     json_object* json_obj;
1564     int ret = jh::inputJsonFilie(file_name.c_str(), &json_obj);
1565     if (0 > ret)
1566     {
1567         HMI_ERROR("wm", "Could not open old_role.db, so use default old_role information");
1568         json_obj = json_tokener_parse(kDefaultOldRoleDb);
1569     }
1570     HMI_DEBUG("wm", "json_obj dump:%s", json_object_get_string(json_obj));
1571
1572     // Perse apps
1573     json_object* json_cfg;
1574     if (!json_object_object_get_ex(json_obj, "old_roles", &json_cfg))
1575     {
1576         HMI_ERROR("wm", "Parse Error!!");
1577         return -1;
1578     }
1579
1580     int len = json_object_array_length(json_cfg);
1581     HMI_DEBUG("wm", "json_cfg len:%d", len);
1582     HMI_DEBUG("wm", "json_cfg dump:%s", json_object_get_string(json_cfg));
1583
1584     for (int i=0; i<len; i++)
1585     {
1586         json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
1587
1588         const char* old_role = jh::getStringFromJson(json_tmp, "name");
1589         if (nullptr == old_role)
1590         {
1591             HMI_ERROR("wm", "Parse Error!!");
1592             return -1;
1593         }
1594
1595         const char* new_role = jh::getStringFromJson(json_tmp, "new");
1596         if (nullptr == new_role)
1597         {
1598             HMI_ERROR("wm", "Parse Error!!");
1599             return -1;
1600         }
1601
1602         this->roleold2new[old_role] = std::string(new_role);
1603     }
1604
1605     // Check
1606     for(auto itr = this->roleold2new.begin();
1607       itr != this->roleold2new.end(); ++itr)
1608     {
1609         HMI_DEBUG("wm", ">>> role old:%s new:%s",
1610                   itr->first.c_str(), itr->second.c_str());
1611     }
1612
1613     // Release json_object
1614     json_object_put(json_obj);
1615
1616     return 0;
1617 }
1618
1619 const char *WindowManager::check_surface_exist(const char *drawing_name)
1620 {
1621     auto const &surface_id = this->lookup_id(drawing_name);
1622     if (!surface_id)
1623     {
1624         return "Surface does not exist";
1625     }
1626
1627     if (!this->controller->surface_exists(*surface_id))
1628     {
1629         return "Surface does not exist in controller!";
1630     }
1631
1632     auto layer_id = this->layers.get_layer_id(*surface_id);
1633
1634     if (!layer_id)
1635     {
1636         return "Surface is not on any layer!";
1637     }
1638
1639     auto o_state = *this->layers.get_layout_state(*surface_id);
1640
1641     if (o_state == nullptr)
1642     {
1643         return "Could not find layer for surface";
1644     }
1645
1646     HMI_DEBUG("wm", "surface %d is detected", *surface_id);
1647     return nullptr;
1648 }
1649
1650 bool WindowManager::can_split(struct LayoutState const &state, int new_id)
1651 {
1652     if (state.main != -1 && state.main != new_id)
1653     {
1654         auto new_id_layer = this->layers.get_layer_id(new_id).value();
1655         auto current_id_layer = this->layers.get_layer_id(state.main).value();
1656
1657         // surfaces are on separate layers, don't bother.
1658         if (new_id_layer != current_id_layer)
1659         {
1660             return false;
1661         }
1662
1663         std::string const &new_id_str = this->lookup_name(new_id).value();
1664         std::string const &cur_id_str = this->lookup_name(state.main).value();
1665
1666         auto const &layer = this->layers.get_layer(new_id_layer);
1667
1668         HMI_DEBUG("wm", "layer info name: %s", layer->name.c_str());
1669
1670         if (layer->layouts.empty())
1671         {
1672             return false;
1673         }
1674
1675         for (auto i = layer->layouts.cbegin(); i != layer->layouts.cend(); i++)
1676         {
1677             HMI_DEBUG("wm", "%d main_match '%s'", new_id_layer, i->main_match.c_str());
1678             auto rem = std::regex(i->main_match);
1679             if (std::regex_match(cur_id_str, rem))
1680             {
1681                 // build the second one only if the first already matched
1682                 HMI_DEBUG("wm", "%d sub_match '%s'", new_id_layer, i->sub_match.c_str());
1683                 auto res = std::regex(i->sub_match);
1684                 if (std::regex_match(new_id_str, res))
1685                 {
1686                     HMI_DEBUG("wm", "layout matched!");
1687                     return true;
1688                 }
1689             }
1690         }
1691     }
1692
1693     return false;
1694 }
1695
1696 const char* WindowManager::kDefaultOldRoleDb = "{ \
1697     \"old_roles\": [ \
1698         { \
1699             \"name\": \"HomeScreen\", \
1700             \"new\": \"homescreen\" \
1701         }, \
1702         { \
1703             \"name\": \"Music\", \
1704             \"new\": \"music\" \
1705         }, \
1706         { \
1707             \"name\": \"MediaPlayer\", \
1708             \"new\": \"music\" \
1709         }, \
1710         { \
1711             \"name\": \"Video\", \
1712             \"new\": \"video\" \
1713         }, \
1714         { \
1715             \"name\": \"VideoPlayer\", \
1716             \"new\": \"video\" \
1717         }, \
1718         { \
1719             \"name\": \"WebBrowser\", \
1720             \"new\": \"browser\" \
1721         }, \
1722         { \
1723             \"name\": \"Radio\", \
1724             \"new\": \"radio\" \
1725         }, \
1726         { \
1727             \"name\": \"Phone\", \
1728             \"new\": \"phone\" \
1729         }, \
1730         { \
1731             \"name\": \"Navigation\", \
1732             \"new\": \"map\" \
1733         }, \
1734         { \
1735             \"name\": \"HVAC\", \
1736             \"new\": \"hvac\" \
1737         }, \
1738         { \
1739             \"name\": \"Settings\", \
1740             \"new\": \"settings\" \
1741         }, \
1742         { \
1743             \"name\": \"Dashboard\", \
1744             \"new\": \"dashboard\" \
1745         }, \
1746         { \
1747             \"name\": \"POI\", \
1748             \"new\": \"poi\" \
1749         }, \
1750         { \
1751             \"name\": \"Mixer\", \
1752             \"new\": \"mixer\" \
1753         }, \
1754         { \
1755             \"name\": \"Restriction\", \
1756             \"new\": \"restriction\" \
1757         }, \
1758         { \
1759             \"name\": \"^OnScreen.*\", \
1760             \"new\": \"on_screen\" \
1761         } \
1762     ] \
1763 }";
1764
1765 /**
1766  * controller_hooks
1767  */
1768 void controller_hooks::surface_created(uint32_t surface_id)
1769 {
1770     this->app->surface_created(surface_id);
1771 }
1772
1773 void controller_hooks::surface_removed(uint32_t surface_id)
1774 {
1775     this->app->surface_removed(surface_id);
1776 }
1777
1778 void controller_hooks::surface_visibility(uint32_t /*surface_id*/,
1779                                           uint32_t /*v*/) {}
1780
1781 void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/,
1782                                                      uint32_t /*x*/,
1783                                                      uint32_t /*y*/,
1784                                                      uint32_t /*w*/,
1785                                                      uint32_t /*h*/) {}
1786
1787 } // namespace wm