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