getCarInfo() can get lightstatus.brake status
[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 #if 0 // FOR ALS: using lightstatus brake, so do not emit parking brake event
386             this->emitParkingBrakeOff();
387 #endif
388         }
389         else if ("parking_brake_on" == parking_brake_state) {
390             this->crr_car_info_.parking_brake_stt = true;
391 #if 0 // FOR ALS: using lightstatus brake, so do not emit parking brake event
392             this->emitParkingBrakeOn();
393 #endif
394         }
395         else {
396             reply("Unknown parking brake state");
397             return;
398         }
399     }
400
401     // Check accelerator pedal state
402     json_object* json_accel_pedal;
403     if (!json_object_object_get_ex(json_out, "accel_pedal", &json_accel_pedal)) {
404         reply("Not found key \"accel_pedal\"");
405         return;
406     }
407
408     is_changed = jh::getBoolFromJson(json_accel_pedal, "is_changed");
409     if (is_changed) {
410         std::string accel_pedal_state = jh::getStringFromJson(json_accel_pedal, "state");
411         HMI_DEBUG("wm", "accel_pedal_state: %s", accel_pedal_state.c_str());
412
413         // Update state
414         if ("accel_pedal_off" == accel_pedal_state) {
415             this->crr_car_info_.accel_pedal_stt = false;
416         }
417         else if ("accel_pedal_on" == accel_pedal_state) {
418             this->crr_car_info_.accel_pedal_stt = true;
419         }
420         else {
421             reply("Unknown accel pedal state");
422             return;
423         }
424     }
425
426     // Check lightstatus brake state
427     json_object* json_lightstatus_brake;
428     if (!json_object_object_get_ex(json_out, "lightstatus_brake", &json_lightstatus_brake)) {
429         reply("Not found key \"lightstatus_brake\"");
430         return;
431     }
432
433     is_changed = jh::getBoolFromJson(json_lightstatus_brake, "is_changed");
434     if (is_changed) {
435         std::string lightstatus_brake_state = jh::getStringFromJson(json_lightstatus_brake, "state");
436         HMI_DEBUG("wm", "lightstatus_brake_state: %s", lightstatus_brake_state.c_str());
437
438         // Update state and emit event
439         if ("lightstatus_brake_off" == lightstatus_brake_state) {
440             this->crr_car_info_.lightstatus_brake_stt = false;
441             this->emitLightstatusBrakeOff();
442         }
443         else if ("lightstatus_brake_on" == lightstatus_brake_state) {
444             this->crr_car_info_.lightstatus_brake_stt = true;
445             this->emitLightstatusBrakeOn();
446         }
447         else {
448             reply("Unknown lightstatus brake state");
449             return;
450         }
451     }
452
453     // Check car state
454     json_object* json_car;
455     if (!json_object_object_get_ex(json_out, "car", &json_car)) {
456         reply("Not found key \"car\"");
457         return;
458     }
459
460     is_changed = jh::getBoolFromJson(json_car, "is_changed");
461     if (is_changed) {
462         std::string car_state = jh::getStringFromJson(json_car, "state");
463         HMI_DEBUG("wm", "car_state: %s", car_state.c_str());
464
465         // Emit car event
466         if ("car_stop" == car_state) {
467             this->crr_car_info_.car_stt = "stop";
468             this->emitCarStop();
469         }
470         else if ("car_run" == car_state) {
471             this->crr_car_info_.car_stt = "run";
472             this->emitCarRun();
473         }
474         else {
475             reply("Unknown car state");
476             return;
477         }
478     }
479
480     // Check lamp state
481     json_object* json_lamp;
482     if (!json_object_object_get_ex(json_out, "lamp", &json_lamp)) {
483         reply("Not found key \"lamp\"");
484         return;
485     }
486
487     is_changed = jh::getBoolFromJson(json_lamp, "is_changed");
488     if (is_changed) {
489         std::string lamp_state = jh::getStringFromJson(json_lamp, "state");
490         HMI_DEBUG("wm", "lamp_state: %s", lamp_state.c_str());
491
492         // Update state and emit event
493         if ("lamp_off" == lamp_state) {
494             this->crr_car_info_.headlamp_stt = false;
495             this->emitHeadlampOff();
496         }
497         else if ("lamp_on" == lamp_state) {
498             this->crr_car_info_.headlamp_stt = true;
499             this->emitHeadlampOn();
500         }
501         else {
502             reply("Unknown lamp state");
503             return;
504         }
505     }
506
507     // Get category
508     const char* category = nullptr;
509     std::string str_category;
510     if (nullptr != new_role) {
511         str_category = this->pm_.roleToCategory(new_role);
512         category = str_category.c_str();
513         HMI_DEBUG("wm", "role:%s category:%s", new_role, category);
514     }
515
516     // Update layout
517     if (this->lm_.updateLayout(json_out, new_role, category)) {
518         HMI_DEBUG("wm", "Layer is changed!!");
519
520         // Allocate surface
521         this->allocateSurface();
522     }
523     else {
524         HMI_DEBUG("wm", "All layer is NOT changed!!");
525     }
526
527     // Release json_object
528     json_object_put(json_out);
529
530     return;
531 }
532
533 void App::enqueue_flushdraw(int surface_id) {
534    this->check_flushdraw(surface_id);
535    HMI_DEBUG("wm", "Enqueuing EndDraw for surface_id %d", surface_id);
536    this->pending_end_draw.push_back(surface_id);
537 }
538
539 void App::check_flushdraw(int surface_id) {
540    auto i = std::find(std::begin(this->pending_end_draw),
541                       std::end(this->pending_end_draw), surface_id);
542    if (i != std::end(this->pending_end_draw)) {
543       auto n = this->lookup_name(surface_id);
544       HMI_ERROR("wm", "Application %s (%d) has pending EndDraw call(s)!",
545                n ? n->c_str() : "unknown-name", surface_id);
546       std::swap(this->pending_end_draw[std::distance(
547                    std::begin(this->pending_end_draw), i)],
548                 this->pending_end_draw.back());
549       this->pending_end_draw.resize(this->pending_end_draw.size() - 1);
550    }
551 }
552
553 void App::api_enddraw(char const *drawing_name) {
554    for (unsigned i = 0, iend = this->pending_end_draw.size(); i < iend; i++) {
555       auto n = this->lookup_name(this->pending_end_draw[i]);
556       if (n && *n == drawing_name) {
557          std::swap(this->pending_end_draw[i], this->pending_end_draw[iend - 1]);
558          this->pending_end_draw.resize(iend - 1);
559          this->activate(this->pending_end_draw[i]);
560          this->emit_flushdraw(drawing_name);
561       }
562    }
563 }
564
565 void App::api_ping() { this->dispatch_pending_events(); }
566
567 void App::send_event(char const *evname){
568    HMI_DEBUG("wm", "%s: %s", __func__, evname);
569
570    int ret = afb_event_push(this->map_afb_event[evname], nullptr);
571    if (ret != 0) {
572       HMI_DEBUG("wm", "afb_event_push failed: %m");
573    }
574 }
575
576 void App::send_event(char const *evname, char const *label){
577    HMI_DEBUG("wm", "%s: %s(%s)", __func__, evname, label);
578
579    json_object *j = json_object_new_object();
580    json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
581
582    int ret = afb_event_push(this->map_afb_event[evname], j);
583    if (ret != 0) {
584       HMI_DEBUG("wm", "afb_event_push failed: %m");
585    }
586 }
587
588 void App::send_event(char const *evname, char const *label, char const *area,
589                              int x, int y, int w, int h) {
590    HMI_DEBUG("wm", "%s: %s(%s, %s) x:%d y:%d w:%d h:%d",
591              __func__, evname, label, area, x, y, w, h);
592
593    json_object *j_rect = json_object_new_object();
594    json_object_object_add(j_rect, kKeyX,      json_object_new_int(x));
595    json_object_object_add(j_rect, kKeyY,      json_object_new_int(y));
596    json_object_object_add(j_rect, kKeyWidth,  json_object_new_int(w));
597    json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
598
599    json_object *j = json_object_new_object();
600    json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
601    json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area));
602    json_object_object_add(j, kKeyDrawingRect, j_rect);
603
604    int ret = afb_event_push(this->map_afb_event[evname], j);
605    if (ret != 0) {
606       HMI_DEBUG("wm", "afb_event_push failed: %m");
607    }
608 }
609
610 /**
611  * proxied events
612  */
613 void App::surface_created(uint32_t surface_id) {
614    auto layer_id = this->layers.get_layer_id(surface_id);
615    if (!layer_id) {
616       HMI_DEBUG("wm", "Newly created surfce %d is not associated with any layer!",
617                surface_id);
618       return;
619    }
620
621    HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", surface_id, *layer_id);
622
623    this->controller->layers[*layer_id]->add_surface(surface_id);
624    this->layout_commit();
625    // activate the main_surface right away
626    /*if (surface_id == static_cast<unsigned>(this->layers.main_surface)) {
627       HMI_DEBUG("wm", "Activating main_surface (%d)", surface_id);
628
629       this->api_activate_surface(
630          this->lookup_name(surface_id).value_or("unknown-name").c_str());
631    }*/
632 }
633
634 void App::surface_removed(uint32_t surface_id) {
635    HMI_DEBUG("wm", "surface_id is %u", surface_id);
636
637    // We cannot normally deactivate the main_surface, so be explicit
638    // about it:
639    if (int(surface_id) == this->layers.main_surface) {
640       this->deactivate_main_surface();
641    } else {
642       auto drawing_name = this->lookup_name(surface_id);
643       if (drawing_name) {
644          this->allocateWindowResource("deactivate", drawing_name->c_str(),
645                                       nullptr, nullptr,
646                                       [](const char*){});
647       }
648    }
649
650    this->id_alloc.remove_id(surface_id);
651    this->layers.remove_surface(surface_id);
652 }
653
654 void App::emit_activated(char const *label) {
655    this->send_event(kListEventName[Event_Active], label);
656 }
657
658 void App::emit_deactivated(char const *label) {
659    this->send_event(kListEventName[Event_Inactive], label);
660 }
661
662 void App::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h) {
663    this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
664 }
665
666 void App::emit_flushdraw(char const *label) {
667    this->send_event(kListEventName[Event_FlushDraw], label);
668 }
669
670 void App::emit_visible(char const *label, bool is_visible) {
671    this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
672 }
673
674 void App::emit_invisible(char const *label) {
675    return emit_visible(label, false);
676 }
677
678 void App::emit_visible(char const *label) { return emit_visible(label, true); }
679
680 void App::emitHeadlampOff() {
681     // Send HeadlampOff event for all application
682     this->send_event(kListEventName[Event_HeadlampOff]);
683 }
684
685 void App::emitHeadlampOn() {
686     // Send HeadlampOn event for all application
687     this->send_event(kListEventName[Event_HeadlampOn]);
688 }
689
690 void App::emitParkingBrakeOff() {
691     // Send ParkingBrakeOff event for all application
692     this->send_event(kListEventName[Event_ParkingBrakeOff]);
693 }
694
695 void App::emitParkingBrakeOn() {
696     // Send ParkingBrakeOn event for all application
697     this->send_event(kListEventName[Event_ParkingBrakeOn]);
698 }
699
700 void App::emitLightstatusBrakeOff() {
701     // Send LightstatusBrakeOff event for all application
702     this->send_event(kListEventName[Event_LightstatusBrakeOff]);
703 }
704
705 void App::emitLightstatusBrakeOn() {
706     // Send LightstatusBrakeOn event for all application
707     this->send_event(kListEventName[Event_LightstatusBrakeOn]);
708 }
709
710 void App::emitCarStop() {
711     // Send CarStop event for all application
712     this->send_event(kListEventName[Event_CarStop]);
713 }
714
715 void App::emitCarRun() {
716     // Send CarRun event for all application
717     this->send_event(kListEventName[Event_CarRun]);
718 }
719
720 result<int> App::api_request_surface(char const *drawing_name) {
721    auto lid = this->layers.get_layer_id(std::string(drawing_name));
722    if (!lid) {
723       /**
724        * register drawing_name as fallback and make it displayed.
725        */
726       lid = this->layers.get_layer_id(std::string("Fallback"));
727       HMI_DEBUG("wm", "%s is not registered in layers.json, then fallback as normal app", drawing_name);
728       if(!lid){
729           return Err<int>("Drawing name does not match any role, Fallback is disabled");
730       }
731    }
732
733    auto rname = this->lookup_id(drawing_name);
734    if (!rname) {
735       // name does not exist yet, allocate surface id...
736       auto id = int(this->id_alloc.generate_id(drawing_name));
737       this->layers.add_surface(id, *lid);
738
739       // set the main_surface[_name] here and now
740       if (!this->layers.main_surface_name.empty() &&
741           this->layers.main_surface_name == drawing_name) {
742          this->layers.main_surface = id;
743          HMI_DEBUG("wm", "Set main_surface id to %u", id);
744       }
745
746 #if 0 // @@@@@
747       // TODO:
748       // This process will be implemented in SystemManager
749       {
750           // Generate app id
751           auto id = int(this->app_id_alloc_.generate_id(drawing_name));
752           this->appname2appid_[drawing_name] = id;
753       }
754 #endif
755
756       // Set map of (role, surface_id)
757       std::string role = this->app2role_[std::string(drawing_name)];
758       this->role2surfaceid_[role] = id;
759
760       // Set map of (role, app)
761       // If the new app which has the same role which is had by existing app is requested,
762       // the role is given to the new app.
763       this->role2app_[role] = std::string(drawing_name);
764
765       return Ok<int>(id);
766    }
767
768    // Check currently registered drawing names if it is already there.
769    return Err<int>("Surface already present");
770 }
771
772 char const *App::api_request_surface(char const *drawing_name,
773                                      char const *ivi_id) {
774    ST();
775
776    auto lid = this->layers.get_layer_id(std::string(drawing_name));
777    unsigned sid = std::stol(ivi_id);
778
779    if (!lid) {
780       /**
781        * register drawing_name as fallback and make it displayed.
782        */
783       lid = this->layers.get_layer_id(std::string("Fallback"));
784       HMI_DEBUG("wm", "%s is not registered in layers.json, then fallback as normal app", drawing_name);
785       if(!lid){
786           return "Drawing name does not match any role, Fallback is disabled";
787       }
788    }
789
790    auto rname = this->lookup_id(drawing_name);
791
792    if (rname) {
793        return "Surface already present";
794    }
795
796    // register pair drawing_name and ivi_id
797    this->id_alloc.register_name_id(drawing_name, sid);
798    this->layers.add_surface(sid, *lid);
799
800    // this surface is already created
801    HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", sid, *lid);
802
803    this->controller->layers[*lid]->add_surface(sid);
804    this->layout_commit();
805
806    return nullptr;
807 }
808
809 result<json_object *> App::api_get_display_info() {
810    // Check controller
811    if (!this->controller) {
812       return Err<json_object *>("ivi_controller global not available");
813    }
814
815    // Set display info
816    compositor::size o_size = this->controller->output_size;
817    compositor::size p_size = this->controller->physical_size;
818
819    json_object *object = json_object_new_object();
820    json_object_object_add(object, kKeyWidthPixel,  json_object_new_int(o_size.w));
821    json_object_object_add(object, kKeyHeightPixel, json_object_new_int(o_size.h));
822    json_object_object_add(object, kKeyWidthMm,     json_object_new_int(p_size.w));
823    json_object_object_add(object, kKeyHeightMm,    json_object_new_int(p_size.h));
824
825    return Ok<json_object *>(object);
826 }
827
828 result<json_object *> App::api_get_area_info(char const *drawing_name) {
829    HMI_DEBUG("wm", "called");
830
831    // Check drawing name, surface/layer id
832    auto const &surface_id = this->lookup_id(drawing_name);
833    if (!surface_id) {
834       return Err<json_object *>("Surface does not exist");
835    }
836
837    if (!this->controller->surface_exists(*surface_id)) {
838       return Err<json_object *>("Surface does not exist in controller!");
839    }
840
841    auto layer_id = this->layers.get_layer_id(*surface_id);
842    if (!layer_id) {
843       return Err<json_object *>("Surface is not on any layer!");
844    }
845
846    auto o_state = *this->layers.get_layout_state(*surface_id);
847    if (o_state == nullptr) {
848       return Err<json_object *>("Could not find layer for surface");
849    }
850
851    // Set area rectangle
852    compositor::rect area_info = this->area_info[*surface_id];
853    json_object *object = json_object_new_object();
854    json_object_object_add(object, kKeyX,      json_object_new_int(area_info.x));
855    json_object_object_add(object, kKeyY,      json_object_new_int(area_info.y));
856    json_object_object_add(object, kKeyWidth,  json_object_new_int(area_info.w));
857    json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
858
859    return Ok<json_object *>(object);
860 }
861
862 result<json_object *> App::api_get_car_info(char const *label) {
863     HMI_DEBUG("wm", "called");
864
865     json_object *j_in  = nullptr;
866     json_object *j_out = nullptr;
867
868     if (0 == strcmp("parking_brake_status", label)) {
869         // Get parking brake status
870         json_bool val = this->crr_car_info_.parking_brake_stt;
871         j_in = json_object_new_boolean(val);
872     }
873     else if (0 == strcmp("accelerator.pedal.position", label)) {
874         // Get accelerator pedal position
875         double val = this->crr_car_info_.accel_pedal_pos;
876         j_in = json_object_new_double(val);
877     }
878     else if (0 == strcmp("car_state", label)) {
879         // Get car state
880         const char* val = this->crr_car_info_.car_stt;
881         j_in = json_object_new_string(val);
882     }
883     else if (0 == strcmp("lightstatus.brake", label)) {
884         // Get lightstatus brake status
885         json_bool val = this->crr_car_info_.lightstatus_brake_stt;
886         j_in = json_object_new_boolean(val);
887     }
888     else {
889        return Err<json_object *>("Car info does not exist");
890     }
891
892     // Create output object
893     j_out = json_object_new_object();
894     json_object_object_add(j_out, "value", j_in);
895
896     return Ok<json_object *>(j_out);
897 }
898
899 void App::activate(int id) {
900    auto ip = this->controller->sprops.find(id);
901    if (ip != this->controller->sprops.end()) {
902       this->controller->surfaces[id]->set_visibility(1);
903       char const *label =
904          this->lookup_name(id).value_or("unknown-name").c_str();
905
906       // FOR CES DEMO >>>
907       if ((0 == strcmp(label, "Radio"))
908           || (0 == strcmp(label, "MediaPlayer"))
909           || (0 == strcmp(label, "Music"))
910           || (0 == strcmp(label, "Navigation"))) {
911         for (auto i = surface_bg.begin(); i != surface_bg.end(); ++i) {
912             if (id == *i) {
913                // Remove id
914                this->surface_bg.erase(i);
915
916                // Remove from BG layer (999)
917                HMI_DEBUG("wm", "Remove %s(%d) from BG layer", label, id);
918                this->controller->layers[999]->remove_surface(id);
919
920                // Add to FG layer (1001)
921                HMI_DEBUG("wm", "Add %s(%d) to FG layer", label, id);
922                this->controller->layers[1001]->add_surface(id);
923
924                for (int j : this->surface_bg) {
925                  HMI_DEBUG("wm", "Stored id:%d", j);
926                }
927                break;
928             }
929          }
930       }
931       // <<< FOR CES DEMO
932       this->layout_commit();
933
934       this->emit_visible(label);
935       this->emit_activated(label);
936    }
937 }
938
939 void App::deactivate(int id) {
940    auto ip = this->controller->sprops.find(id);
941    if (ip != this->controller->sprops.end()) {
942       char const *label =
943          this->lookup_name(id).value_or("unknown-name").c_str();
944
945       // FOR CES DEMO >>>
946       if ((0 == strcmp(label, "Radio"))
947           || (0 == strcmp(label, "MediaPlayer"))
948           || (0 == strcmp(label, "Music"))
949           || (0 == strcmp(label, "Navigation"))) {
950
951          // Store id
952          this->surface_bg.push_back(id);
953
954          // Remove from FG layer (1001)
955          HMI_DEBUG("wm", "Remove %s(%d) from FG layer", label, id);
956          this->controller->layers[1001]->remove_surface(id);
957
958          // Add to BG layer (999)
959          HMI_DEBUG("wm", "Add %s(%d) to BG layer", label, id);
960          this->controller->layers[999]->add_surface(id);
961
962          for (int j : surface_bg) {
963             HMI_DEBUG("wm", "Stored id:%d", j);
964          }
965       }
966       else {
967          this->controller->surfaces[id]->set_visibility(0);
968       }
969       // <<< FOR CES DEMO
970
971       this->layout_commit();
972
973       this->emit_deactivated(label);
974       this->emit_invisible(label);
975    }
976 }
977
978 void App::deactivate(std::string role) {
979     std::string app = this->role2app_[role];
980     auto const &id = this->lookup_id(app.c_str());
981     if (!id) {
982       HMI_ERROR("wm", "Surface does not exist");
983       return;
984     }
985     HMI_DEBUG("wm", "Deactivate role:%s (app:%s)",
986               role.c_str(), app.c_str());
987
988     this->deactivate(*id);
989 }
990
991 void App::deactivate_main_surface() {
992    this->layers.main_surface = -1;
993    this->allocateWindowResource("deactivate", this->layers.main_surface_name.c_str(),
994                                 nullptr, nullptr,
995                                 [](const char*){});
996 }
997
998 /**
999  * controller_hooks
1000  */
1001 void controller_hooks::surface_created(uint32_t surface_id) {
1002    this->app->surface_created(surface_id);
1003 }
1004
1005 void controller_hooks::surface_removed(uint32_t surface_id) {
1006    this->app->surface_removed(surface_id);
1007 }
1008
1009 void controller_hooks::surface_visibility(uint32_t /*surface_id*/,
1010                                           uint32_t /*v*/) {}
1011
1012 void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/,
1013                                                      uint32_t /*x*/,
1014                                                      uint32_t /*y*/,
1015                                                      uint32_t /*w*/,
1016                                                      uint32_t /*h*/) {}
1017
1018 int App::allocateSurface() {
1019     HMI_DEBUG("wm", "Call");
1020
1021     // Get current/previous layers
1022     LayoutManager::TypeLayers crr_layers = this->lm_.getCurrentLayers();
1023     LayoutManager::TypeLayers prv_layers = this->lm_.getPreviousLayers();
1024
1025     // Update resource of all layers
1026     for (auto itr_layers = crr_layers.begin();
1027          itr_layers != crr_layers.end(); ++itr_layers) {
1028         // Get layer
1029         std::string layer = itr_layers->first;
1030         HMI_DEBUG("wm", "Try to update resource in %s layer", layer.c_str());
1031
1032         // If layout is changed, update resouce
1033         if (this->lm_.isLayoutChanged(layer.c_str())) {
1034             // Get current/previous layout
1035             LayoutManager::TypeLayouts crr_layout = itr_layers->second;
1036             LayoutManager::TypeLayouts prv_layout = prv_layers[layer];
1037
1038             // Get current/previous layout name
1039             std::string crr_layout_name = crr_layout.begin()->first;
1040             std::string prv_layout_name = prv_layout.begin()->first;
1041             HMI_DEBUG("wm", "layout name crr:%s prv:%s",
1042                       crr_layout_name.c_str(), prv_layout_name.c_str());
1043
1044             // Get current/previous ares
1045             LayoutManager::TypeAreas crr_areas = crr_layout[crr_layout_name];
1046             LayoutManager::TypeAreas prv_areas = prv_layout[prv_layout_name];
1047
1048             // Create previous displayed role list
1049             std::string prv_area_name;
1050             std::vector<std::string> prv_role_list;
1051             for (auto itr_areas = prv_areas.begin();
1052                  itr_areas != prv_areas.end(); ++itr_areas) {
1053                 prv_area_name = itr_areas->first;
1054                 prv_role_list.push_back(prv_areas[prv_area_name]["role"]);
1055                 HMI_DEBUG("wm", "previous displayed role:%s",
1056                           prv_areas[prv_area_name]["role"].c_str());
1057             }
1058
1059             // Allocate surface for each area
1060             std::string crr_area_name;
1061             std::string crr_role_name;
1062             LayoutManager::TypeRolCtg crr_rol_ctg;
1063             for (auto itr_areas = crr_areas.begin();
1064                  itr_areas != crr_areas.end(); ++itr_areas) {
1065                 crr_area_name = itr_areas->first;
1066                 crr_rol_ctg = itr_areas->second;
1067
1068                 // Get role of current area
1069                 if ("category" == crr_rol_ctg.begin()->first) {
1070                     // If current area have category
1071                     // Get category name
1072                     std::string crr_ctg = crr_rol_ctg.begin()->second;
1073
1074                     // Serch relevant role from previous displayed role list
1075                     for (auto itr_role = prv_role_list.begin();
1076                          itr_role != prv_role_list.end(); ++itr_role) {
1077                         std::string prv_ctg = this->pm_.roleToCategory((*itr_role).c_str());
1078                         if (crr_ctg == prv_ctg) {
1079                             // First discovered role is set to current role
1080                             crr_role_name = *itr_role;
1081
1082                             // Delete used role for other areas
1083                             // which have same category
1084                             prv_role_list.erase(itr_role);
1085
1086                             break;
1087                         }
1088                     }
1089                 }
1090                 else {
1091                     crr_role_name = itr_areas->second["role"];
1092                 }
1093                 HMI_DEBUG("wm", "Allocate surface for area:%s role:%s",
1094                           crr_area_name.c_str(), crr_role_name.c_str());
1095
1096                 // Deactivate non-displayed role
1097                 std::string prv_role_name;
1098                 if (crr_layout_name == prv_layout_name) {
1099                     HMI_DEBUG("wm", "Current layout is same with previous");
1100
1101                     // Deactivate previous role in same area
1102                     // if it is different with current
1103                     prv_role_name = prv_areas[crr_area_name]["role"];
1104                     if (crr_role_name != prv_role_name) {
1105                         this->deactivate(prv_role_name);
1106                     }
1107                 }
1108                 else {
1109                     HMI_DEBUG("wm", "Current layout is different with previous");
1110
1111                     if ("none" != prv_layout_name) {
1112                         // Deactivate previous role in all area in previous layout
1113                         // if it is different with current role
1114                         for(auto itr = prv_areas.begin(); itr != prv_areas.end(); ++itr) {
1115                             prv_role_name = itr->second["role"].c_str();
1116                             if (crr_role_name != prv_role_name) {
1117                                 this->deactivate(prv_role_name);
1118                             }
1119                         }
1120                     }
1121                 }
1122
1123                 // Set surface for displayed role
1124                 if ("none" != crr_layout_name) {
1125                     // If current layout is not "none",
1126                     // set surface for current role
1127                     this->setSurfaceSize(crr_role_name.c_str(), crr_area_name.c_str());
1128
1129                     // TODO:
1130                     // This API is workaround.
1131                     // Resource manager should manage each resource infomations
1132                     // according to architecture document.
1133                     this->lm_.updateArea(layer.c_str(), crr_role_name.c_str(), crr_area_name.c_str());
1134                 }
1135             }
1136         }
1137     }
1138     return 0;
1139 }
1140
1141 void App::setSurfaceSize(const char* role, const char* area) {
1142     HMI_DEBUG("wm", "role:%s area:%s", role, area);
1143
1144     // Get size of current area
1145     compositor::rect size = this->lm_.getAreaSize(area);
1146
1147     // Set destination to the display rectangle
1148     int surface_id = this->role2surfaceid_[role];
1149
1150     if (!this->controller->surface_exists(surface_id)) {
1151         // Block until all pending request are processed by wayland display server
1152         // because waiting for the surface of new app is created
1153         this->display->roundtrip();
1154     }
1155     auto &s = this->controller->surfaces[surface_id];
1156     s->set_destination_rectangle(size.x, size.y, size.w, size.h);
1157     this->layout_commit();
1158
1159     // Update area information
1160     this->area_info[surface_id].x = size.x;
1161     this->area_info[surface_id].y = size.y;
1162     this->area_info[surface_id].w = size.w;
1163     this->area_info[surface_id].h = size.h;
1164     HMI_DEBUG("wm", "Surface rect { %d, %d, %d, %d }",
1165               size.x, size.y, size.w, size.h);
1166
1167     // Emit syncDraw event
1168     const char* app = this->role2app_[role].c_str();
1169     this->emit_syncdraw(app, area,
1170                         size.x, size.y, size.w, size.h);
1171
1172     // Enqueue flushDraw event
1173     this->enqueue_flushdraw(surface_id);
1174 }
1175
1176 void App::setAccelPedalPos(double val) {
1177     this->crr_car_info_.accel_pedal_pos = val;
1178 }
1179
1180 extern const char* kDefaultAppDb;
1181 int App::loadAppDb() {
1182     HMI_DEBUG("wm", "Call");
1183
1184     // Get afm application installed dir
1185     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1186     HMI_DEBUG("wm", "afm_app_install_dir:%s", afm_app_install_dir);
1187
1188     std::string file_name;
1189     if (!afm_app_install_dir) {
1190         HMI_ERROR("wm", "AFM_APP_INSTALL_DIR is not defined");
1191     }
1192     else {
1193         file_name = std::string(afm_app_install_dir) + std::string("/etc/app.db");
1194     }
1195
1196     // Load app.db
1197     json_object* json_obj;
1198     int ret = jh::inputJsonFilie(file_name.c_str(), &json_obj);
1199     if (0 > ret) {
1200         HMI_ERROR("wm", "Could not open app.db, so use default role information");
1201         json_obj = json_tokener_parse(kDefaultAppDb);
1202     }
1203     HMI_DEBUG("wm", "json_obj dump:%s", json_object_get_string(json_obj));
1204
1205     // Perse apps
1206     HMI_DEBUG("wm", "Perse apps");
1207     json_object* json_cfg;
1208     if (!json_object_object_get_ex(json_obj, "apps", &json_cfg)) {
1209         HMI_ERROR("wm", "Parse Error!!");
1210         return -1;
1211     }
1212
1213     int len = json_object_array_length(json_cfg);
1214     HMI_DEBUG("wm", "json_cfg len:%d", len);
1215     HMI_DEBUG("wm", "json_cfg dump:%s", json_object_get_string(json_cfg));
1216
1217     for (int i=0; i<len; i++) {
1218         json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
1219         HMI_DEBUG("wm", "> json_tmp dump:%s", json_object_get_string(json_tmp));
1220
1221         const char* app = jh::getStringFromJson(json_tmp, "name");
1222         if (nullptr == app) {
1223             HMI_ERROR("wm", "Parse Error!!");
1224             return -1;
1225         }
1226         HMI_DEBUG("wm", "> app:%s", app);
1227
1228         const char* role = jh::getStringFromJson(json_tmp, "role");
1229         if (nullptr == role) {
1230             HMI_ERROR("wm", "Parse Error!!");
1231             return -1;
1232         }
1233         HMI_DEBUG("wm", "> role:%s", role);
1234
1235         this->app2role_[app] = std::string(role);
1236     }
1237
1238     // Check
1239     for(auto itr = this->app2role_.begin();
1240       itr != this->app2role_.end(); ++itr) {
1241         HMI_DEBUG("wm", "app:%s role:%s",
1242                   itr->first.c_str(), itr->second.c_str());
1243     }
1244
1245     // Release json_object
1246     json_object_put(json_obj);
1247
1248     return 0;
1249 }
1250
1251
1252 const char* kDefaultAppDb = "{ \
1253     \"apps\": [ \
1254         { \
1255             \"name\": \"HomeScreen\", \
1256             \"role\": \"homescreen\" \
1257         }, \
1258         { \
1259             \"name\": \"Music\", \
1260             \"role\": \"music\" \
1261         }, \
1262         { \
1263             \"name\": \"MediaPlayer\", \
1264             \"role\": \"music\" \
1265         }, \
1266         { \
1267             \"name\": \"Video\", \
1268             \"role\": \"video\" \
1269         }, \
1270         { \
1271             \"name\": \"VideoPlayer\", \
1272             \"role\": \"video\" \
1273         }, \
1274         { \
1275             \"name\": \"WebBrowser\", \
1276             \"role\": \"browser\" \
1277         }, \
1278         { \
1279             \"name\": \"Radio\", \
1280             \"role\": \"radio\" \
1281         }, \
1282         { \
1283             \"name\": \"Phone\", \
1284             \"role\": \"phone\" \
1285         }, \
1286         { \
1287             \"name\": \"Navigation\", \
1288             \"role\": \"map\" \
1289         }, \
1290         { \
1291             \"name\": \"HVAC\", \
1292             \"role\": \"hvac\" \
1293         }, \
1294         { \
1295             \"name\": \"Settings\", \
1296             \"role\": \"settings\" \
1297         }, \
1298         { \
1299             \"name\": \"Dashboard\", \
1300             \"role\": \"dashboard\" \
1301         }, \
1302         { \
1303             \"name\": \"POI\", \
1304             \"role\": \"poi\" \
1305         }, \
1306         { \
1307             \"name\": \"Mixer\", \
1308             \"role\": \"mixer\" \
1309         } \
1310     ] \
1311 }";
1312
1313
1314 }  // namespace wm