add source for ces2019
[apps/agl-service-windowmanager-2017.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->changedLightstatusBrakeOnToOff())
411         {
412             HMI_DEBUG("Store current state for state of restriction mode off");
413             this->prv_layers_car_stop[layer_name] = this->crr_layers[layer_name];
414         }
415
416         // This layer is changed?
417         int changed = this->p_crr_state->layer[layer_no].changed;
418         if (changed)
419         {
420             HMI_DEBUG(">>>>>>>>>> Update layout of layer:%s", layer_name);
421
422             // Get current layout name of this layer
423             int crr_layout_state_no = this->p_crr_state->layer[layer_no].state;
424             std::string crr_layout_name = std::string(kStmLayoutName[crr_layout_state_no]);
425
426             LayoutState crr_layout_state;
427             changed = this->updateLayout(event_id, layer_no,
428                                          crr_layout_name, crr_layout_state);
429
430             // Update current layout of this layer
431             this->crr_layers[layer_name].layout_state = crr_layout_state;
432         }
433         else
434         {
435             int category_no = STM_GET_CATEGORY_FROM_ID(event_id);
436             std::string req_ctg = kStmCategoryName[category_no];
437             std::string req_role = this->req_role_list[event_id];
438             for (const auto &ctg : this->layer2categories[layer_name])
439             {
440                 if (ctg == req_ctg)
441                 {
442                     // If layer is not changed and requested role is in this layer,
443                     // push requested role to history stack
444                     // because the application which has this role have been started
445                     HMI_DEBUG("Add requested role to history "
446                               "because the application which has this role have been started");
447                     this->pushInvisibleRoleHistory(req_ctg, req_role);
448                 }
449             }
450         }
451
452         // Update changed flag
453         this->crr_layers[layer_name].changed = (changed) ? true : false;
454     }
455
456     // Erase role for the event_id from list
457     this->req_role_list.erase(event_id);
458
459     HMI_DEBUG(">>>>>>>>>> DUMP LAYERS (BEFORE)");
460     this->dumpLayerState(this->prv_layers);
461
462     HMI_DEBUG(">>>>>>>>>> DUMP LAYERS (AFTER)");
463     this->dumpLayerState(this->crr_layers);
464
465     this->dumpInvisibleRoleHistory();
466 }
467
468 int PolicyManager::updateLayout(int event_id, int layer_no,
469                                 std::string crr_layout_name, LayoutState &crr_layout_state)
470 {
471     int changed = 1;
472
473     int event_no = STM_GET_EVENT_FROM_ID(event_id);
474     int category_no = STM_GET_CATEGORY_FROM_ID(event_id);
475     int area_no = STM_GET_AREA_FROM_ID(event_id);
476
477     std::string req_evt = kStmEventName[event_no];
478     std::string req_ctg = kStmCategoryName[category_no];
479     std::string req_area = kStmAreaName[area_no];
480     std::string req_role = this->req_role_list[event_id];
481
482     const char *layer_name = kStmLayerName[layer_no];
483
484     // Get previous layout name of this layer
485     LayoutState prv_layout_state = this->prv_layers[layer_name].layout_state;
486     std::string prv_layout_name = prv_layout_state.name;
487
488     if (this->changedRestrictionMode2OnToOther() ||
489         this->changedLightstatusBrakeOffToOn())
490     {
491         // If restriction mode is changed from mode2 -> mode1,
492         // restore state of restriction mode off
493         HMI_DEBUG("Restriction mode is changed from mode2 -> mode1, so restore state of restriction mode off");
494         crr_layout_state = this->prv_layers_car_stop[layer_name].layout_state;
495         crr_layout_name = crr_layout_state.name;
496         if ((prv_layout_name == crr_layout_name) &&
497             (kStmAreaName[StmAreaNoNone] == crr_layout_name))
498         {
499             changed = 0;
500         }
501         else
502         {
503             // If the roles which is exist in previous layout is not in current,
504             // push to role history
505             for (const auto &prv_as : prv_layout_state.area_list)
506             {
507                 for (const auto &crr_as : crr_layout_state.area_list)
508                 {
509                     if (prv_as.role == crr_as.role)
510                         break;
511                 }
512
513                 this->pushInvisibleRoleHistory(prv_as.category, prv_as.role);
514             }
515         }
516     }
517     else if ((prv_layout_name == crr_layout_name) &&
518         (kStmLayoutName[StmLayoutNoNone] == crr_layout_name))
519     {
520         // If previous and current layout are none
521         // Copy previous layout state for current
522         crr_layout_state = prv_layout_state;
523         changed = 0;
524     }
525     else
526     {
527         crr_layout_state = prv_layout_state;
528         changed = 1;
529
530         HMI_DEBUG("-- layout name previous:%s current:%s",
531                   prv_layout_name.c_str(), crr_layout_name.c_str());
532         if (prv_layout_name == crr_layout_name)
533         {
534             HMI_DEBUG("---- Previous layout is same with current");
535         }
536         else
537         {
538             // If previous layout is NOT same with current,
539             // current areas is set with default value
540             HMI_DEBUG("---- Previous layout is NOT same with current");
541             crr_layout_state.name = this->default_layouts[crr_layout_name].name;
542             crr_layout_state.category_num = this->default_layouts[crr_layout_name].category_num;
543             crr_layout_state.area_list = this->default_layouts[crr_layout_name].area_list;
544         }
545
546         // Create candidate list
547         std::map<std::string, AreaList> cand_list;
548         // for (int ctg_no = StmCtgNoMin;
549         //      ctg_no <= StmCtgNoMax; ctg_no++)
550         // {
551         for (const auto &ctg : this->layer2categories[layer_name])
552         {
553             // if (ctg_no == StmCtgNoNone)
554             // {
555             //     continue;
556             // }
557
558             // const char *ctg = kStmCategoryName[ctg_no];
559             HMI_DEBUG("-- Create candidate list for ctg:%s", ctg.c_str());
560
561             AreaList tmp_cand_list;
562             int candidate_num = 0;
563             int blank_num = crr_layout_state.category_num[ctg];
564
565             // If requested event is "activate"
566             // and there are requested category and area,
567             // update area with requested role in current layout.
568             bool request_for_this_layer = false;
569             std::string used_role = "";
570             if ((ctg == req_ctg) && ("activate" == req_evt))
571             {
572                 HMI_DEBUG("---- Requested event is activate");
573                 for (AreaState &as : crr_layout_state.area_list)
574                 {
575                     if (as.category == req_ctg)
576                     {
577                         request_for_this_layer = true;
578
579                         if (as.name == req_area)
580                         {
581                             as.role = req_role;
582                             used_role = req_role;
583                             blank_num--;
584                             HMI_DEBUG("------ Update current layout: area:%s category:%s role:%s",
585                                       as.name.c_str(), as.category.c_str(), as.role.c_str());
586                             break;
587                         }
588                     }
589                 }
590             }
591
592             // Create candidate list for category from the previous displayed categories
593             for (AreaState area_state : prv_layout_state.area_list)
594             {
595                 if ((ctg == area_state.category) &&
596                     (used_role != area_state.role))
597                 {
598                     // If there is the category
599                     // which is same with new category and not used for updating yet,
600                     // push it to list
601                     HMI_DEBUG("---- Push previous(category:%s role:%s) to candidate list",
602                               area_state.category.c_str(), area_state.role.c_str());
603                     tmp_cand_list.push_back(area_state);
604                     candidate_num++;
605                 }
606             }
607
608             // If NOT updated by requested area:
609             // there is not requested area in new layout,
610             // so push requested role to candidate list
611             if (request_for_this_layer && ("" == used_role))
612             {
613                 HMI_DEBUG("---- Push request(area:%s category:%s role:%s) to candidate list",
614                           req_area.c_str(), req_ctg.c_str(), req_role.c_str());
615                 AreaState area_state;
616                 area_state.name = req_area;
617                 area_state.category = req_ctg;
618                 area_state.role = req_role;
619                 tmp_cand_list.push_back(area_state);
620                 candidate_num++;
621             }
622
623             HMI_DEBUG("---- blank_num:%d candidate_num:%d", blank_num, candidate_num);
624
625             // Compare number of candidate/blank,
626             // And remove role in order of the oldest as necessary
627             if (candidate_num < blank_num)
628             {
629                 // Refer history stack
630                 // and add to the top of tmp_cand_list in order to the newest
631                 while (candidate_num != blank_num)
632                 {
633                     AreaState area_state;
634                     area_state.name = kStmAreaName[StmAreaNoNone];
635                     area_state.category = ctg;
636                     area_state.role = this->popInvisibleRoleHistory(ctg);
637                     if ("" == area_state.role)
638                     {
639                         HMI_ERROR("There is no role in history stack!!");
640                     }
641                     tmp_cand_list.push_back(area_state);
642                     HMI_DEBUG("------ Add role:%s to candidate list",
643                               area_state.role.c_str());
644                     candidate_num++;
645                 }
646             }
647             else if (candidate_num > blank_num)
648             {
649                 // Remove the oldest role from candidate list
650                 while (candidate_num != blank_num)
651                 {
652                     std::string removed_role = tmp_cand_list.begin()->role;
653                     HMI_DEBUG("------ Remove the oldest role:%s from candidate list",
654                               removed_role.c_str());
655                     tmp_cand_list.erase(tmp_cand_list.begin());
656                     candidate_num--;
657
658                     // Push removed data to history stack
659                     this->pushInvisibleRoleHistory(ctg, removed_role);
660
661                     // Remove from current layout
662                     for (AreaState &as : crr_layout_state.area_list)
663                     {
664                         if (as.role == removed_role)
665                         {
666                             as.role = "";
667                         }
668                     }
669                 }
670             }
671             else
672             { // (candidate_num == blank_num)
673                 // nop
674             }
675
676             cand_list[ctg] = tmp_cand_list;
677         }
678
679         // Update areas
680         HMI_DEBUG("-- Update areas by using candidate list");
681         for (AreaState &as : crr_layout_state.area_list)
682         {
683             HMI_DEBUG("---- Check area:%s category:%s role:%s",
684                       as.name.c_str(), as.category.c_str(), as.role.c_str());
685             if ("" == as.role)
686             {
687                 HMI_DEBUG("------ Update this area with role:%s",
688                           cand_list[as.category].begin()->role.c_str());
689                 as.role = cand_list[as.category].begin()->role;
690                 cand_list[as.category].erase(cand_list[as.category].begin());
691             }
692         }
693     }
694     return changed;
695 }
696
697 void PolicyManager::createOutputInformation(json_object **json_out)
698 {
699     json_object *json_tmp;
700
701     // Create car element information
702     // {
703     //     "car_elements": [
704     //     {
705     //         "parking_brake": {
706     //             "changed": <bool>,
707     //             "state": <const char*>
708     //         },
709     //         ...
710     //     },
711     json_object *json_car_ele = json_object_new_array();
712     const char *car_ele_name;
713     for (int car_ele_no = StmCarElementNoMin;
714          car_ele_no <= StmCarElementNoMax; car_ele_no++)
715     {
716         car_ele_name = kStmCarElementName[car_ele_no];
717         json_tmp = json_object_new_object();
718         this->addStateToJson(car_ele_name,
719                              this->crr_car_elements[car_ele_name].changed,
720                              this->crr_car_elements[car_ele_name].state,
721                              &json_tmp);
722         json_object_array_add(json_car_ele, json_tmp);
723     }
724     json_object_object_add(*json_out, "car_elements", json_car_ele);
725
726     // Create layout information
727     //
728     //     "layers": [
729     //     {
730     //         "homescreen": {
731     //             "changed": <bool>,
732     //             "areas": [
733     //             {
734     //                 "name":<const char*>,
735     //                 "role":<const char*>
736     //             }.
737     //             ...
738     //             ]
739     //         }
740     //     },
741     //     ...
742     json_object *json_layer = json_object_new_array();
743     const char *layer_name;
744     for (int layer_no = StmLayerNoMin;
745          layer_no <= StmLayerNoMax; layer_no++)
746     {
747         layer_name = kStmLayerName[layer_no];
748         json_tmp = json_object_new_object();
749         this->addStateToJson(layer_name,
750                              this->crr_layers[layer_name].changed,
751                              this->crr_layers[layer_name].layout_state.area_list,
752                              &json_tmp);
753         json_object_array_add(json_layer, json_tmp);
754     }
755     json_object_object_add(*json_out, "layers", json_layer);
756 }
757
758 void PolicyManager::controlTimerEvent()
759 {
760     if (this->p_crr_state->car_element[StmCarElementNoRunning].changed)
761     {
762         if (StmRunningNoRun == this->p_crr_state->car_element[StmCarElementNoRunning].state)
763         {
764             // Set delay event(restriction mode on)
765             this->setStateTransitionProcessToSystemd(StmEvtNoRestrictionModeOn,
766                                                      3000, "");
767         }
768         else if (StmRunningNoStop ==
769                  this->p_crr_state->car_element[StmCarElementNoRunning].state)
770         {
771             // Stop timer for restriction on event
772             if (this->event_source_list.find(StmEvtNoRestrictionModeOn) !=
773                 this->event_source_list.end())
774             {
775                 HMI_DEBUG("Stop timer for restriction on");
776                 sd_event_source *event_source = this->event_source_list[StmEvtNoRestrictionModeOn];
777                 int ret = sd_event_source_set_enabled(event_source, SD_EVENT_OFF);
778                 if (0 > ret)
779                 {
780                     HMI_ERROR("Failed to stop timer");
781                 }
782             }
783
784             // Set event(restriction mode off)
785             this->setStateTransitionProcessToSystemd(StmEvtNoRestrictionModeOff, 0, "");
786         }
787     }
788 }
789
790 int PolicyManager::transitionState(sd_event_source *source, void *data)
791 {
792     HMI_DEBUG(">>>>>>>>>> START STATE TRANSITION");
793
794     int event_id = *((int *)data);
795
796     int event_no, category_no, area_no;
797     event_no = STM_GET_EVENT_FROM_ID(event_id);
798     category_no = STM_GET_CATEGORY_FROM_ID(event_id);
799     area_no = STM_GET_AREA_FROM_ID(event_id);
800     HMI_DEBUG(">>>>>>>>>> EVENT:%s CATEGORY:%s AREA:%s",
801               kStmEventName[event_no],
802               kStmCategoryName[category_no],
803               kStmAreaName[area_no]);
804
805     // Store current state
806     *(this->p_prv_state) = *(this->p_crr_state);
807
808     // Transition state
809     int ret = stmTransitionState(event_id, this->p_crr_state);
810     if (0 > ret)
811     {
812         HMI_ERROR("Failed transition state");
813         if (nullptr != this->callback.onError)
814         {
815             json_object *json_out = json_object_new_object();
816             json_object_object_add(json_out, "message",
817                                    json_object_new_string("Failed to transition state"));
818             json_object_object_add(json_out, "event",
819                                    json_object_new_string(kStmEventName[event_no]));
820             json_object_object_add(json_out, "role",
821                                    json_object_new_string(this->req_role_list[event_id].c_str()));
822             json_object_object_add(json_out, "area",
823                                    json_object_new_string(kStmAreaName[area_no]));
824             this->callback.onError(json_out);
825             json_object_put(json_out);
826         }
827         return -1;
828     }
829
830     // Update state which is managed by PolicyManager
831     this->updateState(event_id);
832
833     // Create output information for ResourceManager
834     json_object *json_out = json_object_new_object();
835     this->createOutputInformation(&json_out);
836
837     // Notify changed state
838     if (nullptr != this->callback.onStateTransitioned)
839     {
840         this->callback.onStateTransitioned(json_out);
841     }
842
843     // Start/Stop timer events
844     this->controlTimerEvent();
845
846     // Release json_object
847     json_object_put(json_out);
848
849     // Release data
850     delete (int *)data;
851
852     // Destroy sd_event_source object
853     sd_event_source_unref(source);
854
855     // Remove event source from list
856     if (this->event_source_list.find(event_id) != this->event_source_list.end())
857     {
858         this->event_source_list.erase(event_id);
859     }
860
861     HMI_DEBUG(">>>>>>>>>> FINISH STATE TRANSITION");
862     return 0;
863 }
864
865 int PolicyManager::timerEvent(sd_event_source *source, uint64_t usec, void *data)
866 {
867     HMI_DEBUG("Call");
868
869     int ret = this->transitionState(source, data);
870     return ret;
871 }
872
873 int PolicyManager::setStateTransitionProcessToSystemd(int event_id, uint64_t delay_ms, std::string role)
874 {
875     struct sd_event_source *event_source;
876     HMI_DEBUG("event_id:0x%x delay:%d role:%s", event_id, delay_ms, role.c_str());
877
878     if (0 == delay_ms)
879     {
880         int ret = sd_event_add_defer(afb_daemon_get_event_loop(), &event_source,
881                                      &pm::transitionStateWrapper, new int(event_id));
882         if (0 > ret)
883         {
884             HMI_ERROR("Faild to sd_event_add_defer: errno:%d", ret);
885             return -1;
886         }
887     }
888     else
889     {
890         // Get current time
891         struct timespec time_spec;
892         clock_gettime(CLOCK_BOOTTIME, &time_spec);
893
894         // Calculate timer fired time
895         uint64_t usec = (time_spec.tv_sec * 1000000) + (time_spec.tv_nsec / 1000) + (delay_ms * 1000);
896
897         // Set timer
898         int ret = sd_event_add_time(afb_daemon_get_event_loop(), &event_source,
899                                     CLOCK_BOOTTIME, usec, 1,
900                                     &pm::timerEventWrapper, new int(event_id));
901         if (0 > ret)
902         {
903             HMI_ERROR("Faild to sd_event_add_time: errno:%d", ret);
904             return -1;
905         }
906     }
907     // Store event source
908     this->event_source_list[event_id] = event_source;
909     // Store requested role
910     this->req_role_list[event_id] = role;
911     return 0;
912 }
913
914 bool PolicyManager::changedRestrictionModeTo2On()
915 {
916     // TODO: If possible thie process should be include in zipc stm in the future
917     if (this->p_crr_state->car_element[StmCarElementNoRestrictionMode].changed &&
918         (StmRestrictionModeSttNoOn != this->p_prv_state->car_element[StmCarElementNoRestrictionMode].state) &&
919         (StmRestrictionModeSttNoOn == this->p_crr_state->car_element[StmCarElementNoRestrictionMode].state))
920     {
921         return true;
922     }
923     return false;
924 }
925
926 bool PolicyManager::changedRestrictionMode2OnToOther()
927 {
928     // TODO: If possible thie process should be include in zipc stm in the future
929     if (this->p_crr_state->car_element[StmCarElementNoRestrictionMode].changed &&
930         (StmRestrictionModeSttNoOn == this->p_prv_state->car_element[StmCarElementNoRestrictionMode].state) &&
931         (StmRestrictionModeSttNoOn != this->p_crr_state->car_element[StmCarElementNoRestrictionMode].state))
932     {
933         return true;
934     }
935     return false;
936 }
937
938 bool PolicyManager::changedLightstatusBrakeOffToOn()
939 {
940     // TODO: For master
941     //       If possible thie process should be include in zipc stm in the future
942     if (("master" == this->ecu_name) &&
943         this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].changed &&
944         (StmLightstatusBrakeSttNoOff == this->p_prv_state->car_element[StmCarElementNoLightstatusBrake].state) &&
945         (StmLightstatusBrakeSttNoOn  == this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].state))
946     {
947         return true;
948     }
949     return false;
950 }
951
952 bool PolicyManager::changedLightstatusBrakeOnToOff()
953 {
954     // TODO: For master
955     //       If possible thie process should be include in zipc stm in the future
956     if (("master" == this->ecu_name) &&
957         this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].changed &&
958         (StmLightstatusBrakeSttNoOn == this->p_prv_state->car_element[StmCarElementNoLightstatusBrake].state) &&
959         (StmLightstatusBrakeSttNoOff  == this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].state))
960     {
961         return true;
962     }
963     return false;
964 }
965
966 int PolicyManager::loadRolesConfigFile()
967 {
968     std::string file_name;
969
970     // Get afm application installed dir
971     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
972     HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
973
974     if (!afm_app_install_dir)
975     {
976         HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
977     }
978     else
979     {
980         file_name = std::string(afm_app_install_dir) + std::string(pm::kPathRolesConfigFile);
981     }
982
983     // Load roles config file
984     json_object *json_obj;
985     int ret = this->inputJsonFilie(file_name.c_str(), &json_obj);
986     if (0 > ret)
987     {
988         HMI_ERROR("Could not open %s, so use default role information", pm::kPathRolesConfigFile);
989         json_obj = json_tokener_parse(kDefaultRolesConfig);
990     }
991     HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
992
993     // Parse ecus
994     json_object *json_cfg;
995     if (!json_object_object_get_ex(json_obj, "ecus", &json_cfg))
996     {
997         HMI_ERROR("Parse Error!!");
998         return -1;
999     }
1000
1001     int num_ecu = json_object_array_length(json_cfg);
1002     HMI_DEBUG("json_cfg(ecus) len:%d", num_ecu);
1003
1004     const char* c_ecu_name;
1005     json_object *json_ecu;
1006     for (int i = 0; i < num_ecu; i++)
1007     {
1008         json_ecu= json_object_array_get_idx(json_cfg, i);
1009
1010         c_ecu_name = this->getStringFromJson(json_ecu, "name");
1011         if (nullptr == c_ecu_name)
1012         {
1013             HMI_ERROR("Parse Error!!");
1014             return -1;
1015         }
1016
1017         if (std::string(c_ecu_name) == this->ecu_name)
1018         {
1019             break;
1020         }
1021         else
1022         {
1023             json_ecu = nullptr;
1024         }
1025     }
1026
1027     if (!json_ecu)
1028     {
1029         HMI_ERROR("Areas for ecu:%s is NOT exist!!", this->ecu_name.c_str());
1030         return -1;
1031     }
1032
1033     // Parse roles
1034     json_object *json_roles;
1035     if (!json_object_object_get_ex(json_ecu, "roles", &json_roles))
1036     {
1037         HMI_ERROR("Parse Error!!");
1038         return -1;
1039     }
1040
1041     int len = json_object_array_length(json_roles);
1042     HMI_DEBUG("json_cfg len:%d", len);
1043     HMI_DEBUG("json_cfg dump:%s", json_object_get_string(json_roles));
1044
1045     json_object *json_tmp;
1046     const char *category;
1047     const char *roles;
1048     const char *areas;
1049     const char *layer;
1050     for (int i = 0; i < len; i++)
1051     {
1052         json_tmp = json_object_array_get_idx(json_roles, i);
1053
1054         category = this->getStringFromJson(json_tmp, "category");
1055         roles = this->getStringFromJson(json_tmp, "role");
1056         areas = this->getStringFromJson(json_tmp, "area");
1057         layer = this->getStringFromJson(json_tmp, "layer");
1058
1059         if ((nullptr == category) || (nullptr == roles) ||
1060             (nullptr == areas) || (nullptr == layer))
1061         {
1062             HMI_ERROR("Parse Error!!");
1063             return -1;
1064         }
1065
1066         // Parse roles by '|'
1067         std::vector<std::string> vct_roles;
1068         vct_roles = this->parseString(std::string(roles), '|');
1069
1070         // Parse areas by '|'
1071         Areas vct_areas;
1072         vct_areas = this->parseString(std::string(areas), '|');
1073
1074         // Set role, category, areas
1075         for (auto itr = vct_roles.begin(); itr != vct_roles.end(); ++itr)
1076         {
1077             this->role2category[*itr] = std::string(category);
1078         }
1079         this->category2role[category] = std::string(roles);
1080         this->category2areas[category] = vct_areas;
1081         this->layer2categories[layer].push_back(category);
1082     }
1083
1084     // Check
1085     HMI_DEBUG("Check role2category");
1086     for (const auto &x : this->role2category)
1087     {
1088         HMI_DEBUG("key:%s, val:%s", x.first.c_str(), x.second.c_str());
1089     }
1090
1091     HMI_DEBUG("Check category2role");
1092     for (const auto &x : this->category2role)
1093     {
1094         HMI_DEBUG("key:%s, val:%s", x.first.c_str(), x.second.c_str());
1095     }
1096
1097     HMI_DEBUG("Check category2areas");
1098     for (const auto &x : this->category2areas)
1099     {
1100         for (const auto &y : x.second)
1101         {
1102             HMI_DEBUG("key:%s, val:%s", x.first.c_str(), y.c_str());
1103         }
1104     }
1105
1106     HMI_DEBUG("Check layer2categories");
1107     for (const auto &x : this->layer2categories)
1108     {
1109         for (const auto &y : x.second)
1110         {
1111             HMI_DEBUG("key:%s, val:%s", x.first.c_str(), y.c_str());
1112         }
1113     }
1114     return 0;
1115 }
1116
1117 int PolicyManager::loadLayoutsConfigFile()
1118 {
1119     HMI_DEBUG("Call");
1120
1121     // Get afm application installed dir
1122     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1123     HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
1124
1125     std::string file_name;
1126     if (!afm_app_install_dir)
1127     {
1128         HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
1129     }
1130     else
1131     {
1132         file_name = std::string(afm_app_install_dir) + std::string(pm::kPathLayoutsConfigFile);
1133     }
1134
1135     // Load states config file
1136     json_object *json_obj;
1137     int ret = this->inputJsonFilie(file_name.c_str(), &json_obj);
1138     if (0 > ret)
1139     {
1140         HMI_DEBUG("Could not open %s, so use default layout information", pm::kPathLayoutsConfigFile);
1141         json_obj = json_tokener_parse(kDefaultLayoutsConfig);
1142     }
1143     HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
1144
1145     // Parse ecus
1146     json_object *json_cfg;
1147     if (!json_object_object_get_ex(json_obj, "ecus", &json_cfg))
1148     {
1149         HMI_ERROR("Parse Error!!");
1150         return -1;
1151     }
1152
1153     int num_ecu = json_object_array_length(json_cfg);
1154     HMI_DEBUG("json_cfg(ecus) len:%d", num_ecu);
1155
1156     const char* c_ecu_name;
1157     json_object *json_ecu;
1158     for (int i = 0; i < num_ecu; i++)
1159     {
1160         json_ecu= json_object_array_get_idx(json_cfg, i);
1161
1162         c_ecu_name = this->getStringFromJson(json_ecu, "name");
1163         if (nullptr == c_ecu_name)
1164         {
1165             HMI_ERROR("Parse Error!!");
1166             return -1;
1167         }
1168
1169         if (std::string(c_ecu_name) == this->ecu_name)
1170         {
1171             break;
1172         }
1173         else
1174         {
1175             json_ecu = nullptr;
1176         }
1177     }
1178
1179     if (!json_ecu)
1180     {
1181         HMI_ERROR("Areas for ecu:%s is NOT exist!!", this->ecu_name.c_str());
1182         return -1;
1183     }
1184
1185     // Perse layouts
1186     HMI_DEBUG("Perse layouts");
1187     json_object *json_layouts;
1188     if (!json_object_object_get_ex(json_ecu, "layouts", &json_layouts))
1189     {
1190         HMI_ERROR("Parse Error!!");
1191         return -1;
1192     }
1193
1194     int len = json_object_array_length(json_layouts);
1195     HMI_DEBUG("json_layouts len:%d", len);
1196     HMI_DEBUG("json_layouts dump:%s", json_object_get_string(json_layouts));
1197
1198     const char *layout;
1199     const char *role;
1200     const char *category;
1201     for (int i = 0; i < len; i++)
1202     {
1203         json_object *json_tmp = json_object_array_get_idx(json_layouts, i);
1204
1205         layout = this->getStringFromJson(json_tmp, "name");
1206         if (nullptr == layout)
1207         {
1208             HMI_ERROR("Parse Error!!");
1209             return -1;
1210         }
1211         HMI_DEBUG("> layout:%s", layout);
1212
1213         json_object *json_area_array;
1214         if (!json_object_object_get_ex(json_tmp, "areas", &json_area_array))
1215         {
1216             HMI_ERROR("Parse Error!!");
1217             return -1;
1218         }
1219
1220         int len_area = json_object_array_length(json_area_array);
1221         HMI_DEBUG("json_area_array len:%d", len_area);
1222         HMI_DEBUG("json_area_array dump:%s", json_object_get_string(json_area_array));
1223
1224         LayoutState layout_state;
1225         AreaState area_state;
1226         std::map<std::string, int> category_num;
1227         for (int ctg_no = StmCtgNoMin;
1228              ctg_no <= StmCtgNoMax; ctg_no++)
1229         {
1230             const char *ctg_name = kStmCategoryName[ctg_no];
1231             category_num[ctg_name] = 0;
1232         }
1233
1234         for (int j = 0; j < len_area; j++)
1235         {
1236             json_object *json_area = json_object_array_get_idx(json_area_array, j);
1237
1238             // Get area name
1239             const char *area = this->getStringFromJson(json_area, "name");
1240             if (nullptr == area)
1241             {
1242                 HMI_ERROR("Parse Error!!");
1243                 return -1;
1244             }
1245             area_state.name = std::string(area);
1246             HMI_DEBUG(">> area:%s", area);
1247
1248             // Get app attribute of the area
1249             category = this->getStringFromJson(json_area, "category");
1250             if (nullptr == category)
1251             {
1252                 HMI_ERROR("Parse Error!!");
1253                 return -1;
1254             }
1255             area_state.category = std::string(category);
1256             category_num[category]++;
1257             HMI_DEBUG(">>> category:%s", category);
1258
1259             role = this->getStringFromJson(json_area, "role");
1260             if (nullptr != role)
1261             {
1262                 // Role is NOT essential here
1263                 area_state.role = std::string(role);
1264             }
1265             else
1266             {
1267                 area_state.role = std::string("");
1268             }
1269             HMI_DEBUG(">>> role:%s", role);
1270
1271             layout_state.area_list.push_back(area_state);
1272         }
1273
1274         layout_state.name = layout;
1275         layout_state.category_num = category_num;
1276         this->default_layouts[layout] = layout_state;
1277     }
1278
1279     // initialize for none layout
1280     LayoutState none_layout_state;
1281     memset(&none_layout_state, 0, sizeof(none_layout_state));
1282     none_layout_state.name = "none";
1283     this->default_layouts["none"] = none_layout_state;
1284
1285     // Check
1286     for (auto itr_layout = this->default_layouts.begin();
1287          itr_layout != this->default_layouts.end(); ++itr_layout)
1288     {
1289         HMI_DEBUG(">>> layout:%s", itr_layout->first.c_str());
1290
1291         for (auto itr_area = itr_layout->second.area_list.begin();
1292              itr_area != itr_layout->second.area_list.end(); ++itr_area)
1293         {
1294             HMI_DEBUG(">>> >>> area    :%s", itr_area->name.c_str());
1295             HMI_DEBUG(">>> >>> category:%s", itr_area->category.c_str());
1296             HMI_DEBUG(">>> >>> role    :%s", itr_area->role.c_str());
1297         }
1298     }
1299
1300     // Release json_object
1301     json_object_put(json_obj);
1302
1303     return 0;
1304 }
1305
1306 void PolicyManager::pushInvisibleRoleHistory(std::string category, std::string role)
1307 {
1308     auto i = std::remove_if(this->crr_invisible_role_history[category].begin(),
1309                             this->crr_invisible_role_history[category].end(),
1310                             [role](std::string x) { return (role == x); });
1311
1312     if (this->crr_invisible_role_history[category].end() != i)
1313     {
1314         this->crr_invisible_role_history[category].erase(i);
1315     }
1316
1317     this->crr_invisible_role_history[category].push_back(role);
1318
1319     if (pm::kInvisibleRoleHistoryNum < crr_invisible_role_history[category].size())
1320     {
1321         this->crr_invisible_role_history[category].erase(
1322             this->crr_invisible_role_history[category].begin());
1323     }
1324 }
1325
1326 std::string PolicyManager::popInvisibleRoleHistory(std::string category)
1327 {
1328     std::string role;
1329     if (crr_invisible_role_history[category].empty())
1330     {
1331         role = "";
1332     }
1333     else
1334     {
1335         role = this->crr_invisible_role_history[category].back();
1336         this->crr_invisible_role_history[category].pop_back();
1337     }
1338     return role;
1339 }
1340
1341 const char *PolicyManager::getStringFromJson(json_object *obj, const char *key)
1342 {
1343     json_object *tmp;
1344     if (!json_object_object_get_ex(obj, key, &tmp))
1345     {
1346         HMI_DEBUG("Not found key \"%s\"", key);
1347         return nullptr;
1348     }
1349
1350     return json_object_get_string(tmp);
1351 }
1352
1353 int PolicyManager::inputJsonFilie(const char *file, json_object **obj)
1354 {
1355     const int input_size = 128;
1356     int ret = -1;
1357
1358     HMI_DEBUG("Input file: %s", file);
1359
1360     // Open json file
1361     FILE *fp = fopen(file, "rb");
1362     if (nullptr == fp)
1363     {
1364         HMI_ERROR("Could not open file");
1365         return ret;
1366     }
1367
1368     // Parse file data
1369     struct json_tokener *tokener = json_tokener_new();
1370     enum json_tokener_error json_error;
1371     char buffer[input_size];
1372     int block_cnt = 1;
1373     while (1)
1374     {
1375         size_t len = fread(buffer, sizeof(char), input_size, fp);
1376         *obj = json_tokener_parse_ex(tokener, buffer, len);
1377         if (nullptr != *obj)
1378         {
1379             HMI_DEBUG("File input is success");
1380             ret = 0;
1381             break;
1382         }
1383
1384         json_error = json_tokener_get_error(tokener);
1385         if ((json_tokener_continue != json_error) || (input_size > len))
1386         {
1387             HMI_ERROR("Failed to parse file (byte:%d err:%s)",
1388                       (input_size * block_cnt), json_tokener_error_desc(json_error));
1389             HMI_ERROR("\n%s", buffer);
1390             *obj = nullptr;
1391             break;
1392         }
1393         block_cnt++;
1394     }
1395
1396     // Close json file
1397     fclose(fp);
1398
1399     // Free json_tokener
1400     json_tokener_free(tokener);
1401
1402     return ret;
1403 }
1404
1405 void PolicyManager::dumpLayerState(std::unordered_map<std::string, LayerState> &layers)
1406 {
1407     HMI_DEBUG("-------------------------------------------------------------------------------------------------------");
1408     HMI_DEBUG("|%-15s|%s|%-20s|%-20s|%-20s|%-20s|",
1409               "LAYER", "C", "LAYOUT", "AREA", "CATEGORY", "ROLE");
1410     for (const auto &itr : layers)
1411     {
1412         LayerState ls = itr.second;
1413         const char* layer   = ls.name.c_str();
1414         const char* changed = (ls.changed) ? "T" : "f";
1415         const char* layout  = ls.layout_state.name.c_str();
1416         bool first = true;
1417         for (const auto &as : ls.layout_state.area_list)
1418         {
1419             if (first)
1420             {
1421                 first = false;
1422                 HMI_DEBUG("|%-15s|%1s|%-20s|%-20s|%-20s|%-20s|",
1423                           layer, changed, layout,
1424                           as.name.c_str(), as.category.c_str(), as.role.c_str());
1425             }
1426             else
1427                 HMI_DEBUG("|%-15s|%1s|%-20s|%-20s|%-20s|%-20s|",
1428                           "", "", "", as.name.c_str(), as.category.c_str(), as.role.c_str());
1429         }
1430     }
1431     HMI_DEBUG("-------------------------------------------------------------------------------------------------------");
1432 }
1433
1434 void PolicyManager::dumpInvisibleRoleHistory()
1435 {
1436     HMI_DEBUG(">>>>>>>>>> DUMP INVISIBLE ROLE HISTORY ( category [older > newer] )");
1437     for (int ctg_no = StmCtgNoMin; ctg_no <= StmCtgNoMax; ctg_no++)
1438     {
1439         if (ctg_no == StmCtgNoNone)
1440             continue;
1441
1442         std::string category = std::string(kStmCategoryName[ctg_no]);
1443
1444         std::string str = category + " [ ";
1445         for (const auto &i : this->crr_invisible_role_history[category])
1446             str += (i + " > ");
1447
1448         str += "]";
1449         HMI_DEBUG("%s", str.c_str());
1450     }
1451 }
1452
1453 std::vector<std::string> PolicyManager::parseString(std::string str, char delimiter)
1454 {
1455     // Parse string by delimiter
1456     std::vector<std::string> vct;
1457     std::stringstream ss{str};
1458     std::string buf;
1459     while (std::getline(ss, buf, delimiter))
1460     {
1461         if (!buf.empty())
1462         {
1463             // Delete space and push back to vector
1464             vct.push_back(this->deleteSpace(buf));
1465         }
1466     }
1467     return vct;
1468 }
1469
1470 std::string PolicyManager::deleteSpace(std::string str)
1471 {
1472     std::string ret = str;
1473     size_t pos;
1474     while ((pos = ret.find_first_of(" ")) != std::string::npos)
1475     {
1476         ret.erase(pos, 1);
1477     }
1478     return ret;
1479 }
1480
1481 const char *PolicyManager::kDefaultRolesConfig = "{ \
1482     \"roles\":[ \
1483     { \
1484         \"category\": \"homescreen\", \
1485         \"role\": \"homescreen\", \
1486         \"area\": \"fullscreen\", \
1487     }, \
1488     { \
1489         \"category\": \"map\", \
1490         \"role\": \"map\", \
1491         \"area\": \"normal.full | split.main\", \
1492     }, \
1493     { \
1494         \"category\": \"general\", \
1495         \"role\": \"launcher | poi | browser | sdl | mixer | radio | hvac | debug | phone | video | music\", \
1496         \"area\": \"normal.full\", \
1497     }, \
1498     { \
1499         \"category\": \"system\", \
1500         \"role\": \"settings | dashboard\", \
1501         \"area\": \"normal.full\", \
1502     }, \
1503     { \
1504         \"category\": \"software_keyboard\", \
1505         \"role\": \"software_keyboard\", \
1506         \"area\": \"software_keyboard\", \
1507     }, \
1508     { \
1509         \"category\": \"restriction\", \
1510         \"role\": \"restriction\", \
1511         \"area\": \"restriction.normal | restriction.split.main | restriction.split.sub\", \
1512     }, \
1513     { \
1514         \"category\": \"pop_up\", \
1515         \"role\": \"pop_up\", \
1516         \"area\": \"on_screen\", \
1517     }, \
1518     { \
1519         \"category\": \"system_alert\", \
1520         \"role\": \"system_alert\", \
1521         \"area\": \"on_screen\", \
1522     } \
1523     ] \
1524 }";
1525
1526 const char *PolicyManager::kDefaultLayoutsConfig = "{ \
1527     \"layouts\": [ \
1528         { \
1529             \"name\": \"homescreen\", \
1530             \"layer\": \"far_homescreen\", \
1531             \"areas\": [ \
1532                 { \
1533                     \"name\": \"fullscreen\", \
1534                     \"category\": \"homescreen\" \
1535                 } \
1536             ] \
1537         }, \
1538         { \
1539             \"name\": \"map.normal\", \
1540             \"layer\": \"apps\", \
1541             \"areas\": [ \
1542                 { \
1543                     \"name\": \"normal.full\", \
1544                     \"category\": \"map\" \
1545                 } \
1546             ] \
1547         }, \
1548         { \
1549             \"name\": \"map.split\", \
1550             \"layer\": \"apps\", \
1551             \"areas\": [ \
1552                 { \
1553                     \"name\": \"split.main\", \
1554                     \"category\": \"map\" \
1555                 }, \
1556                 { \
1557                     \"name\": \"split.sub\", \
1558                     \"category\": \"splitable\" \
1559                 } \
1560             ] \
1561         }, \
1562         { \
1563             \"name\": \"map.fullscreen\", \
1564             \"layer\": \"apps\", \
1565             \"areas\": [ \
1566                 { \
1567                     \"name\": \"fullscreen\", \
1568                     \"category\": \"map\" \
1569                 } \
1570             ] \
1571         }, \
1572         { \
1573             \"name\": \"splitable.normal\", \
1574             \"layer\": \"apps\", \
1575             \"areas\": [ \
1576                 { \
1577                     \"name\": \"normal.full\", \
1578                     \"category\": \"splitable\" \
1579                 } \
1580             ] \
1581         }, \
1582         { \
1583             \"name\": \"splitable.split\", \
1584             \"layer\": \"apps\", \
1585             \"areas\": [ \
1586                 { \
1587                     \"name\": \"split.main\", \
1588                     \"category\": \"splitable\" \
1589                 }, \
1590                 { \
1591                     \"name\": \"split.sub\", \
1592                     \"category\": \"splitable\" \
1593                 } \
1594             ] \
1595         }, \
1596         { \
1597             \"name\": \"general.normal\", \
1598             \"layer\": \"apps\", \
1599             \"areas\": [ \
1600                 { \
1601                     \"name\": \"normal.full\", \
1602                     \"category\": \"general\" \
1603                 } \
1604             ] \
1605         }, \
1606         { \
1607             \"name\": \"system.normal\", \
1608             \"layer\": \"apps\", \
1609             \"areas\": [ \
1610                 { \
1611                     \"name\": \"normal.full\", \
1612                     \"category\": \"system\" \
1613                 } \
1614             ] \
1615         }, \
1616         { \
1617             \"name\": \"software_keyboard\", \
1618             \"layer\": \"near_homescreen\", \
1619             \"areas\": [ \
1620                 { \
1621                     \"name\": \"software_keyboard\", \
1622                     \"category\": \"software_keyboard\" \
1623                 } \
1624             ] \
1625         }, \
1626         { \
1627             \"name\": \"restriction.normal\", \
1628             \"layer\": \"restriction\", \
1629             \"areas\": [ \
1630                 { \
1631                     \"name\": \"restriction.normal\", \
1632                     \"category\": \"restriction\" \
1633                 } \
1634             ] \
1635         }, \
1636         { \
1637             \"name\": \"restriction.split.main\", \
1638             \"layer\": \"restriction\", \
1639             \"areas\": [ \
1640                 { \
1641                     \"name\": \"restriction.split.main\", \
1642                     \"category\": \"restriction\" \
1643                 } \
1644             ] \
1645         }, \
1646         { \
1647             \"name\": \"restriction.split.sub\", \
1648             \"layer\": \"restriction\", \
1649             \"areas\": [ \
1650                 { \
1651                     \"name\": \"restriction.split.sub\", \
1652                     \"category\": \"restriction\" \
1653                 } \
1654             ] \
1655         }, \
1656         { \
1657             \"name\": \"pop_up\", \
1658             \"layer\": \"on_screen\", \
1659             \"areas\": [ \
1660                 { \
1661                     \"name\": \"on_screen\", \
1662                     \"category\": \"pop_up\" \
1663                 } \
1664             ] \
1665         }, \
1666         { \
1667             \"name\": \"system_alert\", \
1668             \"layer\": \"on_screen\", \
1669             \"areas\": [ \
1670                 { \
1671                     \"name\": \"on_screen\", \
1672                     \"category\": \"system_alert\" \
1673                 } \
1674             ] \
1675         } \
1676     ] \
1677 }";