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