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