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