Bug Fix: When restriction app gets invisible event, other app also gets it
[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 #include <string>
38
39
40 namespace wm {
41
42 /* DrawingArea name used by "{layout}.{area}" */
43 const char kNameLayoutNormal[] = "normal";
44 const char kNameLayoutSplit[]  = "split";
45 const char kNameAreaFull[]     = "full";
46 const char kNameAreaMain[]     = "main";
47 const char kNameAreaSub[]      = "sub";
48
49 /* Key for json obejct */
50 const char kKeyDrawingName[] = "drawing_name";
51 const char kKeyDrawingArea[] = "drawing_area";
52 const char kKeyDrawingRect[] = "drawing_rect";
53 const char kKeyX[]           = "x";
54 const char kKeyY[]           = "y";
55 const char kKeyWidth[]       = "width";
56 const char kKeyHeight[]      = "height";
57 const char kKeyWidthPixel[]  = "width_pixel";
58 const char kKeyHeightPixel[] = "height_pixel";
59 const char kKeyWidthMm[]     = "width_mm";
60 const char kKeyHeightMm[]    = "height_mm";
61
62
63 namespace {
64
65 using nlohmann::json;
66
67 result<json> file_to_json(char const *filename) {
68    json j;
69    std::ifstream i(filename);
70    if (i.fail()) {
71       HMI_DEBUG("wm", "Could not open config file, so use default layer information");
72       j = default_layers_json;
73    }
74    else {
75       i >> j;
76    }
77
78    return Ok(j);
79 }
80
81 struct result<layer_map> load_layer_map(char const *filename) {
82    HMI_DEBUG("wm", "loading IDs from %s", filename);
83
84    auto j = file_to_json(filename);
85    if (j.is_err()) {
86       return Err<layer_map>(j.unwrap_err());
87    }
88    json jids = j.unwrap();
89
90    return to_layer_map(jids);
91 }
92
93 }  // namespace
94
95
96 /**
97  * App Impl
98  */
99 App::App(wl::display *d)
100    : chooks{this},
101      display{d},
102      controller{},
103      outputs(),
104      config(),
105      layers(),
106      id_alloc{},
107      pending_events(false),
108      policy{} {
109    try {
110       {
111          auto l = load_layer_map(
112             this->config.get_string("layers.json").value().c_str());
113          if (l.is_ok()) {
114             this->layers = l.unwrap();
115          } else {
116             HMI_ERROR("wm", "%s", l.err().value());
117          }
118       }
119    } catch (std::exception &e) {
120       HMI_ERROR("wm", "Loading of configuration failed: %s", e.what());
121    }
122
123    // Initialize current car info
124    this->crr_car_info_.parking_brake_stt = true;
125    this->crr_car_info_.accel_pedal_stt = false;
126    this->crr_car_info_.accel_pedal_pos = 0;
127    this->crr_car_info_.car_stt = "stop";
128    this->crr_car_info_.headlamp_stt = false;
129 }
130
131 int App::init() {
132    if (!this->display->ok()) {
133       return -1;
134    }
135
136    if (this->layers.mapping.empty()) {
137       HMI_ERROR("wm", "No surface -> layer mapping loaded");
138       return -1;
139    }
140
141 #if 1 // @@@@@
142    // Load app.db
143    this->loadAppDb();
144 #endif
145
146    // Initialize PolicyManager
147    this->pm_.initialize();
148
149    // Initialize LayoutManager
150    this->lm_.initialize();
151
152    // Make afb event
153    for (int i=Event_Val_Min; i<=Event_Val_Max; i++) {
154       map_afb_event[kListEventName[i]] = afb_daemon_make_event(kListEventName[i]);
155    }
156
157    this->display->add_global_handler(
158       "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
159          this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
160       });
161
162    this->display->add_global_handler(
163       "ivi_wm", [this](wl_registry *r, uint32_t name, uint32_t v) {
164          this->controller =
165             std::make_unique<struct compositor::controller>(r, name, v);
166
167          // Init controller hooks
168          this->controller->chooks = &this->chooks;
169
170          // This protocol needs the output, so lets just add our mapping here...
171          this->controller->add_proxy_to_id_mapping(
172             this->outputs.back()->proxy.get(),
173             wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
174                this->outputs.back()->proxy.get())));
175
176          // Create screen
177          this->controller->create_screen(this->outputs.back()->proxy.get());
178
179          // Set display to controller
180          this->controller->display = this->display;
181       });
182
183    // First level objects
184    this->display->roundtrip();
185    // Second level objects
186    this->display->roundtrip();
187    // Third level objects
188    this->display->roundtrip();
189
190    return init_layers();
191 }
192
193 int App::dispatch_pending_events() {
194    if (this->pop_pending_events()) {
195       this->display->dispatch_pending();
196       return 0;
197    }
198    return -1;
199 }
200
201 bool App::pop_pending_events() {
202    bool x{true};
203    return this->pending_events.compare_exchange_strong(
204       x, false, std::memory_order_consume);
205 }
206
207 void App::set_pending_events() {
208    this->pending_events.store(true, std::memory_order_release);
209 }
210
211 optional<int> App::lookup_id(char const *name) {
212    return this->id_alloc.lookup(std::string(name));
213 }
214 optional<std::string> App::lookup_name(int id) {
215    return this->id_alloc.lookup(id);
216 }
217
218 /**
219  * init_layers()
220  */
221 int App::init_layers() {
222    if (!this->controller) {
223       HMI_ERROR("wm", "ivi_controller global not available");
224       return -1;
225    }
226
227    if (this->outputs.empty()) {
228       HMI_ERROR("wm", "no output was set up!");
229       return -1;
230    }
231
232    auto &c = this->controller;
233
234    auto &o = this->outputs.front();
235    auto &s = c->screens.begin()->second;
236    auto &layers = c->layers;
237
238    // Write output dimensions to ivi controller...
239    c->output_size = compositor::size{uint32_t(o->width), uint32_t(o->height)};
240    c->physical_size = compositor::size{uint32_t(o->physical_width),
241                                        uint32_t(o->physical_height)};
242
243    // Clear scene
244    layers.clear();
245
246    // Clear screen
247    s->clear();
248
249    // Quick and dirty setup of layers
250    for (auto const &i : this->layers.mapping) {
251       c->layer_create(i.second.layer_id, o->width, o->height);
252       auto &l = layers[i.second.layer_id];
253       l->set_destination_rectangle(0, 0, o->width, o->height);
254       l->set_visibility(1);
255       HMI_DEBUG("wm", "Setting up layer %s (%d) for surface role match \"%s\"",
256                i.second.name.c_str(), i.second.layer_id, i.second.role.c_str());
257    }
258
259    // Add layers to screen
260    s->set_render_order(this->layers.layers);
261
262    this->layout_commit();
263
264    return 0;
265 }
266
267 void App::layout_commit() {
268    this->controller->commit_changes();
269    this->display->flush();
270 }
271
272 void App::allocateWindowResource(char const *event, char const *drawing_name,
273                                  char const *drawing_area, char const *role,
274                                  const reply_func &reply) {
275     const char* new_role = nullptr;
276     const char* new_area = nullptr;
277
278     if (0 == strcmp("activate", event)) {
279         // TODO:
280         // This process will be removed
281         // because the applications will specify role instead of drawing_name
282         {
283             if ((nullptr == role) || (0 == strcmp("", role))) {
284                 HMI_DEBUG("wm", "Role is not specified, so get by using app name");
285                 new_role = this->app2role_[drawing_name].c_str();
286             }
287             else {
288                 new_role = role;
289             }
290             HMI_DEBUG("wm", "drawing_name:%s, new_role: %s", drawing_name, new_role);
291         }
292
293         // TODO:
294         // This process will be removed
295         // because the area "normal.full" and "normalfull" will be prohibited
296         {
297             if (0 == strcmp("Restriction", drawing_name)) {
298                 new_area = drawing_area;
299             }
300             else {
301                 if (nullptr == drawing_area) {
302                     new_area = "normal";
303                 }
304                 else if (0 == strcmp("normal.full", drawing_area)) {
305                     new_area = "normal";
306                 }
307                 else if (0 == strcmp("restriction.split.sub", drawing_area)) {
308                     new_area = "restriction.split.sub";
309                 }
310                 else if (0 == strcmp("homescreen", new_role)) {
311                     // Now homescreen specifies "normalfull"
312                     new_area = "full";
313                 }
314                 else {
315                     new_area = "normal";
316                 }
317             }
318             HMI_DEBUG("wm", "drawing_area:%s, new_area: %s", drawing_area, new_area);
319         }
320     }
321     else if (0 == strcmp("deactivate", event)) {
322         // TODO:
323         // This process will be removed
324         // because the applications will specify role instead of drawing_name
325         {
326             if ((nullptr == role) || (0 == strcmp("", role))) {
327                 HMI_DEBUG("wm", "Role is not specified, so get by using app name");
328                 new_role = this->app2role_[drawing_name].c_str();
329             }
330             else {
331                 new_role = role;
332             }
333             HMI_DEBUG("wm", "drawing_name:%s, new_role: %s", drawing_name, new_role);
334         }
335         new_area = "";
336     }
337
338     // TODO:
339     // Check role
340
341     // TODO:
342     // If event is "activate" and area is not specifid,
343     // get default value by using role
344
345     // Check Policy
346     json_object* json_in = json_object_new_object();
347     json_object* json_out = json_object_new_object();
348     json_object_object_add(json_in, "event", json_object_new_string(event));
349
350     if (nullptr != new_role) {
351         json_object_object_add(json_in, "role", json_object_new_string(new_role));
352     }
353     if (nullptr != new_area) {
354         json_object_object_add(json_in, "area", json_object_new_string(new_area));
355     }
356
357     int ret = this->pm_.checkPolicy(json_in, &json_out);
358     if (0 > ret) {
359         reply("Error checkPolicy()");
360         return;
361     }
362     else {
363         HMI_DEBUG("wm", "result: %s", json_object_get_string(json_out));
364     }
365
366     // Release json_object
367     json_object_put(json_in);
368
369     // Check parking brake state
370     json_object* json_parking_brake;
371     if (!json_object_object_get_ex(json_out, "parking_brake", &json_parking_brake)) {
372         reply("Not found key \"parking_brake\"");
373         return;
374     }
375
376     json_bool is_changed;
377     is_changed = jh::getBoolFromJson(json_parking_brake, "is_changed");
378     if (is_changed) {
379         std::string parking_brake_state = jh::getStringFromJson(json_parking_brake, "state");
380         HMI_DEBUG("wm", "parking_brake_state: %s", parking_brake_state.c_str());
381
382         // Update state and emit event
383         if ("parking_brake_off" == parking_brake_state) {
384             this->crr_car_info_.parking_brake_stt = false;
385             this->emitParkingBrakeOff();
386         }
387         else if ("parking_brake_on" == parking_brake_state) {
388             this->crr_car_info_.parking_brake_stt = true;
389             this->emitParkingBrakeOn();
390         }
391         else {
392             reply("Unknown parking brake state");
393             return;
394         }
395     }
396
397     // Check accelerator pedal state
398     json_object* json_accel_pedal;
399     if (!json_object_object_get_ex(json_out, "accel_pedal", &json_accel_pedal)) {
400         reply("Not found key \"accel_pedal\"");
401         return;
402     }
403
404     is_changed = jh::getBoolFromJson(json_accel_pedal, "is_changed");
405     if (is_changed) {
406         std::string accel_pedal_state = jh::getStringFromJson(json_accel_pedal, "state");
407         HMI_DEBUG("wm", "accel_pedal_state: %s", accel_pedal_state.c_str());
408
409         // Update state
410         if ("accel_pedal_off" == accel_pedal_state) {
411             this->crr_car_info_.accel_pedal_stt = false;
412         }
413         else if ("accel_pedal_on" == accel_pedal_state) {
414             this->crr_car_info_.accel_pedal_stt = true;
415         }
416         else {
417             reply("Unknown accel pedal state");
418             return;
419         }
420     }
421
422     // Check car state
423     json_object* json_car;
424     if (!json_object_object_get_ex(json_out, "car", &json_car)) {
425         reply("Not found key \"car\"");
426         return;
427     }
428
429     is_changed = jh::getBoolFromJson(json_car, "is_changed");
430     if (is_changed) {
431         std::string car_state = jh::getStringFromJson(json_car, "state");
432         HMI_DEBUG("wm", "car_state: %s", car_state.c_str());
433
434         // Emit car event
435         if ("car_stop" == car_state) {
436             this->crr_car_info_.car_stt = "stop";
437             this->emitCarStop();
438         }
439         else if ("car_run" == car_state) {
440             this->crr_car_info_.car_stt = "run";
441             this->emitCarRun();
442         }
443         else {
444             reply("Unknown car state");
445             return;
446         }
447     }
448
449     // Check lamp state
450     json_object* json_lamp;
451     if (!json_object_object_get_ex(json_out, "lamp", &json_lamp)) {
452         reply("Not found key \"lamp\"");
453         return;
454     }
455
456     is_changed = jh::getBoolFromJson(json_lamp, "is_changed");
457     if (is_changed) {
458         std::string lamp_state = jh::getStringFromJson(json_lamp, "state");
459         HMI_DEBUG("wm", "lamp_state: %s", lamp_state.c_str());
460
461         // Update state and emit event
462         if ("lamp_off" == lamp_state) {
463             this->crr_car_info_.headlamp_stt = false;
464             this->emitHeadlampOff();
465         }
466         else if ("lamp_on" == lamp_state) {
467             this->crr_car_info_.headlamp_stt = true;
468             this->emitHeadlampOn();
469         }
470         else {
471             reply("Unknown lamp state");
472             return;
473         }
474     }
475
476     // Get category
477     const char* category = nullptr;
478     std::string str_category;
479     if (nullptr != new_role) {
480         str_category = this->pm_.roleToCategory(new_role);
481         category = str_category.c_str();
482         HMI_DEBUG("wm", "role:%s category:%s", new_role, category);
483     }
484
485     // Update layout
486     if (this->lm_.updateLayout(json_out, new_role, category)) {
487         HMI_DEBUG("wm", "Layer is changed!!");
488
489         // Allocate surface
490         this->allocateSurface();
491     }
492     else {
493         HMI_DEBUG("wm", "All layer is NOT changed!!");
494     }
495
496     // Release json_object
497     json_object_put(json_out);
498
499     return;
500 }
501
502 void App::enqueue_flushdraw(int surface_id) {
503    this->check_flushdraw(surface_id);
504    HMI_DEBUG("wm", "Enqueuing EndDraw for surface_id %d", surface_id);
505    this->pending_end_draw.push_back(surface_id);
506 }
507
508 void App::check_flushdraw(int surface_id) {
509    auto i = std::find(std::begin(this->pending_end_draw),
510                       std::end(this->pending_end_draw), surface_id);
511    if (i != std::end(this->pending_end_draw)) {
512       auto n = this->lookup_name(surface_id);
513       HMI_ERROR("wm", "Application %s (%d) has pending EndDraw call(s)!",
514                n ? n->c_str() : "unknown-name", surface_id);
515       std::swap(this->pending_end_draw[std::distance(
516                    std::begin(this->pending_end_draw), i)],
517                 this->pending_end_draw.back());
518       this->pending_end_draw.resize(this->pending_end_draw.size() - 1);
519    }
520 }
521
522 void App::api_enddraw(char const *drawing_name) {
523    for (unsigned i = 0, iend = this->pending_end_draw.size(); i < iend; i++) {
524       auto n = this->lookup_name(this->pending_end_draw[i]);
525       if (n && *n == drawing_name) {
526          std::swap(this->pending_end_draw[i], this->pending_end_draw[iend - 1]);
527          this->pending_end_draw.resize(iend - 1);
528          this->activate(this->pending_end_draw[i]);
529          this->emit_flushdraw(drawing_name);
530       }
531    }
532 }
533
534 void App::api_ping() { this->dispatch_pending_events(); }
535
536 void App::send_event(char const *evname){
537    HMI_DEBUG("wm", "%s: %s", __func__, evname);
538
539    int ret = afb_event_push(this->map_afb_event[evname], nullptr);
540    if (ret != 0) {
541       HMI_DEBUG("wm", "afb_event_push failed: %m");
542    }
543 }
544
545 void App::send_event(char const *evname, char const *label){
546    HMI_DEBUG("wm", "%s: %s(%s)", __func__, evname, label);
547
548    json_object *j = json_object_new_object();
549    json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
550
551    int ret = afb_event_push(this->map_afb_event[evname], j);
552    if (ret != 0) {
553       HMI_DEBUG("wm", "afb_event_push failed: %m");
554    }
555 }
556
557 void App::send_event(char const *evname, char const *label, char const *area,
558                              int x, int y, int w, int h) {
559    HMI_DEBUG("wm", "%s: %s(%s, %s) x:%d y:%d w:%d h:%d",
560              __func__, evname, label, area, x, y, w, h);
561
562    json_object *j_rect = json_object_new_object();
563    json_object_object_add(j_rect, kKeyX,      json_object_new_int(x));
564    json_object_object_add(j_rect, kKeyY,      json_object_new_int(y));
565    json_object_object_add(j_rect, kKeyWidth,  json_object_new_int(w));
566    json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
567
568    json_object *j = json_object_new_object();
569    json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
570    json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area));
571    json_object_object_add(j, kKeyDrawingRect, j_rect);
572
573    int ret = afb_event_push(this->map_afb_event[evname], j);
574    if (ret != 0) {
575       HMI_DEBUG("wm", "afb_event_push failed: %m");
576    }
577 }
578
579 /**
580  * proxied events
581  */
582 void App::surface_created(uint32_t surface_id) {
583    auto layer_id = this->layers.get_layer_id(surface_id);
584    if (!layer_id) {
585       HMI_DEBUG("wm", "Newly created surfce %d is not associated with any layer!",
586                surface_id);
587       return;
588    }
589
590    HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", surface_id, *layer_id);
591
592    this->controller->layers[*layer_id]->add_surface(surface_id);
593    this->layout_commit();
594    // activate the main_surface right away
595    /*if (surface_id == static_cast<unsigned>(this->layers.main_surface)) {
596       HMI_DEBUG("wm", "Activating main_surface (%d)", surface_id);
597
598       this->api_activate_surface(
599          this->lookup_name(surface_id).value_or("unknown-name").c_str());
600    }*/
601 }
602
603 void App::surface_removed(uint32_t surface_id) {
604    HMI_DEBUG("wm", "surface_id is %u", surface_id);
605
606    // We cannot normally deactivate the main_surface, so be explicit
607    // about it:
608    if (int(surface_id) == this->layers.main_surface) {
609       this->deactivate_main_surface();
610    } else {
611       auto drawing_name = this->lookup_name(surface_id);
612       if (drawing_name) {
613          this->allocateWindowResource("deactivate", drawing_name->c_str(),
614                                       nullptr, nullptr,
615                                       [](const char*){});
616       }
617    }
618
619    this->id_alloc.remove_id(surface_id);
620    this->layers.remove_surface(surface_id);
621 }
622
623 void App::emit_activated(char const *label) {
624    this->send_event(kListEventName[Event_Active], label);
625 }
626
627 void App::emit_deactivated(char const *label) {
628    this->send_event(kListEventName[Event_Inactive], label);
629 }
630
631 void App::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h) {
632    this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
633 }
634
635 void App::emit_flushdraw(char const *label) {
636    this->send_event(kListEventName[Event_FlushDraw], label);
637 }
638
639 void App::emit_visible(char const *label, bool is_visible) {
640    this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
641 }
642
643 void App::emit_invisible(char const *label) {
644    return emit_visible(label, false);
645 }
646
647 void App::emit_visible(char const *label) { return emit_visible(label, true); }
648
649 void App::emitHeadlampOff() {
650     // Send HeadlampOff event for all application
651     this->send_event(kListEventName[Event_HeadlampOff]);
652 }
653
654 void App::emitHeadlampOn() {
655     // Send HeadlampOn event for all application
656     this->send_event(kListEventName[Event_HeadlampOn]);
657 }
658
659 void App::emitParkingBrakeOff() {
660     // Send ParkingBrakeOff event for all application
661     this->send_event(kListEventName[Event_ParkingBrakeOff]);
662 }
663
664 void App::emitParkingBrakeOn() {
665     // Send ParkingBrakeOn event for all application
666     this->send_event(kListEventName[Event_ParkingBrakeOn]);
667 }
668
669 void App::emitCarStop() {
670     // Send CarStop event for all application
671     this->send_event(kListEventName[Event_CarStop]);
672 }
673
674 void App::emitCarRun() {
675     // Send CarRun event for all application
676     this->send_event(kListEventName[Event_CarRun]);
677 }
678
679 result<int> App::api_request_surface(char const *drawing_name) {
680    auto lid = this->layers.get_layer_id(std::string(drawing_name));
681    if (!lid) {
682       /**
683        * register drawing_name as fallback and make it displayed.
684        */
685       lid = this->layers.get_layer_id(std::string("Fallback"));
686       HMI_DEBUG("wm", "%s is not registered in layers.json, then fallback as normal app", drawing_name);
687       if(!lid){
688           return Err<int>("Drawing name does not match any role, Fallback is disabled");
689       }
690    }
691
692    auto rname = this->lookup_id(drawing_name);
693    if (!rname) {
694       // name does not exist yet, allocate surface id...
695       auto id = int(this->id_alloc.generate_id(drawing_name));
696       this->layers.add_surface(id, *lid);
697
698       // set the main_surface[_name] here and now
699       if (!this->layers.main_surface_name.empty() &&
700           this->layers.main_surface_name == drawing_name) {
701          this->layers.main_surface = id;
702          HMI_DEBUG("wm", "Set main_surface id to %u", id);
703       }
704
705 #if 0 // @@@@@
706       // TODO:
707       // This process will be implemented in SystemManager
708       {
709           // Generate app id
710           auto id = int(this->app_id_alloc_.generate_id(drawing_name));
711           this->appname2appid_[drawing_name] = id;
712       }
713 #endif
714
715       // Set map of (role, surface_id)
716       std::string role = this->app2role_[std::string(drawing_name)];
717       this->role2surfaceid_[role] = id;
718
719       // Set map of (role, app)
720       // If the new app which has the same role which is had by existing app is requested,
721       // the role is given to the new app.
722       this->role2app_[role] = std::string(drawing_name);
723
724       return Ok<int>(id);
725    }
726
727    // Check currently registered drawing names if it is already there.
728    return Err<int>("Surface already present");
729 }
730
731 char const *App::api_request_surface(char const *drawing_name,
732                                      char const *ivi_id) {
733    ST();
734
735    auto lid = this->layers.get_layer_id(std::string(drawing_name));
736    unsigned sid = std::stol(ivi_id);
737
738    if (!lid) {
739       /**
740        * register drawing_name as fallback and make it displayed.
741        */
742       lid = this->layers.get_layer_id(std::string("Fallback"));
743       HMI_DEBUG("wm", "%s is not registered in layers.json, then fallback as normal app", drawing_name);
744       if(!lid){
745           return "Drawing name does not match any role, Fallback is disabled";
746       }
747    }
748
749    auto rname = this->lookup_id(drawing_name);
750
751    if (rname) {
752        return "Surface already present";
753    }
754
755    // register pair drawing_name and ivi_id
756    this->id_alloc.register_name_id(drawing_name, sid);
757    this->layers.add_surface(sid, *lid);
758
759    // this surface is already created
760    HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", sid, *lid);
761
762    this->controller->layers[*lid]->add_surface(sid);
763    this->layout_commit();
764
765    return nullptr;
766 }
767
768 result<json_object *> App::api_get_display_info() {
769    // Check controller
770    if (!this->controller) {
771       return Err<json_object *>("ivi_controller global not available");
772    }
773
774    // Set display info
775    compositor::size o_size = this->controller->output_size;
776    compositor::size p_size = this->controller->physical_size;
777
778    json_object *object = json_object_new_object();
779    json_object_object_add(object, kKeyWidthPixel,  json_object_new_int(o_size.w));
780    json_object_object_add(object, kKeyHeightPixel, json_object_new_int(o_size.h));
781    json_object_object_add(object, kKeyWidthMm,     json_object_new_int(p_size.w));
782    json_object_object_add(object, kKeyHeightMm,    json_object_new_int(p_size.h));
783
784    return Ok<json_object *>(object);
785 }
786
787 result<json_object *> App::api_get_area_info(char const *drawing_name) {
788    HMI_DEBUG("wm", "called");
789
790    // Check drawing name, surface/layer id
791    auto const &surface_id = this->lookup_id(drawing_name);
792    if (!surface_id) {
793       return Err<json_object *>("Surface does not exist");
794    }
795
796    if (!this->controller->surface_exists(*surface_id)) {
797       return Err<json_object *>("Surface does not exist in controller!");
798    }
799
800    auto layer_id = this->layers.get_layer_id(*surface_id);
801    if (!layer_id) {
802       return Err<json_object *>("Surface is not on any layer!");
803    }
804
805    auto o_state = *this->layers.get_layout_state(*surface_id);
806    if (o_state == nullptr) {
807       return Err<json_object *>("Could not find layer for surface");
808    }
809
810    struct LayoutState &state = *o_state;
811    if ((state.main != *surface_id) && (state.sub != *surface_id)) {
812       return Err<json_object *>("Surface is inactive");
813    }
814
815    // Set area rectangle
816    compositor::rect area_info = this->area_info[*surface_id];
817    json_object *object = json_object_new_object();
818    json_object_object_add(object, kKeyX,      json_object_new_int(area_info.x));
819    json_object_object_add(object, kKeyY,      json_object_new_int(area_info.y));
820    json_object_object_add(object, kKeyWidth,  json_object_new_int(area_info.w));
821    json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
822
823    return Ok<json_object *>(object);
824 }
825
826 void App::activate(int id) {
827    auto ip = this->controller->sprops.find(id);
828    if (ip != this->controller->sprops.end()) {
829       this->controller->surfaces[id]->set_visibility(1);
830       char const *label =
831          this->lookup_name(id).value_or("unknown-name").c_str();
832
833       // FOR CES DEMO >>>
834       if ((0 == strcmp(label, "Radio"))
835           || (0 == strcmp(label, "MediaPlayer"))
836           || (0 == strcmp(label, "Music"))
837           || (0 == strcmp(label, "Navigation"))) {
838         for (auto i = surface_bg.begin(); i != surface_bg.end(); ++i) {
839             if (id == *i) {
840                // Remove id
841                this->surface_bg.erase(i);
842
843                // Remove from BG layer (999)
844                HMI_DEBUG("wm", "Remove %s(%d) from BG layer", label, id);
845                this->controller->layers[999]->remove_surface(id);
846
847                // Add to FG layer (1001)
848                HMI_DEBUG("wm", "Add %s(%d) to FG layer", label, id);
849                this->controller->layers[1001]->add_surface(id);
850
851                for (int j : this->surface_bg) {
852                  HMI_DEBUG("wm", "Stored id:%d", j);
853                }
854                break;
855             }
856          }
857       }
858       // <<< FOR CES DEMO
859       this->layout_commit();
860
861       this->emit_visible(label);
862       this->emit_activated(label);
863    }
864 }
865
866 void App::deactivate(int id) {
867    auto ip = this->controller->sprops.find(id);
868    if (ip != this->controller->sprops.end()) {
869       char const *label =
870          this->lookup_name(id).value_or("unknown-name").c_str();
871
872       // FOR CES DEMO >>>
873       if ((0 == strcmp(label, "Radio"))
874           || (0 == strcmp(label, "MediaPlayer"))
875           || (0 == strcmp(label, "Music"))
876           || (0 == strcmp(label, "Navigation"))) {
877
878          // Store id
879          this->surface_bg.push_back(id);
880
881          // Remove from FG layer (1001)
882          HMI_DEBUG("wm", "Remove %s(%d) from FG layer", label, id);
883          this->controller->layers[1001]->remove_surface(id);
884
885          // Add to BG layer (999)
886          HMI_DEBUG("wm", "Add %s(%d) to BG layer", label, id);
887          this->controller->layers[999]->add_surface(id);
888
889          for (int j : surface_bg) {
890             HMI_DEBUG("wm", "Stored id:%d", j);
891          }
892       }
893       else {
894          this->controller->surfaces[id]->set_visibility(0);
895       }
896       // <<< FOR CES DEMO
897
898       this->layout_commit();
899
900       this->emit_deactivated(label);
901       this->emit_invisible(label);
902    }
903 }
904
905 void App::deactivate(std::string role) {
906     std::string app = this->role2app_[role];
907     auto const &id = this->lookup_id(app.c_str());
908     if (!id) {
909       HMI_ERROR("wm", "Surface does not exist");
910       return;
911     }
912     HMI_DEBUG("wm", "Deactivate role:%s (app:%s)",
913               role.c_str(), app.c_str());
914
915     this->deactivate(*id);
916 }
917
918 void App::deactivate_main_surface() {
919    this->layers.main_surface = -1;
920    this->allocateWindowResource("deactivate", this->layers.main_surface_name.c_str(),
921                                 nullptr, nullptr,
922                                 [](const char*){});
923 }
924
925 /**
926  * controller_hooks
927  */
928 void controller_hooks::surface_created(uint32_t surface_id) {
929    this->app->surface_created(surface_id);
930 }
931
932 void controller_hooks::surface_removed(uint32_t surface_id) {
933    this->app->surface_removed(surface_id);
934 }
935
936 void controller_hooks::surface_visibility(uint32_t /*surface_id*/,
937                                           uint32_t /*v*/) {}
938
939 void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/,
940                                                      uint32_t /*x*/,
941                                                      uint32_t /*y*/,
942                                                      uint32_t /*w*/,
943                                                      uint32_t /*h*/) {}
944
945 int App::allocateSurface() {
946     HMI_DEBUG("wm", "Call");
947
948     // Get current/previous layers
949     LayoutManager::TypeLayers crr_layers = this->lm_.getCurrentLayers();
950     LayoutManager::TypeLayers prv_layers = this->lm_.getPreviousLayers();
951
952     // Update resource of all layers
953     for (auto itr_layers = crr_layers.begin();
954          itr_layers != crr_layers.end(); ++itr_layers) {
955         // Get layer
956         std::string layer = itr_layers->first;
957         HMI_DEBUG("wm", "Try to update resource in %s layer", layer.c_str());
958
959         // If layout is changed, update resouce
960         if (this->lm_.isLayoutChanged(layer.c_str())) {
961             // Get current/previous layout
962             LayoutManager::TypeLayouts crr_layout = itr_layers->second;
963             LayoutManager::TypeLayouts prv_layout = prv_layers[layer];
964
965             // Get current/previous layout name
966             std::string crr_layout_name = crr_layout.begin()->first;
967             std::string prv_layout_name = prv_layout.begin()->first;
968             HMI_DEBUG("wm", "layout name crr:%s prv:%s",
969                       crr_layout_name.c_str(), prv_layout_name.c_str());
970
971             // Get current/previous ares
972             LayoutManager::TypeAreas crr_areas = crr_layout[crr_layout_name];
973             LayoutManager::TypeAreas prv_areas = prv_layout[prv_layout_name];
974
975             // Create previous displayed role list
976             std::string prv_area_name;
977             std::vector<std::string> prv_role_list;
978             for (auto itr_areas = prv_areas.begin();
979                  itr_areas != prv_areas.end(); ++itr_areas) {
980                 prv_area_name = itr_areas->first;
981                 prv_role_list.push_back(prv_areas[prv_area_name]["role"]);
982                 HMI_DEBUG("wm", "previous displayed role:%s",
983                           prv_areas[prv_area_name]["role"].c_str());
984             }
985
986             // Allocate surface for each area
987             std::string crr_area_name;
988             std::string crr_role_name;
989             LayoutManager::TypeRolCtg crr_rol_ctg;
990             for (auto itr_areas = crr_areas.begin();
991                  itr_areas != crr_areas.end(); ++itr_areas) {
992                 crr_area_name = itr_areas->first;
993                 crr_rol_ctg = itr_areas->second;
994
995                 // Get role of current area
996                 if ("category" == crr_rol_ctg.begin()->first) {
997                     // If current area have category
998                     // Get category name
999                     std::string crr_ctg = crr_rol_ctg.begin()->second;
1000
1001                     // Serch relevant role from previous displayed role list
1002                     for (auto itr_role = prv_role_list.begin();
1003                          itr_role != prv_role_list.end(); ++itr_role) {
1004                         std::string prv_ctg = this->pm_.roleToCategory((*itr_role).c_str());
1005                         if (crr_ctg == prv_ctg) {
1006                             // First discovered role is set to current role
1007                             crr_role_name = *itr_role;
1008
1009                             // Delete used role for other areas
1010                             // which have same category
1011                             prv_role_list.erase(itr_role);
1012
1013                             break;
1014                         }
1015                     }
1016                 }
1017                 else {
1018                     crr_role_name = itr_areas->second["role"];
1019                 }
1020                 HMI_DEBUG("wm", "Allocate surface for area:%s role:%s",
1021                           crr_area_name.c_str(), crr_role_name.c_str());
1022
1023                 // Deactivate non-displayed role
1024                 std::string prv_role_name;
1025                 if (crr_layout_name == prv_layout_name) {
1026                     HMI_DEBUG("wm", "Current layout is same with previous");
1027
1028                     // Deactivate previous role in same area
1029                     // if it is different with current
1030                     prv_role_name = prv_areas[crr_area_name]["role"];
1031                     if (crr_role_name != prv_role_name) {
1032                         this->deactivate(prv_role_name);
1033                     }
1034                 }
1035                 else {
1036                     HMI_DEBUG("wm", "Current layout is different with previous");
1037
1038                     if ("none" != prv_layout_name) {
1039                         // Deactivate previous role in all area in previous layout
1040                         // if it is different with current role
1041                         for(auto itr = prv_areas.begin(); itr != prv_areas.end(); ++itr) {
1042                             prv_role_name = itr->second["role"].c_str();
1043                             if (crr_role_name != prv_role_name) {
1044                                 this->deactivate(prv_role_name);
1045                             }
1046                         }
1047                     }
1048                 }
1049
1050                 // Set surface for displayed role
1051                 if ("none" != crr_layout_name) {
1052                     // If current layout is not "none",
1053                     // set surface for current role
1054                     this->setSurfaceSize(crr_role_name.c_str(), crr_area_name.c_str());
1055
1056                     // TODO:
1057                     // This API is workaround.
1058                     // Resource manager should manage each resource infomations
1059                     // according to architecture document.
1060                     this->lm_.updateArea(layer.c_str(), crr_role_name.c_str(), crr_area_name.c_str());
1061                 }
1062             }
1063         }
1064     }
1065     return 0;
1066 }
1067
1068 void App::setSurfaceSize(const char* role, const char* area) {
1069     HMI_DEBUG("wm", "role:%s area:%s", role, area);
1070
1071     // Get size of current area
1072     compositor::rect size = this->lm_.getAreaSize(area);
1073
1074     // Set destination to the display rectangle
1075     int surface_id = this->role2surfaceid_[role];
1076     auto &s = this->controller->surfaces[surface_id];
1077     s->set_destination_rectangle(size.x, size.y, size.w, size.h);
1078     this->layout_commit();
1079
1080     // Update area information
1081     this->area_info[surface_id].x = size.x;
1082     this->area_info[surface_id].y = size.y;
1083     this->area_info[surface_id].w = size.w;
1084     this->area_info[surface_id].h = size.h;
1085     HMI_DEBUG("wm", "Surface rect { %d, %d, %d, %d }",
1086               size.x, size.y, size.w, size.h);
1087
1088     // Emit syncDraw event
1089     const char* app = this->role2app_[role].c_str();
1090     this->emit_syncdraw(app, area,
1091                         size.x, size.y, size.w, size.h);
1092
1093     // Enqueue flushDraw event
1094     this->enqueue_flushdraw(surface_id);
1095 }
1096
1097 void App::setAccelPedalPos(double val) {
1098     this->crr_car_info_.accel_pedal_pos = val;
1099 }
1100
1101 extern const char* kDefaultAppDb;
1102 int App::loadAppDb() {
1103     HMI_DEBUG("wm", "Call");
1104
1105     // Get afm application installed dir
1106     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1107     HMI_DEBUG("wm", "afm_app_install_dir:%s", afm_app_install_dir);
1108
1109     std::string file_name;
1110     if (!afm_app_install_dir) {
1111         HMI_ERROR("wm", "AFM_APP_INSTALL_DIR is not defined");
1112     }
1113     else {
1114         file_name = std::string(afm_app_install_dir) + std::string("/etc/app.db");
1115     }
1116
1117     // Load app.db
1118     json_object* json_obj;
1119     int ret = jh::inputJsonFilie(file_name.c_str(), &json_obj);
1120     if (0 > ret) {
1121         HMI_ERROR("wm", "Could not open app.db, so use default role information");
1122         json_obj = json_tokener_parse(kDefaultAppDb);
1123     }
1124     HMI_DEBUG("wm", "json_obj dump:%s", json_object_get_string(json_obj));
1125
1126     // Perse apps
1127     HMI_DEBUG("wm", "Perse apps");
1128     json_object* json_cfg;
1129     if (!json_object_object_get_ex(json_obj, "apps", &json_cfg)) {
1130         HMI_ERROR("wm", "Parse Error!!");
1131         return -1;
1132     }
1133
1134     int len = json_object_array_length(json_cfg);
1135     HMI_DEBUG("wm", "json_cfg len:%d", len);
1136     HMI_DEBUG("wm", "json_cfg dump:%s", json_object_get_string(json_cfg));
1137
1138     for (int i=0; i<len; i++) {
1139         json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
1140         HMI_DEBUG("wm", "> json_tmp dump:%s", json_object_get_string(json_tmp));
1141
1142         const char* app = jh::getStringFromJson(json_tmp, "name");
1143         if (nullptr == app) {
1144             HMI_ERROR("wm", "Parse Error!!");
1145             return -1;
1146         }
1147         HMI_DEBUG("wm", "> app:%s", app);
1148
1149         const char* role = jh::getStringFromJson(json_tmp, "role");
1150         if (nullptr == role) {
1151             HMI_ERROR("wm", "Parse Error!!");
1152             return -1;
1153         }
1154         HMI_DEBUG("wm", "> role:%s", role);
1155
1156         this->app2role_[app] = std::string(role);
1157     }
1158
1159     // Check
1160     for(auto itr = this->app2role_.begin();
1161       itr != this->app2role_.end(); ++itr) {
1162         HMI_DEBUG("wm", "app:%s role:%s",
1163                   itr->first.c_str(), itr->second.c_str());
1164     }
1165
1166     // Release json_object
1167     json_object_put(json_obj);
1168
1169     return 0;
1170 }
1171
1172
1173 const char* kDefaultAppDb = "{ \
1174     \"apps\": [ \
1175         { \
1176             \"name\": \"HomeScreen\", \
1177             \"role\": \"homescreen\" \
1178         }, \
1179         { \
1180             \"name\": \"Music\", \
1181             \"role\": \"music\" \
1182         }, \
1183         { \
1184             \"name\": \"MediaPlayer\", \
1185             \"role\": \"music\" \
1186         }, \
1187         { \
1188             \"name\": \"Video\", \
1189             \"role\": \"video\" \
1190         }, \
1191         { \
1192             \"name\": \"VideoPlayer\", \
1193             \"role\": \"video\" \
1194         }, \
1195         { \
1196             \"name\": \"WebBrowser\", \
1197             \"role\": \"browser\" \
1198         }, \
1199         { \
1200             \"name\": \"Radio\", \
1201             \"role\": \"radio\" \
1202         }, \
1203         { \
1204             \"name\": \"Phone\", \
1205             \"role\": \"phone\" \
1206         }, \
1207         { \
1208             \"name\": \"Navigation\", \
1209             \"role\": \"map\" \
1210         }, \
1211         { \
1212             \"name\": \"HVAC\", \
1213             \"role\": \"hvac\" \
1214         }, \
1215         { \
1216             \"name\": \"Settings\", \
1217             \"role\": \"settings\" \
1218         }, \
1219         { \
1220             \"name\": \"Dashboard\", \
1221             \"role\": \"dashboard\" \
1222         }, \
1223         { \
1224             \"name\": \"POI\", \
1225             \"role\": \"poi\" \
1226         }, \
1227         { \
1228             \"name\": \"Mixer\", \
1229             \"role\": \"mixer\" \
1230         } \
1231     ] \
1232 }";
1233
1234
1235 }  // namespace wm