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