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