-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcolumbus.py
275 lines (207 loc) · 9 KB
/
columbus.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#! /usr/bin/env python
# Copyright (c) 2015 Niek J. Bouman
# Licensed under the MIT License:
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import locale
from dialog import Dialog
import sys
import capnp
import operator
import glob
import os
locale.setlocale(locale.LC_ALL, '')
d = Dialog(dialog="dialog")
d.set_background_title("Captain Config: Cap'n Proto Explorer")
floatTypes = ['float32','float64']
integralTypes = ['uint8','uint16','uint32','uint64','int8','int16','int32','int64']
modLen = 'Modify list length'
def fieldTypeAsString(field):
'''Determine the type of the field'''
try:
return field.schema.node.which()
except capnp.KjException:
return field.proto.slot.type.which()
except AttributeError:
return field.proto.slot.type.which()
def abbreviate(obj):
'''Stringify object and, if necessary, abbreviate and append ellipsis'''
s = str(obj)
if len(s) > 20:
s = s[:20]+'...'
return s
def unionDialog(node):
(code,selectedField) = d.radiolist('Union',
choices = [(x,'',True if x==node.which() else False) for x in node.schema.union_fields])
if code == Dialog.CANCEL:
return
#initialize if necessary
if node.schema.fields[selectedField].proto.slot.type.which() == 'struct':
getattr(node,'init')(selectedField)
handleField(node,selectedField,setInit=False)
def getValueDialog(getter,setter,datatype,setInit=True):
stringRepr = str(datatype).split("'")[1]
(code,inp) = d.inputbox('Set %s field' % stringRepr, init = str(getter() if setInit else ''))
if code == Dialog.OK:
try:
setter(datatype(inp))
except capnp.KjException:
d.msgbox('Illegal value')
except ValueError:
d.msgbox("Please enter a value of type '%s'" % stringRepr)
def isNamedUnion(node):
return len(node.schema.non_union_fields) == 0
def handleStruct(node,skipUnionCheck=False):
while True:
if not skipUnionCheck and isNamedUnion(node):
unionDialog(node)
return
visibleFields = node.schema.non_union_fields
if len( node.schema.union_fields)>0:
# in case of an unnamed union:
# add the active union field to the list of visible fields
visibleFields += (node.which(),)
(code, tag) = d.menu('Traverse struct', ok_label='Modify',cancel_label='Exit' if node.is_root else 'Back',choices = [(name,abbreviate(getattr(node,name))) for name in visibleFields])
if code == Dialog.CANCEL:
return
if len(node.schema.union_fields)>0 and tag == node.which():
# the user has selected the field
# that corresponds to the unnamed union
unionDialog(node)
else:
handleField(node,tag)
def listLenDialog():
while True:
(code,inp) = d.inputbox('Choose list size')
if code == Dialog.CANCEL:
return
length = int(inp)
if length > 0:
node.init(tag,int(inp))
break
d.msgbox('Invalid list length')
def handleField(parentNode, fieldName, fieldSchema = None, fieldType = None, getter = None,
setter = None, setInit = True):
'''
The 'setInit' option can be used to prevent fields from displaying the current value.
(trying to get() a union member which is not currently initialized gives a KjException)
'''
if getter is None:
getter = lambda : getattr(parentNode,fieldName)
if setter is None:
setter = lambda x : setattr(parentNode,fieldName,x)
if fieldSchema is None:
fieldSchema = parentNode.schema.fields[fieldName]
if fieldType is None:
fieldType = fieldTypeAsString(fieldSchema)
if fieldType == 'enum':
sortedItems = sorted(parentNode.schema.fields[fieldName].schema.enumerants.items(),key=operator.itemgetter(1))
(code,enumerant) = d.radiolist('Select enumerant', choices = [(x[0],'',True if x[0] == getter() else False) for x in sortedItems])
if code == Dialog.CANCEL:
return
setter(enumerant)
elif fieldType == 'bool':
(code,tf) = d.radiolist('Select boolean', choices = [(str(x),'',getter()==x) for x in [True,False]])
if code == Dialog.CANCEL:
return
val = True if tf == 'True' else False
setter(val)
elif fieldType in ['text','str']:
(code,string) = d.inputbox('Set text field', init = getter() if setInit else '')
if code == Dialog.CANCEL:
return
setter(string)
elif fieldType == 'struct':
handleStruct(getattr(parentNode,fieldName))
elif fieldType in floatTypes:
getValueDialog(getter,setter,float,setInit)
elif fieldType in integralTypes:
getValueDialog(getter,setter,int,setInit)
elif fieldType == 'void':
setter(None)
elif fieldType == 'list':
if len(getattr(parentNode,fieldName)) == 0:
while True:
(code,inp) = d.inputbox('Choose list size')
if code == Dialog.CANCEL:
return
length = int(inp)
if length > 0:
parentNode.init(fieldName,int(inp))
break
d.msgbox('Invalid list length')
while True:
menuItems = [(str(i),str(entry)) for i,entry in enumerate(getattr(parentNode,fieldName))]
(code, selection) = d.menu('Edit list', ok_label='Modify',cancel_label='Back',choices = menuItems + [(modLen,'')] )
if code == Dialog.CANCEL:
return
if selection == modLen:
parentNode.init(fieldName,0)
return handleField(parentNode,fieldName) #,field, getter,setter)
else:
gttr = lambda: getattr(parentNode,fieldName)[int(selection)]
sttr = lambda x: getattr(getattr(parentNode,fieldName),'__setitem__')(int(selection),x)
listElemType = parentNode.schema.fields[fieldName].proto.slot.type.list.elementType.which()
if listElemType == 'struct':
handleStruct(gttr(),skipUnionCheck = True)
else:
handleField(parentNode,fieldName, fieldType = listElemType,getter=gttr,setter=sttr)
else:
print 'Not implemented yet:', fieldType
exit()
class Chdir:
def __init__( self ):
self.savedPath = os.getcwd()
def changeDir(self , newPath ):
os.chdir(newPath)
def __del__( self ):
os.chdir( self.savedPath )
def main():
dirMngr = Chdir()
currPath = os.getcwd()
wildcard = '*.capnp'
chWildcard = 'Change schema wildcard'
chDir = 'Change directory'
while True:
schemaFiles = [(x,'') for x in glob.glob(wildcard)]
code, tag = d.menu('Schema selection',
choices=schemaFiles+[
(chDir, '('+os.getcwd()+')'),
(chWildcard, '('+wildcard+')')])
if code == Dialog.CANCEL:
return
if tag == chWildcard:
code, tag = d.inputbox('Wildcard',init = wildcard)
if code == Dialog.OK:
wildcard = tag
continue
if tag == chDir:
code, tag = d.dselect(os.getcwd())
if code == Dialog.OK:
dirMngr.changeDir(tag)
else:
break
userSchema = capnp.load(str(tag))
(code,rootStruct) = d.menu('Select root struct',
choices = [(x.name,'') for x in userSchema.schema.node.nestedNodes])
msg = getattr(userSchema, rootStruct).new_message()
handleStruct(msg)
print msg.to_dict()
if __name__ == "__main__":
main()