Esempio n. 1
1
def mayaUIContent(parent):
    """ Contents by Maya standard UI widgets """

    layout = cmds.columnLayout(adjustableColumn=True, parent=parent)

    cmds.frameLayout("Sample Frame 1", collapsable=True)
    cmds.columnLayout(adjustableColumn=True, rowSpacing=2)
    cmds.button("maya button 1")
    cmds.button("maya button 2")
    cmds.button("maya button 3")
    cmds.setParent('..')
    cmds.setParent('..')

    cmds.frameLayout("Sample Frame 2", collapsable=True)
    cmds.gridLayout(numberOfColumns=6, cellWidthHeight=(35, 35))
    cmds.shelfButton(image1="polySphere.png", rpt=True, c=cmds.polySphere)
    cmds.shelfButton(image1="sphere.png", rpt=True, c=cmds.sphere)
    cmds.setParent('..')
    cmds.setParent('..')

    cmds.setParent('..')  # columnLayout

    ptr = OpenMayaUI.MQtUtil.findLayout(layout)
    obj = shiboken2.wrapInstance(long(ptr), QtWidgets.QWidget)

    return obj
Esempio n. 2
0
def mainWindow():

    omui.MQtUtil.mainWindow()
    ptr = omui.MQtUtil.mainWindow()

    print QtWidgets.__file__
    widget = wrapInstance(long(ptr), QtWidgets.QWidget)
Esempio n. 3
0
def getMainWindow():
    """
    Returns the main maya window as the appropriate QObject to use as a parent.
    """

    ptr = omui.MQtUtil.mainWindow()
    qObj = shiboken2.wrapInstance(long(ptr), QtCore.QObject)
    metaObj = qObj.metaObject()
    cls = metaObj.className()
    superCls = metaObj.superClass().className()
    if hasattr(QtWidgets, cls):
        base = getattr(QtWidgets, cls)
    elif hasattr(QtWidgets, superCls):
        base = getattr(QtWidgets, superCls)
    else:
        base = QtWidgets.QWidget
    mainWin = shiboken2.wrapInstance(long(ptr), base)

    return mainWin
Esempio n. 4
0
    def pysideWrapInstance(ptr, base=None):
        '''Utility to convert a point to a Qt Class and produce the same result
        as sip.wrapinstance using shiboken.wrapInstance.

        Note: This is modeled after nathanhorne.com/?p=486. The base arg isn't
        currently used, and defaults to QObject. The way that base arg was used
        seems like it would give a different result than the sip version. It would
        skip the checking for attribute and just use base as base, however the sip
        version will still return QMainWindow even if QObject is passed in.
        '''
        if ptr is None:
            return

        try:
            import PySide2.QtCore as qtcore
            import PySide2.QtGui as qtgui
            import PySide2.QtWidgets as qtwidgets
            from shiboken2 import wrapInstance
        except ImportError:
            import shiboken
            import PySide.QtCore as qtcore
            import PySide.QtGui as qtgui
            import PySide.QtGui as qtwidgets
            from shiboken import wrapInstance

        qObj = wrapInstance(long(ptr), qtcore.QObject)

        metaObj = qObj.metaObject()
        cls = metaObj.className()
        superCls = metaObj.superClass().className()
        if hasattr(qtgui, cls):
            base = getattr(qtgui, cls)
        elif hasattr(qtgui, superCls):
            base = getattr(qtgui, superCls)
        elif hasattr(qtwidgets, cls):
            base = getattr(qtwidgets, cls)
        elif hasattr(qtwidgets, superCls):
            base = getattr(qtwidgets, superCls)
        else:
            base = qtwidgets.QWidget
        return wrapInstance(long(ptr), base)
Esempio n. 5
0
    def __init__(self):
        ptr = OpenMayaUI.MQtUtil.mainWindow()
        parent = shiboken.wrapInstance(long(ptr), QtGui.QMainWindow)

        super(ProgressHandler, self).__init__(parent=parent)

        self._progress_value = None
        self._message = None
        self._timer = QtCore.QTimer(parent=self)

        self._timer.timeout.connect(self._update_progress)
        self._timer.start(self.PROGRESS_INTERVAL)
Esempio n. 6
0
 def wrapinstance(ptr):
     """
     Convert a pointer (int or long) into the concrete
     PyQt/PySide object it represents.
     """
     ptr = long(ptr)
     # Get the pointer as a QObject, and use metaObject
     # to find a better type.
     qobj = shiboken.wrapInstance(ptr, QtCore.QObject)
     metaobj = qobj.metaObject()
     # Look for the real class in qt namespaces.
     # If not found, walk up the hierarchy.
     # When we reach the top of the Qt hierarchy,
     # we'll break out of the loop since we'll eventually
     # reach QObject.
     realcls = None
     while realcls is None:
         realcls = _getcls(metaobj.className())
         metaobj = metaobj.superClass()
     # Finally, return the same pointer/object
     # as its most specific type.
     return shiboken.wrapInstance(ptr, realcls)
Esempio n. 7
0
    def testWrapInstance(self):
        addr = ObjectType.createObjectType()
        obj = shiboken.wrapInstance(addr, ObjectType)
        self.assertFalse(shiboken.createdByPython(obj))
        obj.setObjectName("obj")
        self.assertEqual(obj.objectName(), "obj")
        self.assertEqual(addr, obj.identifier())
        self.assertFalse(shiboken.createdByPython(obj))

        # avoid mem leak =]
        bb = BlackBox()
        self.assertTrue(shiboken.createdByPython(bb))
        bb.disposeObjectType(bb.keepObjectType(obj))
Esempio n. 8
0
def build_workspace_control_ui(shotgun_panel_name):
    """
    Embeds a Shotgun app panel into the calling Maya workspace control.

    This function will be called in two cases:
    - When the workspace control is being created by Maya command workspaceControl;
    - When the workspace control is being restored from a workspace control state
      created by Maya when this workspace control was previously closed and deleted.

    .. note:: This function is only for Maya 2017 and later.

    :param shotgun_panel_name: Name of the Qt widget at the root of a Shotgun app panel.
    """

    import maya.api.OpenMaya
    import maya.utils
    from maya.OpenMayaUI import MQtUtil

    # In the context of this function, we know that we are running in Maya 2017 and later
    # with the newer versions of PySide and shiboken.
    from PySide2 import QtWidgets
    from shiboken2 import wrapInstance

    # Retrieve the calling Maya workspace control.
    ptr = MQtUtil.getCurrentParent()
    workspace_control = wrapInstance(long(ptr), QtWidgets.QWidget)

    # Search for the Shotgun app panel widget.
    for widget in QtWidgets.QApplication.allWidgets():
        if widget.objectName() == shotgun_panel_name:

            # Reparent the Shotgun app panel widget under Maya workspace control.
            widget.setParent(workspace_control)

            # Add the Shotgun app panel widget to the Maya workspace control layout.
            workspace_control.layout().addWidget(widget)

            # Install an event filter on Maya workspace control to monitor
            # its close event in order to reparent the Shotgun app panel widget
            # under Maya main window for later use.
            panel_util.install_event_filter_by_widget(workspace_control, shotgun_panel_name)

            break
    else:
        msg = "Shotgun: Cannot restore %s: Shotgun app panel not found" % shotgun_panel_name
        fct = maya.api.OpenMaya.MGlobal.displayError
        maya.utils.executeInMainThreadWithResult(fct, msg)
Esempio n. 9
0
def get_main_window():
    '''<QtWidgets.QWidget> or NoneType: Cast Maya's window to widget.'''
    window_ptr = omui.MQtUtil.mainWindow()

    # The pointer returns None in command-line (mayapy) under situational
    # circumstances (I'm being vague because I don't know why this sometimes
    # happens). In which case, just return None
    #
    if window_ptr is None:
        return

    try:
        obj = long(window_ptr)
    except TypeError:
        return

    return wrapInstance(obj, QtWidgets.QWidget)
Esempio n. 10
0
    def _get_dialog_parent(self):
        """
        Get the QWidget parent for all dialogs created through
        show_dialog & show_modal.
        """
        # Find a parent for the dialog - this is the Maya mainWindow()
        from tank.platform.qt import QtGui
        import maya.OpenMayaUI as OpenMayaUI

        try:
            import shiboken2 as shiboken
        except ImportError:
            import shiboken

        ptr = OpenMayaUI.MQtUtil.mainWindow()
        parent = shiboken.wrapInstance(long(ptr), QtGui.QMainWindow)

        return parent
Esempio n. 11
0
def _on_parent_closed_callback(widget_id):
    """
    Callback which fires when a panel is closed.
    This will locate the widget with the given id
    and close and delete this.
    
    :param widget_id: Object name of widget to close
    """
    widget = _find_widget(widget_id)
    if widget:
        # Use the proper close logic according to the Maya version.
        if mel.eval("getApplicationVersionAsFloat()") < 2017:
            # Close and delete the Shotgun app panel widget.
            # It needs to be deleted later since we are inside a slot.
            widget.close()
            widget.deleteLater()
        else:  # Maya 2017 and later
            # Reparent the Shotgun app panel widget under Maya main window for later use.
            ptr = OpenMayaUI.MQtUtil.mainWindow()
            main_window = shiboken.wrapInstance(long(ptr), QtGui.QMainWindow)
            widget.setParent(main_window)
Esempio n. 12
0
import check_fun

try:
    from PySide2.QtCore import *
    from PySide2.QtGui import *
    from PySide2.QtWidgets import *
    from PySide2.QtUiTools import *
    from shiboken2 import wrapInstance
except ImportError:
    from PySide.QtCore import *
    from PySide.QtGui import *
    from PySide.QtUiTools import *
    from shiboken import wrapInstance

mayaMainWindowPtr = OMUI.MQtUtil.mainWindow()
mayaMainWindow = wrapInstance(long(mayaMainWindowPtr), QWidget)


class SceneCheck(QWidget):
    def __init__(self, *args, **kwargs):
        super(SceneCheck, self).__init__(*args, **kwargs)
        self.setParent(mayaMainWindow)
        self.setWindowFlags(Qt.Window)
        self.setWindowTitle("Scene Clean up场景清理")
        self.initUI()

    def initUI(self):
        loader = QUiLoader()
        file_path = os.path.abspath(getsourcefile(lambda: 0))  #获取脚本的绝对路径
        currentUI = file_path.replace(
            file_path.split('\\')[-1], "scene_check.ui")
def maya_main_window():
    """
    Return the Maya main window widget as a Python object
    """
    main_window_ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(main_window_ptr), QtWidgets.QWidget)
Esempio n. 14
0
def get_mayamainwindow():
    pointer = omUI.MQtUtil.mainWindow()
    return wrapInstance(long(pointer), QtWidgets.QMainWindow)
