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