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