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