20f5b56cbb6561b6b4bf518179128b1a88990d74
[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 (nullptr == drawing_area) {
291                 new_area = "normal";
292             }
293             else if (0 == strcmp("normal.full", drawing_area)) {
294                 new_area = "normal";
295             }
296             else if (0 == strcmp("homescreen", new_role)) {
297                 // Now homescreen specifies "normalfull"
298                 new_area = "full";
299             }
300             else {
301                 new_area = "normal";
302             }
303             HMI_DEBUG("wm", "drawing_area:%s, new_area: %s", drawing_area, new_area);
304         }
305     }
306     else if (0 == strcmp("deactivate", event)) {
307         // TODO:
308         // This process will be removed
309         // because the applications will specify role instead of drawing_name
310         {
311             if ((nullptr == role) || (0 == strcmp("", role))) {
312                 HMI_DEBUG("wm", "Role is not specified, so get by using app name");
313                 new_role = this->app2role_[drawing_name].c_str();
314             }
315             else {
316                 new_role = role;
317             }
318             HMI_DEBUG("wm", "drawing_name:%s, new_role: %s", drawing_name, new_role);
319         }
320         new_area = "";
321     }
322
323     // TODO:
324     // Check role
325
326     // TODO:
327     // If event is "activate" and area is not specifid,
328     // get default value by using role
329
330     // Check Policy
331     json_object* json_in = json_object_new_object();
332     json_object* json_out = json_object_new_object();
333     json_object_object_add(json_in, "event", json_object_new_string(event));
334
335     if (nullptr != new_role) {
336         json_object_object_add(json_in, "role", json_object_new_string(new_role));
337     }
338     if (nullptr != new_area) {
339         json_object_object_add(json_in, "area", json_object_new_string(new_area));
340     }
341
342     int ret = this->pm_.checkPolicy(json_in, &json_out);
343     if (0 > ret) {
344         reply("Error checkPolicy()");
345         return;
346     }
347     else {
348         HMI_DEBUG("wm", "result: %s", json_object_get_string(json_out));
349     }
350
351     // Release json_object
352     json_object_put(json_in);
353
354     // Cat state
355     json_object* json_car;
356     if (!json_object_object_get_ex(json_out, "car", &json_car)) {
357         reply("Not found key \"car\"");
358         return;
359     }
360
361     json_bool is_changed;
362     is_changed = jh::getBoolFromJson(json_car, "is_changed");
363     if (is_changed) {
364         // Update car state
365         std::string car_state = jh::getStringFromJson(json_car, "state");
366         HMI_DEBUG("wm", "car_state: %s", car_state.c_str());
367
368         // Emit car event
369         if ("car_stop" == car_state) {
370             this->emitCarStop();
371         }
372         else if ("car_run" == car_state) {
373             this->emitCarRun();
374         }
375         else {
376             reply("Unknown car state");
377             return;
378         }
379     }
380
381     // Lamp state
382     json_object* json_lamp;
383     if (!json_object_object_get_ex(json_out, "lamp", &json_lamp)) {
384         reply("Not found key \"lamp\"");
385         return;
386     }
387
388     is_changed = jh::getBoolFromJson(json_lamp, "is_changed");
389     if (is_changed) {
390         // Update car state
391         std::string lamp_state = jh::getStringFromJson(json_lamp, "state");
392         HMI_DEBUG("wm", "lamp_state: %s", lamp_state.c_str());
393
394         // Emit lamp event
395         if ("lamp_off" == lamp_state) {
396             this->emitHeadlampOff();
397         }
398         else if ("lamp_on" == lamp_state) {
399             this->emitHeadlampOn();
400         }
401         else {
402             reply("Unknown lamp state");
403             return;
404         }
405     }
406
407     // Get category
408     const char* category = nullptr;
409     std::string str_category;
410     if (nullptr != new_role) {
411         str_category = this->pm_.roleToCategory(new_role);
412         category = str_category.c_str();
413         HMI_DEBUG("wm", "role:%s category:%s", new_role, category);
414     }
415
416     // Update layout
417     if (this->lm_.updateLayout(json_out, new_role, category)) {
418         HMI_DEBUG("wm", "Layer is changed!!");
419
420         // Allocate surface
421         this->allocateSurface();
422     }
423     else {
424         HMI_DEBUG("wm", "All layer is NOT changed!!");
425     }
426
427     // Release json_object
428     json_object_put(json_out);
429
430     return;
431 }
432
433 void App::enqueue_flushdraw(int surface_id) {
434    this->check_flushdraw(surface_id);
435    HMI_DEBUG("wm", "Enqueuing EndDraw for surface_id %d", surface_id);
436    this->pending_end_draw.push_back(surface_id);
437 }
438
439 void App::check_flushdraw(int surface_id) {
440    auto i = std::find(std::begin(this->pending_end_draw),
441                       std::end(this->pending_end_draw), surface_id);
442    if (i != std::end(this->pending_end_draw)) {
443       auto n = this->lookup_name(surface_id);
444       HMI_ERROR("wm", "Application %s (%d) has pending EndDraw call(s)!",
445                n ? n->c_str() : "unknown-name", surface_id);
446       std::swap(this->pending_end_draw[std::distance(
447                    std::begin(this->pending_end_draw), i)],
448                 this->pending_end_draw.back());
449       this->pending_end_draw.resize(this->pending_end_draw.size() - 1);
450    }
451 }
452
453 void App::api_enddraw(char const *drawing_name) {
454    for (unsigned i = 0, iend = this->pending_end_draw.size(); i < iend; i++) {
455       auto n = this->lookup_name(this->pending_end_draw[i]);
456       if (n && *n == drawing_name) {
457          std::swap(this->pending_end_draw[i], this->pending_end_draw[iend - 1]);
458          this->pending_end_draw.resize(iend - 1);
459          this->activate(this->pending_end_draw[i]);
460          this->emit_flushdraw(drawing_name);
461       }
462    }
463 }
464
465 void App::api_ping() { this->dispatch_pending_events(); }
466
467 void App::send_event(char const *evname){
468    HMI_DEBUG("wm", "%s: %s", __func__, evname);
469
470    int ret = afb_event_push(this->map_afb_event[evname], nullptr);
471    if (ret != 0) {
472       HMI_DEBUG("wm", "afb_event_push failed: %m");
473    }
474 }
475
476 void App::send_event(char const *evname, char const *label){
477    HMI_DEBUG("wm", "%s: %s(%s)", __func__, evname, label);
478
479    json_object *j = json_object_new_object();
480    json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
481
482    int ret = afb_event_push(this->map_afb_event[evname], j);
483    if (ret != 0) {
484       HMI_DEBUG("wm", "afb_event_push failed: %m");
485    }
486 }
487
488 void App::send_event(char const *evname, char const *label, char const *area,
489                              int x, int y, int w, int h) {
490    HMI_DEBUG("wm", "%s: %s(%s, %s) x:%d y:%d w:%d h:%d",
491              __func__, evname, label, area, x, y, w, h);
492
493    json_object *j_rect = json_object_new_object();
494    json_object_object_add(j_rect, kKeyX,      json_object_new_int(x));
495    json_object_object_add(j_rect, kKeyY,      json_object_new_int(y));
496    json_object_object_add(j_rect, kKeyWidth,  json_object_new_int(w));
497    json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
498
499    json_object *j = json_object_new_object();
500    json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
501    json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area));
502    json_object_object_add(j, kKeyDrawingRect, j_rect);
503
504    int ret = afb_event_push(this->map_afb_event[evname], j);
505    if (ret != 0) {
506       HMI_DEBUG("wm", "afb_event_push failed: %m");
507    }
508 }
509
510 /**
511  * proxied events
512  */
513 void App::surface_created(uint32_t surface_id) {
514    auto layer_id = this->layers.get_layer_id(surface_id);
515    if (!layer_id) {
516       HMI_DEBUG("wm", "Newly created surfce %d is not associated with any layer!",
517                surface_id);
518       return;
519    }
520
521    HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", surface_id, *layer_id);
522
523    this->controller->layers[*layer_id]->add_surface(surface_id);
524    this->layout_commit();
525    // activate the main_surface right away
526    /*if (surface_id == static_cast<unsigned>(this->layers.main_surface)) {
527       HMI_DEBUG("wm", "Activating main_surface (%d)", surface_id);
528
529       this->api_activate_surface(
530          this->lookup_name(surface_id).value_or("unknown-name").c_str());
531    }*/
532 }
533
534 void App::surface_removed(uint32_t surface_id) {
535    HMI_DEBUG("wm", "surface_id is %u", surface_id);
536
537    // We cannot normally deactivate the main_surface, so be explicit
538    // about it:
539    if (int(surface_id) == this->layers.main_surface) {
540       this->deactivate_main_surface();
541    } else {
542       auto drawing_name = this->lookup_name(surface_id);
543       if (drawing_name) {
544          this->allocateWindowResource("deactivate", drawing_name->c_str(),
545                                       nullptr, nullptr,
546                                       [](const char*){});
547       }
548    }
549
550    this->id_alloc.remove_id(surface_id);
551    this->layers.remove_surface(surface_id);
552 }
553
554 void App::emit_activated(char const *label) {
555    this->send_event(kListEventName[Event_Active], label);
556 }
557
558 void App::emit_deactivated(char const *label) {
559    this->send_event(kListEventName[Event_Inactive], label);
560 }
561
562 void App::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h) {
563    this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
564 }
565
566 void App::emit_flushdraw(char const *label) {
567    this->send_event(kListEventName[Event_FlushDraw], label);
568 }
569
570 void App::emit_visible(char const *label, bool is_visible) {
571    this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
572 }
573
574 void App::emit_invisible(char const *label) {
575    return emit_visible(label, false);
576 }
577
578 void App::emit_visible(char const *label) { return emit_visible(label, true); }
579
580 void App::emitHeadlampOff() {
581     // Send HeadlampOff event for all application
582     this->send_event(kListEventName[Event_HeadlampOff]);
583 }
584
585 void App::emitHeadlampOn() {
586     // Send HeadlampOn event for all application
587     this->send_event(kListEventName[Event_HeadlampOn]);
588 }
589
590 void App::emitCarStop() {
591     // Send CarStop event for all application
592     this->send_event(kListEventName[Event_CarStop]);
593 }
594
595 void App::emitCarRun() {
596     // Send CarRun event for all application
597     this->send_event(kListEventName[Event_CarRun]);
598 }
599
600 result<int> App::api_request_surface(char const *drawing_name) {
601    auto lid = this->layers.get_layer_id(std::string(drawing_name));
602    if (!lid) {
603       /**
604        * register drawing_name as fallback and make it displayed.
605        */
606       lid = this->layers.get_layer_id(std::string("Fallback"));
607       HMI_DEBUG("wm", "%s is not registered in layers.json, then fallback as normal app", drawing_name);
608       if(!lid){
609           return Err<int>("Drawing name does not match any role, Fallback is disabled");
610       }
611    }
612
613    auto rname = this->lookup_id(drawing_name);
614    if (!rname) {
615       // name does not exist yet, allocate surface id...
616       auto id = int(this->id_alloc.generate_id(drawing_name));
617       this->layers.add_surface(id, *lid);
618
619       // set the main_surface[_name] here and now
620       if (!this->layers.main_surface_name.empty() &&
621           this->layers.main_surface_name == drawing_name) {
622          this->layers.main_surface = id;
623          HMI_DEBUG("wm", "Set main_surface id to %u", id);
624       }
625
626 #if 0 // @@@@@
627       // TODO:
628       // This process will be implemented in SystemManager
629       {
630           // Generate app id
631           auto id = int(this->app_id_alloc_.generate_id(drawing_name));
632           this->appname2appid_[drawing_name] = id;
633       }
634 #endif
635
636       // Set map of (role, surface_id)
637       std::string role = this->app2role_[std::string(drawing_name)];
638       this->role2surfaceid_[role] = id;
639
640       return Ok<int>(id);
641    }
642
643    // Check currently registered drawing names if it is already there.
644    return Err<int>("Surface already present");
645 }
646
647 char const *App::api_request_surface(char const *drawing_name,
648                                      char const *ivi_id) {
649    ST();
650
651    auto lid = this->layers.get_layer_id(std::string(drawing_name));
652    unsigned sid = std::stol(ivi_id);
653
654    if (!lid) {
655       /**
656        * register drawing_name as fallback and make it displayed.
657        */
658       lid = this->layers.get_layer_id(std::string("Fallback"));
659       HMI_DEBUG("wm", "%s is not registered in layers.json, then fallback as normal app", drawing_name);
660       if(!lid){
661           return "Drawing name does not match any role, Fallback is disabled";
662       }
663    }
664
665    auto rname = this->lookup_id(drawing_name);
666
667    if (rname) {
668        return "Surface already present";
669    }
670
671    // register pair drawing_name and ivi_id
672    this->id_alloc.register_name_id(drawing_name, sid);
673    this->layers.add_surface(sid, *lid);
674
675    // this surface is already created
676    HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", sid, *lid);
677
678    this->controller->layers[*lid]->add_surface(sid);
679    this->layout_commit();
680
681    return nullptr;
682 }
683
684 result<json_object *> App::api_get_display_info() {
685    // Check controller
686    if (!this->controller) {
687       return Err<json_object *>("ivi_controller global not available");
688    }
689
690    // Set display info
691    compositor::size o_size = this->controller->output_size;
692    compositor::size p_size = this->controller->physical_size;
693
694    json_object *object = json_object_new_object();
695    json_object_object_add(object, kKeyWidthPixel,  json_object_new_int(o_size.w));
696    json_object_object_add(object, kKeyHeightPixel, json_object_new_int(o_size.h));
697    json_object_object_add(object, kKeyWidthMm,     json_object_new_int(p_size.w));
698    json_object_object_add(object, kKeyHeightMm,    json_object_new_int(p_size.h));
699
700    return Ok<json_object *>(object);
701 }
702
703 result<json_object *> App::api_get_area_info(char const *drawing_name) {
704    HMI_DEBUG("wm", "called");
705
706    // Check drawing name, surface/layer id
707    auto const &surface_id = this->lookup_id(drawing_name);
708    if (!surface_id) {
709       return Err<json_object *>("Surface does not exist");
710    }
711
712    if (!this->controller->surface_exists(*surface_id)) {
713       return Err<json_object *>("Surface does not exist in controller!");
714    }
715
716    auto layer_id = this->layers.get_layer_id(*surface_id);
717    if (!layer_id) {
718       return Err<json_object *>("Surface is not on any layer!");
719    }
720
721    auto o_state = *this->layers.get_layout_state(*surface_id);
722    if (o_state == nullptr) {
723       return Err<json_object *>("Could not find layer for surface");
724    }
725
726    struct LayoutState &state = *o_state;
727    if ((state.main != *surface_id) && (state.sub != *surface_id)) {
728       return Err<json_object *>("Surface is inactive");
729    }
730
731    // Set area rectangle
732    compositor::rect area_info = this->area_info[*surface_id];
733    json_object *object = json_object_new_object();
734    json_object_object_add(object, kKeyX,      json_object_new_int(area_info.x));
735    json_object_object_add(object, kKeyY,      json_object_new_int(area_info.y));
736    json_object_object_add(object, kKeyWidth,  json_object_new_int(area_info.w));
737    json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
738
739    return Ok<json_object *>(object);
740 }
741
742 void App::activate(int id) {
743    auto ip = this->controller->sprops.find(id);
744    if (ip != this->controller->sprops.end()) {
745       this->controller->surfaces[id]->set_visibility(1);
746       char const *label =
747          this->lookup_name(id).value_or("unknown-name").c_str();
748
749       // FOR CES DEMO >>>
750       if ((0 == strcmp(label, "Radio"))
751           || (0 == strcmp(label, "MediaPlayer"))
752           || (0 == strcmp(label, "Music"))
753           || (0 == strcmp(label, "Navigation"))) {
754         for (auto i = surface_bg.begin(); i != surface_bg.end(); ++i) {
755             if (id == *i) {
756                // Remove id
757                this->surface_bg.erase(i);
758
759                // Remove from BG layer (999)
760                HMI_DEBUG("wm", "Remove %s(%d) from BG layer", label, id);
761                this->controller->layers[999]->remove_surface(id);
762
763                // Add to FG layer (1001)
764                HMI_DEBUG("wm", "Add %s(%d) to FG layer", label, id);
765                this->controller->layers[1001]->add_surface(id);
766
767                for (int j : this->surface_bg) {
768                  HMI_DEBUG("wm", "Stored id:%d", j);
769                }
770                break;
771             }
772          }
773       }
774       // <<< FOR CES DEMO
775       this->layout_commit();
776
777       this->emit_visible(label);
778       this->emit_activated(label);
779    }
780 }
781
782 void App::deactivate(int id) {
783    auto ip = this->controller->sprops.find(id);
784    if (ip != this->controller->sprops.end()) {
785       char const *label =
786          this->lookup_name(id).value_or("unknown-name").c_str();
787
788       // FOR CES DEMO >>>
789       if ((0 == strcmp(label, "Radio"))
790           || (0 == strcmp(label, "MediaPlayer"))
791           || (0 == strcmp(label, "Music"))
792           || (0 == strcmp(label, "Navigation"))) {
793
794          // Store id
795          this->surface_bg.push_back(id);
796
797          // Remove from FG layer (1001)
798          HMI_DEBUG("wm", "Remove %s(%d) from FG layer", label, id);
799          this->controller->layers[1001]->remove_surface(id);
800
801          // Add to BG layer (999)
802          HMI_DEBUG("wm", "Add %s(%d) to BG layer", label, id);
803          this->controller->layers[999]->add_surface(id);
804
805          for (int j : surface_bg) {
806             HMI_DEBUG("wm", "Stored id:%d", j);
807          }
808       }
809       else {
810          this->controller->surfaces[id]->set_visibility(0);
811       }
812       // <<< FOR CES DEMO
813
814       this->emit_deactivated(label);
815       this->emit_invisible(label);
816    }
817 }
818
819 void App::deactivate(std::string role) {
820     std::string app = this->roleToApp(role);
821     auto const &id = this->lookup_id(app.c_str());
822     if (!id) {
823       HMI_ERROR("wm", "Surface does not exist");
824       return;
825     }
826     HMI_DEBUG("wm", "Deactivate role:%s (app:%s)",
827               role.c_str(), app.c_str());
828
829     this->deactivate(*id);
830 }
831
832 void App::deactivate_main_surface() {
833    this->layers.main_surface = -1;
834    this->allocateWindowResource("deactivate", this->layers.main_surface_name.c_str(),
835                                 nullptr, nullptr,
836                                 [](const char*){});
837 }
838
839 /**
840  * controller_hooks
841  */
842 void controller_hooks::surface_created(uint32_t surface_id) {
843    this->app->surface_created(surface_id);
844 }
845
846 void controller_hooks::surface_removed(uint32_t surface_id) {
847    this->app->surface_removed(surface_id);
848 }
849
850 void controller_hooks::surface_visibility(uint32_t /*surface_id*/,
851                                           uint32_t /*v*/) {}
852
853 void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/,
854                                                      uint32_t /*x*/,
855                                                      uint32_t /*y*/,
856                                                      uint32_t /*w*/,
857                                                      uint32_t /*h*/) {}
858
859 int App::allocateSurface() {
860     HMI_DEBUG("wm", "Call");
861
862     // Get current/previous layers
863     LayoutManager::TypeLayers crr_layers = this->lm_.getCurrentLayers();
864     LayoutManager::TypeLayers prv_layers = this->lm_.getPreviousLayers();
865
866     // Update resource of all layers
867     for (auto itr_layers = crr_layers.begin();
868          itr_layers != crr_layers.end(); ++itr_layers) {
869         // Get layer
870         std::string layer = itr_layers->first;
871         HMI_DEBUG("wm", "Update resource in %s layer", layer.c_str());
872
873         // If layout is changed, update resouce
874         if (this->lm_.isLayoutChanged(layer.c_str())) {
875             // Get current/previous layout
876             LayoutManager::TypeLayouts crr_layout = itr_layers->second;
877             LayoutManager::TypeLayouts prv_layout = prv_layers[layer];
878
879             // Get current/previous layout name
880             std::string crr_layout_name = crr_layout.begin()->first;
881             std::string prv_layout_name = prv_layout.begin()->first;
882             HMI_DEBUG("wm", "layout name crr:%s prv:%s",
883                       crr_layout_name.c_str(), prv_layout_name.c_str());
884
885             // Get current/previous ares
886             LayoutManager::TypeAreas crr_areas = crr_layout[crr_layout_name];
887             LayoutManager::TypeAreas prv_areas = prv_layout[prv_layout_name];
888
889             // Create previous displayed role list
890             std::string prv_area_name;
891             std::vector<std::string> prv_role_list;
892             for (auto itr_areas = prv_areas.begin();
893                  itr_areas != prv_areas.end(); ++itr_areas) {
894                 prv_area_name = itr_areas->first;
895                 prv_role_list.push_back(prv_areas[prv_area_name]["role"]);
896                 HMI_DEBUG("wm", "previous displayed role:%s",
897                           prv_areas[prv_area_name]["role"].c_str());
898             }
899
900             // Allocate surface for each area
901             std::string crr_area_name;
902             std::string crr_role_name;
903             LayoutManager::TypeRolCtg crr_rol_ctg;
904             for (auto itr_areas = crr_areas.begin();
905                  itr_areas != crr_areas.end(); ++itr_areas) {
906                 crr_area_name = itr_areas->first;
907                 crr_rol_ctg = itr_areas->second;
908
909                 // Get role of current area
910                 if ("category" == crr_rol_ctg.begin()->first) {
911                     // If current area have category
912                     // Get category name
913                     std::string crr_ctg = crr_rol_ctg.begin()->second;
914
915                     // Serch relevant role fron previous displayed role list
916                     for (auto itr_role = prv_role_list.begin();
917                          itr_role != prv_role_list.end(); ++itr_role) {
918                         std::string prv_ctg = this->pm_.roleToCategory((*itr_role).c_str());
919                         if (crr_ctg == prv_ctg) {
920                             // First discovered role is set to current role
921                             crr_role_name = *itr_role;
922
923                             // Delete used role for other areas
924                             // which have same category
925                             prv_role_list.erase(itr_role);
926
927                             break;
928                         }
929                     }
930                 }
931                 else {
932                     crr_role_name = itr_areas->second["role"];
933                 }
934                 HMI_DEBUG("wm", "Allocate surface for area:%s role:%s",
935                           crr_area_name.c_str(), crr_role_name.c_str());
936
937                 // Deactivate non-displayed role
938                 std::string prv_role_name;
939                 if (crr_layout_name == prv_layout_name) {
940                     HMI_DEBUG("wm", "Current layout is same with previous");
941
942                     // Deactivate previous role in same area
943                     // if it is different with current
944                     prv_role_name = prv_areas[crr_area_name]["role"];
945                     if (crr_role_name != prv_role_name) {
946                         this->deactivate(prv_role_name);
947                     }
948                 }
949                 else {
950                     HMI_DEBUG("wm", "Current layout is different with previous");
951
952                     if ("none" != prv_layout_name) {
953                         // Deactivate previous role in all area in previous layout
954                         // if it is different with current role
955                         for(auto itr = prv_areas.begin(); itr != prv_areas.end(); ++itr) {
956                             prv_role_name = itr->second["role"].c_str();
957                             if (crr_role_name != prv_role_name) {
958                                 this->deactivate(prv_role_name);
959                             }
960                         }
961                     }
962                 }
963
964                 // Set surface for displayed role
965                 if ("none" != crr_layout_name) {
966                     // If current layout is not "none",
967                     // set surface for current role
968                     this->setSurfaceSize(crr_role_name.c_str(), crr_area_name.c_str());
969
970                     // TODO:
971                     // This API is workaround.
972                     // Resource manager should manage each resource infomations
973                     // according to architecture document.
974                     this->lm_.updateArea(layer.c_str(), crr_role_name.c_str(), crr_area_name.c_str());
975                 }
976             }
977         }
978     }
979     return 0;
980 }
981
982 void App::setSurfaceSize(const char* role, const char* area) {
983     HMI_DEBUG("wm", "role:%s area:%s", role, area);
984
985     // Get size of current area
986     compositor::rect size = this->lm_.getAreaSize(area);
987
988     // Set destination to the display rectangle
989     int surface_id = this->role2surfaceid_[role];
990     auto &s = this->controller->surfaces[surface_id];
991     s->set_destination_rectangle(size.x, size.y, size.w, size.h);
992     this->layout_commit();
993
994     // Update area information
995     this->area_info[surface_id].x = size.x;
996     this->area_info[surface_id].y = size.y;
997     this->area_info[surface_id].w = size.w;
998     this->area_info[surface_id].h = size.h;
999     HMI_DEBUG("wm", "Surface rect { %d, %d, %d, %d }",
1000               size.x, size.y, size.w, size.h);
1001
1002     // Emit syncDraw event
1003     const char* app = this->roleToApp(role).c_str();
1004     this->emit_syncdraw(app, area,
1005                         size.x, size.y, size.w, size.h);
1006
1007     // Enqueue flushDraw event
1008     this->enqueue_flushdraw(surface_id);
1009 }
1010
1011 std::string App::roleToApp(std::string role) {
1012     HMI_DEBUG("wm", "Call");
1013
1014     for (auto itr = this->app2role_.begin();
1015          itr != this->app2role_.end(); itr++) {
1016         if (role == itr->second) {
1017             return itr->first;
1018         }
1019     }
1020     return std::string("none");
1021 }
1022
1023 extern const char* kDefaultAppDb;
1024 int App::loadAppDb() {
1025     HMI_DEBUG("wm", "Call");
1026
1027     // Get afm application installed dir
1028     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1029     HMI_DEBUG("wm", "afm_app_install_dir:%s", afm_app_install_dir);
1030
1031     std::string file_name;
1032     if (!afm_app_install_dir) {
1033         HMI_ERROR("wm", "AFM_APP_INSTALL_DIR is not defined");
1034     }
1035     else {
1036         file_name = std::string(afm_app_install_dir) + std::string("/etc/app.db");
1037     }
1038
1039     // Load app.db
1040     HMI_DEBUG("wm", "file_name:%s", file_name.c_str());
1041     json_object* json_obj = json_object_from_file(file_name.c_str());
1042     if (nullptr == json_obj) {
1043         HMI_ERROR("wm", "Could not open app.db, so use default role information");
1044         json_obj = json_tokener_parse(kDefaultAppDb);
1045     }
1046     HMI_DEBUG("wm", "json_obj dump:%s", json_object_get_string(json_obj));
1047
1048     // Perse apps
1049     HMI_DEBUG("wm", "Perse apps");
1050     json_object* json_cfg;
1051     if (!json_object_object_get_ex(json_obj, "apps", &json_cfg)) {
1052         HMI_ERROR("wm", "Parse Error!!");
1053         return -1;
1054     }
1055
1056     int len = json_object_array_length(json_cfg);
1057     HMI_DEBUG("wm", "json_cfg len:%d", len);
1058     HMI_DEBUG("wm", "json_cfg dump:%s", json_object_get_string(json_cfg));
1059
1060     for (int i=0; i<len; i++) {
1061         json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
1062         HMI_DEBUG("wm", "> json_tmp dump:%s", json_object_get_string(json_tmp));
1063
1064         const char* app = jh::getStringFromJson(json_tmp, "name");
1065         if (nullptr == app) {
1066             HMI_ERROR("wm", "Parse Error!!");
1067             return -1;
1068         }
1069         HMI_DEBUG("wm", "> app:%s", app);
1070
1071         const char* role = jh::getStringFromJson(json_tmp, "role");
1072         if (nullptr == role) {
1073             HMI_ERROR("wm", "Parse Error!!");
1074             return -1;
1075         }
1076         HMI_DEBUG("wm", "> role:%s", role);
1077
1078         this->app2role_[app] = std::string(role);
1079     }
1080
1081     // Check
1082     for(auto itr = this->app2role_.begin();
1083       itr != this->app2role_.end(); ++itr) {
1084         HMI_DEBUG("wm", "app:%s role:%s",
1085                   itr->first.c_str(), itr->second.c_str());
1086     }
1087
1088     // Release json_object
1089     json_object_put(json_obj);
1090
1091     return 0;
1092 }
1093
1094
1095 const char* kDefaultAppDb = "{ \
1096     \"apps\": [ \
1097         { \
1098             \"name\": \"HomeScreen\", \
1099             \"role\": \"homescreen\" \
1100         }, \
1101         { \
1102             \"name\": \"Music\", \
1103             \"role\": \"music\" \
1104         }, \
1105         { \
1106             \"name\": \"MediaPlayer\", \
1107             \"role\": \"music\" \
1108         }, \
1109         { \
1110             \"name\": \"Video\", \
1111             \"role\": \"video\" \
1112         }, \
1113         { \
1114             \"name\": \"VideoPlayer\", \
1115             \"role\": \"video\" \
1116         }, \
1117         { \
1118             \"name\": \"WebBrowser\", \
1119             \"role\": \"browser\" \
1120         }, \
1121         { \
1122             \"name\": \"Radio\", \
1123             \"role\": \"radio\" \
1124         }, \
1125         { \
1126             \"name\": \"Phone\", \
1127             \"role\": \"phone\" \
1128         }, \
1129         { \
1130             \"name\": \"Navigation\", \
1131             \"role\": \"map\" \
1132         }, \
1133         { \
1134             \"name\": \"HVAC\", \
1135             \"role\": \"hvac\" \
1136         }, \
1137         { \
1138             \"name\": \"Settings\", \
1139             \"role\": \"settings\" \
1140         }, \
1141         { \
1142             \"name\": \"Dashboard\", \
1143             \"role\": \"dashboard\" \
1144         }, \
1145         { \
1146             \"name\": \"POI\", \
1147             \"role\": \"poi\" \
1148         }, \
1149         { \
1150             \"name\": \"Mixer\", \
1151             \"role\": \"mixer\" \
1152         } \
1153     ] \
1154 }";
1155
1156
1157 }  // namespace wm