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