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 const vector<string> kListEventName{
69 static sd_event_source *g_timer_ev_src = nullptr;
70 static AppList g_app_list;
71 static WindowManager *g_context;
76 static int processTimerHandler(sd_event_source *s, uint64_t usec, void *userdata)
78 HMI_NOTICE("Time out occurs because the client replys endDraw slow, so revert the request");
79 reinterpret_cast<wm::WindowManager *>(userdata)->timerHandler();
83 static void onStateTransitioned(vector<WMAction> actions)
85 g_context->startTransitionWrapper(actions);
90 g_context->processError(WMError::LAYOUT_CHANGE_FAIL);
97 WindowManager::WindowManager()
100 const char *path = getenv("AFM_APP_INSTALL_DIR");
103 HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
107 this->lc = std::make_shared<LayerControl>(root);
109 HMI_DEBUG("Layer Controller initialized");
112 int WindowManager::init()
114 LayerControlCallbacks lmcb;
115 lmcb.surfaceCreated = [&](unsigned pid, unsigned surface){
116 this->surface_created(surface);
118 lmcb.surfaceDestroyed = [&](unsigned surface){
119 this->surface_removed(surface);
122 if(this->lc->init(lmcb) != WMError::SUCCESS)
127 // Store my context for calling callback from PolicyManager
130 // Initialize PMWrapper
131 this->pmw.initialize();
133 // Register callback to PolicyManager
134 this->pmw.registerCallback(onStateTransitioned, onError);
137 for (int i = Event_Val_Min; i <= Event_Val_Max; i++)
139 map_afb_event[kListEventName[i]] = afb_api_make_event(afbBindingV3root, kListEventName[i].c_str());
142 const struct rect css_bg = this->lc->getAreaSize("fullscreen");
143 Screen screen = this->lc->getScreenInfo();
144 rectangle dp_bg(screen.width(), screen.height());
146 dp_bg.set_aspect(static_cast<double>(css_bg.w) / css_bg.h);
147 dp_bg.fit(screen.width(), screen.height());
148 dp_bg.center(screen.width(), screen.height());
149 HMI_DEBUG("SCALING: CSS BG(%dx%d) -> DDP %dx%d,(%dx%d)",
150 css_bg.w, css_bg.h, dp_bg.left(), dp_bg.top(), dp_bg.width(), dp_bg.height());
152 double scale = static_cast<double>(dp_bg.height()) / css_bg.h;
153 this->lc->setupArea(dp_bg, scale);
158 result<int> WindowManager::api_request_surface(char const *appid, char const *drawing_name)
160 string str_id = appid;
161 string role = drawing_name;
164 if(!g_app_list.contains(str_id))
166 lid = this->lc->getNewLayerID(role);
169 // register drawing_name as fallback and make it displayed.
170 lid = this->lc->getNewLayerID(string("fallback"));
171 HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
174 return Err<int>("Designated role does not match any role, fallback is disabled");
177 this->lc->createNewLayer(lid);
178 // add client into the db
179 g_app_list.addClient(str_id, lid, role);
182 // generate surface ID for ivi-shell application
183 auto rname = this->id_alloc.lookup(role);
186 // name does not exist yet, allocate surface id...
187 auto id = int(this->id_alloc.generate_id(role));
188 this->tmp_surface2app[id] = {str_id, lid};
190 auto client = g_app_list.lookUpClient(str_id);
191 client->registerSurface(id);
196 // Check currently registered drawing names if it is already there.
197 return Err<int>("Surface already present");
200 char const *WindowManager::api_request_surface(char const *appid, char const *drawing_name,
203 string str_id = appid;
204 string role = drawing_name;
206 unsigned sid = std::stol(ivi_id);
207 HMI_DEBUG("This API(requestSurfaceXDG) is for XDG Application using runXDG");
209 * IVI-shell doesn't send surface_size event via ivi-wm protocol
210 * if the application is using XDG surface.
211 * So WM has to set surface size with original size here
213 WMError ret = this->lc->setXDGSurfaceOriginSize(sid);
216 HMI_ERROR("%s", errorDescription(ret));
217 HMI_WARNING("The main user of this API is runXDG");
221 if(!g_app_list.contains(str_id))
223 unsigned l_id = this->lc->getNewLayerID(role);
226 // register drawing_name as fallback and make it displayed.
227 l_id = this->lc->getNewLayerID("fallback");
228 HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
231 return "Designated role does not match any role, fallback is disabled";
234 this->lc->createNewLayer(l_id);
235 // add client into the db
236 g_app_list.addClient(str_id, l_id, role);
239 auto rname = this->id_alloc.lookup(role);
243 return "Surface already present";
246 // register pair drawing_name and ivi_id
247 this->id_alloc.register_name_id(role, sid);
249 auto client = g_app_list.lookUpClient(str_id);
250 client->addSurface(sid);
255 void WindowManager::api_activate_window(char const *appid, char const *drawing_name,
256 char const *drawing_area, const reply_func &reply)
259 string role = drawing_name;
260 string area = drawing_area;
262 if(!g_app_list.contains(id))
264 reply("app doesn't request 'requestSurface' or 'setRole' yet");
267 auto client = g_app_list.lookUpClient(id);
269 Task task = Task::TASK_ALLOCATE;
270 unsigned req_num = 0;
271 WMError ret = WMError::UNKNOWN;
273 ret = this->setRequest(id, role, area, task, &req_num);
275 if(ret != WMError::SUCCESS)
277 HMI_ERROR(errorDescription(ret));
278 reply("Failed to set request");
283 if (req_num != g_app_list.currentRequestNumber())
285 // Add request, then invoked after the previous task is finished
286 HMI_SEQ_DEBUG(req_num, "request is accepted");
292 ret = this->checkPolicy(req_num);
294 if (ret != WMError::SUCCESS)
297 HMI_SEQ_ERROR(req_num, errorDescription(ret));
298 g_app_list.removeRequest(req_num);
299 this->processNextRequest();
303 void WindowManager::api_deactivate_window(char const *appid, char const *drawing_name,
304 const reply_func &reply)
308 string role = drawing_name;
309 string area = ""; //drawing_area;
310 Task task = Task::TASK_RELEASE;
311 unsigned req_num = 0;
312 WMError ret = WMError::UNKNOWN;
314 ret = this->setRequest(id, role, area, task, &req_num);
316 if (ret != WMError::SUCCESS)
318 HMI_ERROR(errorDescription(ret));
319 reply("Failed to set request");
324 if (req_num != g_app_list.currentRequestNumber())
326 // Add request, then invoked after the previous task is finished
327 HMI_SEQ_DEBUG(req_num, "request is accepted");
332 ret = this->checkPolicy(req_num);
334 if (ret != WMError::SUCCESS)
337 HMI_SEQ_ERROR(req_num, errorDescription(ret));
338 g_app_list.removeRequest(req_num);
339 this->processNextRequest();
343 void WindowManager::api_enddraw(char const *appid, char const *drawing_name)
346 string role = drawing_name;
347 unsigned current_req = g_app_list.currentRequestNumber();
348 bool result = g_app_list.setEndDrawFinished(current_req, id, role);
352 HMI_ERROR("%s is not in transition state", id.c_str());
356 if (g_app_list.endDrawFullfilled(current_req))
358 // do task for endDraw
360 WMError ret = this->doEndDraw(current_req);
362 if(ret != WMError::SUCCESS)
364 //this->emit_error();
366 // Undo state of PolicyManager
367 this->pmw.undoState();
368 this->lc->undoUpdate();
370 this->emitScreenUpdated(current_req);
371 HMI_SEQ_INFO(current_req, "Finish request status: %s", errorDescription(ret));
373 g_app_list.removeRequest(current_req);
375 this->processNextRequest();
379 HMI_SEQ_INFO(current_req, "Wait other App call endDraw");
384 int WindowManager::api_subscribe(afb_req_t req, int event_id)
386 afb_event_t event = this->map_afb_event[kListEventName[event_id]];
387 return afb_req_subscribe(req, event);
390 result<json_object *> WindowManager::api_get_display_info()
392 Screen screen = this->lc->getScreenInfo();
394 json_object *object = json_object_new_object();
395 json_object_object_add(object, kKeyWidthPixel, json_object_new_int(screen.width()));
396 json_object_object_add(object, kKeyHeightPixel, json_object_new_int(screen.height()));
398 json_object_object_add(object, kKeyWidthMm, json_object_new_int(0));
399 json_object_object_add(object, kKeyHeightMm, json_object_new_int(0));
400 json_object_object_add(object, kKeyScale, json_object_new_double(this->lc->scale()));
402 return Ok<json_object *>(object);
405 result<json_object *> WindowManager::api_get_area_info(char const *drawing_name)
409 string role = drawing_name;
411 // Check drawing name, surface/layer id
412 auto const &surface_id = this->id_alloc.lookup(role);
415 return Err<json_object *>("Surface does not exist");
418 // Set area rectangle
419 struct rect area_info = this->area_info[*surface_id];
420 json_object *object = json_object_new_object();
421 json_object_object_add(object, kKeyX, json_object_new_int(area_info.x));
422 json_object_object_add(object, kKeyY, json_object_new_int(area_info.y));
423 json_object_object_add(object, kKeyWidth, json_object_new_int(area_info.w));
424 json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
426 return Ok<json_object *>(object);
429 void WindowManager::send_event(const string& evname, const string& role)
431 json_object *j = json_object_new_object();
432 json_object_object_add(j, kKeyDrawingName, json_object_new_string(role.c_str()));
434 int ret = afb_event_push(this->map_afb_event[evname], j);
437 HMI_DEBUG("afb_event_push failed: %m");
441 void WindowManager::send_event(const string& evname, const string& role, const string& area,
442 int x, int y, int w, int h)
444 json_object *j_rect = json_object_new_object();
445 json_object_object_add(j_rect, kKeyX, json_object_new_int(x));
446 json_object_object_add(j_rect, kKeyY, json_object_new_int(y));
447 json_object_object_add(j_rect, kKeyWidth, json_object_new_int(w));
448 json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
450 json_object *j = json_object_new_object();
451 json_object_object_add(j, kKeyDrawingName, json_object_new_string(role.c_str()));
452 json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area.c_str()));
453 json_object_object_add(j, kKeyDrawingRect, j_rect);
455 int ret = afb_event_push(this->map_afb_event[evname], j);
458 HMI_DEBUG("afb_event_push failed: %m");
465 void WindowManager::surface_created(unsigned surface_id)
468 if(this->tmp_surface2app.count(surface_id) != 0)
470 string appid = this->tmp_surface2app[surface_id].appid;
471 auto client = g_app_list.lookUpClient(appid);
472 if(client != nullptr)
474 WMError ret = client->addSurface(surface_id);
475 HMI_INFO("Add surface %d to \"%s\"", surface_id, appid.c_str());
476 if(ret != WMError::SUCCESS)
478 HMI_ERROR("Failed to add surface to client %s", client->appID().c_str());
481 this->tmp_surface2app.erase(surface_id);
485 void WindowManager::surface_removed(unsigned surface_id)
487 HMI_DEBUG("Delete surface_id %u", surface_id);
488 this->id_alloc.remove_id(surface_id);
489 g_app_list.removeSurface(surface_id);
492 void WindowManager::removeClient(const string &appid)
494 HMI_DEBUG("Remove clinet %s from list", appid.c_str());
495 auto client = g_app_list.lookUpClient(appid);
496 this->lc->appTerminated(client);
497 g_app_list.removeClient(appid);
500 void WindowManager::exceptionProcessForTransition()
502 unsigned req_num = g_app_list.currentRequestNumber();
503 HMI_SEQ_NOTICE(req_num, "Process exception handling for request. Remove current request %d", req_num);
504 g_app_list.removeRequest(req_num);
505 HMI_SEQ_NOTICE(g_app_list.currentRequestNumber(), "Process next request if exists");
506 this->processNextRequest();
509 void WindowManager::timerHandler()
511 unsigned req_num = g_app_list.currentRequestNumber();
512 HMI_SEQ_DEBUG(req_num, "Timer expired remove Request");
513 g_app_list.reqDump();
514 g_app_list.removeRequest(req_num);
515 this->processNextRequest();
518 void WindowManager::startTransitionWrapper(vector<WMAction> &actions)
521 unsigned req_num = g_app_list.currentRequestNumber();
525 if (g_app_list.haveRequest())
527 HMI_SEQ_DEBUG(req_num, "There is no WMAction for this request");
528 goto proc_remove_request;
532 HMI_SEQ_DEBUG(req_num, "There is no request");
537 for (auto &act : actions)
542 auto const &surface_id = this->id_alloc.lookup(act.role);
543 if(surface_id == nullopt)
545 goto proc_remove_request;
547 string appid = g_app_list.getAppID(*surface_id, &found);
550 if (TaskVisible::INVISIBLE == act.visible)
552 // App is killed, so do not set this action
557 HMI_SEQ_ERROR(req_num, "appid which is visible is not found");
562 auto client = g_app_list.lookUpClient(appid);
563 act.req_num = req_num;
567 ret = g_app_list.setAction(req_num, act);
568 if (ret != WMError::SUCCESS)
570 HMI_SEQ_ERROR(req_num, "Setting action is failed");
575 HMI_SEQ_DEBUG(req_num, "Start transition.");
576 ret = this->startTransition(req_num);
577 if (ret != WMError::SUCCESS)
579 if (ret == WMError::NO_LAYOUT_CHANGE)
581 goto proc_remove_request;
585 HMI_SEQ_ERROR(req_num, "Transition state is failed");
594 HMI_SEQ_ERROR(req_num, errorDescription(ret));
595 this->pmw.undoState();
598 g_app_list.removeRequest(req_num);
599 this->processNextRequest();
602 void WindowManager::processError(WMError error)
604 unsigned req_num = g_app_list.currentRequestNumber();
607 HMI_SEQ_ERROR(req_num, errorDescription(error));
608 g_app_list.removeRequest(req_num);
609 this->processNextRequest();
613 ******* Private Functions *******
616 void WindowManager::emit_activated(const string& role)
618 this->send_event(kListEventName[Event_Active], role);
621 void WindowManager::emit_deactivated(const string& role)
623 this->send_event(kListEventName[Event_Inactive], role);
626 void WindowManager::emit_syncdraw(const string& role, char const *area, int x, int y, int w, int h)
628 this->send_event(kListEventName[Event_SyncDraw], role, area, x, y, w, h);
631 void WindowManager::emit_syncdraw(const string &role, const string &area)
633 struct rect rect = this->lc->getAreaSize(area);
634 this->send_event(kListEventName[Event_SyncDraw],
635 role, area, rect.x, rect.y, rect.w, rect.h);
638 void WindowManager::emit_flushdraw(const string& role)
640 this->send_event(kListEventName[Event_FlushDraw], role);
643 void WindowManager::emit_visible(const string& role, bool is_visible)
645 this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], role);
648 void WindowManager::emit_invisible(const string& role)
650 return emit_visible(role, false);
653 void WindowManager::emit_visible(const string& role) { return emit_visible(role, true); }
655 WMError WindowManager::setRequest(const string& appid, const string &role, const string &area,
656 Task task, unsigned* req_num)
658 if (!g_app_list.contains(appid))
660 return WMError::NOT_REGISTERED;
663 auto client = g_app_list.lookUpClient(appid);
668 unsigned current = g_app_list.currentRequestNumber();
669 unsigned requested_num = g_app_list.getRequestNumber(appid);
670 if (requested_num != 0)
672 HMI_SEQ_INFO(requested_num,
673 "%s %s %s request is already queued", appid.c_str(), role.c_str(), area.c_str());
677 WMRequest req = WMRequest(appid, role, area, task);
678 unsigned new_req = g_app_list.addRequest(req);
680 g_app_list.reqDump();
682 HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", appid.c_str(), role.c_str(), area.c_str());
684 return WMError::SUCCESS;
687 WMError WindowManager::checkPolicy(unsigned req_num)
692 // get current trigger
694 WMError ret = WMError::LAYOUT_CHANGE_FAIL;
695 auto trigger = g_app_list.getRequest(req_num, &found);
698 ret = WMError::NO_ENTRY;
701 string req_area = trigger.area;
703 // Input event data to PolicyManager
704 if (0 > this->pmw.setInputEventData(trigger.task, trigger.role, trigger.area))
706 HMI_SEQ_ERROR(req_num, "Failed to set input event data to PolicyManager");
710 // Execute state transition of PolicyManager
711 if (0 > this->pmw.executeStateTransition())
713 HMI_SEQ_ERROR(req_num, "Failed to execute state transition of PolicyManager");
717 ret = WMError::SUCCESS;
719 g_app_list.reqDump();
724 WMError WindowManager::startTransition(unsigned req_num)
726 bool sync_draw_happen = false;
728 WMError ret = WMError::SUCCESS;
729 auto actions = g_app_list.getActions(req_num, &found);
732 ret = WMError::NO_ENTRY;
733 HMI_SEQ_ERROR(req_num,
734 "Window Manager bug :%s : Action is not set", errorDescription(ret));
738 g_app_list.reqDump();
739 for (const auto &action : actions)
741 if (action.visible == TaskVisible::VISIBLE)
743 sync_draw_happen = true;
744 this->emit_syncdraw(action.role, action.area);
745 /* TODO: emit event for app not subscriber
746 if(g_app_list.contains(y.appid))
747 g_app_list.lookUpClient(y.appid)->emit_syncdraw(y.role, y.area); */
751 if (sync_draw_happen)
757 // deactivate only, no syncDraw
758 // Make it deactivate here
759 for (const auto &x : actions)
761 this->lc->visibilityChange(x);
762 emit_deactivated(x.role);
763 /* if (g_app_list.contains(x.client->appID()))
765 auto client = g_app_list.lookUpClient(x.client->appID());
766 this->deactivate(client->surfaceID(x.role));
769 this->lc->renderLayers();
770 ret = WMError::NO_LAYOUT_CHANGE;
775 WMError WindowManager::doEndDraw(unsigned req_num)
779 auto actions = g_app_list.getActions(req_num, &found);
780 WMError ret = WMError::SUCCESS;
783 ret = WMError::NO_ENTRY;
787 HMI_SEQ_INFO(req_num, "do endDraw");
789 // layout change and make it visible
790 for (const auto &act : actions)
792 if(act.visible != TaskVisible::NO_CHANGE)
795 ret = this->lc->layoutChange(act);
796 if(ret != WMError::SUCCESS)
798 HMI_SEQ_WARNING(req_num,
799 "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
802 ret = this->lc->visibilityChange(act);
804 if(act.visible == VISIBLE)
806 emit_visible(act.role);
807 emit_activated(act.role);
811 emit_invisible(act.role);
812 emit_deactivated(act.role);
815 if (ret != WMError::SUCCESS)
817 HMI_SEQ_WARNING(req_num,
818 "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
821 HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str());
824 this->lc->renderLayers();
826 HMI_SEQ_INFO(req_num, "emit flushDraw");
828 for(const auto &act_flush : actions)
830 if(act_flush.visible == TaskVisible::VISIBLE)
832 this->emit_flushdraw(act_flush.role);
839 void WindowManager::emitScreenUpdated(unsigned req_num)
842 HMI_SEQ_DEBUG(req_num, "emit screen updated");
844 auto actions = g_app_list.getActions(req_num, &found);
847 HMI_SEQ_ERROR(req_num,
848 "Window Manager bug :%s : Action is not set",
849 errorDescription(WMError::NO_ENTRY));
853 // create json object
854 json_object *j = json_object_new_object();
855 json_object *jarray = json_object_new_array();
857 for(const auto& action: actions)
859 if(action.visible != TaskVisible::INVISIBLE)
861 json_object_array_add(jarray, json_object_new_string(action.client->appID().c_str()));
864 json_object_object_add(j, kKeyIds, jarray);
865 HMI_SEQ_INFO(req_num, "Visible app: %s", json_object_get_string(j));
867 int ret = afb_event_push(
868 this->map_afb_event[kListEventName[Event_ScreenUpdated]], j);
871 HMI_DEBUG("afb_event_push failed: %m");
875 void WindowManager::setTimer()
878 if (clock_gettime(CLOCK_BOOTTIME, &ts) != 0) {
879 HMI_ERROR("Could't set time (clock_gettime() returns with error");
883 HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Timer set activate");
884 if (g_timer_ev_src == nullptr)
886 // firsttime set into sd_event
887 int ret = sd_event_add_time(afb_api_get_event_loop(afbBindingV3root), &g_timer_ev_src,
888 CLOCK_BOOTTIME, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL, 1, processTimerHandler, this);
891 HMI_ERROR("Could't set timer");
896 // update timer limitation after second time
897 sd_event_source_set_time(g_timer_ev_src, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL);
898 sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT);
902 void WindowManager::stopTimer()
904 unsigned req_num = g_app_list.currentRequestNumber();
905 HMI_SEQ_DEBUG(req_num, "Timer stop");
906 int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF);
909 HMI_SEQ_ERROR(req_num, "Timer stop failed");
913 void WindowManager::processNextRequest()
916 g_app_list.reqDump();
917 unsigned req_num = g_app_list.currentRequestNumber();
918 if (g_app_list.haveRequest())
920 HMI_SEQ_DEBUG(req_num, "Process next request");
921 WMError rc = checkPolicy(req_num);
922 if (rc != WMError::SUCCESS)
924 HMI_SEQ_ERROR(req_num, errorDescription(rc));
929 HMI_SEQ_DEBUG(req_num, "Nothing Request. Waiting Request");