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