Esempio n. 15
0
def build_gui_help_auto_FK():
    '''Builds the help window. You can reset persistent settings in here.'''
    window_name = "build_gui_help_auto_FK"
    if cmds.window(window_name, exists=True):
        cmds.deleteUI(window_name, window=True)

    cmds.window(window_name,
                title=script_name + " Help",
                mnb=False,
                mxb=False,
                s=True)
    cmds.window(window_name, e=True, s=True, wh=[1, 1])

    cmds.columnLayout("main_column", p=window_name)

    # Title Text
    cmds.separator(h=12, style='none')  # Empty Space
    cmds.rowColumnLayout(nc=1, cw=[(1, 310)], cs=[(1, 10)],
                         p="main_column")  # Window Size Adjustment
    cmds.rowColumnLayout(nc=1, cw=[(1, 300)], cs=[(1, 10)],
                         p="main_column")  # Title Column
    cmds.text(script_name + " Help",
              bgc=[0, .5, 0],
              fn="boldLabelFont",
              align="center")
    cmds.separator(h=10, style='none', p="main_column")  # Empty Space

    # Body ====================
    cmds.rowColumnLayout(nc=1, cw=[(1, 300)], cs=[(1, 10)], p="main_column")
    cmds.text(l='This script generates FK controls for joints while storing',
              align="left")
    cmds.text(l='their transforms in groups.', align="left")
    cmds.text(l='Select desired joints and run script.', align="left")
    cmds.separator(h=15, style='none')  # Empty Space
    cmds.text(l='Colorize Controls:', align="left", fn="boldLabelFont")
    cmds.text(l='Automatically colorize controls according to their',
              align="left")
    cmds.text(l='names (prefix). It ignores uppercase/lowercase. ',
              align="left")
    cmds.text(l='No Prefix = Yellow', align="left")
    cmds.text(l='"l_" or "left_" = Blue', align="left")
    cmds.text(l='"r_" or "right_" = Red', align="left")
    cmds.separator(h=15, style='none')  # Empty Space
    cmds.text(l='Select Hierarchy: ', align="left", fn="boldLabelFont")
    cmds.text(l='Automatically selects the rest of the hierarchy of the',
              align="left")
    cmds.text(l='selected object, thus allowing you to only select the',
              align="left")
    cmds.text(l='root joint before creating controls.', align="left")
    cmds.separator(h=15, style='none')  # Empty Space
    cmds.text(l='(Advanced) Custom Curve:', align="left", fn="boldLabelFont")
    cmds.text(l='You can change the curve used for the creation of the',
              align="left")
    cmds.text(l='controls. Use the script "GT Generate Python Curve"',
              align="left")
    cmds.text(l='to generate the code you need to enter here.', align="left")
    cmds.separator(h=15, style='none')  # Empty Space
    cmds.text(l='Joint, Control, and Control Group Tag:',
              align="left",
              fn="boldLabelFont")
    cmds.text(l='Used to determine the suffix of the elements.', align="left")
    cmds.text(l='Joint Tag is removed from the joint name for the control.',
              align="left")
    cmds.text(l='Control Tag is added to the generated control.', align="left")
    cmds.text(l='Control Group Tag is added to the control group.',
              align="left")
    cmds.text(
        l='(This is the transform carrying the transforms of the joint).',
        align="left")
    cmds.separator(h=15, style='none')  # Empty Space
    cmds.text(l='Ignore Joints Containing These Strings: ',
              align="left",
              fn="boldLabelFont")
    cmds.text(l='The script will ignore joints containing these strings.',
              align="left")
    cmds.text(l='To add multiple strings use commas - ",".', align="left")
    cmds.separator(h=15, style='none')  # Empty Space
    cmds.rowColumnLayout(nc=2,
                         cw=[(1, 140), (2, 140)],
                         cs=[(1, 10), (2, 0)],
                         p="main_column")
    cmds.text('Guilherme Trevisan  ')
    cmds.text(
        l='<a href="mailto:[email protected]">[email protected]</a>',
        hl=True,
        highlightColor=[1, 1, 1])
    cmds.rowColumnLayout(nc=2,
                         cw=[(1, 140), (2, 140)],
                         cs=[(1, 10), (2, 0)],
                         p="main_column")
    cmds.separator(h=15, style='none')  # Empty Space
    cmds.text(l='<a href="https://github.com/TrevisanGMW">Github</a>',
              hl=True,
              highlightColor=[1, 1, 1])
    cmds.separator(h=7, style='none')  # Empty Space

    # Close Button
    cmds.rowColumnLayout(nc=1, cw=[(1, 300)], cs=[(1, 10)], p="main_column")
    cmds.separator(h=10, style='none')
    cmds.button(l='Reset Persistent Settings',
                h=30,
                c=lambda args: reset_persistent_settings_auto_fk())
    cmds.separator(h=5, style='none')
    cmds.button(l='OK', h=30, c=lambda args: close_help_gui())
    cmds.separator(h=8, style='none')

    # Show and Lock Window
    cmds.showWindow(window_name)
    cmds.window(window_name, e=True, s=False)

    # Set Window Icon
    qw = omui.MQtUtil.findWindow(window_name)
    widget = wrapInstance(long(qw), QWidget)
    icon = QIcon(':/question.png')
    widget.setWindowIcon(icon)

    def close_help_gui():
        '''Function to close the help UI, created for the "OK" Button'''
        if cmds.window(window_name, exists=True):
            cmds.deleteUI(window_name, window=True)
Esempio n. 16
0
def get_main_maya_window():
    ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(ptr), QMainWindow)
Esempio n. 17
0
def getMayaWindow():
    #get maya main window
    win = omui.MQtUtil_mainWindow()
    ptr = wrapInstance(long(win), QtWidgets.QMainWindow)

    return ptr
Esempio n. 18
0
from PySide2.QtWidgets import *
from shiboken2 import wrapInstance
from maya import OpenMayaUI as omui
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
from maya.app.general.mayaMixin import MayaQDockWidget

__author__ = "chris.thwaites"
__email__ = "*****@*****.**"
__docs__ = "https://github.com/ChrisTwaitees/Samson"

# Maya imports
import maya.cmds as mc

# Maya Main Window Hook
MAYA_MAIN_WINDOW_PTR = omui.MQtUtil.mainWindow()
MAYA_MAIN_WINDOW = wrapInstance(long(MAYA_MAIN_WINDOW_PTR), QWidget)


