This repository was archived by the owner on Jul 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathtween_machine.py
More file actions
1290 lines (1142 loc) · 45.9 KB
/
tween_machine.py
File metadata and controls
1290 lines (1142 loc) · 45.9 KB
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
"""
tween_machine.py
"""
# Built-in
import contextlib
import json
import logging
import logging.config
import os
import sys
import tempfile
import urllib2
import webbrowser
from threading import Thread
import xml.etree.cElementTree as etree
from maya.api import OpenMaya
# Third-party
import maya.cmds as mc
import maya.mel as mel
__version__ = "3.0.0"
MAYA_VERSION = mc.about(version=True)
GITHUB_URL = 'https://github.com/alexwidener/tweenMachine'
GITHUB_ISSUES_URL = 'https://github.com/alexwidener/tweenMachine/issues'
LOG = None
def get_logger():
"""Create a stream handler and a file handler. The file handler will only log warning and above.
Returns:
logging.Logger: The global instance of the logger.
"""
global LOG
configuration = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(message)s'
},
'file_format': {
'format': '%(asctime)s [%(levelname)-8s] %(message)s'
}
},
'handlers': {
'default': {
'level': 'INFO',
'formatter': 'standard',
'class': 'logging.StreamHandler'
},
'file_handler': {
'level': 'WARNING',
'formatter': 'file_format',
'class': 'logging.handlers.RotatingFileHandler',
'filename': 'tween_machine.log'
}
},
'loggers': {
'': {
'handlers': ['default', 'file_handler'],
'level': 'INFO',
'propagate': True,
'maxBytes': 2048,
'backupCount': 5
}
}
}
temp_dir = tempfile.gettempdir()
tween_machine_dir = os.path.join(temp_dir, 'tween_machine')
if not os.path.exists(tween_machine_dir):
os.makedirs(tween_machine_dir)
configuration['handlers']['file_handler']['filename'] = os.path.join(
tween_machine_dir, configuration['handlers']['file_handler']['filename'])
if not LOG:
LOG = logging.getLogger(__name__)
logging.config.dictConfig(configuration)
return LOG
get_logger()
LOG.setLevel(logging.INFO)
def clear_menu(menu):
"""
Clear the specified menu of its current contents
"""
try:
[mc.deleteUI(i) for i in mc.menu(menu, q=True, ia=True)]
except:
pass
def defer_delete(item):
"""
Defer the deletion of a UI item to prevent Maya from crashing when that UI
item is still active as it's deleted
"""
mc.evalDeferred("mc.deleteUI('" + item + "')")
def find_ui(uitype):
found = mc.lsUI(type=uitype)
if found is None:
return ""
for item in found:
try:
doctag = eval("mc." + uitype + "(item, q=True, docTag=True)")
except RuntimeError:
doctag = ""
if doctag == "tweenMachine":
return item
return ""
def start():
"""
Convenience function to open the main tweenMachine instance
"""
TMWindowUI()
def inactive():
"""
Display a warning when a feature is not active
"""
LOG.warn('This tweenMachine feature is not currently active.')
def getCurves(pullfrom):
"""
Returns a list of only selected curves or all curves if no curves selected.
"""
curves = getSelected(pullfrom)
if curves:
return curves
else:
return mc.keyframe(pullfrom, q=True, name=True)
def getSelected(pullfrom=None):
"""
Returns a list of curves that are any keys selected.
"""
selection = []
if not pullfrom:
curves = mc.keyframe(q=True, name=True, selected=True) or []
else:
curves = mc.keyframe(pullfrom, q=True, name=True, selected=True) or []
for curve in curves:
try:
# Trace the output of the curve to find the attribute.
# attr = getFirstConnection(curve, 'output', outAttr=1, findAttribute=1)
attrs = mc.listConnections(
'{}.output'.format(curve),
d=True,
s=False,
skipConversionNodes=True,
plugs=True) or []
selection += attrs
except AttributeError:
pass
return selection
def tween(bias, nodes=None):
"""
Create the in-between key(s) on the specified nodes
"""
if isinstance(nodes, list) and not nodes:
nodes = None
# Find the current frame, where the new key will be added
currenttime = mc.timeControl("timeControl1", q=True, ra=True)[0]
# Figure out which nodes to pull from
if nodes is not None:
pullfrom = nodes
else:
pullfrom = mc.ls(sl=True)
if not pullfrom:
return
selected_curves = getSelected(pullfrom)
attributes = mc.channelBox("mainChannelBox", q=True, sma=True)
# If any curves are selected, use them first
if selected_curves:
curves = selected_curves
# If attributes are selected, use them to build curve node second
elif attributes:
curves = []
for attr in attributes:
for node in pullfrom:
fullnode = "%s.%s" % (node, attr)
if not mc.objExists(fullnode):
continue
tmp = mc.keyframe(fullnode, q=True, name=True)
if not tmp:
continue
curves += tmp
# Otherwise get curves for all nodes
else:
curves = getCurves(pullfrom)
mc.waitCursor(state=True)
# Wrap the main operation in a try/except to prevent the waitcursor from
# sticking if something should fail
try:
# If we have no curves, force a list
if curves is None:
curves = []
# Process all curves
for curve in curves:
# Find time for next and previous keys...
time_prev = mc.findKeyframe(curve, which="previous")
time_next = mc.findKeyframe(curve, which="next")
# Find previous and next tangent types
try:
in_tan_prev = mc.keyTangent(curve, time=(time_prev,), q=True,
itt=True)[0]
out_tan_prev = mc.keyTangent(curve, time=(time_prev,), q=True,
ott=True)[0]
in_tan_next = mc.keyTangent(curve, time=(time_next,), q=True,
itt=True)[0]
out_tan_next = mc.keyTangent(curve, time=(time_next,), q=True,
ott=True)[0]
# Workaround for keyTangent error in Maya 2016 Extension 2
except RuntimeError:
in_tan_prev = mel.eval("keyTangent -time %s -q -itt %s" % (time_prev, curve))[0]
out_tan_prev = mel.eval("keyTangent -time %s -q -ott %s" % (time_prev, curve))[0]
in_tan_next = mel.eval("keyTangent -time %s -q -itt %s" % (time_next, curve))[0]
out_tan_next = mel.eval("keyTangent -time %s -q -ott %s" % (time_next, curve))[0]
# Set new in and out tangent types
in_tan_new = out_tan_prev
out_tan_new = in_tan_next
# However, if any of the types (previous or next) is "fixed",
# use the global (default) tangent instead
if "fixed" in [in_tan_prev, out_tan_prev, in_tan_next, out_tan_next]:
in_tan_new = mc.keyTangent(q=True, g=True, itt=True)[0]
out_tan_new = mc.keyTangent(q=True, g=True, ott=True)[0]
elif out_tan_next == "step":
out_tan_new = out_tan_next
# Find previous and next key values
value_prev = mc.keyframe(curve, time=(time_prev,), q=True,
valueChange=True)[0]
value_next = mc.keyframe(curve, time=(time_next,), q=True,
valueChange=True)[0]
value_new = value_prev + ((value_next - value_prev) * bias)
# Set new keyframe and tangents
mc.setKeyframe(curve, t=(currenttime,), v=value_new,
ott=out_tan_new)
if in_tan_new != "step":
mc.keyTangent(curve, t=(currenttime,), itt=in_tan_new)
# If we're using the special tick, set that appropriately
if SETTINGS["use_special_tick"]:
mc.keyframe(curve, tds=True, t=(currenttime,))
except:
raise
finally:
mc.waitCursor(state=False)
mc.currentTime(currenttime)
mel.eval("global string $gMainWindow;")
windowname = mel.eval("$temp = $gMainWindow")
mc.setFocus(windowname)
class TMData(object):
"""
Core code for data organization (groups and sets)
"""
def __init__(self):
# Try to read preferences from option variables; otherwise use defaults
self.element = None
self.node = None
self.name = "selected"
self.groups = []
# Try to read the existing XML data
oldnodes = mc.ls("tmXML*")
newnodes = mc.ls("tweenMachineData")
# if True:
# return
if oldnodes:
# If we have more than one, use the first one, but warn the user
self.node = oldnodes[0]
if len(oldnodes) > 1:
LOG.warn('Multiple tweenMachine data nodes found. Using {}'.format(self.node))
# If the data is in the old format (tmXML has children), convert it
if mc.listRelatives(self.node, children=True):
LOG.info('# tweenMachine: Old data found. Converting.')
self.root = etree.XML("<tweenMachineData />")
self.tree = etree.ElementTree(self.root)
# Create base elements
buttons_element = etree.SubElement(self.root, "buttons")
buttons_element.set("height", str(SETTINGS["button_height"]))
groups_element = etree.SubElement(self.root, "groups")
# Convert option data
slider_vis_node = mc.ls("tmSliderVis*")[0]
slider_vis_value = int(mc.getAttr(slider_vis_node + ".data"))
button_vis_node = mc.ls("tmSliderVis*")[0]
button_vis_value = int(mc.getAttr(button_vis_node + ".data"))
if slider_vis_value and button_vis_value:
show_mode = "both"
else:
if slider_vis_value:
show_mode = "slider"
else:
show_mode = "buttons"
SETTINGS["show_mode"] = show_mode
# Convert button data
buttons_node = mc.ls("tmButtons*")[0]
for node in mc.listRelatives(buttons_node, children=True):
suffix = node[-1]
bcolor = str(mc.getAttr("tmButtonRGB%s.data" % suffix))
bvalue = str(mc.getAttr("tmButtonValue%s.data" % suffix))
button_element = etree.SubElement(buttons_element, "button")
button_element.set("rgb", bcolor)
button_element.set("value", bvalue)
# Convert groups and sets
group_node = mc.ls("tmGroups*")[0]
for node in mc.ls(group_node + "|tmGroup*"):
# Get the group name and order
gname = str(mc.getAttr(node + ".id"))
gorder = str(mc.getAttr(node + ".order"))
group_element = etree.SubElement(groups_element, "group")
group_element.set("name", gname)
group_element.set("index", gorder)
# Get the sets in this group
for setnode in mc.listRelatives(node, children=True):
setname = str(mc.getAttr(setnode + ".id"))
setorder = str(mc.getAttr(setnode + ".order"))
# Create a set node and add the set objects to it
set_element = etree.SubElement(group_element, "set")
set_element.set("name", setname)
set_element.set("index", setorder)
setobjs = []
for objnode in mc.listRelatives(setnode, children=True):
setobjs.append(str(mc.getAttr(objnode + ".data")))
set_element.text = " ".join(setobjs)
# Otherwise get the data from the node
else:
self.root = etree.XML(mc.getAttr(node + ".data"))
self.tree = etree.ElementTree(self.root)
# Otherwise start from scratch
else:
self.root = etree.XML("""<tweenMachineData>
<buttons height="%s">
<button rgb="0.6 0.6 0.6" value="-75" />
<button rgb="0.6 0.6 0.6" value="-60" />
<button rgb="0.6 0.6 0.6" value="-33" />
<button rgb="0.6 0.6 0.6" value="0" />
<button rgb="0.6 0.6 0.6" value="33" />
<button rgb="0.6 0.6 0.6" value="60" />
<button rgb="0.6 0.6 0.6" value="75" />
</buttons>
<groups />
</tweenMachineData>
""" % SETTINGS["button_height"])
self.tree = etree.ElementTree(self.root)
# Next: replace existing data with new XML data
if newnodes:
self.node = newnodes[0]
else:
# Capture former selection
selection = mc.ls(sl=True)
# Make the new data node
self.node = mc.createNode("transform", name="tweenMachineData")
mc.addAttr(self.node, longName="data", dataType="string")
# Reset former selection
if selection:
mc.select(selection)
else:
mc.select(clear=True)
self.save_data()
# Erase old data nodes (FUTURE: ask user to confirm)
if False:
for node in oldnodes:
mc.delete(node)
# Build groups and sets
self.group_root = self.root.find("groups")
for group in self.group_root.findall("group"):
# Build a group node
self.groups.append(TMGroup(group))
def save_data(self):
"""
Save everything to the data node
"""
mc.setAttr(self.node + ".data", etree.tostring(self.root), type="string")
def add_group(self, name):
"""
Add a named group
"""
element = etree.SubElement(self.group_root, "group")
element.set("name", name)
element.set("index", str(len(self.groups)))
self.groups.append(TMGroup(self, element))
self.save_data()
def remove_group(self, name):
"""
Remove a named group
"""
for group in self.groups:
if group.name == name:
self.group_root.remove(group._element)
self.groups.remove(group)
break
self.save_data()
class TMGroup(object):
"""
Container object for a collection of TMSet classes
"""
def __init__(self, data, element):
self.data = data
self.sets = []
self._element = element
self.index = self._element.get("index")
self.name = self._element.get("name")
# Build list of sets from XML data
for set_ in self._element.findall("set"):
self.sets.append(TMSet(set_))
def save_data(self):
"""
Call data root to save data
"""
self.data.save_data()
def add_set(self, name, index, nodes):
"""
Add the named set to affect the specified nodes
"""
element = etree.SubElement(self._element, "set")
element.set("name", name)
element.set("index", str(len(self.sets)))
element.text = " ".join(nodes)
self.sets.append(TMSet(self, element))
self.save_data()
def remove_set(self, name):
"""
Remove the named set
"""
for set_ in self.sets:
if set.name == name:
self._element.remove(set.element)
self.sets.remove(set_)
break
self.save_data()
def set_index(self, index):
"""
Set the index of the group
"""
self.index = index
self._element.set("index", str(index))
self.save_data()
def set_name(self, name):
"""
Set the name of the group
"""
self.name = name
self._element.set("name", name)
self.save_data()
# Properties
def _get_nodes(self):
"""
Return all nodes in all contained sets
"""
allnodes = []
for set_ in self.sets:
allnodes += set_.nodes
return list(set(allnodes))
nodes = property(_get_nodes)
class TMSet(object):
"""
Data class that operates on a predefined list of nodes (or no nodes, in the
case of the default selected set)
"""
def __init__(self, group=None, element=None):
self.group = group
self._element = element
self.nodes = None
self.name = None
self.index = None
# If we have an element, assume that it contains the list of nodes
if element is not None:
self._nodes = element.text.split()
self.name = element.get("name")
self.index = element.get("index")
def set_index(self, index):
"""
Set the index for this set
"""
self.index = index
if self._element:
self._element.set("index", str(index))
self.group.save_data()
def set_name(self, name):
"""
Rename this set
"""
self.name = name
if self._element:
self._element.set("name", name)
self.group.save_data()
def set_nodes(self, nodes=None):
"""
Sets the list of nodes
"""
# If no nodes were passed (or None was passed), default to the current selection
if nodes is None:
self.nodes = mc.ls(sl=True)
else:
self.nodes = nodes
if self._element:
self._element.text = " ".join(nodes)
self.group.save_data()
class TMWindowUI(object):
"""
Main tool window
"""
def __init__(self):
# Import maya.cmds at root namespace for deferred commands
mc.evalDeferred("import maya.cmds as mc")
# Check for updates
# Spawn in a Thread so we don't have blocking if user is offline or response takes too long.
Thread(target=self.update_check, args=tuple()).start()
# First get an instance of the main data class
self.data = TMData()
# Test adding a group
self.data.add_group("testing")
# Set core variables
self.docked = SETTINGS["docked"]
self.show_mode = SETTINGS["show_mode"]
self.use_overshoot = SETTINGS["use_overshoot"]
self.use_special_tick = SETTINGS["use_special_tick"]
self.window = None
self.set_ui_mode()
self._build_all_groups()
# Kick off scriptJobs
##scriptJob -p tweenMachineWin -e "SceneOpened" "deleteUI tweenMachineWin; tweenMachine;";
# scriptJob -p tweenMachineWin -e "NewSceneOpened" "deleteUI tweenMachineWin;";
# scriptJob -uid tweenMachineWin "tmRestoreTimeControl";
def _make_window(self):
"""
Make the core window that will contain all the UI elements
"""
# Make the main window
windowname = "tweenMachineWindow"
if SETTINGS["ui_mode"] != "window":
windowname = None
if SETTINGS["ui_mode"] == "window" and mc.window("tweenMachineWindow",
q=True, ex=True):
mc.deleteUI("tweenMachineWindow")
self.window = mc.window(windowname, width=300, height=50,
minimizeButton=True, maximizeButton=False, menuBar=True,
menuBarVisible=SETTINGS["show_menu_bar"],
resizeToFitChildren=True, sizeable=True,
title="tweenMachine v%s" % __version__,
docTag="tweenMachine", iconName="tweenMachine")
# Build the base UI elements
self.main_form = mc.formLayout(parent=self.window)
self.selected_row = TMSetUI(self.main_form, "Selected")
mc.formLayout(self.main_form, e=True,
attachForm=[(self.selected_row.form, "top", 0),
(self.selected_row.form, "left", 0),
(self.selected_row.form, "right", 0)])
def _make_menus(self):
"""
Make the menus
"""
# Force the show_menu_bar to a certain setting in certain modes
if SETTINGS["ui_mode"] in ["toolbar", "dock"]:
SETTINGS["show_menu_bar"] = False
# Make the base menus
if SETTINGS["show_menu_bar"]:
menus = mc.window(self.window, q=True, menuArray=True)
if menus is not None:
for menu in menus:
# if mc.menu(menu, q=True, label=True) == "File":
# self._file_menu = menu
# if mc.menu(menu, q=True, label=True) == "Tools":
# self._tool_menu = menu
if mc.menu(menu, q=True, label=True) == "Options":
self._opt_menu = menu
else:
# self._file_menu = mc.menu(label="File",
# postMenuCommand=self._make_file_menu)
# self._tool_menu = mc.menu(label="Tools",
# postMenuCommand=self._make_tool_menu)
self._opt_menu = mc.menu(label="Options",
postMenuCommand=self._make_opt_menu)
# Help menu
helpmenu = mc.menu(label="Help", helpMenu=True)
mc.menuItem(p=helpmenu, label="Support",
command=self.open_support)
mc.menuItem(p=helpmenu, label="Docs",
command=self.open_docs)
mc.evalDeferred("mc.window('%s', e=True, menuBarVisible=True)"
% self.window)
else:
if not hasattr(self, "popup_menu"):
self.popup_menu = mc.popupMenu(parent=self.main_form)
# self._file_menu = mc.menuItem(p=self.popup_menu, label="File",
# postMenuCommand=self._make_file_menu,
# subMenu=True)
# self._tool_menu = mc.menuItem(p=self.popup_menu, label="Tools",
# postMenuCommand=self._make_tool_menu,
# subMenu=True)
self._opt_menu = mc.menuItem(p=self.popup_menu, label="Options",
postMenuCommand=self._make_opt_menu,
subMenu=True)
# Help menu
helpmenu = mc.menuItem(p=self.popup_menu, label="Help", subMenu=True)
mc.menuItem(p=helpmenu, label="Support",
command=self.open_support)
mc.menuItem(p=helpmenu, label="Docs",
command=self.open_docs)
def _make_file_menu(self, *args):
"""
Make the file menu
"""
clear_menu(self._file_menu)
mc.menuItem(p=self._file_menu, label="Coming soon...", enable=False)
if True:
return
mc.menuItem(p=self._file_menu, label="New...", command=self.new)
mc.menuItem(p=self._file_menu, divider=True)
mc.menuItem(p=self._file_menu, label="Open...", command=self.load)
mc.menuItem(p=self._file_menu, label="Save...", command=self.save,
enable=len(self.data.groups) > 0)
def _make_tool_menu(self, *args):
"""
Make the tool menu
"""
clear_menu(self._tool_menu)
mc.menuItem(p=self._tool_menu, label="Coming soon...", enable=False)
if True:
return
mc.menuItem(p=self._tool_menu, label="Add Group...",
command=self._add_group_prompt)
mc.menuItem(p=self._tool_menu, label="Add Set...",
command=self._add_set_pre,
enable=len(self.data.groups) > 0)
mc.menuItem(p=self._tool_menu, divider=True)
mc.menuItem(p=self._tool_menu, label="Manage Sets and Groups...",
command=self._open_data_manager)
mc.menuItem(p=self._tool_menu, label="Manage Buttons...",
command=self._open_button_manager)
mc.menuItem(p=self._tool_menu, divider=True)
charset_menu = mc.menuItem(p=self._tool_menu, label="Character Sets...",
subMenu=True)
mc.menuItem(p=charset_menu, label="Add Character Group",
command=self._add_character_group)
mc.menuItem(p=charset_menu, label="Import Character Sets",
command=self._import_character_sets)
def _make_opt_menu(self, *args):
"""
Make the options menu
"""
clear_menu(self._opt_menu)
show_menu = mc.menuItem(p=self._opt_menu, label="Show...", subMenu=True)
# Menu bar and label visibility toggles
if SETTINGS["ui_mode"] in ["window", "dock"]:
mc.menuItem(p=show_menu, label="Menu Bar",
cb=SETTINGS["show_menu_bar"],
command=self._toggle_menu_visibility)
mc.menuItem(p=show_menu, label="Label", cb=SETTINGS["show_label"],
command=self._toggle_label_visibility)
mc.menuItem(p=show_menu, divider=True)
# Slider and button visibility options
show_collection = mc.radioMenuItemCollection(parent=show_menu)
mc.menuItem(p=show_menu, label="Slider and Buttons",
rb=self.show_mode == "both",
command=lambda x, m="both": self._set_show_mode(m))
mc.menuItem(p=show_menu, label="Slider Only",
rb=self.show_mode == "slider",
command=lambda x, m="slider": self._set_show_mode(m))
mc.menuItem(p=show_menu, label="Buttons Only",
rb=self.show_mode == "buttons",
command=lambda x, m="buttons": self._set_show_mode(m))
# UI mode options
if "2013" not in MAYA_VERSION:
mc.menuItem(p=self._opt_menu, divider=True)
mode_menu = mc.menuItem(p=self._opt_menu, label="Mode...",
subMenu=True)
mode_collection = mc.radioMenuItemCollection(parent=mode_menu)
mc.menuItem(p=mode_menu, label="Window",
rb=SETTINGS["ui_mode"] == "window",
command=lambda x, m="window": self.set_ui_mode(m))
mc.menuItem(p=mode_menu, label="Toolbar",
rb=SETTINGS["ui_mode"] == "toolbar",
command=lambda x, m="toolbar": self.set_ui_mode(m))
# mc.menuItem(p=mode_menu, label="HUD",
# rb=SETTINGS["ui_mode"] == "hud",
# command=lambda x, m="hud":self.set_ui_mode(m))
mc.menuItem(p=self._opt_menu, divider=True)
mc.menuItem(p=self._opt_menu, label="Overshoot", cb=self.use_overshoot,
command=self._toggle_overshoot)
mc.menuItem(p=self._opt_menu, label="Special Tick Color",
cb=self.use_special_tick,
command=self._toggle_special_tick)
def open_support(self, *args):
"""Open tweenMachine support in a browser"""
webbrowser.open(GITHUB_ISSUES_URL)
def open_docs(self, *args):
"""Open tweenMachine docs in a browser"""
webbrowser.open(GITHUB_URL)
def _add_group_prompt(self, *args):
"""
Open a dialog that allows the user to add a new group
"""
result = mc.promptDialog(title="Add Group", message="Enter group name",
button=["OK", "Cancel"], defaultButton="OK",
cancelButton="Cancel", dismissString="Cancel")
if result == "OK":
self._add_group(mc.promptDialog(q=True, text=True))
def _add_group(self, name):
"""
Create a group with the specified name
"""
inactive()
def _add_set_pre(self, *args):
"""
Open a dialog that allows the user to add a new set
"""
inactive()
def _add_set_post(self):
"""
Callback from the dialog made by _add_set_pre
"""
inactive()
def _open_data_manager(self, *args):
"""
Open the group/set data manager dialog
"""
inactive()
def _open_button_manager(self, *args):
"""
Open the group/set data manager dialog
"""
inactive()
def _set_show_mode(self, mode):
"""
Set the show mode
"""
self.show_mode = mode
SETTINGS["show_mode"] = mode
self.selected_row.set_show_mode(mode)
def _toggle_overshoot(self, *args):
"""
Toggle the overshoot setting
"""
self.use_overshoot = not self.use_overshoot
SETTINGS["use_overshoot"] = self.use_overshoot
self.selected_row.toggle_overshoot()
def _toggle_special_tick(self, *args):
"""
Toggle the use of the special tick color
"""
self.use_special_tick = not self.use_special_tick
SETTINGS["use_special_tick"] = self.use_special_tick
def _toggle_label_visibility(self, *args):
"""
Toggle visibility of the slider label(s)
"""
show = not SETTINGS["show_label"]
SETTINGS["show_label"] = show
self.selected_row.set_label_visibility(show)
def _toggle_menu_visibility(self, *args):
"""
Toggle visibility of the window menu
"""
show = not SETTINGS["show_menu_bar"]
SETTINGS["show_menu_bar"] = show
mc.window(self.window, e=True, menuBarVisible=show)
self._make_menus()
mc.refresh(force=True)
if show:
if self.popup_menu is not None:
mc.popupMenu(self.popup_menu, e=True, dai=True)
def _build_all_groups(self):
"""
Build the group interface(s) based on the data in the scene
"""
def _cleanup(self):
"""
Clean up stuff when the tool is closed
"""
# Restore the time control to the animation list
mc.timeControl("timeControl1", e=True, mlc="animationList")
# def window_name(self):
# return find_ui("window")
def _add_character_group(self, *args):
"""
Add a group that will work with character set data
"""
inactive()
def _import_character_sets(self, *args):
"""
Import character set data from scene
"""
inactive()
def set_ui_mode(self, mode=None):
"""
Set the UI's current state (window, dock, toolbar, HUD)
"""
oldmode = SETTINGS["ui_mode"]
# If user is in Maya 2013, force window mode until a fix can be found
# for toolbar mode
if "2013" in MAYA_VERSION:
mode = None
oldmode = "window"
# Update the UI appropriately if we're changing modes
if mode != oldmode:
if mode is None:
mode = oldmode
SETTINGS["ui_mode"] = mode
# Delete the popup menu variable so that a new one can be made
if hasattr(self, "popup_menu"):
del (self.popup_menu)
# Show the proper UI
window = self.window
if self.window is None:
window = find_ui("window")
toolbar = find_ui("toolBar")
dock = find_ui("dockControl")
self._make_window()
deleteold = None
hasmenu = True
if mode == "window":
if oldmode == "toolbar" and toolbar:
deleteold = toolbar
SETTINGS["show_menu_bar"] = True
if oldmode == "dock" and dock:
deleteold = dock
mc.showWindow(self.window)
elif mode == "toolbar":
if toolbar:
deleteold = toolbar
if oldmode == "window" and window:
deleteold = window
if oldmode == "dock" and dock:
deleteold = dock
if not mc.toolBar("tweenMachineToolbar", q=True, exists=True):
mc.toolBar("tweenMachineToolbar", height=20,
docTag="tweenMachine", content=self.window,
area="left", label="tweenMachine")
mc.windowPref(restoreMainWindowState="startupMainWindowState")
else:
mc.windowPref(saveMainWindowState="startupMainWindowState")
elif mode == "dock":
pass
elif mode == "hud":
hasmenu = False
if hasmenu:
self._make_menus()
# If we're deleting an old item, set a deferred command to do so
if deleteold is not None:
defer_delete(deleteold)
# ----- File Management --------------------------------------------------#
def new(self, *args):
"""
Flush all data and start over
"""
inactive()
def load(self, *args):
"""
Load groups and sets from a tweenMachine data file
"""
inactive()
def save(self, *args):
"""
Save groups and sets to a tweenMachine data file
"""
inactive()
@staticmethod
def update_check():
"""Check for available updates."""
url = 'https://api.github.com/repos/alexwidener/tweenMachine/releases/latest'
with contextlib.closing(urllib2.urlopen(url)) as response:
data = json.loads(response.read())
# TODO: When doing the Qt rework, add a QMessageBox
if data['tag_name'] > __version__:
LOG.info('A new version is available')
class TMSetUI(object):
"""
Base UI class for a single set, which includes a slider, a set of buttons,
a numeric field, a check box, and a label
"""
def __init__(self, parent, name, **kwds):
self.data = TMSet()
self.name = name
self.form = mc.formLayout(parent=parent)
self.showcheck = lambda: self.data.nodes is not None
self.checkbox = mc.checkBox(parent=self.form, label="",
manage=self.showcheck())
self.label = mc.text(parent=self.form, label=self.name, width=90,
manage=SETTINGS["show_label"])
mode = SETTINGS["show_mode"]
self.slider = mc.floatSlider(parent=self.form, min=-100,
max=100, value=0,
manage=mode in ["both", "slider"],
changeCommand=self.tween_slider,
dragCommand=self.update_field)
self.field = mc.floatField(parent=self.form, min=-100, max=100, value=0,
width=50, pre=1, step=1,
changeCommand=self.tween_field,
enterCommand=self.tween_field,
dragCommand=self.tween_field)
# Attach the checkbox
mc.formLayout(self.form, e=True,
attachForm=[(self.checkbox, "left", 5),
(self.checkbox, "top", 0)])
# Attach the label
mc.formLayout(self.form, e=True,
attachControl=[(self.label, "left", 5, self.checkbox)])
mc.formLayout(self.form, e=True,
attachForm=[(self.label, "top", 3)])
labelOffset = 90 * int(SETTINGS["show_label"])
# Attach the field
mc.formLayout(self.form, e=True,
attachForm=[(self.field, "left", labelOffset),
(self.field, "top", 0)])
# Attach the slider
mc.formLayout(self.form, e=True,
attachForm=[(self.slider, "left", labelOffset + 55),
(self.slider, "right", 5),
(self.slider, "top", 3)])