-
Notifications
You must be signed in to change notification settings - Fork 10
/
picker.py
1741 lines (1449 loc) · 57.6 KB
/
picker.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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import with_statement
from maya import mel
from maya.cmds import *
from baseMelUI import *
from vectors import Vector, Colour
from common import printErrorStr, printWarningStr
from mayaDecorators import d_unifyUndo
from apiExtensions import asMObject, sortByHierarchy
from triggered import resolveCmdStr, Trigger
import re
import names
import colours
import presetsUI
eval = __builtins__[ 'eval' ] #otherwise this gets clobbered by the eval in maya.cmds
TOOL_NAME = 'zooPicker'
TOOL_EXTENSION = filesystem.presets.DEFAULT_XTN
TOOL_CMD_EXTENSION = 'cmdPreset'
VERSION = 0
MODIFIERS = SHIFT, CAPS, CTRL, ALT = 2**0, 2**1, 2**2, 2**3
ADDITIVE = CTRL | SHIFT
def isValidMayaNodeName( theStr ):
validChars = 'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
for char in theStr:
if char not in validChars:
return False
return True
def getLabelWidth( theString ):
'''
some guestimate code to determine the width of a given string when displayed as
text on a ButtonUI instance
'''
wideLetters = 'abcdeghkmnopqrsuvwxyz_ '
width = 0
for char in theString:
if char in wideLetters:
width += 7
else:
width += 3
return width
def removeRefEdits( objs, cmd=None ):
'''
removes reference edits from a list of objects. if the $cmd arg is an empty string
then ALL commands are removed. if $cmd is a valid reference edit command, only those
commands are removed from the list of objects supplied
'''
refNodeLoadStateDict = {}
for obj in objs:
if referenceQuery( obj, inr=True ):
refNode = referenceQuery( obj, rfn=True )
loadState = bool( referenceQuery( refNode, n=True ) )
refNodeLoadStateDict[ refNode ] = loadState
#now unload all references so we can remove edits
for node in refNodeLoadStateDict:
file( unloadReference=node )
#remove failed edits
for obj in objs:
referenceEdit( obj, failedEdits=True, successfulEdits=False, removeEdits=True )
#remove specified edits for the objects
for obj in objs:
if cmd is None:
referenceEdit( obj, failedEdits=True, successfulEdits=True, removeEdits=True )
else:
referenceEdit( obj, failedEdits=True, successfulEdits=True, editCommand=cmd, removeEdits=True )
#now set the refs to their initial load state
for node, loadState in refNodeLoadStateDict.iteritems():
if loadState:
file( loadReference=node )
select( objs )
def getTopPickerSet():
existing = [ node for node in ls( type='objectSet', r=True ) or [] if sets( node, q=True, text=True ) == TOOL_NAME ]
if existing:
return existing[ 0 ]
else:
pickerNode = createNode( 'objectSet', n='picker' )
sets( pickerNode, e=True, text=TOOL_NAME )
return pickerNode
class Button(object):
'''
A Button instance is a "container" for a button within a picker. To instantiate a button you need to pass the set node
that contains the button data. You can create a new set node using Button.Create.
A button, when pressed, by default selects the contents of the set based on the keyboard modifiers pressed. But a button
can also define its own press command. Button press commands are stored on the cmdStr string attribute on the set node
and can be most easily edited using the editor tab created by the PickerLayout UI.
'''
SELECTION_STATES = NONE, PARTIAL, COMPLETE = range( 3 )
CMD_MODES = MODE_SELECTION_FIRST, MODE_CMD_FIRST, MODE_CMD_ONLY = range( 3 )
CMD_MODES_NAMES = 'selection first', 'cmd first', 'cmd only'
MIN_SIZE, MAX_SIZE = 5, 100
DEFAULT_SIZE = 14, 14
DEFAULT_COLOUR = tuple( Colour( (0.25, 0.25, 0.3) ).asRGB() )
AUTO_COLOUR = None
COLOUR_PARTIAL, COLOUR_COMPLETE = (1, 0.6, 0.5), Colour( 'white' ).asRGB()
DEFAULT_ATTRS = ( { 'ln': 'posSize', 'dt': 'string' }, #stuff pos and size into a single str attr - so lazy...
{ 'ln': 'colour', 'dt': 'string' },
{ 'ln': 'label', 'dt': 'string' },
{ 'ln': 'cmdStr', 'dt': 'string' },
{ 'ln': 'cmdIsPython', 'at': 'bool', 'dv': False },
{ 'ln': 'cmdMode', 'at': 'enum', 'enumName': ':'.join( CMD_MODES_NAMES ), 'dv': MODE_SELECTION_FIRST }
)
@classmethod
def Create( cls, character, pos, size=DEFAULT_SIZE, colour=AUTO_COLOUR, label=None, objs=(), cmdStr=None, cmdIsPython=False ):
node = sets( em=True, text='zooPickerButton' )
sets( node, e=True, add=character.getNode() )
cls.ValidateNode( node )
self = cls( node )
self.setPosSize( pos, size )
self.setLabel( label )
self.setObjs( objs )
self.setCmdStr( cmdStr )
self.setCmdIsPython( cmdIsPython )
#if the colour is set to "AUTO_COLOUR" then try to determine the button colour based off the object's colour
if colour is cls.AUTO_COLOUR:
self.setColour( cls.DEFAULT_COLOUR )
self.setAutoColour()
else:
self.setColour( colour )
return self
@classmethod
def ValidateNode( cls, node ):
for addAttrKw in cls.DEFAULT_ATTRS:
if not objExists( '%s.%s' % (node, addAttrKw[ 'ln' ]) ):
addAttr( node, **addAttrKw )
def __init__( self, node ):
self.__node = asMObject( node )
def __repr__( self ):
return "%s( '%s' )" % (type( self ).__name__, self.getNode())
__str__ = __repr__
def __eq__( self, other ):
'''
two buttons are equal on if all their attributes are the same
'''
return self.getCharacter() == other.getCharacter() and \
self.getPos() == other.getPos() and \
self.getSize() == other.getSize() and \
self.getColour() == other.getColour() and \
self.getLabel() == other.getLabel() and \
self.getObjs() == other.getObjs() and \
self.getCmdStr() == other.getCmdStr() and \
self.getCmdIsPython() == other.getCmdIsPython()
def __ne__( self, other ):
return not self.__eq__( other )
def __hash__( self ):
return hash( self.getNode() )
def getNode( self ):
return unicode( self.__node )
def getCharacter( self ):
cons = listConnections( self.getNode(), type='objectSet', s=False )
if cons:
return Character( cons[0] )
def getPosSize( self ):
valStr = getAttr( '%s.posSize' % self.getNode() )
if valStr is None:
return Vector( (0,0,0) ), self.DEFAULT_SIZE
posStr, sizeStr = valStr.split( ';' )
pos = Vector( [ int( p ) for p in posStr.split( ',' ) ] )
size = Vector( [ int( p ) for p in sizeStr.split( ',' ) ] )
return pos, size
def getPos( self ): return self.getPosSize()[0]
def getSize( self ): return self.getPosSize()[1]
def getColour( self ):
rgbStr = getAttr( '%s.colour' % self.getNode() )
if rgbStr is None:
return self.DEFAULT_COLOUR
rgb = rgbStr.split( ',' )
rgb = map( float, rgb )
return Colour( rgb )
def getLabel( self ):
return getAttr( '%s.label' % self.getNode() )
def getNiceLabel( self ):
labelStr = self.getLabel()
#if there is no label AND the button has objects, communicate this to the user
if not labelStr:
if len( self.getObjs() ) > 1:
return '+'
return labelStr
def getObjs( self ):
return sets( self.getNode(), q=True ) or []
def getCmdStr( self ): return getAttr( '%s.cmdStr' % self.getNode() )
def getCmdIsPython( self ): return getAttr( '%s.cmdIsPython' % self.getNode() )
def getCmdMode( self ):
try:
return getAttr( '%s.cmdMode' % self.getNode() )
except TypeError:
self.ValidateNode( self.getNode() )
return getAttr( '%s.cmdMode' % self.getNode() )
def getResolvedCmdStr( self ):
cmdStr = self.getCmdStr()
if self.getCmdIsPython():
return cmdStr % locals()
else:
return resolveCmdStr( cmdStr, self.getNode(), self.getObjs() )
def setPosSize( self, pos, size ):
#make sure the pos/size values are ints...
pos = map( int, map( round, pos ) )
size = map( int, map( round, size ) )
posStr = ','.join( map( str, pos ) )
sizeStr = ','.join( map( str, size ) )
valStr = setAttr( '%s.posSize' % self.getNode(), '%s;%s' % (posStr, sizeStr), type='string' )
def setPos( self, val ):
if not isinstance( val, Vector ):
val = Vector( val )
p, s = self.getPosSize()
self.setPosSize( val, s )
def setSize( self, val ):
if not isinstance( val, Vector ):
val = Vector( val )
p, s = self.getPosSize()
self.setPosSize( p, val )
def setColour( self, val ):
if val is None:
val = self.DEFAULT_COLOUR
valStr = ','.join( map( str, val ) )
setAttr( '%s.colour' % self.getNode(), valStr, type='string' )
def setLabel( self, val ):
if val is None:
val = ''
setAttr( '%s.label' % self.getNode(), val, type='string' )
#rename the node to reflect the label
try:
if val and isValidMayaNodeName( val ):
rename( self.getNode(), val )
else:
objs = self.getObjs()
if objs:
rename( self.getNode(), '%s_picker' % objs[0] )
else:
rename( self.getNode(), 'picker' )
#this generally happens if the node is referenced... its no big deal if the rename fails - renaming just happens to make the sets slightly more comprehendible when outliner surfing
except RuntimeError: pass
def setObjs( self, val ):
if isinstance( val, basestring ):
val = [ val ]
if not val:
return
sets( e=True, clear=self.getNode() )
sets( val, e=True, add=self.getNode() )
def setCmdStr( self, val ):
if val is None:
val = ''
setAttr( '%s.cmdStr' % self.getNode(), val, type='string' )
def setCmdIsPython( self, val ):
setAttr( '%s.cmdIsPython' % self.getNode(), val )
def setCmdMode( self, val ):
setAttr( '%s.cmdMode' % self.getNode(), val )
def setAutoColour( self, defaultColour=None ):
objs = self.getObjs()
for obj in objs:
colour = colours.getObjColour( obj )
if colour:
self.setColour( colour )
return
if defaultColour is not None:
self.setColour( defaultColour )
def select( self, forceModifiers=None, executeCmd=True ):
'''
this is what happens when a user "clicks" or "selects" this button. It handles executing the button
command in the desired order and handling object selection
'''
cmdMode = self.getCmdMode()
#if we're executing the command only, execute it and bail
if cmdMode == self.MODE_CMD_ONLY:
if executeCmd:
self.executeCmd()
return
#if we're executing the command first - do it
if cmdMode == self.MODE_CMD_FIRST:
if executeCmd:
self.executeCmd()
if forceModifiers is None:
mods = getModifiers()
else:
mods = forceModifiers
objs = self.getObjs()
if objs:
if mods & SHIFT and mods & CTRL:
select( objs, add=True )
elif mods & SHIFT:
select( objs, toggle=True )
elif mods & CTRL:
select( objs, deselect=True )
else:
select( objs )
if cmdMode == self.MODE_SELECTION_FIRST:
if executeCmd:
self.executeCmd()
def selectedState( self ):
'''
returns whether this button is partially or fully selected - return values are one of the
values in self.SELECTION_STATES
'''
objs = self.getObjs()
sel = ls( objs, sl=True )
if not sel:
return self.NONE
elif len( objs ) == len( sel ):
return self.COMPLETE
return self.PARTIAL
def moveBy( self, offset ):
pos = self.getPos()
self.setPos( pos + offset )
def exists( self ):
return objExists( self.getNode() )
def isEmpty( self ):
return not bool( self.getObjs() )
def executeCmd( self ):
'''
executes the command string for this button
'''
cmdStr = self.getResolvedCmdStr()
if cmdStr:
try:
if self.getCmdIsPython():
return eval( cmdStr )
else:
return maya.mel.eval( "{%s;}" % cmdStr )
except:
printErrorStr( 'Executing command "%s" on button "%s"' % (cmdStr, self.getNode()) )
def duplicate( self ):
dupe = self.Create( self.getCharacter(), self.getPos(), self.getSize(),
self.getColour(), self.getLabel(), self.getObjs(),
self.getCmdStr(), self.getCmdIsPython() )
return dupe
def mirrorObjs( self ):
'''
replaces the objects in this button with their name based opposites - ie if this button contained the
object ctrl_L, this method would replace the objects with ctrl_R. It uses names.swapParity
'''
oppositeObjs = []
for obj in self.getObjs():
opposite = names.swapParity( obj )
if opposite:
oppositeObjs.append( opposite )
self.setObjs( oppositeObjs )
def delete( self ):
delete( self.getNode() )
class Character(object):
'''
A Character is made up of many Button instances to select the controls or groups of controls that
comprise a puppet rig. A Character is also stored as a set node in the scene. New Character nodes
can be created using Character.Create, or existing ones instantiated by passing the set node to
Character.
'''
DEFAULT_BG_IMAGE = 'pickerGrid.bmp'
@classmethod
def IterAll( cls ):
for node in ls( type='objectSet' ):
if sets( node, q=True, text=True ) == 'zooPickerCharacter':
yield cls( node )
@classmethod
def Create( cls, name ):
'''
creates a new character for the picker tool
'''
node = sets( em=True, text='zooPickerCharacter' )
node = rename( node, name )
sets( node, e=True, add=getTopPickerSet() )
addAttr( node, ln='version', at='long' )
addAttr( node, ln='name', dt='string' )
addAttr( node, ln='bgImage', dt='string' )
addAttr( node, ln='bgColour', dt='string' )
addAttr( node, ln='filepath', dt='string' )
setAttr( '%s.version' % node, VERSION )
setAttr( '%s.name' % node, name, type='string' )
setAttr( '%s.bgImage' % node, cls.DEFAULT_BG_IMAGE, type='string' )
setAttr( '%s.bgColour' % node, '0,0,0', type='string' )
#lock the node - this stops maya from auto-deleting it if all buttons are removed
lockNode( node )
self = cls( node )
allButton = self.createButton( (5, 5), (25, 14), (1, 0.65, 0.25), 'all', [], '%(self)s.getCharacter().selectAllButtonObjs()', True )
return self
def __init__( self, node ):
self.__node = asMObject( node )
def __repr__( self ):
return "%s( '%s' )" % (type( self ).__name__, self.getNode())
__str__ = __repr__
def __eq__( self, other ):
return self.getNode() == other.getNode()
def __ne__( self, other ):
return not self.__eq__( other )
def getNode( self ):
return unicode( self.__node )
def getButtons( self ):
buttonNodes = sets( self.getNode(), q=True ) or []
return [ Button( node ) for node in buttonNodes ]
def getName( self ):
return getAttr( '%s.name' % self.getNode() )
def getBgImage( self ):
return getAttr( '%s.bgImage' % self.getNode() )
def getBgColour( self ):
colStr = getAttr( '%s.bgColour' % self.getNode() )
return Colour( [ float( c ) for c in colStr.split( ',' ) ] ).asRGB()
def getFilepath( self ):
return getAttr( '%s.filepath' % self.getNode() )
def setName( self, val ):
setAttr( '%s.name' % self.getNode(), str( val ), type='string' )
lockNode( self.getNode(), lock=False )
rename( self.getNode(), val )
lockNode( self.getNode(), lock=True )
def setBgImage( self, val ):
setAttr( '%s.bgImage' % self.getNode(), val, type='string' )
def setBgColour( self, val ):
valStr = ','.join( map( str, val ) )
setAttr( '%s.bgColour' % self.getNode(), valStr, type='string' )
def setFilepath( self, filepath ):
setAttr( '%s.filepath' % self.getNode(), filepath, type='string' )
def createButton( self, pos, size, colour=None, label=None, objs=(), cmdStr=None, cmdIsPython=False ):
'''
appends a new button to the character - a new Button instance is returned
'''
return Button.Create( self, pos, size, colour, label, objs, cmdStr, cmdIsPython )
def removeButton( self, button, delete=True ):
'''
given a Button instance, will remove it from the character
'''
for aButton in self.getButtons():
if button == aButton:
sets( button.getNode(), e=True, remove=self.getNode() )
if delete:
button.delete()
return
def breakoutButton( self, button, direction, padding=5, colour=None ):
'''
doing a "breakout" on a button will basically take each object in the button and
create a new button for it in the given direction
'''
buttonPos, buttonSize = button.getPosSize()
colour = button.getColour()
posIncrement = Vector( direction ).normalize()
posIncrement[0] *= buttonSize[0] + padding
posIncrement[1] *= buttonSize[1] + padding
newButtons = []
objs = button.getObjs()
#figure out which axis to use to sort the objects - basically figure out which axis has the highest delta between smallest and largest
posObjs = [ (Vector( xform( obj, q=True, ws=True, rp=True ) ), obj) for obj in objs ]
bestDelta, bestSorting = 0, []
for n in range( 3 ):
sortedByN = [ (objPos[n], obj) for objPos, obj in posObjs ]
sortedByN.sort()
delta = abs( sortedByN[-1][0] - sortedByN[0][0] )
if delta > bestDelta:
bestDelta, bestSorting = delta, sortedByN
#now we've figured out which axis is the most appropriate axis and have the best sorting, build the buttons
objs = [ obj for objPosN, obj in bestSorting ]
#if the direction is positive (which is down the screen in the picker), then we want to breakout the buttons in ascending hierarchical fashion
ascending = True
if direction[0] < 0 or direction[1] < 0:
ascending = False
if ascending:
objs.reverse()
for obj in objs:
buttonPos += posIncrement
button = self.createButton( buttonPos, buttonSize, objs=[ obj ] )
button.setAutoColour( colour )
newButtons.append( button )
return newButtons
def selectAllButtonObjs( self ):
for button in self.getButtons():
button.select( ADDITIVE, False )
def isEmpty( self ):
if objExists( self.getNode() ):
return not self.getButtons()
return False
def delete( self ):
for button in self.getButtons():
button.delete()
node = self.getNode()
lockNode( node, lock=False )
delete( node )
def saveToPreset( self, filepath ):
'''
stores this picker character out to disk
'''
filepath = filesystem.Path( filepath )
if filepath.exists():
filepath.editoradd()
with open( filepath, 'w' ) as fOpen:
infoDict = {}
infoDict[ 'version' ] = VERSION
infoDict[ 'name' ] = self.getName()
infoDict[ 'bgImage' ] = self.getBgImage() or ''
infoDict[ 'bgColour' ] = tuple( self.getBgColour() )
fOpen.write( str( infoDict ) )
fOpen.write( '\n' )
#the preset just needs to contain a list of buttons
for button in self.getButtons():
buttonDict = {}
pos, size = button.getPosSize()
buttonDict[ 'pos' ] = tuple( pos )
buttonDict[ 'size' ] = tuple( size )
buttonDict[ 'colour' ] = tuple( button.getColour() )
buttonDict[ 'label' ] = button.getLabel()
buttonDict[ 'objs' ] = button.getObjs()
buttonDict[ 'cmdStr' ] = button.getCmdStr()
buttonDict[ 'cmdIsPython' ] = button.getCmdIsPython()
buttonDict[ 'cmdMode' ] = button.getCmdMode()
fOpen.write( str( buttonDict ) )
fOpen.write( '\n' )
#store the filepath on the character node
self.setFilepath( filepath.unresolved() )
@classmethod
def LoadFromPreset( cls, filepath, namespaceHint=None ):
'''
'''
filepath = filesystem.Path( filepath )
#make sure the namespaceHint - if we have one - doesn't end in a semi-colon
if namespaceHint:
if namespaceHint.endswith( ':' ):
namespaceHint = namespaceHint[ :-1 ]
buttonDicts = []
with open( filepath ) as fOpen:
lineIter = iter( fOpen )
try:
infoLine = lineIter.next()
infoDict = eval( infoLine.strip() )
while True:
buttonLine = lineIter.next()
buttonDict = eval( buttonLine.strip() )
buttonDicts.append( buttonDict )
except StopIteration: pass
version = infoDict.pop( 'version', 0 )
newCharacter = cls.Create( infoDict.pop( 'name', 'A Picker' ) )
newCharacter.setBgImage( infoDict.pop( 'bgImage', cls.DEFAULT_BG_IMAGE ) )
newCharacter.setBgColour( infoDict.pop( 'bgColour', (0, 0, 0) ) )
#if there is still data in the infoDict print a warning - perhaps new data was written to the file that was handled when loading the preset?
if infoDict:
printWarningStr( 'Not all info was loaded from %s on to the character: %s still remains un-handled' % (filepath, infoDict) )
for buttonDict in buttonDicts:
newButton = Button.Create( newCharacter, buttonDict.pop( 'pos' ),
buttonDict.pop( 'size' ),
buttonDict.pop( 'colour', Button.DEFAULT_COLOUR ),
buttonDict.pop( 'label', '' ) )
newButton.setCmdStr( buttonDict.pop( 'cmdStr', '' ) )
newButton.setCmdIsPython( buttonDict.pop( 'cmdIsPython', False ) )
newButton.setCmdMode( buttonDict.pop( 'cmdMode', Button.MODE_SELECTION_FIRST ) )
#now handle objects - this is about the only tricky part - we want to try to match the objects stored to file to objects in this scene as best we can
objs = buttonDict.pop( 'objs', [] )
realObjs = []
for obj in objs:
#does the exact object exist?
if objExists( obj ):
realObjs.append( obj )
continue
#how about inserting a namespace in-between any path tokens?
pathToks = obj.split( '|' )
if namespaceHint:
objNs = '|'.join( '%s:%s' % (namespaceHint, tok) for tok in pathToks )
if objExists( objNs ):
realObjs.append( objNs )
continue
#how about ANY matches on the leaf path token?
anyMatches = ls( pathToks[-1] )
if anyMatches:
realObjs.append( anyMatches[0] )
if not namespaceHint:
namespaceHint = ':'.join( anyMatches[0].split( ':' )[ :-1 ] )
newButton.setObjs( realObjs )
#print a warning if there is still data in the buttonDict - perhaps new data was written to the file that was handled when loading the preset?
if buttonDict:
printWarningStr( 'Not all info was loaded from %s on to the character: %s still remains un-handled' % (filepath, infoDict) )
return newCharacter
def _drag( *a ):
'''
passes the local coords the widget is being dragged from
'''
return [a[-3], a[-2]]
def _drop( src, tgt, msgs, x, y, mods ):
'''
this is the drop handler used by everything in this module
'''
src = BaseMelUI.FromStr( src )
tgt = BaseMelUI.FromStr( tgt )
#if dragging an existing button around on the form, interpret it as a move
if isinstance( src, ButtonUI ) and isinstance( tgt, DragDroppableFormLayout ):
srcX, srcY = map( int, msgs )
x -= srcX
y -= srcY
#figure out the delta moved
curX, curY = src.button.getPos()
delta = x - curX, y - curY
charUI = src.getParentOfType( CharacterUI )
buttonsToMove = charUI.getSelectedButtonUIs()
#if the button dragged isn't in the selection - add it to the selection
if src not in buttonsToMove:
buttonsToMove.insert( 0, src )
charUI.setSelectedButtonUIs( buttonsToMove )
#now move all the buttons by the given delta
for buttonUI in buttonsToMove:
buttonUI.button.moveBy( delta )
buttonUI.updateGeometry( False )
#finally, refresh the BG image
charUI.refreshImage()
#if dragging from the form to the form, or dragging from the creation button, interpret it as a create new button
elif isinstance( src, CreatePickerButton ) and isinstance( tgt, DragDroppableFormLayout ) or \
isinstance( src, DragDroppableFormLayout ) and isinstance( tgt, DragDroppableFormLayout ):
characterUI = tgt.getParentOfType( CharacterUI )
if characterUI:
newButton = characterUI.createButton( (x, y) )
class ButtonUI(MelIconButton):
def __init__( self, parent, button ):
MelIconButton.__init__( self, parent )
self.setColour( button.getColour() )
assert isinstance( button, Button )
self.button = button
self.state = Button.NONE
self( e=True, dgc=_drag, dpc=_drop, style='textOnly', c=self.on_press )
self.POP_menu = MelPopupMenu( self, pmc=self.buildMenu )
self._hashGeo = 0
self._hashApp = 0
self.update()
def buildMenu( self, *a ):
menu = self.POP_menu
isEditorOpen = EditorWindow.Exists()
menu.clear()
editButtonKwargs = { 'l': 'edit this button',
'c': self.on_edit,
'ann': 'opens the button editor which allows you to edit properties of this button - colour, size, position etc...' }
if isEditorOpen:
MelMenuItem( menu, l='ADD selection to button', c=self.on_add, ann='adds the selected scene objects to this button' )
MelMenuItem( menu, l='REPLACE button with selection', c=self.on_replace, ann="replaces this button's objects with the selected scene objects" )
MelMenuItem( menu, l='REMOVE selection from button', c=self.on_remove, ann='removes the selected scene objects from this button' )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='mirror duplicate button', c=self.on_mirrorDupe )
MelMenuItem( menu, l='move to mirror position', c=self.on_mirrorThis )
MelMenuItemDiv( menu )
MelMenuItem( menu, **editButtonKwargs )
MelMenuItem( menu, l='select highlighted buttons', c=self.on_selectHighlighted, ann='selects all buttons that are highlighted (ie are %s)' % Colour.ColourToName( Button.COLOUR_COMPLETE ) )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='breakout UP', c=self.on_breakoutUp, ann='for each object in this button, creates a button above this one' )
MelMenuItem( menu, l='breakout DOWN', c=self.on_breakoutDown, ann='for each object in this button, creates a button below this one' )
MelMenuItem( menu, l='<-- breakout LEFT', c=self.on_breakoutLeft, ann='for each object in this button, creates a button to the left of this one' )
MelMenuItem( menu, l='breakout RIGHT -->', c=self.on_breakoutRight, ann='for each object in this button, creates a button to the right of this one' )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='DELETE this button', c=self.on_delete, ann='deletes the button being right clicked on' )
MelMenuItem( menu, l='DELETE selected buttons', c=self.on_deleteSelected, ann='deletes all selected buttons. NOTE: this is not necessarily the highlighted buttons - look in the button editor for the list of buttons that are selected' )
else:
class Callback(object):
def __init__( self, func, *a ):
self.f = func
self.a = a
def __call__( self, *a ):
return self.f( *self.a )
buttonObjs = self.button.getObjs()
if len( buttonObjs ) == 1:
objTrigger = Trigger( buttonObjs[0] )
for slot, menuName, menuCmd in objTrigger.iterMenus( True ):
MelMenuItem( menu, l=menuName, c=Callback( mel.eval, menuCmd ) )
MelMenuItemDiv( menu )
MelMenuItem( menu, **editButtonKwargs )
def updateHighlightState( self ):
selectedState = self.button.selectedState()
if self.state == selectedState:
return
if selectedState == Button.PARTIAL:
self.setColour( Button.COLOUR_PARTIAL )
elif selectedState == Button.COMPLETE:
self.setColour( Button.COLOUR_COMPLETE )
else:
self.setColour( self.button.getColour() )
self.state = selectedState
def isButtonHighlighted( self ):
return self.button.selectedState()
def update( self ):
self.updateGeometry()
self.updateAppearance()
self.updateHighlightState()
def updateGeometry( self, refreshUI=True ):
posSize = pos, size = self.button.getPosSize()
x, y = pos
#check against the stored hash - early out if they match
if hash( posSize ) == self._hashGeo:
return
#clamp the pos to the size of the parent
parent = self.getParent()
maxX, maxY = parent.getSize()
#x = min( max( x, 0 ), maxX ) #NOTE: this is commented out because it seems maya reports the size of the parent to be 0, 0 until there are children...
#y = min( max( y, 0 ), maxY )
parent( e=True, ap=((self, 'top', y, 0), (self, 'left', x, 0)) )
self.setSize( size )
#store the hash - geo hashes are stored so that we can do lazy refreshes
self._hashGeo = hash( posSize )
if refreshUI:
self.sendEvent( 'refreshImage' )
def updateAppearance( self ):
niceLabel = self.button.getNiceLabel()
if hash( niceLabel ) == self._hashApp:
return
self.setLabel( niceLabel )
self._hashApp = hash( niceLabel )
def mirrorDuplicate( self ):
dupe = self.button.duplicate()
dupe.mirrorObjs()
dupe.setAutoColour( self.button.getColour() )
self.mirrorPosition( dupe )
#if the button has a label - see if it has a parity and if so, reverse it
label = self.button.getLabel()
if label:
newLabel = names.swapParity( label )
dupe.setLabel( newLabel )
self.sendEvent( 'appendButton', dupe, True )
def mirrorPosition( self, button=None ):
if button is None:
button = self.button
pickerLayout = self.getParentOfType( PickerLayout )
pickerWidth = pickerLayout( q=True, w=True )
pos, size = button.getPosSize()
buttonCenterX = pos.x + (size.x / 2)
newPosX = pickerWidth - buttonCenterX - size.x
newPosX = min( max( newPosX, 0 ), pickerWidth )
button.setPos( (newPosX, pos.y) )
### EVENT HANDLERS ###
def on_press( self, *a ):
self.button.select()
self.sendEvent( 'buttonSelected', self )
def on_add( self, *a ):
objs = self.button.getObjs()
objs += ls( sl=True ) or []
self.button.setObjs( objs )
def on_replace( self, *a ):
self.button.setObjs( ls( sl=True ) or [] )
def on_remove( self, *a ):
objs = self.button.getObjs()
objs += ls( sl=True ) or []
self.button.setObjs( objs )
def on_mirrorDupe( self, *a ):
self.mirrorDuplicate()
def on_mirrorThis( self, *a ):
self.mirrorPosition()
self.updateGeometry()
def on_edit( self, *a ):
self.sendEvent( 'buttonSelected', self )
self.sendEvent( 'on_showEditor' )
def on_selectHighlighted( self, *a ):
self.sendEvent( 'selectHighlightedButtons' )
def on_breakoutUp( self, *a ):
self.sendEvent( 'breakoutButton', self, (0, -1) )
def on_breakoutDown( self, *a ):
self.sendEvent( 'breakoutButton', self, (0, 1) )
def on_breakoutLeft( self, *a ):
self.sendEvent( 'breakoutButton', self, (-1, 0) )
def on_breakoutRight( self, *a ):
self.sendEvent( 'breakoutButton', self, (1, 0) )
def on_delete( self, *a ):
self.delete()
self.button.delete()
self.sendEvent( 'refreshImage' )
self.sendEvent( 'updateButtonList' )
def on_deleteSelected( self, *a ):
self.sendEvent( 'deleteSelectedButtons' )
class MelPicture(BaseMelWidget):
WIDGET_CMD = picture
def getImage( self ):
return self( q=True, i=True )
def setImage( self, image ):
self( e=True, i=image )
class DragDroppableFormLayout(MelFormLayout):
def __init__( self, parent, **kw ):
MelFormLayout.__init__( self, parent, **kw )
self( e=True, dgc=_drag, dpc=_drop )
class CharacterUI(MelHLayout):
def __init__( self, parent, character ):
self.character = character
self._selectedButtonUIs = []
self.UI_picker = MelPicture( self, en=False, dgc=_drag, dpc=_drop )
self.UI_picker.setImage( character.getBgImage() )
self.layout()
self.UI_buttonLayout = UI_buttonLayout = DragDroppableFormLayout( self )
self( e=True, af=((UI_buttonLayout, 'top', 0), (UI_buttonLayout, 'left', 0), (UI_buttonLayout, 'right', 0), (UI_buttonLayout, 'bottom', 0)) )
self.populate()
self.highlightButtons()
self.setDeletionCB( self.on_close )
def populate( self ):
for button in self.character.getButtons():
self.appendButton( button )
def updateEditor( self ):
self.sendEvent( 'updateEditor' )
def updateButtonList( self ):
self.sendEvent( 'updateButtonList' )
def createButton( self, pos, size=Button.DEFAULT_SIZE, colour=Button.AUTO_COLOUR, label='', objs=None ):
if objs is None:
objs = ls( sl=True, type='transform' )
newButton = Button.Create( self.character, pos, size, colour, label, objs )
#we want the drop position to be the centre of the button, not its edge - so we need to factor out the size, which we can only do after instantiating the button so we can query its size
sizeHalf = newButton.getSize() / 2.0
newButton.setPos( Vector( pos ) - sizeHalf )
self.appendButton( newButton, True )
#tell the editor to update the button list
self.sendEvent( 'updateButtonList' )
return newButton
def appendButton( self, button, select=False ):
ui = ButtonUI( self.UI_buttonLayout, button )
if select:
self.buttonSelected( ui )
self.updateButtonList()
return ui
def highlightButtons( self ):
for buttonUI in self.getButtonUIs():
buttonUI.updateHighlightState()
def getSelectedButtonUIs( self ):
selButtonUIs = []
for buttonUI in self._selectedButtonUIs:
if buttonUI.button.exists():
selButtonUIs.append( buttonUI )
return selButtonUIs
def setSelectedButtonUIs( self, buttonUIs ):
self._selectedButtonUIs = buttonUIs[:]
self.updateEditor()
def selectHighlightedButtons( self ):
currentSelection = []
for buttonUI in self.getButtonUIs():
if buttonUI.isButtonHighlighted() == Button.COMPLETE:
currentSelection.append( buttonUI )
self.setSelectedButtonUIs( currentSelection )
def breakoutButton( self, buttonUI, direction ):
buttons = self.character.breakoutButton( buttonUI.button, direction )
for button in buttons:
self.appendButton( button )
def refreshImage( self ):
self.UI_picker.setVisibility( False )
self.UI_picker.setVisibility( True )
self.updateEditor()
def buttonSelected( self, button ):
mods = getModifiers()
if mods & SHIFT and mods & CTRL:
if button not in self._selectedButtonUIs:
self._selectedButtonUIs.append( button )
elif mods & CTRL:
if button in self._selectedButtonUIs:
self._selectedButtonUIs.remove( button )
elif mods & SHIFT:
if button in self._selectedButtonUIs:
self._selectedButtonUIs.remove( button )
else:
self._selectedButtonUIs.append( button )