2 * Copyright (c) 2017 TOYOTA MOTOR CORPORATION
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include "window_manager.hpp"
21 #include "json_helper.hpp"
22 #include "applist.hpp"
26 #include <systemd/sd-event.h>
35 static const uint64_t kTimeOut = 3ULL; /* 3s */
37 /* DrawingArea name used by "{layout}.{area}" */
38 const char kNameLayoutNormal[] = "normal";
39 const char kNameLayoutSplit[] = "split";
40 const char kNameAreaFull[] = "full";
41 const char kNameAreaMain[] = "main";
42 const char kNameAreaSub[] = "sub";
44 /* Key for json obejct */
45 const char kKeyDrawingName[] = "drawing_name";
46 const char kKeyDrawingArea[] = "drawing_area";
47 const char kKeyDrawingRect[] = "drawing_rect";
48 const char kKeyX[] = "x";
49 const char kKeyY[] = "y";
50 const char kKeyWidth[] = "width";
51 const char kKeyHeight[] = "height";
52 const char kKeyWidthPixel[] = "width_pixel";
53 const char kKeyHeightPixel[] = "height_pixel";
54 const char kKeyWidthMm[] = "width_mm";
55 const char kKeyHeightMm[] = "height_mm";
56 const char kKeyScale[] = "scale";
57 const char kKeyIds[] = "ids";
59 static sd_event_source *g_timer_ev_src = nullptr;
60 static AppList g_app_list;
61 static WindowManager *g_context;
66 // using nlohmann::json;
68 /* result<json> file_to_json(char const *filename)
71 std::ifstream i(filename);
74 HMI_DEBUG("Could not open config file, so use default layer information");
75 j = default_layers_json;
85 struct result<layer_map> load_layer_map(char const *filename)
87 HMI_DEBUG("loading IDs from %s", filename);
89 auto j = file_to_json(filename);
92 return Err<layer_map>(j.unwrap_err());
94 json jids = j.unwrap();
96 return to_layer_map(jids);
99 static int processTimerHandler(sd_event_source *s, uint64_t usec, void *userdata)
101 HMI_NOTICE("Time out occurs because the client replys endDraw slow, so revert the request");
102 reinterpret_cast<wm::WindowManager *>(userdata)->timerHandler();
106 static void onStateTransitioned(vector<WMAction> actions)
108 g_context->startTransitionWrapper(actions);
111 static void onError()
113 g_context->processError(WMError::LAYOUT_CHANGE_FAIL);
120 WindowManager::WindowManager()
124 const char *path = getenv("AFM_APP_INSTALL_DIR");
127 HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
131 this->lc = std::make_shared<LayerControl>(root);
136 auto l = load_layer_map(path.c_str());
139 this->layers = l.unwrap();
143 HMI_ERROR("%s", l.err().value());
147 catch (std::exception &e)
149 HMI_ERROR("Loading of configuration failed: %s", e.what());
153 int WindowManager::init()
155 /* if (!this->display->ok())
160 if (this->layers.mapping.empty())
162 HMI_ERROR("No surface -> layer mapping loaded");
166 // TODO: application requests by old role,
167 // so create role map (old, new)
169 this->loadOldRoleDb();
171 // Store my context for calling callback from PolicyManager
174 // Initialize PMWrapper
175 this->pmw.initialize();
177 // Register callback to PolicyManager
178 this->pmw.registerCallback(onStateTransitioned, onError);
181 for (int i = Event_Val_Min; i <= Event_Val_Max; i++)
183 map_afb_event[kListEventName[i]] = afb_daemon_make_event(kListEventName[i]);
186 const struct rect css_bg = this->lc->getAreaSize("fullscreen");
187 Screen screen = this->lc->getScreenInfo();
188 rectangle dp_bg(screen.width(), screen.height());
190 dp_bg.set_aspect(static_cast<double>(css_bg.w) / css_bg.h);
191 dp_bg.fit(screen.width(), screen.height());
192 dp_bg.center(screen.width(), screen.height());
193 HMI_DEBUG("SCALING: CSS BG(%dx%d) -> DDP %dx%d,(%dx%d)",
194 css_bg.w, css_bg.h, dp_bg.left(), dp_bg.top(), dp_bg.width(), dp_bg.height());
196 double scale = static_cast<double>(dp_bg.height()) / css_bg.h;
197 this->lc->setupArea(scale);
199 /* this->display->add_global_handler(
200 "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
201 this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
204 this->display->add_global_handler(
205 "ivi_wm", [this](wl_registry *r, uint32_t name, uint32_t v) {
207 std::make_unique<struct compositor::controller>(r, name, v);
209 // Init controller hooks
210 this->controller->chooks = &this->chooks;
212 // This protocol needs the output, so lets just add our mapping here...
213 this->controller->add_proxy_to_id_mapping(
214 this->outputs.front()->proxy.get(),
215 wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
216 this->outputs.front()->proxy.get())));
219 this->controller->create_screen(this->outputs.front()->proxy.get());
221 // Set display to controller
222 this->controller->display = this->display;
225 // First level objects
226 this->display->roundtrip();
227 // Second level objects
228 this->display->roundtrip();
229 // Third level objects
230 this->display->roundtrip(); */
232 return 0; //init_layers();
235 /* int WindowManager::dispatch_pending_events()
237 if (this->pop_pending_events())
239 this->display->dispatch_pending();
245 void WindowManager::set_pending_events()
247 this->pending_events.store(true, std::memory_order_release);
250 result<int> WindowManager::api_request_surface(char const *appid, char const *drawing_name)
252 // TODO: application requests by old role,
253 // so convert role old to new
254 const char *role = this->convertRoleOldToNew(drawing_name);
257 // auto lid = this->layers.get_layer_id(string(role));
258 unsigned l_id = this->lc->getNewLayerID(role, &l_name);
262 * register drawing_name as fallback and make it displayed.
264 // lid = this->layers.get_layer_id(string("fallback"));
265 l_id = this->lc->getNewLayerID("fallback", &l_name);
266 HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
269 return Err<int>("Designated role does not match any role, fallback is disabled");
273 // generate surface ID for ivi-shell application
275 auto rname = this->id_alloc.lookup(string(role));
278 // name does not exist yet, allocate surface id...
279 auto id = int(this->id_alloc.generate_id(role));
280 // this->layers.add_surface(id, *lid);
282 // set the main_surface[_name] here and now
283 // if (!this->layers.main_surface_name.empty() &&
284 // this->layers.main_surface_name == drawing_name)
286 // this->layers.main_surface = id;
287 // HMI_DEBUG("Set main_surface id to %u", id);
290 // add client into the db
291 string appid_str(appid);
292 g_app_list.addClient(appid_str, l_id, l_name, id, string(role));
294 /* if(g_app_list.contains(appid_str))
296 // add surface into app
297 auto client = g_app_list.lookUpClient(appid_str);
298 // client.addSurface(id);
302 g_app_list.addClient(appid_str, l_id, id, string(role));
305 // Set role map of (new, old)
306 this->rolenew2old[role] = string(drawing_name);
311 // Check currently registered drawing names if it is already there.
312 return Err<int>("Surface already present");
315 char const *WindowManager::api_request_surface(char const *appid, char const *drawing_name,
318 // TODO: application requests by old role,
319 // so convert role old to new
320 const char *role = this->convertRoleOldToNew(drawing_name);
324 // auto lid = this->layers.get_layer_id(string(role));
325 unsigned lid = this->lc->getNewLayerID(str, &l_name);
326 unsigned sid = std::stol(ivi_id);
330 //register drawing_name as fallback and make it displayed.
331 lid = this->lc->getNewLayerID(str, &l_name);
332 HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
335 return "Drawing name does not match any role, fallback is disabled";
339 auto rname = this->id_alloc.lookup(str);
343 return "Surface already present";
346 // register pair drawing_name and ivi_id
347 this->id_alloc.register_name_id(role, sid);
348 // this->layers.add_surface(sid, *lid);
350 // this surface is already created
351 // HMI_DEBUG("surface_id is %u, layer_id is %u", sid, *lid);
353 // this->controller->layers[*lid]->add_surface(sid);
354 // this->layout_commit();
356 // add client into the db
357 string appid_str(appid);
358 g_app_list.addClient(appid_str, lid, l_name, sid, string(role));
360 // Set role map of (new, old)
361 this->rolenew2old[role] = string(drawing_name);
367 * This function is substitute of requestSurface
368 * If surface creation is faster than application request of this function,
369 * WM will bind surfaceID with application and role.
370 * If surface creation is slower than application request of thie function,
371 * WM will put Client into pending list.
374 * Application can request with pid but this is temporary solution for now.
375 * This will be removed.
377 bool WindowManager::api_set_role(char const *appid, char const *drawing_name, unsigned pid){
379 string role = drawing_name;
381 unsigned surface = 0;
382 WMError wm_err = WMError::UNKNOWN;
385 // get layer ID which role should be in
386 // auto lid = this->layers.get_layer_id(role);
387 unsigned lid = this->lc->getNewLayerID(role, &l_name);
390 // lid = this->layers.get_layer_id(string("fallback"));
391 HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role.c_str());
394 HMI_ERROR("Drawing name does not match any role, fallback is disabled");
400 // search floating surfaceID from pid if pid is designated.
401 wm_err = g_app_list.popFloatingSurface(pid, &surface);
404 // get floating surface with appid. If WM queries appid from pid,
405 // WM can bind surface and role with appid(not implemented yet)
406 //wm_err = g_app_list.popFloatingSurface(id);
408 if(wm_err != WMError::SUCCESS){
409 HMI_ERROR("No floating surface for app: %s", id.c_str());
410 g_app_list.addFloatingClient(id, lid, role);
411 HMI_NOTICE("%s : Waiting for surface creation", id.c_str());
416 if (g_app_list.contains(id))
418 HMI_INFO("Add role: %s with surface: %d. Client %s has multi surfaces.",
419 role.c_str(), surface, id.c_str());
420 auto client = g_app_list.lookUpClient(id);
421 client->appendRole(role);
424 HMI_INFO("Create new client: %s, surface: %d into layer: %d with role: %s",
425 id.c_str(), surface, lid, role.c_str());
426 g_app_list.addClient(id, lid, l_name, surface, role);
429 // register pair drawing_name and ivi_id
430 this->id_alloc.register_name_id(role.c_str(), surface);
431 // this->layers.add_surface(surface, *lid);
433 // this surface is already created
434 HMI_DEBUG("surface_id is %u, layer_id is %u", surface, lid);
436 // const auto &o_layer = this->layers.get_layer(*lid);
437 /* auto rect = o_layer.value().rect;
440 rect.w = this->controller->output_size.w + 1 + rect.w;
444 rect.h = this->controller->output_size.h + 1 + rect.h;
447 // this->controller->layers[*lid]->add_surface(surface);
448 // this->layout_commit();
453 void WindowManager::api_activate_surface(char const *appid, char const *drawing_name,
454 char const *drawing_area, const reply_func &reply)
458 // TODO: application requests by old role,
459 // so convert role old to new
460 const char *c_role = this->convertRoleOldToNew(drawing_name);
463 string role = c_role;
464 string area = drawing_area;
466 if(!g_app_list.contains(id))
468 reply("app doesn't request 'requestSurface' or 'setRole' yet");
471 auto client = g_app_list.lookUpClient(id);
473 // unsigned srfc = client->surfaceID(role);
474 // unsigned layer = client->layerID();
476 // g_app_list.removeFloatingSurface(client->surfaceID());
477 // g_app_list.removeFloatingSurface(client);
479 Task task = Task::TASK_ALLOCATE;
480 unsigned req_num = 0;
481 WMError ret = WMError::UNKNOWN;
483 ret = this->setRequest(id, role, area, task, &req_num);
485 //vector<WMLayerState> current_states = this->lc->getCurrentStates();
486 // ret = this->setRequest(id, role, area, task, current_states, &req_num);
488 if(ret != WMError::SUCCESS)
490 HMI_ERROR(errorDescription(ret));
491 reply("Failed to set request");
496 if (req_num != g_app_list.currentRequestNumber())
498 // Add request, then invoked after the previous task is finished
499 HMI_SEQ_DEBUG(req_num, "request is accepted");
506 ret = this->doTransition(req_num);
508 if (ret != WMError::SUCCESS)
511 HMI_SEQ_ERROR(req_num, errorDescription(ret));
512 g_app_list.removeRequest(req_num);
513 this->processNextRequest();
517 void WindowManager::api_deactivate_surface(char const *appid, char const *drawing_name,
518 const reply_func &reply)
522 // TODO: application requests by old role,
523 // so convert role old to new
524 const char *c_role = this->convertRoleOldToNew(drawing_name);
530 string role = c_role;
531 string area = ""; //drawing_area;
532 Task task = Task::TASK_RELEASE;
533 unsigned req_num = 0;
534 WMError ret = WMError::UNKNOWN;
536 ret = this->setRequest(id, role, area, task, &req_num);
537 //vector<WMLayerState> current_states = this->lc->getCurrentStates();
538 // ret = this->setRequest(id, role, area, task, current_states, &req_num);
540 if (ret != WMError::SUCCESS)
542 HMI_ERROR(errorDescription(ret));
543 reply("Failed to set request");
548 if (req_num != g_app_list.currentRequestNumber())
550 // Add request, then invoked after the previous task is finished
551 HMI_SEQ_DEBUG(req_num, "request is accepted");
558 ret = this->doTransition(req_num);
560 if (ret != WMError::SUCCESS)
563 HMI_SEQ_ERROR(req_num, errorDescription(ret));
564 g_app_list.removeRequest(req_num);
565 this->processNextRequest();
569 void WindowManager::api_enddraw(char const *appid, char const *drawing_name)
571 // TODO: application requests by old role,
572 // so convert role old to new
573 const char *c_role = this->convertRoleOldToNew(drawing_name);
576 string role = c_role;
577 unsigned current_req = g_app_list.currentRequestNumber();
578 bool result = g_app_list.setEndDrawFinished(current_req, id, role);
582 HMI_ERROR("%s is not in transition state", id.c_str());
586 if (g_app_list.endDrawFullfilled(current_req))
588 // do task for endDraw
590 WMError ret = this->doEndDraw(current_req);
592 if(ret != WMError::SUCCESS)
594 //this->emit_error();
596 // Undo state of PolicyManager
597 this->pmw.undoState();
598 this->lc->undoUpdate();
600 this->emitScreenUpdated(current_req);
601 HMI_SEQ_INFO(current_req, "Finish request status: %s", errorDescription(ret));
603 g_app_list.removeRequest(current_req);
605 this->processNextRequest();
609 HMI_SEQ_INFO(current_req, "Wait other App call endDraw");
614 result<json_object *> WindowManager::api_get_display_info()
616 /* if (!this->display->ok())
618 return Err<json_object *>("Wayland compositor is not available");
622 /* size o_size = this->controller->output_size;
623 size p_size = this->controller->physical_size; */
624 Screen screen = this->lc->getScreenInfo();
626 json_object *object = json_object_new_object();
627 json_object_object_add(object, kKeyWidthPixel, json_object_new_int(screen.width()));
628 json_object_object_add(object, kKeyHeightPixel, json_object_new_int(screen.height()));
630 json_object_object_add(object, kKeyWidthMm, json_object_new_int(0));
631 json_object_object_add(object, kKeyHeightMm, json_object_new_int(0));
632 json_object_object_add(object, kKeyScale, json_object_new_double(this->lc->scale()));
634 return Ok<json_object *>(object);
637 result<json_object *> WindowManager::api_get_area_info(char const *drawing_name)
641 // TODO: application requests by old role,
642 // so convert role old to new
643 const char *role = this->convertRoleOldToNew(drawing_name);
645 // Check drawing name, surface/layer id
646 auto const &surface_id = this->id_alloc.lookup(string(role));
649 return Err<json_object *>("Surface does not exist");
652 /* if (!this->controller->surface_exists(*surface_id))
654 return Err<json_object *>("Surface does not exist in controller!");
657 /* // auto layer_id = this->layers.get_layer_id(*surface_id);
660 return Err<json_object *>("Surface is not on any layer!");
663 // Set area rectangle
664 rect area_info = this->area_info[*surface_id];
665 json_object *object = json_object_new_object();
666 json_object_object_add(object, kKeyX, json_object_new_int(area_info.x));
667 json_object_object_add(object, kKeyY, json_object_new_int(area_info.y));
668 json_object_object_add(object, kKeyWidth, json_object_new_int(area_info.w));
669 json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
671 return Ok<json_object *>(object);
674 void WindowManager::api_ping() { /* this->dispatch_pending_events(); */ }
676 void WindowManager::send_event(char const *evname, char const *label)
678 HMI_DEBUG("%s: %s(%s)", __func__, evname, label);
680 json_object *j = json_object_new_object();
681 json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
683 int ret = afb_event_push(this->map_afb_event[evname], j);
686 HMI_DEBUG("afb_event_push failed: %m");
690 void WindowManager::send_event(char const *evname, char const *label, char const *area,
691 int x, int y, int w, int h)
693 HMI_DEBUG("%s: %s(%s, %s) x:%d y:%d w:%d h:%d",
694 __func__, evname, label, area, x, y, w, h);
696 json_object *j_rect = json_object_new_object();
697 json_object_object_add(j_rect, kKeyX, json_object_new_int(x));
698 json_object_object_add(j_rect, kKeyY, json_object_new_int(y));
699 json_object_object_add(j_rect, kKeyWidth, json_object_new_int(w));
700 json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
702 json_object *j = json_object_new_object();
703 json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
704 json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area));
705 json_object_object_add(j, kKeyDrawingRect, j_rect);
707 int ret = afb_event_push(this->map_afb_event[evname], j);
710 HMI_DEBUG("afb_event_push failed: %m");
717 void WindowManager::surface_created(uint32_t surface_id)
719 /* this->controller->get_surface_properties(surface_id, IVI_WM_PARAM_SIZE);
721 auto layer_id = this->layers.get_layer_id(surface_id);
724 HMI_DEBUG("Newly created surfce %d is not associated with any layer!",
729 HMI_DEBUG("surface_id is %u, layer_id is %u", surface_id, *layer_id);
731 this->controller->layers[*layer_id]->add_surface(surface_id);
732 this->layout_commit(); */
735 void WindowManager::surface_removed(uint32_t surface_id)
737 HMI_DEBUG("Delete surface_id %u", surface_id);
738 this->id_alloc.remove_id(surface_id);
739 // this->layers.remove_surface(surface_id);
740 g_app_list.removeSurface(surface_id);
743 void WindowManager::surface_properties(unsigned surface_id, unsigned pid)
745 HMI_DEBUG("get surface properties");
747 // search pid from surfaceID
748 /*json_object *response;
749 afb_service_call_sync("afm-main", "runners", nullptr, &response);
751 // retrieve appid from pid from application manager
753 if(response == nullptr)
755 HMI_ERROR("No runners");
759 // check appid then add it to the client
760 HMI_INFO("Runners:%s", json_object_get_string(response));
761 int size = json_object_array_length(response);
762 for(int i = 0; i < size; i++)
764 json_object *j = json_object_array_get_idx(response, i);
765 const char* id = jh::getStringFromJson(j, "id");
766 int runid = jh::getIntFromJson(j, "runid");
767 if(id && (runid > 0))
777 json_object_put(response);
779 g_app_list.addFloatingSurface(appid, surface_id, pid);*/
782 void WindowManager::removeClient(const string &appid)
784 HMI_DEBUG("Remove clinet %s from list", appid.c_str());
785 g_app_list.removeClient(appid);
788 void WindowManager::exceptionProcessForTransition()
790 unsigned req_num = g_app_list.currentRequestNumber();
791 HMI_SEQ_NOTICE(req_num, "Process exception handling for request. Remove current request %d", req_num);
792 g_app_list.removeRequest(req_num);
793 HMI_SEQ_NOTICE(g_app_list.currentRequestNumber(), "Process next request if exists");
794 this->processNextRequest();
797 void WindowManager::timerHandler()
799 unsigned req_num = g_app_list.currentRequestNumber();
800 HMI_SEQ_DEBUG(req_num, "Timer expired remove Request");
801 g_app_list.reqDump();
802 g_app_list.removeRequest(req_num);
803 this->processNextRequest();
806 void WindowManager::startTransitionWrapper(vector<WMAction> &actions)
809 unsigned req_num = g_app_list.currentRequestNumber();
813 if (g_app_list.haveRequest())
815 HMI_SEQ_DEBUG(req_num, "There is no WMAction for this request");
816 goto proc_remove_request;
820 HMI_SEQ_DEBUG(req_num, "There is no request");
825 for (auto &act : actions)
830 auto const &surface_id = this->id_alloc.lookup(act.role);
831 string appid = g_app_list.getAppID(*surface_id, act.role, &found);
834 if (TaskVisible::INVISIBLE == act.visible)
836 // App is killed, so do not set this action
841 HMI_SEQ_ERROR(req_num, "appid which is visible is not found");
849 ret = g_app_list.setAction(req_num, act);
850 if (ret != WMError::SUCCESS)
852 HMI_SEQ_ERROR(req_num, "Setting action is failed");
857 HMI_SEQ_DEBUG(req_num, "Start transition.");
858 ret = this->startTransition(req_num);
859 if (ret != WMError::SUCCESS)
861 if (ret == WMError::NO_LAYOUT_CHANGE)
863 goto proc_remove_request;
867 HMI_SEQ_ERROR(req_num, "Transition state is failed");
876 HMI_SEQ_ERROR(req_num, errorDescription(ret));
877 this->pmw.undoState();
880 g_app_list.removeRequest(req_num);
881 this->processNextRequest();
884 void WindowManager::processError(WMError error)
886 unsigned req_num = g_app_list.currentRequestNumber();
889 HMI_SEQ_ERROR(req_num, errorDescription(error));
890 g_app_list.removeRequest(req_num);
891 this->processNextRequest();
895 ******* Private Functions *******
901 int WindowManager::init_layers()
903 /* if (!this->controller)
905 HMI_ERROR("ivi_controller global not available");
909 if (this->outputs.empty())
911 HMI_ERROR("no output was set up!");
915 auto &c = this->controller;
917 auto &o = this->outputs.front();
918 auto &s = c->screens.begin()->second;
919 auto &layers = c->layers;
921 // Write output dimensions to ivi controller...
922 c->output_size = compositor::size{uint32_t(o->width), uint32_t(o->height)};
923 c->physical_size = compositor::size{uint32_t(o->physical_width),
924 uint32_t(o->physical_height)};
927 HMI_DEBUG("SCALING: screen (%dx%d), physical (%dx%d)",
928 o->width, o->height, o->physical_width, o->physical_height);
930 // this->layers.loadAreaDb();
932 const compositor::rect css_bg = this->layers.getAreaSize("fullscreen");
933 rectangle dp_bg(o->width, o->height);
935 dp_bg.set_aspect(static_cast<double>(css_bg.w) / css_bg.h);
936 dp_bg.fit(o->width, o->height);
937 dp_bg.center(o->width, o->height);
938 HMI_DEBUG("SCALING: CSS BG(%dx%d) -> DDP %dx%d,(%dx%d)",
939 css_bg.w, css_bg.h, dp_bg.left(), dp_bg.top(), dp_bg.width(), dp_bg.height());
947 // Quick and dirty setup of layers
948 for (auto const &i : this->layers.mapping)
950 c->layer_create(i.second.layer_id, dp_bg.width(), dp_bg.height());
951 auto &l = layers[i.second.layer_id];
952 l->set_destination_rectangle(dp_bg.left(), dp_bg.top(), dp_bg.width(), dp_bg.height());
953 l->set_visibility(1);
954 HMI_DEBUG("Setting up layer %s (%d) for surface role match \"%s\"",
955 i.second.name.c_str(), i.second.layer_id, i.second.role.c_str());
958 // Add layers to screen
959 s->set_render_order(this->layers.layers);
961 this->layout_commit();
963 c->scale = static_cast<double>(dp_bg.height()) / css_bg.h;
964 this->layers.setupArea(c->scale);
969 void WindowManager::surface_set_layout(int surface_id, const string& area)
971 /* if (!this->controller->surface_exists(surface_id))
973 HMI_ERROR("Surface %d does not exist", surface_id);
977 auto o_layer_id = this->layers.get_layer_id(surface_id);
981 HMI_ERROR("Surface %d is not associated with any layer!", surface_id);
985 uint32_t layer_id = *o_layer_id;
987 auto const &layer = this->layers.get_layer(layer_id);
988 auto rect = this->layers.getAreaSize(area);
989 HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "%s : x:%d y:%d w:%d h:%d", area.c_str(),
990 rect.x, rect.y, rect.w, rect.h);
991 auto &s = this->controller->surfaces[surface_id];
998 HMI_DEBUG("surface_set_layout for surface %u on layer %u", surface_id,
1001 // set destination to the display rectangle
1002 s->set_destination_rectangle(x, y, w, h);
1004 // update area information
1005 this->area_info[surface_id].x = x;
1006 this->area_info[surface_id].y = y;
1007 this->area_info[surface_id].w = w;
1008 this->area_info[surface_id].h = h;
1010 HMI_DEBUG("Surface %u now on layer %u with rect { %d, %d, %d, %d }",
1011 surface_id, layer_id, x, y, w, h); */
1014 void WindowManager::layout_commit()
1016 /* this->controller->commit_changes();
1017 this->display->flush(); */
1020 void WindowManager::emit_activated(char const *label)
1022 this->send_event(kListEventName[Event_Active], label);
1025 void WindowManager::emit_deactivated(char const *label)
1027 this->send_event(kListEventName[Event_Inactive], label);
1030 void WindowManager::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h)
1032 this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
1035 void WindowManager::emit_syncdraw(const string &role, const string &area)
1037 /* rect rect = this->layers.getAreaSize(area);
1038 this->send_event(kListEventName[Event_SyncDraw],
1039 role.c_str(), area.c_str(), rect.x, rect.y, rect.w, rect.h); */
1042 void WindowManager::emit_flushdraw(char const *label)
1044 this->send_event(kListEventName[Event_FlushDraw], label);
1047 void WindowManager::emit_visible(char const *label, bool is_visible)
1049 this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
1052 void WindowManager::emit_invisible(char const *label)
1054 return emit_visible(label, false);
1057 void WindowManager::emit_visible(char const *label) { return emit_visible(label, true); }
1059 void WindowManager::activate(int id)
1061 /* auto ip = this->controller->sprops.find(id);
1062 if (ip != this->controller->sprops.end())
1064 this->controller->surfaces[id]->set_visibility(1);
1067 this->id_alloc.lookup(id).value_or("unknown-name").c_str();
1069 /* // FOR CES DEMO >>>
1070 if ((0 == strcmp(label, "radio")) ||
1071 (0 == strcmp(label, "music")) ||
1072 (0 == strcmp(label, "video")) ||
1073 (0 == strcmp(label, "map")))
1075 for (auto i = surface_bg.begin(); i != surface_bg.end(); ++i)
1080 this->surface_bg.erase(i);
1082 // Remove from BG layer (999)
1083 HMI_DEBUG("Remove %s(%d) from BG layer", label, id);
1084 this->controller->layers[999]->remove_surface(id);
1086 // Add to FG layer (1001)
1087 HMI_DEBUG("Add %s(%d) to FG layer", label, id);
1088 this->controller->layers[1001]->add_surface(id);
1090 for (int j : this->surface_bg)
1092 HMI_DEBUG("Stored id:%d", j);
1100 this->layout_commit(); */
1102 // TODO: application requests by old role,
1103 // so convert role new to old for emitting event
1104 const char* old_role = this->rolenew2old[label].c_str();
1106 this->emit_visible(old_role);
1107 this->emit_activated(old_role);
1111 void WindowManager::deactivate(int id)
1113 /* auto ip = this->controller->sprops.find(id);
1114 if (ip != this->controller->sprops.end())
1117 this->id_alloc.lookup(id).value_or("unknown-name").c_str();
1119 /*// FOR CES DEMO >>>
1120 if ((0 == strcmp(label, "radio")) ||
1121 (0 == strcmp(label, "music")) ||
1122 (0 == strcmp(label, "video")) ||
1123 (0 == strcmp(label, "map")))
1127 this->surface_bg.push_back(id);
1129 // Remove from FG layer (1001)
1130 HMI_DEBUG("Remove %s(%d) from FG layer", label, id);
1131 this->controller->layers[1001]->remove_surface(id);
1133 // Add to BG layer (999)
1134 HMI_DEBUG("Add %s(%d) to BG layer", label, id);
1135 this->controller->layers[999]->add_surface(id);
1137 for (int j : surface_bg)
1139 HMI_DEBUG("Stored id:%d", j);
1144 this->controller->surfaces[id]->set_visibility(0);
1148 this->layout_commit(); */
1150 // TODO: application requests by old role,
1151 // so convert role new to old for emitting event
1152 const char* old_role = this->rolenew2old[label].c_str();
1154 this->emit_deactivated(old_role);
1155 this->emit_invisible(old_role);
1159 WMError WindowManager::setRequest(const string& appid, const string &role, const string &area,
1160 Task task, unsigned* req_num)
1162 if (!g_app_list.contains(appid))
1164 return WMError::NOT_REGISTERED;
1167 auto client = g_app_list.lookUpClient(appid);
1172 unsigned current = g_app_list.currentRequestNumber();
1173 unsigned requested_num = g_app_list.getRequestNumber(appid);
1174 if (requested_num != 0)
1176 HMI_SEQ_INFO(requested_num,
1177 "%s %s %s request is already queued", appid.c_str(), role.c_str(), area.c_str());
1178 return REQ_REJECTED;
1181 WMRequest req = WMRequest(appid, role, area, task);
1182 unsigned new_req = g_app_list.addRequest(req);
1184 g_app_list.reqDump();
1186 HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", appid.c_str(), role.c_str(), area.c_str());
1188 return WMError::SUCCESS;
1191 WMError WindowManager::doTransition(unsigned req_num)
1193 HMI_SEQ_DEBUG(req_num, "check policy");
1194 WMError ret = this->checkPolicy(req_num);
1198 WMError WindowManager::checkPolicy(unsigned req_num)
1203 // get current trigger
1205 WMError ret = WMError::LAYOUT_CHANGE_FAIL;
1206 auto trigger = g_app_list.getRequest(req_num, &found);
1209 ret = WMError::NO_ENTRY;
1212 string req_area = trigger.area;
1214 if (trigger.task == Task::TASK_ALLOCATE)
1216 const char *msg = this->check_surface_exist(trigger.role.c_str());
1220 HMI_SEQ_ERROR(req_num, msg);
1225 // Input event data to PolicyManager
1226 if (0 > this->pmw.setInputEventData(trigger.task, trigger.role, trigger.area))
1228 HMI_SEQ_ERROR(req_num, "Failed to set input event data to PolicyManager");
1232 // Execute state transition of PolicyManager
1233 if (0 > this->pmw.executeStateTransition())
1235 HMI_SEQ_ERROR(req_num, "Failed to execute state transition of PolicyManager");
1239 ret = WMError::SUCCESS;
1241 g_app_list.reqDump();
1246 WMError WindowManager::startTransition(unsigned req_num)
1248 bool sync_draw_happen = false;
1250 WMError ret = WMError::SUCCESS;
1251 auto actions = g_app_list.getActions(req_num, &found);
1254 ret = WMError::NO_ENTRY;
1255 HMI_SEQ_ERROR(req_num,
1256 "Window Manager bug :%s : Action is not set", errorDescription(ret));
1260 for (const auto &action : actions)
1262 if (action.visible == TaskVisible::VISIBLE)
1264 sync_draw_happen = true;
1266 // TODO: application requests by old role,
1267 // so convert role new to old for emitting event
1268 string old_role = this->rolenew2old[action.role];
1270 this->emit_syncdraw(old_role, action.area);
1271 /* TODO: emit event for app not subscriber
1272 if(g_app_list.contains(y.appid))
1273 g_app_list.lookUpClient(y.appid)->emit_syncdraw(y.role, y.area); */
1277 if (sync_draw_happen)
1283 // deactivate only, no syncDraw
1284 // Make it deactivate here
1285 for (const auto &x : actions)
1287 if (g_app_list.contains(x.appid))
1289 auto client = g_app_list.lookUpClient(x.appid);
1290 this->deactivate(client->surfaceID(x.role));
1293 ret = WMError::NO_LAYOUT_CHANGE;
1298 WMError WindowManager::doEndDraw(unsigned req_num)
1302 auto actions = g_app_list.getActions(req_num, &found);
1303 WMError ret = WMError::SUCCESS;
1306 ret = WMError::NO_ENTRY;
1310 HMI_SEQ_INFO(req_num, "do endDraw");
1312 // layout change and make it visible
1313 for (const auto &act : actions)
1315 if(act.visible != TaskVisible::NO_CHANGE)
1318 if(!g_app_list.contains(act.appid)){
1319 ret = WMError::NOT_REGISTERED;
1321 ret = this->lc->layoutChange(act);
1322 if(ret != WMError::SUCCESS)
1324 HMI_SEQ_WARNING(req_num,
1325 "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1328 ret = this->lc->visibilityChange(act);
1329 if (ret != WMError::SUCCESS)
1331 HMI_SEQ_WARNING(req_num,
1332 "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1335 HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str());
1336 //this->lc_enddraw(act.role.c_str());
1339 this->lc->commitChange();
1341 HMI_SEQ_INFO(req_num, "emit flushDraw");
1343 for(const auto &act_flush : actions)
1345 if(act_flush.visible == TaskVisible::VISIBLE)
1347 // TODO: application requests by old role,
1348 // so convert role new to old for emitting event
1349 string old_role = this->rolenew2old[act_flush.role];
1351 this->emit_flushdraw(old_role.c_str());
1358 WMError WindowManager::layoutChange(const WMAction &action)
1360 if (action.visible == TaskVisible::INVISIBLE)
1362 // Visibility is not change -> no redraw is required
1363 return WMError::SUCCESS;
1365 auto client = g_app_list.lookUpClient(action.appid);
1366 unsigned surface = client->surfaceID(action.role);
1369 HMI_SEQ_ERROR(g_app_list.currentRequestNumber(),
1370 "client doesn't have surface with role(%s)", action.role.c_str());
1371 return WMError::NOT_REGISTERED;
1374 WMError ret = this->setSurfaceSize(surface, action.area);
1378 WMError WindowManager::visibilityChange(const WMAction &action)
1380 HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Change visibility");
1381 if(!g_app_list.contains(action.appid)){
1382 return WMError::NOT_REGISTERED;
1384 auto client = g_app_list.lookUpClient(action.appid);
1385 unsigned surface = client->surfaceID(action.role);
1388 HMI_SEQ_ERROR(g_app_list.currentRequestNumber(),
1389 "client doesn't have surface with role(%s)", action.role.c_str());
1390 return WMError::NOT_REGISTERED;
1393 if (action.visible != TaskVisible::INVISIBLE)
1395 this->activate(surface); // Layout Manager task
1399 this->deactivate(surface); // Layout Manager task
1401 return WMError::SUCCESS;
1404 WMError WindowManager::setSurfaceSize(unsigned surface, const string &area)
1406 this->surface_set_layout(surface, area);
1408 return WMError::SUCCESS;
1411 void WindowManager::emitScreenUpdated(unsigned req_num)
1414 HMI_SEQ_DEBUG(req_num, "emit screen updated");
1416 auto actions = g_app_list.getActions(req_num, &found);
1418 // create json object
1419 json_object *j = json_object_new_object();
1420 json_object *jarray = json_object_new_array();
1422 for(const auto& action: actions)
1424 if(action.visible != TaskVisible::INVISIBLE)
1426 json_object_array_add(jarray, json_object_new_string(action.appid.c_str()));
1429 json_object_object_add(j, kKeyIds, jarray);
1430 HMI_SEQ_INFO(req_num, "Visible app: %s", json_object_get_string(j));
1432 int ret = afb_event_push(
1433 this->map_afb_event[kListEventName[Event_ScreenUpdated]], j);
1436 HMI_DEBUG("afb_event_push failed: %m");
1440 void WindowManager::setTimer()
1443 if (clock_gettime(CLOCK_BOOTTIME, &ts) != 0) {
1444 HMI_ERROR("Could't set time (clock_gettime() returns with error");
1448 HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Timer set activate");
1449 if (g_timer_ev_src == nullptr)
1451 // firsttime set into sd_event
1452 int ret = sd_event_add_time(afb_daemon_get_event_loop(), &g_timer_ev_src,
1453 CLOCK_BOOTTIME, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL, 1, processTimerHandler, this);
1456 HMI_ERROR("Could't set timer");
1461 // update timer limitation after second time
1462 sd_event_source_set_time(g_timer_ev_src, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL);
1463 sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT);
1467 void WindowManager::stopTimer()
1469 unsigned req_num = g_app_list.currentRequestNumber();
1470 HMI_SEQ_DEBUG(req_num, "Timer stop");
1471 int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF);
1474 HMI_SEQ_ERROR(req_num, "Timer stop failed");
1478 void WindowManager::processNextRequest()
1481 g_app_list.reqDump();
1482 unsigned req_num = g_app_list.currentRequestNumber();
1483 if (g_app_list.haveRequest())
1485 HMI_SEQ_DEBUG(req_num, "Process next request");
1486 WMError rc = doTransition(req_num);
1487 if (rc != WMError::SUCCESS)
1489 HMI_SEQ_ERROR(req_num, errorDescription(rc));
1494 HMI_SEQ_DEBUG(req_num, "Nothing Request. Waiting Request");
1498 const char* WindowManager::convertRoleOldToNew(char const *old_role)
1500 const char *new_role = nullptr;
1502 for (auto const &on : this->roleold2new)
1504 std::regex regex = std::regex(on.first);
1505 if (std::regex_match(old_role, regex))
1507 // role is old. So convert to new.
1508 new_role = on.second.c_str();
1513 if (nullptr == new_role)
1515 // role is new or fallback.
1516 new_role = old_role;
1519 HMI_DEBUG("old:%s -> new:%s", old_role, new_role);
1524 int WindowManager::loadOldRoleDb()
1526 // Get afm application installed dir
1527 char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1528 HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
1531 if (!afm_app_install_dir)
1533 HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
1537 file_name = string(afm_app_install_dir) + string("/etc/old_roles.db");
1541 json_object* json_obj;
1542 int ret = jh::inputJsonFilie(file_name.c_str(), &json_obj);
1545 HMI_ERROR("Could not open old_role.db, so use default old_role information");
1546 json_obj = json_tokener_parse(kDefaultOldRoleDb);
1548 HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
1551 json_object* json_cfg;
1552 if (!json_object_object_get_ex(json_obj, "old_roles", &json_cfg))
1554 HMI_ERROR("Parse Error!!");
1558 int len = json_object_array_length(json_cfg);
1559 HMI_DEBUG("json_cfg len:%d", len);
1560 HMI_DEBUG("json_cfg dump:%s", json_object_get_string(json_cfg));
1562 for (int i=0; i<len; i++)
1564 json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
1566 const char* old_role = jh::getStringFromJson(json_tmp, "name");
1567 if (nullptr == old_role)
1569 HMI_ERROR("Parse Error!!");
1573 const char* new_role = jh::getStringFromJson(json_tmp, "new");
1574 if (nullptr == new_role)
1576 HMI_ERROR("Parse Error!!");
1580 this->roleold2new[old_role] = string(new_role);
1584 for(auto itr = this->roleold2new.begin();
1585 itr != this->roleold2new.end(); ++itr)
1587 HMI_DEBUG(">>> role old:%s new:%s",
1588 itr->first.c_str(), itr->second.c_str());
1591 // Release json_object
1592 json_object_put(json_obj);
1597 const char *WindowManager::check_surface_exist(const char *drawing_name)
1599 auto const &surface_id = this->id_alloc.lookup(string(drawing_name));
1602 return "Surface does not exist";
1605 /* if (!this->controller->surface_exists(*surface_id))
1607 return "Surface does not exist in controller!";
1610 /* auto layer_id = this->layers.get_layer_id(*surface_id);
1614 return "Surface is not on any layer!";
1617 HMI_DEBUG("surface %d is detected", *surface_id);
1621 const char* WindowManager::kDefaultOldRoleDb = "{ \
1624 \"name\": \"HomeScreen\", \
1625 \"new\": \"homescreen\" \
1628 \"name\": \"Music\", \
1629 \"new\": \"music\" \
1632 \"name\": \"MediaPlayer\", \
1633 \"new\": \"music\" \
1636 \"name\": \"Video\", \
1637 \"new\": \"video\" \
1640 \"name\": \"VideoPlayer\", \
1641 \"new\": \"video\" \
1644 \"name\": \"WebBrowser\", \
1645 \"new\": \"browser\" \
1648 \"name\": \"Radio\", \
1649 \"new\": \"radio\" \
1652 \"name\": \"Phone\", \
1653 \"new\": \"phone\" \
1656 \"name\": \"Navigation\", \
1660 \"name\": \"HVAC\", \
1664 \"name\": \"Settings\", \
1665 \"new\": \"settings\" \
1668 \"name\": \"Dashboard\", \
1669 \"new\": \"dashboard\" \
1672 \"name\": \"POI\", \
1676 \"name\": \"Mixer\", \
1677 \"new\": \"mixer\" \
1680 \"name\": \"Restriction\", \
1681 \"new\": \"restriction\" \
1684 \"name\": \"^OnScreen.*\", \
1685 \"new\": \"on_screen\" \
1693 void controller_hooks::surface_created(uint32_t surface_id)
1695 this->wmgr->surface_created(surface_id);
1698 void controller_hooks::surface_removed(uint32_t surface_id)
1700 this->wmgr->surface_removed(surface_id);
1703 void controller_hooks::surface_visibility(uint32_t /*surface_id*/,
1706 void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/,
1712 void controller_hooks::surface_properties(uint32_t surface_id, uint32_t pid)
1714 this->wmgr->surface_properties(surface_id, pid);