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