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