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