-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathChecklist.py
321 lines (268 loc) · 8.96 KB
/
Checklist.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import os
import wx
import wx.dataview
import rsonlite
import Model
import Utils
_raceStatusNames = ['NotStarted'.lower(), 'Finished'.lower(), 'Running'.lower()]
def _checkRaceStatus( race, val ):
val = val.lower()
if val not in _raceStatusNames:
raise ValueError( 'Unknown option: "RaceStatus = {}"'.format(val) )
return (val == _raceStatusNames[0 if race.isUnstarted() else 1 if race.isFinished() else 2])
def _toBool( s ):
if s[:1] not in 'TtYy1FfNn0':
raise ValueError( 'Unknown boolean value "{}"'.format(s) )
return s[:1] in 'TtYy1'
_processRequirementLookup = {
'RaceStatus'.lower(): _checkRaceStatus,
'TimeTrial'.lower(): lambda race, v: race.isTimeTrial == _toBool(v),
'ChipReader'.lower(): lambda race, v: race.enableJChipIntegration == _toBool(v),
'Camera'.lower(): lambda race, v: race.enableUSBCamera == _toBool(v),
}
class Task:
NotDone = 0
Partial = 1
Done = 2
def __init__( self ):
self.title = ''
self.note = ''
self.status = self.NotDone
self.expand = True
self.requires = []
self.subtasks = []
def meetsRequirements( self ):
race = Model.race
if not race:
return False
success = True
for req, val in self.requires:
try:
if not _processRequirementLookup[req.lower()]( race, val ):
success = False
except KeyError:
raise ValueError( '{} "{}"'.format('Unknown Requirement', req) )
return success
def setStatus( self, s = Done ):
self.status = s
if s != self.Partial:
for i in self.subtasks:
i.setStatus( s )
def appendRequires( self, req, val ):
self.requires.append( (req, val) )
def appendSubtask( self, task ):
self.subtasks.append( task )
def validate( self ):
self.meetsRequirements()
for t in self.subtasks:
t.meetsRequirements()
return True
def pprint( self, indent = ' ', indent_level = 0 ):
print( '{}task'.format( indent*indent_level ) )
print( '{}title = {}'.format( indent*(indent_level+1), self.title ) )
if self.note:
print( '{}note = {}'.format( indent*(indent_level+1), self.note ) )
print( '{}status = {}'.format( indent*(indent_level+1), ['NotDone', 'Partial', 'Done'][self.status] ) )
if self.requires:
print( '{}requires'.format( indent*(indent_level+1) ) )
for req, val in self.requires:
print( '{}{} = {}'.format( indent*(indent_level+2), req, val ) )
if self.subtasks:
print( '{}subtasks'.format( indent*(indent_level+1) ) )
for task in self.subtasks:
task.pprint( indent, indent_level + 2 )
def _setTitle( task, val ):
task.title = '{}'.format(val[0])
def _setNote( task, val ):
task.note = '{}'.format(val[0])
def _setRequires( task, requires ):
for r in requires:
task.appendRequires( '{}'.format(r[0]), '{}'.format(r[1][0]))
def _setSubtasks( task, subtasks ):
for s in subtasks:
task.appendSubtask( _createTask(s) )
_processTokenLookup = dict(
title = _setTitle,
note = _setNote,
requires = _setRequires,
subtasks = _setSubtasks
)
def _createTask( task_data ):
assert task_data[0] == 'task', 'Missing "task" keyword. Line: "{}"'.format( task_data )
task = Task()
for key, val in task_data[1]:
_processTokenLookup[key.lower()](task, val)
return task
def createTasks( fname, fp ):
try:
tasks = rsonlite.loads( fp.read() )
except Exception as e:
Utils.writeLog( 'CheckList: Error: {} in "{}"'.format(e, fname) )
tasks = rsonlite.loads( '''
task
title = File Read Error
note = {} in file "{}"\n'''.format(e, fname) )
try:
root = Task()
root.title = 'root'
_setSubtasks( root, tasks )
except Exception as e:
tasks = rsonlite.loads( '''
task
title = File Content Error
note = {} in file "{}"\n'''.format(e, fname) )
root = Task()
root.title = 'root'
_setSubtasks( root, tasks )
return root
class Checklist( wx.Panel ):
def __init__( self, parent, id = wx.ID_ANY, style = 0 ):
super().__init__(parent, id, style = style)
self.Bind( wx.EVT_SIZE, self.onSize )
self.SetBackgroundColour( wx.Colour(255,255,255) )
self.tree = wx.dataview.TreeListCtrl( self, style = wx.TR_HAS_BUTTONS | wx.dataview.TL_3STATE )
self.tree.SetFont( wx.Font( (0,16), wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL ) )
self.tree.AppendColumn( _('Task') )
self.tree.AppendColumn( _('Note') )
self.tree.SetSortColumn( 0 )
self.tree.SetColumnWidth( 0, 450 )
self.tree.SetColumnWidth( 1, 450 )
self.tree.Bind( wx.dataview.EVT_TREELIST_ITEM_CHECKED, self.onTreeItemChecked )
self.checklist = None
self.refresh()
def updateChecklist( self ):
race = Model.race
self.checklist = getattr( Model.race, 'checklist', None ) if race else None
if self.checklist is None:
searchDirs = []
if Utils.getFileName():
searchDirs.append( os.path.dirname(Utils.getFileName()) )
searchDirs.extend( [os.path.expanduser('~'), Utils.getImageFolder(), os.path.dirname(__file__)] )
for dir in searchDirs:
fname = os.path.join(dir, 'CrossMgrChecklist.txt')
try:
fp = open(fname, 'r', encoding='utf8')
except Exception as e:
continue
self.checklist = createTasks( fname, fp )
fp.close()
if race:
race.checklist = self.checklist
break
def setChanged( self ):
try:
Model.race.setChanged()
except Exception:
pass
def onSize( self, event ):
width, height = self.GetSize()
self.tree.SetColumnWidth( 1, max(200, width - self.tree.GetColumnWidth(0) - 8) )
self.tree.SetSize( self.GetSize() )
event.Skip()
def updateStatus( self, treeNode ):
if treeNode != self.tree.GetRootItem():
task = self.tree.GetItemData( treeNode )
state = [wx.CHK_UNCHECKED, wx.CHK_UNDETERMINED, wx.CHK_CHECKED][task.status]
self.tree.CheckItem( treeNode, state )
child = self.tree.GetFirstChild( treeNode )
while child.IsOk():
self.updateStatus( child )
child = self.tree.GetNextSibling( child )
def onTreeItemChecked( self, event ):
treeNode = event.GetItem()
# If this is not a leaf node, skip it.
if self.tree.GetFirstChild(treeNode).IsOk():
return
task = self.tree.GetItemData( treeNode )
task.status = task.NotDone if task.status else task.Done
# Propagate the update child status to the parent.
while 1:
parentNode = self.tree.GetItemParent( treeNode )
if not parentNode.IsOk():
break
allChildrenDone = True
someChildrenDone = False
childNode = self.tree.GetFirstChild( parentNode )
while childNode.IsOk():
childTask = self.tree.GetItemData( childNode )
if childTask.status == childTask.Done:
someChildrenDone = True
else:
allChildrenDone = False
childNode = self.tree.GetNextSibling( childNode )
# Check if the parent has the correct status.
parentTask = self.tree.GetItemData( parentNode )
if allChildrenDone: # All children done.
if parentTask.status == parentTask.Done:
break
parentTask.status = parentTask.Done
elif not someChildrenDone: # No children done.
if parentTask.status == parentTask.NotDone:
break
parentTask.status = parentTask.NotDone
else: # Some children done.
if parentTask.status == parentTask.Partial:
break
parentTask.status = parentTask.Partial
treeNode = parentNode
self.updateStatus( treeNode )
self.setChanged()
def expandTree( self, treeNode ):
child = self.tree.GetFirstChild( treeNode )
while child.IsOk():
self.expandTree( child )
child = self.tree.GetNextSibling( child )
task = self.tree.GetItemData( treeNode )
if task.expand and treeNode != self.tree.GetRootItem():
self.tree.Expand( treeNode )
def addChildren( self, treeNode ):
task = self.tree.GetItemData( treeNode )
for t in task.subtasks:
if t.meetsRequirements():
child = self.tree.AppendItem( treeNode, t.title, data = t )
self.tree.SetItemText( child, 1, t.note )
self.addChildren( child )
def doCollapseAll( self, treeNode ):
child = self.tree.GetFirstChild( treeNode )
while child.IsOk():
self.doCollapseAll( child )
child = self.tree.GetNextSibling( child )
if treeNode != self.tree.GetRootItem():
self.tree.Collapse( treeNode )
def updateExpanded( self ):
setChanged = Model.race.setChanged if Model.race else lambda: None
n = self.tree.GetFirstItem()
while n.IsOk():
task = self.tree.GetItemData( n )
if task.expand != self.tree.IsExpanded(n):
task.expand = self.tree.IsExpanded(n)
setChanged()
n = self.tree.GetNextItem( n )
def commit( self ):
self.updateExpanded()
def refresh( self ):
self.updateChecklist()
self.tree.DeleteAllItems()
root = self.tree.GetRootItem()
self.tree.SetItemData( root, self.checklist )
self.addChildren( root )
self.doCollapseAll( root )
self.updateStatus( root )
self.expandTree( root )
if __name__ == '__main__':
race = Model.Race()
race._populate()
race.finishRaceNow()
Model.setRace( race )
app = wx.App(False)
mainWin = wx.Frame(None,title="CrossMan", size=(1024,600))
checklist = Checklist(mainWin)
checklist.refresh()
mainWin.Show()
app.MainLoop()
'''
with open('Checklist.txt', 'r', encoding='utf8') as fp:
root = createTasks( fp )
root.pprint()
root.validate()
'''