Fix place of connection.json
[apps/agl-service-windowmanager.git] / 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 #include <fstream>
18 #include <sstream>
19 #include <istream>
20 #include <thread>
21 #include <map>
22 #include <algorithm>
23 #include <json-c/json.h>
24 #include "policy_manager.hpp"
25 #include "util.hpp"
26
27 extern "C"
28 {
29 #define AFB_BINDING_VERSION 2
30 #include <afb/afb-binding.h>
31 #include <systemd/sd-event.h>
32 #include "stm.h"
33 }
34
35 namespace pm
36 {
37 static const char kPathRolesConfigFile[] = "/etc/roles.json";
38 static const char kPathLayoutsConfigFile[] = "/etc/layouts.json";
39
40 static const int kInvisibleRoleHistoryNum = 5;
41
42 static PolicyManager *g_context;
43
44 static int transitionStateWrapper(sd_event_source *source, void *data)
45 {
46     int ret = g_context->transitionState(source, data);
47     return ret;
48 }
49
50 static int timerEventWrapper(sd_event_source *source, uint64_t usec, void *data)
51 {
52     int ret = g_context->timerEvent(source, usec, data);
53     return ret;
54 }
55
56 } // namespace pm
57
58 PolicyManager::PolicyManager()
59     : eventname2no(),
60       categoryname2no(),
61       areaname2no(),
62       role2category(),
63       category2role(),
64       category2areas()
65 {
66     this->p_crr_state = new (StmState);
67     this->p_prv_state = new (StmState);
68 }
69
70 PolicyManager::~PolicyManager()
71 {
72     delete this->p_crr_state;
73     delete this->p_prv_state;
74 }
75
76 int PolicyManager::initialize(std::string ecu_name)
77 {
78     int ret = 0;
79
80     // Set ECU name
81     this->ecu_name = ecu_name;
82
83     // Create convert map
84     for (int i = StmEvtNoMin; i <= StmEvtNoMax; i++)
85     {
86         HMI_DEBUG("event name:%s no:%d", kStmEventName[i], i);
87         this->eventname2no[kStmEventName[i]] = i;
88     }
89
90     for (int i = StmCtgNoMin; i <= StmCtgNoMax; i++)
91     {
92         HMI_DEBUG("category name:%s no:%d", kStmCategoryName[i], i);
93         this->categoryname2no[kStmCategoryName[i]] = i;
94     }
95
96     for (int i = StmAreaNoMin; i <= StmAreaNoMax; i++)
97     {
98         HMI_DEBUG("area name:%s no:%d", kStmAreaName[i], i);
99         this->areaname2no[kStmAreaName[i]] = i;
100     }
101
102     // Load roles config
103     ret = this->loadRolesConfigFile();
104     if (0 > ret)
105     {
106         HMI_ERROR("Load roles config file Error!!");
107         return ret;
108     }
109
110     // Load layouts config
111     ret = this->loadLayoutsConfigFile();
112     if (0 > ret)
113     {
114         HMI_ERROR("Load layouts config file Error!!");
115         return ret;
116     }
117
118     // Initialize state which is managed by PolicyManager
119     this->initializeState();
120
121     // Initialize StateTransitioner
122     stmInitialize(ecu_name.c_str());
123
124     // Store instance
125     pm::g_context = this;
126
127     return ret;
128 }
129
130 void PolicyManager::registerCallback(CallbackTable callback)
131 {
132     this->callback.onStateTransitioned = callback.onStateTransitioned;
133     this->callback.onError = callback.onError;
134 }
135
136 int PolicyManager::setInputEventData(json_object *json_in)
137 {
138     // Check arguments
139     if (nullptr == json_in)
140     {
141         HMI_ERROR("Argument is NULL!!");
142         return -1;
143     }
144
145     // Get event from json_object
146     const char *event = this->getStringFromJson(json_in, "event");
147     int event_no = StmEvtNoNone;
148     if (nullptr != event)
149     {
150         // Convert name to number
151         auto itr = this->eventname2no.find(event);
152         if (this->eventname2no.end() != itr)
153         {
154             event_no = this->eventname2no[event];
155             HMI_DEBUG("event(%s:%d)", event, event_no);
156         }
157         else
158         {
159             HMI_ERROR("Invalid event name!!");
160             return -1;
161         }
162     }
163     else
164     {
165         HMI_ERROR("Event is not set!!");
166         return -1;
167     }
168
169     // Get role from json_object
170     const char *role = this->getStringFromJson(json_in, "role");
171     std::string category = "";
172     int category_no = StmCtgNoNone;
173     if (nullptr != role)
174     {
175         HMI_DEBUG("role(%s)", role);
176
177         // Convert role to category
178         auto itr = this->role2category.find(role);
179         if (this->role2category.end() != itr)
180         {
181             category = this->role2category[role];
182         }
183         else
184         {
185             itr = this->role2category.find("fallback");
186             if (this->role2category.end() != itr)
187             {
188                 HMI_DEBUG("Role:%s is not registered in roles config file, fallback as normal app", role);
189                 category = this->role2category["fallback"];
190             }
191         }
192
193         if ("" != category)
194         {
195             // Convert name to number
196             category_no = categoryname2no[category];
197             HMI_DEBUG("category(%s:%d)", category.c_str(), category_no);
198         }
199     }
200     if (StmCtgNoNone == category_no)
201     {
202         role = "";
203     }
204
205     // Get area from json_object
206     const char *area = this->getStringFromJson(json_in, "area");
207     int area_no = StmAreaNoNone;
208     if ((nullptr != area) && (StmCtgNoNone != category_no))
209     {
210         for (const auto &x : this->category2areas[category])
211         {
212             if (x == std::string(area))
213             {
214                 area_no = this->areaname2no[area];
215                 break;
216             }
217         }
218         if (StmAreaNoNone == area_no)
219         {
220             area = this->category2areas[category].front().c_str();
221             area_no = this->areaname2no[area];
222         }
223         HMI_DEBUG("area(%s:%d)", area, area_no);
224     }
225
226     // Set event info to the queue
227     EventInfo event_info;
228     int event_id = STM_CREATE_EVENT_ID(event_no, category_no, area_no);
229     event_info.event = event_id;
230     event_info.role = std::string(role);
231     event_info.delay = 0;
232     this->event_info_queue.push(event_info);
233
234     return 0;
235 }
236
237 int PolicyManager::executeStateTransition()
238 {
239     int ret;
240     EventInfo event_info;
241
242     // Get event info from queue and delete
243     event_info = this->event_info_queue.front();
244     this->event_info_queue.pop();
245
246     // Set event info to check policy
247     ret = this->setStateTransitionProcessToSystemd(event_info.event,
248                                                    event_info.delay,
249                                                    event_info.role);
250     return ret;
251 }
252
253 void PolicyManager::undoState()
254 {
255     HMI_DEBUG("Undo State !!!");
256
257     // Undo state of STM
258     stmUndoState();
259
260     HMI_DEBUG(">>>>>>>>>> BEFORE UNDO");
261     this->dumpLayerState(this->crr_layers);
262
263     this->crr_layers = this->prv_layers;
264     this->crr_invisible_role_history = this->prv_invisible_role_history;
265
266     HMI_DEBUG(">>>>>>>>>> AFTER UNDO");
267     this->dumpLayerState(this->crr_layers);
268 }
269
270 void PolicyManager::initializeState()
271 {
272     this->initializeModeState();
273     this->initializeLayerState();
274 }
275
276 void PolicyManager::initializeModeState()
277 {
278     Mode init_car_ele;
279     init_car_ele.state = "none";
280     init_car_ele.changed = false;
281
282     for (int i = StmCarElementNoMin; i <= StmCarElementNoMax; i++)
283     {
284         const char *car_ele_name = kStmCarElementName[i];
285         this->crr_car_elements[car_ele_name] = init_car_ele;
286     }
287
288     this->prv_car_elements = this->crr_car_elements;
289 }
290
291 void PolicyManager::initializeLayerState()
292 {
293     AreaState init_area;
294     LayoutState init_layout;
295     init_area.name = kStmAreaName[StmAreaNoNone];
296     init_area.category = kStmCategoryName[StmCtgNoNone];
297     init_area.role = "";
298     init_layout.name = kStmLayoutName[StmLayoutNoNone];
299     init_layout.area_list.push_back(init_area);
300
301     for (int i = StmLayerNoMin; i <= StmLayerNoMax; i++)
302     {
303         const char *layer_name = kStmLayerName[i];
304         this->crr_layers[layer_name].name = layer_name;
305         this->crr_layers[layer_name].layout_state = init_layout;
306         this->crr_layers[layer_name].changed = false;
307     }
308
309     this->prv_layers = this->crr_layers;
310 }
311
312 void PolicyManager::addStateToJson(const char *name, bool changed,
313                                    std::string state, json_object **json_out)
314 {
315     if ((nullptr == name) || (nullptr == json_out))
316     {
317         HMI_ERROR("Invalid argument!!!");
318         return;
319     }
320
321     json_object_object_add(*json_out, "name", json_object_new_string(name));
322     json_object_object_add(*json_out, "state", json_object_new_string(state.c_str()));
323     json_object_object_add(*json_out, "changed", json_object_new_boolean(changed));
324 }
325
326 void PolicyManager::addStateToJson(const char *layer_name, bool changed,
327                                    AreaList area_list, json_object **json_out)
328 {
329     if ((nullptr == layer_name) || (nullptr == json_out))
330     {
331         HMI_ERROR("Invalid argument!!!");
332         return;
333     }
334
335     json_object *json_areas = json_object_new_array();
336     json_object *json_tmp;
337     for (const auto &as : area_list)
338     {
339         json_tmp = json_object_new_object();
340         json_object_object_add(json_tmp, "name", json_object_new_string(as.name.c_str()));
341         json_object_object_add(json_tmp, "role", json_object_new_string(as.role.c_str()));
342         json_object_array_add(json_areas, json_tmp);
343     }
344
345     json_object_object_add(*json_out, "name", json_object_new_string(layer_name));
346     json_object_object_add(*json_out, "changed", json_object_new_boolean(changed));
347     json_object_object_add(*json_out, "areas", json_areas);
348 }
349
350 void PolicyManager::updateState(int event_id)
351 {
352     this->updateModeState();
353     this->updateLayer(event_id);
354 }
355
356 void PolicyManager::updateModeState()
357 {
358     int car_state_no;
359     std::string car_state;
360     bool changed;
361
362     // Store previous layers
363     this->prv_car_elements = this->crr_car_elements;
364
365     // Update car elements
366     HMI_DEBUG(">>> CAR ELEMENTS");
367     for (int car_ele_no = StmCarElementNoMin;
368          car_ele_no <= StmCarElementNoMax; car_ele_no++)
369     {
370         const char *car_ele_name = kStmCarElementName[car_ele_no];
371
372         car_state_no = this->p_crr_state->car_element[car_ele_no].state;
373         car_state = kStmCarElementStateNameList[car_ele_no][car_state_no];
374         changed = (this->p_crr_state->car_element[car_ele_no].changed) ? true : false;
375
376         this->crr_car_elements[car_ele_name].state = car_state;
377         this->crr_car_elements[car_ele_name].changed = changed;
378
379         HMI_DEBUG(">>> >>> NAME: %s", car_ele_name);
380         HMI_DEBUG(">>> >>> >>> STATE:%s", car_state.c_str());
381         HMI_DEBUG(">>> >>> >>> CHANGED:%s", (changed) ? "true" : "false");
382     }
383 }
384
385 void PolicyManager::updateLayer(int event_id)
386 {
387     for (int layer_no = StmLayerNoMin;
388          layer_no <= StmLayerNoMax; layer_no++)
389     {
390         HMI_DEBUG(">>> LAYER:%s CHANGED:%d LAYOUT:%s",
391                   kStmLayerName[layer_no], this->p_crr_state->layer[layer_no].changed,
392                   kStmLayoutName[this->p_crr_state->layer[layer_no].state]);
393     }
394
395     // Store previous layers
396     this->prv_layers = this->crr_layers;
397
398     // Store previous role history
399     this->prv_invisible_role_history = this->crr_invisible_role_history;
400
401     // Update layers
402     for (int layer_no = StmLayerNoMin;
403          layer_no <= StmLayerNoMax; layer_no++)
404     {
405         const char *layer_name = kStmLayerName[layer_no];
406
407         // If restriction mode is changed to mode2 on,
408         // store current state for state of restriction mode off
409         if (this->changedRestrictionModeTo2On() ||
410             this->changedAccelPedalOffToOn())   // Control by Accel
411             // this->changedLightstatusBrakeOnToOff())   // Control by Brake
412         {
413             HMI_DEBUG("Store current state for state of restriction mode off");
414             this->prv_layers_car_stop[layer_name] = this->crr_layers[layer_name];
415         }
416
417         // This layer is changed?
418         int changed = this->p_crr_state->layer[layer_no].changed;
419         if (changed)
420         {
421             HMI_DEBUG(">>>>>>>>>> Update layout of layer:%s", layer_name);
422
423             // Get current layout name of this layer
424             int crr_layout_state_no = this->p_crr_state->layer[layer_no].state;
425             std::string crr_layout_name = std::string(kStmLayoutName[crr_layout_state_no]);
426
427             LayoutState crr_layout_state;
428             changed = this->updateLayout(event_id, layer_no,
429                                          crr_layout_name, crr_layout_state);
430
431             // Update current layout of this layer
432             this->crr_layers[layer_name].layout_state = crr_layout_state;
433         }
434         else
435         {
436             int category_no = STM_GET_CATEGORY_FROM_ID(event_id);
437             std::string req_ctg = kStmCategoryName[category_no];
438             std::string req_role = this->req_role_list[event_id];
439             for (const auto &ctg : this->layer2categories[layer_name])
440             {
441                 if (ctg == req_ctg)
442                 {
443                     // If layer is not changed and requested role is in this layer,
444                     // push requested role to history stack
445                     // because the application which has this role have been started
446                     HMI_DEBUG("Add requested role to history "
447                               "because the application which has this role have been started");
448                     this->pushInvisibleRoleHistory(req_ctg, req_role);
449                 }
450             }
451         }
452
453         // Update changed flag
454         this->crr_layers[layer_name].changed = (changed) ? true : false;
455     }
456
457     // Erase role for the event_id from list
458     this->req_role_list.erase(event_id);
459
460     HMI_DEBUG(">>>>>>>>>> DUMP LAYERS (BEFORE)");
461     this->dumpLayerState(this->prv_layers);
462
463     HMI_DEBUG(">>>>>>>>>> DUMP LAYERS (AFTER)");
464     this->dumpLayerState(this->crr_layers);
465
466     this->dumpInvisibleRoleHistory();
467 }
468
469 int PolicyManager::updateLayout(int event_id, int layer_no,
470                                 std::string crr_layout_name, LayoutState &crr_layout_state)
471 {
472     int changed = 1;
473
474     int event_no = STM_GET_EVENT_FROM_ID(event_id);
475     int category_no = STM_GET_CATEGORY_FROM_ID(event_id);
476     int area_no = STM_GET_AREA_FROM_ID(event_id);
477
478     std::string req_evt = kStmEventName[event_no];
479     std::string req_ctg = kStmCategoryName[category_no];
480     std::string req_area = kStmAreaName[area_no];
481     std::string req_role = this->req_role_list[event_id];
482
483     const char *layer_name = kStmLayerName[layer_no];
484
485     // Get previous layout name of this layer
486     LayoutState prv_layout_state = this->prv_layers[layer_name].layout_state;
487     std::string prv_layout_name = prv_layout_state.name;
488
489     if (this->changedRestrictionMode2OnToOther() ||
490         this->changedAccelPedalOnToOff())   // Control by Accel
491         // this->changedLightstatusBrakeOffToOn())   // Control by Brake
492     {
493         // If restriction mode is changed from mode2 -> mode1,
494         // restore state of restriction mode off
495         HMI_DEBUG("Restriction mode is changed from mode2 -> mode1, so restore state of restriction mode off");
496         crr_layout_state = this->prv_layers_car_stop[layer_name].layout_state;
497         crr_layout_name = crr_layout_state.name;
498         if ((prv_layout_name == crr_layout_name) &&
499             (kStmAreaName[StmAreaNoNone] == crr_layout_name))
500         {
501             changed = 0;
502         }
503         else
504         {
505             // If the roles which is exist in previous layout is not in current,
506             // push to role history
507             for (const auto &prv_as : prv_layout_state.area_list)
508             {
509                 for (const auto &crr_as : crr_layout_state.area_list)
510                 {
511                     if (prv_as.role == crr_as.role)
512                         break;
513                 }
514
515                 this->pushInvisibleRoleHistory(prv_as.category, prv_as.role);
516             }
517         }
518     }
519     else if ((prv_layout_name == crr_layout_name) &&
520         (kStmLayoutName[StmLayoutNoNone] == crr_layout_name))
521     {
522         // If previous and current layout are none
523         // Copy previous layout state for current
524         crr_layout_state = prv_layout_state;
525         changed = 0;
526     }
527     else
528     {
529         crr_layout_state = prv_layout_state;
530         changed = 1;
531
532         HMI_DEBUG("-- layout name previous:%s current:%s",
533                   prv_layout_name.c_str(), crr_layout_name.c_str());
534         if (prv_layout_name == crr_layout_name)
535         {
536             HMI_DEBUG("---- Previous layout is same with current");
537         }
538         else
539         {
540             // If previous layout is NOT same with current,
541             // current areas is set with default value
542             HMI_DEBUG("---- Previous layout is NOT same with current");
543             crr_layout_state.name = this->default_layouts[crr_layout_name].name;
544             crr_layout_state.category_num = this->default_layouts[crr_layout_name].category_num;
545             crr_layout_state.area_list = this->default_layouts[crr_layout_name].area_list;
546         }
547
548         // Create candidate list
549         std::map<std::string, AreaList> cand_list;
550         // for (int ctg_no = StmCtgNoMin;
551         //      ctg_no <= StmCtgNoMax; ctg_no++)
552         // {
553         for (const auto &ctg : this->layer2categories[layer_name])
554         {
555             // if (ctg_no == StmCtgNoNone)
556             // {
557             //     continue;
558             // }
559
560             // const char *ctg = kStmCategoryName[ctg_no];
561             HMI_DEBUG("-- Create candidate list for ctg:%s", ctg.c_str());
562
563             AreaList tmp_cand_list;
564             int candidate_num = 0;
565             int blank_num = crr_layout_state.category_num[ctg];
566
567             // If requested event is "activate"
568             // and there are requested category and area,
569             // update area with requested role in current layout.
570             bool request_for_this_layer = false;
571             std::string used_role = "";
572             if ((ctg == req_ctg) && ("activate" == req_evt))
573             {
574                 HMI_DEBUG("---- Requested event is activate");
575                 for (AreaState &as : crr_layout_state.area_list)
576                 {
577                     if (as.category == req_ctg)
578                     {
579                         request_for_this_layer = true;
580
581                         if (as.name == req_area)
582                         {
583                             as.role = req_role;
584                             used_role = req_role;
585                             blank_num--;
586                             HMI_DEBUG("------ Update current layout: area:%s category:%s role:%s",
587                                       as.name.c_str(), as.category.c_str(), as.role.c_str());
588                             break;
589                         }
590                     }
591                 }
592             }
593
594             // Create candidate list for category from the previous displayed categories
595             for (AreaState area_state : prv_layout_state.area_list)
596             {
597                 if ((ctg == area_state.category) &&
598                     (used_role != area_state.role))
599                 {
600                     // If there is the category
601                     // which is same with new category and not used for updating yet,
602                     // push it to list
603                     HMI_DEBUG("---- Push previous(category:%s role:%s) to candidate list",
604                               area_state.category.c_str(), area_state.role.c_str());
605                     tmp_cand_list.push_back(area_state);
606                     candidate_num++;
607                 }
608             }
609
610             // If NOT updated by requested area:
611             // there is not requested area in new layout,
612             // so push requested role to candidate list
613             if (request_for_this_layer && ("" == used_role))
614             {
615                 HMI_DEBUG("---- Push request(area:%s category:%s role:%s) to candidate list",
616                           req_area.c_str(), req_ctg.c_str(), req_role.c_str());
617                 AreaState area_state;
618                 area_state.name = req_area;
619                 area_state.category = req_ctg;
620                 area_state.role = req_role;
621                 tmp_cand_list.push_back(area_state);
622                 candidate_num++;
623             }
624
625             HMI_DEBUG("---- blank_num:%d candidate_num:%d", blank_num, candidate_num);
626
627             // Compare number of candidate/blank,
628             // And remove role in order of the oldest as necessary
629             if (candidate_num < blank_num)
630             {
631                 // Refer history stack
632                 // and add to the top of tmp_cand_list in order to the newest
633                 while (candidate_num != blank_num)
634                 {
635                     AreaState area_state;
636                     area_state.name = kStmAreaName[StmAreaNoNone];
637                     area_state.category = ctg;
638                     area_state.role = this->popInvisibleRoleHistory(ctg);
639                     if ("" == area_state.role)
640                     {
641                         HMI_ERROR("There is no role in history stack!!");
642                     }
643                     tmp_cand_list.push_back(area_state);
644                     HMI_DEBUG("------ Add role:%s to candidate list",
645                               area_state.role.c_str());
646                     candidate_num++;
647                 }
648             }
649             else if (candidate_num > blank_num)
650             {
651                 // Remove the oldest role from candidate list
652                 while (candidate_num != blank_num)
653                 {
654                     std::string removed_role = tmp_cand_list.begin()->role;
655                     HMI_DEBUG("------ Remove the oldest role:%s from candidate list",
656                               removed_role.c_str());
657                     tmp_cand_list.erase(tmp_cand_list.begin());
658                     candidate_num--;
659
660                     // Push removed data to history stack
661                     this->pushInvisibleRoleHistory(ctg, removed_role);
662
663                     // Remove from current layout
664                     for (AreaState &as : crr_layout_state.area_list)
665                     {
666                         if (as.role == removed_role)
667                         {
668                             as.role = "";
669                         }
670                     }
671                 }
672             }
673             else
674             { // (candidate_num == blank_num)
675                 // nop
676             }
677
678             cand_list[ctg] = tmp_cand_list;
679         }
680
681         // Update areas
682         HMI_DEBUG("-- Update areas by using candidate list");
683         for (AreaState &as : crr_layout_state.area_list)
684         {
685             HMI_DEBUG("---- Check area:%s category:%s role:%s",
686                       as.name.c_str(), as.category.c_str(), as.role.c_str());
687             if ("" == as.role)
688             {
689                 HMI_DEBUG("------ Update this area with role:%s",
690                           cand_list[as.category].begin()->role.c_str());
691                 as.role = cand_list[as.category].begin()->role;
692                 cand_list[as.category].erase(cand_list[as.category].begin());
693             }
694         }
695     }
696     return changed;
697 }
698
699 void PolicyManager::createOutputInformation(json_object **json_out)
700 {
701     json_object *json_tmp;
702
703     // Create car element information
704     // {
705     //     "car_elements": [
706     //     {
707     //         "parking_brake": {
708     //             "changed": <bool>,
709     //             "state": <const char*>
710     //         },
711     //         ...
712     //     },
713     json_object *json_car_ele = json_object_new_array();
714     const char *car_ele_name;
715     for (int car_ele_no = StmCarElementNoMin;
716          car_ele_no <= StmCarElementNoMax; car_ele_no++)
717     {
718         car_ele_name = kStmCarElementName[car_ele_no];
719         json_tmp = json_object_new_object();
720         this->addStateToJson(car_ele_name,
721                              this->crr_car_elements[car_ele_name].changed,
722                              this->crr_car_elements[car_ele_name].state,
723                              &json_tmp);
724         json_object_array_add(json_car_ele, json_tmp);
725     }
726     json_object_object_add(*json_out, "car_elements", json_car_ele);
727
728     // Create layout information
729     //
730     //     "layers": [
731     //     {
732     //         "homescreen": {
733     //             "changed": <bool>,
734     //             "areas": [
735     //             {
736     //                 "name":<const char*>,
737     //                 "role":<const char*>
738     //             }.
739     //             ...
740     //             ]
741     //         }
742     //     },
743     //     ...
744     json_object *json_layer = json_object_new_array();
745     const char *layer_name;
746     for (int layer_no = StmLayerNoMin;
747          layer_no <= StmLayerNoMax; layer_no++)
748     {
749         layer_name = kStmLayerName[layer_no];
750         json_tmp = json_object_new_object();
751         this->addStateToJson(layer_name,
752                              this->crr_layers[layer_name].changed,
753                              this->crr_layers[layer_name].layout_state.area_list,
754                              &json_tmp);
755         json_object_array_add(json_layer, json_tmp);
756     }
757     json_object_object_add(*json_out, "layers", json_layer);
758 }
759
760 void PolicyManager::controlTimerEvent()
761 {
762     // for ALS2018 (RestrictionMode = Running and after 3sec)
763     // if (this->p_crr_state->car_element[StmCarElementNoRunning].changed)
764     // {
765     //     if (StmRunningNoRun == this->p_crr_state->car_element[StmCarElementNoRunning].state)
766     //     {
767     //         // Set delay event(restriction mode on)
768     //         this->setStateTransitionProcessToSystemd(StmEvtNoRestrictionModeOn,
769     //                                                  3000, "");
770     //     }
771     //     else if (StmRunningNoStop ==
772     //              this->p_crr_state->car_element[StmCarElementNoRunning].state)
773     //     {
774     //         // Stop timer for restriction on event
775     //         if (this->event_source_list.find(StmEvtNoRestrictionModeOn) !=
776     //             this->event_source_list.end())
777     //         {
778     //             HMI_DEBUG("Stop timer for restriction on");
779     //             sd_event_source *event_source = this->event_source_list[StmEvtNoRestrictionModeOn];
780     //             int ret = sd_event_source_set_enabled(event_source, SD_EVENT_OFF);
781     //             if (0 > ret)
782     //             {
783     //                 HMI_ERROR("Failed to stop timer");
784     //             }
785     //         }
786
787     //         // Set event(restriction mode off)
788     //         this->setStateTransitionProcessToSystemd(StmEvtNoRestrictionModeOff, 0, "");
789     //     }
790     // }
791 }
792
793 int PolicyManager::transitionState(sd_event_source *source, void *data)
794 {
795     HMI_DEBUG(">>>>>>>>>> START STATE TRANSITION");
796
797     int event_id = *((int *)data);
798
799     int event_no, category_no, area_no;
800     event_no = STM_GET_EVENT_FROM_ID(event_id);
801     category_no = STM_GET_CATEGORY_FROM_ID(event_id);
802     area_no = STM_GET_AREA_FROM_ID(event_id);
803     HMI_DEBUG(">>>>>>>>>> EVENT:%s CATEGORY:%s AREA:%s",
804               kStmEventName[event_no],
805               kStmCategoryName[category_no],
806               kStmAreaName[area_no]);
807
808     // Store current state
809     *(this->p_prv_state) = *(this->p_crr_state);
810
811     // Transition state
812     int ret = stmTransitionState(event_id, this->p_crr_state);
813     if (0 > ret)
814     {
815         HMI_ERROR("Failed transition state");
816         if (nullptr != this->callback.onError)
817         {
818             json_object *json_out = json_object_new_object();
819             json_object_object_add(json_out, "message",
820                                    json_object_new_string("Failed to transition state"));
821             json_object_object_add(json_out, "event",
822                                    json_object_new_string(kStmEventName[event_no]));
823             json_object_object_add(json_out, "role",
824                                    json_object_new_string(this->req_role_list[event_id].c_str()));
825             json_object_object_add(json_out, "area",
826                                    json_object_new_string(kStmAreaName[area_no]));
827             this->callback.onError(json_out);
828             json_object_put(json_out);
829         }
830         return -1;
831     }
832
833     // Update state which is managed by PolicyManager
834     this->updateState(event_id);
835
836     // Create output information for ResourceManager
837     json_object *json_out = json_object_new_object();
838     this->createOutputInformation(&json_out);
839
840     // Notify changed state
841     if (nullptr != this->callback.onStateTransitioned)
842     {
843         this->callback.onStateTransitioned(json_out);
844     }
845
846     // Start/Stop timer events
847     this->controlTimerEvent();
848
849     // Release json_object
850     json_object_put(json_out);
851
852     // Release data
853     delete (int *)data;
854
855     // Destroy sd_event_source object
856     sd_event_source_unref(source);
857
858     // Remove event source from list
859     if (this->event_source_list.find(event_id) != this->event_source_list.end())
860     {
861         this->event_source_list.erase(event_id);
862     }
863
864     HMI_DEBUG(">>>>>>>>>> FINISH STATE TRANSITION");
865     return 0;
866 }
867
868 int PolicyManager::timerEvent(sd_event_source *source, uint64_t usec, void *data)
869 {
870     HMI_DEBUG("Call");
871
872     int ret = this->transitionState(source, data);
873     return ret;
874 }
875
876 int PolicyManager::setStateTransitionProcessToSystemd(int event_id, uint64_t delay_ms, std::string role)
877 {
878     struct sd_event_source *event_source;
879     HMI_DEBUG("event_id:0x%x delay:%d role:%s", event_id, delay_ms, role.c_str());
880
881     if (0 == delay_ms)
882     {
883         int ret = sd_event_add_defer(afb_daemon_get_event_loop(), &event_source,
884                                      &pm::transitionStateWrapper, new int(event_id));
885         if (0 > ret)
886         {
887             HMI_ERROR("Faild to sd_event_add_defer: errno:%d", ret);
888             return -1;
889         }
890     }
891     else
892     {
893         // Get current time
894         struct timespec time_spec;
895         clock_gettime(CLOCK_BOOTTIME, &time_spec);
896
897         // Calculate timer fired time
898         uint64_t usec = (time_spec.tv_sec * 1000000) + (time_spec.tv_nsec / 1000) + (delay_ms * 1000);
899
900         // Set timer
901         int ret = sd_event_add_time(afb_daemon_get_event_loop(), &event_source,
902                                     CLOCK_BOOTTIME, usec, 1,
903                                     &pm::timerEventWrapper, new int(event_id));
904         if (0 > ret)
905         {
906             HMI_ERROR("Faild to sd_event_add_time: errno:%d", ret);
907             return -1;
908         }
909     }
910     // Store event source
911     this->event_source_list[event_id] = event_source;
912     // Store requested role
913     this->req_role_list[event_id] = role;
914     return 0;
915 }
916
917 bool PolicyManager::changedRestrictionModeTo2On()
918 {
919     // TODO: If possible thie process should be include in zipc stm in the future
920     if (this->p_crr_state->car_element[StmCarElementNoRestrictionMode].changed &&
921         (StmRestrictionModeSttNoOn != this->p_prv_state->car_element[StmCarElementNoRestrictionMode].state) &&
922         (StmRestrictionModeSttNoOn == this->p_crr_state->car_element[StmCarElementNoRestrictionMode].state))
923     {
924         return true;
925     }
926     return false;
927 }
928
929 bool PolicyManager::changedRestrictionMode2OnToOther()
930 {
931     // TODO: If possible thie process should be include in zipc stm in the future
932     if (this->p_crr_state->car_element[StmCarElementNoRestrictionMode].changed &&
933         (StmRestrictionModeSttNoOn == this->p_prv_state->car_element[StmCarElementNoRestrictionMode].state) &&
934         (StmRestrictionModeSttNoOn != this->p_crr_state->car_element[StmCarElementNoRestrictionMode].state))
935     {
936         return true;
937     }
938     return false;
939 }
940
941 // bool PolicyManager::changedLightstatusBrakeOffToOn()
942 // {
943 //     // TODO: For master
944 //     //       If possible thie process should be include in zipc stm in the future
945 //     if (("master" == this->ecu_name) &&
946 //         this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].changed &&
947 //         (StmLightstatusBrakeSttNoOff == this->p_prv_state->car_element[StmCarElementNoLightstatusBrake].state) &&
948 //         (StmLightstatusBrakeSttNoOn  == this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].state))
949 //     {
950 //         return true;
951 //     }
952 //     return false;
953 // }
954
955 // bool PolicyManager::changedLightstatusBrakeOnToOff()
956 // {
957 //     // TODO: For master
958 //     //       If possible thie process should be include in zipc stm in the future
959 //     if (("master" == this->ecu_name) &&
960 //         this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].changed &&
961 //         (StmLightstatusBrakeSttNoOn == this->p_prv_state->car_element[StmCarElementNoLightstatusBrake].state) &&
962 //         (StmLightstatusBrakeSttNoOff  == this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].state))
963 //     {
964 //         return true;
965 //     }
966 //     return false;
967 // }
968
969 bool PolicyManager::changedAccelPedalOffToOn()
970 {
971     // TODO: For master
972     //       If possible thie process should be include in zipc stm in the future
973     if (("master" == this->ecu_name) &&
974         this->p_crr_state->car_element[StmCarElementNoAccelPedal].changed &&
975         (StmAccelPedalSttNoOff == this->p_prv_state->car_element[StmCarElementNoAccelPedal].state) &&
976         (StmAccelPedalSttNoOn  == this->p_crr_state->car_element[StmCarElementNoAccelPedal].state))
977     {
978         return true;
979     }
980     return false;
981 }
982
983 bool PolicyManager::changedAccelPedalOnToOff()
984 {
985     // TODO: For master
986     //       If possible thie process should be include in zipc stm in the future
987     if (("master" == this->ecu_name) &&
988         this->p_crr_state->car_element[StmCarElementNoAccelPedal].changed &&
989         (StmAccelPedalSttNoOn == this->p_prv_state->car_element[StmCarElementNoAccelPedal].state) &&
990         (StmAccelPedalSttNoOff  == this->p_crr_state->car_element[StmCarElementNoAccelPedal].state))
991     {
992         return true;
993     }
994     return false;
995 }
996
997 int PolicyManager::loadRolesConfigFile()
998 {
999     std::string file_name;
1000
1001     // Get afm application installed dir
1002     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1003     HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
1004
1005     if (!afm_app_install_dir)
1006     {
1007         HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
1008     }
1009     else
1010     {
1011         file_name = std::string(afm_app_install_dir) + std::string(pm::kPathRolesConfigFile);
1012     }
1013
1014     // Load roles config file
1015     json_object *json_obj;
1016     int ret = this->inputJsonFilie(file_name.c_str(), &json_obj);
1017     if (0 > ret)
1018     {
1019         HMI_ERROR("Could not open %s, so use default role information", pm::kPathRolesConfigFile);
1020         json_obj = json_tokener_parse(kDefaultRolesConfig);
1021     }
1022     HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
1023
1024     // Parse ecus
1025     json_object *json_cfg;
1026     if (!json_object_object_get_ex(json_obj, "ecus", &json_cfg))
1027     {
1028         HMI_ERROR("Parse Error!!");
1029         return -1;
1030     }
1031
1032     int num_ecu = json_object_array_length(json_cfg);
1033     HMI_DEBUG("json_cfg(ecus) len:%d", num_ecu);
1034
1035     const char* c_ecu_name;
1036     json_object *json_ecu;
1037     for (int i = 0; i < num_ecu; i++)
1038     {
1039         json_ecu= json_object_array_get_idx(json_cfg, i);
1040
1041         c_ecu_name = this->getStringFromJson(json_ecu, "name");
1042         if (nullptr == c_ecu_name)
1043         {
1044             HMI_ERROR("Parse Error!!");
1045             return -1;
1046         }
1047
1048         if (std::string(c_ecu_name) == this->ecu_name)
1049         {
1050             break;
1051         }
1052         else
1053         {
1054             json_ecu = nullptr;
1055         }
1056     }
1057
1058     if (!json_ecu)
1059     {
1060         HMI_ERROR("Areas for ecu:%s is NOT exist!!", this->ecu_name.c_str());
1061         return -1;
1062     }
1063
1064     // Parse roles
1065     json_object *json_roles;
1066     if (!json_object_object_get_ex(json_ecu, "roles", &json_roles))
1067     {
1068         HMI_ERROR("Parse Error!!");
1069         return -1;
1070     }
1071
1072     int len = json_object_array_length(json_roles);
1073     HMI_DEBUG("json_cfg len:%d", len);
1074     HMI_DEBUG("json_cfg dump:%s", json_object_get_string(json_roles));
1075
1076     json_object *json_tmp;
1077     const char *category;
1078     const char *roles;
1079     const char *areas;
1080     const char *layer;
1081     for (int i = 0; i < len; i++)
1082     {
1083         json_tmp = json_object_array_get_idx(json_roles, i);
1084
1085         category = this->getStringFromJson(json_tmp, "category");
1086         roles = this->getStringFromJson(json_tmp, "role");
1087         areas = this->getStringFromJson(json_tmp, "area");
1088         layer = this->getStringFromJson(json_tmp, "layer");
1089
1090         if ((nullptr == category) || (nullptr == roles) ||
1091             (nullptr == areas) || (nullptr == layer))
1092         {
1093             HMI_ERROR("Parse Error!!");
1094             return -1;
1095         }
1096
1097         // Parse roles by '|'
1098         std::vector<std::string> vct_roles;
1099         vct_roles = this->parseString(std::string(roles), '|');
1100
1101         // Parse areas by '|'
1102         Areas vct_areas;
1103         vct_areas = this->parseString(std::string(areas), '|');
1104
1105         // Set role, category, areas
1106         for (auto itr = vct_roles.begin(); itr != vct_roles.end(); ++itr)
1107         {
1108             this->role2category[*itr] = std::string(category);
1109         }
1110         this->category2role[category] = std::string(roles);
1111         this->category2areas[category] = vct_areas;
1112         this->layer2categories[layer].push_back(category);
1113
1114         // TODO: For run-by-default applications, set history in advance
1115         const char *auto_started_roles;
1116         auto_started_roles = this->getStringFromJson(json_tmp, "auto_started_roles");
1117         if (nullptr != auto_started_roles)
1118         {
1119             std::vector<std::string> vct_auto_started_roles;
1120             vct_auto_started_roles =
1121                 this->parseString(std::string(auto_started_roles), '|');
1122
1123             for (auto itr = vct_auto_started_roles.end() - 1;
1124                  itr >= vct_auto_started_roles.begin(); --itr)
1125             {
1126                 this->pushInvisibleRoleHistory(category, *itr);
1127             }
1128         }
1129     }
1130
1131     // Check
1132     HMI_DEBUG("Check role2category");
1133     for (const auto &x : this->role2category)
1134     {
1135         HMI_DEBUG("key:%s, val:%s", x.first.c_str(), x.second.c_str());
1136     }
1137
1138     HMI_DEBUG("Check category2role");
1139     for (const auto &x : this->category2role)
1140     {
1141         HMI_DEBUG("key:%s, val:%s", x.first.c_str(), x.second.c_str());
1142     }
1143
1144     HMI_DEBUG("Check category2areas");
1145     for (const auto &x : this->category2areas)
1146     {
1147         for (const auto &y : x.second)
1148         {
1149             HMI_DEBUG("key:%s, val:%s", x.first.c_str(), y.c_str());
1150         }
1151     }
1152
1153     HMI_DEBUG("Check layer2categories");
1154     for (const auto &x : this->layer2categories)
1155     {
1156         for (const auto &y : x.second)
1157         {
1158             HMI_DEBUG("key:%s, val:%s", x.first.c_str(), y.c_str());
1159         }
1160     }
1161     return 0;
1162 }
1163
1164 int PolicyManager::loadLayoutsConfigFile()
1165 {
1166     HMI_DEBUG("Call");
1167
1168     // Get afm application installed dir
1169     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1170     HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
1171
1172     std::string file_name;
1173     if (!afm_app_install_dir)
1174     {
1175         HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
1176     }
1177     else
1178     {
1179         file_name = std::string(afm_app_install_dir) + std::string(pm::kPathLayoutsConfigFile);
1180     }
1181
1182     // Load states config file
1183     json_object *json_obj;
1184     int ret = this->inputJsonFilie(file_name.c_str(), &json_obj);
1185     if (0 > ret)
1186     {
1187         HMI_DEBUG("Could not open %s, so use default layout information", pm::kPathLayoutsConfigFile);
1188         json_obj = json_tokener_parse(kDefaultLayoutsConfig);
1189     }
1190     HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
1191
1192     // Parse ecus
1193     json_object *json_cfg;
1194     if (!json_object_object_get_ex(json_obj, "ecus", &json_cfg))
1195     {
1196         HMI_ERROR("Parse Error!!");
1197         return -1;
1198     }
1199
1200     int num_ecu = json_object_array_length(json_cfg);
1201     HMI_DEBUG("json_cfg(ecus) len:%d", num_ecu);
1202
1203     const char* c_ecu_name;
1204     json_object *json_ecu;
1205     for (int i = 0; i < num_ecu; i++)
1206     {
1207         json_ecu= json_object_array_get_idx(json_cfg, i);
1208
1209         c_ecu_name = this->getStringFromJson(json_ecu, "name");
1210         if (nullptr == c_ecu_name)
1211         {
1212             HMI_ERROR("Parse Error!!");
1213             return -1;
1214         }
1215
1216         if (std::string(c_ecu_name) == this->ecu_name)
1217         {
1218             break;
1219         }
1220         else
1221         {
1222             json_ecu = nullptr;
1223         }
1224     }
1225
1226     if (!json_ecu)
1227     {
1228         HMI_ERROR("Areas for ecu:%s is NOT exist!!", this->ecu_name.c_str());
1229         return -1;
1230     }
1231
1232     // Perse layouts
1233     HMI_DEBUG("Perse layouts");
1234     json_object *json_layouts;
1235     if (!json_object_object_get_ex(json_ecu, "layouts", &json_layouts))
1236     {
1237         HMI_ERROR("Parse Error!!");
1238         return -1;
1239     }
1240
1241     int len = json_object_array_length(json_layouts);
1242     HMI_DEBUG("json_layouts len:%d", len);
1243     HMI_DEBUG("json_layouts dump:%s", json_object_get_string(json_layouts));
1244
1245     const char *layout;
1246     const char *role;
1247     const char *category;
1248     for (int i = 0; i < len; i++)
1249     {
1250         json_object *json_tmp = json_object_array_get_idx(json_layouts, i);
1251
1252         layout = this->getStringFromJson(json_tmp, "name");
1253         if (nullptr == layout)
1254         {
1255             HMI_ERROR("Parse Error!!");
1256             return -1;
1257         }
1258         HMI_DEBUG("> layout:%s", layout);
1259
1260         json_object *json_area_array;
1261         if (!json_object_object_get_ex(json_tmp, "areas", &json_area_array))
1262         {
1263             HMI_ERROR("Parse Error!!");
1264             return -1;
1265         }
1266
1267         int len_area = json_object_array_length(json_area_array);
1268         HMI_DEBUG("json_area_array len:%d", len_area);
1269         HMI_DEBUG("json_area_array dump:%s", json_object_get_string(json_area_array));
1270
1271         LayoutState layout_state;
1272         AreaState area_state;
1273         std::map<std::string, int> category_num;
1274         for (int ctg_no = StmCtgNoMin;
1275              ctg_no <= StmCtgNoMax; ctg_no++)
1276         {
1277             const char *ctg_name = kStmCategoryName[ctg_no];
1278             category_num[ctg_name] = 0;
1279         }
1280
1281         for (int j = 0; j < len_area; j++)
1282         {
1283             json_object *json_area = json_object_array_get_idx(json_area_array, j);
1284
1285             // Get area name
1286             const char *area = this->getStringFromJson(json_area, "name");
1287             if (nullptr == area)
1288             {
1289                 HMI_ERROR("Parse Error!!");
1290                 return -1;
1291             }
1292             area_state.name = std::string(area);
1293             HMI_DEBUG(">> area:%s", area);
1294
1295             // Get app attribute of the area
1296             category = this->getStringFromJson(json_area, "category");
1297             if (nullptr == category)
1298             {
1299                 HMI_ERROR("Parse Error!!");
1300                 return -1;
1301             }
1302             area_state.category = std::string(category);
1303             category_num[category]++;
1304             HMI_DEBUG(">>> category:%s", category);
1305
1306             role = this->getStringFromJson(json_area, "role");
1307             if (nullptr != role)
1308             {
1309                 // Role is NOT essential here
1310                 area_state.role = std::string(role);
1311             }
1312             else
1313             {
1314                 area_state.role = std::string("");
1315             }
1316             HMI_DEBUG(">>> role:%s", role);
1317
1318             layout_state.area_list.push_back(area_state);
1319         }
1320
1321         layout_state.name = layout;
1322         layout_state.category_num = category_num;
1323         this->default_layouts[layout] = layout_state;
1324     }
1325
1326     // initialize for none layout
1327     LayoutState none_layout_state;
1328     memset(&none_layout_state, 0, sizeof(none_layout_state));
1329     none_layout_state.name = "none";
1330     this->default_layouts["none"] = none_layout_state;
1331
1332     // Check
1333     for (auto itr_layout = this->default_layouts.begin();
1334          itr_layout != this->default_layouts.end(); ++itr_layout)
1335     {
1336         HMI_DEBUG(">>> layout:%s", itr_layout->first.c_str());
1337
1338         for (auto itr_area = itr_layout->second.area_list.begin();
1339              itr_area != itr_layout->second.area_list.end(); ++itr_area)
1340         {
1341             HMI_DEBUG(">>> >>> area    :%s", itr_area->name.c_str());
1342             HMI_DEBUG(">>> >>> category:%s", itr_area->category.c_str());
1343             HMI_DEBUG(">>> >>> role    :%s", itr_area->role.c_str());
1344         }
1345     }
1346
1347     // Release json_object
1348     json_object_put(json_obj);
1349
1350     return 0;
1351 }
1352
1353 void PolicyManager::pushInvisibleRoleHistory(std::string category, std::string role)
1354 {
1355     auto i = std::remove_if(this->crr_invisible_role_history[category].begin(),
1356                             this->crr_invisible_role_history[category].end(),
1357                             [role](std::string x) { return (role == x); });
1358
1359     if (this->crr_invisible_role_history[category].end() != i)
1360     {
1361         this->crr_invisible_role_history[category].erase(i);
1362     }
1363
1364     this->crr_invisible_role_history[category].push_back(role);
1365
1366     if (pm::kInvisibleRoleHistoryNum < crr_invisible_role_history[category].size())
1367     {
1368         this->crr_invisible_role_history[category].erase(
1369             this->crr_invisible_role_history[category].begin());
1370     }
1371 }
1372
1373 std::string PolicyManager::popInvisibleRoleHistory(std::string category)
1374 {
1375     std::string role;
1376     if (crr_invisible_role_history[category].empty())
1377     {
1378         role = "";
1379     }
1380     else
1381     {
1382         role = this->crr_invisible_role_history[category].back();
1383         this->crr_invisible_role_history[category].pop_back();
1384     }
1385     return role;
1386 }
1387
1388 const char *PolicyManager::getStringFromJson(json_object *obj, const char *key)
1389 {
1390     json_object *tmp;
1391     if (!json_object_object_get_ex(obj, key, &tmp))
1392     {
1393         HMI_DEBUG("Not found key \"%s\"", key);
1394         return nullptr;
1395     }
1396
1397     return json_object_get_string(tmp);
1398 }
1399
1400 int PolicyManager::inputJsonFilie(const char *file, json_object **obj)
1401 {
1402     const int input_size = 128;
1403     int ret = -1;
1404
1405     HMI_DEBUG("Input file: %s", file);
1406
1407     // Open json file
1408     FILE *fp = fopen(file, "rb");
1409     if (nullptr == fp)
1410     {
1411         HMI_ERROR("Could not open file");
1412         return ret;
1413     }
1414
1415     // Parse file data
1416     struct json_tokener *tokener = json_tokener_new();
1417     enum json_tokener_error json_error;
1418     char buffer[input_size];
1419     int block_cnt = 1;
1420     while (1)
1421     {
1422         size_t len = fread(buffer, sizeof(char), input_size, fp);
1423         *obj = json_tokener_parse_ex(tokener, buffer, len);
1424         if (nullptr != *obj)
1425         {
1426             HMI_DEBUG("File input is success");
1427             ret = 0;
1428             break;
1429         }
1430
1431         json_error = json_tokener_get_error(tokener);
1432         if ((json_tokener_continue != json_error) || (input_size > len))
1433         {
1434             HMI_ERROR("Failed to parse file (byte:%d err:%s)",
1435                       (input_size * block_cnt), json_tokener_error_desc(json_error));
1436             HMI_ERROR("\n%s", buffer);
1437             *obj = nullptr;
1438             break;
1439         }
1440         block_cnt++;
1441     }
1442
1443     // Close json file
1444     fclose(fp);
1445
1446     // Free json_tokener
1447     json_tokener_free(tokener);
1448
1449     return ret;
1450 }
1451
1452 void PolicyManager::dumpLayerState(std::unordered_map<std::string, LayerState> &layers)
1453 {
1454     HMI_DEBUG("-------------------------------------------------------------------------------------------------------");
1455     HMI_DEBUG("|%-15s|%s|%-20s|%-20s|%-20s|%-20s|",
1456               "LAYER", "C", "LAYOUT", "AREA", "CATEGORY", "ROLE");
1457     for (const auto &itr : layers)
1458     {
1459         LayerState ls = itr.second;
1460         const char* layer   = ls.name.c_str();
1461         const char* changed = (ls.changed) ? "T" : "f";
1462         const char* layout  = ls.layout_state.name.c_str();
1463         bool first = true;
1464         for (const auto &as : ls.layout_state.area_list)
1465         {
1466             if (first)
1467             {
1468                 first = false;
1469                 HMI_DEBUG("|%-15s|%1s|%-20s|%-20s|%-20s|%-20s|",
1470                           layer, changed, layout,
1471                           as.name.c_str(), as.category.c_str(), as.role.c_str());
1472             }
1473             else
1474                 HMI_DEBUG("|%-15s|%1s|%-20s|%-20s|%-20s|%-20s|",
1475                           "", "", "", as.name.c_str(), as.category.c_str(), as.role.c_str());
1476         }
1477     }
1478     HMI_DEBUG("-------------------------------------------------------------------------------------------------------");
1479 }
1480
1481 void PolicyManager::dumpInvisibleRoleHistory()
1482 {
1483     HMI_DEBUG(">>>>>>>>>> DUMP INVISIBLE ROLE HISTORY ( category [older > newer] )");
1484     for (int ctg_no = StmCtgNoMin; ctg_no <= StmCtgNoMax; ctg_no++)
1485     {
1486         if (ctg_no == StmCtgNoNone)
1487             continue;
1488
1489         std::string category = std::string(kStmCategoryName[ctg_no]);
1490
1491         std::string str = category + " [ ";
1492         for (const auto &i : this->crr_invisible_role_history[category])
1493             str += (i + " > ");
1494
1495         str += "]";
1496         HMI_DEBUG("%s", str.c_str());
1497     }
1498 }
1499
1500 std::vector<std::string> PolicyManager::parseString(std::string str, char delimiter)
1501 {
1502     // Parse string by delimiter
1503     std::vector<std::string> vct;
1504     std::stringstream ss{str};
1505     std::string buf;
1506     while (std::getline(ss, buf, delimiter))
1507     {
1508         if (!buf.empty())
1509         {
1510             // Delete space and push back to vector
1511             vct.push_back(this->deleteSpace(buf));
1512         }
1513     }
1514     return vct;
1515 }
1516
1517 std::string PolicyManager::deleteSpace(std::string str)
1518 {
1519     std::string ret = str;
1520     size_t pos;
1521     while ((pos = ret.find_first_of(" ")) != std::string::npos)
1522     {
1523         ret.erase(pos, 1);
1524     }
1525     return ret;
1526 }
1527
1528 const char *PolicyManager::kDefaultRolesConfig = "{ \
1529     \"roles\":[ \
1530     { \
1531         \"category\": \"homescreen\", \
1532         \"role\": \"homescreen\", \
1533         \"area\": \"fullscreen\", \
1534     }, \
1535     { \
1536         \"category\": \"map\", \
1537         \"role\": \"map\", \
1538         \"area\": \"normal.full | split.main\", \
1539     }, \
1540     { \
1541         \"category\": \"general\", \
1542         \"role\": \"launcher | poi | browser | sdl | mixer | radio | hvac | debug | phone | video | music\", \
1543         \"area\": \"normal.full\", \
1544     }, \
1545     { \
1546         \"category\": \"system\", \
1547         \"role\": \"settings | dashboard\", \
1548         \"area\": \"normal.full\", \
1549     }, \
1550     { \
1551         \"category\": \"software_keyboard\", \
1552         \"role\": \"software_keyboard\", \
1553         \"area\": \"software_keyboard\", \
1554     }, \
1555     { \
1556         \"category\": \"restriction\", \
1557         \"role\": \"restriction\", \
1558         \"area\": \"restriction.normal | restriction.split.main | restriction.split.sub\", \
1559     }, \
1560     { \
1561         \"category\": \"pop_up\", \
1562         \"role\": \"pop_up\", \
1563         \"area\": \"on_screen\", \
1564     }, \
1565     { \
1566         \"category\": \"system_alert\", \
1567         \"role\": \"system_alert\", \
1568         \"area\": \"on_screen\", \
1569     } \
1570     ] \
1571 }";
1572
1573 const char *PolicyManager::kDefaultLayoutsConfig = "{ \
1574     \"layouts\": [ \
1575         { \
1576             \"name\": \"homescreen\", \
1577             \"layer\": \"far_homescreen\", \
1578             \"areas\": [ \
1579                 { \
1580                     \"name\": \"fullscreen\", \
1581                     \"category\": \"homescreen\" \
1582                 } \
1583             ] \
1584         }, \
1585         { \
1586             \"name\": \"map.normal\", \
1587             \"layer\": \"apps\", \
1588             \"areas\": [ \
1589                 { \
1590                     \"name\": \"normal.full\", \
1591                     \"category\": \"map\" \
1592                 } \
1593             ] \
1594         }, \
1595         { \
1596             \"name\": \"map.split\", \
1597             \"layer\": \"apps\", \
1598             \"areas\": [ \
1599                 { \
1600                     \"name\": \"split.main\", \
1601                     \"category\": \"map\" \
1602                 }, \
1603                 { \
1604                     \"name\": \"split.sub\", \
1605                     \"category\": \"splitable\" \
1606                 } \
1607             ] \
1608         }, \
1609         { \
1610             \"name\": \"map.fullscreen\", \
1611             \"layer\": \"apps\", \
1612             \"areas\": [ \
1613                 { \
1614                     \"name\": \"fullscreen\", \
1615                     \"category\": \"map\" \
1616                 } \
1617             ] \
1618         }, \
1619         { \
1620             \"name\": \"splitable.normal\", \
1621             \"layer\": \"apps\", \
1622             \"areas\": [ \
1623                 { \
1624                     \"name\": \"normal.full\", \
1625                     \"category\": \"splitable\" \
1626                 } \
1627             ] \
1628         }, \
1629         { \
1630             \"name\": \"splitable.split\", \
1631             \"layer\": \"apps\", \
1632             \"areas\": [ \
1633                 { \
1634                     \"name\": \"split.main\", \
1635                     \"category\": \"splitable\" \
1636                 }, \
1637                 { \
1638                     \"name\": \"split.sub\", \
1639                     \"category\": \"splitable\" \
1640                 } \
1641             ] \
1642         }, \
1643         { \
1644             \"name\": \"general.normal\", \
1645             \"layer\": \"apps\", \
1646             \"areas\": [ \
1647                 { \
1648                     \"name\": \"normal.full\", \
1649                     \"category\": \"general\" \
1650                 } \
1651             ] \
1652         }, \
1653         { \
1654             \"name\": \"system.normal\", \
1655             \"layer\": \"apps\", \
1656             \"areas\": [ \
1657                 { \
1658                     \"name\": \"normal.full\", \
1659                     \"category\": \"system\" \
1660                 } \
1661             ] \
1662         }, \
1663         { \
1664             \"name\": \"software_keyboard\", \
1665             \"layer\": \"near_homescreen\", \
1666             \"areas\": [ \
1667                 { \
1668                     \"name\": \"software_keyboard\", \
1669                     \"category\": \"software_keyboard\" \
1670                 } \
1671             ] \
1672         }, \
1673         { \
1674             \"name\": \"restriction.normal\", \
1675             \"layer\": \"restriction\", \
1676             \"areas\": [ \
1677                 { \
1678                     \"name\": \"restriction.normal\", \
1679                     \"category\": \"restriction\" \
1680                 } \
1681             ] \
1682         }, \
1683         { \
1684             \"name\": \"restriction.split.main\", \
1685             \"layer\": \"restriction\", \
1686             \"areas\": [ \
1687                 { \
1688                     \"name\": \"restriction.split.main\", \
1689                     \"category\": \"restriction\" \
1690                 } \
1691             ] \
1692         }, \
1693         { \
1694             \"name\": \"restriction.split.sub\", \
1695             \"layer\": \"restriction\", \
1696             \"areas\": [ \
1697                 { \
1698                     \"name\": \"restriction.split.sub\", \
1699                     \"category\": \"restriction\" \
1700                 } \
1701             ] \
1702         }, \
1703         { \
1704             \"name\": \"pop_up\", \
1705             \"layer\": \"on_screen\", \
1706             \"areas\": [ \
1707                 { \
1708                     \"name\": \"on_screen\", \
1709                     \"category\": \"pop_up\" \
1710                 } \
1711             ] \
1712         }, \
1713         { \
1714             \"name\": \"system_alert\", \
1715             \"layer\": \"on_screen\", \
1716             \"areas\": [ \
1717                 { \
1718                     \"name\": \"on_screen\", \
1719                     \"category\": \"system_alert\" \
1720                 } \
1721             ] \
1722         } \
1723     ] \
1724 }";