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