# QUICK UTILS - Style
def standard_icons_dict(icon_name):
    return {
        "Exit": "SP_BrowserStop",
        "OpenFile": "SP_DialogOpenButton",
        "Check": "SP_DialogApplyButton",
        "Save": "SP_DialogSaveButton",
        "Refresh": "SP_BrowserReload",
        "Add": "SP_FileDialogNewFolder",
        "New": "SP_FileDialogNewFolder",
        "Delete": "SP_DialogDiscardButton",
        "Trash": "SP_TrashIcon",
        "Next": "SP_ToolBarHorizontalExtensionButton",
Esempio n. 19
0
def build_gui_generate_text_curve():
    window_name = "build_gui_generate_text_curve"
    if cmds.window(window_name, exists=True):
        cmds.deleteUI(window_name)

    # Main GUI Start Here =================================================================================

    # Build UI
    build_gui_generate_text_curve = cmds.window(window_name, title=script_name + "  v" + script_version,\
                          titleBar=True, mnb=False, mxb=False, sizeable =True)

    cmds.window(window_name, e=True, s=True, wh=[1, 1])

    column_main = cmds.columnLayout()

    form = cmds.formLayout(p=column_main)

    content_main = cmds.columnLayout(adj=True)

    # Title Text
    cmds.separator(h=10, style='none')  # Empty Space
    cmds.rowColumnLayout(nc=1, cw=[(1, 270)], cs=[(1, 10)],
                         p=content_main)  # Window Size Adjustment
    cmds.rowColumnLayout(nc=3,
                         cw=[(1, 10), (2, 200), (3, 50)],
                         cs=[(1, 10), (2, 0), (3, 0)],
                         p=content_main)  # Title Column
    cmds.text(" ", bgc=[0, .5, 0])  # Tiny Empty Green Space
    cmds.text(script_name + " - v" + script_version,
              bgc=[0, .5, 0],
              fn="boldLabelFont",
              align="left")
    cmds.button(l="Help",
                bgc=(0, .5, 0),
                c=lambda x: build_gui_help_generate_text_curve())
    cmds.separator(h=10, style='none', p=content_main)  # Empty Space

    # Body ====================
    body_column = cmds.rowColumnLayout(nc=1,
                                       cw=[(1, 260)],
                                       cs=[(1, 10)],
                                       p=content_main)

    cmds.separator(h=7, style='none', p=body_column)  # Empty Space

    cmds.rowColumnLayout(nc=2,
                         cw=[(1, 80), (2, 170)],
                         cs=[(1, 0), (2, 0)],
                         p=body_column)
    cmds.text('Current Font:')
    font_button = cmds.button(h=17,
                              l=default_font,
                              c=lambda x: change_text_font())

    cmds.rowColumnLayout(nc=1, cw=[(1, 260)], cs=[(1, 0)], p=body_column)

    cmds.separator(h=15, p=body_column)
    cmds.text('Text:', p=body_column)
    desired_text = cmds.textField(p=body_column,
                                  text="hello, world",
                                  enterCommand=lambda x: generate_text_curve())
    cmds.separator(h=10, style='none')  # Empty Space
    cmds.button(p=body_column,
                l="Generate",
                bgc=(.6, .8, .6),
                c=lambda x: generate_text_curve())
    cmds.separator(h=10, style='none', p=content_main)  # Empty Space

    # Show and Lock Window
    cmds.showWindow(build_gui_generate_text_curve)
    cmds.window(window_name, e=True, s=False)

    # Set Window Icon
    qw = omui.MQtUtil.findWindow(window_name)
    widget = wrapInstance(long(qw), QWidget)
    icon = QIcon(':/text.png')
    widget.setWindowIcon(icon)

    # Main GUI Ends Here =================================================================================

    # Main Function Starts ----------------------
    def generate_text_curve():
        strings = parse_text_field_commas(
            cmds.textField(desired_text, q=True, text=True))
        for string in strings:
            create_text(string, current_font.get('current_font'))

    # Change Font
    def change_text_font():
        strings = parse_text_field_commas(
            cmds.textField(desired_text, q=True, text=True))
        new_font = cmds.fontDialog()
        print(new_font)
        if new_font != '':
            new_font_short_name = new_font.split('|')[0]
            current_font['current_font'] = new_font
            cmds.button(font_button, e=True, label=new_font_short_name)
Esempio n. 20
0
    from PySide2.QtGui import *
    from PySide2.QtCore import *
except ImportError:
    from PySide.QtGui import *
    from PySide.QtCore import *
try:
    imp.find_module("shiboken2")
    import shiboken2 as shiboken
except ImportError:
    import shiboken

MAYA_VER = int(cmds.about(v=True)[:4])
MAYA_API_VER = int(cmds.about(api=True))

try:
    MAYA_WIDNOW = shiboken.wrapInstance(long(OpenMayaUI.MQtUtil.mainWindow()),
                                        QWidget)
except:
    MAYA_WIDNOW = None


#MayaWindow単独取得関数
def get_maya_window():
    try:
        return shiboken.wrapInstance(long(OpenMayaUI.MQtUtil.mainWindow()),
                                     QWidget)
    except:
        return None


class MainWindow(QMainWindow):
    def __init__(self, parent=MAYA_WIDNOW):
Esempio n. 21
0
def build_gui_gt_check_for_updates():
    ''' Build a GUI to show current and latest versions '''
    window_name = "build_gui_gt_check_for_updates"
    if cmds.window(window_name, exists=True):
        cmds.deleteUI(window_name, window=True)

    cmds.window(window_name, title= 'GT Check for Updates - (v' + script_version + ')', mnb=False, mxb=False, s=True)
    cmds.window(window_name, e=True, s=True, wh=[1,1])

    cmds.columnLayout("main_column", p= window_name)
   
    # Title Text
    title_bgc_color = (.4, .4, .4)
    cmds.separator(h=12, style='none') # Empty Space
    cmds.rowColumnLayout(nc=1, cw=[(1, 410)], cs=[(1, 10)], p="main_column") # Window Size Adjustment
    cmds.rowColumnLayout(nc=1, cw=[(1, 400)], cs=[(1, 10)], p="main_column") # Title Column
    cmds.text("GT Check for Updates", bgc=title_bgc_color,  fn="boldLabelFont", align="center")
    cmds.separator(h=10, style='none', p="main_column") # Empty Space

    # Body ====================
    checklist_spacing = 4

    cmds.text(l='\ngithub.com/TrevisanGMW/gt-tools', align="center")
    cmds.separator(h=7, style='none') # Empty Space
    
    
    general_column_width = [(1, 210),(2, 110),(4, 37)]
    
    cmds.rowColumnLayout(nc=3, cw=general_column_width, cs=[(1, 18),(2, 0),(3, 0),(4, 0)], p="main_column")
    cmds.text(l='Status:', align="center", fn="boldLabelFont")
    update_status = cmds.text(l='...', align="center")
    cmds.separator(h=7, style='none') # Empty Space
    
    cmds.separator(h=7, style='none') # Empty Space
    
    cmds.rowColumnLayout(nc=3, cw=general_column_width, cs=[(1, 18),(2, 0),(3, 0),(4, 0)], p="main_column")
    cmds.text(l='Web Response:', align="center", fn="boldLabelFont")
    web_response_text = cmds.text(l='...', align="center", fn="tinyBoldLabelFont", bgc=(1, 1, 0))
    cmds.separator(h=7, style='none') # Empty Space
    
    cmds.separator(h=7, style='none') # Empty Space
    
    cmds.rowColumnLayout(nc=3, cw=general_column_width, cs=[(1, 18),(2, 0),(3, 0),(4, 0)], p="main_column")
    cmds.text(l='Installed Version:', align="center", fn="boldLabelFont")
    installed_version_text = cmds.text(l='...', align="center")
    cmds.separator(h=7, style='none') # Empty Space
    
    cmds.separator(h=7, style='none') # Empty Space
    
    cmds.rowColumnLayout(nc=3, cw=general_column_width, cs=[(1, 18),(2, 0),(3, 0),(4, 0)], p="main_column")
    cmds.text(l='Latest Release:', align="center", fn="boldLabelFont")
    latest_version_text = cmds.text(l='...', align="center")
    cmds.separator(h=7, style='none') # Empty Space

    
    cmds.separator(h=15, style='none') # Empty Space

    # Changelog =============
    cmds.rowColumnLayout(nc=1, cw=[(1, 400)], cs=[(1, 10)], p="main_column")
    cmds.text(l='Latest Release Changelog:', align="center", fn="boldLabelFont") 
    cmds.text(l='Use the refresh button to check again:', align="center", fn="smallPlainLabelFont") 
    cmds.separator(h=checklist_spacing, style='none') # Empty Space
   
   
    output_scroll_field = cmds.scrollField(editable=False, wordWrap=True, fn="obliqueLabelFont")
    
    cmds.separator(h=10, style='none') # Empty Space

    # Refresh Button
    cmds.rowColumnLayout(nc=2, cw=[(1, 280),(2, 115)], cs=[(1,10),(2,5)], p="main_column")
    auto_update_btn = cmds.button(l='Auto Check For Updates: Activated', h=30, c=lambda args: toggle_auto_updater())
    auto_updater_interval_btn = cmds.button(l='Interval: 15 days', h=30, c=lambda args: change_auto_update_interval())
    cmds.rowColumnLayout(nc=1, cw=[(1, 400)], cs=[(1,10)], p="main_column")
    cmds.separator(h=5, style='none')
    cmds.button(l='Refresh', h=30, c=lambda args: reroute_errors('check_for_updates'))
    cmds.separator(h=8, style='none')
    update_btn = cmds.button(l='Update', h=30, en=False, c=lambda args: reroute_errors('open_releases_page'))
    cmds.separator(h=8, style='none')
    
    # Show and Lock Window
    cmds.showWindow(window_name)
    cmds.window(window_name, e=True, s=False)
    
    # Set Window Icon
    qw = omui.MQtUtil.findWindow(window_name)
    widget = wrapInstance(long(qw), QWidget)
    icon = QIcon(':/SP_FileDialogToParent_Disabled.png')
    widget.setWindowIcon(icon)
    

    def toggle_auto_updater(refresh_only=False):
        ''' 
        Toggle the auto check for updates button while updating an optionVar that controls this behaviour
        
                Parameters:
                    refresh_only (bool): Is it only refreshing or toggling?

        '''
        persistent_auto_updater_exists = cmds.optionVar(exists=('gt_check_for_updates_auto_active'))
        if persistent_auto_updater_exists:
            current_status = bool(cmds.optionVar(q=("gt_check_for_updates_auto_active")))
        else:
            current_status = gt_check_for_updates.get('def_auto_updater_status')
        
        if refresh_only:
            if current_status:
                cmds.button(auto_update_btn, e=True, label='Auto Check For Updates: Activated')
                cmds.button(auto_updater_interval_btn, e=True, en=True)
            else:
                cmds.button(auto_update_btn, e=True, label='Auto Check For Updates: Deactivated')
                cmds.button(auto_updater_interval_btn, e=True, en=False)
                
        
        if not refresh_only:
            if current_status:
                cmds.button(auto_update_btn, e=True, label='Auto Check For Updates: Deactivated')
                cmds.optionVar( iv=('gt_check_for_updates_auto_active', int(False)))
                cmds.button(auto_updater_interval_btn, e=True, en=False)
            else:
                cmds.button(auto_update_btn, e=True, label='Auto Check For Updates: Activated')
                cmds.optionVar( iv=('gt_check_for_updates_auto_active', int(True)))
                cmds.button(auto_updater_interval_btn, e=True, en=True)

    def change_auto_update_interval(refresh_only=False):
        ''' 
        Toggle the auto check for updates button while updating an optionVar that controls this behaviour
        
                Parameters:
                    refresh_only (bool): Is it only refreshing or toggling?

        '''
        check_interval = gt_check_for_updates.get('def_auto_updater_interval')
        persistent_check_interval_exists = cmds.optionVar(exists=('gt_check_for_updates_interval_days'))
        if persistent_check_interval_exists:
            check_interval = int(cmds.optionVar(q=("gt_check_for_updates_interval_days")))
                  
        interval_list = {'five_days' : 5,
                         'half_month' : 15,
                         'one_month' : 30,
                         'three_months' : 91,
                         'six_months': 182,
                         'one_year': 365}
                
        if not refresh_only:
            if check_interval == interval_list.get('five_days'):
                check_interval = interval_list.get('half_month')
                cmds.optionVar( iv=('gt_check_for_updates_interval_days', int(check_interval)))
            elif check_interval == interval_list.get('half_month'):
                check_interval = interval_list.get('one_month')
                cmds.optionVar( iv=('gt_check_for_updates_interval_days', int(check_interval)))
            elif check_interval == interval_list.get('one_month'):
                check_interval = interval_list.get('three_months')
                cmds.optionVar( iv=('gt_check_for_updates_interval_days', int(check_interval)))
            elif check_interval == interval_list.get('three_months'):
                check_interval = interval_list.get('six_months')
                cmds.optionVar( iv=('gt_check_for_updates_interval_days', int(check_interval)))
            elif check_interval == interval_list.get('six_months'):
                check_interval = interval_list.get('one_year')
                cmds.optionVar( iv=('gt_check_for_updates_interval_days', int(check_interval)))
            elif check_interval == interval_list.get('one_year'):
                check_interval = interval_list.get('five_days') # Restart
                cmds.optionVar( iv=('gt_check_for_updates_interval_days', int(check_interval)))
                
        new_interval = ''
        if check_interval == interval_list.get('half_month') or check_interval == interval_list.get('one_month') or check_interval == interval_list.get('five_days'):
            new_interval = str(check_interval) + ' days'
        elif check_interval == interval_list.get('three_months'):
            new_interval = '3 months'
        elif check_interval == interval_list.get('six_months'):
            new_interval = '6 months'
        elif check_interval == interval_list.get('one_year'):
            new_interval = '1 year'

        cmds.button(auto_updater_interval_btn, e=True, label='Interval: ' + new_interval)

    
    def reroute_errors(operation):
        ''' Wrap functions around a try and catch to avoid big crashes during runtime '''
        try:
            if operation == 'open_releases_page':
                open_releases_page()
            else:
                check_for_updates()
        except Exception as exception:
            cmds.scrollField(output_scroll_field, e=True, clear=True)
            cmds.scrollField(output_scroll_field, e=True, ip=0, it=str(exception) + '\n')
    
    
    def open_releases_page():
        ''' Opens a web browser with the latest release '''
        cmds.showHelp ('https://github.com/TrevisanGMW/gt-tools/releases/latest', absolute=True) 
      
        
    def check_for_updates():
        ''' 
        Compare versions and update text accordingly 
        It uses "get_github_release" to check for updates
        '''
        
        def execute_operation():
            # Define Current Version
            stored_gt_tools_version_exists = cmds.optionVar(exists=("gt_tools_version"))

            if stored_gt_tools_version_exists:
                gt_check_for_updates['current_version'] = "v" + str(cmds.optionVar(q=("gt_tools_version")))
            else:
                gt_check_for_updates['current_version'] = 'v0.0.0'
            
            # Retrive Latest Version
            response_list = get_github_release(gt_tools_latest_release_api)

            gt_check_for_updates['latest_version'] = response_list[0].get('tag_name') or "v0.0.0"
            
            success_codes = [200, 201, 202, 203, 204, 205, 206]
            web_response_color = (0, 1, 0)
            if response_list[1] not in success_codes:
                web_response_color = (1, .5, .5)
                
            cmds.text(web_response_text, e=True, l=response_list[2], bgc=web_response_color)
            cmds.text(installed_version_text, e=True, l=gt_check_for_updates.get('current_version'))
            cmds.text(latest_version_text, e=True, l=gt_check_for_updates.get('latest_version'))
            
            current_version_int = int(re.sub("[^0-9]", "", str(gt_check_for_updates.get('current_version'))))
            latest_version_int = int(re.sub("[^0-9]", "", str(gt_check_for_updates.get('latest_version'))))
            
            if current_version_int < latest_version_int:
                cmds.button(update_btn, e=True, en=True, bgc=(.6, .6, .6))
                cmds.text(update_status, e=True, l="New Update Available!", fn="tinyBoldLabelFont", bgc=(1, .5, .5))
            elif current_version_int > latest_version_int:
                cmds.text(update_status, e=True, l="Unreleased update!", fn="tinyBoldLabelFont", bgc=(.7, 0 , 1))
                cmds.button(update_btn, e=True, en=False)
            else:
                cmds.text(update_status, e=True, l="You're up to date!", fn="tinyBoldLabelFont", bgc=(0, 1, 0))
                cmds.button(update_btn, e=True, en=False)
            
            published_at = ''
            try:
                published_at = response_list[0].get('published_at').split('T')[0]
            except:
                pass
            
            cmds.scrollField(output_scroll_field, e=True, clear=True)
            cmds.scrollField(output_scroll_field, e=True, ip=0, it=(response_list[0].get('tag_name') + (' ' * 80) + '(' + published_at + ')\n'))
            cmds.scrollField(output_scroll_field, e=True, ip=0, it=response_list[0].get('body'))
            
            if latest_version_int != 0:
                try:
                    previous_version = str(latest_version_int - 1)
                    previous_version_tag = 'v'
                    for c in previous_version:
                        previous_version_tag += c + '.'
                    previous_version_tag = previous_version_tag[:-1]
                    
                    before_previous_version = str(latest_version_int - 2)
                    before_previous_version_tag = 'v'
                    for c in before_previous_version:
                        before_previous_version_tag += c + '.'
                    before_previous_version_tag = before_previous_version_tag[:-1]
                    

                    previous_version_response = get_github_release(gt_tools_tag_release_api + previous_version_tag)
                    before_previous_version_response = get_github_release(gt_tools_tag_release_api + before_previous_version_tag)
                    
                    if previous_version_response[1] in success_codes:
                        published_at = ''
                        try:
                            published_at = previous_version_response[0].get('published_at').split('T')[0]
                        except:
                            pass
                        cmds.scrollField(output_scroll_field, e=True, ip=0, it='\n\n' + (previous_version_response[0].get('tag_name') + (' ' * 80) + '(' + published_at + ')\n'))
                        cmds.scrollField(output_scroll_field, e=True, ip=0, it=previous_version_response[0].get('body'))
                    

                    
                    if before_previous_version_response[1] in success_codes:
                        published_at = ''
                        try:
                            published_at = before_previous_version_response[0].get('published_at').split('T')[0]
                        except:
                            pass
                        cmds.scrollField(output_scroll_field, e=True, ip=0, it='\n\n' + (before_previous_version_response[0].get('tag_name') + (' ' * 80) + '(' + published_at + ')\n'))
                        cmds.scrollField(output_scroll_field, e=True, ip=0, it=before_previous_version_response[0].get('body'))

                except:
                    pass
                
            if response_list[1] not in success_codes:
                cmds.text(update_status, e=True, l="Unknown", fn="tinyBoldLabelFont", bgc=(1, .5, .5))
                
            cmds.scrollField(output_scroll_field, e=True, ip=1, it='') # Bring Back to the Top
        
        # Threaded Operation
        def threaded_operation():
            try:
                utils.executeDeferred(execute_operation)
            except Exception as e:
                print(e)
                
        thread = threading.Thread(None, target = threaded_operation)
        thread.start()
        
    # Refresh When Opening
    reroute_errors('')
    
    # Refresh Buttons
    toggle_auto_updater(refresh_only=True)
    change_auto_update_interval(refresh_only=True)
Esempio n. 22
0
def build_gui_help_generate_text_curve():
    window_name = "build_gui_help_generate_text_curve"
    if cmds.window(window_name, exists=True):
        cmds.deleteUI(window_name, window=True)

    cmds.window(window_name,
                title=script_name + " Help",
                mnb=False,
                mxb=False,
                s=True)
    cmds.window(window_name, e=True, s=True, wh=[1, 1])

    cmds.columnLayout("main_column", p=window_name)

    # Title Text
    cmds.separator(h=12, style='none')  # Empty Space
    cmds.rowColumnLayout(nc=1, cw=[(1, 310)], cs=[(1, 10)],
                         p="main_column")  # Window Size Adjustment
    cmds.rowColumnLayout(nc=1, cw=[(1, 300)], cs=[(1, 10)],
                         p="main_column")  # Title Column
    cmds.text(script_name + " Help",
              bgc=[0, .5, 0],
              fn="boldLabelFont",
              align="center")
    cmds.separator(h=10, style='none', p="main_column")  # Empty Space

    # Body ====================
    cmds.rowColumnLayout(nc=1, cw=[(1, 300)], cs=[(1, 10)], p="main_column")
    cmds.text(l='This script creates merged curves containing the input',
              align="left")
    cmds.text(l='text from the text field.', align="left")
    cmds.separator(h=15, style='none')  # Empty Space
    cmds.text(l='(All shapes go under one transform)', align="center")
    cmds.separator(h=15, style='none')  # Empty Space
    cmds.text(l='You can create multiple curves by separanting them with',
              align="left")
    cmds.text(l='commas ",".', align="left")
    cmds.separator(h=15, style='none')  # Empty Space
    cmds.text(l='Current Font:', align="left", fn="boldLabelFont")
    cmds.text(l='Click on the button on its right to change the font.',
              align="left")
    cmds.separator(h=15, style='none')  # Empty Space
    cmds.rowColumnLayout(nc=2,
                         cw=[(1, 140), (2, 140)],
                         cs=[(1, 10), (2, 0)],
                         p="main_column")
    cmds.text('Guilherme Trevisan  ')
    cmds.text(
        l='<a href="mailto:[email protected]">[email protected]</a>',
        hl=True,
        highlightColor=[1, 1, 1])
    cmds.rowColumnLayout(nc=2,
                         cw=[(1, 140), (2, 140)],
                         cs=[(1, 10), (2, 0)],
                         p="main_column")
    cmds.separator(h=15, style='none')  # Empty Space
    cmds.text(l='<a href="https://github.com/TrevisanGMW">Github</a>',
              hl=True,
              highlightColor=[1, 1, 1])
    cmds.separator(h=7, style='none')  # Empty Space

    # Close Button
    cmds.rowColumnLayout(nc=1, cw=[(1, 300)], cs=[(1, 10)], p="main_column")
    cmds.separator(h=10, style='none')
    cmds.button(l='OK', h=30, c=lambda args: close_help_gui())
    cmds.separator(h=8, style='none')

    # Show and Lock Window
    cmds.showWindow(window_name)
    cmds.window(window_name, e=True, s=False)

    # Set Window Icon
    qw = omui.MQtUtil.findWindow(window_name)
    widget = wrapInstance(long(qw), QWidget)
    icon = QIcon(':/question.png')
    widget.setWindowIcon(icon)

    def close_help_gui():
        if cmds.window(window_name, exists=True):
            cmds.deleteUI(window_name, window=True)
Esempio n. 23
0
def _get_maya_main_window():
    pointer = omui.MQtUtil.mainWindow()
    return wrapInstance(long(pointer), QtWidgets.QWidget)
Esempio n. 24
0
    def initUI(self):
        """
        Creates the UI
        :return: None
        """

        mayaMainWindowPtr = omui.MQtUtil.mainWindow()
        mayaMainWindow = wrapInstance(long(mayaMainWindowPtr),
                                      QtWidgets.QWidget)

        # Create our main window
        self.mainWindow = QtWidgets.QDialog()
        self.mainWindow.setParent(mayaMainWindow)
        self.mainWindow.setWindowTitle(PLUGIN_NAME + ' version ' +
                                       PLUGIN_VERSION)
        self.mainWindow.setFixedSize(350, 350)
        self.mainWindow.setWindowFlags(QtCore.Qt.Window)

        # Create vertical layout
        self.layVMainWindowMain = QtWidgets.QVBoxLayout()
        self.mainWindow.setLayout(self.layVMainWindowMain)
        self.mainWindow.setStyleSheet("""
                                       QGroupBox {  }
                                       """)

        # Texture Folder
        self.grpOptions = QtWidgets.QGroupBox('Options')
        self.layVMainWindowMain.addWidget(self.grpOptions)

        self.optionsLayout = QtWidgets.QVBoxLayout()
        self.grpOptions.setLayout(self.optionsLayout)

        # Create the layout
        self.optionsSubLayout4 = QtWidgets.QHBoxLayout()
        self.optionsLayout.insertLayout(0, self.optionsSubLayout4, stretch=0)

        # Create the widgets
        sourceImagesFolder = self.actualWorkspace + '/' + TEXTURE_FOLDER
        self.texturePath = QtWidgets.QLineEdit(sourceImagesFolder)
        self.optionsSubLayout4.addWidget(self.texturePath)

        self.getButton = QtWidgets.QPushButton('Get')
        self.getButton.clicked.connect(lambda: self.getTextureFolder())
        self.optionsSubLayout4.addWidget(self.getButton)

        # Create the layout
        self.optionsSubLayout3 = QtWidgets.QHBoxLayout()
        self.optionsLayout.insertLayout(1, self.optionsSubLayout3, stretch=0)

        # Create the widgets
        self.map1 = QtWidgets.QLabel('UV folder')
        self.optionsSubLayout3.addWidget(self.map1)

        self.uvFolder = QtWidgets.QLineEdit('UV')
        self.optionsSubLayout3.addWidget(self.uvFolder)

        # Create the layout
        self.optionsSubLayout5 = QtWidgets.QHBoxLayout()
        self.optionsLayout.insertLayout(2, self.optionsSubLayout5, stretch=0)

        # Create the widgets
        self.map1 = QtWidgets.QLabel('UV suffix')
        self.optionsSubLayout5.addWidget(self.map1)

        self.uvSuffix = QtWidgets.QLineEdit('_UVSnap')
        self.optionsSubLayout5.addWidget(self.uvSuffix)

        # Create the layout
        self.optionsSubLayout1 = QtWidgets.QHBoxLayout()
        self.optionsLayout.insertLayout(3, self.optionsSubLayout1, stretch=0)

        # Create the widgets
        self.map1 = QtWidgets.QLabel('File type')
        self.optionsSubLayout1.addWidget(self.map1)

        self.fileExtension = QtWidgets.QComboBox()
        self.fileExtension.addItems(FILE_TYPES)
        self.fileExtension.setCurrentIndex(0)
        self.optionsSubLayout1.addWidget(self.fileExtension)

        # Create the layout
        self.optionsSubLayout2 = QtWidgets.QHBoxLayout()
        self.optionsLayout.insertLayout(4, self.optionsSubLayout2, stretch=0)

        # Create the widgets
        self.map1 = QtWidgets.QLabel('Map resolution')
        self.optionsSubLayout2.addWidget(self.map1)

        self.resolution = QtWidgets.QComboBox()
        self.resolution.addItems(SIZE)
        self.resolution.setCurrentIndex(1)
        self.optionsSubLayout2.addWidget(self.resolution)

        # Create the layout
        self.optionsSubLayout6 = QtWidgets.QHBoxLayout()
        self.optionsLayout.insertLayout(5, self.optionsSubLayout6, stretch=0)

        # Create the widgets
        self.map1 = QtWidgets.QLabel('Color')
        self.optionsSubLayout6.addWidget(self.map1)

        self.color = QtWidgets.QComboBox()
        self.color.addItems(COLORS)
        self.color.setCurrentIndex(1)
        self.optionsSubLayout6.addWidget(self.color)

        # Create the layout
        self.optionsSubLayout7 = QtWidgets.QHBoxLayout()
        self.optionsLayout.insertLayout(6, self.optionsSubLayout7, stretch=0)

        # Create the widgets
        self.proceedButton = QtWidgets.QPushButton('Proceed')
        self.proceedButton.clicked.connect(lambda: self.main())
        self.optionsSubLayout7.addWidget(self.proceedButton)

        # Infos
        self.grpInfos = QtWidgets.QGroupBox('Credits')
        self.layVMainWindowMain.addWidget(self.grpInfos)

        self.infosLayout = QtWidgets.QVBoxLayout()
        self.grpInfos.setLayout(self.infosLayout)

        # Infos widgets
        self.infos = QtWidgets.QLabel(INFOS)
        self.infosLayout.addWidget(self.infos)
        self.infos.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter)

        global window

        try:
            window.close()
            window.deleteLater()
        except:
            pass

        window = self.mainWindow
        self.mainWindow.show()
        print('UI opened')
