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