Fix app surface is set to position (0, 0)
[apps/agl-service-windowmanager.git] / src / wm_layer_control.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 #include <assert.h>
17 #include <unistd.h>
18 #include "wm_layer_control.hpp"
19 #include "wm_layer.hpp"
20 #include "wm_client.hpp"
21 #include "request.hpp"
22 #include "json_helper.hpp"
23
24 #define LC_AREA_PATH "/etc/areas.json"
25 #define LC_LAYER_SETTING_PATH "/etc/layers.json"
26 #define LC_DEFAULT_AREA "fullscreen"
27 #define BACK_GROUND_LAYER "BackGroundLayer"
28
29 using std::string;
30 using std::vector;
31 using std::shared_ptr;
32
33 namespace wm {
34
35 LayerControl* g_lc_ctxt;
36
37 static void createCallback_static(ilmObjectType object,
38                             t_ilm_uint id,
39                             t_ilm_bool created,
40                             void* data)
41 {
42     static_cast<LayerControl*>(data)->dispatchCreateEvent(object, id, created);
43 }
44
45 static void surfaceCallback_static(t_ilm_surface surface,
46             struct ilmSurfaceProperties* surface_prop,
47             t_ilm_notification_mask mask)
48 {
49     g_lc_ctxt->dispatchSurfacePropChangeEvent(surface, surface_prop, mask);
50 }
51
52 static void layerCallback_static(t_ilm_layer layer,
53             struct ilmLayerProperties* layer_prop,
54             t_ilm_notification_mask mask)
55 {
56     g_lc_ctxt->dispatchLayerPropChangeEvent(layer, layer_prop, mask);
57 }
58
59 LayerControl::LayerControl(const std::string& root)
60 {
61     string area_path = root + LC_AREA_PATH;
62     string layer_path= root + LC_LAYER_SETTING_PATH;
63     // load layers.setting.json
64     WMError ret = this->loadLayerSetting(layer_path);
65     assert(ret == WMError::SUCCESS);
66     // load areas.json
67     ret = this->loadAreaDb(area_path);
68     assert(ret == WMError::SUCCESS);
69 }
70
71 WMError LayerControl::init(const LayerControlCallbacks& cb)
72 {
73     HMI_DEBUG("Initialize of ilm library and display");
74     t_ilm_uint num = 0;
75     t_ilm_uint *ids;
76     int cnt = 0;
77     ilmErrorTypes rc = ilm_init();
78
79     while (rc != ILM_SUCCESS)
80     {
81         cnt++;
82         if (20 <= cnt)
83         {
84             HMI_ERROR("Could not connect to compositor");
85             goto lc_init_error;
86         }
87         HMI_ERROR("Wait to start weston ...");
88         sleep(1);
89         rc = ilm_init();
90     }
91     if(rc != ILM_SUCCESS) goto lc_init_error;
92
93     // Get current screen setting
94     rc = ilm_getScreenIDs(&num, &ids);
95
96     if(rc != ILM_SUCCESS) goto lc_init_error;
97
98     for(unsigned i = 0; i < num; i++)
99     {
100         HMI_INFO("get screen: %d", ids[i]);
101     }
102     // Currently, 0 is only available
103     this->screenID = ids[0];
104
105     rc = ilm_getPropertiesOfScreen(this->screenID, &this->screen_prop);
106
107     if(rc != ILM_SUCCESS) goto lc_init_error;
108
109     // Register Callback to Window Manager and from ILM
110     this->cb = cb;
111     ilm_registerNotification(createCallback_static, this);
112
113     return WMError::SUCCESS;
114
115 lc_init_error:
116     HMI_ERROR("Failed to initialize. Terminate WM");
117
118     return WMError::FAIL;
119 }
120
121 void LayerControl::createNewLayer(unsigned id)
122 {
123     HMI_INFO("create new ID :%d", id);
124     struct rect rct = this->area2size[LC_DEFAULT_AREA];
125     ilm_layerCreateWithDimension(&id, rct.w, rct.h);
126     //ilm_layerSetSourceRectangle(id, rct.x, rct.y, rct.w, rct.h);
127     ilm_layerSetDestinationRectangle(id, this->offset_x, this->offset_y, rct.w, rct.h);
128     ilm_layerSetOpacity(id, 1.0);
129     ilm_layerSetVisibility(id, ILM_FALSE);
130     ilm_commitChanges();
131     auto wm_layer = getWMLayer(id);
132     wm_layer->addLayerToState(id);
133     this->renderLayers();
134 }
135
136 unsigned LayerControl::getNewLayerID(const string& role)
137 {
138     unsigned ret = 0;
139     for(const auto& l: this->wm_layers)
140     {
141         ret = l->getNewLayerID(role);
142         if(ret != 0)
143         {
144             unsigned wmlid = l->getWMLayerID();
145             this->lid2wmlid[ret] = wmlid;
146             break;
147         }
148     }
149     return ret;
150 }
151
152 shared_ptr<WMLayer> LayerControl::getWMLayer(unsigned layer)
153 {
154     unsigned wm_lid = this->lid2wmlid[layer];
155     return this->wm_layers[wm_lid];
156 }
157
158 std::shared_ptr<WMLayer> LayerControl::getWMLayer(std::string layer_name)
159 {
160     for(auto &l : this->wm_layers)
161     {
162         if(l->layerName() == layer_name)
163         {
164             return l;
165         }
166     }
167     return nullptr;
168 }
169
170 struct rect LayerControl::getAreaSize(const std::string& area)
171 {
172     return area2size[area];
173 }
174
175 void LayerControl::setupArea(const rectangle& base_rct, double scaling)
176 {
177     this->scaling = scaling;
178     this->offset_x = base_rct.left();
179     this->offset_y = base_rct.top();
180
181     for (auto &i : this->area2size)
182     {
183         i.second.x = static_cast<int>(scaling * i.second.x + 0.5);
184         i.second.y = static_cast<int>(scaling * i.second.y + 0.5);
185         i.second.w = static_cast<int>(scaling * i.second.w + 0.5);
186         i.second.h = static_cast<int>(scaling * i.second.h + 0.5);
187
188         HMI_DEBUG("area:%s size(after) : x:%d y:%d w:%d h:%d",
189             i.first.c_str(), i.second.x, i.second.y, i.second.w, i.second.h);
190     }
191 }
192
193 Screen LayerControl::getScreenInfo()
194 {
195     return Screen(this->screen_prop.screenWidth, this->screen_prop.screenHeight);
196 }
197
198 double LayerControl::scale()
199 {
200     return this->scaling;
201 }
202
203 WMError LayerControl::renderLayers()
204 {
205     HMI_INFO("Commit change");
206     WMError rc = WMError::SUCCESS;
207
208     // Check the number of layers
209     vector<unsigned> ivi_l_ids;
210     for(auto& l : this->wm_layers)
211     {
212         auto state = l->getLayerState();
213         HMI_DEBUG("layer %s", l->layerName().c_str());
214         for(const auto& id : state.getIviIdList())
215         {
216             HMI_DEBUG("Add %d", id);
217             ivi_l_ids.push_back(id);
218         }
219     }
220
221     // Create render order
222     t_ilm_layer* id_array = new t_ilm_layer[ivi_l_ids.size()];
223     if(id_array == nullptr)
224     {
225         HMI_WARNING("short memory");
226         this->undoUpdate();
227         return WMError::FAIL;
228     }
229     int count = 0;
230     for(const auto& i : ivi_l_ids)
231     {
232         id_array[count] = i;
233         ++count;
234     }
235
236     // Display
237     ilmErrorTypes ret = ilm_displaySetRenderOrder(this->screenID, id_array, ivi_l_ids.size());
238     if(ret != ILM_SUCCESS)
239     {
240         this->undoUpdate();
241         rc = WMError::FAIL;
242     }
243     else
244     {
245         for(auto& l : this->wm_layers)
246         {
247             l->update();
248         }
249     }
250     ilm_commitChanges();
251     delete id_array;
252     return rc;
253 }
254
255 WMError LayerControl::setXDGSurfaceOriginSize(unsigned surface)
256 {
257     WMError ret = WMError::NOT_REGISTERED;
258     ilmSurfaceProperties prop;
259     ilmErrorTypes rc = ilm_getPropertiesOfSurface(surface, &prop);
260     if(rc == ILM_SUCCESS)
261     {
262         HMI_INFO("xdg surface info %d, %d", prop.origSourceWidth, prop.origSourceHeight);
263         ilm_surfaceSetSourceRectangle(surface, 0, 0, prop.origSourceWidth, prop.origSourceHeight);
264         ret = WMError::SUCCESS;
265     }
266     return ret;
267 }
268
269
270 void LayerControl::undoUpdate()
271 {
272     for(auto& l : this->wm_layers)
273     {
274         l->undo();
275     }
276 }
277
278 WMError LayerControl::loadLayerSetting(const string &path)
279 {
280     HMI_DEBUG("loading WMLayer(Application Containers) Setting from %s", path);
281
282     json_object *json_obj, *json_cfg;
283     int ret = jh::inputJsonFilie(path.c_str(), &json_obj);
284     if (0 > ret)
285     {
286         HMI_ERROR("Could not open %s", path.c_str());
287         return WMError::FAIL;
288     }
289     HMI_INFO("json_obj dump:%s", json_object_get_string(json_obj));
290
291     if (!json_object_object_get_ex(json_obj, "mappings", &json_cfg))
292     {
293         HMI_ERROR("Parse Error!!");
294         return WMError::FAIL;
295     }
296
297     int len = json_object_array_length(json_cfg);
298     HMI_DEBUG("json_cfg len:%d", len);
299
300     for (int i = 0; i < len; i++)
301     {
302         json_object *json_tmp = json_object_array_get_idx(json_cfg, i);
303         HMI_DEBUG("> json_tmp dump:%s", json_object_get_string(json_tmp));
304
305         this->wm_layers.emplace_back(std::make_shared<WMLayer>(json_tmp, i));
306     }
307     json_object_put(json_obj);
308
309     return WMError::SUCCESS;
310 }
311
312 WMError LayerControl::loadAreaDb(const std::string& path)
313 {
314     // Load area.db
315     json_object *json_obj;
316     int ret = jh::inputJsonFilie(path.c_str(), &json_obj);
317     if (0 > ret)
318     {
319         HMI_ERROR("Could not open %s", path.c_str());
320         return WMError::FAIL;
321     }
322     HMI_INFO("json_obj dump:%s", json_object_get_string(json_obj));
323
324     // Perse areas
325     json_object *json_cfg;
326     if (!json_object_object_get_ex(json_obj, "areas", &json_cfg))
327     {
328         HMI_ERROR("Parse Error!!");
329         return WMError::FAIL;
330     }
331
332     int len = json_object_array_length(json_cfg);
333     HMI_DEBUG("json_cfg len:%d", len);
334
335     const char *area;
336     for (int i = 0; i < len; i++)
337     {
338         json_object *json_tmp = json_object_array_get_idx(json_cfg, i);
339         HMI_DEBUG("> json_tmp dump:%s", json_object_get_string(json_tmp));
340
341         area = jh::getStringFromJson(json_tmp, "name");
342         if (nullptr == area)
343         {
344             HMI_ERROR("Parse Error!!");
345             return WMError::FAIL;
346         }
347         HMI_DEBUG("> area:%s", area);
348
349         json_object *json_rect;
350         if (!json_object_object_get_ex(json_tmp, "rect", &json_rect))
351         {
352             HMI_ERROR("Parse Error!!");
353             return WMError::FAIL;
354         }
355         HMI_DEBUG("> json_rect dump:%s", json_object_get_string(json_rect));
356
357         struct rect area_size;
358         area_size.x = jh::getIntFromJson(json_rect, "x");
359         area_size.y = jh::getIntFromJson(json_rect, "y");
360         area_size.w = jh::getIntFromJson(json_rect, "w");
361         area_size.h = jh::getIntFromJson(json_rect, "h");
362
363         this->area2size[area] = area_size;
364     }
365
366     // Check
367     for (const auto& itr : this->area2size)
368     {
369         HMI_DEBUG("area:%s x:%d y:%d w:%d h:%d",
370                   itr.first.c_str(), itr.second.x, itr.second.y,
371                   itr.second.w, itr.second.h);
372     }
373
374     // Release json_object
375     json_object_put(json_obj);
376
377     return WMError::SUCCESS;
378 }
379
380 WMError LayerControl::layoutChange(const WMAction& action)
381 {
382     if (action.visible == TaskVisible::INVISIBLE)
383     {
384         // Visibility is not change -> no redraw is required
385         return WMError::SUCCESS;
386     }
387     if(action.client == nullptr)
388     {
389         HMI_SEQ_ERROR(action.req_num, "client may vanish");
390         return WMError::NOT_REGISTERED;
391     }
392     unsigned layer = action.client->layerID();
393     unsigned surface = action.client->surfaceID();
394
395     auto rect = this->getAreaSize(action.area);
396     HMI_DEBUG("Set layout %d, %d, %d, %d",rect.x, rect.y, rect.w, rect.h);
397
398     // Sometimes, ivi_wm_surface_size signal doesn't reach window manager,
399     // then, Window Manager set set source size = 0.
400     if(!action.client->isSourceSizeSet())
401     {
402         ilmSurfaceProperties sp;
403         ilm_getPropertiesOfSurface(surface, &sp);
404         if((sp.origSourceHeight != sp.sourceHeight) || (sp.origSourceWidth != sp.sourceWidth))
405         {
406             HMI_SEQ_NOTICE(action.req_num, "set source size w:%d h%d", sp.origSourceWidth, sp.origSourceHeight);
407             ilm_surfaceSetSourceRectangle(surface, 0, 0, sp.origSourceWidth, sp.origSourceHeight);
408             ilm_commitChanges();
409             action.client->setSurfaceSizeCorrectly();
410         }
411     }
412
413     ilm_surfaceSetDestinationRectangle(surface, rect.x, rect.y, rect.w, rect.h);
414     ilm_commitChanges();
415     for(auto &wm_layer: this->wm_layers)
416     {
417         // Store the state who is assigned to the area
418         if(wm_layer->hasLayerID(layer))
419         {
420             wm_layer->attachAppToArea(action.client->appID(), action.area);
421             /* TODO: manipulate state directly
422             LayerState ls = wm_layer->getLayerState();
423             ls.seattachAppToAreatArea(action.client->appID(), action.area);
424             wm_layer->dump(); */
425         }
426     }
427
428     return WMError::SUCCESS;
429 }
430
431 WMError LayerControl::visibilityChange(const WMAction& action)
432 {
433     WMError ret = WMError::FAIL;
434     if(action.client == nullptr)
435     {
436         HMI_SEQ_ERROR(action.req_num, "client may vanish");
437         return WMError::NOT_REGISTERED;
438     }
439
440     if (action.visible == TaskVisible::VISIBLE)
441     {
442         ret = this->makeVisible(action.client);
443     }
444     else if (action.visible == TaskVisible::INVISIBLE)
445     {
446         ret = this->makeInvisible(action.client);
447     }
448     ilm_commitChanges();
449     return ret;
450 }
451
452 void LayerControl::appTerminated(const shared_ptr<WMClient> client)
453 {
454     for(auto& l : this->wm_layers)
455     {
456         if(l->hasLayerID(client->layerID()))
457         {
458             l->appTerminated(client->layerID());
459         }
460     }
461 }
462
463 void LayerControl::dispatchCreateEvent(ilmObjectType object, unsigned id, bool created)
464 {
465     if (ILM_SURFACE == object)
466     {
467         if (created)
468         {
469             ilmSurfaceProperties sp;
470             ilmErrorTypes rc;
471             rc = ilm_getPropertiesOfSurface(id, &sp);
472             if(rc != ILM_SUCCESS)
473             {
474                 HMI_ERROR("Failed to get surface %d property due to %d", id, ilm_getError());
475                 return;
476             }
477             this->cb.surfaceCreated(sp.creatorPid, id);
478             ilm_surfaceAddNotification(id, surfaceCallback_static);
479             ilm_surfaceSetVisibility(id, ILM_TRUE);
480             ilm_surfaceSetType(id, ILM_SURFACETYPE_DESKTOP);
481         }
482         else
483         {
484             this->cb.surfaceDestroyed(id);
485         }
486     }
487     if (ILM_LAYER == object)
488     {
489         if(created)
490         {
491             ilm_layerAddNotification(id, layerCallback_static);
492         }
493         else
494         {
495             // Ignore here. Nothing to do currently.
496             // Process of application dead is handled by Window Manager
497             // from binder notification
498         }
499     }
500 }
501
502 void LayerControl::dispatchSurfacePropChangeEvent(unsigned id,
503         struct ilmSurfaceProperties* sprop,
504         t_ilm_notification_mask mask)
505 {
506     /*
507       ILM_NOTIFICATION_CONTENT_AVAILABLE & ILM_NOTIFICATION_CONTENT_REMOVED
508       are not handled here, handled in create/destroy event
509      */
510     if (ILM_NOTIFICATION_VISIBILITY & mask)
511     {
512         HMI_DEBUG("surface %d turns visibility %d", id, sprop->visibility);
513     }
514     if (ILM_NOTIFICATION_OPACITY & mask)
515     {
516         HMI_DEBUG("surface %d turns opacity %f", id, sprop->opacity);
517     }
518     if (ILM_NOTIFICATION_SOURCE_RECT & mask)
519     {
520         HMI_DEBUG("surface %d source rect changes", id);
521     }
522     if (ILM_NOTIFICATION_DEST_RECT & mask)
523     {
524         HMI_DEBUG("surface %d dest rect changes", id);
525     }
526     if (ILM_NOTIFICATION_CONFIGURED & mask)
527     {
528         HMI_DEBUG("surface %d size %d, %d, %d, %d", id,
529             sprop->sourceX, sprop->sourceY, sprop->origSourceWidth, sprop->origSourceHeight);
530         ilm_surfaceSetSourceRectangle(id, 0, 0, sprop->origSourceWidth, sprop->origSourceHeight);
531     }
532 }
533
534 void LayerControl::dispatchLayerPropChangeEvent(unsigned id,
535         struct ilmLayerProperties* lprop,
536         t_ilm_notification_mask mask)
537 {
538     if (ILM_NOTIFICATION_VISIBILITY & mask)
539     {
540         HMI_DEBUG("layer %d turns visibility %d", id, lprop->visibility);
541     }
542     if (ILM_NOTIFICATION_OPACITY & mask)
543     {
544         HMI_DEBUG("layer %d turns opacity %f", id, lprop->opacity);
545     }
546     if (ILM_NOTIFICATION_SOURCE_RECT & mask)
547     {
548         HMI_DEBUG("layer %d source rect changes", id);
549     }
550     if (ILM_NOTIFICATION_DEST_RECT & mask)
551     {
552         HMI_DEBUG("layer %d dest rect changes", id);
553     }
554 }
555
556 WMError LayerControl::makeVisible(const shared_ptr<WMClient> client)
557 {
558     WMError ret = WMError::SUCCESS;
559     // Don't check here wheher client is nullptr or not
560     unsigned layer = client->layerID();
561
562     this->moveForeGround(client);
563
564     ilm_layerSetVisibility(layer, ILM_TRUE);
565
566     return ret;
567 }
568
569 WMError LayerControl::makeInvisible(const shared_ptr<WMClient> client)
570 {
571     WMError ret = WMError::SUCCESS;
572     // Don't check here the client is not nullptr
573     unsigned layer = client->layerID();
574
575     bool mv_ok = this->moveBackGround(client);
576
577     if(!mv_ok)
578     {
579         HMI_INFO("make invisible client %s", client->appID().c_str());
580         ilm_layerSetVisibility(layer, ILM_FALSE);
581     }
582
583     return ret;
584 }
585
586 bool LayerControl::moveBackGround(const shared_ptr<WMClient> client)
587 {
588     bool ret = false;
589
590     // Move background from foreground layer
591     auto bg = this->getWMLayer(BACK_GROUND_LAYER);
592     if(bg != nullptr)
593     {
594         HMI_DEBUG("client %s role %s", client->appID().c_str(), client->role().c_str());
595         unsigned layer = client->layerID();
596         if(bg->hasRole(client->role()))
597         {
598             HMI_INFO("%s go to background", client->appID().c_str());
599             bg->addLayerToState(layer);
600             auto wm_layer = this->getWMLayer(layer);
601             wm_layer->removeLayerFromState(layer);
602             /* TODO: manipulate state directly
603             LayerState bg_ls = bg->getLayerState();
604             bg_ls.addLayer(layer);
605             LayerState ls = wm_layer->getLayerState();
606             ls.removeLayer(layer); */
607             bg->dump();
608             wm_layer->dump();
609             ret = true;
610         }
611     }
612     return ret;
613 }
614
615 bool LayerControl::moveForeGround(const shared_ptr<WMClient> client)
616 {
617     bool ret = false;
618
619     // Move foreground from foreground layer
620     auto bg = this->getWMLayer(BACK_GROUND_LAYER);
621     if(bg != nullptr)
622     {
623         if(bg->hasRole(client->role()))
624         {
625             unsigned layer = client->layerID();
626             HMI_INFO("%s go to foreground", client->appID().c_str());
627             bg->removeLayerFromState(layer);
628             auto wm_layer = this->getWMLayer(layer);
629             wm_layer->addLayerToState(layer);
630             /* TODO: manipulate state directly
631             LayerState bg_ls = bg->getLayerState();
632             bg_ls.removeLayer(layer);
633             LayerState ls = wm_layer->getLayerState();
634             ls.addLayer(layer); */
635             bg->dump();
636             wm_layer->dump();
637             ret = true;
638         }
639     }
640     return ret;
641 }
642
643 } // namespace wm