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 /* this->display->add_global_handler(
187 "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
188 this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
191 this->display->add_global_handler(
192 "ivi_wm", [this](wl_registry *r, uint32_t name, uint32_t v) {
194 std::make_unique<struct compositor::controller>(r, name, v);
196 // Init controller hooks
197 this->controller->chooks = &this->chooks;
199 // This protocol needs the output, so lets just add our mapping here...
200 this->controller->add_proxy_to_id_mapping(
201 this->outputs.front()->proxy.get(),
202 wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
203 this->outputs.front()->proxy.get())));
206 this->controller->create_screen(this->outputs.front()->proxy.get());
208 // Set display to controller
209 this->controller->display = this->display;
212 // First level objects
213 this->display->roundtrip();
214 // Second level objects
215 this->display->roundtrip();
216 // Third level objects
217 this->display->roundtrip(); */
219 return init_layers();
222 /* int WindowManager::dispatch_pending_events()
224 if (this->pop_pending_events())
226 this->display->dispatch_pending();
232 void WindowManager::set_pending_events()
234 this->pending_events.store(true, std::memory_order_release);
237 result<int> WindowManager::api_request_surface(char const *appid, char const *drawing_name)
239 // TODO: application requests by old role,
240 // so convert role old to new
241 const char *role = this->convertRoleOldToNew(drawing_name);
243 // auto lid = this->layers.get_layer_id(string(role));
244 unsigned l_id = this->lc->getNewLayerID(role);
248 * register drawing_name as fallback and make it displayed.
250 // lid = this->layers.get_layer_id(string("fallback"));
251 l_id = this->lc->getNewLayerID("fallback");
252 HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
255 return Err<int>("Drawing name does not match any role, fallback is disabled");
259 // generate surface ID for ivi-shell application
261 // auto rname = this->lookup_id(role);
264 // name does not exist yet, allocate surface id...
265 auto id = int(this->id_alloc.generate_id(role));
266 // this->layers.add_surface(id, *lid);
268 // set the main_surface[_name] here and now
269 // if (!this->layers.main_surface_name.empty() &&
270 // this->layers.main_surface_name == drawing_name)
272 // this->layers.main_surface = id;
273 // HMI_DEBUG("Set main_surface id to %u", id);
276 // add client into the db
277 string appid_str(appid);
278 if(g_app_list.contains(appid_str))
280 // add surface into app
281 auto client = g_app_list.lookUpClient(appid_str);
282 // client.addSurface(id);
286 g_app_list.addClient(appid_str, l_id, id, string(role));
289 // Set role map of (new, old)
290 this->rolenew2old[role] = string(drawing_name);
295 // Check currently registered drawing names if it is already there.
296 return Err<int>("Surface already present");
299 char const *WindowManager::api_request_surface(char const *appid, char const *drawing_name,
304 // TODO: application requests by old role,
305 // so convert role old to new
306 const char *role = this->convertRoleOldToNew(drawing_name);
309 // auto lid = this->layers.get_layer_id(string(role));
310 unsigned lid = this->lc->getNewLayerID(str);
311 unsigned sid = std::stol(ivi_id);
315 //register drawing_name as fallback and make it displayed.
316 // lid = this->layers.get_layer_id(string("fallback"));
317 HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role);
320 return "Drawing name does not match any role, fallback is disabled";
324 auto rname = this->lookup_id(role);
328 return "Surface already present";
331 // register pair drawing_name and ivi_id
332 this->id_alloc.register_name_id(role, sid);
333 // this->layers.add_surface(sid, *lid);
335 // this surface is already created
336 // HMI_DEBUG("surface_id is %u, layer_id is %u", sid, *lid);
338 // this->controller->layers[*lid]->add_surface(sid);
339 // this->layout_commit();
341 // add client into the db
342 string appid_str(appid);
343 g_app_list.addClient(appid_str, lid, sid, string(role));
345 // Set role map of (new, old)
346 this->rolenew2old[role] = string(drawing_name);
352 * This function is substitute of requestSurface
353 * If surface creation is faster than application request of this function,
354 * WM will bind surfaceID with application and role.
355 * If surface creation is slower than application request of thie function,
356 * WM will put Client into pending list.
359 * Application can request with pid but this is temporary solution for now.
360 * This will be removed.
362 bool WindowManager::api_set_role(char const *appid, char const *drawing_name, unsigned pid){
364 string role = drawing_name;
365 unsigned surface = 0;
366 WMError wm_err = WMError::UNKNOWN;
369 // get layer ID which role should be in
370 // auto lid = this->layers.get_layer_id(role);
371 unsigned lid = this->lc->getNewLayerID(role);
374 // lid = this->layers.get_layer_id(string("fallback"));
375 HMI_DEBUG("%s is not registered in layers.json, then fallback as normal app", role.c_str());
378 HMI_ERROR("Drawing name does not match any role, fallback is disabled");
384 // search floating surfaceID from pid if pid is designated.
385 // It is not good that application request with its pid
386 wm_err = g_app_list.popFloatingSurface(pid, &surface);
389 // get floating surface with appid. If WM queries appid from pid,
390 // WM can bind surface and role with appid(not implemented yet)
391 //wm_err = g_app_list.popFloatingSurface(id);
393 if(wm_err != WMError::SUCCESS){
394 HMI_ERROR("No floating surface for app: %s", id.c_str());
395 g_app_list.addFloatingClient(id, lid, role);
396 HMI_NOTICE("%s : Waiting for surface creation", id.c_str());
401 if (g_app_list.contains(id))
403 HMI_INFO("Add role: %s with surface: %d. Client %s has multi surfaces.",
404 role.c_str(), surface, id.c_str());
405 wm_err = g_app_list.appendRole(id, role, surface);
406 if(wm_err != WMError::SUCCESS){
407 HMI_INFO(errorDescription(wm_err));
411 HMI_INFO("Create new client: %s, surface: %d into layer: %d with role: %s",
412 id.c_str(), surface, lid, role.c_str());
413 g_app_list.addClient(id, lid, surface, role);
416 // register pair drawing_name and ivi_id
417 this->id_alloc.register_name_id(role.c_str(), surface);
418 // this->layers.add_surface(surface, *lid);
420 // this surface is already created
421 HMI_DEBUG("surface_id is %u, layer_id is %u", surface, lid);
423 // const auto &o_layer = this->layers.get_layer(*lid);
424 /* auto rect = o_layer.value().rect;
427 rect.w = this->controller->output_size.w + 1 + rect.w;
431 rect.h = this->controller->output_size.h + 1 + rect.h;
434 // this->controller->layers[*lid]->add_surface(surface);
435 this->layout_commit();
440 void WindowManager::api_activate_surface(char const *appid, char const *drawing_name,
441 char const *drawing_area, const reply_func &reply)
445 // TODO: application requests by old role,
446 // so convert role old to new
447 const char *c_role = this->convertRoleOldToNew(drawing_name);
450 string role = c_role;
451 string area = drawing_area;
453 if(!g_app_list.contains(id))
455 reply("app doesn't request 'requestSurface' or 'setRole' yet");
458 auto client = g_app_list.lookUpClient(id);
460 unsigned srfc = client->surfaceID(role);
463 HMI_ERROR("role sould be set with surface");
464 reply("role sould be set with surface");
467 g_app_list.removeFloatingSurface(client->surfaceID());
469 Task task = Task::TASK_ALLOCATE;
470 unsigned req_num = 0;
471 WMError ret = WMError::UNKNOWN;
473 ret = this->setRequest(id, role, area, task, &req_num);
475 if(ret != WMError::SUCCESS)
477 HMI_ERROR(errorDescription(ret));
478 reply("Failed to set request");
483 if (req_num != g_app_list.currentRequestNumber())
485 // Add request, then invoked after the previous task is finished
486 HMI_SEQ_DEBUG(req_num, "request is accepted");
493 ret = this->doTransition(req_num);
495 if (ret != WMError::SUCCESS)
498 HMI_SEQ_ERROR(req_num, errorDescription(ret));
499 g_app_list.removeRequest(req_num);
500 this->processNextRequest();
504 void WindowManager::api_deactivate_surface(char const *appid, char const *drawing_name,
505 const reply_func &reply)
509 // TODO: application requests by old role,
510 // so convert role old to new
511 const char *c_role = this->convertRoleOldToNew(drawing_name);
517 string role = c_role;
518 string area = ""; //drawing_area;
519 Task task = Task::TASK_RELEASE;
520 unsigned req_num = 0;
521 WMError ret = WMError::UNKNOWN;
523 ret = this->setRequest(id, role, area, task, &req_num);
525 if (ret != WMError::SUCCESS)
527 HMI_ERROR(errorDescription(ret));
528 reply("Failed to set request");
533 if (req_num != g_app_list.currentRequestNumber())
535 // Add request, then invoked after the previous task is finished
536 HMI_SEQ_DEBUG(req_num, "request is accepted");
543 ret = this->doTransition(req_num);
545 if (ret != WMError::SUCCESS)
548 HMI_SEQ_ERROR(req_num, errorDescription(ret));
549 g_app_list.removeRequest(req_num);
550 this->processNextRequest();
554 void WindowManager::api_enddraw(char const *appid, char const *drawing_name)
556 // TODO: application requests by old role,
557 // so convert role old to new
558 const char *c_role = this->convertRoleOldToNew(drawing_name);
561 string role = c_role;
562 unsigned current_req = g_app_list.currentRequestNumber();
563 bool result = g_app_list.setEndDrawFinished(current_req, id, role);
567 HMI_ERROR("%s is not in transition state", id.c_str());
571 if (g_app_list.endDrawFullfilled(current_req))
573 // do task for endDraw
575 WMError ret = this->doEndDraw(current_req);
577 if(ret != WMError::SUCCESS)
579 //this->emit_error();
581 // Undo state of PolicyManager
582 this->pmw.undoState();
584 this->emitScreenUpdated(current_req);
585 HMI_SEQ_INFO(current_req, "Finish request status: %s", errorDescription(ret));
587 g_app_list.removeRequest(current_req);
589 this->processNextRequest();
593 HMI_SEQ_INFO(current_req, "Wait other App call endDraw");
598 result<json_object *> WindowManager::api_get_display_info()
600 /* if (!this->display->ok())
602 return Err<json_object *>("Wayland compositor is not available");
606 /* size o_size = this->controller->output_size;
607 size p_size = this->controller->physical_size; */
609 json_object *object = json_object_new_object();
610 /* json_object_object_add(object, kKeyWidthPixel, json_object_new_int(o_size.w));
611 json_object_object_add(object, kKeyHeightPixel, json_object_new_int(o_size.h));
612 json_object_object_add(object, kKeyWidthMm, json_object_new_int(p_size.w));
613 json_object_object_add(object, kKeyHeightMm, json_object_new_int(p_size.h));
614 json_object_object_add(object, kKeyScale, json_object_new_double(this->controller->scale));
616 return Ok<json_object *>(object);
619 result<json_object *> WindowManager::api_get_area_info(char const *drawing_name)
623 // TODO: application requests by old role,
624 // so convert role old to new
625 const char *role = this->convertRoleOldToNew(drawing_name);
627 // Check drawing name, surface/layer id
628 auto const &surface_id = this->lookup_id(role);
631 return Err<json_object *>("Surface does not exist");
634 /* if (!this->controller->surface_exists(*surface_id))
636 return Err<json_object *>("Surface does not exist in controller!");
639 /* // auto layer_id = this->layers.get_layer_id(*surface_id);
642 return Err<json_object *>("Surface is not on any layer!");
645 // Set area rectangle
646 rect area_info = this->area_info[*surface_id];
647 json_object *object = json_object_new_object();
648 json_object_object_add(object, kKeyX, json_object_new_int(area_info.x));
649 json_object_object_add(object, kKeyY, json_object_new_int(area_info.y));
650 json_object_object_add(object, kKeyWidth, json_object_new_int(area_info.w));
651 json_object_object_add(object, kKeyHeight, json_object_new_int(area_info.h));
653 return Ok<json_object *>(object);
656 void WindowManager::api_ping() { /* this->dispatch_pending_events(); */ }
658 void WindowManager::send_event(char const *evname, char const *label)
660 HMI_DEBUG("%s: %s(%s)", __func__, evname, label);
662 json_object *j = json_object_new_object();
663 json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
665 int ret = afb_event_push(this->map_afb_event[evname], j);
668 HMI_DEBUG("afb_event_push failed: %m");
672 void WindowManager::send_event(char const *evname, char const *label, char const *area,
673 int x, int y, int w, int h)
675 HMI_DEBUG("%s: %s(%s, %s) x:%d y:%d w:%d h:%d",
676 __func__, evname, label, area, x, y, w, h);
678 json_object *j_rect = json_object_new_object();
679 json_object_object_add(j_rect, kKeyX, json_object_new_int(x));
680 json_object_object_add(j_rect, kKeyY, json_object_new_int(y));
681 json_object_object_add(j_rect, kKeyWidth, json_object_new_int(w));
682 json_object_object_add(j_rect, kKeyHeight, json_object_new_int(h));
684 json_object *j = json_object_new_object();
685 json_object_object_add(j, kKeyDrawingName, json_object_new_string(label));
686 json_object_object_add(j, kKeyDrawingArea, json_object_new_string(area));
687 json_object_object_add(j, kKeyDrawingRect, j_rect);
689 int ret = afb_event_push(this->map_afb_event[evname], j);
692 HMI_DEBUG("afb_event_push failed: %m");
699 void WindowManager::surface_created(uint32_t surface_id)
701 /* this->controller->get_surface_properties(surface_id, IVI_WM_PARAM_SIZE);
703 auto layer_id = this->layers.get_layer_id(surface_id);
706 HMI_DEBUG("Newly created surfce %d is not associated with any layer!",
711 HMI_DEBUG("surface_id is %u, layer_id is %u", surface_id, *layer_id);
713 this->controller->layers[*layer_id]->add_surface(surface_id);
714 this->layout_commit(); */
717 void WindowManager::surface_removed(uint32_t surface_id)
719 HMI_DEBUG("Delete surface_id %u", surface_id);
720 this->id_alloc.remove_id(surface_id);
721 // this->layers.remove_surface(surface_id);
722 g_app_list.removeSurface(surface_id);
725 void WindowManager::surface_properties(unsigned surface_id, unsigned pid)
727 HMI_DEBUG("get surface properties");
729 // search pid from surfaceID
730 /*json_object *response;
731 afb_service_call_sync("afm-main", "runners", nullptr, &response);
733 // retrieve appid from pid from application manager
735 if(response == nullptr)
737 HMI_ERROR("No runners");
741 // check appid then add it to the client
742 HMI_INFO("Runners:%s", json_object_get_string(response));
743 int size = json_object_array_length(response);
744 for(int i = 0; i < size; i++)
746 json_object *j = json_object_array_get_idx(response, i);
747 const char* id = jh::getStringFromJson(j, "id");
748 int runid = jh::getIntFromJson(j, "runid");
749 if(id && (runid > 0))
759 json_object_put(response);
761 g_app_list.addFloatingSurface(appid, surface_id, pid);*/
764 void WindowManager::removeClient(const string &appid)
766 HMI_DEBUG("Remove clinet %s from list", appid.c_str());
767 g_app_list.removeClient(appid);
770 void WindowManager::exceptionProcessForTransition()
772 unsigned req_num = g_app_list.currentRequestNumber();
773 HMI_SEQ_NOTICE(req_num, "Process exception handling for request. Remove current request %d", req_num);
774 g_app_list.removeRequest(req_num);
775 HMI_SEQ_NOTICE(g_app_list.currentRequestNumber(), "Process next request if exists");
776 this->processNextRequest();
779 void WindowManager::timerHandler()
781 unsigned req_num = g_app_list.currentRequestNumber();
782 HMI_SEQ_DEBUG(req_num, "Timer expired remove Request");
783 g_app_list.reqDump();
784 g_app_list.removeRequest(req_num);
785 this->processNextRequest();
788 void WindowManager::startTransitionWrapper(vector<WMAction> &actions)
791 unsigned req_num = g_app_list.currentRequestNumber();
795 if (g_app_list.haveRequest())
797 HMI_SEQ_DEBUG(req_num, "There is no WMAction for this request");
798 goto proc_remove_request;
802 HMI_SEQ_DEBUG(req_num, "There is no request");
807 for (auto &act : actions)
812 auto const &surface_id = this->lookup_id(act.role.c_str());
813 string appid = g_app_list.getAppID(*surface_id, act.role, &found);
816 if (TaskVisible::INVISIBLE == act.visible)
818 // App is killed, so do not set this action
823 HMI_SEQ_ERROR(req_num, "appid which is visible is not found");
831 ret = g_app_list.setAction(req_num, act);
832 if (ret != WMError::SUCCESS)
834 HMI_SEQ_ERROR(req_num, "Setting action is failed");
839 HMI_SEQ_DEBUG(req_num, "Start transition.");
840 ret = this->startTransition(req_num);
841 if (ret != WMError::SUCCESS)
843 if (ret == WMError::NO_LAYOUT_CHANGE)
845 goto proc_remove_request;
849 HMI_SEQ_ERROR(req_num, "Transition state is failed");
858 HMI_SEQ_ERROR(req_num, errorDescription(ret));
859 this->pmw.undoState();
862 g_app_list.removeRequest(req_num);
863 this->processNextRequest();
866 void WindowManager::processError(WMError error)
868 unsigned req_num = g_app_list.currentRequestNumber();
871 HMI_SEQ_ERROR(req_num, errorDescription(error));
872 g_app_list.removeRequest(req_num);
873 this->processNextRequest();
877 ******* Private Functions *******
880 optional<int> WindowManager::lookup_id(char const *name)
882 return this->id_alloc.lookup(string(name));
884 optional<string> WindowManager::lookup_name(int id)
886 return this->id_alloc.lookup(id);
892 int WindowManager::init_layers()
894 /* if (!this->controller)
896 HMI_ERROR("ivi_controller global not available");
900 if (this->outputs.empty())
902 HMI_ERROR("no output was set up!");
906 auto &c = this->controller;
908 auto &o = this->outputs.front();
909 auto &s = c->screens.begin()->second;
910 auto &layers = c->layers;
912 // Write output dimensions to ivi controller...
913 c->output_size = compositor::size{uint32_t(o->width), uint32_t(o->height)};
914 c->physical_size = compositor::size{uint32_t(o->physical_width),
915 uint32_t(o->physical_height)};
918 HMI_DEBUG("SCALING: screen (%dx%d), physical (%dx%d)",
919 o->width, o->height, o->physical_width, o->physical_height);
921 // this->layers.loadAreaDb();
923 const compositor::rect css_bg = this->layers.getAreaSize("fullscreen");
924 rectangle dp_bg(o->width, o->height);
926 dp_bg.set_aspect(static_cast<double>(css_bg.w) / css_bg.h);
927 dp_bg.fit(o->width, o->height);
928 dp_bg.center(o->width, o->height);
929 HMI_DEBUG("SCALING: CSS BG(%dx%d) -> DDP %dx%d,(%dx%d)",
930 css_bg.w, css_bg.h, dp_bg.left(), dp_bg.top(), dp_bg.width(), dp_bg.height());
938 // Quick and dirty setup of layers
939 for (auto const &i : this->layers.mapping)
941 c->layer_create(i.second.layer_id, dp_bg.width(), dp_bg.height());
942 auto &l = layers[i.second.layer_id];
943 l->set_destination_rectangle(dp_bg.left(), dp_bg.top(), dp_bg.width(), dp_bg.height());
944 l->set_visibility(1);
945 HMI_DEBUG("Setting up layer %s (%d) for surface role match \"%s\"",
946 i.second.name.c_str(), i.second.layer_id, i.second.role.c_str());
949 // Add layers to screen
950 s->set_render_order(this->layers.layers);
952 this->layout_commit();
954 c->scale = static_cast<double>(dp_bg.height()) / css_bg.h;
955 this->layers.setupArea(c->scale);
960 void WindowManager::surface_set_layout(int surface_id, const string& area)
962 /* if (!this->controller->surface_exists(surface_id))
964 HMI_ERROR("Surface %d does not exist", surface_id);
968 auto o_layer_id = this->layers.get_layer_id(surface_id);
972 HMI_ERROR("Surface %d is not associated with any layer!", surface_id);
976 uint32_t layer_id = *o_layer_id;
978 auto const &layer = this->layers.get_layer(layer_id);
979 auto rect = this->layers.getAreaSize(area);
980 HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "%s : x:%d y:%d w:%d h:%d", area.c_str(),
981 rect.x, rect.y, rect.w, rect.h);
982 auto &s = this->controller->surfaces[surface_id];
989 HMI_DEBUG("surface_set_layout for surface %u on layer %u", surface_id,
992 // set destination to the display rectangle
993 s->set_destination_rectangle(x, y, w, h);
995 // update area information
996 this->area_info[surface_id].x = x;
997 this->area_info[surface_id].y = y;
998 this->area_info[surface_id].w = w;
999 this->area_info[surface_id].h = h;
1001 HMI_DEBUG("Surface %u now on layer %u with rect { %d, %d, %d, %d }",
1002 surface_id, layer_id, x, y, w, h); */
1005 void WindowManager::layout_commit()
1007 /* this->controller->commit_changes();
1008 this->display->flush(); */
1011 void WindowManager::emit_activated(char const *label)
1013 this->send_event(kListEventName[Event_Active], label);
1016 void WindowManager::emit_deactivated(char const *label)
1018 this->send_event(kListEventName[Event_Inactive], label);
1021 void WindowManager::emit_syncdraw(char const *label, char const *area, int x, int y, int w, int h)
1023 this->send_event(kListEventName[Event_SyncDraw], label, area, x, y, w, h);
1026 void WindowManager::emit_syncdraw(const string &role, const string &area)
1028 /* rect rect = this->layers.getAreaSize(area);
1029 this->send_event(kListEventName[Event_SyncDraw],
1030 role.c_str(), area.c_str(), rect.x, rect.y, rect.w, rect.h); */
1033 void WindowManager::emit_flushdraw(char const *label)
1035 this->send_event(kListEventName[Event_FlushDraw], label);
1038 void WindowManager::emit_visible(char const *label, bool is_visible)
1040 this->send_event(is_visible ? kListEventName[Event_Visible] : kListEventName[Event_Invisible], label);
1043 void WindowManager::emit_invisible(char const *label)
1045 return emit_visible(label, false);
1048 void WindowManager::emit_visible(char const *label) { return emit_visible(label, true); }
1050 void WindowManager::activate(int id)
1052 /* auto ip = this->controller->sprops.find(id);
1053 if (ip != this->controller->sprops.end())
1055 this->controller->surfaces[id]->set_visibility(1);
1058 this->lookup_name(id).value_or("unknown-name").c_str();
1060 /* // FOR CES DEMO >>>
1061 if ((0 == strcmp(label, "radio")) ||
1062 (0 == strcmp(label, "music")) ||
1063 (0 == strcmp(label, "video")) ||
1064 (0 == strcmp(label, "map")))
1066 for (auto i = surface_bg.begin(); i != surface_bg.end(); ++i)
1071 this->surface_bg.erase(i);
1073 // Remove from BG layer (999)
1074 HMI_DEBUG("Remove %s(%d) from BG layer", label, id);
1075 this->controller->layers[999]->remove_surface(id);
1077 // Add to FG layer (1001)
1078 HMI_DEBUG("Add %s(%d) to FG layer", label, id);
1079 this->controller->layers[1001]->add_surface(id);
1081 for (int j : this->surface_bg)
1083 HMI_DEBUG("Stored id:%d", j);
1091 this->layout_commit(); */
1093 // TODO: application requests by old role,
1094 // so convert role new to old for emitting event
1095 const char* old_role = this->rolenew2old[label].c_str();
1097 this->emit_visible(old_role);
1098 this->emit_activated(old_role);
1102 void WindowManager::deactivate(int id)
1104 /* auto ip = this->controller->sprops.find(id);
1105 if (ip != this->controller->sprops.end())
1108 this->lookup_name(id).value_or("unknown-name").c_str();
1110 /*// FOR CES DEMO >>>
1111 if ((0 == strcmp(label, "radio")) ||
1112 (0 == strcmp(label, "music")) ||
1113 (0 == strcmp(label, "video")) ||
1114 (0 == strcmp(label, "map")))
1118 this->surface_bg.push_back(id);
1120 // Remove from FG layer (1001)
1121 HMI_DEBUG("Remove %s(%d) from FG layer", label, id);
1122 this->controller->layers[1001]->remove_surface(id);
1124 // Add to BG layer (999)
1125 HMI_DEBUG("Add %s(%d) to BG layer", label, id);
1126 this->controller->layers[999]->add_surface(id);
1128 for (int j : surface_bg)
1130 HMI_DEBUG("Stored id:%d", j);
1135 this->controller->surfaces[id]->set_visibility(0);
1139 this->layout_commit(); */
1141 // TODO: application requests by old role,
1142 // so convert role new to old for emitting event
1143 const char* old_role = this->rolenew2old[label].c_str();
1145 this->emit_deactivated(old_role);
1146 this->emit_invisible(old_role);
1150 WMError WindowManager::setRequest(const string& appid, const string &role, const string &area,
1151 Task task, unsigned* req_num)
1153 if (!g_app_list.contains(appid))
1155 return WMError::NOT_REGISTERED;
1158 auto client = g_app_list.lookUpClient(appid);
1163 unsigned current = g_app_list.currentRequestNumber();
1164 unsigned requested_num = g_app_list.getRequestNumber(appid);
1165 if (requested_num != 0)
1167 HMI_SEQ_INFO(requested_num,
1168 "%s %s %s request is already queued", appid.c_str(), role.c_str(), area.c_str());
1169 return REQ_REJECTED;
1172 WMRequest req = WMRequest(appid, role, area, task);
1173 unsigned new_req = g_app_list.addRequest(req);
1175 g_app_list.reqDump();
1177 HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", appid.c_str(), role.c_str(), area.c_str());
1179 return WMError::SUCCESS;
1182 WMError WindowManager::doTransition(unsigned req_num)
1184 HMI_SEQ_DEBUG(req_num, "check policy");
1185 WMError ret = this->checkPolicy(req_num);
1189 WMError WindowManager::checkPolicy(unsigned req_num)
1194 // get current trigger
1196 WMError ret = WMError::LAYOUT_CHANGE_FAIL;
1197 auto trigger = g_app_list.getRequest(req_num, &found);
1200 ret = WMError::NO_ENTRY;
1203 string req_area = trigger.area;
1205 if (trigger.task == Task::TASK_ALLOCATE)
1207 const char *msg = this->check_surface_exist(trigger.role.c_str());
1211 HMI_SEQ_ERROR(req_num, msg);
1216 // Input event data to PolicyManager
1217 if (0 > this->pmw.setInputEventData(trigger.task, trigger.role, trigger.area))
1219 HMI_SEQ_ERROR(req_num, "Failed to set input event data to PolicyManager");
1223 // Execute state transition of PolicyManager
1224 if (0 > this->pmw.executeStateTransition())
1226 HMI_SEQ_ERROR(req_num, "Failed to execute state transition of PolicyManager");
1230 ret = WMError::SUCCESS;
1232 g_app_list.reqDump();
1237 WMError WindowManager::startTransition(unsigned req_num)
1239 bool sync_draw_happen = false;
1241 WMError ret = WMError::SUCCESS;
1242 auto actions = g_app_list.getActions(req_num, &found);
1245 ret = WMError::NO_ENTRY;
1246 HMI_SEQ_ERROR(req_num,
1247 "Window Manager bug :%s : Action is not set", errorDescription(ret));
1251 for (const auto &action : actions)
1253 if (action.visible == TaskVisible::VISIBLE)
1255 sync_draw_happen = true;
1257 // TODO: application requests by old role,
1258 // so convert role new to old for emitting event
1259 string old_role = this->rolenew2old[action.role];
1261 this->emit_syncdraw(old_role, action.area);
1262 /* TODO: emit event for app not subscriber
1263 if(g_app_list.contains(y.appid))
1264 g_app_list.lookUpClient(y.appid)->emit_syncdraw(y.role, y.area); */
1268 if (sync_draw_happen)
1274 // deactivate only, no syncDraw
1275 // Make it deactivate here
1276 for (const auto &x : actions)
1278 if (g_app_list.contains(x.appid))
1280 auto client = g_app_list.lookUpClient(x.appid);
1281 this->deactivate(client->surfaceID(x.role));
1284 ret = WMError::NO_LAYOUT_CHANGE;
1289 WMError WindowManager::doEndDraw(unsigned req_num)
1293 auto actions = g_app_list.getActions(req_num, &found);
1294 WMError ret = WMError::SUCCESS;
1297 ret = WMError::NO_ENTRY;
1301 HMI_SEQ_INFO(req_num, "do endDraw");
1303 // layout change and make it visible
1304 for (const auto &act : actions)
1306 if(act.visible != TaskVisible::NO_CHANGE)
1309 if(!g_app_list.contains(act.appid)){
1310 ret = WMError::NOT_REGISTERED;
1312 ret = this->layoutChange(act);
1313 if(ret != WMError::SUCCESS)
1315 HMI_SEQ_WARNING(req_num,
1316 "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1319 ret = this->visibilityChange(act);
1320 if (ret != WMError::SUCCESS)
1322 HMI_SEQ_WARNING(req_num,
1323 "Failed to manipulate surfaces while state change : %s", errorDescription(ret));
1326 HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str());
1327 //this->lc_enddraw(act.role.c_str());
1330 this->layout_commit();
1332 HMI_SEQ_INFO(req_num, "emit flushDraw");
1334 for(const auto &act_flush : actions)
1336 if(act_flush.visible == TaskVisible::VISIBLE)
1338 // TODO: application requests by old role,
1339 // so convert role new to old for emitting event
1340 string old_role = this->rolenew2old[act_flush.role];
1342 this->emit_flushdraw(old_role.c_str());
1349 WMError WindowManager::layoutChange(const WMAction &action)
1351 if (action.visible == TaskVisible::INVISIBLE)
1353 // Visibility is not change -> no redraw is required
1354 return WMError::SUCCESS;
1356 auto client = g_app_list.lookUpClient(action.appid);
1357 unsigned surface = client->surfaceID(action.role);
1360 HMI_SEQ_ERROR(g_app_list.currentRequestNumber(),
1361 "client doesn't have surface with role(%s)", action.role.c_str());
1362 return WMError::NOT_REGISTERED;
1365 WMError ret = this->setSurfaceSize(surface, action.area);
1369 WMError WindowManager::visibilityChange(const WMAction &action)
1371 HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Change visibility");
1372 if(!g_app_list.contains(action.appid)){
1373 return WMError::NOT_REGISTERED;
1375 auto client = g_app_list.lookUpClient(action.appid);
1376 unsigned surface = client->surfaceID(action.role);
1379 HMI_SEQ_ERROR(g_app_list.currentRequestNumber(),
1380 "client doesn't have surface with role(%s)", action.role.c_str());
1381 return WMError::NOT_REGISTERED;
1384 if (action.visible != TaskVisible::INVISIBLE)
1386 this->activate(surface); // Layout Manager task
1390 this->deactivate(surface); // Layout Manager task
1392 return WMError::SUCCESS;
1395 WMError WindowManager::setSurfaceSize(unsigned surface, const string &area)
1397 this->surface_set_layout(surface, area);
1399 return WMError::SUCCESS;
1402 void WindowManager::emitScreenUpdated(unsigned req_num)
1405 HMI_SEQ_DEBUG(req_num, "emit screen updated");
1407 auto actions = g_app_list.getActions(req_num, &found);
1409 // create json object
1410 json_object *j = json_object_new_object();
1411 json_object *jarray = json_object_new_array();
1413 for(const auto& action: actions)
1415 if(action.visible != TaskVisible::INVISIBLE)
1417 json_object_array_add(jarray, json_object_new_string(action.appid.c_str()));
1420 json_object_object_add(j, kKeyIds, jarray);
1421 HMI_SEQ_INFO(req_num, "Visible app: %s", json_object_get_string(j));
1423 int ret = afb_event_push(
1424 this->map_afb_event[kListEventName[Event_ScreenUpdated]], j);
1427 HMI_DEBUG("afb_event_push failed: %m");
1431 void WindowManager::setTimer()
1434 if (clock_gettime(CLOCK_BOOTTIME, &ts) != 0) {
1435 HMI_ERROR("Could't set time (clock_gettime() returns with error");
1439 HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Timer set activate");
1440 if (g_timer_ev_src == nullptr)
1442 // firsttime set into sd_event
1443 int ret = sd_event_add_time(afb_daemon_get_event_loop(), &g_timer_ev_src,
1444 CLOCK_BOOTTIME, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL, 1, processTimerHandler, this);
1447 HMI_ERROR("Could't set timer");
1452 // update timer limitation after second time
1453 sd_event_source_set_time(g_timer_ev_src, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL);
1454 sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT);
1458 void WindowManager::stopTimer()
1460 unsigned req_num = g_app_list.currentRequestNumber();
1461 HMI_SEQ_DEBUG(req_num, "Timer stop");
1462 int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF);
1465 HMI_SEQ_ERROR(req_num, "Timer stop failed");
1469 void WindowManager::processNextRequest()
1472 g_app_list.reqDump();
1473 unsigned req_num = g_app_list.currentRequestNumber();
1474 if (g_app_list.haveRequest())
1476 HMI_SEQ_DEBUG(req_num, "Process next request");
1477 WMError rc = doTransition(req_num);
1478 if (rc != WMError::SUCCESS)
1480 HMI_SEQ_ERROR(req_num, errorDescription(rc));
1485 HMI_SEQ_DEBUG(req_num, "Nothing Request. Waiting Request");
1489 const char* WindowManager::convertRoleOldToNew(char const *old_role)
1491 const char *new_role = nullptr;
1493 for (auto const &on : this->roleold2new)
1495 std::regex regex = std::regex(on.first);
1496 if (std::regex_match(old_role, regex))
1498 // role is old. So convert to new.
1499 new_role = on.second.c_str();
1504 if (nullptr == new_role)
1506 // role is new or fallback.
1507 new_role = old_role;
1510 HMI_DEBUG("old:%s -> new:%s", old_role, new_role);
1515 int WindowManager::loadOldRoleDb()
1517 // Get afm application installed dir
1518 char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1519 HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
1522 if (!afm_app_install_dir)
1524 HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
1528 file_name = string(afm_app_install_dir) + string("/etc/old_roles.db");
1532 json_object* json_obj;
1533 int ret = jh::inputJsonFilie(file_name.c_str(), &json_obj);
1536 HMI_ERROR("Could not open old_role.db, so use default old_role information");
1537 json_obj = json_tokener_parse(kDefaultOldRoleDb);
1539 HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
1542 json_object* json_cfg;
1543 if (!json_object_object_get_ex(json_obj, "old_roles", &json_cfg))
1545 HMI_ERROR("Parse Error!!");
1549 int len = json_object_array_length(json_cfg);
1550 HMI_DEBUG("json_cfg len:%d", len);
1551 HMI_DEBUG("json_cfg dump:%s", json_object_get_string(json_cfg));
1553 for (int i=0; i<len; i++)
1555 json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
1557 const char* old_role = jh::getStringFromJson(json_tmp, "name");
1558 if (nullptr == old_role)
1560 HMI_ERROR("Parse Error!!");
1564 const char* new_role = jh::getStringFromJson(json_tmp, "new");
1565 if (nullptr == new_role)
1567 HMI_ERROR("Parse Error!!");
1571 this->roleold2new[old_role] = string(new_role);
1575 for(auto itr = this->roleold2new.begin();
1576 itr != this->roleold2new.end(); ++itr)
1578 HMI_DEBUG(">>> role old:%s new:%s",
1579 itr->first.c_str(), itr->second.c_str());
1582 // Release json_object
1583 json_object_put(json_obj);
1588 const char *WindowManager::check_surface_exist(const char *drawing_name)
1590 auto const &surface_id = this->lookup_id(drawing_name);
1593 return "Surface does not exist";
1596 /* if (!this->controller->surface_exists(*surface_id))
1598 return "Surface does not exist in controller!";
1601 /* auto layer_id = this->layers.get_layer_id(*surface_id);
1605 return "Surface is not on any layer!";
1608 HMI_DEBUG("surface %d is detected", *surface_id);
1612 const char* WindowManager::kDefaultOldRoleDb = "{ \
1615 \"name\": \"HomeScreen\", \
1616 \"new\": \"homescreen\" \
1619 \"name\": \"Music\", \
1620 \"new\": \"music\" \
1623 \"name\": \"MediaPlayer\", \
1624 \"new\": \"music\" \
1627 \"name\": \"Video\", \
1628 \"new\": \"video\" \
1631 \"name\": \"VideoPlayer\", \
1632 \"new\": \"video\" \
1635 \"name\": \"WebBrowser\", \
1636 \"new\": \"browser\" \
1639 \"name\": \"Radio\", \
1640 \"new\": \"radio\" \
1643 \"name\": \"Phone\", \
1644 \"new\": \"phone\" \
1647 \"name\": \"Navigation\", \
1651 \"name\": \"HVAC\", \
1655 \"name\": \"Settings\", \
1656 \"new\": \"settings\" \
1659 \"name\": \"Dashboard\", \
1660 \"new\": \"dashboard\" \
1663 \"name\": \"POI\", \
1667 \"name\": \"Mixer\", \
1668 \"new\": \"mixer\" \
1671 \"name\": \"Restriction\", \
1672 \"new\": \"restriction\" \
1675 \"name\": \"^OnScreen.*\", \
1676 \"new\": \"on_screen\" \
1684 void controller_hooks::surface_created(uint32_t surface_id)
1686 this->wmgr->surface_created(surface_id);
1689 void controller_hooks::surface_removed(uint32_t surface_id)
1691 this->wmgr->surface_removed(surface_id);
1694 void controller_hooks::surface_visibility(uint32_t /*surface_id*/,
1697 void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/,
1703 void controller_hooks::surface_properties(uint32_t surface_id, uint32_t pid)
1705 this->wmgr->surface_properties(surface_id, pid);