19a6a0b487a278300d33d54891541be75ba04f22
[apps/agl-service-windowmanager.git] / src / policy_manager / policy_manager.cpp
1 /*
2  * Copyright (c) 2018 TOYOTA MOTOR CORPORATION
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17
18 #include <fstream>
19 #include <sstream>
20 #include <istream>
21 #include <thread>
22 #include <map>
23 #include <queue>
24 #include <systemd/sd-event.h>
25 #include <json-c/json.h>
26 #include "policy_manager.hpp"
27 #include "hmi-debug.h"
28
29 namespace stm {
30 extern "C" {
31 #include "dummy_stm.h"
32 }
33 } // namespace stm
34
35
36 namespace pm {
37 typedef struct AreaState {
38     std::string name;
39     std::string category;
40     std::string role;
41 } AreaState;
42
43 typedef std::vector<AreaState> AreaList;
44 typedef struct LayoutState {
45     std::string name;
46     std::map<std::string, int> category_num;
47     AreaList area_list;
48     std::map<std::string, std::vector<std::string>> role_history;
49 } LayoutState;
50
51 typedef struct LayerState {
52     std::string name;
53     LayoutState layout_state;
54     int changed;
55 } LayerState;
56
57 typedef struct CarElement {
58     std::string state;
59     int changed;
60 } CarElement;
61
62 typedef struct EventInfo {
63     int event;
64     std::string role;
65     uint64_t delay;
66 } EventInfo;
67
68 struct sd_event* event_loop;
69 std::map<int, struct sd_event_source*> event_source_list;
70 std::map<int, std::string> g_req_role_list;
71 PolicyManager::CallbackTable callback;
72 std::queue<EventInfo> g_event_info_queue;
73
74 std::unordered_map<std::string, CarElement> g_prv_car_elements;
75 std::unordered_map<std::string, CarElement> g_crr_car_elements;
76
77 std::unordered_map<std::string, LayerState> g_prv_layers;
78 std::unordered_map<std::string, LayerState> g_crr_layers;
79
80 std::unordered_map<std::string, LayerState> g_prv_layers_car_stop;
81
82 std::unordered_map<std::string, LayoutState> g_default_layouts;
83 }  // namespace pm
84
85
86 PolicyManager::PolicyManager() :
87   eventname2no_(),
88   categoryname2no_(),
89   areaname2no_(),
90   role2category_(),
91   category2role_(),
92   role2defaultarea_()
93 {
94     HMI_DEBUG("wm:pm", "Call");
95 }
96
97 int PolicyManager::initialize() {
98     HMI_DEBUG("wm:pm", "Call");
99
100     int ret = 0;
101
102     // Create convert map
103     for (int i = stm::gStmEventNoMin; i <= stm::gStmEventNoMax; i++) {
104         HMI_DEBUG("wm:pm", "event name:%s no:%d", stm::gStmEventName[i], stm::gStmEventNo[i]);
105         this->eventname2no_[stm::gStmEventName[i]] = stm::gStmEventNo[i];
106     }
107
108     for (int i = stm::gStmCategoryNoMin; i <= stm::gStmCategoryNoMax; i++) {
109         HMI_DEBUG("wm:pm", "category name:%s no:%d", stm::gStmCategoryName[i], stm::gStmCategoryNo[i]);
110         this->categoryname2no_[stm::gStmCategoryName[i]] = stm::gStmCategoryNo[i];
111     }
112
113     for (int i = stm::gStmAreaNoMin; i <= stm::gStmAreaNoMax; i++) {
114         HMI_DEBUG("wm:pm", "area name:%s no:%d", stm::gStmAreaName[i], stm::gStmAreaNo[i]);
115         this->areaname2no_[stm::gStmAreaName[i]] = stm::gStmAreaNo[i];
116     }
117
118     // Load role.db
119     ret = this->loadRoleDb();
120     if (0 > ret) {
121         HMI_ERROR("wm:pm", "Load role.db Error!!");
122         return ret;
123     }
124
125     // Load layout.db
126     ret = this->loadLayoutDb();
127     if (0 > ret) {
128         HMI_ERROR("wm:pm", "Load layout.db Error!!");
129         return ret;
130     }
131
132     // Initialize state which is managed by PolicyManager
133     this->initializeLocalState();
134
135     // Initialize StateTransitioner
136     stm::stmInitialize();
137
138     // Initialize sd_event loop
139     ret = this->initializeSdEventLoop();
140     if (0 > ret) {
141         HMI_ERROR("wm:pm", "Failed to initializeSdEventLoop!!");
142         return ret;
143     }
144
145     return ret;
146 }
147
148 static void initializeLocalCarElementState() {
149     pm::CarElement init_car_ele;
150     init_car_ele.state   = "none";
151     init_car_ele.changed = 0;
152
153     for (int i = stm::gStmCarElementNoMin; i <= stm::gStmCarElementNoMax; i++) {
154         const char* car_ele_name = stm::gStmCarElementName[i];
155         pm::g_crr_car_elements[car_ele_name] = init_car_ele;
156     }
157
158     pm::g_prv_car_elements = pm::g_crr_car_elements;
159 }
160
161 static void initializeLocalLayerState() {
162     pm::AreaState init_area;
163     pm::LayoutState init_layout;
164     init_area.name     = "none";
165     init_area.category = "none";
166     init_area.role     = "none";
167     init_layout.name   = "none";
168     init_layout.area_list.push_back(init_area);
169
170     for (int i = stm::gStmLayerNoMin; i <= stm::gStmLayerNoMax; i++) {
171         const char* layer_name = stm::gStmLayerName[i];
172         pm::g_crr_layers[layer_name].name         = layer_name;
173         pm::g_crr_layers[layer_name].layout_state = init_layout;
174         pm::g_crr_layers[layer_name].changed      = 0;
175     }
176
177     pm::g_prv_layers = pm::g_crr_layers;
178 }
179
180 void PolicyManager::initializeLocalState() {
181     initializeLocalCarElementState();
182     initializeLocalLayerState();
183 }
184
185 int PolicyManager::initializeSdEventLoop() {
186     // Get default event loop object
187     int ret = sd_event_new(&(pm::event_loop));
188     if (0 > ret) {
189         HMI_ERROR("wm:pm", "Faild to sd_event_default: errno:%d", ret);
190         return -1;
191     }
192
193     // Create thread for sd_event and detach
194     std::thread sd_event_loop([this]() {
195         while (1) {
196             sd_event_run(pm::event_loop, 1000);
197         }
198     });
199     sd_event_loop.detach();
200
201     return 0;
202 }
203
204 static void addStateToJson(
205   const char* key, int is_changed, std::string state, json_object** json_out) {
206     if ((nullptr == key) || (nullptr == json_out)) {
207         HMI_ERROR("wm:pm", "Argument is nullptr!!!");
208         return;
209     }
210
211     json_object* json_obj = json_object_new_object();
212     json_object_object_add(json_obj, "is_changed", json_object_new_boolean(is_changed));
213     if (is_changed) {
214         HMI_DEBUG("wm:pm", "%s: state changed (%s)", key, state.c_str());
215         json_object_object_add(json_obj, "state", json_object_new_string(state.c_str()));
216     }
217     json_object_object_add(*json_out, key, json_obj);
218 }
219
220 static void addStateToJson(const char* layer_name, unsigned int changed,
221                            pm::AreaList area_list, json_object** json_out) {
222     if ((nullptr == layer_name) || (1 < changed) || (nullptr == json_out)) {
223         HMI_ERROR("wm:pm", "Invalid argument!!!");
224         return;
225     }
226
227     json_object* json_areas = json_object_new_array();
228     json_object* json_tmp;
229     for (pm::AreaState as : area_list) {
230         json_tmp = json_object_new_object();
231         json_object_object_add(json_tmp, "name", json_object_new_string(as.name.c_str()));
232         json_object_object_add(json_tmp, "role", json_object_new_string(as.role.c_str()));
233         json_object_array_add(json_areas, json_tmp);
234     }
235
236     json_object_object_add(*json_out, "name", json_object_new_string(layer_name));
237     json_object_object_add(*json_out, "changed", json_object_new_boolean(changed));
238     json_object_object_add(*json_out, "areas", json_areas);
239 }
240
241 static void updateLocalCarElementState(stm::stm_state_t crr_state) {
242     int car_state_no;
243     std::string car_state;
244     bool changed;
245
246     // Store previous layers
247     pm::g_prv_car_elements = pm::g_crr_car_elements;
248
249     // Update car elements
250     HMI_DEBUG("wm:pm", ">>> CAR ELEMENT");
251     for (int car_ele_no = stm::gStmCarElementNoMin;
252          car_ele_no <= stm::gStmCarElementNoMax; car_ele_no++) {
253         const char* car_ele_name = stm::gStmCarElementName[car_ele_no];
254
255         car_state_no = crr_state.car_element[car_ele_no].state;
256         car_state = stm::gStmCarStateNameList[car_ele_no][car_state_no];
257         changed = crr_state.car_element[car_ele_no].is_changed;
258
259         pm::g_crr_car_elements[car_ele_name].state = car_state;
260         pm::g_crr_car_elements[car_ele_name].changed = changed;
261
262         HMI_DEBUG("wm:pm", ">>> >>> NAME: %s", car_ele_name);
263         HMI_DEBUG("wm:pm", ">>> >>> >>> STATE:%s", car_state.c_str());
264         HMI_DEBUG("wm:pm", ">>> >>> >>> CHANGED:%d", changed);
265     }
266 }
267
268 static void updateLocalLayerState(int event_data, stm::stm_state_t crr_state) {
269     int event_no, category_no, area_no;
270
271     event_no    = (event_data & STM_MSK_EVT_NO) - 1;
272     category_no = ((event_data & STM_MSK_CTG_NO) >> 8) - 1;
273     area_no     = ((event_data & STM_MSK_ARA_NO) >> 16) - 1;
274
275     std::string req_evt = std::string(stm::gStmEventName[event_no]);
276     std::string req_ctg = std::string(stm::gStmCategoryName[category_no]);
277     std::string req_area = std::string(stm::gStmAreaName[area_no]);
278     std::string req_role = pm::g_req_role_list[event_data];
279     HMI_DEBUG("wm:pm", "REQ: event:%s role:%s category:%s area:%s",
280         req_evt.c_str(), req_role.c_str(), req_ctg.c_str(), req_area.c_str());
281
282     // Store previous layers
283     pm::g_prv_layers = pm::g_crr_layers;
284
285     // Update layers
286     for (int layer_no = stm::gStmLayerNoMin;
287          layer_no <= stm::gStmLayerNoMax; layer_no++) {
288         const char* layer_name = stm::gStmLayerName[layer_no];
289         HMI_DEBUG("wm:pm", "LAYER:%s", layer_name);
290
291 #if 1
292         // If restriction mode is changed off -> on,
293         // store current state for state of restriction mode off
294         if ((crr_state.car_element[stm::gStmCarElementNoRestrictionMode].is_changed)
295             && (stm::gStmRestrictionModeStateNoOn == crr_state.car_element[stm::gStmCarElementNoRestrictionMode].state)) {
296             HMI_DEBUG("wm:lm", "Store current state for state of restriction mode off");
297             pm::g_prv_layers_car_stop[layer_name] = pm::g_crr_layers[layer_name];
298         }
299 #else
300         // If car state is changed car_stop -> car_run,
301         // store current state for state of car stop
302         if ((crr_state.car.is_changed)
303             && (stm::gStmRunningNoRun == crr_state.car.state)) {
304             HMI_DEBUG("wm:lm", "Store current state for state of car stop");
305             pm::g_prv_layers_car_stop[layer_name] = pm::g_crr_layers[layer_name];
306         }
307 #endif
308
309
310         // This layer is changed?
311         if (crr_state.layer[layer_no].is_changed) {
312             // Get previous layout name of this layer
313             pm::LayoutState prv_layout_state =  pm::g_prv_layers[layer_name].layout_state;
314             std::string prv_layout_name = prv_layout_state.name;
315
316             // Get current layout name of this layer
317             int crr_layout_state_no =  crr_state.layer[layer_no].state;
318             std::string crr_layout_name = std::string(stm::gStmLayoutNo2Name[crr_layout_state_no]);
319
320             pm::LayoutState crr_layout_state;
321 #if 1
322             if ((crr_state.car_element[stm::gStmCarElementNoRestrictionMode].is_changed)
323                 && (stm::gStmRestrictionModeStateNoOff == crr_state.car_element[stm::gStmCarElementNoRestrictionMode].state)) {
324                 // If restriction mode is changed on -> off,
325                 // restore state of restriction mode off
326                 HMI_DEBUG("wm:lm", "Restriction mode is changed on -> off, so restore state of restriction mode off");
327                 crr_layout_state = pm::g_prv_layers_car_stop[layer_name].layout_state;
328 #else
329             if ((crr_state.car_element[gStmCarElementNoRunning].is_changed)
330                 && (stm::gStmCarElementNoStop == crr_state.car_element[gStmCarElementNoRunning].state)) {
331                 // If car state is changed car_run -> car_stop,
332                 // restore state of car stop
333                 HMI_DEBUG("wm:lm", "Car state is changed car_run -> car_stop, so restore state of car stop");
334                 crr_layout_state = pm::g_prv_layers_car_stop[layer_name].layout_state;
335 #endif
336             }
337             else {
338                 // Copy previous layout state for current
339                 crr_layout_state = prv_layout_state;
340
341                 if (prv_layout_name == crr_layout_name) {
342                     HMI_DEBUG("wm:lm", "Previous layout is same with current");
343                 }
344                 else {
345                     // If previous layout is NOT same with current,
346                     // current areas is set with default value
347                     HMI_DEBUG("wm:lm", "Previous layout is NOT same with current");
348                     crr_layout_state.name         = pm::g_default_layouts[crr_layout_name].name;
349                     crr_layout_state.category_num = pm::g_default_layouts[crr_layout_name].category_num;
350                     crr_layout_state.area_list    = pm::g_default_layouts[crr_layout_name].area_list;
351                 }
352
353                 // Create candidate list
354                 std::map<std::string, pm::AreaList> cand_list;
355                 for (int ctg_no=stm::gStmCategoryNoMin;
356                      ctg_no<=stm::gStmCategoryNoMax; ctg_no++) {
357                     const char* ctg = stm::gStmCategoryName[ctg_no];
358                     HMI_DEBUG("wm:pm", "ctg:%s", ctg);
359
360                     // Create candidate list for category from the previous displayed categories
361                     pm::AreaList tmp_cand_list;
362                     for (pm::AreaState area_state : prv_layout_state.area_list) {
363                         if (std::string(ctg) == area_state.category) {
364                             // If there is the category which is same with new category in previous layout,
365                             // push it to list
366                             HMI_DEBUG("wm:pm", "Push to candidate list category:%s role:%s",
367                                       area_state.category.c_str(), area_state.role.c_str());
368                             tmp_cand_list.push_back(area_state);
369                         }
370                     }
371
372                     int candidate_num = prv_layout_state.category_num[ctg];
373                     int blank_num = crr_layout_state.category_num[ctg];
374                     HMI_DEBUG("wm:pm", "blank_num:%d candidate_num:%d", blank_num, candidate_num);
375
376                     // If requested event is "activate"
377                     // and there are requested category and area,
378                     // update area with requested role in current layout.
379                     bool request_for_this_layer = false;
380                     bool updated = false;
381                     if ((ctg == req_ctg) && ("activate" == req_evt) ) {
382                         HMI_DEBUG("wm:pm", "requested event is activate");
383                         for (pm::AreaState &as : crr_layout_state.area_list) {
384                             if (as.category == req_ctg) {
385                                 request_for_this_layer = true;
386
387                                 if (as.name == req_area) {
388                                     HMI_DEBUG("wm:pm", "Update current layout: area:%s category:%s role:%s",
389                                               as.name.c_str(), as.category.c_str(), as.role.c_str());
390                                     as.role = req_role;
391                                     blank_num--;
392                                     updated = true;
393                                     break;
394                                 }
395                             }
396                         }
397
398                         // If NOT updated: there is not requested area in new layout, 
399                         // so push requested role to candidate list
400                         if (request_for_this_layer && (!updated)) {
401                             HMI_DEBUG("wm:pm", "Push request to candidate list");
402                             pm::AreaState area_state;
403                             area_state.name = req_area;
404                             area_state.category = req_ctg;
405                             area_state.role = req_role;
406                             tmp_cand_list.push_back(area_state);
407                         }
408                     }
409
410                     // Compare number of candidate/blank,
411                     // And remove role in order of the oldest as necessary
412                     if (candidate_num < blank_num) {
413                         // Refer history stack
414                         // and add to the top of tmp_cand_list in order to the newest
415                         while (candidate_num != blank_num) {
416                             pm::AreaState area_state;
417                             area_state.name = "";
418                             area_state.category = ctg;
419                             if (0 != crr_layout_state.role_history[ctg].size()) {
420                                 HMI_ERROR("wm:pm", "Use role in history stack:%s",
421                                           crr_layout_state.role_history[ctg].back().c_str());
422                                 area_state.role = crr_layout_state.role_history[ctg].back();
423                                 crr_layout_state.role_history[ctg].pop_back();
424                             }
425                             else {
426                                 HMI_ERROR("wm:pm", "There is no role in history stack!!");
427                                 area_state.role = "";
428                             }
429                             tmp_cand_list.push_back(area_state);
430                             candidate_num++;
431                         }
432                     }
433                     else if (candidate_num > blank_num) {
434                         HMI_DEBUG("wm:pm", "candidate_num > blank_num");
435
436                         // Remove the oldest role from candidate list
437                         while (candidate_num != blank_num) {
438                             std::string removed_role = tmp_cand_list.begin()->role;
439                             HMI_DEBUG("wm:pm", "Remove the oldest data(role:%s) from tmp_cand_list",
440                                       removed_role.c_str());
441                             tmp_cand_list.erase(tmp_cand_list.begin());
442                             candidate_num--;
443
444                             // Push removed data to history stack
445                             crr_layout_state.role_history[ctg].push_back(removed_role);
446                         }
447                     }
448                     else {  // (candidate_num == blank_num)
449                         // nop
450                     }
451
452                     cand_list[ctg] = tmp_cand_list;
453                 }
454
455                 // Update areas
456                 for (pm::AreaState &as : crr_layout_state.area_list) {
457                     HMI_DEBUG("wm:pm", "Current area info area:%s category:%s",
458                               as.name.c_str(), as.category.c_str());
459                     if ("" == as.role) {
460                         HMI_DEBUG("wm:pm", "Update this area with role:%s",
461                                   cand_list[as.category].begin()->role.c_str());
462                         as.role = cand_list[as.category].begin()->role;
463                         cand_list[as.category].erase(cand_list[as.category].begin());
464                     }
465                 }
466             }
467             // Update current layout of this layer
468             pm::g_crr_layers[layer_name].layout_state = crr_layout_state;
469             pm::g_crr_layers[layer_name].changed = crr_state.layer[layer_no].is_changed;
470         }
471     }
472
473     // Erase role for the event_data from list
474     pm::g_req_role_list.erase(event_data);
475
476     // Check
477     for (auto itr : pm::g_crr_layers) {
478         pm::LayerState ls = itr.second;
479         HMI_DEBUG("wm:pm", ">>> LAYER:%s",ls.name.c_str());
480         HMI_DEBUG("wm:pm", ">>> >>> LAYOUT:%s", ls.layout_state.name.c_str());
481
482         for (pm::AreaState as : ls.layout_state.area_list) {
483             HMI_DEBUG("wm:pm", ">>> >>> >>> AREA:%s", as.name.c_str());
484             HMI_DEBUG("wm:pm", ">>> >>> >>> >>> CTG:%s", as.category.c_str());
485             HMI_DEBUG("wm:pm", ">>> >>> >>> >>> ROLE:%s", as.role.c_str());
486         }
487         HMI_DEBUG("wm:pm", ">>> >>> CHANGED:%d", ls.changed);
488     }
489 }
490
491 static void updateLocalState(int event_data, stm::stm_state_t crr_state) {
492     updateLocalCarElementState(crr_state);
493     updateLocalLayerState(event_data, crr_state);
494 }
495
496 static void createOutputInformation(stm::stm_state_t crr_state, json_object **json_out) {
497     json_object* json_tmp;
498
499     // Create car element information
500     // {
501     //     "car_elements": [
502     //     {
503     //         "parking_brake": {
504     //             "is_changed": <bool>,
505     //             "state": <const char*>
506     //         },
507     //         ...
508     //     },
509     json_object* json_car_ele = json_object_new_array();
510     const char* car_ele_name;
511     for (int car_ele_no = stm::gStmCarElementNoMin;
512          car_ele_no <= stm::gStmCarElementNoMax; car_ele_no++) {
513         car_ele_name = stm::gStmCarElementName[car_ele_no];
514         json_tmp = json_object_new_object();
515         addStateToJson(car_ele_name,
516                        pm::g_crr_car_elements[car_ele_name].changed,
517                        pm::g_crr_car_elements[car_ele_name].state,
518                        &json_tmp);
519         json_object_array_add(json_car_ele, json_tmp);
520     }
521     json_object_object_add(*json_out, "car_elements", json_car_ele);
522
523     // Create layout information
524     //
525     //     "layers": [
526     //     {
527     //         "homescreen": {
528     //             "changed": <bool>,
529     //             "areas": [
530     //             {
531     //                 "name":<const char*>,
532     //                 "role":<const char*>
533     //             }.
534     //             ...
535     //             ]
536     //         }
537     //     },
538     //     ...
539     json_object* json_layer = json_object_new_array();
540     const char* layer_name;
541     for (int layer_no = stm::gStmLayerNoMin;
542          layer_no <= stm::gStmLayerNoMax; layer_no++) {
543         layer_name = stm::gStmLayerName[layer_no];
544         json_tmp = json_object_new_object();
545         addStateToJson(layer_name,
546                        pm::g_crr_layers[layer_name].changed,
547                        pm::g_crr_layers[layer_name].layout_state.area_list,
548                        &json_tmp);
549         json_object_array_add(json_layer, json_tmp);
550     }
551     json_object_object_add(*json_out, "layers", json_layer);
552 }
553
554 static int checkPolicyEntry(int event, uint64_t delay_ms, std::string role);
555 static void controlTimerEvent(stm::stm_state_t crr_state) {
556     if (crr_state.car_element[stm::gStmCarElementNoRunning].is_changed) {
557         if (stm::gStmRunningNoRun == crr_state.car_element[stm::gStmCarElementNoRunning].state) {
558             // Set delay event(restriction mode on)
559             checkPolicyEntry(STM_EVT_NO_RESTRICTION_MODE_ON, 3000, "");
560         }
561         else if (stm::gStmRunningNoStop == crr_state.car_element[stm::gStmCarElementNoRunning].state) {
562             // Stop timer for restriction on event
563             if (pm::event_source_list.find(STM_EVT_NO_RESTRICTION_MODE_ON)
564               != pm::event_source_list.end()) {
565                 HMI_DEBUG("wm:pm", "Stop timer for restriction on");
566                 sd_event_source *event_source
567                     = pm::event_source_list[STM_EVT_NO_RESTRICTION_MODE_ON];
568                 int ret = sd_event_source_set_enabled(event_source, SD_EVENT_OFF);
569                 if (0 > ret) {
570                     HMI_ERROR("wm:pm", "Failed to stop timer");
571                 }
572             }
573
574             // Set event(restriction mode off)
575             checkPolicyEntry(STM_EVT_NO_RESTRICTION_MODE_OFF, 0, "");
576         }
577     }
578 }
579
580 static int checkPolicy(sd_event_source *source, void *data) {
581     HMI_DEBUG("wm:pm", "Call");
582     HMI_DEBUG("wm:pm", ">>>>>>>>>> START CHECK POLICY");
583
584     int event_data = *((int*)data);
585
586     int event_no, category_no, area_no;
587     event_no    = (event_data & STM_MSK_EVT_NO) - 1;
588     category_no = ((event_data & STM_MSK_CTG_NO) >> 8) - 1;
589     area_no     = ((event_data & STM_MSK_ARA_NO) >> 16) - 1;
590     HMI_DEBUG("wm:pm", ">>>>>>>>>> event:%s category:%s area:%s",
591               stm::gStmEventName[event_no],
592               stm::gStmCategoryName[category_no],
593               stm::gStmAreaName[area_no]);
594
595     // Transition state
596     stm::stm_state_t crr_state;
597     int ret = stm::stmTransitionState(event_data, &crr_state);
598     if (0 > ret) {
599         HMI_ERROR("wm:pm", "Failed transition state");
600         if (nullptr != pm::callback.onError) {
601             json_object* json_out = json_object_new_object();
602             json_object_object_add(json_out, "message",
603                                    json_object_new_string("Failed to transition state"));
604             json_object_object_add(json_out, "event",
605                                    json_object_new_string(stm::gStmEventName[event_no]));
606             json_object_object_add(json_out, "role",
607                                    json_object_new_string(pm::g_req_role_list[event_data].c_str()));
608             json_object_object_add(json_out, "area",
609                                    json_object_new_string(stm::gStmAreaName[area_no]));
610             pm::callback.onError(json_out);
611             json_object_put(json_out);
612         }
613         return -1;
614     }
615
616     // Update state which is managed by PolicyManager
617     updateLocalState(event_data, crr_state);
618
619     // Create output information for ResourceManager
620     json_object* json_out = json_object_new_object();
621     createOutputInformation(crr_state, &json_out);
622
623     // Notify changed state
624     if (nullptr != pm::callback.onStateTransitioned) {
625         pm::callback.onStateTransitioned(json_out);
626     }
627
628     // Start/Stop timer events
629     controlTimerEvent(crr_state);
630
631     // Release json_object
632     json_object_put(json_out);
633
634     // Release data
635     delete (int*)data;
636
637     // Destroy sd_event_source object
638     sd_event_source_unref(source);
639
640     // Remove event source from list
641     if (pm::event_source_list.find(event_data) != pm::event_source_list.end()) {
642         pm::event_source_list.erase(event_data);
643     }
644
645     HMI_DEBUG("wm:pm", ">>>>>>>>>> FINISH CHECK POLICY");
646     return 0;
647 }
648
649 static int timerEvent(sd_event_source *source, uint64_t usec, void *data) {
650     HMI_DEBUG("wm:pm", "Call");
651
652     int ret = checkPolicy(source, data);
653     return ret;
654 }
655
656 static int checkPolicyEntry(int event, uint64_t delay_ms, std::string role)
657 {
658     HMI_DEBUG("wm:pm", "Call");
659     HMI_DEBUG("wm:pm", "event:0x%x delay:%d role:%s", event, delay_ms, role.c_str());
660
661     // Store requested role
662     pm::g_req_role_list[event] = role;
663
664     if (0 == delay_ms) {
665         int ret = sd_event_add_defer(pm::event_loop, NULL,
666                                      &checkPolicy, new int(event));
667         if (0 > ret) {
668             HMI_ERROR("wm:pm", "Faild to sd_event_add_defer: errno:%d", ret);
669             pm::g_req_role_list.erase(event);
670             return -1;
671         }
672     }
673     else {
674         // Get current time
675         struct timespec time_spec;
676         clock_gettime(CLOCK_MONOTONIC, &time_spec);
677
678         // Calculate timer fired time
679         uint64_t usec = (time_spec.tv_sec * 1000000)
680             + (time_spec.tv_nsec / 1000)
681             + (delay_ms * 1000);
682
683         // Set timer
684         struct sd_event_source* event_source;
685         int ret = sd_event_add_time(pm::event_loop, &event_source, CLOCK_MONOTONIC, usec, 1,
686                                     &timerEvent, new int(event));
687         if (0 > ret) {
688             HMI_ERROR("wm:pm", "Faild to sd_event_add_time: errno:%d", ret);
689             pm::g_req_role_list.erase(event);
690             return -1;
691         }
692
693         // Store event source
694         pm::event_source_list[event] = event_source;
695     }
696
697     return 0;
698 }
699
700 void PolicyManager::registerCallback(CallbackTable callback) {
701     HMI_DEBUG("wm:pm", "Call");
702
703     pm::callback.onStateTransitioned = callback.onStateTransitioned;
704     pm::callback.onError             = callback.onError;
705 }
706
707 int PolicyManager::setInputEventData(json_object* json_in) {
708     HMI_DEBUG("wm:pm", "Call");
709
710     // Check arguments
711     if (nullptr == json_in) {
712         HMI_ERROR("wm:pm", "Argument is NULL!!");
713         return -1;
714     }
715
716     // Get event from json_object
717     const char* event = this->getStringFromJson(json_in, "event");
718     int event_no = 0;
719     if (nullptr != event) {
720         // Convert name to number
721         event_no = this->eventname2no_[event];
722         HMI_DEBUG("wm:pm", "event(%s:%d)", event, event_no);
723     }
724
725     // Get role from json_object
726     const char* role = this->getStringFromJson(json_in, "role");
727     int category_no = 0;
728     if (nullptr != role) {
729         HMI_DEBUG("wm:pm", "role(%s)", role);
730
731         // Convert role to category
732         const char* category = this->role2category_[role].c_str();
733         if (0 == strcmp("", category)) {
734             HMI_ERROR("wm:pm", "Error!!");
735             return -1;
736         }
737         HMI_DEBUG("wm:pm", "category(%s)", category);
738
739         // Convert name to number
740         category_no = categoryname2no_[category];
741         HMI_DEBUG("wm:pm", "role(%s), category(%s:%d)", role, category, category_no);
742     }
743
744     // Get areat from json_object
745     const char* area = this->getStringFromJson(json_in, "area");
746     int area_no = 0;
747     if (nullptr != area) {
748         // Convert name to number
749         area_no = areaname2no_[area];
750         HMI_DEBUG("wm:pm", "area(%s:%d)", area, area_no);
751     }
752
753     // Set event info to the queue
754     pm::EventInfo event_info;
755     event_info.event = (event_no | category_no | area_no);
756     if (nullptr == role) {
757         event_info.role = std::string("");
758     }
759     else {
760         event_info.role = std::string(role);
761     }
762     event_info.delay = 0;
763     pm::g_event_info_queue.push(event_info);
764
765     return 0;
766 }
767
768 int PolicyManager::executeStateTransition() {
769     HMI_DEBUG("wm:pm", "Call");
770
771     int ret;
772     pm::EventInfo event_info;
773
774     while (!pm::g_event_info_queue.empty()) {
775         // Get event info from queue and delete
776         event_info = pm::g_event_info_queue.front();
777         pm::g_event_info_queue.pop();
778
779         // Set event info for checking policy
780         ret = checkPolicyEntry(event_info.event, event_info.delay, event_info.role);
781     }
782     return ret;
783 }
784
785 void PolicyManager::undoState() {
786     HMI_DEBUG("wm:pm", "Call");
787
788     // Undo state of STM
789     stm::stmUndoState();
790
791     pm::g_crr_layers = pm::g_prv_layers;
792 }
793
794 extern const char* kDefaultRoleDb;
795 int PolicyManager::loadRoleDb() {
796     HMI_DEBUG("wm:pm", "Call");
797
798     std::string file_name;
799
800     // Get afm application installed dir
801     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
802     HMI_DEBUG("wm:pm", "afm_app_install_dir:%s", afm_app_install_dir);
803
804     if (!afm_app_install_dir) {
805         HMI_ERROR("wm:pm", "AFM_APP_INSTALL_DIR is not defined");
806     }
807     else {
808         file_name = std::string(afm_app_install_dir) + std::string("/etc/role.db");
809     }
810
811     // Load role.db
812     json_object* json_obj;
813     int ret = this->inputJsonFilie(file_name.c_str(), &json_obj);
814     if (0 > ret) {
815         HMI_ERROR("wm:pm", "Could not open role.db, so use default role information");
816         json_obj = json_tokener_parse(kDefaultRoleDb);
817     }
818     HMI_DEBUG("wm:pm", "json_obj dump:%s", json_object_get_string(json_obj));
819
820     json_object* json_roles;
821     if (!json_object_object_get_ex(json_obj, "roles", &json_roles)) {
822         HMI_ERROR("wm:pm", "Parse Error!!");
823         return -1;
824     }
825
826     int len = json_object_array_length(json_roles);
827     HMI_DEBUG("wm:pm", "json_cfg len:%d", len);
828     HMI_DEBUG("wm:pm", "json_cfg dump:%s", json_object_get_string(json_roles));
829
830     json_object* json_tmp;
831     const char* category;
832     const char* roles;
833     const char* areas;
834     for (int i=0; i<len; i++) {
835         json_tmp = json_object_array_get_idx(json_roles, i);
836
837         category = this->getStringFromJson(json_tmp, "category");
838         roles =  this->getStringFromJson(json_tmp, "role");
839         areas =  this->getStringFromJson(json_tmp, "area");
840
841         if ((nullptr == category) || (nullptr == roles) || (nullptr == areas)) {
842             HMI_ERROR("wm:pm", "Parse Error!!");
843             return -1;
844         }
845
846         // Parse roles by '|'
847         std::vector<std::string> vct_roles;
848         vct_roles = this->parseString(std::string(roles), '|');
849
850         // Parse areas by '|'
851         std::vector<std::string> vct_areas;
852         vct_areas = this->parseString(std::string(areas), '|');
853
854         // Set role, category, default area
855         for (auto itr = vct_roles.begin(); itr != vct_roles.end(); ++itr) {
856             // Delete space from role and area name
857             std::string role = this->deleteSpace(*itr);
858             std::string area = this->deleteSpace(vct_areas[0]);
859
860             this->role2category_[role] = std::string(category);
861             this->role2defaultarea_[role] = area;
862         }
863
864         this->category2role_[std::string(category)] = std::string(roles);
865     }
866
867     // Check
868     HMI_DEBUG("wm:pm", "Check role2category_");
869     for (auto& x:this->role2category_){
870         HMI_DEBUG("wm:pm", "key:%s, val:%s", x.first.c_str(), x.second.c_str());
871     }
872
873     HMI_DEBUG("wm:pm", "Check role2defaultarea_");
874     for (auto& x:this->role2defaultarea_){
875         HMI_DEBUG("wm:pm", "key:%s, val:%s", x.first.c_str(), x.second.c_str());
876     }
877
878     HMI_DEBUG("wm:pm", "Check category2role_");
879     for (auto& x:this->category2role_){
880         HMI_DEBUG("wm:pm", "key:%s, val:%s", x.first.c_str(), x.second.c_str());
881     }
882
883     return 0;
884 }
885
886 extern const char* kDefaultLayoutDb;
887 int PolicyManager::loadLayoutDb() {
888     HMI_DEBUG("wm:lm", "Call");
889
890     // Get afm application installed dir
891     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
892     HMI_DEBUG("wm:pm", "afm_app_install_dir:%s", afm_app_install_dir);
893
894     std::string file_name;
895     if (!afm_app_install_dir) {
896         HMI_ERROR("wm:pm", "AFM_APP_INSTALL_DIR is not defined");
897     }
898     else {
899         file_name = std::string(afm_app_install_dir) + std::string("/etc/layout.db");
900     }
901
902     // Load layout.db
903     json_object* json_obj;
904     int ret = this->inputJsonFilie(file_name.c_str(), &json_obj);
905     if (0 > ret) {
906         HMI_DEBUG("wm:pm", "Could not open layout.db, so use default layout information");
907         json_obj = json_tokener_parse(kDefaultLayoutDb);
908     }
909     HMI_DEBUG("wm:pm", "json_obj dump:%s", json_object_get_string(json_obj));
910
911     // Perse layouts
912     HMI_DEBUG("wm:pm", "Perse layouts");
913     json_object* json_cfg;
914     if (!json_object_object_get_ex(json_obj, "layouts", &json_cfg)) {
915         HMI_ERROR("wm:pm", "Parse Error!!");
916         return -1;
917     }
918
919     int len = json_object_array_length(json_cfg);
920     HMI_DEBUG("wm:pm", "json_cfg len:%d", len);
921     HMI_DEBUG("wm:pm", "json_cfg dump:%s", json_object_get_string(json_cfg));
922
923     const char* layout;
924     const char* role;
925     const char* category;
926     for (int i=0; i<len; i++) {
927         json_object* json_tmp = json_object_array_get_idx(json_cfg, i);
928
929         layout = this->getStringFromJson(json_tmp, "name");
930         if (nullptr == layout) {
931             HMI_ERROR("wm:pm", "Parse Error!!");
932             return -1;
933         }
934         HMI_DEBUG("wm:pm", "> layout:%s", layout);
935
936         json_object* json_area_array;
937         if (!json_object_object_get_ex(json_tmp, "areas", &json_area_array)) {
938           HMI_ERROR("wm:pm", "Parse Error!!");
939           return -1;
940         }
941
942         int len_area = json_object_array_length(json_area_array);
943         HMI_DEBUG("wm:pm", "json_area_array len:%d", len_area);
944         HMI_DEBUG("wm:pm", "json_area_array dump:%s", json_object_get_string(json_area_array));
945
946         pm::LayoutState layout_state;
947         pm::AreaState area_state;
948         std::map<std::string, int> category_num;
949         for (int ctg_no = stm::gStmCategoryNoMin;
950              ctg_no <= stm::gStmCategoryNoMax; ctg_no++) {
951             const char* ctg_name = stm::gStmCategoryName[ctg_no];
952             category_num[ctg_name] = 0;
953         }
954
955         for (int j=0; j<len_area; j++) {
956             json_object* json_area = json_object_array_get_idx(json_area_array, j);
957
958             // Get area name
959             const char* area = this->getStringFromJson(json_area, "name");
960             if (nullptr == area) {
961               HMI_ERROR("wm:pm", "Parse Error!!");
962               return -1;
963             }
964             area_state.name = std::string(area);
965             HMI_DEBUG("wm:pm", ">> area:%s", area);
966
967             // Get app attribute of the area
968             category = this->getStringFromJson(json_area, "category");
969             if (nullptr == category) {
970                 HMI_ERROR("wm:pm", "Parse Error!!");
971                 return -1;
972             }
973             area_state.category = std::string(category);
974             category_num[category]++;
975             HMI_DEBUG("wm:pm", ">>> category:%s", category);
976
977             role = this->getStringFromJson(json_area, "role");
978             if (nullptr != role) {
979                 // Role is NOT essential here
980                 area_state.role = std::string(role);
981             }
982             else {
983                 area_state.role = std::string("");
984
985             }
986             HMI_DEBUG("wm:pm", ">>> role:%s", role);
987
988             layout_state.area_list.push_back(area_state);
989
990         }
991
992         layout_state.name = layout;
993         layout_state.category_num = category_num;
994         pm::g_default_layouts[layout] = layout_state;
995     }
996
997     // initialize for none layout
998     pm::LayoutState none_layout_state;
999     memset(&none_layout_state, 0, sizeof(none_layout_state));
1000     none_layout_state.name                 = "none";
1001     pm::g_default_layouts["none"] = none_layout_state;
1002
1003     // Check
1004     for(auto itr_layout = pm::g_default_layouts.begin();
1005       itr_layout != pm::g_default_layouts.end(); ++itr_layout) {
1006         HMI_DEBUG("wm:pm", ">>> layout:%s", itr_layout->first.c_str());
1007
1008         for (auto itr_area = itr_layout->second.area_list.begin();
1009           itr_area != itr_layout->second.area_list.end(); ++itr_area) {
1010             HMI_DEBUG("wm:pm", ">>> >>> area    :%s", itr_area->name.c_str());
1011             HMI_DEBUG("wm:pm", ">>> >>> category:%s", itr_area->category.c_str());
1012             HMI_DEBUG("wm:pm", ">>> >>> role    :%s", itr_area->role.c_str());
1013         }
1014     }
1015
1016     // Release json_object
1017     json_object_put(json_obj);
1018
1019     return 0;
1020 }
1021
1022 // TODO:
1023 // This function will be removed because json_helper has same function.
1024 // json_helper should be library.
1025 const char* PolicyManager::getStringFromJson(json_object* obj, const char* key) {
1026     if ((nullptr == obj) || (nullptr == key)) {
1027         HMI_ERROR("wm:pm", "Argument is nullptr!!!");
1028         return nullptr;
1029     }
1030
1031     json_object* tmp;
1032     if (!json_object_object_get_ex(obj, key, &tmp)) {
1033         HMI_DEBUG("wm:pm", "Not found key \"%s\"", key);
1034         return nullptr;
1035     }
1036
1037     return json_object_get_string(tmp);
1038 }
1039
1040 // TODO:
1041 // This function will be removed because json_helper has same function.
1042 // json_helper should be library.
1043 int PolicyManager::inputJsonFilie(const char* file, json_object** obj) {
1044     const int input_size = 128;
1045     int ret = -1;
1046
1047     if ((nullptr == file) || (nullptr == obj)) {
1048         HMI_ERROR("wm:jh", "Argument is nullptr!!!");
1049         return ret;
1050     }
1051
1052     HMI_DEBUG("wm:jh", "Input file: %s", file);
1053
1054     // Open json file
1055     FILE *fp = fopen(file, "rb");
1056     if (nullptr == fp) {
1057         HMI_ERROR("wm:jh", "Could not open file");
1058         return ret;
1059     }
1060
1061     // Parse file data
1062     struct json_tokener *tokener = json_tokener_new();
1063     enum json_tokener_error json_error;
1064     char buffer[input_size];
1065     int block_cnt = 1;
1066     while (1) {
1067         size_t len = fread(buffer, sizeof(char), input_size, fp);
1068         *obj = json_tokener_parse_ex(tokener, buffer, len);
1069         if (nullptr != *obj) {
1070             HMI_DEBUG("wm:jh", "File input is success");
1071             ret = 0;
1072             break;
1073         }
1074
1075         json_error = json_tokener_get_error(tokener);
1076         if ((json_tokener_continue != json_error)
1077             || (input_size > len)) {
1078             HMI_ERROR("wm:jh", "Failed to parse file (byte:%d err:%s)",
1079                       (input_size * block_cnt), json_tokener_error_desc(json_error));
1080             HMI_ERROR("wm:jh", "\n%s", buffer);
1081             *obj = nullptr;
1082             break;
1083         }
1084         block_cnt++;
1085     }
1086
1087     // Close json file
1088     fclose(fp);
1089
1090     // Free json_tokener
1091     json_tokener_free(tokener);
1092
1093     return ret;
1094 }
1095
1096 std::vector<std::string> PolicyManager::parseString(std::string str, char delimiter) {
1097     // Parse string by delimiter
1098     std::vector<std::string> vct;
1099     std::stringstream ss{str};
1100     std::string buf;
1101     while (std::getline(ss, buf, delimiter)) {
1102       if (!buf.empty()) {
1103         vct.push_back(buf);
1104       }
1105     }
1106     return vct;
1107 }
1108
1109 std::string PolicyManager::deleteSpace(std::string str) {
1110     std::string ret = str;
1111     size_t pos;
1112     while ((pos = ret.find_first_of(" ")) != std::string::npos) {
1113       ret.erase(pos, 1);
1114     }
1115     return ret;
1116 }
1117
1118 const char* kDefaultRoleDb = "{ \
1119     \"roles\":[ \
1120     { \
1121         \"category\": \"homescreen\", \
1122         \"role\": \"homescreen\", \
1123         \"area\": \"full\", \
1124     }, \
1125     { \
1126         \"category\": \"map\", \
1127         \"role\": \"map\", \
1128         \"area\": \"full | normal | split.main\", \
1129     }, \
1130     { \
1131         \"category\": \"general\", \
1132         \"role\": \"poi | music | video | browser | sdl | settings | mixer | radio | hvac | dashboard | debug\", \
1133         \"area\": \"normal\", \
1134     }, \
1135     { \
1136         \"category\": \"phone\", \
1137         \"role\": \"phone\", \
1138         \"area\": \"normal\", \
1139     }, \
1140     { \
1141         \"category\": \"splitable\", \
1142         \"role\": \"splitable1 | splitable2\", \
1143         \"area\": \"normal | split.main | split.sub\", \
1144     }, \
1145     { \
1146         \"category\": \"popup\", \
1147         \"role\": \"popup\", \
1148         \"area\": \"on_screen\", \
1149     }, \
1150     { \
1151         \"category\": \"system_alert\", \
1152         \"role\": \"system_alert\", \
1153         \"area\": \"on_screen\", \
1154     }, \
1155     { \
1156         \"category\": \"tbt\", \
1157         \"role\": \"tbt\", \
1158         \"area\": \"hud\", \
1159     } \
1160     ] \
1161 }";
1162
1163
1164 const char* kDefaultLayoutDb = "{ \
1165     \"layouts\": [ \
1166         { \
1167             \"name\": \"pu\", \
1168             \"layer\": \"on_screen\", \
1169             \"areas\": [ \
1170                 { \
1171                     \"name\": \"pop_up\", \
1172                     \"role\": \"incomming_call\" \
1173                 } \
1174             ] \
1175         }, \
1176         { \
1177             \"name\": \"sa\", \
1178             \"layer\": \"on_screen\", \
1179             \"areas\": [ \
1180                 { \
1181                     \"name\": \"system_alert\", \
1182                     \"role\": \"system_alert\" \
1183                 } \
1184             ] \
1185         }, \
1186         { \
1187             \"name\": \"m1\", \
1188             \"layer\": \"apps\", \
1189             \"areas\": [ \
1190                 { \
1191                     \"name\": \"normal\", \
1192                     \"role\": \"map\" \
1193                 } \
1194             ] \
1195         }, \
1196         { \
1197             \"name\": \"m2\", \
1198             \"layer\": \"apps\", \
1199             \"areas\": [ \
1200                 { \
1201                     \"name\": \"split.main\", \
1202                     \"role\": \"map\" \
1203                 }, \
1204                 { \
1205                     \"name\": \"split.sub\", \
1206                     \"category\": \"hvac\" \
1207                 } \
1208             ] \
1209         }, \
1210         { \
1211             \"name\": \"mf\", \
1212             \"layer\": \"apps\", \
1213             \"areas\": [ \
1214                 { \
1215                     \"name\": \"full\", \
1216                     \"role\": \"map\" \
1217                 } \
1218             ] \
1219         }, \
1220         { \
1221             \"name\": \"s1\", \
1222             \"layer\": \"apps\", \
1223             \"areas\": [ \
1224                 { \
1225                     \"name\": \"normal\", \
1226                     \"category\": \"splitable\" \
1227                 } \
1228             ] \
1229         }, \
1230         { \
1231             \"name\": \"s2\", \
1232             \"layer\": \"apps\", \
1233             \"areas\": [ \
1234                 { \
1235                     \"name\": \"split.main\", \
1236                     \"category\": \"splitable\" \
1237                 }, \
1238                 { \
1239                     \"name\": \"split.sub\", \
1240                     \"category\": \"splitable\" \
1241                 } \
1242             ] \
1243         }, \
1244         { \
1245             \"name\": \"g\", \
1246             \"layer\": \"apps\", \
1247             \"areas\": [ \
1248                 { \
1249                     \"name\": \"normal\", \
1250                     \"category\": \"general\" \
1251                 } \
1252             ] \
1253         }, \
1254         { \
1255             \"name\": \"hs\", \
1256             \"layer\": \"homescreen\", \
1257             \"areas\": [ \
1258                 { \
1259                     \"name\": \"full\", \
1260                     \"role\": \"homescreen\" \
1261                 } \
1262             ] \
1263         } \
1264     ], \
1265     \"areas\": [ \
1266         { \
1267             \"name\": \"normal\", \
1268             \"rect\": { \
1269                 \"x\": 0, \
1270                 \"y\": 218, \
1271                 \"w\": 1080, \
1272                 \"h\": 1488 \
1273             } \
1274         }, \
1275         { \
1276             \"name\": \"split.main\", \
1277             \"rect\": { \
1278                 \"x\": 0, \
1279                 \"y\": 218, \
1280                 \"w\": 1080, \
1281                 \"h\": 744 \
1282             } \
1283         }, \
1284         { \
1285             \"name\": \"split.sub\", \
1286             \"rect\": { \
1287                 \"x\": 0, \
1288                 \"y\": 962, \
1289                 \"w\": 1080, \
1290                 \"h\": 744 \
1291             } \
1292         }, \
1293         { \
1294             \"name\": \"full\", \
1295             \"rect\": { \
1296                 \"x\": 0, \
1297                 \"y\": 0, \
1298                 \"w\": 1080, \
1299                 \"h\": 1920 \
1300             } \
1301         }, \
1302         { \
1303             \"name\": \"pop_up\", \
1304             \"rect\": { \
1305                 \"x\": 0, \
1306                 \"y\": 640, \
1307                 \"w\": 1080, \
1308                 \"h\": 640 \
1309             } \
1310         }, \
1311         { \
1312             \"name\": \"system_alert\", \
1313             \"rect\": { \
1314                 \"x\": 0, \
1315                 \"y\": 640, \
1316                 \"w\": 1080, \
1317                 \"h\": 640 \
1318             } \
1319         } \
1320     ] \
1321 }";