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