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