Esempio n. 25
0
def getMayaWindow():
    mayaWindowptr = omui.MQtUtil.mainWindow()
    window = wrapInstance(long(mayaWindowptr), QtWidgets.QWidget)
    return window
sys.path.append('//p.sv/Prism/project/SER/user/chew/SERTools'
                )  #adding new directory for tools to import
import PySide2  #importing modules for the UI
import PySide2.QtWidgets as QtWidgets
import PySide2.QtGui as QtGui
#import PySide2.QtCore
from PySide2.QtCore import *  #either this or the other

from PySide2 import QtUiTools
import shiboken2
import ExporterUI_001  #this is the UI file
reload(ExporterUI_001)
from ExporterUI_001 import Ui_MainWindow

mayaMainWindowPtr = omui.MQtUtil.mainWindow()
mayaMainWindow = shiboken2.wrapInstance(long(mayaMainWindowPtr),
                                        QtWidgets.QWidget)


def main():
    #mayaMainWindowPtr = omui.MQtUtil.mainWindow()
    #mayaMainWindow = shiboken2.wrapInstance(long(mayaMainWindowPtr), QtWidgets.QWidget)
    expDialog = MainWindow()
    expDialog.show()

    return expDialog


class MainWindow(QtWidgets.QDialog, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
Esempio n. 27
0
def get_maya_window():
    try:
        return shiboken.wrapInstance(long(OpenMayaUI.MQtUtil.mainWindow()),
                                     QWidget)
    except:
        return None
Esempio n. 28
0
def getMayaMainWindow():
    mayaMainWindow = OpenMayaUI.MQtUtil.mainWindow()
    return wrapInstance(long(mayaMainWindow), QtWidgets.QMainWindow)
Esempio n. 29
0
def getMayaMainWindow():
    main_window_ptr = OpenMayaUI.MQtUtil.mainWindow()
    return wrapInstance(long(main_window_ptr), QtWidgets.QMainWindow)
Esempio n. 30
0
def maya_main_window():
    """Return the maya main window widget"""
    main_window = omui.MQtUtil.mainWindow()
    return wrapInstance(long(main_window), QtWidgets.QWidget)
Esempio n. 31
0
def build_gui_help_connect_attributes():
    window_name = "build_gui_help_connect_attributes"
    if cmds.window(window_name, exists=True):
        cmds.deleteUI(window_name, window=True)

    cmds.window(window_name, title= script_name + " Help", mnb=False, mxb=False, s=True)
    cmds.window(window_name, e=True, s=True, wh=[1,1])

    cmds.columnLayout("main_column", p= window_name)
   
    # Title Text 
    cmds.separator(h=12, style='none') # Empty Space
    cmds.rowColumnLayout(nc=1, cw=[(1, 310)], cs=[(1, 10)], p="main_column") # Window Size Adjustment
    cmds.rowColumnLayout(nc=1, cw=[(1, 300)], cs=[(1, 10)], p="main_column") # Title Column
    cmds.text(script_name + " Help", bgc=(.4, .4, .4),  fn="boldLabelFont", align="center")
    cmds.separator(h=10, style='none', p="main_column") # Empty Space

    
    # Body ====================
    cmds.rowColumnLayout(nc=1, cw=[(1, 300)], cs=[(1,10)], p="main_column")
    cmds.text(l='This script automates the creation of connections', align="left")
    cmds.text(l='between attributes from source (output) and target', align="left")
    cmds.text(l='(input).', align="left")
    cmds.separator(h=15, style='none') # Empty Space
    cmds.text(l='Use Selection for Source and Target (s):', align="left", fn="boldLabelFont")
    cmds.text(l='When this option is activated, you no longer need to', align="left")
    cmds.text(l='load sources/target (s).', align="left")
    cmds.text(l='You can simply select: 1st: source, 2nd, 3rd... : target(s)', align="left")
    cmds.separator(h=15, style='none') # Empty Space
    cmds.text(l='Add Reverse Node:', align="left", fn="boldLabelFont")
    cmds.text(l='Adds a reverse node between connections.', align="left")
    cmds.separator(h=15, style='none') # Empty Space
    cmds.text(l='Disconnect:', align="left", fn="boldLabelFont")
    cmds.text(l='Break connections between selected nodes.', align="left")
    cmds.separator(h=15, style='none') # Empty Space
    cmds.text(l='Force Connection (Overrides Existing)', align="left", fn="boldLabelFont")
    cmds.text(l='Connects nodes even if they already have a connection.', align="left")
    cmds.separator(h=15, style='none') # Empty Space
    cmds.text(l='Add Custom Node Between Connection: ', align="left", fn="boldLabelFont")
    cmds.text(l='Allows user to create a node between connections.', align="left")
    cmds.text(l='Excellent for controlling dataflow.', align="left")
    cmds.text(l='-Custom Node: Which node to create', align="left")
    cmds.text(l='-Add Input Node: Creates one master control to update', align="left")
    cmds.text(l='all in betweens.', align="left")
    cmds.separator(h=15, style='none') # Empty Space
    cmds.text(l='Load Source/Target Objects:', align="left", fn="boldLabelFont")
    cmds.text(l='Use these buttons to load the objects you want to use', align="left")
    cmds.text(l='as source and target (s).', align="left")
    cmds.separator(h=15, style='none') # Empty Space
    cmds.text(l='Source Attribute and Target Attributes:', align="left", fn="boldLabelFont")
    cmds.text(l='Name of the attribute you want to connect.', align="left")
    cmds.text(l='Requirement: Use long or short name (no nice names)', align="left")
    cmds.separator(h=15, style='none') # Empty Space
    cmds.text(l='List All Attributes & List Keyable Attributes:', align="left", fn="boldLabelFont")
    cmds.text(l='Returns a list of attributes that can be used to populate', align="left")
    cmds.text(l='the Source and Target Attributes fields.', align="left")
    cmds.separator(h=15, style='none') # Empty Space
    cmds.rowColumnLayout(nc=2, cw=[(1, 140),(2, 140)], cs=[(1,10),(2, 0)], p="main_column")
    cmds.text('Guilherme Trevisan  ')
    cmds.text(l='<a href="mailto:[email protected]">[email protected]</a>', hl=True, highlightColor=[1,1,1])
    cmds.rowColumnLayout(nc=2, cw=[(1, 140),(2, 140)], cs=[(1,10),(2, 0)], p="main_column")
    cmds.separator(h=15, style='none') # Empty Space
    cmds.text(l='<a href="https://github.com/TrevisanGMW">Github</a>', hl=True, highlightColor=[1,1,1])
    cmds.separator(h=7, style='none') # Empty Space
    
    # Close Button 
    cmds.rowColumnLayout(nc=1, cw=[(1, 300)], cs=[(1,10)], p="main_column")
    cmds.separator(h=10, style='none')
    cmds.button(l='OK', h=30, c=lambda args: close_help_gui())
    cmds.separator(h=8, style='none')
    
    # Show and Lock Window
    cmds.showWindow(window_name)
    cmds.window(window_name, e=True, s=False)
    
    # Set Window Icon
    qw = omui.MQtUtil.findWindow(window_name)
    if python_version == 3:
        widget = wrapInstance(int(qw), QWidget)
    else:
        widget = wrapInstance(long(qw), QWidget)
    icon = QIcon(':/question.png')
    widget.setWindowIcon(icon)
    
    def close_help_gui():
        if cmds.window(window_name, exists=True):
            cmds.deleteUI(window_name, window=True)
Esempio n. 32
0
def build_gui_auto_fk():
    '''
    Builds the UI for the script GT Auto FK
    '''
    window_name = "build_gui_auto_fk"
    if cmds.window(window_name, exists=True):
        cmds.deleteUI(window_name)

    # Main GUI Start Here =================================================================================

    build_gui_auto_fk = cmds.window(window_name, title=script_name + "  v" + script_version,\
                          titleBar=True, mnb=False, mxb=False, sizeable =True)

    cmds.window(window_name, e=True, s=True, wh=[1, 1])

    content_main = cmds.columnLayout()

    # Title Text
    cmds.separator(h=10, style='none')  # Empty Space
    cmds.rowColumnLayout(nc=1, cw=[(1, 270)], cs=[(1, 10)],
                         p=content_main)  # Window Size Adjustment
    cmds.rowColumnLayout(nc=3,
                         cw=[(1, 10), (2, 200), (3, 50)],
                         cs=[(1, 10), (2, 0), (3, 0)],
                         p=content_main)  # Title Column
    cmds.text(" ", bgc=[0, .5, 0])  # Tiny Empty Green Space
    cmds.text(script_name + " v" + script_version,
              bgc=[0, .5, 0],
              fn="boldLabelFont",
              align="left")
    cmds.button(l="Help", bgc=(0, .5, 0), c=lambda x: build_gui_help_auto_FK())
    cmds.separator(h=10, style='none', p=content_main)  # Empty Space

    # Body ====================
    body_column = cmds.rowColumnLayout(nc=1,
                                       cw=[(1, 260)],
                                       cs=[(1, 10)],
                                       p=content_main)

    cmds.rowColumnLayout(nc=1, cw=[(1, 270)], cs=[(1, 13)], p=body_column)
    check_boxes_one = cmds.checkBoxGrp(columnWidth2=[120, 1], numberOfCheckBoxes=2, \
                                label1 = 'Mimic Hierarchy', label2 = 'Constraint Joint    ', \
                                v1 = gt_auto_fk_settings.get('mimic_hierarchy'), \
                                v2 = gt_auto_fk_settings.get('constraint_joint'),\
                                cc1=lambda x:set_persistent_settings_auto_fk('gt_auto_fk_mimic_hierarchy', cmds.checkBoxGrp(check_boxes_one, q=True, value1=True)),\
                                cc2=lambda x:set_persistent_settings_auto_fk('gt_auto_fk_constraint_joint', cmds.checkBoxGrp(check_boxes_one, q=True, value2=True)))

    cmds.rowColumnLayout(nc=1, cw=[(1, 270)], cs=[(1, 13)], p=body_column)

    check_boxes_two = cmds.checkBoxGrp(columnWidth2=[120, 1], numberOfCheckBoxes=2, \
                                label1 = 'Colorize Controls', label2 = "Select Hierarchy  ", \
                                v1 = gt_auto_fk_settings.get("auto_color_ctrls"), \
                                v2 = gt_auto_fk_settings.get("select_hierarchy"),\
                                cc1=lambda x:set_persistent_settings_auto_fk('gt_auto_fk_auto_color_ctrls', cmds.checkBoxGrp(check_boxes_two, q=True, value1=True)),\
                                cc2=lambda x:set_persistent_settings_auto_fk('gt_auto_fk_select_hierarchy', cmds.checkBoxGrp(check_boxes_two, q=True, value2=True)))

    cmds.rowColumnLayout(nc=1, cw=[(1, 270)], cs=[(1, 0)], p=body_column)
    cmds.separator(h=10)
    cmds.separator(h=5, style='none')  # Empty Space

    # Customize Control
    cmds.rowColumnLayout(nc=1, cw=[(1, 230)], cs=[(1, 0)], p=body_column)
    ctrl_curve_radius_slider_grp = cmds.floatSliderGrp( cw=[(1, 100),(2, 50),(3, 10)], label='Curve Radius: ', field=True, value=float(gt_auto_fk_settings.get('curve_radius')), \
                                                        cc=lambda x:set_persistent_settings_auto_fk('gt_auto_fk_curve_radius', str(cmds.floatSliderGrp(ctrl_curve_radius_slider_grp, q=True, value=True))),\
                                                        en=not gt_auto_fk_settings.get('using_custom_curve'))
    cmds.separator(h=7, style='none')  # Empty Space
    cmds.rowColumnLayout(nc=1, cw=[(1, 230)], cs=[(1, 13)], p=body_column)
    cmds.button('gt_auto_fk_custom_curve_btn',
                l="(Advanced) Custom Curve",
                c=lambda x: define_custom_curve())
    if gt_auto_fk_settings.get(
            'using_custom_curve') == True and gt_auto_fk_settings.get(
                'failed_to_build_curve') == False:
        cmds.button('gt_auto_fk_custom_curve_btn',
                    e=True,
                    l='ACTIVE - Custom Curve',
                    bgc=[0, .1, 0])

    cmds.rowColumnLayout(nc=1, cw=[(1, 270)], cs=[(1, 0)], p=body_column)
    cmds.separator(h=5, style='none')  # Empty Space
    cmds.separator(h=10)

    # Text Fields
    cmds.rowColumnLayout(nc=3,
                         cw=[(1, 70), (2, 75), (3, 100)],
                         cs=[(1, 5), (2, 0)],
                         p=body_column)
    cmds.text("Joint Tag:")
    cmds.text("Control Tag:")
    cmds.text("Control Grp Tag:")
    joint_tag_text_field = cmds.textField(text = gt_auto_fk_settings.get('string_joint_suffix'), \
                                          enterCommand=lambda x:generate_fk_controls(),\
                                          cc=lambda x:set_persistent_settings_auto_fk('gt_auto_fk_string_joint_suffix', cmds.textField(joint_tag_text_field, q=True, text=True)))
    ctrl_tag_text_field = cmds.textField(text = gt_auto_fk_settings.get('string_ctrl_suffix'), enterCommand=lambda x:generate_fk_controls(),\
                                          cc=lambda x:set_persistent_settings_auto_fk('gt_auto_fk_string_ctrl_suffix', cmds.textField(ctrl_tag_text_field, q=True, text=True)))
    ctrl_grp_tag_text_field = cmds.textField(text = gt_auto_fk_settings.get('string_ctrl_grp_suffix'), enterCommand=lambda x:generate_fk_controls(),\
                                          cc=lambda x:set_persistent_settings_auto_fk('gt_auto_fk_string_ctrl_grp_suffix', cmds.textField(ctrl_grp_tag_text_field, q=True, text=True)))

    cmds.rowColumnLayout(nc=1, cw=[(1, 260)], cs=[(1, 0)], p=body_column)

    cmds.separator(h=10)
    cmds.separator(h=5, style='none')  # Empty Space
    cmds.text(label='Ignore Joints Containing These Strings:')
    cmds.rowColumnLayout(nc=1, cw=[(1, 245)], cs=[(1, 5)], p=body_column)
    undesired_strings_text_field = cmds.textField(text=gt_auto_fk_settings.get('undesired_strings'), enterCommand=lambda x:generate_fk_controls(),\
                                   cc=lambda x:set_persistent_settings_auto_fk('gt_auto_fk_undesired_strings', cmds.textField(undesired_strings_text_field, q=True, text=True)))
    cmds.rowColumnLayout(nc=1, cw=[(1, 260)], cs=[(1, 0)], p=body_column)
    cmds.text(label='(Use Commas to Separate Strings)')
    cmds.separator(h=5, style='none')  # Empty Space
    cmds.separator(h=10)
    cmds.separator(h=10, style='none')  # Empty Space
    cmds.button(l="Generate",
                bgc=(.6, .8, .6),
                c=lambda x: generate_fk_controls())
    cmds.separator(h=10, style='none')  # Empty Space

    # Generate FK Main Function Starts --------------------------------------------
    def generate_fk_controls():
        '''
        Generate FK Controls. 
        This is the main function of this script. It will create a curve, and according to the settings use it as a control for the selected joint.
        '''

        cmds.undoInfo(openChunk=True, chunkName='Auto Generate FK Ctrls')
        try:
            errors = ''
            ctrl_curve_radius = cmds.floatSliderGrp(
                ctrl_curve_radius_slider_grp, q=True, value=True)
            selected_joints = cmds.ls(selection=True, type='joint', long=True)
            if cmds.checkBoxGrp(check_boxes_two, q=True, value2=True):
                cmds.select(hierarchy=True)
                selected_joints = cmds.ls(selection=True,
                                          type='joint',
                                          long=True)
            ctrl_tag = parse_text_field(
                cmds.textField(ctrl_tag_text_field, q=True, text=True))[0]
            ctrl_grp_tag = parse_text_field(
                cmds.textField(ctrl_grp_tag_text_field, q=True, text=True))[0]
            joint_tag = parse_text_field(
                cmds.textField(joint_tag_text_field, q=True, text=True))[0]
            undesired_jnt_strings = parse_text_field(
                cmds.textField(undesired_strings_text_field, q=True,
                               text=True))
            undesired_joints = []

            # Find undesired joints and make a list of them
            for jnt in selected_joints:
                for string in undesired_jnt_strings:
                    if string in get_short_name(jnt):
                        undesired_joints.append(jnt)

            # Remove undesired joints from selection list
            for jnt in undesired_joints:
                if jnt in undesired_joints:
                    selected_joints.remove(jnt)

            for jnt in selected_joints:
                if len(joint_tag) != 0:
                    joint_name = get_short_name(jnt).replace(joint_tag, '')
                else:
                    joint_name = get_short_name(jnt)
                ctrl_name = joint_name + ctrl_tag
                ctrlgrp_name = joint_name + ctrl_grp_tag

                if gt_auto_fk_settings.get("using_custom_curve"):
                    ctrl = create_custom_curve(
                        gt_auto_fk_settings.get("custom_curve"))

                    try:
                        ctrl = [cmds.rename(ctrl, ctrl_name)]
                    except:
                        ctrl = cmds.circle(name=ctrl_name,
                                           normal=[1, 0, 0],
                                           radius=ctrl_curve_radius,
                                           ch=False)  # Default Circle Curve

                    if gt_auto_fk_settings.get("failed_to_build_curve"):
                        ctrl = cmds.circle(name=ctrl_name,
                                           normal=[1, 0, 0],
                                           radius=ctrl_curve_radius,
                                           ch=False)  # Default Circle Curve

                else:
                    ctrl = cmds.circle(name=ctrl_name,
                                       normal=[1, 0, 0],
                                       radius=ctrl_curve_radius,
                                       ch=False)  # Default Circle Curve

                grp = cmds.group(name=ctrlgrp_name, empty=True)
                try:
                    cmds.parent(ctrl, grp)
                    constraint = cmds.parentConstraint(jnt, grp)
                    cmds.delete(constraint)
                except Exception as e:
                    errors = errors + str(e)

                # Colorize Control Start ------------------

                if cmds.checkBoxGrp(check_boxes_two, q=True, value1=True):
                    try:
                        cmds.setAttr(ctrl[0] + ".overrideEnabled", 1)
                        if ctrl[0].lower().startswith(
                                'right_') or ctrl[0].lower().startswith('r_'):
                            cmds.setAttr(ctrl[0] + ".overrideColor", 13)  #Red
                        elif ctrl[0].lower().startswith(
                                'left_') or ctrl[0].lower().startswith('l_'):
                            cmds.setAttr(ctrl[0] + ".overrideColor", 6)  #Blue
                        else:
                            cmds.setAttr(ctrl[0] + ".overrideColor",
                                         17)  #Yellow
                    except Exception as e:
                        errors = errors + str(e)

                # Colorize Control End ---------------------

                # Constraint Joint
                if cmds.checkBoxGrp(check_boxes_one, q=True, value2=True):
                    try:
                        cmds.parentConstraint(ctrl_name, jnt)
                    except Exception as e:
                        errors = errors + str(e) + '\n'

                # Mimic Hierarchy
                if cmds.checkBoxGrp(check_boxes_one, q=True, value1=True):
                    try:
                        #Auto parents new controls
                        # "or []" Accounts for root joint that doesn't have a parent, it forces it to be a list
                        jnt_parent = cmds.listRelatives(jnt,
                                                        allParents=True) or []
                        if len(jnt_parent) == 0:
                            pass
                        else:

                            if len(joint_tag) != 0:
                                parent_ctrl = (
                                    jnt_parent[0].replace(joint_tag, "") +
                                    ctrl_tag)
                            else:
                                parent_ctrl = (jnt_parent[0] + ctrl_tag)

                            if cmds.objExists(parent_ctrl):
                                cmds.parent(grp, parent_ctrl)
                    except Exception as e:
                        errors = errors + str(e) + '\n'

            # Print Errors if necessary
            if errors != '':
                print('#' * 80)
                print(errors)
                print('#' * 80)
                cmds.warning(gt_auto_fk_settings.get('error_message'))
        except Exception as e:
            cmds.warning(str(e))
        finally:
            cmds.undoInfo(closeChunk=True, chunkName='Auto Generate FK Ctrls')

    # Generate FK Main Function Ends --------------------------------------------

    # Define Custom Curve
    def define_custom_curve():
        '''Asks the user for input. Uses this input as a custom curve (by storing it in the settings dictionary)'''

        if gt_auto_fk_settings.get(
                'custom_curve') == gt_auto_fk_settings_default_values.get(
                    'custom_curve'):
            textfield_data = ''
        else:
            textfield_data = str(gt_auto_fk_settings.get('custom_curve'))

        result = cmds.promptDialog(
            scrollableField=True,
            title='Py Curve',
            message=
            'Paste Python Curve Below: \n(Use \"GT Generate Python Curve \" to extract it from an existing curve)',
            button=['OK', 'Use Default'],
            defaultButton='OK',
            cancelButton='Use Default',
            dismissString='Use Default',
            text=textfield_data)

        if result == 'OK':
            if cmds.promptDialog(query=True, text=True) != '':
                gt_auto_fk_settings["custom_curve"] = cmds.promptDialog(
                    query=True, text=True)
                gt_auto_fk_settings["using_custom_curve"] = True
                gt_auto_fk_settings["failed_to_build_curve"] = False
                cmds.floatSliderGrp(ctrl_curve_radius_slider_grp,
                                    e=True,
                                    en=False)
                # Update Persistent Settings
                set_persistent_settings_auto_fk(
                    'gt_auto_fk_custom_curve',
                    str(cmds.promptDialog(query=True, text=True)))
                set_persistent_settings_auto_fk(
                    'gt_auto_fk_using_custom_curve', True)
                set_persistent_settings_auto_fk(
                    'gt_auto_fk_failed_to_build_curve', False)
                cmds.button('gt_auto_fk_custom_curve_btn',
                            e=True,
                            l='ACTIVE - Custom Curve',
                            bgc=[0, .1, 0])

        else:
            gt_auto_fk_settings["using_custom_curve"] = False
            cmds.floatSliderGrp(ctrl_curve_radius_slider_grp, e=True, en=True)
            gt_auto_fk_settings[
                'custom_curve'] = gt_auto_fk_settings_default_values.get(
                    'custom_curve')
            cmds.button('gt_auto_fk_custom_curve_btn',
                        e=True,
                        l="(Advanced) Custom Curve",
                        nbg=False)
            # Update Persistent Settings
            set_persistent_settings_auto_fk('gt_auto_fk_using_custom_curve',
                                            False)

    # Show and Lock Window
    cmds.showWindow(build_gui_auto_fk)
    cmds.window(window_name, e=True, s=False)

    # Set Window Icon
    qw = omui.MQtUtil.findWindow(window_name)
    widget = wrapInstance(long(qw), QWidget)
    icon = QIcon(':/kinInsert.png')
    widget.setWindowIcon(icon)
Esempio n. 33
0
def build_gui_connect_attributes():
    window_name = "build_gui_connect_attributes"
    if cmds.window(window_name, exists =True):
        cmds.deleteUI(window_name)    

    # Main GUI Start Here =================================================================================
    title_bgc_color = (.4, .4, .4)
    build_gui_connect_attributes = cmds.window(window_name, title=script_name + "  (v" + script_version + ')',\
                          titleBar=True, mnb=False, mxb=False, sizeable =True)

    cmds.window(window_name, e=True, s=True, wh=[1,1])

    content_main = cmds.columnLayout()
    
    # Title Text
    
    cmds.separator(h=10, style='none') # Empty Space
    cmds.rowColumnLayout(nc=1, cw=[(1, 270)], cs=[(1, 10)], p=content_main) # Window Size Adjustment
    cmds.rowColumnLayout(nc=3, cw=[(1, 10), (2, 200), (3, 50)], cs=[(1, 10), (2, 0), (3, 0)], p=content_main) # Title Column
    cmds.text(" ", bgc=title_bgc_color) # Tiny Empty Green Space
    cmds.text(script_name, bgc=title_bgc_color,  fn="boldLabelFont", align="left")
    cmds.button( l ="Help", bgc=title_bgc_color, c=lambda x:build_gui_help_connect_attributes())
    cmds.separator(h=10, style='none', p=content_main) # Empty Space
    
    # Body ====================
    body_column = cmds.rowColumnLayout(nc=1, cw=[(1, 260)], cs=[(1,10)], p=content_main)
    #cmds.separator(h=5)
    
    # Checkbox - Selection as Source and Target
    interactive_container_misc = cmds.rowColumnLayout(p=body_column, nc=1, cs=[(1,12)], h= 25)
    single_source_target = cmds.checkBox(p=interactive_container_misc, label='  Use Selection for Source and Target (s)', value=settings.get("def_single_source_target"),\
                         cc=lambda x:is_using_single_target(cmds.checkBox(single_source_target, query=True, value=True)) )

    # CheckboxGrp Reverse and Disconnect
    interactive_container_jnt = cmds.rowColumnLayout(p=body_column, nc=1, cs=[(1,11)], h= 25)
    rev_disc_check_box_grp = cmds.checkBoxGrp(p=interactive_container_jnt, columnWidth2=[137, 0], numberOfCheckBoxes=2, \
                                label1 = '  Add Reverse Node', label2 = " Disconnect", v1 = settings.get("def_reverse_node"), v2 = settings.get("def_disconnect"), \
                                cc1=lambda x:update_stored_values(), cc2= lambda x:is_disconnecting(cmds.checkBoxGrp(rev_disc_check_box_grp,q=True,v2=True)))   

    # Checkbox - Override Existing (Force Connection)
    override_existing_container = cmds.rowColumnLayout(p=body_column, nc=1, cs=[(1,12)], h= 25)
    forcing_connection_checkbox = cmds.checkBox(p=override_existing_container, label='  Force Connection  (Overrides Existing)', value=settings.get("def_force_connection"),\
                         cc=lambda x:update_stored_values())

    cmds.separator(h=15, p=body_column)

    # Checkbox Use Custom Node Between Connection
    interactive_container_misc = cmds.rowColumnLayout(p=body_column, nc=1, cs=[(1,12)], h= 25)
    add_custom_node = cmds.checkBox(p=interactive_container_misc, label='  Add Custom Node Between Connection', value=settings.get("def_use_custom_node"),\
                          cc=lambda x:is_using_custom_node(cmds.checkBox(add_custom_node, query=True, value=True)) ) # UPDATE THIS
    
    # Dropdown Menu (Custom Node)
    custom_node_menu_container = cmds.rowColumnLayout(p=body_column, nc=1, cw=[(1,247)], cs=[(1,3)], h= 25)
    custom_node_menu = cmds.optionMenu(en=False, p=custom_node_menu_container, label='   Custom Node : ', cc=lambda x:update_stored_values()) #######
    cmds.menuItem( label='plusMinusAverage' )
    cmds.menuItem( label='multiplyDivide' )
    cmds.menuItem( label='condition' )

    #custom_node_empty_space = cmds.rowColumnLayout(p=body_column, numberOfRows=1, h= 7) #??????????
    cmds.separator(h=5, style='none', p=body_column) # Empty Space
    
    # Checkbox and Dropdown Menu for Input node and its type
    node_behaviour_container_one = cmds.rowColumnLayout(p=body_column, numberOfRows=1, h= 25)
    cmds.text("    ")
    add_ctrl_node = cmds.checkBox(p=node_behaviour_container_one, en=False, label='  Add Input Node  ', value=settings.get("def_use_custom_node"),\
                          cc=lambda x:update_stored_values())
    
    ctrl_node_output = cmds.optionMenu(en=False, p=node_behaviour_container_one, label='', w=120,cc=lambda x:update_stored_values()) #######
    cmds.menuItem( label='condition' )
    cmds.menuItem( label='plusMinusAverage' )
    cmds.menuItem( label='multiplyDivide' )     
    cmds.text("   ",p=custom_node_menu_container)
                                                   
    cmds.separator(h=10, p=body_column)
    cmds.separator(h=3, style='none', p=body_column) # Empty Space
    
    # Source List Loader (Buttons)
    source_container = cmds.rowColumnLayout( p=body_column, numberOfRows=1)
    source_btn = cmds.button(p=source_container, l ="Load Source Object", c=lambda x:update_load_btn_jnt("source"), w=130)
    source_status = cmds.button(p=source_container, l ="Not loaded yet", bgc=(.2, .2, .2), w=130, \
                            c="cmds.headsUpMessage( 'Select your source element and click on \"Load Source Object\"', verticalOffset=150 , time=5.0)")
                            
    # Target List Loader (Buttons)
    target_container = cmds.rowColumnLayout( p=body_column, numberOfRows=1)
    target_btn = cmds.button(p=target_container, l ="Load Target Objects", c=lambda x:update_load_btn_jnt("target"), w=130)
    target_status = cmds.button(p=target_container, l ="Not loaded yet", bgc=(.2, .2, .2), w=130, \
                            c="cmds.headsUpMessage( 'Select your target elements and click on \"Load Target Objects\"', verticalOffset=150 , time=5.0)")
    cmds.separator(h=3, style='none', p=body_column) # Empty Space
    cmds.separator(h=10, p=body_column)
    
    # Source/Target Attributes
    bottom_container = cmds.rowColumnLayout(p=body_column, adj=True)
    cmds.text('Source Attribute (Only One):',p=bottom_container)
    source_attributes_input = cmds.textField(p = bottom_container, text="translate", \
                                    enterCommand=lambda x:connect_attributes(cmds.textField(source_attributes_input, q=True, text=True),\
                                                                            cmds.textField(target_attributes_input, q=True, text=True)))
    cmds.text('Target Attributes:',p=bottom_container)
    target_attributes_input = cmds.textField(p = bottom_container, text="translate, rotate, scale", \
                                    enterCommand=lambda x:connect_attributes(cmds.textField(source_attributes_input, q=True, text=True),\
                                                                            cmds.textField(target_attributes_input, q=True, text=True)))
    
    cmds.separator(h=3, style='none', p=body_column) # Empty Space
    cmds.separator(h=10, p=body_column)
    
    # Print Attributes Buttons
    cmds.rowColumnLayout(p=body_column, adj=True, h=5)
    show_attributes_container = cmds.rowColumnLayout(p=body_column, numberOfRows=1, h= 25)
    cmds.button(p=show_attributes_container, l ="List All Attributes", w=130,\
                                    c=lambda x:print_selection_attributes("all"))                                                                    
    cmds.button(p=show_attributes_container, l ="List Keyable Attributes", w=130,\
                                    c=lambda x:print_selection_attributes("keyable")) 
    
    cmds.separator(h=10, style='none', p=body_column) # Empty Space
    
    # Connect Button (Main Function)
    cmds.button(p=body_column, l ="Connect Attributes", bgc=(.6, .6, .6), \
                                    c=lambda x:connect_attributes(cmds.textField(source_attributes_input, q=True, text=True),\
                                                                            cmds.textField(target_attributes_input, q=True, text=True)))
    cmds.separator(h=10, style='none', p=body_column) # Empty Space

    # Prints selection attributes
    def print_selection_attributes(type):
        selection = cmds.ls(selection=True)
        header = ""
        if type == "keyable" and len(selection) > 0:
            attrList = cmds.listAttr (selection[0], k=True) or []
            header = '"' + selection[0] + '" keyable attributes: '
        elif len(selection) > 0:
            attrList = cmds.listAttr (selection[0]) or []
            header = '"' + selection[0] + '" attributes: '
        
        
        if len(selection) > 0 and attrList != []:
            export_to_txt(header, attrList)
        else:
            cmds.warning("Nothing selected (or no attributes to be displayed)")
                
    # Updates elements to reflect the use of selection (instead of loaders)
    def is_using_single_target(state): 
        if state:
            settings["status_single_source_target"] = cmds.checkBox(single_source_target, q=True, value=True)
            cmds.button(source_btn, e=True, en=False)
            cmds.button(source_status, l ="Not necessary", e=True, en=False, bgc=(.25, .25, .25))
            cmds.button(target_btn, e=True, en=False)
            cmds.button(target_status, l ="Not necessary", e=True, en=False, bgc=(.25, .25, .25))
            settings["target_list"] = []
            settings["source_obj"] = []
        else:
            settings["status_single_source_target"] = cmds.checkBox(single_source_target, q=True, value=True)
            cmds.button(source_btn, e=True, en=True)
            cmds.button(source_status, l ="Not loaded yet", e=True, en=True, bgc=(.2, .2, .2),\
                        c="cmds.headsUpMessage( 'Select your source element and click on \"Load Source Object\"', verticalOffset=150 , time=5.0)")
            cmds.button(target_btn, e=True, en=True)
            cmds.button(target_status, l ="Not loaded yet", e=True, en=True, bgc=(.2, .2, .2), \
                        c="cmds.headsUpMessage( 'Select your target elements and click on \"Load Target Objects\"', verticalOffset=150 , time=5.0)")
            
    # Updates elements to reflect the use of in between custom node
    def is_using_custom_node(state): 
        if state:
            cmds.optionMenu(custom_node_menu, e=True, en=True)
            settings["status_use_custom_node"] = cmds.checkBox(add_custom_node, q=True, value=True)
            cmds.checkBox(add_ctrl_node,e=True, en=True)
            cmds.optionMenu(ctrl_node_output,e=True, en=True)
        else:
            cmds.optionMenu(custom_node_menu, e=True, en=False)
            settings["status_use_custom_node"] = cmds.checkBox(add_custom_node, q=True, value=True)
            cmds.checkBox(add_ctrl_node,e=True, en=False)
            cmds.optionMenu(ctrl_node_output,e=True, en=False)

    # Updates many of the stored GUI values (Used by multiple elements)
    def update_stored_values(): 
        settings["custom_node"] = cmds.optionMenu(custom_node_menu, q=True, value=True)
        settings["status_use_reverse_node"] = cmds.checkBoxGrp(rev_disc_check_box_grp, q=True, value1=True)
        settings["status_disconnect"] = cmds.checkBoxGrp(rev_disc_check_box_grp, q=True, value2=True)
        settings["input_node_type"] = cmds.optionMenu(ctrl_node_output, q=True, value=True)
        settings["status_add_input"] = cmds.checkBox(add_ctrl_node, q=True, value=True)
        settings["status_force_connection"] = cmds.checkBox(forcing_connection_checkbox, q=True, value=True)
        #print(settings.get("status_force_connections")) # Debugging
        
    # Updates elements to reflect the use disconnect function
    def is_disconnecting(state): 
        
        if state:
            cmds.checkBox(add_custom_node, e=True, en=False)
            is_using_custom_node(False)
            cmds.checkBoxGrp(rev_disc_check_box_grp, e=True, en1=False)
            update_stored_values()
            
        else:
            cmds.checkBox(add_custom_node, e=True, en=True)
            is_using_custom_node(cmds.checkBox(add_custom_node, q=True, value=True))
            cmds.checkBoxGrp(rev_disc_check_box_grp, e=True, en1=True)
            update_stored_values()
    
    # Objects Loader
    def update_load_btn_jnt(button_name):
        
        # Check If Selection is Valid
        received_valid_source_selection = False
        received_valid_target_selection = False
        selected_elements = cmds.ls(selection=True)
        
        if button_name == "source":
            if len(selected_elements) == 0:
                cmds.warning("Please make sure you select at least one object before loading")
            elif len(selected_elements) == 1:
                received_valid_source_selection = True
            elif len(selected_elements) > 1:
                 cmds.warning("You can only have one source object")
            else:
                cmds.warning("Something went wrong, make sure you selected all necessary elements")
                
        if button_name == "target":
            if len(selected_elements) == 0:
                cmds.warning("Please make sure you select at least one object before loading")
            elif len(selected_elements) > 0:
                 received_valid_target_selection = True
            else:
                cmds.warning("Something went wrong, make sure you selected all necessary elements")
            
        # If Source
        if button_name is "source" and received_valid_source_selection == True:
            settings["source_obj"] = selected_elements[0]
            cmds.button(source_status, l=selected_elements[0],e=True, bgc=(.6, .8, .6), w=130, c=lambda x:if_exists_select(settings.get("source_obj")))
        elif button_name is "source":
            cmds.button(source_status, l ="Failed to Load",e=True, bgc=(1, .4, .4), w=130,\
                        c="cmds.headsUpMessage( 'Make sure you select only one source element', verticalOffset=150 , time=5.0)")
        
        # If Target
        if button_name is "target" and received_valid_target_selection == True:
            settings["target_list"] = selected_elements
            
            loaded_text = str(len(selected_elements)) + " objects loaded"
            if len(selected_elements) == 1:
                loaded_text = selected_elements[0]
        
            cmds.button(target_status, l =loaded_text,e=True, bgc=(.6, .8, .6), w=130, c=lambda x:target_listManager(settings.get("target_list")))
        elif button_name is "target":
            cmds.button(target_status, l ="Failed to Load",e=True, bgc=(1, .4, .4), w=130,\
                        c="cmds.headsUpMessage( 'Make sure you select at least one target element', verticalOffset=150 , time=5.0)")

    # Update Connection Type
    is_using_single_target(settings.get("def_single_source_target"))
    
    # Show and Lock Window
    cmds.showWindow(build_gui_connect_attributes)
    cmds.window(window_name, e=True, s=False)
    
    # Set Window Icon
    qw = omui.MQtUtil.findWindow(window_name)
    if python_version == 3:
        widget = wrapInstance(int(qw), QWidget)
    else:
        widget = wrapInstance(long(qw), QWidget)
    icon = QIcon(':/hsRearrange.png')
    widget.setWindowIcon(icon)
def getMayaMainWindow():
    mayaPtr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(mayaPtr), QtWidgets.QWidget)
