1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 import os
33 from python_qt_binding import QtCore
34
35 import rospy
36
37 import node_manager_fkie as nm
38
39 -class History(QtCore.QObject):
40
41 PARAM_CACHE = dict()
42 '''
43 the cache is used to store and recover the value for last entered parameter in parameter dialog.
44 '''
45
49
52
53 - def cachedParamValues(self, key):
54 try:
55 return list(self.PARAM_CACHE[key])
56 except:
57 result = []
58 return result
59
60 - def addParamCache(self, key, value):
61 self._add2Cache(self.PARAM_CACHE, key, value)
62
63 - def removeParamCache(self, key, value):
64 self._removeFromCache(self.PARAM_CACHE, key, value)
65
66 - def loadCache(self, file):
67 '''
68 Loads the content of the given file and return it as cache.
69 @param file: the name of the history file
70 @type file: C{str}
71 @return: the dictionary with arguments
72 @rtype: C{dict(str(name):[str(value), ...], ...)}
73 '''
74 result = {}
75 historyFile = os.path.join(nm.settings().cfg_path, file)
76 if os.path.isfile(historyFile):
77 with open(historyFile, 'r') as f:
78 line = f.readline()
79 while line:
80 if line:
81 line = line.strip()
82 if line:
83 key, sep, value = line.partition(':=')
84 if sep:
85 if not key in result.keys():
86 result[key] = [value]
87 elif len(result[key]) <= nm.settings().param_history_length:
88 result[key].append(value)
89 line = f.readline()
90 return result
91
92 - def storeCache(self, file, cache, history_len):
93 '''
94 Stores the cache to a file.
95 @param file: the name of the history file
96 @type file: C{str}
97 @param cache: the dictionary with values
98 @type cache: C{dict}
99 @param history_len: the maximal count of value for a key
100 @type history_len: C{int}
101 '''
102 ignored = dict()
103 with open(os.path.join(nm.settings().cfg_path, file), 'w') as f:
104 for key in cache.keys():
105 count = 0
106 for value in cache[key]:
107 if count < history_len:
108 try:
109 f.write(''.join([key, ':=', value, '\n']))
110 except UnicodeEncodeError, e:
111 ignored[key] = (value, str(e))
112 except:
113 import traceback
114 rospy.logwarn("Storing history aborted: %s", traceback.format_exc)
115 count += 1
116 else:
117 break
118 if ignored:
119 rospy.logwarn("Error while storing follow keys: %s", str(ignored))
120
121 - def _add2Cache(self, cache, key, value):
122 uvalue = unicode(value)
123 if key and uvalue:
124 if not cache.has_key(key):
125 cache[key] = [uvalue]
126 elif not uvalue in cache[key]:
127 cache[key].insert(0, uvalue)
128 if len(cache[key]) >= nm.settings().param_history_length:
129 cache[key].pop()
130 else:
131 cache[key].remove(uvalue)
132 cache[key].insert(0, uvalue)
133
134 - def _removeFromCache(self, cache, key, value):
135 uvalue = unicode(value)
136 if key and uvalue:
137 if cache.has_key(key):
138 value_list = cache[key]
139 try:
140 value_list.remove(uvalue)
141 except:
142 pass
143 if len(value_list) == 0:
144 del cache[key]
145