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