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 PySide import QtCore
34
35 import node_manager_fkie as nm
36
37 -class History(QtCore.QObject):
38
39 HISTORY_LENGTH = 12
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
46 PARAM_HISTORY_FILE = 'param.history'
47
49 QtCore.QObject.__init__(self)
50 self.PARAM_CACHE = self.loadCache(self.PARAM_HISTORY_FILE)
51
54
55 - def cachedParamValues(self, key):
56 try:
57 return list(self.PARAM_CACHE[key])
58 except:
59 result = []
60 return result
61
62 - def addParamCache(self, key, value):
63 self._add2Cache(self.PARAM_CACHE, key, value)
64
65 - def removeParamCache(self, key, value):
66 self._removeFromCache(self.PARAM_CACHE, key, value)
67
68 - def loadCache(self, file):
69 '''
70 Loads the content of the given file and return it as cache.
71 @param file: the name of the history file
72 @type file: C{str}
73 @return: the dictionary with arguments
74 @rtype: C{dict(str(name):[str(value), ...], ...)}
75 '''
76 result = {}
77 historyFile = ''.join([nm.CFG_PATH, file])
78 if not os.path.isdir(nm.CFG_PATH):
79 os.makedirs(nm.CFG_PATH)
80 if os.path.isfile(historyFile):
81 with open(historyFile, 'r') as f:
82 line = f.readline()
83 while line:
84 if line:
85 line = line.strip()
86 if line:
87 key, sep, value = line.partition(':=')
88 if sep:
89 if not key in result.keys():
90 result[key] = [value]
91 else:
92 result[key].append(value)
93 line = f.readline()
94 return result
95
96 - def storeCache(self, file, cache, history_len):
97 '''
98 Stores the cache to a file.
99 @param file: the name of the history file
100 @type file: C{str}
101 @param cache: the dictionary with values
102 @type cache: C{dict}
103 @param history_len: the maximal count of value for a key
104 @type history_len: C{int}
105 '''
106 if not os.path.isdir(nm.CFG_PATH):
107 os.makedirs(nm.CFG_PATH)
108 with open(''.join([nm.CFG_PATH, file]), 'w') as f:
109 for key in cache.keys():
110 count = 0
111 for value in cache[key]:
112 if count < history_len:
113 f.write(''.join([key, ':=', value, '\n']))
114 count += 1
115 else:
116 break
117
118 - def _add2Cache(self, cache, key, value):
119 uvalue = unicode(value)
120 if key and uvalue:
121 if not cache.has_key(key):
122 cache[key] = [uvalue]
123 elif not uvalue in cache[key]:
124 cache[key].insert(0, uvalue)
125 if len(cache[key]) >= self.HISTORY_LENGTH:
126 cache[key].pop()
127 else:
128 cache[key].remove(uvalue)
129 cache[key].insert(0, uvalue)
130
131 - def _removeFromCache(self, cache, key, value):
132 uvalue = unicode(value)
133 if key and uvalue:
134 if cache.has_key(key):
135 value_list = cache[key]
136 try:
137 value_list.remove(uvalue)
138 except:
139 pass
140 if len(value_list) == 0:
141 del cache[key]
142