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