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