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