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