Esempio n. 35
0
def maya_main_window():
    main_window_ptr = OpenMayaUI.MQtUtil.mainWindow()
    return wrapInstance(long(main_window_ptr), QtWidgets.QMainWindow)
def getMayaWindow():
    mayaWindowPointer = mayaUi.MQtUtil.mainWindow()
    mayaWin = wrapInstance(long(mayaWindowPointer), QWidget)
Esempio n. 37
0
def build_workspace_control_ui(shotgun_panel_name):
    """
    Embeds a Shotgun app panel into the calling Maya workspace control.

    This function will be called in two cases:
    - When the workspace control is being created by Maya command workspaceControl;
    - When the workspace control is being restored from a workspace control state
      created by Maya when this workspace control was previously closed and deleted.

    .. note:: This function is only for Maya 2017 and later.

    :param shotgun_panel_name: Name of the Qt widget at the root of a Shotgun app panel.
    """

    from maya.OpenMayaUI import MQtUtil

    # In the context of this function, we know that we are running in Maya 2017 and later
    # with the newer versions of PySide and shiboken.
    from PySide2 import QtWidgets
    from shiboken2 import wrapInstance

    import sgtk.platform

    # Retrieve the Maya engine.
    engine = sgtk.platform.current_engine()

    # Retrieve the calling Maya workspace control.
    ptr = MQtUtil.getCurrentParent()
    workspace_control = wrapInstance(long(ptr), QtWidgets.QWidget)

    # Search for the Shotgun app panel widget.
    for widget in QtWidgets.QApplication.allWidgets():
        if widget.objectName() == shotgun_panel_name:

            maya_panel_name = workspace_control.objectName()

            engine.logger.debug("Reparenting Shotgun app panel %s under Maya workspace panel %s.",
                                shotgun_panel_name, maya_panel_name)

            # When possible, give a minimum width to the workspace control;
            # otherwise, it will use the width of the currently displayed tab.
            # Note that we did not use the workspace control "initialWidth" and "minimumWidth"
            # to set the minimum width to the initial width since these values are not
            # properly saved by Maya 2017 in its layout preference files.
            # This minimum width behaviour is consistent with Maya standard panels.
            size_hint = widget.sizeHint()
            if size_hint.isValid():
                # Use the widget recommended width as the workspace control minimum width.
                minimum_width = size_hint.width()
                engine.logger.debug("Setting Maya workspace panel %s minimum width to %s.",
                                    maya_panel_name, minimum_width)
                workspace_control.setMinimumWidth(minimum_width)
            else:
                # The widget has no recommended size.
                engine.logger.debug("Cannot set Maya workspace panel %s minimum width.", maya_panel_name)

            # Reparent the Shotgun app panel widget under Maya workspace control.
            widget.setParent(workspace_control)

            # Add the Shotgun app panel widget to the Maya workspace control layout.
            workspace_control.layout().addWidget(widget)

            # Install an event filter on Maya workspace control to monitor
            # its close event in order to reparent the Shotgun app panel widget
            # under Maya main window for later use.
            engine.logger.debug("Installing a close event filter on Maya workspace panel %s.", maya_panel_name)
            panel_util.install_event_filter_by_widget(workspace_control, shotgun_panel_name)

            # Delete any leftover workspace control state to avoid a spurious deletion
            # of our workspace control when the user switches to another workspace and back.
            if cmds.workspaceControlState(maya_panel_name, exists=True):
                # Once Maya will have completed its UI update and be idle,
                # delete the leftover workspace control state.
                engine.logger.debug("Deleting leftover Maya workspace control state %s.", maya_panel_name)
                maya.utils.executeDeferred(cmds.workspaceControlState, maya_panel_name, remove=True)

            break
    else:
        # The Shotgun app panel widget was not found and needs to be recreated.

        # Search for the Shotgun app panel that needs to be restored
        # among the panels registered with the engine.
        for panel_id in engine.panels:

            # The name of the Qt widget at the root of the Shotgun app panel
            # was constructed by prepending to the panel unique identifier.
            if shotgun_panel_name.endswith(panel_id):

                # Once Maya will have completed its UI update and be idle,
                # recreate and dock the Shotgun app panel.
                maya.utils.executeDeferred(engine.panels[panel_id]["callback"])

                break
        else:
            # The Shotgun app panel that needs to be restored is not in the context configuration.
            engine.logger.error("Cannot restore %s: Shotgun app panel not found. " \
                             "Make sure the app is in the context configuration. ", shotgun_panel_name)
