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