414e1fb1ab34f7f0685f06c378cc05d5c8d261f1
[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 "wm_client.hpp"
39 #include "applist.hpp"
40
41 extern "C"
42 {
43 #include <systemd/sd-event.h>
44 }
45
46 namespace wm
47 {
48
49 const unsigned kTimeOut = 10000000UL; /* 10s */
50
51 /* DrawingArea name used by "{layout}.{area}" */
52 const char kNameLayoutNormal[] = "normal";
53 const char kNameLayoutSplit[] = "split";
54 const char kNameAreaFull[] = "full";
55 const char kNameAreaMain[] = "main";
56 const char kNameAreaSub[] = "sub";
57
58 /* Key for json obejct */
59 const char kKeyDrawingName[] = "drawing_name";
60 const char kKeyDrawingArea[] = "drawing_area";
61 const char kKeyDrawingRect[] = "drawing_rect";
62 const char kKeyX[] = "x";
63 const char kKeyY[] = "y";
64 const char kKeyWidth[] = "width";
65 const char kKeyHeight[] = "height";
66 const char kKeyWidthPixel[] = "width_pixel";
67 const char kKeyHeightPixel[] = "height_pixel";
68 const char kKeyWidthMm[] = "width_mm";
69 const char kKeyHeightMm[] = "height_mm";
70
71 static sd_event_source *g_timer_ev_src = nullptr;
72
73 static AppList g_app_list;
74
75 namespace
76 {
77
78 using nlohmann::json;
79
80 result<json> file_to_json(char const *filename)
81 {
82     json j;
83     std::ifstream i(filename);
84     if (i.fail())
85     {
86         HMI_DEBUG("wm", "Could not open config file, so use default layer information");
87         j = default_layers_json;
88     }
89     else
90     {
91         i >> j;
92     }
93
94     return Ok(j);
95 }
96
97 struct result<layer_map> load_layer_map(char const *filename)
98 {
99     HMI_DEBUG("wm", "loading IDs from %s", filename);
100
101     auto j = file_to_json(filename);
102     if (j.is_err())
103     {
104         return Err<layer_map>(j.unwrap_err());
105     }
106     json jids = j.unwrap();
107
108     return to_layer_map(jids);
109 }
110
111 static int
112 processTimerHandler(sd_event_source *s, uint64_t usec, void *userdata)
113 {
114     HMI_NOTICE("wm", "Time out occurs because the client replys endDraw slow, so revert the request");
115     reinterpret_cast<wm::App *>(userdata)->timerHandler();
116     return 0;
117 }
118
119 } // namespace
120
121 void App::timerHandler()
122 {
123     unsigned req_num = g_app_list.currentRequestNumber();
124     HMI_SEQ_DEBUG(req_num, "Timer expired remove Request");
125     g_app_list.reqDump();
126     g_app_list.removeRequest(req_num);
127     this->processNextRequest();
128 }
129
130 void App::removeClient(const std::string &appid)
131 {
132     HMI_DEBUG("wm", "Remove clinet %s from list", appid.c_str());
133     g_app_list.removeClient(appid);
134 }
135
136 bool App::subscribeEventForApp(const std::string &appid, afb_req req, const std::string &evname)
137 {
138     if(!g_app_list.contains(appid)){
139         HMI_DEBUG("wm", "Client %s is not registered", appid.c_str());
140         return false;
141     }
142     auto client = g_app_list.lookUpClient(appid);
143     return client->subscribe(req, evname);
144 }
145
146 /**
147  * App Impl
148  */
149 App::App(wl::display *d)
150     : chooks{this},
151       display{d},
152       controller{},
153       outputs(),
154       config(),
155       layers(),
156       id_alloc{},
157       pending_events(false),
158       policy{}
159 {
160     try
161     {
162         {
163             auto l = load_layer_map(
164                 this->config.get_string("layers.json").value().c_str());
165             if (l.is_ok())
166             {
167                 this->layers = l.unwrap();
168             }
169             else
170             {
171                 HMI_ERROR("wm", "%s", l.err().value());
172             }
173         }
174     }
175     catch (std::exception &e)
176     {
177         HMI_ERROR("wm", "Loading of configuration failed: %s", e.what());
178     }
179 }
180
181 int App::init()
182 {
183     if (!this->display->ok())
184     {
185         return -1;
186     }
187
188     if (this->layers.mapping.empty())
189     {
190         HMI_ERROR("wm", "No surface -> layer mapping loaded");
191         return -1;
192     }
193
194     // Make afb event
195     for (int i = Event_Val_Min; i <= Event_Val_Max; i++)
196     {
197         map_afb_event[kListEventName[i]] = afb_daemon_make_event(kListEventName[i]);
198     }
199
200     this->display->add_global_handler(
201         "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
202             this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
203         });
204
205     this->display->add_global_handler(
206         "ivi_wm", [this](wl_registry *r, uint32_t name, uint32_t v) {
207             this->controller =
208                 std::make_unique<struct compositor::controller>(r, name, v);
209
210             // Init controller hooks
211             this->controller->chooks = &this->chooks;
212
213             // This protocol needs the output, so lets just add our mapping here...
214             this->controller->add_proxy_to_id_mapping(
215                 this->outputs.back()->proxy.get(),
216                 wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
217                     this->outputs.back()->proxy.get())));
218
219             // Create screen
220             this->controller->create_screen(this->outputs.back()->proxy.get());
221
222             // Set display to controller
223             this->controller->display = this->display;
224         });
225
226     // First level objects
227     this->display->roundtrip();
228     // Second level objects
229     this->display->roundtrip();
230     // Third level objects
231     this->display->roundtrip();
232
233     return init_layers();
234 }
235
236 int App::dispatch_pending_events()
237 {
238     if (this->pop_pending_events())
239     {
240         this->display->dispatch_pending();
241         return 0;
242     }
243     return -1;
244 }
245
246 bool App::pop_pending_events()
247 {
248     bool x{true};
249     return this->pending_events.compare_exchange_strong(
250         x, false, std::memory_order_consume);
251 }
252
253 void App::set_pending_events()
254 {
255     this->pending_events.store(true, std::memory_order_release);
256 }
257
258 optional<int> App::lookup_id(char const *name)
259 {
260     return this->id_alloc.lookup(std::string(name));
261 }
262 optional<std::string> App::lookup_name(int id)
263 {
264     return this->id_alloc.lookup(id);
265 }
266
267 /**
268  * init_layers()
269  */
270 int App::init_layers()
271 {
272     if (!this->controller)
273     {
274         HMI_ERROR("wm", "ivi_controller global not available");
275         return -1;
276     }
277
278     if (this->outputs.empty())
279     {
280         HMI_ERROR("wm", "no output was set up!");
281         return -1;
282     }
283
284     auto &c = this->controller;
285
286     auto &o = this->outputs.front();
287     auto &s = c->screens.begin()->second;
288     auto &layers = c->layers;
289
290     // Write output dimensions to ivi controller...
291     c->output_size = compositor::size{uint32_t(o->width), uint32_t(o->height)};
292     c->physical_size = compositor::size{uint32_t(o->physical_width),
293                                         uint32_t(o->physical_height)};
294
295     // Clear scene
296     layers.clear();
297
298     // Clear screen
299     s->clear();
300
301     // Quick and dirty setup of layers
302     for (auto const &i : this->layers.mapping)
303     {
304         c->layer_create(i.second.layer_id, o->width, o->height);
305         auto &l = layers[i.second.layer_id];
306         l->set_destination_rectangle(0, 0, o->width, o->height);
307         l->set_visibility(1);
308         HMI_DEBUG("wm", "Setting up layer %s (%d) for surface role match \"%s\"",
309                   i.second.name.c_str(), i.second.layer_id, i.second.role.c_str());
310     }
311
312     // Add layers to screen
313     s->set_render_order(this->layers.layers);
314
315     this->layout_commit();
316
317     return 0;
318 }
319
320 void App::surface_set_layout(int surface_id, optional<int> sub_surface_id)
321 {
322     if (!this->controller->surface_exists(surface_id))
323     {
324         HMI_ERROR("wm", "Surface %d does not exist", surface_id);
325         return;
326     }
327
328     auto o_layer_id = this->layers.get_layer_id(surface_id);
329
330     if (!o_layer_id)
331     {
332         HMI_ERROR("wm", "Surface %d is not associated with any layer!", surface_id);
333         return;
334     }
335
336     uint32_t layer_id = *o_layer_id;
337
338     auto const &layer = this->layers.get_layer(layer_id);
339     auto rect = layer.value().rect;
340     auto &s = this->controller->surfaces[surface_id];
341
342     int x = rect.x;
343     int y = rect.y;
344     int w = rect.w;
345     int h = rect.h;
346
347     // less-than-0 values refer to MAX + 1 - $VALUE
348     // e.g. MAX is either screen width or height
349     if (w < 0)
350     {
351         w = this->controller->output_size.w + 1 + w;
352     }
353     if (h < 0)
354     {
355         h = this->controller->output_size.h + 1 + h;
356     }
357
358     /* if (sub_surface_id)
359     {
360         if (o_layer_id != this->layers.get_layer_id(*sub_surface_id))
361         {
362             HMI_ERROR("wm",
363                       "surface_set_layout: layers of surfaces (%d and %d) don't match!",
364                       surface_id, *sub_surface_id);
365             return;
366         }
367
368         int x_off = 0;
369         int y_off = 0;
370
371         // split along major axis
372         if (w > h)
373         {
374             w /= 2;
375             x_off = w;
376         }
377         else
378         {
379             h /= 2;
380             y_off = h;
381         }
382
383         auto &ss = this->controller->surfaces[*sub_surface_id];
384
385         HMI_DEBUG("wm", "surface_set_layout for sub surface %u on layer %u",
386                   *sub_surface_id, layer_id);
387
388         // set destination to the display rectangle
389         ss->set_destination_rectangle(x + x_off, y + y_off, w, h);
390
391         this->area_info[*sub_surface_id].x = x;
392         this->area_info[*sub_surface_id].y = y;
393         this->area_info[*sub_surface_id].w = w;
394         this->area_info[*sub_surface_id].h = h;
395     } */
396
397     HMI_DEBUG("wm", "surface_set_layout for surface %u on layer %u", surface_id,
398               layer_id);
399
400     // set destination to the display rectangle
401     s->set_destination_rectangle(x, y, w, h);
402
403     // update area information
404     this->area_info[surface_id].x = x;
405     this->area_info[surface_id].y = y;
406     this->area_info[surface_id].w = w;
407     this->area_info[surface_id].h = h;
408
409     HMI_DEBUG("wm", "Surface %u now on layer %u with rect { %d, %d, %d, %d }",
410               surface_id, layer_id, x, y, w, h);
411 }
412
413 void App::layout_commit()
414 {
415     this->controller->commit_changes();
416     this->display->flush();
417 }
418
419 void App::setTimer()
420 {
421     HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Timer set activate");
422     if (g_timer_ev_src == nullptr)
423     {
424         // firsttime set into sd_event
425         int ret = sd_event_add_time(afb_daemon_get_event_loop(), &g_timer_ev_src,
426                                     CLOCK_REALTIME, time(NULL) * (1000000UL) + kTimeOut, 1, processTimerHandler, this);
427         if (ret < 0)
428         {
429             HMI_ERROR("wm", "Could't set timer");
430         }
431     }
432     else
433     {
434         // update timer limitation after second time
435         sd_event_source_set_time(g_timer_ev_src, time(NULL) * (1000000UL) + kTimeOut);
436         sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT);
437     }
438 }
439
440 void App::stopTimer()
441 {
442     unsigned req_num = g_app_list.currentRequestNumber();
443     HMI_SEQ_DEBUG(req_num, "Timer stop");
444     int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF);
445     if (rc < 0)
446     {
447         HMI_SEQ_ERROR(req_num, "Timer stop failed");
448     }
449 }
450
451 WMError App::lm_release(const struct WMAction &action)
452 {
453     //auto const &surface_id = this->lookup_id(drawing_name);
454     WMError ret = WMError::LAYOUT_CHANGE_FAIL;
455     unsigned req_num = g_app_list.currentRequestNumber();
456     auto const &surface_id = this->lookup_id(action.role.c_str());
457     if (!surface_id)
458     {
459         HMI_SEQ_ERROR(req_num, "Surface does not exist");
460         return ret;
461     }
462
463     if (*surface_id == this->layers.main_surface)
464     {
465         HMI_SEQ_ERROR(req_num, "Cannot deactivate main_surface");
466         return ret;
467     }
468
469     auto o_state = *this->layers.get_layout_state(*surface_id);
470
471     if (o_state == nullptr)
472     {
473         HMI_SEQ_ERROR(req_num, "Could not find layer for surface");
474         return ret;
475     }
476
477     struct LayoutState &state = *o_state;
478
479     if (state.main == -1)
480     {
481         HMI_SEQ_ERROR(req_num, "No surface active");
482         return ret;
483     }
484
485     // Check against main_surface, main_surface_name is the configuration item.
486     if (*surface_id == this->layers.main_surface)
487     {
488         HMI_SEQ_DEBUG(req_num, "Refusing to deactivate main_surface %d", *surface_id);
489         //reply(nullptr);
490         return WMError::SUCCESS;
491     }
492     if ((state.main == *surface_id) && (state.sub == *surface_id))
493     {
494         HMI_SEQ_ERROR(req_num, "Surface is not active");
495         return ret;
496     }
497
498     if (state.main == *surface_id)
499     {
500         if (state.sub != -1)
501         {
502             this->try_layout(
503                 state, LayoutState{state.sub, -1}, [&](LayoutState const &nl) {
504                     std::string sub = std::move(*this->lookup_name(state.sub));
505
506                     this->deactivate(*surface_id);
507                     this->surface_set_layout(state.sub);
508                     state = nl;
509
510                     this->layout_commit();
511                     std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
512                     compositor::rect area_rect = this->area_info[state.sub];
513                     this->emit_syncdraw(sub.c_str(), str_area.c_str(),
514                                         area_rect.x, area_rect.y, area_rect.w, area_rect.h);
515                     this->enqueue_flushdraw(state.sub);
516                 });
517         }
518         else
519         {
520             this->try_layout(state, LayoutState{-1, -1}, [&](LayoutState const &nl) {
521                 this->deactivate(*surface_id);
522                 state = nl;
523                 this->layout_commit();
524             });
525         }
526     }
527     else if (state.sub == *surface_id)
528     {
529         this->try_layout(
530             state, LayoutState{state.main, -1}, [&](LayoutState const &nl) {
531                 std::string main = std::move(*this->lookup_name(state.main));
532
533                 this->deactivate(*surface_id);
534                 this->surface_set_layout(state.main);
535                 state = nl;
536
537                 this->layout_commit();
538                 std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
539                 compositor::rect area_rect = this->area_info[state.main];
540                 this->emit_syncdraw(main.c_str(), str_area.c_str(),
541                                     area_rect.x, area_rect.y, area_rect.w, area_rect.h);
542                 this->enqueue_flushdraw(state.main);
543             });
544     }
545     return WMError::SUCCESS;
546 }
547
548 /* WMError App::lm_layout_change(const struct WMAction &action)
549 {
550     const char *msg = this->check_surface_exist(action.role.c_str());
551
552     if (msg)
553     {
554         HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), msg);
555         return WMError::LAYOUT_CHANGE_FAIL;
556     }
557     this->lm_layout_change(action.role.c_str());
558     return WMError::SUCCESS;
559 } */
560
561 WMError App::doTransition(unsigned req_num)
562 {
563     HMI_SEQ_DEBUG(req_num, "check policy");
564     WMError ret = this->checkPolicy(req_num);
565     if (ret != WMError::SUCCESS)
566     {
567         return ret;
568     }
569     HMI_SEQ_DEBUG(req_num, "Start transition.");
570     ret = this->startTransition(req_num);
571     return ret;
572 }
573
574 WMError App::checkPolicy(unsigned req_num)
575 {
576     /*
577     * Check Policy
578     */
579     // get current trigger
580     bool found = false;
581     bool split = false;
582     WMError ret = WMError::LAYOUT_CHANGE_FAIL;
583     auto trigger = g_app_list.getRequest(req_num, &found);
584     if (!found)
585     {
586         ret = WMError::NO_ENTRY;
587         return ret;
588     }
589     std::string req_area = trigger.area;
590
591     // >>>> Compatible with current window manager until policy manager coming
592     if (trigger.task == Task::TASK_ALLOCATE)
593     {
594         HMI_SEQ_DEBUG(req_num, "Check split or not");
595         const char *msg = this->check_surface_exist(trigger.role.c_str());
596
597         if (msg)
598         {
599             HMI_SEQ_ERROR(req_num, msg);
600             ret = WMError::LAYOUT_CHANGE_FAIL;
601             return ret;
602         }
603
604         auto const &surface_id = this->lookup_id(trigger.role.c_str());
605         auto o_state = *this->layers.get_layout_state(*surface_id);
606         struct LayoutState &state = *o_state;
607
608         unsigned curernt_sid = state.main;
609         split = this->can_split(state, *surface_id);
610
611         if (split)
612         {
613             HMI_SEQ_DEBUG(req_num, "Split happens");
614             // Get current visible role
615             std::string add_role = this->lookup_name(state.main).value();
616             // Set next area
617             std::string add_area = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaMain);
618             // Change request area
619             req_area = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaSub);
620             // set another action
621             std::string add_name = g_app_list.getAppID(curernt_sid, add_role, &found);
622             if (!found)
623             {
624                 HMI_SEQ_ERROR(req_num, "Couldn't widhdraw with surfaceID : %s", curernt_sid);
625                 ret = WMError::NOT_REGISTERED;
626                 return ret;
627             }
628             HMI_SEQ_INFO(req_num, "Additional split app %s, role: %s, area: %s",
629                          add_name.c_str(), add_role.c_str(), add_area.c_str());
630             // Set split action
631             bool visible = true;
632             bool end_draw_finished = false;
633             WMAction split_action{
634                 add_name,
635                 add_role,
636                 add_area,
637                 visible,
638                 end_draw_finished};
639             WMError ret = g_app_list.setAction(req_num, split_action);
640             if (ret != WMError::SUCCESS)
641             {
642                 HMI_SEQ_ERROR(req_num, "Failed to set action");
643                 return ret;
644             }
645             g_app_list.reqDump();
646         }
647     }
648     else
649     {
650         HMI_SEQ_DEBUG(req_num, "split doesn't happen");
651     }
652
653     // Set invisible task(Remove if policy manager finish)
654     ret = this->setInvisibleTask(trigger.role, split);
655     if(ret != WMError::SUCCESS)
656     {
657         HMI_SEQ_ERROR(req_num, "Failed to set invisible task: %s", errorDescription(ret));
658         return ret;
659     }
660
661     /*  get new status from Policy Manager */
662     HMI_SEQ_NOTICE(req_num, "ATM, Policy manager does't exist, then set WMAction as is");
663
664     ret = g_app_list.setAction(req_num, trigger.appid, trigger.role, req_area, trigger.task);
665     g_app_list.reqDump();
666
667     return ret;
668 }
669
670 WMError App::startTransition(unsigned req_num)
671 {
672     bool sync_draw_happen = false;
673     bool found = false;
674     WMError ret = WMError::SUCCESS;
675     auto actions = g_app_list.getActions(req_num, &found);
676     if (!found)
677     {
678         ret = WMError::NO_ENTRY;
679         HMI_SEQ_ERROR(req_num, "Window Manager bug :%s : Action is not set", errorDescription(ret));
680         return ret;
681     }
682
683     for (const auto &y : actions)
684     {
685         if (y.visible)
686         {
687             sync_draw_happen = true;
688             this->emit_syncdraw(y.role, y.area);
689             /* TODO: emit event for app not subscriber
690             if(g_app_list.contains(y.appid))
691                 g_app_list.lookUpClient(y.appid)->emit_syncdraw(y.role, y.area); */
692         }
693     }
694
695     if (sync_draw_happen)
696     {
697         this->setTimer();
698     }
699     else
700     {
701         // deactivate only, no syncDraw
702         // Make it deactivate here
703         for (const auto &z : actions)
704         {
705             if (g_app_list.contains(z.appid))
706             {
707                 auto client = g_app_list.lookUpClient(z.appid);
708                 this->deactivate(client->surfaceID(z.role));
709             }
710         }
711         ret = NO_LAYOUT_CHANGE;
712     }
713     return ret;
714 }
715
716 WMError App::setInvisibleTask(const std::string &role, bool split)
717 {
718     unsigned req = g_app_list.currentRequestNumber();
719     HMI_SEQ_DEBUG(req, "set current visible app to invisible task");
720     // This task is copied from original actiavete surface
721     const char *drawing_name = role.c_str();
722     auto const &surface_id = this->lookup_id(drawing_name);
723     auto layer_id = this->layers.get_layer_id(*surface_id);
724     auto o_state = *this->layers.get_layout_state(*surface_id);
725     struct LayoutState &state = *o_state;
726     std::string add_name, add_role;
727     std::string add_area = "";
728     int surface;
729     bool visible = false;
730     bool end_draw_finished = true;
731     bool found = false;
732
733     for (auto const &l : this->layers.mapping)
734     {
735         if (l.second.layer_id <= *layer_id)
736         {
737             continue;
738         }
739         if (l.second.state.main != -1)
740         {
741             //this->deactivate(l.second.state.main);
742             surface = l.second.state.main;
743             add_role = *this->id_alloc.lookup(surface);
744             add_name = g_app_list.getAppID(surface, add_role, &found);
745             if(!found){
746                 return WMError::NOT_REGISTERED;
747             }
748             HMI_SEQ_INFO(req, "Invisible %s", add_name.c_str());
749             WMAction act{add_name, add_role, add_area, visible, end_draw_finished};
750             g_app_list.setAction(req, act);
751             l.second.state.main = -1;
752         }
753
754         if (l.second.state.sub != -1)
755         {
756             //this->deactivate(l.second.state.sub);
757             surface = l.second.state.sub;
758             add_role = *this->id_alloc.lookup(surface);
759             add_name = g_app_list.getAppID(surface, add_role, &found);
760             if (!found)
761             {
762                 return WMError::NOT_REGISTERED;
763             }
764             HMI_SEQ_INFO(req, "Invisible %s", add_name.c_str());
765             WMAction act{add_name, add_role, add_area, visible, end_draw_finished};
766             g_app_list.setAction(req, act);
767             l.second.state.sub = -1;
768         }
769     }
770
771     // change current state here, but this is hack
772     auto layer = this->layers.get_layer(*layer_id);
773
774     if (state.main == -1)
775     {
776         HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
777         state = LayoutState{*surface_id};
778         /* this->try_layout(
779             state, LayoutState{*surface_id}, [&](LayoutState const &nl) {
780                 HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
781                 //this->surface_set_layout(*surface_id);
782                 state = nl;
783
784                 //compositor::rect area_rect = this->area_info[*surface_id];
785             }); */
786     }
787     else
788     {
789         if (0 != strcmp(drawing_name, "HomeScreen"))
790         {
791             if (split)
792             {
793                 std::string main =
794                     std::move(*this->id_alloc.lookup(state.main));
795                 if (state.sub != *surface_id)
796                 {
797                     if (state.sub != -1)
798                     {
799                         //this->deactivate(state.sub);
800                         WMAction deact_sub;
801                         deact_sub.role = main;
802                         deact_sub.area = add_area;
803                         deact_sub.appid = g_app_list.getAppID(state.sub, main, &found);
804                         if (!found)
805                         {
806                             HMI_SEQ_DEBUG(req, "sub surface ddoesn't exist");
807                             return WMError::NOT_REGISTERED;
808                         }
809                         deact_sub.visible = visible;
810                         deact_sub.end_draw_finished = end_draw_finished;
811                         HMI_SEQ_DEBUG(req, "sub surface ddoesn't exist");
812                         g_app_list.setAction(req, deact_sub);
813                     }
814                 }
815                 state = LayoutState{state.main, *surface_id};
816             }
817             else
818             {
819                 HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
820
821                 //this->surface_set_layout(*surface_id);
822                 if (state.main != *surface_id)
823                 {
824                     // this->deactivate(state.main);
825                     WMAction deact_main;
826                     deact_main.role = std::move(*this->id_alloc.lookup(state.main));
827                     ;
828                     deact_main.area = add_area;
829                     deact_main.appid = g_app_list.getAppID(state.main, deact_main.role, &found);
830                     if (!found)
831                     {
832                         HMI_SEQ_DEBUG(req, "sub surface ddoesn't exist");
833                         return WMError::NOT_REGISTERED;
834                     }
835                     deact_main.visible = visible;
836                     deact_main.end_draw_finished = end_draw_finished;
837                     HMI_SEQ_DEBUG(req, "sub surface doesn't exist");
838                     g_app_list.setAction(req, deact_main);
839                 }
840                 if (state.sub != -1)
841                 {
842                     if (state.sub != *surface_id)
843                     {
844                         //this->deactivate(state.sub);
845                         WMAction deact_sub;
846                         deact_sub.role = std::move(*this->id_alloc.lookup(state.sub));
847                         ;
848                         deact_sub.area = add_area;
849                         deact_sub.appid = g_app_list.getAppID(state.sub, deact_sub.role, &found);
850                         if (!found)
851                         {
852                             HMI_SEQ_DEBUG(req, "sub surface ddoesn't exist");
853                             return WMError::NOT_REGISTERED;
854                         }
855                         deact_sub.visible = visible;
856                         deact_sub.end_draw_finished = end_draw_finished;
857                         HMI_SEQ_DEBUG(req, "sub surface ddoesn't exist");
858                         g_app_list.setAction(req, deact_sub);
859                     }
860                 }
861                 state = LayoutState{*surface_id};
862             }
863         }
864     }
865
866     return WMError::SUCCESS;
867 }
868
869 /* void App::lm_layout_change(const char *drawing_name)
870 {
871     auto const &surface_id = this->lookup_id(drawing_name);
872     auto layer_id = this->layers.get_layer_id(*surface_id);
873     auto o_state = *this->layers.get_layout_state(*surface_id);
874     struct LayoutState &state = *o_state;
875
876     // disable layers that are above our current layer
877     for (auto const &l : this->layers.mapping)
878     {
879         if (l.second.layer_id <= *layer_id)
880         {
881             continue;
882         }
883
884         bool flush = false;
885         if (l.second.state.main != -1)
886         {
887             this->deactivate(l.second.state.main);
888             l.second.state.main = -1;
889             flush = true;
890         }
891
892         if (l.second.state.sub != -1)
893         {
894             this->deactivate(l.second.state.sub);
895             l.second.state.sub = -1;
896             flush = true;
897         }
898
899         if (flush)
900         {
901             this->layout_commit();
902         }
903     }
904
905     auto layer = this->layers.get_layer(*layer_id);
906
907     if (state.main == -1)
908     {
909         this->try_layout(
910             state, LayoutState{*surface_id}, [&](LayoutState const &nl) {
911                 HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
912                 this->surface_set_layout(*surface_id);
913                 state = nl;
914
915                 // Commit for configuraton
916                 this->layout_commit();
917
918                 std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
919                 compositor::rect area_rect = this->area_info[*surface_id];
920                 this->emit_syncdraw(drawing_name, str_area.c_str(),
921                                     area_rect.x, area_rect.y, area_rect.w, area_rect.h);
922                 this->enqueue_flushdraw(state.main);
923             });
924     }
925     else
926     {
927         if (0 == strcmp(drawing_name, "HomeScreen"))
928         {
929             this->try_layout(
930                 state, LayoutState{*surface_id}, [&](LayoutState const &nl) {
931                     HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
932                     std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
933                     compositor::rect area_rect = this->area_info[*surface_id];
934                     this->emit_syncdraw(drawing_name, str_area.c_str(),
935                                         area_rect.x, area_rect.y, area_rect.w, area_rect.h);
936                     this->enqueue_flushdraw(state.main);
937                 });
938         }
939         else
940         {
941             bool can_split = this->can_split(state, *surface_id);
942
943             if (can_split)
944             {
945                 this->try_layout(
946                     state,
947                     LayoutState{state.main, *surface_id},
948                     [&](LayoutState const &nl) {
949                         HMI_DEBUG("wm", "Layout: %s", kNameLayoutSplit);
950                         std::string main =
951                             std::move(*this->lookup_name(state.main));
952
953                         this->surface_set_layout(state.main, surface_id);
954                         if (state.sub != *surface_id)
955                         {
956                             if (state.sub != -1)
957                             {
958                                 this->deactivate(state.sub);
959                             }
960                         }
961                         state = nl;
962
963                         // Commit for configuration and visibility(0)
964                         this->layout_commit();
965
966                         std::string str_area_main = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaMain);
967                         std::string str_area_sub = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaSub);
968                         compositor::rect area_rect_main = this->area_info[state.main];
969                         compositor::rect area_rect_sub = this->area_info[*surface_id];
970                         // >>> HACK
971                         HMI_WARNING("wm", "HACK!!! mediaplayer and hvac is only supported for split");
972                         std::string request_role = drawing_name;
973                         //std::string request_app = transform(request_role.begin(), request_role.end(), request_role.begin(), tolower); //hvac or mediaplayer
974                         std::string hack_appid = "navigation";
975                         std::string hack_role = main;
976                         std::string hack_area = str_area_main;
977                         g_app_list.setAction(g_app_list.currentRequestNumber(), hack_appid, hack_role, hack_area, true);
978                         //g_app_list.setEndDrawFinished(g_app_list.currentRequestNumber(), request_role, request_role);
979                         //g_app_list.setEndDrawFinished(g_app_list.currentRequestNumber(), hack_appid, hack_role); // This process is illegal
980                         // >>> HACK
981                         this->emit_syncdraw(main.c_str(), str_area_main.c_str(),
982                                             area_rect_main.x, area_rect_main.y,
983                                             area_rect_main.w, area_rect_main.h);
984                         this->emit_syncdraw(request_role.c_str(), str_area_sub.c_str(),
985                                             area_rect_sub.x, area_rect_sub.y,
986                                             area_rect_sub.w, area_rect_sub.h);
987                         this->enqueue_flushdraw(state.main);
988                         this->enqueue_flushdraw(state.sub);
989                     });
990             }
991             else
992             {
993                 this->try_layout(
994                     state, LayoutState{*surface_id}, [&](LayoutState const &nl) {
995                         HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal);
996
997                         this->surface_set_layout(*surface_id);
998                         if (state.main != *surface_id)
999                         {
1000                             this->deactivate(state.main);
1001                         }
1002                         if (state.sub != -1)
1003                         {
1004                             if (state.sub != *surface_id)
1005                             {
1006                                 this->deactivate(state.sub);
1007                             }
1008                         }
1009                         state = nl;
1010
1011                         // Commit for configuraton and visibility(0)
1012                         this->layout_commit();
1013
1014                         std::string str_area = std::string(kNameLayoutNormal) + "." + std::string(kNameAreaFull);
1015                         compositor::rect area_rect = this->area_info[*surface_id];
1016                         this->emit_syncdraw(drawing_name, str_area.c_str(),
1017                                             area_rect.x, area_rect.y, area_rect.w, area_rect.h);
1018                         this->enqueue_flushdraw(state.main);
1019                     });
1020             }
1021         }
1022     }
1023 } */
1024
1025 const char *App::check_surface_exist(const char *drawing_name)
1026 {
1027     auto const &surface_id = this->lookup_id(drawing_name);
1028     if (!surface_id)
1029     {
1030         //reply("Surface does not exist");
1031         return "Surface does not exist";
1032     }
1033
1034     if (!this->controller->surface_exists(*surface_id))
1035     {
1036         //reply("Surface does not exist in controller!");
1037         return "Surface does not exist in controller!";
1038     }
1039
1040     auto layer_id = this->layers.get_layer_id(*surface_id);
1041
1042     if (!layer_id)
1043     {
1044         //reply("Surface is not on any layer!");
1045         return "Surface is not on any layer!";
1046     }
1047
1048     auto o_state = *this->layers.get_layout_state(*surface_id);
1049
1050     if (o_state == nullptr)
1051     {
1052         //reply("Could not find layer for surface");
1053         return "Could not find layer for surface";
1054     }
1055
1056     HMI_DEBUG("wm", "surface %d is detected", *surface_id);
1057     return nullptr;
1058     //reply(nullptr);
1059 }
1060
1061 WMError App::setRequest(const std::string& appid, const std::string &role, const std::string &area,
1062                             Task task, unsigned* req_num)
1063 {
1064     if (!g_app_list.contains(appid))
1065     {
1066         return WMError::NOT_REGISTERED;
1067     }
1068
1069     auto client = g_app_list.lookUpClient(appid);
1070
1071     /*
1072    * Queueing Phase
1073    */
1074     unsigned current = g_app_list.currentRequestNumber();
1075     unsigned requested_num = g_app_list.getRequestNumber(appid);
1076     if (requested_num != 0)
1077     {
1078         HMI_SEQ_INFO(requested_num, "%s %s %s request is already queued", appid.c_str(), role.c_str(), area.c_str());
1079         return REQ_REJECTED;
1080     }
1081
1082     WMRequest req = WMRequest(appid, role, area, task);
1083     unsigned new_req = g_app_list.addAllocateRequest(req);
1084     *req_num = new_req;
1085     g_app_list.reqDump();
1086
1087     HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", appid.c_str(), role.c_str(), area.c_str());
1088
1089     return WMError::SUCCESS;
1090 }
1091
1092 void App::api_activate_surface(char const *appid, char const *drawing_name, char const *drawing_area, const reply_func &reply)
1093 {
1094     ST();
1095
1096     std::string id = appid;
1097     std::string role = drawing_name;
1098     std::string area = drawing_area;
1099     Task task = Task::TASK_ALLOCATE;
1100     unsigned req_num = 0;
1101     WMError ret = WMError::UNKNOWN;
1102
1103     ret = this->setRequest(id, role, area, task, &req_num);
1104
1105     if(ret != WMError::SUCCESS)
1106     {
1107         HMI_ERROR("wm", errorDescription(ret));
1108         reply("Failed to set request");
1109         return;
1110     }
1111
1112     reply(nullptr);
1113     if (req_num != g_app_list.currentRequestNumber())
1114     {
1115         // Add request, then invoked after the previous task is finished
1116         HMI_SEQ_DEBUG(req_num, "request is accepted");
1117         return;
1118     }
1119
1120     /*
1121     * Do allocate tasks
1122     */
1123     ret = this->doTransition(req_num);
1124
1125     if (ret != WMError::SUCCESS)
1126     {
1127         //this->emit_error()
1128         HMI_SEQ_ERROR(req_num, errorDescription(ret));
1129         g_app_list.removeRequest(req_num);
1130         g_app_list.next();
1131         g_app_list.reqDump();
1132     }
1133 }
1134
1135 void App::api_deactivate_surface(char const *appid, char const *drawing_name, const reply_func &reply)
1136 {
1137     ST();
1138
1139     /*
1140    * Check Phase
1141    */
1142     std::string id = appid;
1143     std::string role = drawing_name;
1144     std::string area = ""; //drawing_area;
1145
1146     if (!g_app_list.contains(id))
1147     {
1148         reply("app doesn't request 'requestSurface' yet");
1149         return;
1150     }
1151     auto client = g_app_list.lookUpClient(id);
1152
1153     /*
1154    * Queueing Phase
1155    */
1156     unsigned current = g_app_list.currentRequestNumber();
1157     unsigned requested_num = g_app_list.getRequestNumber(id);
1158     if (requested_num != 0)
1159     {
1160         HMI_SEQ_INFO(requested_num, "%s %s %s request is already queued", id.c_str(), role.c_str(), area.c_str());
1161         reply("already requested");
1162         return;
1163     }
1164
1165     WMRequest req = WMRequest(id, role, area, Task::TASK_RELEASE);
1166     unsigned new_req = g_app_list.addAllocateRequest(req);
1167     g_app_list.reqDump();
1168
1169     HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", id.c_str(), role.c_str(), area.c_str());
1170
1171     reply(nullptr);
1172     if (new_req != current)
1173     {
1174         // Add request, then invoked after the previous task is finished
1175         HMI_SEQ_DEBUG(new_req, "request is accepted");
1176         return;
1177     }
1178
1179     /*
1180     * Do allocate tasks
1181     */
1182     WMError ret = this->doTransition(new_req);
1183
1184     if (ret != WMError::SUCCESS)
1185     {
1186         HMI_SEQ_ERROR(new_req, errorDescription(ret));
1187         g_app_list.removeRequest(new_req);
1188         g_app_list.next();
1189         //this->emit_error()
1190     }
1191 }
1192
1193 void App::enqueue_flushdraw(int surface_id)
1194 {
1195     this->check_flushdraw(surface_id);
1196     HMI_DEBUG("wm", "Enqueuing EndDraw for surface_id %d", surface_id);
1197     this->pending_end_draw.push_back(surface_id);
1198 }
1199
1200 void App::check_flushdraw(int surface_id)
1201 {
1202     auto i = std::find(std::begin(this->pending_end_draw),
1203                        std::end(this->pending_end_draw), surface_id);
1204     if (i != std::end(this->pending_end_draw))
1205     {
1206         auto n = this->lookup_name(surface_id);
1207         HMI_ERROR("wm", "Application %s (%d) has pending EndDraw call(s)!",
1208                   n ? n->c_str() : "unknown-name", surface_id);
1209         std::swap(this->pending_end_draw[std::distance(
1210                       std::begin(this->pending_end_draw), i)],
1211                   this->pending_end_draw.back());
1212         this->pending_end_draw.resize(this->pending_end_draw.size() - 1);
1213     }
1214 }
1215
1216 /* void App::lm_enddraw(const char *drawing_name)
1217 {
1218     HMI_DEBUG("wm", "end draw %s", drawing_name);
1219     for (unsigned i = 0, iend = this->pending_end_draw.size(); i < iend; i++)
1220     {
1221         auto n = this->lookup_name(this->pending_end_draw[i]);
1222         if (n && *n == drawing_name)
1223         {
1224             std::swap(this->pending_end_draw[i], this->pending_end_draw[iend - 1]);
1225             this->pending_end_draw.resize(iend - 1);
1226             this->activate(this->pending_end_draw[i]);
1227             this->emit_flushdraw(drawing_name);
1228         }
1229     }
1230 } */
1231
1232 WMError App::doEndDraw(unsigned req_num)
1233 {
1234     // get actions
1235     bool found;
1236     auto actions = g_app_list.getActions(req_num, &found);
1237     WMError ret = WMError::SUCCESS;
1238     if (!found)
1239     {
1240         ret = WMError::NO_ENTRY;
1241         return ret;
1242     }
1243
1244     HMI_SEQ_INFO(req_num, "do endDraw");
1245     // layout change and make it visible
1246
1247     // Temporary action
1248     /* auto itr = actions.cend();
1249     this->currentAppInvisible(itr->role); */
1250
1251     for (const auto &act : actions)
1252     {
1253         // layout change
1254         if(!g_app_list.contains(act.appid)){
1255             ret = WMError::NOT_REGISTERED;
1256         }
1257         ret = this->layoutChange(act);
1258         if(ret != WMError::SUCCESS)
1259         {
1260             HMI_SEQ_WARNING(req_num, "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1261             return ret;
1262         }
1263         ret = this->visibilityChange(act);
1264         if (ret != WMError::SUCCESS)
1265         {
1266             HMI_SEQ_WARNING(req_num, "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1267             return ret;
1268         }
1269         HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str());
1270         //this->lm_enddraw(act.role.c_str());
1271     }
1272
1273     HMI_SEQ_INFO(req_num, "emit flushDraw");
1274
1275     for(const auto &act_flush : actions)
1276     {
1277         if(act_flush.visible)
1278         {
1279             this->emit_flushdraw(act_flush.role.c_str());
1280         }
1281     }
1282
1283     return ret;
1284 }
1285
1286 WMError App::setSurfaceSize(unsigned surface, const std::string &area)
1287 {
1288     // Actually this function is under Layout Manager
1289     /* compositor::rect size = this->lm.getAreaSize(area); // compositor::rect size = this->lm_.getAreaSize(area);
1290
1291     if (!this->controller->surface_exists(surface))
1292     {
1293         // Block until all pending request are processed by wayland display server
1294         // because waiting for the surface of new app is created
1295         this->display->roundtrip();
1296     }
1297     auto &s = this->controller->surfaces[surface];
1298     s->set_destination_rectangle(size.x, size.y, size.w, size.h);
1299     this->layout_commit();
1300
1301     // Update area information
1302     this->area_info[surface].x = size.x;
1303     this->area_info[surface].y = size.y;
1304     this->area_info[surface].w = size.w;
1305     this->area_info[surface].h = size.h;
1306     HMI_DEBUG("wm", "Surface %d rect { %d, %d, %d, %d }",
1307               surface, size.x, size.y, size.w, size.h); */
1308     this->surface_set_layout(surface);
1309
1310     return WMError::SUCCESS;
1311 }
1312
1313 WMError App::layoutChange(const WMAction &action)
1314 {
1315     if (action.visible == false)
1316     {
1317         return WMError::SUCCESS;
1318     }
1319     auto client = g_app_list.lookUpClient(action.appid);
1320     unsigned surface = client->surfaceID(action.role);
1321     if (surface == 0)
1322     {
1323         HMI_SEQ_ERROR(g_app_list.currentRequestNumber(),
1324                       "client doesn't have surface with role(%s)", action.role.c_str());
1325         return WMError::NOT_REGISTERED;
1326     }
1327     // Layout Manager
1328     WMError ret = this->setSurfaceSize(surface, action.area);
1329     return ret;
1330 }
1331
1332 /* void App::currentAppInvisible(const std::string &role)
1333 {
1334     const char *drawing_name = role.c_str();
1335     auto const &surface_id = this->lookup_id(drawing_name);
1336     auto layer_id = this->layers.get_layer_id(*surface_id);
1337     auto o_state = *this->layers.get_layout_state(*surface_id);
1338     struct LayoutState &state = *o_state;
1339
1340     // disable layers that are above our current layer
1341     for (auto const &l : this->layers.mapping)
1342     {
1343         if (l.second.layer_id <= *layer_id)
1344         {
1345             continue;
1346         }
1347
1348         bool flush = false;
1349         if (l.second.state.main != -1)
1350         {
1351             this->deactivate(l.second.state.main);
1352             l.second.state.main = -1;
1353             flush = true;
1354         }
1355
1356         if (l.second.state.sub != -1)
1357         {
1358             this->deactivate(l.second.state.sub);
1359             l.second.state.sub = -1;
1360             flush = true;
1361         }
1362
1363         if (flush)
1364         {
1365             this->layout_commit();
1366         }
1367     }
1368 } */
1369
1370 WMError App::visibilityChange(const WMAction &action)
1371 {
1372     auto client = g_app_list.lookUpClient(action.appid);
1373     unsigned surface = client->surfaceID(action.role);
1374     if(surface == 0)
1375     {
1376         HMI_SEQ_ERROR(g_app_list.currentRequestNumber(),
1377                       "client doesn't have surface with role(%s)", action.role.c_str());
1378         return WMError::NOT_REGISTERED;
1379     }
1380
1381     if (action.visible)
1382     {
1383         this->activate(surface); // Layout Manager task
1384     }
1385     else
1386     {
1387         this->deactivate(surface); // Layout Manager task
1388     }
1389     return WMError::SUCCESS;
1390 }
1391
1392 void App::api_enddraw(char const *appid, char const *drawing_name)
1393 {
1394     std::string id = appid;
1395     std::string role = drawing_name;
1396     unsigned current_req = g_app_list.currentRequestNumber();
1397     bool result = g_app_list.setEndDrawFinished(current_req, id, role);
1398
1399     if (!result)
1400     {
1401         HMI_ERROR("wm", "%s is not in transition state", id.c_str());
1402         return;
1403     }
1404
1405     if (g_app_list.endDrawFullfilled(current_req))
1406     {
1407         // do task for endDraw
1408         this->stopTimer();
1409         WMError ret = this->doEndDraw(current_req);
1410
1411         if(ret != WMError::SUCCESS)
1412         {
1413             //this->emit_error();
1414         }
1415         HMI_SEQ_INFO(current_req, "Finish request status: %s", errorDescription(ret));
1416
1417         g_app_list.removeRequest(current_req);
1418
1419         this->processNextRequest();
1420     }
1421     else
1422     {
1423         HMI_SEQ_INFO(current_req, "Wait other App call endDraw");
1424         return;
1425     }
1426 }
1427
1428 void App::processNextRequest()
1429 {
1430     g_app_list.next();
1431     g_app_list.reqDump();
1432     unsigned req_num = g_app_list.currentRequestNumber();
1433     if (g_app_list.haveRequest())
1434     {
1435         HMI_SEQ_DEBUG(req_num, "Process next request");
1436         WMError rc = doTransition(req_num);
1437         if (rc != WMError::SUCCESS)
1438         {
1439             HMI_SEQ_ERROR(req_num, errorDescription(rc));
1440         }
1441     }
1442     else
1443     {
1444         HMI_SEQ_DEBUG(req_num, "Nothing Request. Waiting Request");
1445     }
1446 }
1447
1448 void App::api_ping() { this->dispatch_pending_events(); }
1449
1450 void App::send_event(char const *evname, char const *label)
1451 {
1452     HMI_DEBUG("wm", "%s: %s(%s)", __func__, evname, label);
1453
1454     json_object *j = json_object_new_object();
1455     json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
1456
1457     int ret = afb_event_push(this->map_afb_event[evname], j);
1458     if (ret != 0)
1459     {
1460         HMI_DEBUG("wm", "afb_event_push failed: %m");
1461     }
1462 }
1463
1464 void App::send_event(char const *evname, char const *label, char const *area,
1465                      int x, int y, int w, int h)
1466 {
1467     HMI_DEBUG("wm", "%s: %s(%s, %s) x:%d y:%d w:%d h:%d",
1468               __func__, evname, label, area, x, y, w, h);
1469
1470     json_object *j_rect = json_object_new_object();
1471     json_object_object_add(j_rect, kKeyX, json_object_new_int(x));
1472     json_object_object_add(j_rect, kKeyY, json_object_new_int(y));
1473     json_object_object_add(j_rect, kKeyWidth, json_object_new_int(w));
1474     json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
1475
1476     json_object *j = json_object_new_object();
1477     json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
1478     json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area));
1479     json_object_object_add(j, kKeyDrawingRect, j_rect);
1480
1481     int ret = afb_event_push(this->map_afb_event[evname], j);
1482     if (ret != 0)
1483     {
1484         HMI_DEBUG("wm", "afb_event_push failed: %m");
1485     }
1486 }
1487
1488 /**
1489  * proxied events
1490  */
1491 void App::surface_created(uint32_t surface_id)
1492 {
1493     auto layer_id = this->layers.get_layer_id(surface_id);
1494     if (!layer_id)
1495     {
1496         HMI_DEBUG("wm", "Newly created surfce %d is not associated with any layer!",
1497                   surface_id);
1498         return;
1499     }
1500
1501     HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", surface_id, *layer_id);
1502
1503     this->controller->layers[*layer_id]->add_surface(surface_id);
1504     this->layout_commit();
1505     // activate the main_surface right away
1506     /*if (surface_id == static_cast<unsigned>(this->layers.main_surface)) {
1507       HMI_DEBUG("wm", "Activating main_surface (%d)", surface_id);
1508
1509       this->api_activate_surface(
1510          this->lookup_name(surface_id).value_or("unknown-name").c_str());
1511    }*/
1512
1513     // search pid from surfaceID
1514
1515     // pick up appid from pid from application manager
1516
1517     // check appid then add it to the client
1518 }
1519
1520 void App::surface_removed(uint32_t surface_id)
1521 {
1522     HMI_DEBUG("wm", "surface_id is %u", surface_id);
1523
1524     g_app_list.removeSurface(surface_id);
1525 }
1526
1527 void App::emit_activated(char const *label)
1528 {
1529     this->send_event(kListEventName[Event_Active], label);
1530 }
1531
1532 void App::emit_deactivated(char const *label)
1533 {
1534     this->send_event(kListEventName[Event_Inactive], label);
1535 }
1536
1537 void App::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h)
1538 {
1539     this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
1540 }
1541
1542 void App::emit_syncdraw(const std::string &role, const std::string &area)
1543 {
1544     int x = 0, y = 0, w = 0, h = 0;
1545     //this->lm_get_area_info(area, &x, &y, &w, &h);
1546     this->send_event(kListEventName[Event_SyncDraw],
1547         role.c_str(), area.c_str(), x, y, w, h);
1548 }
1549
1550 void App::emit_flushdraw(char const *label)
1551 {
1552     this->send_event(kListEventName[Event_FlushDraw], label);
1553 }
1554
1555 void App::emit_visible(char const *label, bool is_visible)
1556 {
1557     this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
1558 }
1559
1560 void App::emit_invisible(char const *label)
1561 {
1562     return emit_visible(label, false);
1563 }
1564
1565 void App::emit_visible(char const *label) { return emit_visible(label, true); }
1566
1567 result<int> App::api_request_surface(char const *appid, char const *drawing_name)
1568 {
1569     auto lid = this->layers.get_layer_id(std::string(drawing_name));
1570     if (!lid)
1571     {
1572         /**
1573        * register drawing_name as fallback and make it displayed.
1574        */
1575         lid = this->layers.get_layer_id(std::string("Fallback"));
1576         HMI_DEBUG("wm", "%s is not registered in layers.json, then fallback as normal app", drawing_name);
1577         if (!lid)
1578         {
1579             return Err<int>("Drawing name does not match any role, Fallback is disabled");
1580         }
1581     }
1582
1583     auto rname = this->lookup_id(drawing_name);
1584     if (!rname)
1585     {
1586         // name does not exist yet, allocate surface id...
1587         auto id = int(this->id_alloc.generate_id(drawing_name));
1588         this->layers.add_surface(id, *lid);
1589
1590         // set the main_surface[_name] here and now
1591         if (!this->layers.main_surface_name.empty() &&
1592             this->layers.main_surface_name == drawing_name)
1593         {
1594             this->layers.main_surface = id;
1595             HMI_DEBUG("wm", "Set main_surface id to %u", id);
1596         }
1597
1598         // add client into the db
1599         std::string appid_str(appid);
1600         std::string role(drawing_name);
1601         //g_app_list.addClient(appid_str, role);
1602         g_app_list.addClient(appid_str, *lid, id, role);
1603
1604         return Ok<int>(id);
1605     }
1606
1607     // Check currently registered drawing names if it is already there.
1608     return Err<int>("Surface already present");
1609 }
1610
1611 char const *App::api_request_surface(char const *appid, char const *drawing_name,
1612                                      char const *ivi_id)
1613 {
1614     ST();
1615
1616     auto lid = this->layers.get_layer_id(std::string(drawing_name));
1617     unsigned sid = std::stol(ivi_id);
1618
1619     if (!lid)
1620     {
1621         /**
1622        * register drawing_name as fallback and make it displayed.
1623        */
1624         lid = this->layers.get_layer_id(std::string("Fallback"));
1625         HMI_DEBUG("wm", "%s is not registered in layers.json, then fallback as normal app", drawing_name);
1626         if (!lid)
1627         {
1628             return "Drawing name does not match any role, Fallback is disabled";
1629         }
1630     }
1631
1632     auto rname = this->lookup_id(drawing_name);
1633
1634     if (rname)
1635     {
1636         return "Surface already present";
1637     }
1638
1639     // register pair drawing_name and ivi_id
1640     this->id_alloc.register_name_id(drawing_name, sid);
1641     this->layers.add_surface(sid, *lid);
1642
1643     // this surface is already created
1644     HMI_DEBUG("wm", "surface_id is %u, layer_id is %u", sid, *lid);
1645
1646     this->controller->layers[*lid]->add_surface(sid);
1647     this->layout_commit();
1648
1649     return nullptr;
1650 }
1651
1652 result<json_object *> App::api_get_display_info()
1653 {
1654     // Check controller
1655     if (!this->controller)
1656     {
1657         return Err<json_object *>("ivi_controller global not available");
1658     }
1659
1660     // Set display info
1661     compositor::size o_size = this->controller->output_size;
1662     compositor::size p_size = this->controller->physical_size;
1663
1664     json_object *object = json_object_new_object();
1665     json_object_object_add(object, kKeyWidthPixel, json_object_new_int(o_size.w));
1666     json_object_object_add(object, kKeyHeightPixel, json_object_new_int(o_size.h));
1667     json_object_object_add(object, kKeyWidthMm, json_object_new_int(p_size.w));
1668     json_object_object_add(object, kKeyHeightMm, json_object_new_int(p_size.h));
1669
1670     return Ok<json_object *>(object);
1671 }
1672
1673 result<json_object *> App::api_get_area_info(char const *drawing_name)
1674 {
1675     HMI_DEBUG("wm", "called");
1676
1677     // Check drawing name, surface/layer id
1678     auto const &surface_id = this->lookup_id(drawing_name);
1679     if (!surface_id)
1680     {
1681         return Err<json_object *>("Surface does not exist");
1682     }
1683
1684     if (!this->controller->surface_exists(*surface_id))
1685     {
1686         return Err<json_object *>("Surface does not exist in controller!");
1687     }
1688
1689     auto layer_id = this->layers.get_layer_id(*surface_id);
1690     if (!layer_id)
1691     {
1692         return Err<json_object *>("Surface is not on any layer!");
1693     }
1694
1695     auto o_state = *this->layers.get_layout_state(*surface_id);
1696     if (o_state == nullptr)
1697     {
1698         return Err<json_object *>("Could not find layer for surface");
1699     }
1700
1701     struct LayoutState &state = *o_state;
1702     if ((state.main != *surface_id) && (state.sub != *surface_id))
1703     {
1704         return Err<json_object *>("Surface is inactive");
1705     }
1706
1707     // Set area rectangle
1708     compositor::rect area_info = this->area_info[*surface_id];
1709     json_object *object = json_object_new_object();
1710     json_object_object_add(object, kKeyX, json_object_new_int(area_info.x));
1711     json_object_object_add(object, kKeyY, json_object_new_int(area_info.y));
1712     json_object_object_add(object, kKeyWidth, json_object_new_int(area_info.w));
1713     json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
1714
1715     return Ok<json_object *>(object);
1716 }
1717
1718 void App::activate(int id)
1719 {
1720     auto ip = this->controller->sprops.find(id);
1721     if (ip != this->controller->sprops.end())
1722     {
1723         this->controller->surfaces[id]->set_visibility(1);
1724         char const *label =
1725             this->lookup_name(id).value_or("unknown-name").c_str();
1726
1727         // FOR CES DEMO >>>
1728         if ((0 == strcmp(label, "Radio")) || (0 == strcmp(label, "MediaPlayer")) || (0 == strcmp(label, "Music")) || (0 == strcmp(label, "Navigation")))
1729         {
1730             for (auto i = surface_bg.begin(); i != surface_bg.end(); ++i)
1731             {
1732                 if (id == *i)
1733                 {
1734                     // Remove id
1735                     this->surface_bg.erase(i);
1736
1737                     // Remove from BG layer (999)
1738                     HMI_DEBUG("wm", "Remove %s(%d) from BG layer", label, id);
1739                     this->controller->layers[999]->remove_surface(id);
1740
1741                     // Add to FG layer (1001)
1742                     HMI_DEBUG("wm", "Add %s(%d) to FG layer", label, id);
1743                     this->controller->layers[1001]->add_surface(id);
1744
1745                     for (int j : this->surface_bg)
1746                     {
1747                         HMI_DEBUG("wm", "Stored id:%d", j);
1748                     }
1749                     break;
1750                 }
1751             }
1752         }
1753         // <<< FOR CES DEMO
1754         this->layout_commit();
1755
1756         this->emit_visible(label);
1757         this->emit_activated(label);
1758     }
1759 }
1760
1761 void App::deactivate(int id)
1762 {
1763     auto ip = this->controller->sprops.find(id);
1764     if (ip != this->controller->sprops.end())
1765     {
1766         char const *label =
1767             this->lookup_name(id).value_or("unknown-name").c_str();
1768
1769         // FOR CES DEMO >>>
1770         if ((0 == strcmp(label, "Radio")) || (0 == strcmp(label, "MediaPlayer")) || (0 == strcmp(label, "Music")) || (0 == strcmp(label, "Navigation")))
1771         {
1772
1773             // Store id
1774             this->surface_bg.push_back(id);
1775
1776             // Remove from FG layer (1001)
1777             HMI_DEBUG("wm", "Remove %s(%d) from FG layer", label, id);
1778             this->controller->layers[1001]->remove_surface(id);
1779
1780             // Add to BG layer (999)
1781             HMI_DEBUG("wm", "Add %s(%d) to BG layer", label, id);
1782             this->controller->layers[999]->add_surface(id);
1783
1784             for (int j : surface_bg)
1785             {
1786                 HMI_DEBUG("wm", "Stored id:%d", j);
1787             }
1788         }
1789         else
1790         {
1791             this->controller->surfaces[id]->set_visibility(0);
1792         }
1793         // <<< FOR CES DEMO
1794
1795         this->emit_deactivated(label);
1796         this->emit_invisible(label);
1797     }
1798 }
1799
1800 void App::deactivate_main_surface()
1801 {
1802     this->layers.main_surface = -1;
1803     std::string appid = "HomeScreen";
1804     this->api_deactivate_surface(appid.c_str(), this->layers.main_surface_name.c_str(), [](const char *) {});
1805 }
1806
1807 bool App::can_split(struct LayoutState const &state, int new_id)
1808 {
1809     if (state.main != -1 && state.main != new_id)
1810     {
1811         auto new_id_layer = this->layers.get_layer_id(new_id).value();
1812         auto current_id_layer = this->layers.get_layer_id(state.main).value();
1813
1814         // surfaces are on separate layers, don't bother.
1815         if (new_id_layer != current_id_layer)
1816         {
1817             return false;
1818         }
1819
1820         std::string const &new_id_str = this->lookup_name(new_id).value();
1821         std::string const &cur_id_str = this->lookup_name(state.main).value();
1822
1823         auto const &layer = this->layers.get_layer(new_id_layer);
1824
1825         HMI_DEBUG("wm", "layer info name: %s", layer->name.c_str());
1826
1827         if (layer->layouts.empty())
1828         {
1829             return false;
1830         }
1831
1832         for (auto i = layer->layouts.cbegin(); i != layer->layouts.cend(); i++)
1833         {
1834             HMI_DEBUG("wm", "%d main_match '%s'", new_id_layer, i->main_match.c_str());
1835             auto rem = std::regex(i->main_match);
1836             if (std::regex_match(cur_id_str, rem))
1837             {
1838                 // build the second one only if the first already matched
1839                 HMI_DEBUG("wm", "%d sub_match '%s'", new_id_layer, i->sub_match.c_str());
1840                 auto res = std::regex(i->sub_match);
1841                 if (std::regex_match(new_id_str, res))
1842                 {
1843                     HMI_DEBUG("wm", "layout matched!");
1844                     return true;
1845                 }
1846             }
1847         }
1848     }
1849
1850     return false;
1851 }
1852
1853 void App::try_layout(struct LayoutState & /*state*/,
1854                      struct LayoutState const &new_layout,
1855                      std::function<void(LayoutState const &nl)> apply)
1856 {
1857     if (this->policy.layout_is_valid(new_layout))
1858     {
1859         apply(new_layout);
1860     }
1861 }
1862
1863 /**
1864  * controller_hooks
1865  */
1866 void controller_hooks::surface_created(uint32_t surface_id)
1867 {
1868     this->app->surface_created(surface_id);
1869 }
1870
1871 void controller_hooks::surface_removed(uint32_t surface_id)
1872 {
1873     this->app->surface_removed(surface_id);
1874 }
1875
1876 void controller_hooks::surface_visibility(uint32_t /*surface_id*/,
1877                                           uint32_t /*v*/) {}
1878
1879 void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/,
1880                                                      uint32_t /*x*/,
1881                                                      uint32_t /*y*/,
1882                                                      uint32_t /*w*/,
1883                                                      uint32_t /*h*/) {}
1884
1885 } // namespace wm