Esempio n. 38
0
def maya_main_window():
    main_window_ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(int(main_window_ptr), QtWidgets.QWidget)
Esempio n. 39
0
def getMayaWindow():
    ptr = openMayaUI.MQtUtil.mainWindow()
    if ptr is not None:
        return shiboken.wrapInstance(long(ptr), QtWidgets.QWidget)
Esempio n. 40
0
def mainWindow():
    ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(ptr), widgets.QWidget)
Esempio n. 41
0
def getMayaMainWindow():
    from PySide2 import QtWidgets
    from maya import OpenMayaUI
    from shiboken2 import wrapInstance
    mayaMainWindow = OpenMayaUI.MQtUtil.mainWindow()
    return wrapInstance(long(mayaMainWindow), QtWidgets.QMainWindow)
Esempio n. 42
0
def getMayaWindow():
    ptr = OpenMayaUI.MQtUtil.mainWindow()
    return shiboken.wrapInstance(long(ptr), QtWidgets.QMainWindow)
def getMayaMainWindow():
    winPtr = omui.MQtUtil.mainWindow()
    return shiboken2.wrapInstance(long(winPtr), QWidget)
def get_maya_window():
    # noinspection PyArgumentList
    maya_window = OpenMayaUI.MQtUtil.mainWindow()
    return wrapInstance(long(maya_window), QWidget)
