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