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