-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpyuiEdit.py
831 lines (698 loc) · 23.9 KB
/
pyuiEdit.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
# coding: utf-8
'''
Author: Steven K. Pollack
Date Released: May 16, 2015
allow for text editing to encapsulate specific views from a pyui as subviews of a "container" view
The strucure of a "node" is a dictionary with the four keys:
{ "attributes": {dictionary of artibutes of the current node},
"frame" : "{(top,left},{width,height}}", # notes this is not a dictionary
"nodes": [list of subviews], # a subview is a node
"class": "class type"
}
The topmost node (the rootView) is a list with a single node
'''
import ui, console,os,os.path,sys,json,re,uuid,math,copy,dialogs,time,threading,Queue
from copy import deepcopy
import Shield; reload(Shield); from Shield import Shield
import uidir; reload(uidir); from uidir import FileGetter
import NodeListWalker; reload(NodeListWalker); from NodeListWalker import NodeListWalker
import ui_draw_arrow; reload(ui_draw_arrow); from ui_draw_arrow import ui_draw_arrow
depthColors = [(1.00, 0.80, 0.40),
(1.00, 1.00, 0.00),
(0.40, 0.80, 1.00),
(0.90, 0.90, 0.90),
(1.00, 0.40, 1.00),
(0.80, 1.00, 0.40),
(0.60, 1.00, 0.30),
]
validQuadTuple = re.compile(r"""\(
\D?([+-]?\d+\.?\d*)
\D*([+-]?\d+\.?\d*)
\D*([+-]?\d+\.?\d*)
\D*([+-]?\d+\.?\d*)
\D
|
\D?([+-]?\d+\.?\d*)
\D*([+-]?\d+\.?\d*)
\D*([+-]?\d+\.?\d*)
\D*([+-]?\d+\.?\d*)
""",
re.X)
genericView = '{{"attributes": {{"tint_color": "RGBA(0.000000,0.000000,1.000000,1.000000)","border_color": "RGBA(0.000000,0.000000,0.000000,1.000000)","background_color": "RGBA(1.000000,1.000000,1.000000,1.000000)","enabled": True,"flex": "","uuid": "{}","name": "{}",}},"frame": {},"nodes": {},"class": "View","level":{},"uuid":"{}","parent":"{}",}}'
thisFlex = ''
class RestartableThread(threading.Thread):
def __init__(self,*args,**kwargs):
self._args, self._kwargs = args, kwargs
super(RestartableThread,self).__init__(*args,**kwargs)
def clone(self):
return RestartableThread(*self._args, **self._kwargs)
def flatten(S):
if S == []:
return S
if isinstance(S[0], list):
return flatten(S[0]) + flatten(S[1:])
return S[:1] + flatten(S[1:])
def uniqify(sequence, idfun=None):
''' return a unique, order preserved version in input list'''
if not idfun:
def idfun(x): return x
seen = {}
result = []
for item in sequence:
marker = idfun(item)
if marker in seen.keys():
continue
seen[marker] = 1
result.append(item)
return result
class ItemsWalker(): # walk down an items list and find children
def __init__(self,items):
self.items = items
def walkItems(self,itemList):
indexList = []
for index in itemList:
rowList = []
rowList.append(index)
thisItem = self.items[index]
nodes = thisItem['node']['nodes']
if nodes:
nodeList = []
for node in nodes:
for row,item in enumerate(self.items):
if node == item['node']['uuid']:
nodeList.append(row)
rowList.append(self.walkItems(nodeList))
else:
rowList.append([])
indexList.append(rowList)
return indexList
def listShuffle(list,row_from, row_to):
''' a method to re-order a list '''
from_item = list[row_from]
del list[row_from]
list.insert(row_to,from_item)
return list
def inRectangle(point,rect): # rect is a frame type list: x,y,w,h
if (rect[0] <= point[0] <= rect[0]+rect[2]) and (rect[1] <= point[1] <= rect[1]+rect[3]):
return True
else:
return False
def onLine(point,line): #point is an xy tuple, line is tuple of endpoints
halfWidth = 5
if line[0][0] == line[1][0]: # vertical line
rect = (line[0][0] - halfWidth, min(line[0][1],line[1][1]),
2*halfWidth, abs(line[0][1] - line[1][1]))
else:
rect = (min(line[0][0], line[1][0]), line[0][1] - halfWidth,
abs(line[0][0]-line[1][0]), 2*halfWidth)
return inRectangle(point, rect)
class nodeMapView(ui.View):
def did_load(self):
self.nodes = []
def centroid(self,frame):
cX = frame[2]/2.0 + frame[0]
cY = frame[3]/2.0 + frame[1]
return (cX,cY)
def init(self,data_source):
self.data_source = data_source
self.pyuiFrame = self.data_source.items[0]['node']['frame']
self.pyuiWidth = self.pyuiFrame[2] - self.pyuiFrame[0]
self.pyuiHeight = self.pyuiFrame[3] - self.pyuiFrame[1]
if self.pyuiWidth > self.pyuiHeight:
self.ratio = self.width/self.pyuiWidth
else:
self.ratio = self.height/self.pyuiHeight
def draw(self):
if not self.data_source.items: return
topNodesFrame = self.data_source.items[0]['node']['frame']
topNodeCentroid = self.centroid(topNodesFrame)
# need to account for orgins of parents. need to walk down the tree
for item in self.data_source.items:
title = item['title']
node = item['node']
level = node['level']
frame = node['frame']
uuid = node['uuid']
try:
parent = node['parent']
except KeyError:
print "Keyerror on node['parent']\n"
print item
sys.exit(1)
isSelected = item['selected']
isHidden = item['hidden']
offset = [0,0]
ctr = 0
while parent != 'ROOT_UUID':
# work back through lineage until no more offsets.
ctr +=1
if ctr > 30:
sys.exit(1)
parentFrame,grandParent = walker.frameByUUID[parent]
offset = [offset[0] + parentFrame[0], offset[1] +parentFrame[1]]
parent = grandParent
try:
xframe = [frame[0] + offset[0], frame[1] + offset[1], frame[2], frame[3]]
except TypeError:
print "Type error in collect"
print "frame", xframe, "offset", offset
if not isHidden and level:
scaledFrame = [x*self.ratio for x in xframe]
path = ui.Path.rect(*scaledFrame)
ui.set_color((depthColors[level]) + (0.5,))
path.fill()
ui.set_color(0.5)
path.line_width = 5 if isSelected else 2
path.stroke()
def touch_began(self,touch):
global lastSelectedRow
location = touch.location
for row,item in enumerate(nodeDelegate.items[1:]):
if inRectangle(location,[x*self.ratio for x in item['node']['frame']]) and not item['hidden']:
nodeDelegate.items[row+1]['selected'] = not nodeDelegate.items[row+1]['selected']
if nodeDelegate.items[row+1]['selected']:
lastSelectedRow = row+1
else:
lastSelectedRow = -1
tvNodeList.reload_data()
self.set_needs_display()
break
class NodeTableViewDelegate(object):
def __init__(self,items):
self.items = items
self.listLength = len(self.items)
def tableview_number_of_sections(self, tableview):
# Return the number of sections (defaults to 1)
return 1
def delayed_reload(self):
global tvNodeList
tvNodeList.selected_rows = []
tvNodeList.reload_data()
def tableview_number_of_rows(self, tableview, section):
# Return the number of rows in the section
return self.listLength
def tableview_cell_for_row(self, tableview, section, row):
# Create and return a cell for the given section/row
cell = ui.TableViewCell()
level = self.items[row]['node']['level']
cell.text_label.text = (level)*">>" + (level != 0)*" " + self.items[row]['title']
if self.items[row]['hidden']:
cell.text_label.text_color = (0.90, 0.90, 0.90)
else:
cell.text_label.text_color = 'red' if self.items[row]['selected'] else 'black'
cell.accessory_type = 'detail_button'
try:
level = self.items[row]['node']['level']
except KeyError:
print "Keyerror in cell for row"
print row
print self.items[row]['node']
sys.exit(1)
cell.background_color = depthColors[level]
return cell
def tableview_did_select(self, tableview, section, row):
# Called when a row was selected.
global lastSelectedRow
if not self.items[row]['hidden']:
self.items[row]['selected'] = not self.items[row]['selected']
viewNodeMap.set_needs_display()
lastSelectedRow = row
ui.delay(self.delayed_reload,0.05)
def tableview_did_deselect(self,tableview,section,row):
pass
def tableview_accessory_button_tapped(self, tableview, section, row):
console.hud_alert('Frame: {}'.format(self.items[row]['node']['frame']))
def collectiveSize(selected,margin=(0,0,0,0)):
' calculate size of a container with margins specified '
topLeftX = 10000
bottomRightX = -10000
topLeftY = 10000
bottomRightY = -10000
for _,item in selected:
frame = item['node']['frame']
topLeftX = min(topLeftX,frame[0])
topLeftY = min(topLeftY,frame[1])
bottomRightX = max(bottomRightX, (frame[0]+frame[2]))
bottomRightY = max(bottomRightY, (frame[1]+frame[3]))
width = bottomRightX - topLeftX
height = bottomRightY - topLeftY
topLeftX -= margin[0]
topLeftY -= margin[1]
width += margin[0]+margin[1]
height += margin[2]+margin[3]
return (topLeftX,topLeftY, width, height)
class pyuiBuilder():
def __init__(self,rowByUUID,nodeDelegate):
self.rowByUUID = rowByUUID
self.padLevel = 0
self.items = nodeDelegate.items
self.outString = ""
def openBrace(self):
self.outString += "{}[\n".format(self.padLevel*" ")
self.padLevel +=1
def closeBrace(self,comma=False):
commaIndex = self.outString.find(',',-4)
if commaIndex != -1:
self.outString = self.outString[:commaIndex] + '\n'
self.padLevel -=1
if comma:
self.outString += "{}],\n".format(self.padLevel*" ")
else:
self.outString += "{}]\n".format(self.padLevel*" ")
def openCurly(self):
self.outString += "{}{{\n".format(self.padLevel*" ")
self.padLevel +=1
def closeCurly(self,comma=False):
commaIndex = self.outString.find(',',-4)
if commaIndex != -1:
self.outString = self.outString[:commaIndex] + '\n'
self.padLevel -=1
if comma:
self.outString += "{}}},\n".format(self.padLevel*" ")
else:
self.outString += "{}}}\n".format(self.padLevel*" ")
def padded(self,string):
self.outString += "{}{}".format(self.padLevel*" ",string)
def unpadded(self,string):
self.outString += string
def traverse(self,uuid):
thisNode = self.items[self.rowByUUID[uuid]]['node']
nodes = thisNode['nodes']
attributes = thisNode['attributes']
frame = thisNode['frame']
thisClass = thisNode['class']
try:
name = thisNode['name']
except:
name = attributes['name']
self.openCurly()
self.padded('"attributes": {\n')
self.padLevel += 1
for key,value in attributes.items():
if key in ["frame","class"]:
continue
self.padded('"{}": '.format(key))
if type(value) == type(True):
if value:
self.unpadded('true, \n')
else:
self.unpadded('false, \n')
elif type(value) in (type(1.5),type(1)):
self.unpadded('{}, \n'.format(value))
else:
if key == 'data_source_items':
value = value.replace('\n','\\n')
self.unpadded('"{}", \n'.format(value))
self.closeCurly(comma=True)
self.padded('"frame": "{{{{{}, {}}}, {{{}, {}}}}}", \n'.format(*frame))
self.padded('"class": "{}", \n'.format(thisClass))
self.padded('"nodes":')
if not nodes:
self.unpadded('[],\n')
else:
self.unpadded('[\n')
self.padLevel += 1
firstNode = True
for node in nodes:
self.traverse(node)
self.closeBrace(comma=True)
self.closeCurly(comma=True)
def makeString(self,root):
self.padLevel = 0
self.outString = ''
self.openBrace()
self.traverse(root['uuid'])
self.closeBrace()
return self.outString
@ui.in_background
def onSave(button):
global nodeDelegate,walker,undoStack,fileDirectory
try:
fileName = console.input_alert('Ouptut File','Enter Output File Name',fileDirectory+'/')
except KeyboardInterrupt:
return
base,ext = os.path.splitext(fileName)
if not ext:
ext = '.pyui'
if ext not in ['.pyui','.json']:
console.hud_alert('invalid ui file type')
return
root = nodeDelegate.items[0]['node']
fileName = base+ext
rowByUUID = {}
for row,item in enumerate(nodeDelegate.items):
rowByUUID[item['node']['uuid']] = row
pyui = pyuiBuilder(rowByUUID,nodeDelegate)
outString = pyui.makeString(root)
with open(fileName, 'wb') as fh:
fh.write(outString)
def buildTree(workingList,inputList,items):
for thisIndex,nodes in inputList:
workingList.append(items[thisIndex])
if nodes:
buildTree(workingList,nodes,items)
@ui.in_background
def onCollect(button):
global nodeDelegate,walker,undoStack,lastSelectedRow
selected = []
for row,item in enumerate(tvNodeList.delegate.items):
if item['selected'] and not item['hidden']:
selected.append((row,item))
if selected:
item = selected[0][1] # get the first selected
oldParent = item['node']['parent']
oldLevel = item['node']['level']
for _,item in selected:
if oldParent != item['node']['parent']:
console.hud_alert("Mixed heritgate items collected. Must all have same parent")
return
result = dialogs.form_dialog("Container View",
[{'type':'text',
'key':'name',
'title':'View Name',
'value':''},
{'type':'text',
'key':'margins',
'title':'Frame Margins',
'value':'0,0,0,0'},
{'type':'text',
'key':'customView',
'title':'Custom View Class',
'value':''}
]
)
if not result:
return
customViewClass = result['customView']
name = result['name']
match = validQuadTuple.match(result['margins'])
if match:
margins = [float(x) for x in match.groups() if x]
if len(margins) != 4:
console.hud_alert("{} is invalid margin definition".format(result))
else:
console.hud_alert("{} is invalid margin definition".format(result))
return
undoStack.append((deepcopy(nodeDelegate.items),
deepcopy(walker.frameByUUID))
)
for row,item in enumerate(nodeDelegate.items):
if item['node']['uuid'] == oldParent:
oldParentRow = row
collectionFrame = collectiveSize(selected,margins)
location = "{{{}, {}}}".format(*collectionFrame[:2])
widthHeight = "{{{}, {}}}".format(*collectionFrame[2:])
collectionPyuiFrame = "{{{}, {}}}".format(location,widthHeight)
collectionUUID = str(uuid.uuid4()).upper()
childUUIDs =[]
parentFrame,parentUUID = walker.frameByUUID[oldParent]
children = []
# adjust the first generation children frames and parehhood
for row,item in selected:
thisUUID = item['node']['uuid']
thisFrame = item['node']['frame']
newFrame = (thisFrame[0] - collectionFrame[0],
thisFrame[1] - collectionFrame[1],
thisFrame[2], thisFrame[3])
thisLoc = "{{{}, {}}}".format(*newFrame[:2])
thisWH = "{{{}, {}}}".format(*newFrame[2:])
pyuiFrame = "{{{}, {}}}".format(thisLoc,thisWH)
nodeDelegate.items[row]['node']['frame'] = newFrame
nodeDelegate.items[row]['node']['attributes']['frame'] = pyuiFrame
nodeDelegate.items[row]['node']['parent'] = collectionUUID
for nodeIndex,node in enumerate(nodeDelegate.items[oldParentRow]['node']['nodes']):
if node == thisUUID:
nodeDelegate.items[oldParentRow]['node']['nodes'][nodeIndex] = collectionUUID
break
#the above will lead to redundant references to the same node. Make unique later.
walker.setFrameByUUID(thisUUID,newFrame,collectionUUID) # update the "byUUID" hash
childUUIDs.append(nodeDelegate.items[row]['node']['uuid']) #save for writing the collection view
# accululate all childrens rows (as a tree)
childwalker = ItemsWalker(nodeDelegate.items)
children.append(childwalker.walkItems([row,]))
del childwalker
nodeDelegate.items[oldParentRow]['node']['nodes'] = uniqify(nodeDelegate.items[oldParentRow]['node']['nodes'])
childrenRows = flatten(children) # get the indexes as a simple list
for row in childrenRows:
nodeDelegate.items[row]['node']['level'] += 1
thisNode = genericView.format(collectionUUID, name, collectionFrame, childUUIDs,oldLevel,collectionUUID,oldParent)
thisItem= {
'title': name,
'node' : eval(thisNode),
'selected':False,
'hidden':False,
'accessory_type':None,
}
if customViewClass:
thisItem['custom_class'] = customViewClass
insertPoint = selected[0][0]
childrenItems = [nodeDelegate.items[row] for row in childrenRows]
otherItems = [nodeDelegate.items[row] for
row in range(insertPoint+1,len(nodeDelegate.items))
if row not in childrenRows]
nodeDelegate.items.insert(insertPoint,thisItem)
nodeDelegate.listLength += 1
walker.setFrameByUUID(collectionUUID,collectionFrame,oldParent)
nodeDelegate.items[:] = nodeDelegate.items[:insertPoint+1]
for item in childrenItems:
nodeDelegate.items.append(item)
for item in otherItems:
nodeDelegate.items.append(item)
for row,_ in enumerate(nodeDelegate.items):
nodeDelegate.items[row]['selected'] = False
nodeDelegate.items[row]['hidden'] = False
tvNodeList.selected_rows = []
lastSelectedRow = -1
tvNodeList.reload_data()
viewNodeMap.set_needs_display()
@ui.in_background
def onEditFlex(button):
global v,nodeDelegate,t1,ev
selected = []
shield.conceal()
for row,item in enumerate(nodeDelegate.items):
if item['selected'] and not item['hidden']:
selected.append(row)
if len(selected) > 1:
console.hud_alert('Single selection only')
return
thisRow = selected[0]
# capture Flex here and deposit it in the interface view
flexView = v['flex_view']
flexView.thisRow = thisRow
flexView.thisFlex = nodeDelegate.items[thisRow]['node']['attributes']['flex']
for key in 'LRTBWH':
flexView.states[key] = True if key in flexView.thisFlex else False
v['flex_view'].hidden = False
v['flex_view'].bring_to_front()
v['flex_view']['flex_interface'].set_needs_display()
def repeatAnimation(event,every,action):
global flexQueue
while True:
if event.isSet():
break
if not v['flex_view'].hidden:
if not flexQueue.empty():
v['flex_view']['flex_demo']['outer']['inner'].flex = flexQueue.get()
action()
event.wait(every)
def onSelectChildren(button):
global nodeDelegate,lastSelectedRow
def markChildren(thisRow):
thisUUID = nodeDelegate.items[thisRow]['node']['uuid']
for row in range(thisRow,len(nodeDelegate.items)):
if nodeDelegate.items[row]['node']['parent'] == thisUUID:
nodeDelegate.items[row]['selected'] = True
markChildren(row)
if lastSelectedRow < 0:
return
markChildren(lastSelectedRow)
lastSelectedRow = -1
tvNodeList.reload_data()
viewNodeMap.set_needs_display()
def onQuit(button):
global v
v['flex_view'].ev.set()
v.close()
def onUndo(button):
global nodeDelegate,undoStack,walker,lastSelectedRow
if undoStack:
previousList,previousDict = undoStack.pop()
nodeDelegate.items = deepcopy(previousList)
walker.frameByUUID = deepcopy(previousDict)
for row,_ in enumerate(nodeDelegate.items):
nodeDelegate.items[row]['selected'] = False
nodeDelegate.items[row]['hidden'] = False
nodeDelegate.listLength = len(nodeDelegate.items)
lastSelectedRow = -1
tvNodeList.reload_data()
viewNodeMap.set_needs_display()
def onHideSelected(button):
global nodeDelegate
for row,item in enumerate(nodeDelegate.items):
if item['selected']:
nodeDelegate.items[row]['hidden'] = True
item['selected'] = False
viewNodeMap.set_needs_display()
tvNodeList.reload_data()
def onUnhideAll(button):
global nodeDelegate
for item in nodeDelegate.items:
item['hidden'] = False
viewNodeMap.set_needs_display()
tvNodeList.reload_data()
def onDeselectAll(button):
global nodeDelegate,lastSelectedRow
for item in nodeDelegate.items:
item['selected'] = False
lastSelectedRow = -1
viewNodeMap.set_needs_display()
tvNodeList.reload_data()
class FlexView(ui.View):
def did_load(self):
self.thisRow = -1
self.thisFlex = ''
self.states = {}
self.t1 = []
self.ev = None
def onQuit(self,button):
shield.reveal()
self.hidden = True
def onSave(self,button):
global nodeDelegate
nodeDelegate.items[self.thisRow]['node']['attributes']['flex'] = self.thisFlex
class FlexInterface(ui.View):
def did_load(self):
# This will be called when a view has been fully loaded from a UI file.
self.parent = self.superview
self.oW = self.width
self.oH = self.height
self.iW = self.width*0.60
self.iH = self.height*0.60
self.oX,self.oY = self.x, self.y
self.iX = (self.width - self.iW)/2
self.iY = (self.height - self.iH)/2
self.cX, self.cY = self.center
self.coords = {}
self.coords['T'] = ((self.cX,self.oY), (self.cX,self.iY))
self.coords['B'] = ((self.cX,self.iY+self.iH), (self.cX,self.oY+self.oH))
self.coords['L'] = ((self.oX,self.cY), (self.iX, self.cY))
self.coords['R'] = ((self.iX+self.iW, self.cY), (self.oX+self.oW, self.cY))
self.coords['H'] = ((self.cX, self.iY), (self.cX, self.iY+self.iH))
self.coords['W'] = ((self.iX, self.cY), (self.iX+self.iW, self.cY))
def draw(self):
global nodeDelegate
try:
i = self.iX
i = self.superview.states
except AttributeError: #views not fuly stabilized
return
flexLabel = self.superview['current_flex']
flexLabel.text = self.superview.thisFlex
ui.set_color('black')
inner = ui.Path.rect(self.iX,self.iY,self.iW,self.iH)
inner.stroke()
for key in self.superview.states.keys():
if key in 'RLTB':
thisType = (5,5)
headW = -6
headH = -2
else:
thisType = (2,2)
headW = -6
headH = -12
solidLine = self.superview.states[key]
if key in 'LRTB': #sense is reversed
solidLine = not solidLine
if solidLine:
ui_draw_arrow(self.coords[key][0],self.coords[key][1],pointType=thisType,
headWidth=headW, headHeight=headH)
else:
ui_draw_arrow(self.coords[key][0],self.coords[key][1],pointType=thisType,lineDash=(4,4),
headWidth=headW, headHeight=headH)
def touch_began(self, touch):
# Called when a touch begins.
location = touch.location
for key in 'LRTBWH':
line = self.coords[key]
if onLine(location,line):
self.superview.states[key] = False if self.superview.states[key] else True
i = self.superview.thisFlex.find(key)
if i != -1:
self.superview.thisFlex = self.superview.thisFlex[:i] + self.superview.thisFlex[i+1:]
else:
self.superview.thisFlex += key
flexQueue.put(self.superview.thisFlex)
self.set_needs_display()
break
def touch_moved(self, touch):
# Called when a touch moves.
pass
def touch_ended(self, touch):
# Called when a touch ends.
pass
duration = 1.0
undoStack = []
fg = FileGetter(types=['pyui','json'])
fg.getFile()
thisFile = fg.selection
fileDirectory = os.path.normpath(os.path.dirname(thisFile))
_,ext = os.path.splitext(thisFile)
if not ext in ['.pyui','.json']:
console.hud_alert('Invalid file type')
sys.exit(1)
with open(thisFile,'r') as fh:
pyui = json.load(fh)
walker = NodeListWalker()
walker.traverseNodeList(pyui)
items = [{
'title': x['name'],
'node' : x,
'selected':False,
'hidden':False,
'accessory_type':None,
}
for x in walker.nodes]
v = ui.load_view()
def outerBig():
outerDemo = v['flex_view']['flex_demo']['outer']
outerDemo.frame = (10,10,120,120)
def outerSmall():
outerDemo = v['flex_view']['flex_demo']['outer']
outerDemo.frame = (10,10,55,55)
def animation_small():
ui.animate(outerSmall, duration=duration)
def animation_big():
ui.animate(outerBig, duration=duration, completion=animation_small)
nodeDelegate = NodeTableViewDelegate(items)
tvNodeList = v['view_nodeList']
tvNodeList.delegate = nodeDelegate
tvNodeList.data_source = nodeDelegate
tvNodeList.allows_multiple_selection = True
viewNodeMap = v['nodeMap']
viewNodeMap.init(nodeDelegate)
viewNodeMap.touch_enabled = True
lastSelectedRow = -1
v['button_Collect'].action = onCollect
v['button_Quit'].action = onQuit
v['button_Save'].action = onSave
v['button_Undo'].action = onUndo
v['button_Hide_Selected'].action = onHideSelected
v['button_Unhide_All'].action = onUnhideAll
v['button_Select_Children'].action = onSelectChildren
v['button_Deselect_All'].action = onDeselectAll
v['button_edit_flex'].action = onEditFlex
v['flex_view'].hidden = True
v['flex_view']['button_Quit'].action = v['flex_view'].onQuit
v['flex_view']['button_Save'].action = v['flex_view'].onSave
v['flex_view'].ev = threading.Event()
v['flex_view'].t1 = threading.Thread(target=repeatAnimation,
args=(v['flex_view'].ev,2,animation_big))
v['flex_view'].t1.start()
fullFrame = ui.View(frame=v.frame)
fullFrame.hidden = True
v.add_subview(fullFrame)
fullFrame.send_to_back()
shield = Shield(fullFrame)
flexQueue = Queue.Queue()
v.present()