937da6a36cc7808a908819dc3a21fe157f922aee
[apps/agl-service-windowmanager-2017.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
38
39 namespace wm {
40
41 /* DrawingArea name used by "{layout}.{area}" */
42 const char kNameLayoutNormal[] = "normal";
43 const char kNameLayoutSplit[]  = "split";
44 const char kNameAreaFull[]     = "full";
45 const char kNameAreaMain[]     = "main";
46 const char kNameAreaSub[]      = "sub";
47
48 /* Key for json obejct */
49 const char kKeyDrawingName[] = "drawing_name";
50 const char kKeyDrawingArea[] = "drawing_area";
51 const char kKeyDrawingRect[] = "drawing_rect";
52 const char kKeyX[]           = "x";
53 const char kKeyY[]           = "y";
54 const char kKeyWidth[]       = "width";
55 const char kKeyHeight[]      = "height";
56 const char kKeyWidthPixel[]  = "width_pixel";
57 const char kKeyHeightPixel[] = "height_pixel";
58 const char kKeyWidthMm[]     = "width_mm";
59 const char kKeyHeightMm[]    = "height_mm";
60
61
62 namespace {
63
64 using nlohmann::json;
65
66 result<json> file_to_json(char const *filename) {
67    json j;
68    std::ifstream i(filename);
69    if (i.fail()) {
70       HMI_DEBUG("wm", "Could not open config file, so use default layer information");
71       j = default_layers_json;
72    }
73    else {
74       i >> j;
75    }
76
77    return Ok(j);
78 }
79
80 struct result<layer_map> load_layer_map(char const *filename) {
81    HMI_DEBUG("wm", "loading IDs from %s", filename);
82
83    auto j = file_to_json(filename);
84    if (j.is_err()) {
85       return Err<layer_map>(j.unwrap_err());
86    }
87    json jids = j.unwrap();
88
89    return to_layer_map(jids);
90 }
91
92 }  // namespace
93
94
95 /**
96  * App Impl
97  */
98 App::App(wl::display *d)
99    : chooks{this},
100      display{d},
101      controller{},
102      outputs(),
103      config(),
104      layers(),
105      id_alloc{},
106      pending_events(false),
107      policy{} {
108    try {
109       {
110          auto l = load_layer_map(
111             this->config.get_string("layers.json").value().c_str());
112          if (l.is_ok()) {
113             this->layers = l.unwrap();
114          } else {
115             HMI_ERROR("wm", "%s", l.err().value());
116          }
117       }
118    } catch (std::exception &e) {
119       HMI_ERROR("wm", "Loading of configuration failed: %s", e.what());
120    }
121 }
122
123 int App::init() {
124    if (!this->display->ok()) {
125       return -1;
126    }
127
128    if (this->layers.mapping.empty()) {
129       HMI_ERROR("wm", "No surface -> layer mapping loaded");
130       return -1;
131    }
132
133    // Make afb event
134    for (int i=Event_Val_Min; i<=Event_Val_Max; i++) {
135       map_afb_event[kListEventName[i]] = afb_daemon_make_event(kListEventName[i]);
136    }
137
138    this->display->add_global_handler(
139       "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
140          this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
141       });
142
143    this->display->add_global_handler(
144       "ivi_wm", [this](wl_registry *r, uint32_t name, uint32_t v) {
145          this->controller =
146             std::make_unique<struct compositor::controller>(r, name, v);
147
148          // Init controller hooks
149          this->controller->chooks = &this->chooks;
150
151          // This protocol needs the output, so lets just add our mapping here...
152          this->controller->add_proxy_to_id_mapping(
153             this->outputs.back()->proxy.get(),
154             wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
155                this->outputs.back()->proxy.get())));
156
157          // Create screen
158          this->controller->create_screen(this->outputs.back()->proxy.get());
159
160          // Set display to controller
161          this->controller->display = this->display;
162       });
163
164    // First level objects
165    this->display->roundtrip();
166    // Second level objects
167    this->display->roundtrip();
168    // Third level objects
169    this->display->roundtrip();
170
171    return init_layers();
172 }
173
174 int App::dispatch_pending_events() {
175    if (this->pop_pending_events()) {
176       this->display->dispatch_pending();
177       return 0;
178    }
179    return -1;
180 }
181
182 bool App::pop_pending_events() {
183    bool x{true};
184    return this->pending_events.compare_exchange_strong(
185       x, false, std::memory_order_consume);
186 }
187
188 void App::set_pending_events() {
189    this->pending_events.store(true, std::memory_order_release);
190 }
191
192 optional<int> App::lookup_id(char const *name) {
193    return this->id_alloc.lookup(std::string(name));
194 }
195 optional<std::string> App::lookup_name(int id) {
196    return this->id_alloc.lookup(id);
197 }
198
199 /**
200  * init_layers()
201  */
202 int App::init_layers() {
203    if (!this->controller) {
204       HMI_ERROR("wm", "ivi_controller global not available");
205       return -1;
206    }
207
208    if (this->outputs.empty()) {
209       HMI_ERROR("wm", "no output was set up!");
210       return -1;
211    }
212
213    auto &c = this->controller;
214
215    auto &o = this->outputs.front();
216    auto &s = c->screens.begin()->second;
217    auto &layers = c->layers;
218
219    // Write output dimensions to ivi controller...
220    c->output_size = compositor::size{uint32_t(o->width), uint32_t(o->height)};
221    c->physical_size = compositor::size{uint32_t(o->physical_width),
222                                        uint32_t(o->physical_height)};
223
224    // Clear scene
225    layers.clear();
226
227    // Clear screen
228    s->clear();
229
230    // Quick and dirty setup of layers
231    for (auto const &i : this->layers.mapping) {
232       c->layer_create(i.second.layer_id, o->width, o->height);
233       auto &l = layers[i.second.layer_id];
234       l->set_destination_rectangle(0, 0, o->width, o->height);
235       l->set_visibility(1);
236       HMI_DEBUG("wm", "Setting up layer %s (%d) for surface role match \"%s\"",
237                i.second.name.c_str(), i.second.layer_id, i.second.role.c_str());
238    }
239
240    // Add layers to screen
241    s->set_render_order(this->layers.layers);
242
243    this->layout_commit();
244
245    return 0;
246 }
247
248 void App::surface_set_layout(int surface_id, optional<int> sub_surface_id) {
249    if (!this->controller->surface_exists(surface_id)) {
250       HMI_ERROR("wm", "Surface %d does not exist", surface_id);
251       return;
252    }
253
254    auto o_layer_id = this->layers.get_layer_id(surface_id);
255
256    if (!o_layer_id) {
257       HMI_ERROR("wm", "Surface %d is not associated with any layer!", surface_id);
258       return;
259    }
260
261    uint32_t layer_id = *o_layer_id;
262
263    auto const &layer = this->layers.get_layer(layer_id);
264    auto rect = layer.value().rect;
265    auto &s = this->controller->surfaces[surface_id];
266
267    int x = rect.x;
268    int y = rect.y;
269    int w = rect.w;
270    int h = rect.h;
271
272    // less-than-0 values refer to MAX + 1 - $VALUE
273    // e.g. MAX is either screen width or height
274    if (w < 0) {
275       w = this->controller->output_size.w + 1 + w;
276    }
277    if (h < 0) {
278       h = this->controller->output_size.h + 1 + h;
279    }
280
281    if (sub_surface_id) {
282       if (o_layer_id != this->layers.get_layer_id(*sub_surface_id)) {
283          HMI_ERROR("wm",
284             "surface_set_layout: layers of surfaces (%d and %d) don't match!",
285             surface_id, *sub_surface_id);
286          return;
287       }
288
289       int x_off = 0;
290       int y_off = 0;
291
292       // split along major axis
293       if (w > h) {
294          w /= 2;
295          x_off = w;
296       } else {
297          h /= 2;
298          y_off = h;
299       }
300
301       auto &ss = this->controller->surfaces[*sub_surface_id];
302
303       HMI_DEBUG("wm", "surface_set_layout for sub surface %u on layer %u",
304                *sub_surface_id, layer_id);
305
306       // set destination to the display rectangle
307       ss->set_destination_rectangle(x + x_off, y + y_off, w, h);
308
309       this->area_info[*sub_surface_id].x = x;
310       this->area_info[*sub_surface_id].y = y;
311       this->area_info[*sub_surface_id].w = w;
312       this->area_info[*sub_surface_id].h = h;
313    }
314
315    HMI_DEBUG("wm", "surface_set_layout for surface %u on layer %u", surface_id,
316             layer_id);
317
318    // set destination to the display rectangle
319    s->set_destination_rectangle(x, y, w, h);
320
321    // update area information
322    this->area_info[surface_id].x = x;
323    this->area_info[surface_id].y = y;
324    this->area_info[surface_id].w = w;
325    this->area_info[surface_id].h = h;
326
327    HMI_DEBUG("wm", "Surface %u now on layer %u with rect { %d, %d, %d, %d }",
328             surface_id, layer_id, x, y, w, h);
329 }
330
331 void App::layout_commit() {
332    this->controller->commit_changes();
333    this->display->flush();
334 }
335
336 void App::api_activate_surface(char const *drawing_name, char const *drawing_area, const reply_func &reply) {
337    ST();
338
339    auto const &surface_id = this->lookup_id(drawing_name);
340
341    if (!surface_id) {
342        reply("Surface does not exist");
343        return;
344    }
345
346    if (!this->controller->surface_exists(*surface_id)) {
347       reply("Surface does not exist in controller!");
348       return;
349    }
350
351    auto layer_id = this->layers.get_layer_id(*surface_id);
352
353    if (!layer_id) {
354       reply("Surface is not on any layer!");
355       return;
356    }
357
358    auto o_state = *this->layers.get_layout_state(*surface_id);
359
360    if (o_state == nullptr) {
361       reply("Could not find layer for surface");
362       return;
363    }
364
365    HMI_DEBUG("wm", "surface %d is detected", *surface_id);
366    reply(nullptr);
367
368    struct LayoutState &state = *o_state;
369
370    // disable layers that are above our current layer
371    for (auto const &l : this->layers.mapping) {
372       if (l.second.layer_id <= *layer_id) {
373          continue;
374       }
375
376       bool flush = false;
377       if (l.second.state.main != -1) {
378          this->deactivate(l.second.state.main);
379          l.second.state.main = -1;
380          flush = true;
381       }
382
383       if (l.second.state.sub != -1) {
384          this->deactivate(l.second.state.sub);
385          l.second.state.sub = -1;
386          flush = true;
387       }
388
389       if (flush) {
390          this->layout_commit();
391       }
392    }
393
394    auto layer = this->layers.get_layer(*layer_id);
395
396    if (state.main == -1) {
397       this->try_layout(
398          state, LayoutState{*surface_id}, [&] (LayoutState const &nl) {
399             HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
400             this->surface_set_layout(*surface_id);
401             state = nl;
402
403             // Commit for configuraton
404             this->layout_commit();
405
406             std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
407             compositor::rect area_rect = this->area_info[*surface_id];
408             this->emit_syncdraw(drawing_name, str_area.c_str(),
409                                 area_rect.x, area_rect.y, area_rect.w, area_rect.h);
410             this->enqueue_flushdraw(state.main);
411          });
412    } else {
413       if (0 == strcmp(drawing_name, "HomeScreen")) {
414          this->try_layout(
415             state, LayoutState{*surface_id}, [&] (LayoutState const &nl) {
416                HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
417                std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
418                compositor::rect area_rect = this->area_info[*surface_id];
419                this->emit_syncdraw(drawing_name, str_area.c_str(),
420                                    area_rect.x, area_rect.y, area_rect.w, area_rect.h);
421                this->enqueue_flushdraw(state.main);
422             });
423       } else {
424          bool can_split = this->can_split(state, *surface_id);
425
426          if (can_split) {
427             this->try_layout(
428                state,
429                LayoutState{state.main, *surface_id},
430                [&] (LayoutState const &nl) {
431                   HMI_DEBUG("wm", "Layout: %s", kNameLayoutSplit);
432                   std::string main =
433                      std::move(*this->lookup_name(state.main));
434
435                   this->surface_set_layout(state.main, surface_id);
436                   if (state.sub != *surface_id) {
437                       if (state.sub != -1) {
438                          this->deactivate(state.sub);
439                       }
440                   }
441                   state = nl;
442
443                   // Commit for configuration and visibility(0)
444                   this->layout_commit();
445
446                   std::string str_area_main = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaMain);
447                   std::string str_area_sub = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaSub);
448                   compositor::rect area_rect_main = this->area_info[state.main];
449                   compositor::rect area_rect_sub = this->area_info[*surface_id];
450                   this->emit_syncdraw(main.c_str(), str_area_main.c_str(),
451                                       area_rect_main.x, area_rect_main.y,
452                                       area_rect_main.w, area_rect_main.h);
453                   this->emit_syncdraw(drawing_name, str_area_sub.c_str(),
454                                       area_rect_sub.x, area_rect_sub.y,
455                                       area_rect_sub.w, area_rect_sub.h);
456                   this->enqueue_flushdraw(state.main);
457                   this->enqueue_flushdraw(state.sub);
458                });
459          } else {
460             this->try_layout(
461                state, LayoutState{*surface_id}, [&] (LayoutState const &nl) {
462                   HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
463
464                   this->surface_set_layout(*surface_id);
465                   if (state.main != *surface_id) {
466                       this->deactivate(state.main);
467                   }
468                   if (state.sub != -1) {
469                       if (state.sub != *surface_id) {
470                          this->deactivate(state.sub);
471                       }
472                   }
473                   state = nl;
474
475                   // Commit for configuraton and visibility(0)
476                   this->layout_commit();
477
478                   std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
479                   compositor::rect area_rect = this->area_info[*surface_id];
480                   this->emit_syncdraw(drawing_name, str_area.c_str(),
481                                       area_rect.x, area_rect.y, area_rect.w, area_rect.h);
482                   this->enqueue_flushdraw(state.main);
483                });
484          }
485       }
486    }
487 }
488
489 void App::api_deactivate_surface(char const *drawing_name, const reply_func &reply) {
490    ST();
491    auto const &surface_id = this->lookup_id(drawing_name);
492
493    if (!surface_id) {
494       reply ("Surface does not exist");
495       return;
496    }
497
498    if (*surface_id == this->layers.main_surface) {
499       reply("Cannot deactivate main_surface");
500       return;
501    }
502
503    auto o_state = *this->layers.get_layout_state(*surface_id);
504
505    if (o_state == nullptr) {
506       reply("Could not find layer for surface");
507       return;
508    }
509
510    struct LayoutState &state = *o_state;
511
512    if (state.main == -1) {
513       reply("No surface active");
514       return;
515    }
516
517    // Check against main_surface, main_surface_name is the configuration item.
518    if (*surface_id == this->layers.main_surface) {
519       HMI_DEBUG("wm", "Refusing to deactivate main_surface %d", *surface_id);
520       reply(nullptr);
521       return;
522    }
523    if((state.main == *surface_id) && (state.sub == *surface_id)){
524        reply("Surface is not active");
525        return;
526    }
527    reply(nullptr);
528
529    if (state.main == *surface_id) {
530       if (state.sub != -1) {
531          this->try_layout(
532             state, LayoutState{state.sub, -1}, [&] (LayoutState const &nl) {
533                std::string sub = std::move(*this->lookup_name(state.sub));
534
535                this->deactivate(*surface_id);
536                this->surface_set_layout(state.sub);
537                state = nl;
538
539                this->layout_commit();
540                std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
541                compositor::rect area_rect = this->area_info[state.sub];
542                this->emit_syncdraw(sub.c_str(), str_area.c_str(),
543                                    area_rect.x, area_rect.y, area_rect.w, area_rect.h);
544                this->enqueue_flushdraw(state.sub);
545             });
546       } else {
547          this->try_layout(state, LayoutState{-1, -1}, [&] (LayoutState const &nl) {
548             this->deactivate(*surface_id);
549             state = nl;
550             this->layout_commit();
551          });
552       }
553    } else if (state.sub == *surface_id) {
554       this->try_layout(
555          state, LayoutState{state.main, -1}, [&] (LayoutState const &nl) {
556             std::string main = std::move(*this->lookup_name(state.main));
557
558             this->deactivate(*surface_id);
559             this->surface_set_layout(state.main);
560             state = nl;
561
562             this->layout_commit();
563             std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
564             compositor::rect area_rect = this->area_info[state.main];
565             this->emit_syncdraw(main.c_str(), str_area.c_str(),
566                                 area_rect.x, area_rect.y, area_rect.w, area_rect.h);
567             this->enqueue_flushdraw(state.main);
568          });
569    }
570 }
571
572 void App::enqueue_flushdraw(int surface_id) {
573    this->check_flushdraw(surface_id);
574    HMI_DEBUG("wm", "Enqueuing EndDraw for surface_id %d", surface_id);
575    this->pending_end_draw.push_back(surface_id);
576 }
577
578 void App::check_flushdraw(int surface_id) {
579    auto i = std::find(std::begin(this->pending_end_draw),
580                       std::end(this->pending_end_draw), surface_id);
581    if (i != std::end(this->pending_end_draw)) {
582       auto n = this->lookup_name(surface_id);
583       HMI_ERROR("wm", "Application %s (%d) has pending EndDraw call(s)!",
584                n ? n->c_str() : "unknown-name", surface_id);
585       std::swap(this->pending_end_draw[std::distance(
586                    std::begin(this->pending_end_draw), i)],
587                 this->pending_end_draw.back());
588       this->pending_end_draw.resize(this->pending_end_draw.size() - 1);
589    }
590 }
591
592 void App::api_enddraw(char const *drawing_name) {
593    for (unsigned i = 0, iend = this->pending_end_draw.size(); i < iend; i++) {
594       auto n = this->lookup_name(this->pending_end_draw[i]);
595       if (n && *n == drawing_name) {
596          std::swap(this->pending_end_draw[i], this->pending_end_draw[iend - 1]);
597          this->pending_end_draw.resize(iend - 1);
598          this->activate(this->pending_end_draw[i]);
599          this->emit_flushdraw(drawing_name);
600       }
601    }
602 }
603
604 void App::api_ping() { this->dispatch_pending_events(); }
605
606 void App::send_event(char const *evname, char const *label){
607    HMI_DEBUG("wm", "%s: %s(%s)", __func__, evname, label);
608
609    json_object *j = json_object_new_object();
610    json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
611
612    int ret = afb_event_push(this->map_afb_event[evname], j);
613    if (ret != 0) {
614       HMI_DEBUG("wm", "afb_event_push failed: %m");
615    }
616 }
617
618 void App::send_event(char const *evname, char const *label, char const *area,
619                              int x, int y, int w, int h) {
620    HMI_DEBUG("wm", "%s: %s(%s, %s) x:%d y:%d w:%d h:%d",
621              __func__, evname, label, area, x, y, w, h);
622
623    json_object *j_rect = json_object_new_object();
624    json_object_object_add(j_rect, kKeyX,      json_object_new_int(x));
625    json_object_object_add(j_rect, kKeyY,      json_object_new_int(y));
626    json_object_object_add(j_rect, kKeyWidth,  json_object_new_int(w));
627    json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
628
629    json_object *j = json_object_new_object();
630    json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
631    json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area));
632    json_object_object_add(j, kKeyDrawingRect, j_rect);
633
634    int ret = afb_event_push(this->map_afb_event[evname], j);
635    if (ret != 0) {
636       HMI_DEBUG("wm", "afb_event_push failed: %m");
637    }
638 }
639
640 /**
641  * proxied events
642  */
643 void App::surface_created(uint32_t surface_id) {
644    auto layer_id = this->layers.get_layer_id(surface_id);
645    if (!layer_id) {
646       HMI_DEBUG("wm", "Newly created surfce %d is not associated with any layer!",
647                surface_id);
648       return;
649    }
650
651    HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", surface_id, *layer_id);
652
653    this->controller->layers[*layer_id]->add_surface(surface_id);
654    this->layout_commit();
655    // activate the main_surface right away
656    /*if (surface_id == static_cast<unsigned>(this->layers.main_surface)) {
657       HMI_DEBUG("wm", "Activating main_surface (%d)", surface_id);
658
659       this->api_activate_surface(
660          this->lookup_name(surface_id).value_or("unknown-name").c_str());
661    }*/
662 }
663
664 void App::surface_removed(uint32_t surface_id) {
665    HMI_DEBUG("wm", "surface_id is %u", surface_id);
666
667    // We cannot normally deactivate the main_surface, so be explicit
668    // about it:
669    if (int(surface_id) == this->layers.main_surface) {
670       this->deactivate_main_surface();
671    } else {
672       auto drawing_name = this->lookup_name(surface_id);
673       if (drawing_name) {
674          this->api_deactivate_surface(drawing_name->c_str(), [](const char*){});
675       }
676    }
677
678    this->id_alloc.remove_id(surface_id);
679    this->layers.remove_surface(surface_id);
680 }
681
682 void App::emit_activated(char const *label) {
683    this->send_event(kListEventName[Event_Active], label);
684 }
685
686 void App::emit_deactivated(char const *label) {
687    this->send_event(kListEventName[Event_Inactive], label);
688 }
689
690 void App::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h) {
691    this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
692 }
693
694 void App::emit_flushdraw(char const *label) {
695    this->send_event(kListEventName[Event_FlushDraw], label);
696 }
697
698 void App::emit_visible(char const *label, bool is_visible) {
699    this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
700 }
701
702 void App::emit_invisible(char const *label) {
703    return emit_visible(label, false);
704 }
705
706 void App::emit_visible(char const *label) { return emit_visible(label, true); }
707
708 result<int> App::api_request_surface(char const *drawing_name) {
709    auto lid = this->layers.get_layer_id(std::string(drawing_name));
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 Err<int>("Drawing name does not match any role, Fallback is disabled");
718       }
719    }
720
721    auto rname = this->lookup_id(drawing_name);
722    if (!rname) {
723       // name does not exist yet, allocate surface id...
724       auto id = int(this->id_alloc.generate_id(drawing_name));
725       this->layers.add_surface(id, *lid);
726
727       // set the main_surface[_name] here and now
728       if (!this->layers.main_surface_name.empty() &&
729           this->layers.main_surface_name == drawing_name) {
730          this->layers.main_surface = id;
731          HMI_DEBUG("wm", "Set main_surface id to %u", id);
732       }
733
734       return Ok<int>(id);
735    }
736
737    // Check currently registered drawing names if it is already there.
738    return Err<int>("Surface already present");
739 }
740
741 char const *App::api_request_surface(char const *drawing_name,
742                                      char const *ivi_id) {
743    ST();
744
745    auto lid = this->layers.get_layer_id(std::string(drawing_name));
746    unsigned sid = std::stol(ivi_id);
747
748    if (!lid) {
749       /**
750        * register drawing_name as fallback and make it displayed.
751        */
752       lid = this->layers.get_layer_id(std::string("Fallback"));
753       HMI_DEBUG("wm", "%s is not registered in layers.json, then fallback as normal app", drawing_name);
754       if(!lid){
755           return "Drawing name does not match any role, Fallback is disabled";
756       }
757    }
758
759    auto rname = this->lookup_id(drawing_name);
760
761    if (rname) {
762        return "Surface already present";
763    }
764
765    // register pair drawing_name and ivi_id
766    this->id_alloc.register_name_id(drawing_name, sid);
767    this->layers.add_surface(sid, *lid);
768
769    // this surface is already created
770    HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", sid, *lid);
771
772    this->controller->layers[*lid]->add_surface(sid);
773    this->layout_commit();
774
775    return nullptr;
776 }
777
778 result<json_object *> App::api_get_display_info() {
779    // Check controller
780    if (!this->controller) {
781       return Err<json_object *>("ivi_controller global not available");
782    }
783
784    // Set display info
785    compositor::size o_size = this->controller->output_size;
786    compositor::size p_size = this->controller->physical_size;
787
788    json_object *object = json_object_new_object();
789    json_object_object_add(object, kKeyWidthPixel,  json_object_new_int(o_size.w));
790    json_object_object_add(object, kKeyHeightPixel, json_object_new_int(o_size.h));
791    json_object_object_add(object, kKeyWidthMm,     json_object_new_int(p_size.w));
792    json_object_object_add(object, kKeyHeightMm,    json_object_new_int(p_size.h));
793
794    return Ok<json_object *>(object);
795 }
796
797 result<json_object *> App::api_get_area_info(char const *drawing_name) {
798    HMI_DEBUG("wm", "called");
799
800    // Check drawing name, surface/layer id
801    auto const &surface_id = this->lookup_id(drawing_name);
802    if (!surface_id) {
803       return Err<json_object *>("Surface does not exist");
804    }
805
806    if (!this->controller->surface_exists(*surface_id)) {
807       return Err<json_object *>("Surface does not exist in controller!");
808    }
809
810    auto layer_id = this->layers.get_layer_id(*surface_id);
811    if (!layer_id) {
812       return Err<json_object *>("Surface is not on any layer!");
813    }
814
815    auto o_state = *this->layers.get_layout_state(*surface_id);
816    if (o_state == nullptr) {
817       return Err<json_object *>("Could not find layer for surface");
818    }
819
820    struct LayoutState &state = *o_state;
821    if ((state.main != *surface_id) && (state.sub != *surface_id)) {
822       return Err<json_object *>("Surface is inactive");
823    }
824
825    // Set area rectangle
826    compositor::rect area_info = this->area_info[*surface_id];
827    json_object *object = json_object_new_object();
828    json_object_object_add(object, kKeyX,      json_object_new_int(area_info.x));
829    json_object_object_add(object, kKeyY,      json_object_new_int(area_info.y));
830    json_object_object_add(object, kKeyWidth,  json_object_new_int(area_info.w));
831    json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
832
833    return Ok<json_object *>(object);
834 }
835
836 void App::activate(int id) {
837    auto ip = this->controller->sprops.find(id);
838    if (ip != this->controller->sprops.end()) {
839       this->controller->surfaces[id]->set_visibility(1);
840       char const *label =
841          this->lookup_name(id).value_or("unknown-name").c_str();
842
843       // FOR CES DEMO >>>
844       if ((0 == strcmp(label, "Radio"))
845           || (0 == strcmp(label, "MediaPlayer"))
846           || (0 == strcmp(label, "Music"))
847           || (0 == strcmp(label, "Navigation"))) {
848         for (auto i = surface_bg.begin(); i != surface_bg.end(); ++i) {
849             if (id == *i) {
850                // Remove id
851                this->surface_bg.erase(i);
852
853                // Remove from BG layer (999)
854                HMI_DEBUG("wm", "Remove %s(%d) from BG layer", label, id);
855                this->controller->layers[999]->remove_surface(id);
856
857                // Add to FG layer (1001)
858                HMI_DEBUG("wm", "Add %s(%d) to FG layer", label, id);
859                this->controller->layers[1001]->add_surface(id);
860
861                for (int j : this->surface_bg) {
862                  HMI_DEBUG("wm", "Stored id:%d", j);
863                }
864                break;
865             }
866          }
867       }
868       // <<< FOR CES DEMO
869       this->layout_commit();
870
871       this->emit_visible(label);
872       this->emit_activated(label);
873    }
874 }
875
876 void App::deactivate(int id) {
877    auto ip = this->controller->sprops.find(id);
878    if (ip != this->controller->sprops.end()) {
879       char const *label =
880          this->lookup_name(id).value_or("unknown-name").c_str();
881
882       // FOR CES DEMO >>>
883       if ((0 == strcmp(label, "Radio"))
884           || (0 == strcmp(label, "MediaPlayer"))
885           || (0 == strcmp(label, "Music"))
886           || (0 == strcmp(label, "Navigation"))) {
887
888          // Store id
889          this->surface_bg.push_back(id);
890
891          // Remove from FG layer (1001)
892          HMI_DEBUG("wm", "Remove %s(%d) from FG layer", label, id);
893          this->controller->layers[1001]->remove_surface(id);
894
895          // Add to BG layer (999)
896          HMI_DEBUG("wm", "Add %s(%d) to BG layer", label, id);
897          this->controller->layers[999]->add_surface(id);
898
899          for (int j : surface_bg) {
900             HMI_DEBUG("wm", "Stored id:%d", j);
901          }
902       }
903       else {
904          this->controller->surfaces[id]->set_visibility(0);
905       }
906       // <<< FOR CES DEMO
907
908       this->emit_deactivated(label);
909       this->emit_invisible(label);
910    }
911 }
912
913 void App::deactivate_main_surface() {
914    this->layers.main_surface = -1;
915    this->api_deactivate_surface(this->layers.main_surface_name.c_str(), [](const char*){});
916 }
917
918 bool App::can_split(struct LayoutState const &state, int new_id) {
919    if (state.main != -1 && state.main != new_id) {
920       auto new_id_layer = this->layers.get_layer_id(new_id).value();
921       auto current_id_layer = this->layers.get_layer_id(state.main).value();
922
923       // surfaces are on separate layers, don't bother.
924       if (new_id_layer != current_id_layer) {
925          return false;
926       }
927
928       std::string const &new_id_str = this->lookup_name(new_id).value();
929       std::string const &cur_id_str = this->lookup_name(state.main).value();
930
931       auto const &layer = this->layers.get_layer(new_id_layer);
932
933       HMI_DEBUG("wm", "layer info name: %s", layer->name.c_str());
934
935       if (layer->layouts.empty()) {
936          return false;
937       }
938
939       for (auto i = layer->layouts.cbegin(); i != layer->layouts.cend(); i++) {
940          HMI_DEBUG("wm", "%d main_match '%s'", new_id_layer, i->main_match.c_str());
941          auto rem = std::regex(i->main_match);
942          if (std::regex_match(cur_id_str, rem)) {
943             // build the second one only if the first already matched
944             HMI_DEBUG("wm", "%d sub_match '%s'", new_id_layer, i->sub_match.c_str());
945             auto res = std::regex(i->sub_match);
946             if (std::regex_match(new_id_str, res)) {
947                HMI_DEBUG("wm", "layout matched!");
948                return true;
949             }
950          }
951       }
952    }
953
954    return false;
955 }
956
957 void App::try_layout(struct LayoutState & /*state*/,
958                      struct LayoutState const &new_layout,
959                      std::function<void(LayoutState const &nl)> apply) {
960    if (this->policy.layout_is_valid(new_layout)) {
961       apply(new_layout);
962    }
963 }
964
965 /**
966  * controller_hooks
967  */
968 void controller_hooks::surface_created(uint32_t surface_id) {
969    this->app->surface_created(surface_id);
970 }
971
972 void controller_hooks::surface_removed(uint32_t surface_id) {
973    this->app->surface_removed(surface_id);
974 }
975
976 void controller_hooks::surface_visibility(uint32_t /*surface_id*/,
977                                           uint32_t /*v*/) {}
978
979 void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/,
980                                                      uint32_t /*x*/,
981                                                      uint32_t /*y*/,
982                                                      uint32_t /*w*/,
983                                                      uint32_t /*h*/) {}
984
985 }  // namespace wm