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