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