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