Esempio n. 45
0
def maya_main():
    import maya.OpenMayaUI as OpenMayaUI
    mainWindowPtr = OpenMayaUI.MQtUtil.mainWindow()
    mayaWindow = wrapInstance(long(mainWindowPtr), QtWidgets.QWidget)
    nodeWindow = Window()
    nodeWindow.show()
Esempio n. 46
0
def get_maya_window():
    ptr = omui.MQtUtil.mainWindow()
    if ptr is not None:
        return wrapInstance(long(ptr), QtWidgets.QWidget)
Esempio n. 47
0
def getMayaWindow():
    ptr = mui.MQtUtil.mainWindow()
    return wrapInstance(long(ptr), QMainWindow)
def getMayaMainWindow():
    mayaPtr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(mayaPtr), QtWidgets.QWidget)
Esempio n. 49
0
def getMayaWindow():
    pointer = mui.MQtUtil.mainWindow()
    return wrapInstance(long(pointer), QWidget)
Esempio n. 50
0
def getMayaWindow():
    ptr = mui.MQtUtil.mainWindow()
    return shiboken.wrapInstance(long(ptr), QtWidgets.QWidget)
Esempio n. 51
0
try:
    import ml_utilities as utl
    utl.upToDateCheck(32)
except ImportError:
    result = mc.confirmDialog( title='Module Not Found', 
                message='This tool requires the ml_utilities module. Once downloaded you will need to restart Maya.', 
                button=['Download Module','Cancel'], 
                defaultButton='Cancel', cancelButton='Cancel', dismissString='Cancel' )
    
    if result == 'Download Module':
        mc.showHelp('http://morganloomis.com/tool/ml_utilities/',absolute=True)


#get maya window as qt object
main_window_ptr = mui.MQtUtil.mainWindow()
qt_maya_window = shiboken.wrapInstance(long(main_window_ptr), QtCore.QObject)

def ui():
    '''
    user interface for ml_pivot
    '''

    with utl.MlUi('ml_pivot', 'Change Pivot', width=400, height=150, info='''Select an animated control whose pivot you'd like to change, and press Edit Pivot.
Your selection with change to handle, position this where you'd like the pivot to be
and press Return. Or press ESC or deselect to cancel.''') as win:

        win.buttonWithPopup(label='Edit Pivot', command=edit_pivot, annotation='Creates a temporary node to positon for the new pivot.', shelfLabel='pivot', shelfIcon='defaultTwoStackedLayout')
        win.buttonWithPopup(label='Reset Pivot', command=reset_pivot, annotation='Rest the rotation pivot to zero.', shelfLabel='reset', shelfIcon='defaultTwoStackedLayout')


def edit_pivot(*args):