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