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