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