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