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.
21 #include "window_manager.hpp"
22 #include "json_helper.hpp"
23 #include "applist.hpp"
27 #include <systemd/sd-event.h>
36 static const uint64_t kTimeOut = 3ULL; /* 3s */
38 /* DrawingArea name used by "{layout}.{area}" */
39 const char kNameLayoutNormal[] = "normal";
40 const char kNameLayoutSplit[] = "split";
41 const char kNameAreaFull[] = "full";
42 const char kNameAreaMain[] = "main";
43 const char kNameAreaSub[] = "sub";
45 /* Key for json obejct */
46 const char kKeyDrawingName[] = "drawing_name";
47 const char kKeyDrawingArea[] = "drawing_area";
48 const char kKeyDrawingRect[] = "drawing_rect";
49 const char kKeyX[] = "x";
50 const char kKeyY[] = "y";
51 const char kKeyWidth[] = "width";
52 const char kKeyHeight[] = "height";
53 const char kKeyWidthPixel[] = "width_pixel";
54 const char kKeyHeightPixel[] = "height_pixel";
55 const char kKeyWidthMm[] = "width_mm";
56 const char kKeyHeightMm[] = "height_mm";
57 const char kKeyScale[] = "scale";
58 const char kKeyIds[] = "ids";
60 static sd_event_source *g_timer_ev_src = nullptr;
61 static AppList g_app_list;
62 static WindowManager *g_context;
66 AfbClosure(unsigned pid, unsigned ppid, unsigned surface)
67 : pid(pid), ppid(ppid), surface(surface) {}
68 ~AfbClosure() = default;
77 static int processTimerHandler(sd_event_source *s, uint64_t usec, void *userdata)
79 HMI_NOTICE("Time out occurs because the client replys endDraw slow, so revert the request");
80 reinterpret_cast<wm::WindowManager *>(userdata)->timerHandler();
84 static void onStateTransitioned(vector<WMAction> actions)
86 g_context->startTransitionWrapper(actions);
91 g_context->processError(WMError::LAYOUT_CHANGE_FAIL);
98 WindowManager::WindowManager()
101 const char *path = getenv("AFM_APP_INSTALL_DIR");
104 HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
108 this->lc = std::make_shared<LayerControl>(root);
110 HMI_DEBUG("Layer Controller initialized");
113 int WindowManager::init()
115 // TODO: application requests by old role,
116 // so create role map (old, new)
118 LayerControlCallbacks lmcb;
119 lmcb.surfaceCreated = [&](unsigned pid, unsigned surface){
120 this->surface_created(pid, surface);
122 lmcb.surfaceDestroyed = [&](unsigned surface){
123 this->surface_removed(surface);
125 this->lc->init(lmcb);
126 this->loadOldRoleDb();
128 // Store my context for calling callback from PolicyManager
131 // Initialize PMWrapper
132 this->pmw.initialize();
134 // Register callback to PolicyManager
135 this->pmw.registerCallback(onStateTransitioned, onError);
138 for (int i = Event_Val_Min; i <= Event_Val_Max; i++)
140 map_afb_event[kListEventName[i]] = afb_daemon_make_event(kListEventName[i]);
143 const struct rect css_bg = this->lc->getAreaSize("fullscreen");
144 Screen screen = this->lc->getScreenInfo();
145 rectangle dp_bg(screen.width(), screen.height());
147 dp_bg.set_aspect(static_cast<double>(css_bg.w) / css_bg.h);
148 dp_bg.fit(screen.width(), screen.height());
149 dp_bg.center(screen.width(), screen.height());
150 HMI_DEBUG("SCALING: CSS BG(%dx%d) -> DDP %dx%d,(%dx%d)",
151 css_bg.w, css_bg.h, dp_bg.left(), dp_bg.top(), dp_bg.width(), dp_bg.height());
153 double scale = static_cast<double>(dp_bg.height()) / css_bg.h;
154 this->lc->setupArea(dp_bg, scale);
156 return 0; //init_layers();
159 result<int> WindowManager::api_request_surface(char const *appid, char const *drawing_name)
161 // TODO: application requests by old role,
162 // so convert role old to new
163 const char *role = this->convertRoleOldToNew(drawing_name);
165 string s_appid = appid;
166 string s_role = role;
168 if(!g_app_list.contains(s_appid))
170 // auto lid = this->layers.get_layer_id(string(role));
171 unsigned l_id = this->lc->getNewLayerID(s_role, &l_name);
175 * register drawing_name as fallback and make it displayed.
177 l_id = this->lc->getNewLayerID("fallback", &l_name);
178 HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
181 return Err<int>("Designated role does not match any role, fallback is disabled");
184 this->lc->createNewLayer(l_id);
185 // add client into the db
186 g_app_list.addClient(s_appid, l_id, s_role);
189 // generate surface ID for ivi-shell application
191 auto rname = this->id_alloc.lookup(string(role));
194 // name does not exist yet, allocate surface id...
195 auto id = int(this->id_alloc.generate_id(role));
196 this->tmp_surface2app[id] = {s_appid, 0};
198 // Set role map of (new, old)
199 this->rolenew2old[role] = string(drawing_name);
204 // Check currently registered drawing names if it is already there.
205 return Err<int>("Surface already present");
208 char const *WindowManager::api_request_surface(char const *appid, char const *drawing_name,
211 unsigned sid = std::stol(ivi_id);
213 HMI_DEBUG("This API(requestSurfaceXDG) is for XDG Application using runXDG");
215 * IVI-shell doesn't send surface_size event via ivi-wm protocol
216 * if the application is using XDG surface.
217 * So WM has to set surface size with original size here
219 WMError ret = this->lc->setXDGSurfaceOriginSize(sid);
222 HMI_ERROR("%s", errorDescription(ret));
223 HMI_WARNING("The main user of this API is runXDG");
227 // TODO: application requests by old role,
228 // so convert role old to new
229 const char *role = this->convertRoleOldToNew(drawing_name);
230 string s_role = role;
231 string s_appid = appid;
234 if(!g_app_list.contains(s_appid))
236 // auto lid = this->layers.get_layer_id(string(role));
237 unsigned l_id = this->lc->getNewLayerID(s_role, &l_name);
241 * register drawing_name as fallback and make it displayed.
243 l_id = this->lc->getNewLayerID("fallback", &l_name);
244 HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
247 return "Designated role does not match any role, fallback is disabled";
250 this->lc->createNewLayer(l_id);
251 // add client into the db
252 g_app_list.addClient(s_appid, l_id, s_role);
255 auto rname = this->id_alloc.lookup(s_role);
258 return "Surface already present";
261 // register pair drawing_name and ivi_id
262 this->id_alloc.register_name_id(role, sid);
264 auto client = g_app_list.lookUpClient(s_appid);
265 client->addSurface(sid);
267 // Set role map of (new, old)
268 this->rolenew2old[role] = string(drawing_name);
273 bool WindowManager::api_set_role(char const *appid, char const *drawing_name)
277 // TODO: application requests by old role,
278 // so convert role old to new
279 const char *role = this->convertRoleOldToNew(drawing_name);
280 string s_role = role;
281 string s_appid = appid;
285 if(!g_app_list.contains(s_appid))
287 // auto lid = this->layers.get_layer_id(string(role));
288 unsigned l_id = this->lc->getNewLayerID(s_role, &l_name);
292 * register drawing_name as fallback and make it displayed.
294 l_id = this->lc->getNewLayerID("fallback", &l_name);
295 HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
298 HMI_ERROR("Designated role does not match any role, fallback is disabled");
302 this->lc->createNewLayer(l_id);
303 // add client into the db
304 g_app_list.addClient(s_appid, l_id, s_role);
305 // Set role map of (new, old)
306 this->rolenew2old[role] = string(drawing_name);
309 // for(auto itr = this->tmp_surface2app.begin();
310 // itr != this->tmp_surface2app.end() ; ++itr)
312 for(auto& x : this->tmp_surface2app)
314 if(x.second.appid == s_appid)
316 unsigned surface = x.first;
317 auto client = g_app_list.lookUpClient(s_appid);
318 client->addSurface(surface);
319 this->tmp_surface2app.erase(surface);
320 this->id_alloc.register_name_id(s_role, surface);
326 // search floating surfaceID from pid if pid is designated.
327 wm_err = g_app_list.popFloatingSurface(pid, &surface);
330 // get floating surface with appid. If WM queries appid from pid,
331 // WM can bind surface and role with appid(not implemented yet)
332 //wm_err = g_app_list.popFloatingSurface(id);
334 if(wm_err != WMError::SUCCESS){
335 HMI_ERROR("No floating surface for app: %s", id.c_str());
336 g_app_list.addFloatingClient(id, lid, role);
337 HMI_NOTICE("%s : Waiting for surface creation", id.c_str());
342 if (g_app_list.contains(id))
344 HMI_INFO("Add role: %s with surface: %d. Client %s has multi surfaces.",
345 role.c_str(), surface, id.c_str());
346 auto client = g_app_list.lookUpClient(id);
347 client->appendRole(role);
350 HMI_INFO("Create new client: %s, surface: %d into layer: %d with role: %s",
351 id.c_str(), surface, lid, role.c_str());
352 g_app_list.addClient(id, lid, role);
355 // register pair drawing_name and ivi_id
360 void WindowManager::api_activate_surface(char const *appid, char const *drawing_name,
361 char const *drawing_area, const reply_func &reply)
363 // TODO: application requests by old role,
364 // so convert role old to new
365 const char *c_role = this->convertRoleOldToNew(drawing_name);
368 string role = c_role;
369 string area = drawing_area;
371 if(!g_app_list.contains(id))
373 reply("app doesn't request 'requestSurface' or 'setRole' yet");
376 auto client = g_app_list.lookUpClient(id);
378 // unsigned srfc = client->surfaceID(role);
379 // unsigned layer = client->layerID();
381 // g_app_list.removeFloatingSurface(client->surfaceID());
382 // g_app_list.removeFloatingSurface(client);
384 Task task = Task::TASK_ALLOCATE;
385 unsigned req_num = 0;
386 WMError ret = WMError::UNKNOWN;
388 ret = this->setRequest(id, role, area, task, &req_num);
390 //vector<WMLayerState> current_states = this->lc->getCurrentStates();
391 // ret = this->setRequest(id, role, area, task, current_states, &req_num);
393 if(ret != WMError::SUCCESS)
395 HMI_ERROR(errorDescription(ret));
396 reply("Failed to set request");
401 if (req_num != g_app_list.currentRequestNumber())
403 // Add request, then invoked after the previous task is finished
404 HMI_SEQ_DEBUG(req_num, "request is accepted");
411 ret = this->checkPolicy(req_num);
413 if (ret != WMError::SUCCESS)
416 HMI_SEQ_ERROR(req_num, errorDescription(ret));
417 g_app_list.removeRequest(req_num);
418 this->processNextRequest();
422 void WindowManager::api_deactivate_surface(char const *appid, char const *drawing_name,
423 const reply_func &reply)
425 // TODO: application requests by old role,
426 // so convert role old to new
427 const char *c_role = this->convertRoleOldToNew(drawing_name);
433 string role = c_role;
434 string area = ""; //drawing_area;
435 Task task = Task::TASK_RELEASE;
436 unsigned req_num = 0;
437 WMError ret = WMError::UNKNOWN;
439 ret = this->setRequest(id, role, area, task, &req_num);
441 if (ret != WMError::SUCCESS)
443 HMI_ERROR(errorDescription(ret));
444 reply("Failed to set request");
449 if (req_num != g_app_list.currentRequestNumber())
451 // Add request, then invoked after the previous task is finished
452 HMI_SEQ_DEBUG(req_num, "request is accepted");
459 ret = this->checkPolicy(req_num);
461 if (ret != WMError::SUCCESS)
464 HMI_SEQ_ERROR(req_num, errorDescription(ret));
465 g_app_list.removeRequest(req_num);
466 this->processNextRequest();
470 void WindowManager::api_enddraw(char const *appid, char const *drawing_name)
472 // TODO: application requests by old role,
473 // so convert role old to new
474 const char *c_role = this->convertRoleOldToNew(drawing_name);
477 string role = c_role;
478 unsigned current_req = g_app_list.currentRequestNumber();
479 bool result = g_app_list.setEndDrawFinished(current_req, id, role);
483 HMI_ERROR("%s is not in transition state", id.c_str());
487 if (g_app_list.endDrawFullfilled(current_req))
489 // do task for endDraw
491 WMError ret = this->doEndDraw(current_req);
493 if(ret != WMError::SUCCESS)
495 //this->emit_error();
497 // Undo state of PolicyManager
498 this->pmw.undoState();
499 this->lc->undoUpdate();
501 this->emitScreenUpdated(current_req);
502 HMI_SEQ_INFO(current_req, "Finish request status: %s", errorDescription(ret));
504 g_app_list.removeRequest(current_req);
506 this->processNextRequest();
510 HMI_SEQ_INFO(current_req, "Wait other App call endDraw");
515 bool WindowManager::api_client_set_render_order(char const* appid, const vector<string>& render_order)
519 auto client = g_app_list.lookUpClient(id);
522 client->setRenderOrder(render_order);
527 result<json_object *> WindowManager::api_client_attach_service_surface
528 (const char* appid, const char* dest, const char* service_surface, bool req_sid)
530 string uuid, s_dest = dest;
531 unsigned surface = 0;
532 auto client = g_app_list.lookUpClient(s_dest);
535 HMI_ERROR("Failed to look up destination [%s]", dest);
536 return Err<json_object *>("destination apploication is null");
538 uuid = client->attachTmpServiceSurface(appid, service_surface);
541 // name does not exist yet, allocate surface id...
542 surface = int(this->id_alloc.generate_id(uuid));
544 this->tmp_services.emplace_back(TmpService{appid, dest, service_surface, uuid});
546 json_object *object = json_object_new_object();
547 json_object_object_add(object, "uuid", json_object_new_string(uuid.c_str()));
548 json_object_object_add(object, "surface", json_object_new_int(surface));
550 return Ok<json_object *>(object);
553 result<json_object *> WindowManager::api_get_display_info()
555 Screen screen = this->lc->getScreenInfo();
557 json_object *object = json_object_new_object();
558 json_object_object_add(object, kKeyWidthPixel, json_object_new_int(screen.width()));
559 json_object_object_add(object, kKeyHeightPixel, json_object_new_int(screen.height()));
561 json_object_object_add(object, kKeyWidthMm, json_object_new_int(0));
562 json_object_object_add(object, kKeyHeightMm, json_object_new_int(0));
563 json_object_object_add(object, kKeyScale, json_object_new_double(this->lc->scale()));
565 return Ok<json_object *>(object);
568 result<json_object *> WindowManager::api_get_area_info(char const *drawing_name)
572 // TODO: application requests by old role,
573 // so convert role old to new
574 const char *role = this->convertRoleOldToNew(drawing_name);
576 // Check drawing name, surface/layer id
577 auto const &surface_id = this->id_alloc.lookup(string(role));
580 return Err<json_object *>("Surface does not exist");
583 // Set area rectangle
584 rect area_info = this->area_info[*surface_id];
585 json_object *object = json_object_new_object();
586 json_object_object_add(object, kKeyX, json_object_new_int(area_info.x));
587 json_object_object_add(object, kKeyY, json_object_new_int(area_info.y));
588 json_object_object_add(object, kKeyWidth, json_object_new_int(area_info.w));
589 json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
591 return Ok<json_object *>(object);
594 void WindowManager::send_event(char const *evname, char const *label)
596 HMI_DEBUG("%s: %s(%s)", __func__, evname, label);
598 json_object *j = json_object_new_object();
599 json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
601 int ret = afb_event_push(this->map_afb_event[evname], j);
604 HMI_DEBUG("afb_event_push failed: %m");
608 void WindowManager::send_event(char const *evname, char const *label, char const *area,
609 int x, int y, int w, int h)
611 HMI_DEBUG("%s: %s(%s, %s) x:%d y:%d w:%d h:%d",
612 __func__, evname, label, area, x, y, w, h);
614 json_object *j_rect = json_object_new_object();
615 json_object_object_add(j_rect, kKeyX, json_object_new_int(x));
616 json_object_object_add(j_rect, kKeyY, json_object_new_int(y));
617 json_object_object_add(j_rect, kKeyWidth, json_object_new_int(w));
618 json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
620 json_object *j = json_object_new_object();
621 json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
622 json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area));
623 json_object_object_add(j, kKeyDrawingRect, j_rect);
625 int ret = afb_event_push(this->map_afb_event[evname], j);
628 HMI_DEBUG("afb_event_push failed: %m");
632 string WindowManager::searchApp(unsigned pid, unsigned ppid, unsigned surface, json_object* resp)
634 // retrieve appid from pid from application manager
636 // check appid then add it to the client
637 HMI_INFO("Runners:%s", json_object_get_string(resp));
638 int size = json_object_array_length(resp);
639 HMI_INFO("pid %d, ppid %d, surface %d",pid, ppid, surface);
640 for(int i = 0; i < size; i++)
642 json_object *j = json_object_array_get_idx(resp, i);
643 int runid = jh::getIntFromJson(j, "runid");
644 const char* id = jh::getStringFromJson(j, "id");
645 HMI_DEBUG("Appid %s, runid %d", id, runid);
646 if(id && (runid == ppid))
649 s_id.erase(s_id.find('@'));
651 HMI_INFO("App found %s", appid.c_str());
657 HMI_WARNING("Failed to retrieve id");
662 void WindowManager::storeSurface(const string& appid, unsigned ppid, unsigned surface)
664 auto elem = std::find_if(this->tmp_services.begin(), this->tmp_services.end(),
665 [&appid](TmpService& ts){
666 return (ts.dest == appid );
669 this->lc->setXDGSurfaceOriginSize(surface);
670 if(elem != this->tmp_services.end())
673 auto client = g_app_list.lookUpClient(elem->dest);
674 if(client == nullptr)
678 HMI_INFO("Attach surface %d (service %s) to app %s", surface, elem->service.c_str(), elem->dest.c_str());
679 client->attachServiceSurface(elem->service, surface);
684 auto client = g_app_list.lookUpClient(appid);
685 if(client != nullptr)
687 client->addSurface(surface);
688 this->id_alloc.register_name_id(client->role(), surface);
692 // Store tmp surface and appid for application
693 // who requests setRole after creating shell surface
694 this->tmp_surface2app.emplace(surface, TmpClient{appid, ppid});
702 void WindowManager::surface_created(unsigned pid, unsigned surface_id)
705 if(this->tmp_surface2app.count(surface_id) != 0)
707 string appid = this->tmp_surface2app[surface_id].appid;
708 auto client = g_app_list.lookUpClient(appid);
709 if(client != nullptr)
711 WMError ret = client->addSurface(surface_id);
712 HMI_INFO("Add surface %d to \"%s\"", surface_id, appid.c_str());
713 if(ret != WMError::SUCCESS)
715 HMI_ERROR("Failed to add surface to client %s", client->appID().c_str());
718 this->tmp_surface2app.erase(surface_id);
722 HMI_NOTICE("Unknown surface %d", surface_id);
724 std::ostringstream os;
726 string path = "/proc/" + os.str() + "/stat";
727 std::ifstream ifs(path.c_str());
730 if(!ifs.fail() && std::getline(ifs, str))
732 std::sscanf(str.data(), "%*d %*s %*c %d", &ppid);
733 HMI_INFO("Retrieve ppid %d", ppid);
737 HMI_ERROR("Failed to open /proc/%d/stat", pid);
738 HMI_ERROR("File system may be different");
741 struct AfbClosure* c = new struct AfbClosure(pid, ppid, surface_id);
742 // search pid from surfaceID
743 afb_service_call("afm-main", "runners", json_object_new_object(),
744 [](void* closure, int stat, json_object* resp){
745 HMI_DEBUG("check %s", json_object_get_string(resp));
746 struct AfbClosure* c = static_cast<struct AfbClosure*>(closure);
750 HMI_ERROR("Failed to call runners");
755 json_object_object_get_ex(resp, "response", &j);
756 string appid = g_context->searchApp(c->pid, c->ppid, c->surface, j);
759 g_context->storeSurface(appid, c->ppid, c->surface);
762 json_object_put(resp);
768 void WindowManager::surface_removed(unsigned surface_id)
770 HMI_DEBUG("Delete surface_id %u", surface_id);
771 this->id_alloc.remove_id(surface_id);
772 // this->layers.remove_surface(surface_id);
773 g_app_list.removeSurface(surface_id);
776 void WindowManager::removeClient(const string &appid)
778 HMI_DEBUG("Remove clinet %s from list", appid.c_str());
779 auto client = g_app_list.lookUpClient(appid);
780 this->lc->terminateApp(client);
781 g_app_list.removeClient(appid);
784 void WindowManager::exceptionProcessForTransition()
786 unsigned req_num = g_app_list.currentRequestNumber();
787 HMI_SEQ_NOTICE(req_num, "Process exception handling for request. Remove current request %d", req_num);
788 g_app_list.removeRequest(req_num);
789 HMI_SEQ_NOTICE(g_app_list.currentRequestNumber(), "Process next request if exists");
790 this->processNextRequest();
793 void WindowManager::timerHandler()
795 unsigned req_num = g_app_list.currentRequestNumber();
796 HMI_SEQ_DEBUG(req_num, "Timer expired remove Request");
797 g_app_list.reqDump();
798 g_app_list.removeRequest(req_num);
799 this->processNextRequest();
802 void WindowManager::startTransitionWrapper(vector<WMAction> &actions)
805 // req_num is guaranteed by Window Manager
806 unsigned req_num = g_app_list.currentRequestNumber();
810 if (g_app_list.haveRequest())
812 HMI_SEQ_DEBUG(req_num, "There is no WMAction for this request");
813 goto proc_remove_request;
817 HMI_SEQ_DEBUG(req_num, "There is no request");
822 for (auto &act : actions)
827 auto const &surface_id = this->id_alloc.lookup(act.role.c_str());
828 if(surface_id == nullopt)
830 goto proc_remove_request;
832 std::string appid = g_app_list.getAppID(*surface_id, &found);
835 if (TaskVisible::INVISIBLE == act.visible)
837 // App is killed, so do not set this action
842 HMI_SEQ_ERROR(req_num, "appid which is visible is not found");
847 auto client = g_app_list.lookUpClient(appid);
848 act.req_num = req_num;
852 ret = g_app_list.setAction(req_num, act);
853 if (ret != WMError::SUCCESS)
855 HMI_SEQ_ERROR(req_num, "Setting action is failed");
860 HMI_SEQ_DEBUG(req_num, "Start transition.");
861 ret = this->startTransition(req_num);
862 if (ret != WMError::SUCCESS)
864 if (ret == WMError::NO_LAYOUT_CHANGE)
866 goto proc_remove_request;
870 HMI_SEQ_ERROR(req_num, "Transition state is failed");
879 HMI_SEQ_ERROR(req_num, errorDescription(ret));
880 this->pmw.undoState();
883 g_app_list.removeRequest(req_num);
884 this->processNextRequest();
887 void WindowManager::processError(WMError error)
889 unsigned req_num = g_app_list.currentRequestNumber();
892 HMI_SEQ_ERROR(req_num, errorDescription(error));
893 g_app_list.removeRequest(req_num);
894 this->processNextRequest();
898 ******* Private Functions *******
901 void WindowManager::emit_activated(char const *label)
903 this->send_event(kListEventName[Event_Active], label);
906 void WindowManager::emit_deactivated(char const *label)
908 this->send_event(kListEventName[Event_Inactive], label);
911 void WindowManager::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h)
913 this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
916 void WindowManager::emit_syncdraw(const string &role, const string &area)
918 rect rect = this->lc->getAreaSize(area);
919 this->send_event(kListEventName[Event_SyncDraw],
920 role.c_str(), area.c_str(), rect.x, rect.y, rect.w, rect.h);
923 void WindowManager::emit_flushdraw(char const *label)
925 this->send_event(kListEventName[Event_FlushDraw], label);
928 void WindowManager::emit_visible(char const *label, bool is_visible)
930 this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
933 void WindowManager::emit_invisible(char const *label)
935 return emit_visible(label, false);
938 void WindowManager::emit_visible(char const *label) { return emit_visible(label, true); }
940 void WindowManager::activate(int id)
942 // TODO: application requests by old role,
943 // so convert role new to old for emitting event
944 /* const char* old_role = this->rolenew2old[label].c_str();
946 this->emit_visible(old_role);
947 this->emit_activated(old_role); */
950 void WindowManager::deactivate(int id)
952 // TODO: application requests by old role,
953 // so convert role new to old for emitting event
954 /* const char* old_role = this->rolenew2old[label].c_str();
956 this->emit_deactivated(old_role);
957 this->emit_invisible(old_role); */
960 WMError WindowManager::setRequest(const string& appid, const string &role, const string &area,
961 Task task, unsigned* req_num)
963 if (!g_app_list.contains(appid))
965 return WMError::NOT_REGISTERED;
968 auto client = g_app_list.lookUpClient(appid);
973 unsigned current = g_app_list.currentRequestNumber();
974 unsigned requested_num = g_app_list.getRequestNumber(appid);
975 if (requested_num != 0)
977 HMI_SEQ_INFO(requested_num,
978 "%s %s %s request is already queued", appid.c_str(), role.c_str(), area.c_str());
982 WMRequest req = WMRequest(appid, role, area, task);
983 unsigned new_req = g_app_list.addRequest(req);
985 g_app_list.reqDump();
987 HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", appid.c_str(), role.c_str(), area.c_str());
989 return WMError::SUCCESS;
992 WMError WindowManager::checkPolicy(unsigned req_num)
997 // get current trigger
999 WMError ret = WMError::LAYOUT_CHANGE_FAIL;
1000 auto trigger = g_app_list.getRequest(req_num, &found);
1003 ret = WMError::NO_ENTRY;
1006 string req_area = trigger.area;
1008 if (trigger.task == Task::TASK_ALLOCATE)
1010 const char *msg = this->check_surface_exist(trigger.role.c_str());
1014 HMI_SEQ_ERROR(req_num, msg);
1019 // Input event data to PolicyManager
1020 if (0 > this->pmw.setInputEventData(trigger.task, trigger.role, trigger.area))
1022 HMI_SEQ_ERROR(req_num, "Failed to set input event data to PolicyManager");
1026 // Execute state transition of PolicyManager
1027 if (0 > this->pmw.executeStateTransition())
1029 HMI_SEQ_ERROR(req_num, "Failed to execute state transition of PolicyManager");
1033 ret = WMError::SUCCESS;
1035 g_app_list.reqDump();
1040 WMError WindowManager::startTransition(unsigned req_num)
1042 bool sync_draw_happen = false;
1044 WMError ret = WMError::SUCCESS;
1045 auto actions = g_app_list.getActions(req_num, &found);
1048 ret = WMError::NO_ENTRY;
1049 HMI_SEQ_ERROR(req_num,
1050 "Window Manager bug :%s : Action is not set", errorDescription(ret));
1054 g_app_list.reqDump();
1055 for (const auto &action : actions)
1057 if (action.visible == TaskVisible::VISIBLE)
1059 sync_draw_happen = true;
1061 // TODO: application requests by old role,
1062 // so convert role new to old for emitting event
1063 string old_role = this->rolenew2old[action.role];
1065 this->emit_syncdraw(old_role, action.area);
1066 /* TODO: emit event for app not subscriber
1067 if(g_app_list.contains(y.appid))
1068 g_app_list.lookUpClient(y.appid)->emit_syncdraw(y.role, y.area); */
1072 if (sync_draw_happen)
1078 // deactivate only, no syncDraw
1079 // Make it deactivate here
1080 for (const auto &x : actions)
1082 this->lc->visibilityChange(x);
1083 string old_role = this->rolenew2old[x.role];
1084 emit_deactivated(old_role.c_str());
1086 /* if (g_app_list.contains(x.appid))
1088 auto client = g_app_list.lookUpClient(x.appid);
1089 //this->deactivate(client->surfaceID(x.role));
1092 this->lc->renderLayers();
1093 ret = WMError::NO_LAYOUT_CHANGE;
1098 WMError WindowManager::doEndDraw(unsigned req_num)
1102 auto actions = g_app_list.getActions(req_num, &found);
1103 WMError ret = WMError::SUCCESS;
1106 ret = WMError::NO_ENTRY;
1110 HMI_SEQ_INFO(req_num, "do endDraw");
1112 // layout change and make it visible
1113 for (const auto &act : actions)
1115 if(act.visible != TaskVisible::NO_CHANGE)
1118 ret = this->lc->layoutChange(act);
1119 if(ret != WMError::SUCCESS)
1121 HMI_SEQ_WARNING(req_num,
1122 "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1125 ret = this->lc->visibilityChange(act);
1127 // Emit active/deactive event
1128 string old_role = this->rolenew2old[act.role];
1129 if(act.visible == VISIBLE)
1131 emit_activated(old_role.c_str());
1135 emit_deactivated(old_role.c_str());
1138 if (ret != WMError::SUCCESS)
1140 HMI_SEQ_WARNING(req_num,
1141 "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1144 HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str());
1147 this->lc->renderLayers();
1149 HMI_SEQ_INFO(req_num, "emit flushDraw");
1151 for(const auto &act_flush : actions)
1153 if(act_flush.visible == TaskVisible::VISIBLE)
1155 // TODO: application requests by old role,
1156 // so convert role new to old for emitting event
1157 string old_role = this->rolenew2old[act_flush.role];
1159 this->emit_flushdraw(old_role.c_str());
1166 void WindowManager::emitScreenUpdated(unsigned req_num)
1169 HMI_SEQ_DEBUG(req_num, "emit screen updated");
1171 auto actions = g_app_list.getActions(req_num, &found);
1173 // create json object
1174 json_object *j = json_object_new_object();
1175 json_object *jarray = json_object_new_array();
1177 for(const auto& action: actions)
1179 if(action.visible != TaskVisible::INVISIBLE)
1181 json_object_array_add(jarray, json_object_new_string(action.client->appID().c_str()));
1184 json_object_object_add(j, kKeyIds, jarray);
1185 HMI_SEQ_INFO(req_num, "Visible app: %s", json_object_get_string(j));
1187 int ret = afb_event_push(
1188 this->map_afb_event[kListEventName[Event_ScreenUpdated]], j);
1191 HMI_DEBUG("afb_event_push failed: %m");
1195 void WindowManager::setTimer()
1198 if (clock_gettime(CLOCK_BOOTTIME, &ts) != 0) {
1199 HMI_ERROR("Could't set time (clock_gettime() returns with error");
1203 HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Timer set activate");
1204 if (g_timer_ev_src == nullptr)
1206 // firsttime set into sd_event
1207 int ret = sd_event_add_time(afb_daemon_get_event_loop(), &g_timer_ev_src,
1208 CLOCK_BOOTTIME, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL, 1, processTimerHandler, this);
1211 HMI_ERROR("Could't set timer");
1216 // update timer limitation after second time
1217 sd_event_source_set_time(g_timer_ev_src, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL);
1218 sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT);
1222 void WindowManager::stopTimer()
1224 unsigned req_num = g_app_list.currentRequestNumber();
1225 HMI_SEQ_DEBUG(req_num, "Timer stop");
1226 int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF);
1229 HMI_SEQ_ERROR(req_num, "Timer stop failed");
1233 void WindowManager::processNextRequest()
1236 g_app_list.reqDump();
1237 unsigned req_num = g_app_list.currentRequestNumber();
1238 if (g_app_list.haveRequest())
1240 HMI_SEQ_DEBUG(req_num, "Process next request");
1241 WMError rc = checkPolicy(req_num);
1242 if (rc != WMError::SUCCESS)
1244 HMI_SEQ_ERROR(req_num, errorDescription(rc));
1249 HMI_SEQ_DEBUG(req_num, "Nothing Request. Waiting Request");
1253 const char* WindowManager::convertRoleOldToNew(char const *old_role)
1255 const char *new_role = nullptr;
1257 for (auto const &on : this->roleold2new)
1259 std::regex regex = std::regex(on.first);
1260 if (std::regex_match(old_role, regex))
1262 // role is old. So convert to new.
1263 new_role = on.second.c_str();
1268 if (nullptr == new_role)
1270 // role is new or fallback.
1271 new_role = old_role;
1274 HMI_DEBUG("old:%s -> new:%s", old_role, new_role);
1279 int WindowManager::loadOldRoleDb()
1281 // Get afm application installed dir
1282 char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1283 HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
1286 if (!afm_app_install_dir)
1288 HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
1292 file_name = string(afm_app_install_dir) + string("/etc/old_roles.db");
1296 json_object* json_obj;
1297 int ret = jh::inputJsonFilie(file_name.c_str(), &json_obj);
1300 HMI_ERROR("Could not open old_role.db, so use default old_role information");
1301 json_obj = json_tokener_parse(kDefaultOldRoleDb);
1303 HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
1306 json_object* json_cfg;
1307 if (!json_object_object_get_ex(json_obj, "old_roles", &json_cfg))
1309 HMI_ERROR("Parse Error!!");
1313 int len = json_object_array_length(json_cfg);
1314 HMI_DEBUG("json_cfg len:%d", len);
1315 HMI_DEBUG("json_cfg dump:%s", json_object_get_string(json_cfg));
1317 for (int i=0; i<len; i++)
1319 json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
1321 const char* old_role = jh::getStringFromJson(json_tmp, "name");
1322 if (nullptr == old_role)
1324 HMI_ERROR("Parse Error!!");
1328 const char* new_role = jh::getStringFromJson(json_tmp, "new");
1329 if (nullptr == new_role)
1331 HMI_ERROR("Parse Error!!");
1335 this->roleold2new[old_role] = string(new_role);
1339 for(auto itr = this->roleold2new.begin();
1340 itr != this->roleold2new.end(); ++itr)
1342 HMI_DEBUG(">>> role old:%s new:%s",
1343 itr->first.c_str(), itr->second.c_str());
1346 // Release json_object
1347 json_object_put(json_obj);
1352 const char *WindowManager::check_surface_exist(const char *drawing_name)
1354 auto const &surface_id = this->id_alloc.lookup(string(drawing_name));
1357 return "Surface does not exist";
1360 /* if (!this->controller->surface_exists(*surface_id))
1362 return "Surface does not exist in controller!";
1365 /* auto layer_id = this->layers.get_layer_id(*surface_id);
1369 return "Surface is not on any layer!";
1372 HMI_DEBUG("surface %d is detected", *surface_id);
1376 const char* WindowManager::kDefaultOldRoleDb = "{ \
1379 \"name\": \"HomeScreen\", \
1380 \"new\": \"homescreen\" \
1383 \"name\": \"Music\", \
1384 \"new\": \"music\" \
1387 \"name\": \"MediaPlayer\", \
1388 \"new\": \"music\" \
1391 \"name\": \"Video\", \
1392 \"new\": \"video\" \
1395 \"name\": \"VideoPlayer\", \
1396 \"new\": \"video\" \
1399 \"name\": \"WebBrowser\", \
1400 \"new\": \"browser\" \
1403 \"name\": \"Radio\", \
1404 \"new\": \"radio\" \
1407 \"name\": \"Phone\", \
1408 \"new\": \"phone\" \
1411 \"name\": \"Navigation\", \
1415 \"name\": \"HVAC\", \
1419 \"name\": \"Settings\", \
1420 \"new\": \"settings\" \
1423 \"name\": \"Dashboard\", \
1424 \"new\": \"dashboard\" \
1427 \"name\": \"POI\", \
1431 \"name\": \"Mixer\", \
1432 \"new\": \"mixer\" \
1435 \"name\": \"Restriction\", \
1436 \"new\": \"restriction\" \
1439 \"name\": \"^OnScreen.*\", \
1440 \"new\": \"on_screen\" \