class Ui_BuildAtomsPropertyManager(Command_PropertyManager):
    """
    The Ui_BuildAtomsPropertyManager class defines UI elements for the Property
    Manager of the B{Build Atoms mode}.

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    # The title that appears in the Property Manager header
    title = "Build Atoms"
    # The name of this Property Manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    # The relative path to the PNG file that appears in the header
    iconPath = "ui/actions/Tools/Build Structures/BuildAtoms.png"

    def __init__(self, command):
        """
        Constructor for the B{Build Atoms} property manager class that defines
        its UI.

        @param command: The parent mode where this Property Manager is used
        @type  command: L{depositMode}
        """

        self.previewGroupBox = None
        self.regularElementChooser = None
        self.PAM5Chooser = None
        self.PAM3Chooser = None
        self.elementChooser = None
        self.advancedOptionsGroupBox = None
        self.bondToolsGroupBox = None

        self.selectionFilterCheckBox = None
        self.filterlistLE = None
        self.selectedAtomInfoLabel = None

        #Initialize the following to None. (subclasses may not define this)
        #Make sure you initialize it before adding groupboxes!
        self.selectedAtomPosGroupBox = None
        self.showSelectedAtomInfoCheckBox = None

        _superclass.__init__(self, command)

        self.showTopRowButtons(PM_DONE_BUTTON | PM_WHATS_THIS_BUTTON)
        msg = ''
        self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=False)

    def _addGroupBoxes(self):
        """
        Add various group boxes to the Build Atoms Property manager.
        """
        self._addPreviewGroupBox()
        self._addAtomChooserGroupBox()
        self._addBondToolsGroupBox()

        #@@@TODO HIDE the bonds tool groupbox initially as the
        #by default, the atoms tool is active when BuildAtoms command is
        #finist invoked.
        self.bondToolsGroupBox.hide()

        self._addSelectionOptionsGroupBox()
        self._addAdvancedOptionsGroupBox()

    def _addPreviewGroupBox(self):
        """
        Adde the preview groupbox that shows the element selected in the
        element chooser.
        """
        self.previewGroupBox = PM_PreviewGroupBox( self, glpane = self.o )

    def _addAtomChooserGroupBox(self):
        """
        Add the Atom Chooser groupbox. This groupbox displays one of the
        following three groupboxes depending on the choice selected in the
        combobox:
          a) Periodic Table Elements L{self.regularElementChooser}
          b) PAM5 Atoms  L{self.PAM5Chooser}
          c) PAM3 Atoms  L{self.PAM3Chooser}
        @see: L{self.__updateAtomChooserGroupBoxes}
        """
        self.atomChooserGroupBox = \
            PM_GroupBox(self, title = "Atom Chooser")
        self._loadAtomChooserGroupBox(self.atomChooserGroupBox)

        self._updateAtomChooserGroupBoxes(currentIndex = 0)

    def _addElementChooserGroupBox(self, inPmGroupBox):
        """
        Add the 'Element Chooser' groupbox. (present within the
        Atom Chooser Groupbox)
        """
        if not self.previewGroupBox:
            return

        elementViewer = self.previewGroupBox.elementViewer
        self.regularElementChooser = \
            PM_ElementChooser( inPmGroupBox,
                               parentPropMgr = self,
                               elementViewer = elementViewer)


    def _add_PAM5_AtomChooserGroupBox(self, inPmGroupBox):
        """
        Add the 'PAM5 Atom Chooser' groupbox (present within the
        Atom Chooser Groupbox)
        """
        if not self.previewGroupBox:
            return

        elementViewer = self.previewGroupBox.elementViewer
        self.PAM5Chooser = \
            PM_PAM5_AtomChooser( inPmGroupBox,
                                 parentPropMgr = self,
                                 elementViewer = elementViewer)

    def _add_PAM3_AtomChooserGroupBox(self, inPmGroupBox):
        """
        Add the 'PAM3 Atom Chooser' groupbox (present within the
        Atom Chooser Groupbox)
        """
        if not self.previewGroupBox:
            return

        elementViewer = self.previewGroupBox.elementViewer
        self.PAM3Chooser = \
            PM_PAM3_AtomChooser( inPmGroupBox,
                                 parentPropMgr = self,
                                 elementViewer = elementViewer)

    def _hideAllAtomChooserGroupBoxes(self):
        """
        Hides all Atom Chooser group boxes.
        """
        if self.regularElementChooser:
            self.regularElementChooser.hide()
        if self.PAM5Chooser:
            self.PAM5Chooser.hide()
        if self.PAM3Chooser:
            self.PAM3Chooser.hide()

    def _addBondToolsGroupBox(self):
        """
        Add the 'Bond Tools' groupbox.
        """
        self.bondToolsGroupBox = \
            PM_GroupBox( self, title = "Bond Tools")

        self._loadBondToolsGroupBox(self.bondToolsGroupBox)

    def _addSelectionOptionsGroupBox(self):
        """
        Add 'Selection Options' groupbox
        """
        self.selectionOptionsGroupBox = \
            PM_GroupBox( self, title = "Selection Options" )

        self._loadSelectionOptionsGroupBox(self.selectionOptionsGroupBox)

    def _loadAtomChooserGroupBox(self, inPmGroupBox):
        """
        Load the widgets inside the Atom Chooser groupbox.
        @param inPmGroupBox: The Atom Chooser box in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        atomChooserChoices = [ "Periodic Table Elements",
                             "PAM5 Atoms",
                             "PAM3 Atoms" ]

        self.atomChooserComboBox = \
            PM_ComboBox( inPmGroupBox,
                         label        = '',
                         choices      = atomChooserChoices,
                         index        = 0,
                         setAsDefault = False,
                         spanWidth    = True )

        #Following fixes bug 2550
        self.atomChooserComboBox.setFocusPolicy(Qt.NoFocus)

        self._addElementChooserGroupBox(inPmGroupBox)
        self._add_PAM5_AtomChooserGroupBox(inPmGroupBox)
        self._add_PAM3_AtomChooserGroupBox(inPmGroupBox)

    def _loadSelectionOptionsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Selection Options group box.
        @param inPmGroupBox: The Selection Options box in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """

        self.selectionFilterCheckBox = \
            PM_CheckBox( inPmGroupBox,
                         text  = "Enable atom selection filter",
                         widgetColumn = 0,
                         state        = Qt.Unchecked  )
        self.selectionFilterCheckBox.setDefaultValue(False)

        self.filterlistLE = PM_LineEdit( inPmGroupBox,
                                         label        = "",
                                         text         = "",
                                         setAsDefault = False,
                                         spanWidth    = True )
        self.filterlistLE.setReadOnly(True)

        if self.selectionFilterCheckBox.isChecked():
            self.filterlistLE.setEnabled(True)
        else:
            self.filterlistLE.setEnabled(False)

        self.showSelectedAtomInfoCheckBox = \
            PM_CheckBox(
                inPmGroupBox,
                text  = "Show Selected Atom Info",
                widgetColumn = 0,
                state        = Qt.Unchecked)

        self.selectedAtomPosGroupBox = \
            PM_GroupBox( inPmGroupBox, title = "")
        self._loadSelectedAtomPosGroupBox(self.selectedAtomPosGroupBox)

        self.toggle_selectedAtomPosGroupBox(show = 0)
        self.enable_or_disable_selectedAtomPosGroupBox( bool_enable = False)

        self.reshapeSelectionCheckBox = \
            PM_CheckBox( inPmGroupBox,
                         text         = 'Dragging reshapes selection',
                         widgetColumn = 0,
                         state        = Qt.Unchecked  )

        connect_checkbox_with_boolean_pref( self.reshapeSelectionCheckBox,
                                            reshapeAtomsSelection_prefs_key )

        env.prefs[reshapeAtomsSelection_prefs_key] = False

        self.waterCheckBox = \
            PM_CheckBox( inPmGroupBox,
                         text         = "Z depth filter (water surface)",
                         widgetColumn = 0,
                         state        = Qt.Unchecked  )

    def _loadSelectedAtomPosGroupBox(self, inPmGroupBox):
        """
        Load the selected Atoms position groupbox It is a sub-gropbox of
        L{self.selectionOptionsGroupBox)
        @param inPmGroupBox: 'The Selected Atom Position Groupbox'
        @type  inPmGroupBox: L{PM_GroupBox}
        """

        self.selectedAtomLineEdit = PM_LineEdit( inPmGroupBox,
                                         label        = "Selected Atom:",
                                         text         = "",
                                         setAsDefault = False,
                                         spanWidth    = False )

        self.selectedAtomLineEdit.setReadOnly(True)
        self.selectedAtomLineEdit.setEnabled(False)

        self.coordinateSpinboxes = PM_CoordinateSpinBoxes(inPmGroupBox)

        # User input to specify x-coordinate
        self.xCoordOfSelectedAtom  =  self.coordinateSpinboxes.xSpinBox
        # User input to specify y-coordinate
        self.yCoordOfSelectedAtom  =  self.coordinateSpinboxes.ySpinBox
        # User input to specify z-coordinate
        self.zCoordOfSelectedAtom  =  self.coordinateSpinboxes.zSpinBox

    def _addAdvancedOptionsGroupBox(self):
        """
        Add 'Advanced Options' groupbox
        """
        self.advancedOptionsGroupBox = \
            PM_GroupBox( self, title = "Advanced Options" )

        self._loadAdvancedOptionsGroupBox(self.advancedOptionsGroupBox)

    def _loadAdvancedOptionsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Advanced Options group box.
        @param inPmGroupBox: The Advanced Options box in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """

        self.autoBondCheckBox = \
            PM_CheckBox( inPmGroupBox,
                         text         = 'Auto bond',
                         widgetColumn = 0,
                         state        = Qt.Checked  )

        self.highlightingCheckBox = \
            PM_CheckBox( inPmGroupBox,
                         text         = "Hover highlighting",
                         widgetColumn = 0,
                         state        = Qt.Checked )

    def _loadBondToolsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Bond Tools group box.
        @param inPmGroupBox: The Bond Tools box in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        # Button list to create a toolbutton row.
        # Format:
        # - buttonId,
        # - buttonText ,
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        BOND_TOOL_BUTTONS = \
                          [ ( "QToolButton", 0,  "SINGLE",    "", "", None, 0),
                            ( "QToolButton", 1,  "DOUBLE",    "", "", None, 1),
                            ( "QToolButton", 2,  "TRIPLE",    "", "", None, 2),
                            ( "QToolButton", 3,  "AROMATIC",  "", "", None, 3),
                            ( "QToolButton", 4,  "GRAPHITIC", "", "", None, 4),
                            ( "QToolButton", 5,  "CUTBONDS",  "", "", None, 5)
                          ]


        self.bondToolButtonRow = \
            PM_ToolButtonRow(
                inPmGroupBox,
                title        = "",
                buttonList   = BOND_TOOL_BUTTONS,
                checkedId    = None,
                setAsDefault = True )

    def _addWhatsThisText(self):
        """
        "What's This" text for widgets in this Property Manager.
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_BuildAtomsPropertyManager
        whatsThis_BuildAtomsPropertyManager(self)

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_BuildAtomsPropertyManager
        ToolTip_BuildAtomsPropertyManager(self)

    def toggle_selectedAtomPosGroupBox(self, show = 0):
        """
        Show or hide L{self.selectedAtomPosGroupBox} depending on the state of
        the checkbox (L{self.showSelectedAtomInfoCheckBox})
        @param show: Flag that shows or hides the groupbox (can have values
                     0 or 1
        @type  show: int
        """
        if show:
            self.selectedAtomPosGroupBox.show()
        else:
            self.selectedAtomPosGroupBox.hide()

    def enable_or_disable_selectedAtomPosGroupBox(self, bool_enable = False):
        """
        Enable or disable Selected AtomPosGroupBox present within
        'selection options' and also the checkbox that shows or hide this
        groupbox. These two widgets are enabled when only a single atom is
        selected from the 3D workspace.
        @param bool_enable: Flag that enables or disables widgets
        @type  bool_enable: boolean
        """
        if self.showSelectedAtomInfoCheckBox:
            self.showSelectedAtomInfoCheckBox.setEnabled(bool_enable)
        if self.selectedAtomPosGroupBox:
            self.selectedAtomPosGroupBox.setEnabled(bool_enable)

    def _updateAtomChooserGroupBoxes(self, currentIndex):
        """
        Updates the Atom Chooser Groupbox. It displays one of the
        following three groupboxes depending on the choice selected in the
        combobox:
          a) Periodic Table Elements L{self.regularElementChooser}
          b) PAM5 Atoms  L{self.PAM5Chooser}
          c) PAM3 Atoms  L{self.PAM3Chooser}
        It also sets self.elementChooser to the current active Atom chooser
        and updates the display accordingly in the Preview groupbox.
        """
        self._hideAllAtomChooserGroupBoxes()

        if currentIndex is 0:
            self.elementChooser = self.regularElementChooser
            self.regularElementChooser.show()
        if currentIndex is 1:
            self.elementChooser = self.PAM5Chooser
            self.PAM5Chooser.show()
        if currentIndex is 2:
            self.elementChooser = self.PAM3Chooser
            self.PAM3Chooser.show()

        if self.elementChooser:
            self.elementChooser.updateElementViewer()

        self.updateMessage()


    def updateMessage(self):
        """
        Update the Message groupbox with informative message.
        Subclasses should override this.
        """
        pass
Ejemplo n.º 2
0
class EditResidues_PropertyManager(Command_PropertyManager):
    """
    The ProteinDisplayStyle_PropertyManager class provides a Property Manager 
    for the B{Display Style} command on the flyout toolbar in the 
    Build > Protein mode. 

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title = "Edit Residues"
    pmName = title
    iconPath = "ui/actions/Command Toolbar/BuildProtein/Residues.png"

    rosetta_all_set = "PGAVILMFWYCSTNQDEHKR"
    rosetta_polar_set = "___________STNQDEHKR"
    rosetta_apolar_set = "PGAVILMFWYC_________"

    def __init__(self, command):
        """
        Constructor for the property manager.
        """

        self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key]

        _superclass.__init__(self, command)

        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        self.editingItem = False
        return

    def connect_or_disconnect_signals(self, isConnect=True):

        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self.applyAnyPushButton, SIGNAL("clicked()"),
                       self._applyAny)

        change_connect(self.applySamePushButton, SIGNAL("clicked()"),
                       self._applySame)

        change_connect(self.applyLockedPushButton, SIGNAL("clicked()"),
                       self._applyLocked)

        change_connect(self.applyPolarPushButton, SIGNAL("clicked()"),
                       self._applyPolar)

        change_connect(self.applyApolarPushButton, SIGNAL("clicked()"),
                       self._applyApolar)

        change_connect(self.selectAllPushButton, SIGNAL("clicked()"),
                       self._selectAll)

        change_connect(self.selectNonePushButton, SIGNAL("clicked()"),
                       self._selectNone)

        change_connect(self.selectInvertPushButton, SIGNAL("clicked()"),
                       self._invertSelection)

        change_connect(self.applyDescriptorPushButton, SIGNAL("clicked()"),
                       self._applyDescriptor)

        change_connect(self.removeDescriptorPushButton, SIGNAL("clicked()"),
                       self._removeDescriptor)

        change_connect(self.sequenceTable, SIGNAL("cellClicked(int, int)"),
                       self._sequenceTableCellChanged)

        change_connect(self.sequenceTable,
                       SIGNAL("itemChanged(QTableWidgetItem*)"),
                       self._sequenceTableItemChanged)

        change_connect(self.descriptorsTable,
                       SIGNAL("itemChanged(QTableWidgetItem*)"),
                       self._descriptorsTableItemChanged)

        change_connect(self.newDescriptorPushButton, SIGNAL("clicked()"),
                       self._addNewDescriptor)
        change_connect(self.showSequencePushButton, SIGNAL("clicked()"),
                       self._showSeqEditor)
        return

    def _showSeqEditor(self):
        """
        Shows sequence editor
        """
        if self.showSequencePushButton.isEnabled():
            self.sequenceEditor.show()
        return

    def show(self):
        """
        Shows the Property Manager. Extends superclass method.
        """
        env.history.statusbar_msg("")
        #Urmi 20080728: Set the current protein and this will be used for accessing
        #various properties of this protein
        self.set_current_protein()
        if self.current_protein:
            msg = "Editing structure <b>%s</b>." % self.current_protein.name
            self.showSequencePushButton.setEnabled(True)
        else:
            msg = "Select a single structure to edit."
            self.showSequencePushButton.setEnabled(False)
        self.sequenceEditor.hide()

        _superclass.show(self)

        self._fillSequenceTable()
        self.updateMessage(msg)

        return

    def set_current_protein(self):
        """
        Set the current protein for which all the properties are displayed to the
        one chosen in the build protein combo box
        """
        self.current_protein = self.win.assy.getSelectedProteinChunk()
        return

    def _addGroupBoxes(self):
        """
        Add the Property Manager group boxes.
        """

        if sys.platform == "darwin":
            # Workaround for table font size difference between Mac/Win
            self.labelfont = QFont("Helvetica", 12)
            self.descriptorfont = QFont("Courier New", 12)
        else:
            self.labelfont = QFont("Helvetica", 9)
            self.descriptorfont = QFont("Courier New", 9)

        self._pmGroupBox1 = PM_GroupBox(self, title="Descriptors")
        self._loadGroupBox1(self._pmGroupBox1)

        self._pmGroupBox2 = PM_GroupBox(self, title="Sequence")
        self._loadGroupBox2(self._pmGroupBox2)

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in the first group box.
        """

        self.headerdata_desc = ['Name', 'Descriptor']

        self.set_names = ["Any", "Same", "Locked", "Apolar", "Polar"]
        self.rosetta_set_names = ["ALLAA", "NATAA", "NATRO", "APOLA", "POLAR"]
        self.descriptor_list = [
            "PGAVILMFWYCSTNQDEHKR", "____________________",
            "____________________", "PGAVILMFWYC_________",
            "___________STNQDEHKR"
        ]

        self.applyAnyPushButton = PM_PushButton(pmGroupBox,
                                                text="ALLAA",
                                                setAsDefault=True)

        self.applySamePushButton = PM_PushButton(pmGroupBox,
                                                 text="NATAA",
                                                 setAsDefault=True)

        self.applyLockedPushButton = PM_PushButton(pmGroupBox,
                                                   text="NATRO",
                                                   setAsDefault=True)

        self.applyPolarPushButton = PM_PushButton(pmGroupBox,
                                                  text="APOLA",
                                                  setAsDefault=True)

        self.applyApolarPushButton = PM_PushButton(pmGroupBox,
                                                   text="POLAR",
                                                   setAsDefault=True)

        #self.applyBackrubPushButton = PM_PushButton( pmGroupBox,
        #    text       =  "BACKRUB",
        #    setAsDefault  =  True)

        self.applyAnyPushButton.setFixedHeight(25)
        self.applyAnyPushButton.setFixedWidth(60)

        self.applySamePushButton.setFixedHeight(25)
        self.applySamePushButton.setFixedWidth(60)

        self.applyLockedPushButton.setFixedHeight(25)
        self.applyLockedPushButton.setFixedWidth(60)

        self.applyPolarPushButton.setFixedHeight(25)
        self.applyPolarPushButton.setFixedWidth(60)

        self.applyApolarPushButton.setFixedHeight(25)
        self.applyApolarPushButton.setFixedWidth(60)

        applyButtonList = [('PM_PushButton', self.applyAnyPushButton, 0, 0),
                           ('PM_PushButton', self.applySamePushButton, 1, 0),
                           ('PM_PushButton', self.applyLockedPushButton, 2, 0),
                           ('PM_PushButton', self.applyPolarPushButton, 3, 0),
                           ('PM_PushButton', self.applyApolarPushButton, 4, 0)]

        self.applyButtonGrid = PM_WidgetGrid(pmGroupBox,
                                             label="Apply standard set",
                                             widgetList=applyButtonList)

        self.descriptorsTable = PM_TableWidget(pmGroupBox,
                                               label="Custom descriptors")

        self.descriptorsTable.setFixedHeight(100)
        self.descriptorsTable.setRowCount(0)
        self.descriptorsTable.setColumnCount(2)
        self.descriptorsTable.verticalHeader().setVisible(False)
        self.descriptorsTable.horizontalHeader().setVisible(True)
        self.descriptorsTable.setGridStyle(Qt.NoPen)
        self.descriptorsTable.setHorizontalHeaderLabels(self.headerdata_desc)

        self._updateSetLists()

        self._fillDescriptorsTable()

        self.descriptorsTable.resizeColumnsToContents()

        self.newDescriptorPushButton = PM_PushButton(pmGroupBox,
                                                     text="New",
                                                     setAsDefault=True)

        self.newDescriptorPushButton.setFixedHeight(25)

        self.removeDescriptorPushButton = PM_PushButton(pmGroupBox,
                                                        text="Remove",
                                                        setAsDefault=True)

        self.removeDescriptorPushButton.setFixedHeight(25)

        self.applyDescriptorPushButton = PM_PushButton(pmGroupBox,
                                                       text="Apply",
                                                       setAsDefault=True)

        self.applyDescriptorPushButton.setFixedHeight(25)

        addDescriptorButtonList = [
            ('PM_PushButton', self.newDescriptorPushButton, 0, 0),
            ('PM_PushButton', self.removeDescriptorPushButton, 1, 0),
            ('PM_PushButton', self.applyDescriptorPushButton, 2, 0)
        ]

        self.addDescriptorGrid = PM_WidgetGrid(
            pmGroupBox, alignment="Center", widgetList=addDescriptorButtonList)

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in the second group box.
        """

        self.headerdata_seq = ['', 'ID', 'Set', 'BR', 'Descriptor']

        self.recenterViewCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Re-center view on selected residue",
                         setAsDefault  =  True,
                         widgetColumn  = 0,
                         state         = Qt.Unchecked)

        self.selectAllPushButton = PM_PushButton(pmGroupBox,
                                                 text="All",
                                                 setAsDefault=True)

        self.selectAllPushButton.setFixedHeight(25)

        self.selectNonePushButton = PM_PushButton(pmGroupBox,
                                                  text="None",
                                                  setAsDefault=True)

        self.selectNonePushButton.setFixedHeight(25)

        self.selectInvertPushButton = PM_PushButton(pmGroupBox,
                                                    text="Invert",
                                                    setAsDefault=True)

        self.selectInvertPushButton.setFixedHeight(25)

        buttonList = [('PM_PushButton', self.selectAllPushButton, 0, 0),
                      ('PM_PushButton', self.selectNonePushButton, 1, 0),
                      ('PM_PushButton', self.selectInvertPushButton, 2, 0)]

        self.buttonGrid = PM_WidgetGrid(pmGroupBox, widgetList=buttonList)

        self.sequenceTable = PM_TableWidget(pmGroupBox)
        #self.sequenceTable.setModel(self.tableModel)
        self.sequenceTable.resizeColumnsToContents()
        self.sequenceTable.verticalHeader().setVisible(False)
        #self.sequenceTable.setRowCount(0)
        self.sequenceTable.setColumnCount(5)

        self.checkbox = QCheckBox()

        self.sequenceTable.setFixedHeight(345)

        self.sequenceTable.setGridStyle(Qt.NoPen)

        self.sequenceTable.setHorizontalHeaderLabels(self.headerdata_seq)
        ###self._fillSequenceTable()
        self.showSequencePushButton = PM_PushButton(pmGroupBox,
                                                    text="Show Sequence",
                                                    setAsDefault=True,
                                                    spanWidth=True)

    def _addWhatsThisText(self):
        #from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditResidues_PropertyManager
        #WhatsThis_EditResidues_PropertyManager(self)
        pass

    def _addToolTipText(self):
        #from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager
        #ToolTip_EditProteinDisplayStyle_PropertyManager(self)
        pass

    def _fillSequenceTable(self):
        """
        Fills in the sequence table.
        """

        if not self.current_protein:
            return
        else:
            currentProteinChunk = self.current_protein

        self.editingItem = True

        aa_list = currentProteinChunk.protein.get_amino_acids()
        aa_list_len = len(aa_list)
        self.sequenceTable.setRowCount(aa_list_len)
        for index in range(aa_list_len):
            # Selection checkbox column
            item_widget = QTableWidgetItem("")
            item_widget.setFont(self.labelfont)
            item_widget.setCheckState(Qt.Checked)
            item_widget.setTextAlignment(Qt.AlignLeft)
            item_widget.setSizeHint(QSize(20, 12))
            item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled
                                 | Qt.ItemIsUserCheckable)
            self.sequenceTable.setItem(index, 0, item_widget)

            # Amino acid index column
            item_widget = QTableWidgetItem(str(index + 1))
            item_widget.setFont(self.labelfont)
            item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            item_widget.setTextAlignment(Qt.AlignCenter)
            self.sequenceTable.setItem(index, 1, item_widget)

            # Mutation descriptor name column
            aa = self._get_aa_for_index(index)
            item_widget = QTableWidgetItem(self._get_descriptor_name(aa))
            item_widget.setFont(self.labelfont)
            item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            item_widget.setTextAlignment(Qt.AlignCenter)
            self.sequenceTable.setItem(index, 2, item_widget)

            # Backrub checkbox column
            item_widget = QTableWidgetItem("")
            item_widget.setFont(self.labelfont)
            if aa.get_backrub_mode():
                item_widget.setCheckState(Qt.Checked)
            else:
                item_widget.setCheckState(Qt.Unchecked)
            item_widget.setTextAlignment(Qt.AlignLeft)
            item_widget.setSizeHint(QSize(20, 12))
            item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled
                                 | Qt.ItemIsUserCheckable)
            self.sequenceTable.setItem(index, 3, item_widget)

            # Mutation descriptor column
            aa_string = self._get_mutation_descriptor(aa)
            item_widget = QTableWidgetItem(aa_string)
            item_widget.setFont(self.descriptorfont)
            self.sequenceTable.setItem(index, 4, item_widget)

            self.sequenceTable.setRowHeight(index, 16)

        self.editingItem = False

        self.sequenceTable.resizeColumnsToContents()

        self.sequenceTable.setColumnWidth(0, 35)
        self.sequenceTable.setColumnWidth(2, 80)
        self.sequenceTable.setColumnWidth(3, 35)
        return

    def _fillDescriptorsTable(self):
        """
        Fills in the descriptors table from descriptors user pref.
        """
        dstr = env.prefs[proteinCustomDescriptors_prefs_key].split(":")
        for i in range(len(dstr) / 2):
            self._addNewDescriptorTableRow(dstr[2 * i], dstr[2 * i + 1])

    def _selectAll(self):
        """
        Select all rows in the sequence table.
        """
        for row in range(self.sequenceTable.rowCount()):
            self.sequenceTable.item(row, 0).setCheckState(Qt.Checked)

    def _selectNone(self):
        """
        Unselect all rows in the sequence table.
        """
        for row in range(self.sequenceTable.rowCount()):
            self.sequenceTable.item(row, 0).setCheckState(Qt.Unchecked)

    def _invertSelection(self):
        """
        Inverto row selection range in the sequence table.
        """
        for row in range(self.sequenceTable.rowCount()):
            item_widget = self.sequenceTable.item(row, 0)
            if item_widget.checkState() == Qt.Checked:
                item_widget.setCheckState(Qt.Unchecked)
            else:
                item_widget.setCheckState(Qt.Checked)

    def _get_mutation_descriptor(self, aa):
        """
        Get mutation descriptor string for a given amino acid.
        """
        aa_string = self.rosetta_all_set

        range = aa.get_mutation_range()
        aa_string = self.rosetta_all_set

        if range == "NATRO" or \
           range == "NATAA":
            code = aa.get_one_letter_code()
            aa_string = re.sub("[^" + code + "]", '_', aa_string)
        elif range == "POLAR":
            aa_string = self.rosetta_polar_set
        elif range == "APOLA":
            aa_string = self.rosetta_apolar_set
        elif range == "PIKAA":
            aa_string = aa.get_mutation_descriptor()

        return aa_string

    def _get_descriptor_name(self, aa):
        """
        Returns a mutation descriptor name for an amino acid.
        """
        range_name = aa.get_mutation_range()
        for i in range(len(self.rosetta_set_names)):
            if range_name == self.rosetta_set_names[i]:
                if range_name == "PIKAA":
                    # Find a descriptor with a list of
                    # custom descriptors.
                    dstr = self._makeProperAAString(
                        aa.get_mutation_descriptor())
                    for i in range(5, len(self.descriptor_list)):
                        if dstr == self.descriptor_list[i]:
                            return self.set_names[i]
                else:
                    return self.set_names[i]
        return "Custom"

    def _get_aa_for_index(self, index, expand=False):
        """
        Get amino acid by index.
        @return: amino acid (Residue)
        """

        if not self.current_protein:
            return None
        else:
            currentProteinChunk = self.current_protein

        currentProteinChunk.protein.set_current_amino_acid_index(index)
        current_aa = currentProteinChunk.protein.get_current_amino_acid()
        if expand:
            currentProteinChunk.protein.collapse_all_rotamers()
            currentProteinChunk.protein.expand_rotamer(current_aa)
        return current_aa

    def _sequenceTableCellChanged(self, crow, ccol):
        """
        Slot for sequence table CellChanged event.
        """
        item = self.sequenceTable.item(crow, ccol)
        for row in range(self.sequenceTable.rowCount()):
            self.sequenceTable.removeCellWidget(row, 2)
            self.sequenceTable.setRowHeight(row, 16)
        if ccol == 2:
            # Make the row a little bit wider.
            self.sequenceTable.setRowHeight(crow, 22)
            # Create and insert a Combo Box into a current cell.
            self.setComboBox = QComboBox()
            self.setComboBox.addItems(self.set_names)

            self.win.connect(self.setComboBox, SIGNAL("activated(int)"),
                             self._setComboBoxIndexChanged)

            self.sequenceTable.setCellWidget(crow, 2, self.setComboBox)

        current_aa = self._get_aa_for_index(crow, expand=True)
        if current_aa:
            # Center on the selected amino acid.
            if self.recenterViewCheckBox.isChecked():
                ca_atom = current_aa.get_c_alpha_atom()
                if ca_atom:
                    self.win.glpane.pov = -ca_atom.posn()
            self.win.glpane.gl_update()

            # Update backrub status for selected amino acid.
            if ccol == 3:
                cbox = self.sequenceTable.item(crow, 3)
                if cbox.checkState() == Qt.Checked:
                    current_aa.set_backrub_mode(True)
                else:
                    current_aa.set_backrub_mode(False)

        from PyQt4.Qt import QTextCursor
        cursor = self.sequenceEditor.sequenceTextEdit.textCursor()
        #boundary condition
        if crow == -1:
            crow = 0
        cursor.setPosition(crow, QTextCursor.MoveAnchor)
        cursor.setPosition(crow + 1, QTextCursor.KeepAnchor)
        self.sequenceEditor.sequenceTextEdit.setTextCursor(cursor)

    def _applyDescriptor(self):
        """        
        Apply mutation descriptor to the selected amino acids.
        """
        cdes = self.descriptorsTable.currentRow()
        for row in range(self.sequenceTable.rowCount()):
            self._setComboBoxIndexChanged(cdes + 5,
                                          tablerow=row,
                                          selectedOnly=True)

    def _setComboBoxIndexChanged(self,
                                 index,
                                 tablerow=None,
                                 selectedOnly=False):
        """
        Slot for mutation descriptor combo box (in third column of the sequence
        table.)
        """
        if tablerow is None:
            crow = self.sequenceTable.currentRow()
        else:
            crow = tablerow
        item = self.sequenceTable.item(crow, 2)
        if item:
            self.editingItem = True

            cbox = self.sequenceTable.item(crow, 0)
            if not selectedOnly or \
               cbox.checkState() == Qt.Checked:
                item.setText(self.set_names[index])
                item = self.sequenceTable.item(crow, 4)
                aa = self._get_aa_for_index(crow)
                set_name = self.rosetta_set_names[index]
                aa.set_mutation_range(set_name)
                if set_name == "PIKAA":
                    aa.set_mutation_descriptor(self.descriptor_list[index])
                item.setText(self._get_mutation_descriptor(aa))
                for row in range(self.sequenceTable.rowCount()):
                    self.sequenceTable.removeCellWidget(row, 2)
                    self.sequenceTable.setRowHeight(row, 16)

            self.editingItem = False

    def scrollToPosition(self, index):
        """
        Scrolls the Sequence Table to a given sequence position.
        """
        item = self.sequenceTable.item(index, 0)
        if item:
            self.sequenceTable.scrollToItem(item)

    def _applyAny(self):
        """
        Apply "ALLAA" descriptor.
        """
        for row in range(self.sequenceTable.rowCount()):
            self._setComboBoxIndexChanged(0, tablerow=row, selectedOnly=True)

    def _applySame(self):
        """
        Apply "NATAA" descriptor.
        """
        for row in range(self.sequenceTable.rowCount()):
            self._setComboBoxIndexChanged(1, tablerow=row, selectedOnly=True)

    def _applyLocked(self):
        """
        Apply "NATRO" descriptor.
        """
        for row in range(self.sequenceTable.rowCount()):
            self._setComboBoxIndexChanged(2, tablerow=row, selectedOnly=True)

    def _applyPolar(self):
        """
        Apply "POLAR" descriptor.
        """
        for row in range(self.sequenceTable.rowCount()):
            self._setComboBoxIndexChanged(3, tablerow=row, selectedOnly=True)

    def _applyApolar(self):
        """
        Apply "APOLA" descriptor.
        """
        for row in range(self.sequenceTable.rowCount()):
            self._setComboBoxIndexChanged(4, tablerow=row, selectedOnly=True)

    def resizeEvent(self, event):
        """
        Called whenever PM width has changed. Sets correct width of the
        rows in descriptor and sequence tables.
        """
        self.descriptorsTable.setColumnWidth(
            1,
            self.descriptorsTable.width() -
            self.descriptorsTable.columnWidth(0) - 20)

        self.sequenceTable.setColumnWidth(
            4,
            self.sequenceTable.width() - (self.sequenceTable.columnWidth(0) +
                                          self.sequenceTable.columnWidth(1) +
                                          self.sequenceTable.columnWidth(2) +
                                          self.sequenceTable.columnWidth(3)) -
            20)

    def _addNewDescriptorTableRow(self, name, descriptor):
        """
        Adds a new row to the descriptor table.
        """
        row = self.descriptorsTable.rowCount()
        self.descriptorsTable.insertRow(row)

        item_widget = QTableWidgetItem(name)
        item_widget.setFont(self.labelfont)
        item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled
                             | Qt.ItemIsEditable)
        item_widget.setTextAlignment(Qt.AlignLeft)
        self.descriptorsTable.setItem(row, 0, item_widget)
        self.descriptorsTable.resizeColumnToContents(0)

        s = self._makeProperAAString(descriptor)
        item_widget = QTableWidgetItem(s)
        item_widget.setFont(self.descriptorfont)
        item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled
                             | Qt.ItemIsEditable)
        item_widget.setTextAlignment(Qt.AlignLeft)
        self.descriptorsTable.setItem(row, 1, item_widget)
        self.descriptorsTable.setColumnWidth(
            1,
            self.descriptorsTable.width() -
            self.descriptorsTable.columnWidth(0) - 20)

        self.descriptorsTable.setRowHeight(row, 16)

    def _addNewDescriptor(self):
        """
        Adds a new descriptor to the descriptor table.
        """
        self._addNewDescriptorTableRow("New Set", "PGAVILMFWYCSTNQDEHKR")
        self._makeDescriptorUserPref()
        self._updateSetLists()

    def _removeDescriptor(self):
        """
        Removes a highlighted descriptor from the descriptors table.
        """
        crow = self.descriptorsTable.currentRow()
        if crow >= 0:
            self.descriptorsTable.removeRow(crow)
            self._makeDescriptorUserPref()
            self._updateSetLists()

    def _makeDescriptorUserPref(self):
        """
        Constructs a custom descriptors string.
        """
        dstr = ""
        for row in range(self.descriptorsTable.rowCount()):
            item0 = self.descriptorsTable.item(row, 0)
            item1 = self.descriptorsTable.item(row, 1)
            if item0 and \
               item1:
                dstr += item0.text() + \
                     ":" + \
                     item1.text() + \
                     ":"
        env.prefs[proteinCustomDescriptors_prefs_key] = dstr

    def _makeProperAAString(self, string):
        """
        Creates a proper amino acid string from an arbitrary string.
        """
        aa_string = str(string).upper()
        new_aa_string = ""
        for i in range(len(self.rosetta_all_set)):
            if aa_string.find(self.rosetta_all_set[i]) == -1:
                new_aa_string += "_"
            else:
                new_aa_string += self.rosetta_all_set[i]
        return new_aa_string

    def _sequenceTableItemChanged(self, item):
        """
        Called when an item in the sequence table has changed.
        """
        if self.editingItem:
            return
        if self.sequenceTable.column(item) == 4:
            self.editingItem = True
            crow = self.sequenceTable.currentRow()
            dstr = self._makeProperAAString(str(item.text()).upper())
            item.setText(dstr)
            aa = self._get_aa_for_index(crow)
            if aa:
                aa.set_mutation_range("PIKAA")
                aa.set_mutation_descriptor(dstr.replace("_", ""))
            item = self.sequenceTable.item(crow, 2)
            if item:
                item.setText("Custom")
            self.editingItem = False

    def _descriptorsTableItemChanged(self, item):
        """
        Called when an item in the descriptors table has changed.
        """
        if self.editingItem:
            return
        if self.descriptorsTable.column(item) == 1:
            self.editingItem = True
            item.setText(self._makeProperAAString(str(item.text()).upper()))
            self.editingItem = False

        self._makeDescriptorUserPref()
        self._updateSetLists()

    def _updateSetLists(self):
        """
        Updates lists of descriptor sets and descriptor set names.
        """
        self.set_names = self.set_names[:5]
        self.descriptor_list = self.descriptor_list[:5]
        self.rosetta_set_names = self.rosetta_set_names[:5]

        dstr = env.prefs[proteinCustomDescriptors_prefs_key].split(":")
        for i in range(len(dstr) / 2):
            self.set_names.append(dstr[2 * i])
            self.descriptor_list.append(dstr[2 * i + 1])
            self.rosetta_set_names.append("PIKAA")
            #self._addNewDescriptorTableRow(dstr[2*i], dstr[2*i+1])
        return

    def _update_UI_do_updates_TEMP(self):
        """
        Overrides superclass method. 
        
        @see: Command_PropertyManager._update_UI_do_updates()
        """

        self.current_protein = self.win.assy.getSelectedProteinChunk()

        if self.current_protein is self.previous_protein:
            print "_update_UI_do_updates(): DO NOTHING."
            return

        # NOTE: Changing the display styles of the protein chunks can take some
        # time. We should put up the wait (hourglass) cursor here and restore
        # before returning.

        # Update all PM widgets that need to be since something has changed.
        print "_update_UI_do_updates(): UPDATING the PMGR."
        self.update_name_field()
        self.sequenceEditor.update()
        self.update_residue_combobox()

        if self.previous_protein:
            self.previous_protein.setDisplayStyle(
                self.previous_protein_display_style)

        self.previous_protein = self.current_protein

        if self.current_protein:
            self.previous_protein_display_style = self.current_protein.getDisplayStyle(
            )
            self.current_protein.setDisplayStyle(diPROTEIN)

        return
class BreakOrJoinStrands_PropertyManager(Command_PropertyManager):

    _baseNumberLabelGroupBox = None

    def __init__( self, command ):
        """
        Constructor for the property manager.
        """
        _superclass.__init__(self, command)
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)


        return

    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot
                          method.
        @type  isConnect: boolean
        """
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        # DNA Strand arrowhead display options signal-slot connections.


        self._connect_checkboxes_to_global_prefs_keys(isConnect)

        change_connect(self.fivePrimeEndColorChooser,
                       SIGNAL("editingFinished()"),
                       self.chooseCustomColorOnFivePrimeEnds)

        change_connect(self.threePrimeEndColorChooser,
                       SIGNAL("editingFinished()"),
                       self.chooseCustomColorOnThreePrimeEnds)

        change_connect(self.strandFivePrimeArrowheadsCustomColorCheckBox,
                       SIGNAL("toggled(bool)"),
                       self.allowChoosingColorsOnFivePrimeEnd)

        change_connect(self.strandThreePrimeArrowheadsCustomColorCheckBox,
                       SIGNAL("toggled(bool)"),
                       self.allowChoosingColorsOnThreePrimeEnd)

        self._baseNumberLabelGroupBox.connect_or_disconnect_signals(isConnect)

        return

    def show(self):
        """
        Shows the Property Manager. Extends superclass method.
        @see: Command_PropertyManager.show()
        """
        _superclass.show(self)
        #Required to update the color combobox for Dna base number labels.
        self._baseNumberLabelGroupBox.updateWidgets()


    def _connect_checkboxes_to_global_prefs_keys(self, isConnect = True):
        """
        #doc
        """
        if not isConnect:
            return

        #ORDER of items in tuples checkboxes and prefs_keys is IMPORTANT!
        checkboxes = (
            self.arrowsOnThreePrimeEnds_checkBox,
            self.arrowsOnFivePrimeEnds_checkBox,
            self.strandThreePrimeArrowheadsCustomColorCheckBox,
            self.strandFivePrimeArrowheadsCustomColorCheckBox,
            self.arrowsOnBackBones_checkBox)

        prefs_keys = (
            self._prefs_key_arrowsOnThreePrimeEnds(),
            self._prefs_key_arrowsOnFivePrimeEnds(),
            self._prefs_key_useCustomColorForThreePrimeArrowheads(),
            self._prefs_key_useCustomColorForFivePrimeArrowheads(),
            arrowsOnBackBones_prefs_key)

        for checkbox, prefs_key in zip(checkboxes, prefs_keys):
            connect_checkbox_with_boolean_pref(checkbox, prefs_key)

        return

    #Load various widgets ====================

    def _loadBaseNumberLabelGroupBox(self, pmGroupBox):
        self._baseNumberLabelGroupBox = PM_DnaBaseNumberLabelsGroupBox(pmGroupBox,
                                                                       self.command)

    def _loadDisplayOptionsGroupBox(self, pmGroupBox):
        """
        Load widgets in the display options groupbox
        """
        title = "Arrowhead prefs in %s:"%self.command.featurename
        self._arrowheadPrefsGroupBox = PM_GroupBox(
            pmGroupBox,
            title = title)
        #load all the options
        self._load3PrimeEndArrowAndCustomColor(self._arrowheadPrefsGroupBox)
        self._load5PrimeEndArrowAndCustomColor(self._arrowheadPrefsGroupBox)
        self._loadArrowOnBackBone(pmGroupBox)
        return

    def _load3PrimeEndArrowAndCustomColor(self, pmGroupBox):
        """
        Loads 3' end arrow head and custom color checkbox and color chooser dialog
        """
        self.pmGroupBox3 = PM_GroupBox(pmGroupBox, title = "3' end:")

        self.arrowsOnThreePrimeEnds_checkBox = PM_CheckBox( self.pmGroupBox3,
                                                            text         = "Show arrowhead",
                                                            widgetColumn  = 0,
                                                            setAsDefault = True,
                                                            spanWidth = True )

        self.strandThreePrimeArrowheadsCustomColorCheckBox = PM_CheckBox( self.pmGroupBox3,
                                                            text         = "Display custom color",
                                                            widgetColumn  = 0,
                                                            setAsDefault = True,
                                                            spanWidth = True)

        prefs_key = self._prefs_key_dnaStrandThreePrimeArrowheadsCustomColor()
        self.threePrimeEndColorChooser = \
            PM_ColorComboBox(self.pmGroupBox3,
                             color      = env.prefs[prefs_key])

        prefs_key = self._prefs_key_useCustomColorForThreePrimeArrowheads()
        if env.prefs[prefs_key]:
            self.strandThreePrimeArrowheadsCustomColorCheckBox.setCheckState(Qt.Checked)
            self.threePrimeEndColorChooser.show()
        else:
            self.strandThreePrimeArrowheadsCustomColorCheckBox.setCheckState(Qt.Unchecked)
            self.threePrimeEndColorChooser.hide()

        return

    def _load5PrimeEndArrowAndCustomColor(self, pmGroupBox):
        """
        Loads 5' end custom color checkbox and color chooser dialog
        """
        self.pmGroupBox2 = PM_GroupBox(pmGroupBox, title = "5' end:")
        self.arrowsOnFivePrimeEnds_checkBox = PM_CheckBox( self.pmGroupBox2,
                                                            text         = "Show arrowhead",
                                                            widgetColumn  = 0,
                                                            setAsDefault = True,
                                                            spanWidth = True
                                                            )


        self.strandFivePrimeArrowheadsCustomColorCheckBox = PM_CheckBox( self.pmGroupBox2,
                                                            text         = "Display custom color",
                                                            widgetColumn  = 0,
                                                            setAsDefault = True,
                                                            spanWidth = True )

        prefs_key = self._prefs_key_dnaStrandFivePrimeArrowheadsCustomColor()
        self.fivePrimeEndColorChooser = \
            PM_ColorComboBox(self.pmGroupBox2,
                             color      = env.prefs[prefs_key]
                             )

        prefs_key = self._prefs_key_useCustomColorForFivePrimeArrowheads()
        if env.prefs[prefs_key]:
            self.strandFivePrimeArrowheadsCustomColorCheckBox.setCheckState(Qt.Checked)
            self.fivePrimeEndColorChooser.show()
        else:
            self.strandFivePrimeArrowheadsCustomColorCheckBox.setCheckState(Qt.Unchecked)
            self.fivePrimeEndColorChooser.hide()

        return

    def _loadArrowOnBackBone(self, pmGroupBox):
        """
        Loads Arrow on the backbone checkbox
        """
        self.pmGroupBox4 = PM_GroupBox(pmGroupBox, title = "Global preference:")
        self.arrowsOnBackBones_checkBox = PM_CheckBox( self.pmGroupBox4,
                                                       text         = "Show arrows on back bones",
                                                       widgetColumn  = 0,
                                                       setAsDefault = True,
                                                       spanWidth = True
                                                       )
        return

    def allowChoosingColorsOnFivePrimeEnd(self, state):
        """
        Show or hide color chooser based on the
        strandFivePrimeArrowheadsCustomColorCheckBox's state
        """
        if self.strandFivePrimeArrowheadsCustomColorCheckBox.isChecked():
            self.fivePrimeEndColorChooser.show()
        else:
            self.fivePrimeEndColorChooser.hide()
        return

    def allowChoosingColorsOnThreePrimeEnd(self, state):
        """
        Show or hide color chooser based on the
        strandThreePrimeArrowheadsCustomColorCheckBox's state
        """
        if self.strandThreePrimeArrowheadsCustomColorCheckBox.isChecked():
            self.threePrimeEndColorChooser.show()
        else:
            self.threePrimeEndColorChooser.hide()
        return

    def chooseCustomColorOnThreePrimeEnds(self):
        """
        Choose custom color for 3' ends
        """
        color = self.threePrimeEndColorChooser.getColor()
        prefs_key = self._prefs_key_dnaStrandThreePrimeArrowheadsCustomColor()
        env.prefs[prefs_key] = color
        self.win.glpane.gl_update()
        return

    def chooseCustomColorOnFivePrimeEnds(self):
        """
        Choose custom color for 5' ends
        """
        color = self.fivePrimeEndColorChooser.getColor()
        prefs_key = self._prefs_key_dnaStrandFivePrimeArrowheadsCustomColor()
        env.prefs[prefs_key] = color
        self.win.glpane.gl_update()
        return

    #Return varius prefs_keys for arrowhead display options ui elements =======
    def _prefs_key_arrowsOnThreePrimeEnds(self):
        """
        Return the appropriate KEY of the preference for whether to
        draw arrows on 3' strand ends of PAM DNA.
        """
        return arrowsOnThreePrimeEnds_prefs_key

    def _prefs_key_arrowsOnFivePrimeEnds(self):
        """
        Return the appropriate KEY of the preference for whether to
        draw arrows on 5' strand ends of PAM DNA.
        """
        return arrowsOnFivePrimeEnds_prefs_key

    def _prefs_key_useCustomColorForThreePrimeArrowheads(self):
        """
        Return the appropriate KEY of the preference for whether to use a
        custom color for 3' arrowheads (if they are drawn)
        or for 3' strand end atoms (if arrowheads are not drawn)
        """
        return useCustomColorForThreePrimeArrowheads_prefs_key

    def _prefs_key_useCustomColorForFivePrimeArrowheads(self):
        """
        Return the appropriate KEY of the preference for whether to use a
        custom color for 5' arrowheads (if they are drawn)
        or for 5' strand end atoms (if arrowheads are not drawn).
        """
        return useCustomColorForFivePrimeArrowheads_prefs_key

    def _prefs_key_dnaStrandThreePrimeArrowheadsCustomColor(self):
        """
        Return the appropriate KEY of the preference for what custom color
        to use when drawing 3' arrowheads (if they are drawn)
        or 3' strand end atoms (if arrowheads are not drawn).
        """
        return dnaStrandThreePrimeArrowheadsCustomColor_prefs_key

    def _prefs_key_dnaStrandFivePrimeArrowheadsCustomColor(self):
        """
        Return the appropriate KEY of the preference for what custom color
        to use when drawing 5' arrowheads (if they are drawn)
        or 5' strand end atoms (if arrowheads are not drawn).
        """
        return dnaStrandFivePrimeArrowheadsCustomColor_prefs_key
class FixedBBProteinSim_PropertyManager(Command_PropertyManager):
    """
    The FixedBBProteinSim_PropertyManager class provides a Property Manager
    for the B{Fixed backbone Protein Sequence Design} command on the flyout toolbar in the
    Build > Protein > Simulate mode.

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title = "Fixed Backbone Design"
    pmName = title
    iconPath = "ui/actions/Command Toolbar/BuildProtein/FixedBackbone.png"

    def __init__(self, command):
        """
        Constructor for the property manager.
        """

        _superclass.__init__(self, command)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Choose from the various options below to design "\
            "an optimized <b>fixed backbone protein sequence</b> with Rosetta."
        self.updateMessage(msg)
        return

    def connect_or_disconnect_signals(self, isConnect=True):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot
                          method.
        @type  isConnect: boolean
        """

        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self.ex1Checkbox, SIGNAL("stateChanged(int)"),
                       self.update_ex1)
        change_connect(self.ex1aroCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_ex1aro)
        change_connect(self.ex2Checkbox, SIGNAL("stateChanged(int)"),
                       self.update_ex2)
        change_connect(self.ex2aroOnlyCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_ex2aro_only)
        change_connect(self.ex3Checkbox, SIGNAL("stateChanged(int)"),
                       self.update_ex3)
        change_connect(self.ex4Checkbox, SIGNAL("stateChanged(int)"),
                       self.update_ex4)
        change_connect(self.rotOptCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_rot_opt)
        change_connect(self.tryBothHisTautomersCheckbox,
                       SIGNAL("stateChanged(int)"),
                       self.update_try_both_his_tautomers)
        change_connect(self.softRepDesignCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_soft_rep_design)
        change_connect(self.useElecRepCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_use_elec_rep)
        change_connect(self.norepackDisulfCheckbox,
                       SIGNAL("stateChanged(int)"),
                       self.update_norepack_disulf)
        #signal slot connections for the push buttons
        change_connect(self.okButton, SIGNAL("clicked()"),
                       self.runRosettaFixedBBSim)
        return

    #Protein Display methods

    def show(self):
        """
        Shows the Property Manager.
        """
        #@REVIEW: Why does it create sequence editor here? Also, is it
        #required to be done before the superclass.show call? Similar code
        #found in CompareProteins_PM and some other files --Ninad 2008-10-02

        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.sequenceEditor.hide()

        _superclass.show(self)
        return

    def _addGroupBoxes(self):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox(
            self, title="Rosetta Fixed backbone sequence design")
        self._loadGroupBox1(self._pmGroupBox1)
        return

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        self.numSimSpinBox = PM_SpinBox(pmGroupBox,
                                        labelColumn=0,
                                        label="Number of simulations:",
                                        minimum=1,
                                        maximum=999,
                                        setAsDefault=False,
                                        spanWidth=False)

        self.ex1Checkbox = PM_CheckBox(
            pmGroupBox,
            text="Expand rotamer library for chi1 angle",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex1aroCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Use large chi1 library for aromatic residues",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex2Checkbox = PM_CheckBox(
            pmGroupBox,
            text="Expand rotamer library for chi2 angle",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex2aroOnlyCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Use large chi2 library only for aromatic residues",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex3Checkbox = PM_CheckBox(
            pmGroupBox,
            text="Expand rotamer library for chi3 angle",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex4Checkbox = PM_CheckBox(
            pmGroupBox,
            text="Expand rotamer library for chi4 angle",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.rotOptCheckbox = PM_CheckBox(pmGroupBox,
                                          text="Optimize one-body energy",
                                          state=Qt.Unchecked,
                                          setAsDefault=False,
                                          widgetColumn=0,
                                          spanWidth=True)

        self.tryBothHisTautomersCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Try both histidine tautomers",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.softRepDesignCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Use softer Lennard-Jones repulsive term",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.useElecRepCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Use electrostatic repulsion",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.norepackDisulfCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Don't re-pack disulphide bonds",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.otherCommandLineOptions = PM_TextEdit(
            pmGroupBox, label="Command line options:", spanWidth=True)
        self.otherCommandLineOptions.setFixedHeight(80)

        self.okButton = PM_PushButton(pmGroupBox,
                                      text="Launch Rosetta",
                                      setAsDefault=True,
                                      spanWidth=True)
        return

    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.
        """
        pass

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.
        """
        pass

    def update_ex1(self, state):
        """
        Update the command text edit depending on the state of the update_ex1
        checkbox
        @param state:state of the update_ex1 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex1Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex1 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex1 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex1aro(self, state):
        """
        Update the command text edit depending on the state of the update_ex1aro
        checkbox
        @param state:state of the update_ex1aro checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex1aroCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex1aro '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex1aro ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex2(self, state):
        """
        Update the command text edit depending on the state of the update_ex2
        checkbox
        @param state:state of the update_ex2 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex2Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex2 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex2 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex2aro_only(self, state):
        """
        Update the command text edit depending on the state of the update_ex2aro_only
        checkbox
        @param state:state of the update_ex2aro_only checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex2aroOnlyCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex2aro_only '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex2aro_only ', '')

        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex3(self, state):
        """
        Update the command text edit depending on the state of the update_ex3
        checkbox
        @param state:state of the update_ex3 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex3Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex3 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex3 ', '')

        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex4(self, state):
        """
        Update the command text edit depending on the state of the update_ex4
        checkbox
        @param state:state of the update_ex4 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex4Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex4 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex4 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_rot_opt(self, state):
        """
        Update the command text edit depending on the state of the update_rot_opt
        checkbox
        @param state:state of the update_rot_opt checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.rotOptCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -rot_opt '
        else:
            otherOptionsText = otherOptionsText.replace(' -rot_opt ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_try_both_his_tautomers(self, state):
        """
        Update the command text edit depending on the state of the update_try_both_his_tautomers
        checkbox
        @param state:state of the update_try_both_his_tautomers checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.tryBothHisTautomersCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -try_both_his_tautomers '
        else:
            otherOptionsText = otherOptionsText.replace(
                ' -try_both_his_tautomers ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_soft_rep_design(self, state):
        """
        Update the command text edit depending on the state of the update_soft_rep_design
        checkbox
        @param state:state of the update_soft_rep_design checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.softRepDesignCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -soft_rep_design '
        else:
            otherOptionsText = otherOptionsText.replace(
                ' -soft_rep_design ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_use_elec_rep(self, state):
        """
        Update the command text edit depending on the state of the update_use_elec_rep
        checkbox
        @param state:state of the update_use_elec_rep checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.useElecRepCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -use_electrostatic_repulsion '
        else:
            otherOptionsText = otherOptionsText.replace(
                ' -use_electrostatic_repulsion ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_norepack_disulf(self, state):
        """
        Update the command text edit depending on the state of the update_no_repack
        checkbox
        @param state:state of the update_no_repack checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.norepackDisulfCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -norepack_disulf '
        else:
            otherOptionsText = otherOptionsText.replace(
                ' -norepack_disulf ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def runRosettaFixedBBSim(self):
        """
        Get all the parameters from the PM and run a rosetta simulation.
        """
        proteinChunk = self.win.assy.getSelectedProteinChunk()
        if not proteinChunk:
            msg = "You must select a single protein to run a Rosetta <i>Fixed Backbone</i> simulation."
            self.updateMessage(msg)
            return
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        numSim = self.numSimSpinBox.value()
        argList = [numSim, otherOptionsText, proteinChunk.name]

        from simulation.ROSETTA.rosetta_commandruns import rosettaSetup_CommandRun
        if argList[0] > 0:
            cmdrun = rosettaSetup_CommandRun(
                self.win, argList, "ROSETTA_FIXED_BACKBONE_SEQUENCE_DESIGN")
            cmdrun.run()
        return
Ejemplo n.º 5
0
class PlanePropertyManager(EditCommand_PM):
    """
    The PlanePropertyManager class provides a Property Manager for a
    (reference) Plane.

    """

    # The title that appears in the Property Manager header.
    title = "Plane"
    # The name of this Property Manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    # The relative path to the PNG file that appears in the header
    iconPath = "ui/actions/Insert/Reference Geometry/Plane.png"

    def __init__(self, command):
        """
        Construct the Plane Property Manager.

        @param plane: The plane.
        @type  plane: L{Plane}
        """

        #see self.connect_or_disconnect_signals for comment about this flag
        self.isAlreadyConnected = False
        self.isAlreadyDisconnected = False

        self.gridColor = black
        self.gridXSpacing = 4.0
        self.gridYSpacing = 4.0
        self.gridLineType = 3
        self.displayLabels = False
        self.originLocation = PLANE_ORIGIN_LOWER_LEFT
        self.displayLabelStyle = LABELS_ALONG_ORIGIN

        EditCommand_PM.__init__(self, command)

        # Hide Preview and Restore defaults buttons
        self.hideTopRowButtons(PM_RESTORE_DEFAULTS_BUTTON)

    def _addGroupBoxes(self):
        """
        Add the 1st group box to the Property Manager.
        """
        # Placement Options radio button list to create radio button list.
        # Format: buttonId, buttonText, tooltip
        PLACEMENT_OPTIONS_BUTTON_LIST = [ \
            ( 0, "Parallel to screen",     "Parallel to screen"     ),
            ( 1, "Through selected atoms", "Through selected atoms" ),
            ( 2, "Offset to a plane",      "Offset to a plane"      ),
            ( 3, "Custom",                 "Custom"                 )
        ]

        self.pmPlacementOptions = \
            PM_RadioButtonList( self,
                                title      = "Placement Options",
                                buttonList = PLACEMENT_OPTIONS_BUTTON_LIST,
                                checkedId  = 3 )

        self.pmGroupBox1 = PM_GroupBox(self, title="Parameters")
        self._loadGroupBox1(self.pmGroupBox1)

        #image groupbox
        self.pmGroupBox2 = PM_GroupBox(self, title="Image")
        self._loadGroupBox2(self.pmGroupBox2)

        #grid plane groupbox
        self.pmGroupBox3 = PM_GroupBox(self, title="Grid")
        self._loadGroupBox3(self.pmGroupBox3)

    def _loadGroupBox3(self, pmGroupBox):
        """
        Load widgets in the grid plane group box.

        @param pmGroupBox: The grid  group box in the PM.
        @type  pmGroupBox: L{PM_GroupBox}
        """
        self.gridPlaneCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Show grid",
                         widgetColumn  = 0,
                         setAsDefault = True,
                         spanWidth = True
                         )

        connect_checkbox_with_boolean_pref(self.gridPlaneCheckBox,
                                           PlanePM_showGrid_prefs_key)


        self.gpXSpacingDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "X Spacing:",
                              value         =  4.000,
                              setAsDefault  =  True,
                              minimum       =  1.00,
                              maximum       =  200.0,
                              decimals      =  3,
                              singleStep    =  1.0,
                              spanWidth = False)

        self.gpYSpacingDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Y Spacing:",
                              value         =  4.000,
                              setAsDefault  =  True,
                              minimum       =  1.00,
                              maximum       =  200.0,
                              decimals      =  3,
                              singleStep    =  1.0,
                              spanWidth = False)

        lineTypeChoices = ['Dotted (default)', 'Dashed', 'Solid']

        self.gpLineTypeComboBox = \
            PM_ComboBox( pmGroupBox ,
                         label         =  "Line type:",
                         choices       =  lineTypeChoices,
                         setAsDefault  =  True)

        hhColorList = [
            black, orange, red, magenta, cyan, blue, white, yellow, gray
        ]
        hhColorNames = [
            "Black (default)", "Orange", "Red", "Magenta", "Cyan", "Blue",
            "White", "Yellow", "Other color..."
        ]

        self.gpColorTypeComboBox = \
            PM_ColorComboBox( pmGroupBox,
                              colorList = hhColorList,
                              colorNames = hhColorNames,
                              color = black )

        self.pmGroupBox5 = PM_GroupBox(pmGroupBox)

        self.gpDisplayLabels =\
            PM_CheckBox( self.pmGroupBox5,
                         text         = "Display labels",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True )

        originChoices = [
            'Lower left (default)', 'Upper left', 'Lower right', 'Upper right'
        ]

        self.gpOriginComboBox = \
            PM_ComboBox( self.pmGroupBox5 ,
                         label         =  "Origin:",
                         choices       =  originChoices,
                         setAsDefault  =  True )

        positionChoices = ['Origin axes (default)', 'Plane perimeter']

        self.gpPositionComboBox = \
            PM_ComboBox( self.pmGroupBox5 ,
                         label         =  "Position:",
                         choices       =  positionChoices,
                         setAsDefault  =  True)

        self._showHideGPWidgets()

        if env.prefs[PlanePM_showGridLabels_prefs_key]:
            self.displayLabels = True
            self.gpOriginComboBox.setEnabled(True)
            self.gpPositionComboBox.setEnabled(True)
        else:
            self.displayLabels = False
            self.gpOriginComboBox.setEnabled(False)
            self.gpPositionComboBox.setEnabled(False)

        return

    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot
                          method.
        @type  isConnect: boolean
        """
        #TODO: Fix for bug: When you invoke a temporary mode
        # entering such a temporary mode keeps the signals of
        #PM from the previous mode connected (
        #but while exiting that temporary mode and reentering the
        #previous mode, it actually reconnects the signal! This gives rise to
        #lots  of bugs. This needs more general fix in Temporary mode API.
        # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py

        #UPDATE: (comment copied and modifief from BuildNanotube_PropertyManager.
        #The general problem still remains -- Ninad 2008-06-25

        if isConnect and self.isAlreadyConnected:
            if debug_flags.atom_debug:
                print_compact_stack("warning: attempt to connect widgets"\
                                    "in this PM that are already connected." )
            return

        if not isConnect and self.isAlreadyDisconnected:
            if debug_flags.atom_debug:
                print_compact_stack("warning: attempt to disconnect widgets"\
                                    "in this PM that are already disconnected.")
            return

        self.isAlreadyConnected = isConnect
        self.isAlreadyDisconnected = not isConnect

        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self.pmPlacementOptions.buttonGroup,
                       SIGNAL("buttonClicked(int)"), self.changePlanePlacement)

        change_connect(self.widthDblSpinBox, SIGNAL("valueChanged(double)"),
                       self.change_plane_width)

        change_connect(self.heightDblSpinBox, SIGNAL("valueChanged(double)"),
                       self.change_plane_height)

        change_connect(self.aspectRatioCheckBox, SIGNAL("stateChanged(int)"),
                       self._enableAspectRatioSpinBox)

        #signal slot connection for imageDisplayCheckBox
        change_connect(self.imageDisplayCheckBox, SIGNAL("stateChanged(int)"),
                       self.toggleFileChooserBehavior)

        #signal slot connection for imageDisplayFileChooser
        change_connect(self.imageDisplayFileChooser.lineEdit,
                       SIGNAL("editingFinished()"), self.update_imageFile)

        #signal slot connection for heightfieldDisplayCheckBox
        change_connect(self.heightfieldDisplayCheckBox,
                       SIGNAL("stateChanged(int)"), self.toggleHeightfield)

        #signal slot connection for heightfieldHQDisplayCheckBox
        change_connect(self.heightfieldHQDisplayCheckBox,
                       SIGNAL("stateChanged(int)"), self.toggleHeightfieldHQ)

        #signal slot connection for heightfieldTextureCheckBox
        change_connect(self.heightfieldTextureCheckBox,
                       SIGNAL("stateChanged(int)"), self.toggleTexture)

        #signal slot connection for vScaleSpinBox
        change_connect(self.vScaleSpinBox, SIGNAL("valueChanged(double)"),
                       self.change_vertical_scale)

        change_connect(self.plusNinetyButton, SIGNAL("clicked()"),
                       self.rotate_90)

        change_connect(self.minusNinetyButton, SIGNAL("clicked()"),
                       self.rotate_neg_90)

        change_connect(self.flipButton, SIGNAL("clicked()"), self.flip_image)

        change_connect(self.mirrorButton, SIGNAL("clicked()"),
                       self.mirror_image)

        change_connect(self.gridPlaneCheckBox, SIGNAL("stateChanged(int)"),
                       self.displayGridPlane)

        change_connect(self.gpXSpacingDoubleSpinBox,
                       SIGNAL("valueChanged(double)"), self.changeXSpacingInGP)

        change_connect(self.gpYSpacingDoubleSpinBox,
                       SIGNAL("valueChanged(double)"), self.changeYSpacingInGP)

        change_connect(self.gpLineTypeComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.changeLineTypeInGP)

        change_connect(self.gpColorTypeComboBox, SIGNAL("editingFinished()"),
                       self.changeColorTypeInGP)

        change_connect(self.gpDisplayLabels, SIGNAL("stateChanged(int)"),
                       self.displayLabelsInGP)

        change_connect(self.gpOriginComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.changeOriginInGP)

        change_connect(self.gpPositionComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.changePositionInGP)

        self._connect_checkboxes_to_global_prefs_keys()

        return

    def _connect_checkboxes_to_global_prefs_keys(self):
        """
        """
        connect_checkbox_with_boolean_pref(self.gridPlaneCheckBox,
                                           PlanePM_showGrid_prefs_key)

        connect_checkbox_with_boolean_pref(self.gpDisplayLabels,
                                           PlanePM_showGridLabels_prefs_key)

    def changePositionInGP(self, idx):
        """
        Change Display of origin Labels (choices are along origin edges or along
        the plane perimeter.
        @param idx: Current index of the change grid label position combo box
        @type idx: int
        """
        if idx == 0:
            self.displayLabelStyle = LABELS_ALONG_ORIGIN
        elif idx == 1:
            self.displayLabelStyle = LABELS_ALONG_PLANE_EDGES
        else:
            print "Invalid index", idx
        return

    def changeOriginInGP(self, idx):
        """
        Change Display of origin Labels based on the location of the origin
        @param idx: Current index of the change origin position combo box
        @type idx: int
        """
        if idx == 0:
            self.originLocation = PLANE_ORIGIN_LOWER_LEFT
        elif idx == 1:
            self.originLocation = PLANE_ORIGIN_UPPER_LEFT
        elif idx == 2:
            self.originLocation = PLANE_ORIGIN_LOWER_RIGHT
        elif idx == 3:
            self.originLocation = PLANE_ORIGIN_UPPER_RIGHT
        else:
            print "Invalid index", idx
        return

    def displayLabelsInGP(self, state):
        """
        Choose to show or hide grid labels
        @param state: State of the Display Label Checkbox
        @type state: boolean
        """
        if env.prefs[PlanePM_showGridLabels_prefs_key]:
            self.gpOriginComboBox.setEnabled(True)
            self.gpPositionComboBox.setEnabled(True)
            self.displayLabels = True
            self.originLocation = PLANE_ORIGIN_LOWER_LEFT
            self.displayLabelStyle = LABELS_ALONG_ORIGIN
        else:
            self.gpOriginComboBox.setEnabled(False)
            self.gpPositionComboBox.setEnabled(False)
            self.displayLabels = False
        return

    def changeColorTypeInGP(self):
        """
        Change Color of grid
        """
        self.gridColor = self.gpColorTypeComboBox.getColor()
        return

    def changeLineTypeInGP(self, idx):
        """
        Change line type in grid
        @param idx: Current index of the Line type combo box
        @type idx: int
        """
        #line_type for actually drawing the grid is: 0=None, 1=Solid, 2=Dashed" or 3=Dotted
        if idx == 0:
            self.gridLineType = 3
        if idx == 1:
            self.gridLineType = 2
        if idx == 2:
            self.gridLineType = 1
        return

    def changeYSpacingInGP(self, val):
        """
        Change Y spacing on the grid
        @param val:value of Y spacing
        @type val: double
        """
        self.gridYSpacing = float(val)
        return

    def changeXSpacingInGP(self, val):
        """
        Change X spacing on the grid
        @param val:value of X spacing
        @type val: double
        """
        self.gridXSpacing = float(val)
        return

    def displayGridPlane(self, state):
        """
        Display or hide grid based on the state of the checkbox
        @param state: State of the Display Label Checkbox
        @type state: boolean
        """
        self._showHideGPWidgets()
        if self.gridPlaneCheckBox.isChecked():
            env.prefs[PlanePM_showGrid_prefs_key] = True
            self._makeGridPlane()
        else:
            env.prefs[PlanePM_showGrid_prefs_key] = False

        return

    def _makeGridPlane(self):
        """
        Show grid on the plane
        """
        #get all the grid related values in here
        self.gridXSpacing = float(self.gpXSpacingDoubleSpinBox.value())
        self.gridYSpacing = float(self.gpYSpacingDoubleSpinBox.value())

        #line_type for actually drawing the grid is: 0=None, 1=Solid, 2=Dashed" or 3=Dotted
        idx = self.gpLineTypeComboBox.currentIndex()
        self.changeLineTypeInGP(idx)
        self.gridColor = self.gpColorTypeComboBox.getColor()

        return

    def _showHideGPWidgets(self):
        """
        Enable Disable grid related widgets based on the state of the show grid
        checkbox.
        """
        if self.gridPlaneCheckBox.isChecked():
            self.gpXSpacingDoubleSpinBox.setEnabled(True)
            self.gpYSpacingDoubleSpinBox.setEnabled(True)
            self.gpLineTypeComboBox.setEnabled(True)
            self.gpColorTypeComboBox.setEnabled(True)
            self.gpDisplayLabels.setEnabled(True)
        else:
            self.gpXSpacingDoubleSpinBox.setEnabled(False)
            self.gpXSpacingDoubleSpinBox.setEnabled(False)
            self.gpYSpacingDoubleSpinBox.setEnabled(False)
            self.gpLineTypeComboBox.setEnabled(False)
            self.gpColorTypeComboBox.setEnabled(False)
            self.gpDisplayLabels.setEnabled(False)
        return

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in the image group box.

        @param pmGroupBox: The image group box in the PM.
        @type  pmGroupBox: L{PM_GroupBox}
        """
        self.imageDisplayCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Display image",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.imageDisplayFileChooser = \
            PM_FileChooser(pmGroupBox,
                           label     = 'Image file:',
                           text      = '' ,
                           spanWidth = True,
                           filter    = "PNG (*.png);;"\
                           "All Files (*.*)"
                           )
        self.imageDisplayFileChooser.setEnabled(False)
        # add change image properties button

        BUTTON_LIST = [
            ("QToolButton", 1, "+90",
             "ui/actions/Properties Manager/RotateImage+90.png", "+90", "", 0),
            ("QToolButton", 2, "-90",
             "ui/actions/Properties Manager/RotateImage-90.png", "-90", "", 1),
            ("QToolButton", 3, "FLIP",
             "ui/actions/Properties Manager/FlipImageVertical.png", "Flip", "",
             2),
            ("QToolButton", 4, "MIRROR",
             "ui/actions/Properties Manager/FlipImageHorizontal.png", "Mirror",
             "", 3)
        ]

        #image change button groupbox
        self.pmGroupBox2 = PM_GroupBox(pmGroupBox, title="Modify Image")

        self.imageChangeButtonGroup = \
            PM_ToolButtonRow( self.pmGroupBox2,
                              title        = "",
                              buttonList   = BUTTON_LIST,
                              spanWidth    = True,
                              isAutoRaise  = False,
                              isCheckable  = False,
                              setAsDefault = True,
                              )

        self.imageChangeButtonGroup.buttonGroup.setExclusive(False)

        self.plusNinetyButton = self.imageChangeButtonGroup.getButtonById(1)
        self.minusNinetyButton = self.imageChangeButtonGroup.getButtonById(2)
        self.flipButton = self.imageChangeButtonGroup.getButtonById(3)
        self.mirrorButton = self.imageChangeButtonGroup.getButtonById(4)

        # buttons enabled when a valid image is loaded
        self.mirrorButton.setEnabled(False)
        self.plusNinetyButton.setEnabled(False)
        self.minusNinetyButton.setEnabled(False)
        self.flipButton.setEnabled(False)

        self.heightfieldDisplayCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Create 3D relief",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.heightfieldHQDisplayCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "High quality",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.heightfieldTextureCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Use texture",
                         widgetColumn  = 0,
                         state        = Qt.Checked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.vScaleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label        = " Vertical scale:",
                             value        = 1.0,
                             setAsDefault = True,
                             minimum      = -1000.0, # -1000 A
                             maximum      =  1000.0, # 1000 A
                             singleStep   = 0.1,
                             decimals     = 1,
                             suffix       = ' Angstroms')

        self.heightfieldDisplayCheckBox.setEnabled(False)
        self.heightfieldHQDisplayCheckBox.setEnabled(False)
        self.heightfieldTextureCheckBox.setEnabled(False)
        self.vScaleSpinBox.setEnabled(False)

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in 1st group box.

        @param pmGroupBox: The 1st group box in the PM.
        @type  pmGroupBox: L{PM_GroupBox}
        """

        self.widthDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label        = "Width:",
                             value        = 16.0,
                             setAsDefault = True,
                             minimum      = 1.0,
                             maximum      = 10000.0, # 1000 nm
                             singleStep   = 1.0,
                             decimals     = 1,
                             suffix       = ' Angstroms')



        self.heightDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label        =" Height:",
                             value        = 16.0,
                             setAsDefault = True,
                             minimum      = 1.0,
                             maximum      = 10000.0, # 1000 nm
                             singleStep   = 1.0,
                             decimals     = 1,
                             suffix       = ' Angstroms')



        self.aspectRatioCheckBox = \
            PM_CheckBox(pmGroupBox,
                        text         = 'Maintain Aspect Ratio of:' ,
                        widgetColumn = 1,
                        state        = Qt.Unchecked
                        )


        self.aspectRatioSpinBox = \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "",
                              value         =  1.0,
                              setAsDefault  =  True,
                              minimum       =  0.1,
                              maximum       =  10.0,
                              singleStep    =  0.1,
                              decimals      =  2,
                              suffix        =  " to 1.00")

        if self.aspectRatioCheckBox.isChecked():
            self.aspectRatioSpinBox.setEnabled(True)
        else:
            self.aspectRatioSpinBox.setEnabled(False)

    def _addWhatsThisText(self):
        """
        What's This text for some of the widgets in this Property Manager.

        @note: Many PM widgets are still missing their "What's This" text.
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_PlanePropertyManager
        whatsThis_PlanePropertyManager(self)

    def toggleFileChooserBehavior(self, checked):
        """
        Enables FileChooser and displays image when checkbox is checked otherwise
        not
        """
        self.imageDisplayFileChooser.lineEdit.emit(SIGNAL("editingFinished()"))
        if checked == Qt.Checked:
            self.imageDisplayFileChooser.setEnabled(True)
        elif checked == Qt.Unchecked:
            self.imageDisplayFileChooser.setEnabled(False)
            # if an image is already displayed, that's need to be hidden as well
        else:
            pass

        self.command.struct.glpane.gl_update()

    def toggleHeightfield(self, checked):
        """
        Enables 3D relief drawing mode.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.display_heightfield = checked
            if checked:
                self.heightfieldHQDisplayCheckBox.setEnabled(True)
                self.heightfieldTextureCheckBox.setEnabled(True)
                self.vScaleSpinBox.setEnabled(True)
                plane.computeHeightfield()
            else:
                self.heightfieldHQDisplayCheckBox.setEnabled(False)
                self.heightfieldTextureCheckBox.setEnabled(False)
                self.vScaleSpinBox.setEnabled(False)
                plane.heightfield = None
            plane.glpane.gl_update()

    def toggleHeightfieldHQ(self, checked):
        """
        Enables high quality rendering in 3D relief mode.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.heightfield_hq = checked
            plane.computeHeightfield()
            plane.glpane.gl_update()

    def toggleTexture(self, checked):
        """
        Enables texturing in 3D relief mode.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.heightfield_use_texture = checked
            # It is not necessary to re-compute the heightfield coordinates
            # at this point, they are re-computed whenever the "3D relief image"
            # checkbox is set.
            plane.glpane.gl_update()

    def update_spinboxes(self):
        """
        Update the width and height spinboxes.
        @see: Plane.resizeGeometry()
        This typically gets called when the plane is resized from the
        3D workspace (which marks assy as modified) .So, update the spinboxes
        that represent the Plane's width and height, but do no emit 'valueChanged'
        signal when the spinbox value changes.

        @see: Plane.resizeGeometry()
        @see: self._update_UI_do_updates()
        @see: Plane_EditCommand.command_update_internal_state()
        """
        # blockSignals = True make sure that spinbox.valueChanged()
        # signal is not emitted after calling spinbox.setValue().  This is done
        #because the spinbox valu changes as a result of resizing the plane
        #from the 3D workspace.
        if self.command.hasValidStructure():
            self.heightDblSpinBox.setValue(self.command.struct.height,
                                           blockSignals=True)
            self.widthDblSpinBox.setValue(self.command.struct.width,
                                          blockSignals=True)

    def update_imageFile(self):
        """
        Loads image file if path is valid
        """

        # Update buttons and checkboxes.
        self.mirrorButton.setEnabled(False)
        self.plusNinetyButton.setEnabled(False)
        self.minusNinetyButton.setEnabled(False)
        self.flipButton.setEnabled(False)
        self.heightfieldDisplayCheckBox.setEnabled(False)
        self.heightfieldHQDisplayCheckBox.setEnabled(False)
        self.heightfieldTextureCheckBox.setEnabled(False)
        self.vScaleSpinBox.setEnabled(False)

        plane = self.command.struct

        # Delete current image and heightfield
        plane.deleteImage()
        plane.heightfield = None
        plane.display_image = self.imageDisplayCheckBox.isChecked()

        if plane.display_image:
            imageFile = str(self.imageDisplayFileChooser.lineEdit.text())

            from model.Plane import checkIfValidImagePath
            validPath = checkIfValidImagePath(imageFile)

            if validPath:
                from PIL import Image

                # Load image from file
                plane.image = Image.open(imageFile)
                plane.loadImage(imageFile)

                # Compute the relief image
                plane.computeHeightfield()

                if plane.image:
                    self.mirrorButton.setEnabled(True)
                    self.plusNinetyButton.setEnabled(True)
                    self.minusNinetyButton.setEnabled(True)
                    self.flipButton.setEnabled(True)
                    self.heightfieldDisplayCheckBox.setEnabled(True)
                    if plane.display_heightfield:
                        self.heightfieldHQDisplayCheckBox.setEnabled(True)
                        self.heightfieldTextureCheckBox.setEnabled(True)
                        self.vScaleSpinBox.setEnabled(True)

    def show(self):
        """
        Show the Plane Property Manager.
        """
        EditCommand_PM.show(self)
        #It turns out that if updateCosmeticProps is called before
        #EditCommand_PM.show, the 'preview' properties are not updated
        #when you are editing an existing plane. Don't know the cause at this
        #time, issue is trivial. So calling it in the end -- Ninad 2007-10-03

        if self.command.struct:

            plane = self.command.struct
            plane.updateCosmeticProps(previewing=True)
            if plane.imagePath:
                self.imageDisplayFileChooser.setText(plane.imagePath)
            self.imageDisplayCheckBox.setChecked(plane.display_image)

            #Make sure that the plane placement option is always set to
            #'Custom' when the Plane PM is shown. This makes sure that bugs like
            #2949 won't occur. Let the user change the plane placement option
            #explicitely
            button = self.pmPlacementOptions.getButtonById(3)
            button.setChecked(True)

    def setParameters(self, params):
        """
        """
        width, height, gridColor, gridLineType, \
             gridXSpacing, gridYSpacing, originLocation, \
             displayLabelStyle = params

        # blockSignals = True  flag makes sure that the
        # spinbox.valueChanged()
        # signal is not emitted after calling spinbox.setValue().
        self.widthDblSpinBox.setValue(width, blockSignals=True)
        self.heightDblSpinBox.setValue(height, blockSignals=True)
        self.win.glpane.gl_update()

        self.gpColorTypeComboBox.setColor(gridColor)
        self.gridLineType = gridLineType

        self.gpXSpacingDoubleSpinBox.setValue(gridXSpacing)
        self.gpYSpacingDoubleSpinBox.setValue(gridYSpacing)

        self.gpOriginComboBox.setCurrentIndex(originLocation)
        self.gpPositionComboBox.setCurrentIndex(displayLabelStyle)

    def getCurrrentDisplayParams(self):
        """
        Returns a tuple containing current display parameters such as current
        image path and grid display params.
        @see: Plane_EditCommand.command_update_internal_state() which uses this
        to decide whether to modify the structure (e.g. because of change in the
        image path or display parameters.)
        """
        imagePath = self.imageDisplayFileChooser.text
        gridColor = self.gpColorTypeComboBox.getColor()

        return (imagePath, gridColor, self.gridLineType, self.gridXSpacing,
                self.gridYSpacing, self.originLocation, self.displayLabelStyle)

    def getParameters(self):
        """
        """
        width = self.widthDblSpinBox.value()
        height = self.heightDblSpinBox.value()
        gridColor = self.gpColorTypeComboBox.getColor()

        params = (width, height, gridColor, self.gridLineType,
                  self.gridXSpacing, self.gridYSpacing, self.originLocation,
                  self.displayLabelStyle)

        return params

    def change_plane_width(self, newWidth):
        """
        Slot for width spinbox in the Property Manager.

        @param newWidth: width in Angstroms.
        @type  newWidth: float
        """
        if self.aspectRatioCheckBox.isChecked():
            self.command.struct.width = newWidth
            self.command.struct.height  =  self.command.struct.width / \
                self.aspectRatioSpinBox.value()
            self.update_spinboxes()
        else:
            self.change_plane_size()
        self._updateAspectRatio()

    def change_plane_height(self, newHeight):
        """
        Slot for height spinbox in the Property Manager.

        @param newHeight: height in Angstroms.
        @type  newHeight: float
        """
        if self.aspectRatioCheckBox.isChecked():
            self.command.struct.height = newHeight
            self.command.struct.width   =  self.command.struct.height * \
                self.aspectRatioSpinBox.value()
            self.update_spinboxes()
        else:
            self.change_plane_size()
        self._updateAspectRatio()

    def change_plane_size(self, gl_update=True):
        """
        Slot to change the Plane's width and height.

        @param gl_update: Forces an update of the glpane.
        @type  gl_update: bool
        """
        self.command.struct.width = self.widthDblSpinBox.value()
        self.command.struct.height = self.heightDblSpinBox.value()
        if gl_update:
            self.command.struct.glpane.gl_update()

    def change_vertical_scale(self, scale):
        """
        Changes vertical scaling of the heightfield.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.heightfield_scale = scale
            plane.computeHeightfield()
            plane.glpane.gl_update()

    def changePlanePlacement(self, buttonId):
        """
        Slot to change the placement of the plane depending upon the
        option checked in the "Placement Options" group box of the PM.

        @param buttonId: The button id of the selected radio button (option).
        @type  buttonId: int
        """

        if buttonId == 0:
            msg = "Create a Plane parallel to the screen. "\
                "With <b>Parallel to Screen</b> plane placement option, the "\
                "center of the plane is always (0,0,0)"
            self.updateMessage(msg)
            self.command.placePlaneParallelToScreen()
        elif buttonId == 1:
            msg = "Create a Plane with center coinciding with the common center "\
                "of <b> 3 or more selected atoms </b>. If exactly 3 atoms are "\
                "selected, the Plane will pass through those atoms."
            self.updateMessage(msg)
            self.command.placePlaneThroughAtoms()
            if self.command.logMessage:
                env.history.message(self.command.logMessage)
        elif buttonId == 2:
            msg = "Create a Plane at an <b>offset</b> to the selected plane "\
                "indicated by the direction arrow. "\
                "you can click on the direction arrow to reverse its direction."
            self.updateMessage(msg)
            self.command.placePlaneOffsetToAnother()
            if self.command.logMessage:
                env.history.message(self.command.logMessage)
        elif buttonId == 3:
            #'Custom' plane placement. Do nothing (only update message box)
            # Fixes bug 2439
            msg = "Create a plane with a <b>Custom</b> plane placement. "\
                "The plane is placed parallel to the screen, with "\
                "center at (0, 0, 0). User can then modify the plane placement."
            self.updateMessage(msg)

    def _enableAspectRatioSpinBox(self, enable):
        """
        Slot for "Maintain Aspect Ratio" checkbox which enables or disables
        the Aspect Ratio spin box.

        @param enable: True = enable, False = disable.
        @type  enable: bool
        """

        self.aspectRatioSpinBox.setEnabled(enable)

    def _updateAspectRatio(self):
        """
        Updates the Aspect Ratio spin box based on the current width and height.
        """
        aspectRatio = self.command.struct.width / self.command.struct.height
        self.aspectRatioSpinBox.setValue(aspectRatio)

    def _update_UI_do_updates(self):
        """
        Overrides superclass method.
        @see: Command_PropertyManager._update_UI_do_updates() for documentation.

        @see: Plane.resizeGeometry()
        @see: self.update_spinboxes()
        @see: Plane_EditCommand.command_update_internal_state()
        """
        #This typically gets called when the plane is resized from the
        #3D workspace (which marks assy as modified) . So, update the spinboxes
        #that represent the Plane's width and height.
        self.update_spinboxes()

    def update_props_if_needed_before_closing(self):
        """
        This updates some cosmetic properties of the Plane (e.g. fill color,
        border color, etc.) before closing the Property Manager.
        """

        # Example: The Plane Property Manager is open and the user is
        # 'previewing' the plane. Now the user clicks on "Build > Atoms"
        # to invoke the next command (without clicking "Done").
        # This calls openPropertyManager() which replaces the current PM
        # with the Build Atoms PM.  Thus, it creates and inserts the Plane
        # that was being previewed. Before the plane is permanently inserted
        # into the part, it needs to change some of its cosmetic properties
        # (e.g. fill color, border color, etc.) which distinguishes it as
        # a new plane in the part. This function changes those properties.
        # ninad 2007-06-13

        #called in updatePropertyManager in MWsemeantics.py --(Partwindow class)

        EditCommand_PM.update_props_if_needed_before_closing(self)

        #Don't draw the direction arrow when the object is finalized.
        if self.command.struct and \
           self.command.struct.offsetParentGeometry:

            dirArrow = self.command.struct.offsetParentGeometry.directionArrow
            dirArrow.setDrawRequested(False)

    def updateMessage(self, msg=''):
        """
        Updates the message box with an informative message
        @param message: Message to be displayed in the Message groupbox of
                        the property manager
        @type  message: string
        """
        self.MessageGroupBox.insertHtmlMessage(msg,
                                               setAsDefault=False,
                                               minLines=5)

    def rotate_90(self):
        """
        Rotate the image clockwise.
        """
        if self.command.hasValidStructure():
            self.command.struct.rotateImage(0)
        return

    def rotate_neg_90(self):
        """
        Rotate the image counterclockwise.
        """
        if self.command.hasValidStructure():
            self.command.struct.rotateImage(1)
        return

    def flip_image(self):
        """
        Flip the image horizontally.
        """
        if self.command.hasValidStructure():
            self.command.struct.mirrorImage(1)
        return

    def mirror_image(self):
        """
        Flip the image vertically.
        """
        if self.command.hasValidStructure():
            self.command.struct.mirrorImage(0)
        return
class EditResidues_PropertyManager(Command_PropertyManager):
    """
    The ProteinDisplayStyle_PropertyManager class provides a Property Manager
    for the B{Display Style} command on the flyout toolbar in the
    Build > Protein mode.

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title         =  "Edit Residues"
    pmName        =  title
    iconPath      =  "ui/actions/Command Toolbar/BuildProtein/Residues.png"

    rosetta_all_set =    "PGAVILMFWYCSTNQDEHKR"
    rosetta_polar_set =  "___________STNQDEHKR"
    rosetta_apolar_set = "PGAVILMFWYC_________"


    def __init__( self, command ):
        """
        Constructor for the property manager.
        """

        self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key]

        _superclass.__init__(self, command)

        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        self.editingItem = False
        return

    def connect_or_disconnect_signals(self, isConnect = True):

        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self.applyAnyPushButton,
                         SIGNAL("clicked()"),
                         self._applyAny)

        change_connect(self.applySamePushButton,
                         SIGNAL("clicked()"),
                         self._applySame)

        change_connect(self.applyLockedPushButton,
                         SIGNAL("clicked()"),
                         self._applyLocked)

        change_connect(self.applyPolarPushButton,
                         SIGNAL("clicked()"),
                         self._applyPolar)

        change_connect(self.applyApolarPushButton,
                         SIGNAL("clicked()"),
                         self._applyApolar)

        change_connect(self.selectAllPushButton,
                         SIGNAL("clicked()"),
                         self._selectAll)

        change_connect(self.selectNonePushButton,
                         SIGNAL("clicked()"),
                         self._selectNone)

        change_connect(self.selectInvertPushButton,
                         SIGNAL("clicked()"),
                         self._invertSelection)

        change_connect(self.applyDescriptorPushButton,
                         SIGNAL("clicked()"),
                         self._applyDescriptor)

        change_connect(self.removeDescriptorPushButton,
                         SIGNAL("clicked()"),
                         self._removeDescriptor)

        change_connect(self.sequenceTable,
                         SIGNAL("cellClicked(int, int)"),
                         self._sequenceTableCellChanged)

        change_connect(self.sequenceTable,
                         SIGNAL("itemChanged(QTableWidgetItem*)"),
                         self._sequenceTableItemChanged)

        change_connect(self.descriptorsTable,
                         SIGNAL("itemChanged(QTableWidgetItem*)"),
                         self._descriptorsTableItemChanged)

        change_connect(self.newDescriptorPushButton,
                         SIGNAL("clicked()"),
                         self._addNewDescriptor)
        change_connect(self.showSequencePushButton,
                       SIGNAL("clicked()"),
                       self._showSeqEditor)
        return

    def _showSeqEditor(self):
        """
        Shows sequence editor
        """
        if self.showSequencePushButton.isEnabled():
            self.sequenceEditor.show()
        return

    def show(self):
        """
        Shows the Property Manager. Extends superclass method.
        """
        env.history.statusbar_msg("")
        #Urmi 20080728: Set the current protein and this will be used for accessing
        #various properties of this protein
        self.set_current_protein()
        if self.current_protein:
            msg = "Editing structure <b>%s</b>." % self.current_protein.name
            self.showSequencePushButton.setEnabled(True)
        else:
            msg = "Select a single structure to edit."
            self.showSequencePushButton.setEnabled(False)
        self.sequenceEditor.hide()

        _superclass.show(self)

        self._fillSequenceTable()
        self.updateMessage(msg)

        return

    def set_current_protein(self):
        """
        Set the current protein for which all the properties are displayed to the
        one chosen in the build protein combo box
        """
        self.current_protein = self.win.assy.getSelectedProteinChunk()
        return

    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """

        if sys.platform == "darwin":
            # Workaround for table font size difference between Mac/Win
            self.labelfont = QFont("Helvetica", 12)
            self.descriptorfont = QFont("Courier New", 12)
        else:
            self.labelfont = QFont("Helvetica", 9)
            self.descriptorfont = QFont("Courier New", 9)

        self._pmGroupBox1 = PM_GroupBox( self,
                                         title = "Descriptors")
        self._loadGroupBox1( self._pmGroupBox1 )

        self._pmGroupBox2 = PM_GroupBox( self,
                                         title = "Sequence")
        self._loadGroupBox2( self._pmGroupBox2 )


    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in the first group box.
        """

        self.headerdata_desc = ['Name', 'Descriptor']

        self.set_names = ["Any", "Same", "Locked", "Apolar", "Polar"]
        self.rosetta_set_names = ["ALLAA", "NATAA", "NATRO", "APOLA", "POLAR"]
        self.descriptor_list = ["PGAVILMFWYCSTNQDEHKR",
                                "____________________",
                                "____________________",
                                "PGAVILMFWYC_________",
                                "___________STNQDEHKR"]

        self.applyAnyPushButton = PM_PushButton( pmGroupBox,
            text       =  "ALLAA",
            setAsDefault  =  True)

        self.applySamePushButton = PM_PushButton( pmGroupBox,
            text       =  "NATAA",
            setAsDefault  =  True)

        self.applyLockedPushButton = PM_PushButton( pmGroupBox,
            text       =  "NATRO",
            setAsDefault  =  True)

        self.applyPolarPushButton = PM_PushButton( pmGroupBox,
            text       =  "APOLA",
            setAsDefault  =  True)

        self.applyApolarPushButton = PM_PushButton( pmGroupBox,
            text       =  "POLAR",
            setAsDefault  =  True)

        #self.applyBackrubPushButton = PM_PushButton( pmGroupBox,
        #    text       =  "BACKRUB",
        #    setAsDefault  =  True)

        self.applyAnyPushButton.setFixedHeight(25)
        self.applyAnyPushButton.setFixedWidth(60)

        self.applySamePushButton.setFixedHeight(25)
        self.applySamePushButton.setFixedWidth(60)

        self.applyLockedPushButton.setFixedHeight(25)
        self.applyLockedPushButton.setFixedWidth(60)

        self.applyPolarPushButton.setFixedHeight(25)
        self.applyPolarPushButton.setFixedWidth(60)

        self.applyApolarPushButton.setFixedHeight(25)
        self.applyApolarPushButton.setFixedWidth(60)

        applyButtonList = [
            ('PM_PushButton', self.applyAnyPushButton, 0, 0),
            ('PM_PushButton', self.applySamePushButton, 1, 0),
            ('PM_PushButton', self.applyLockedPushButton, 2, 0),
            ('PM_PushButton', self.applyPolarPushButton, 3, 0),
            ('PM_PushButton', self.applyApolarPushButton, 4, 0)  ]

        self.applyButtonGrid = PM_WidgetGrid( pmGroupBox,
                                              label = "Apply standard set",
                                              widgetList = applyButtonList)

        self.descriptorsTable = PM_TableWidget( pmGroupBox,
                                                label = "Custom descriptors")

        self.descriptorsTable.setFixedHeight(100)
        self.descriptorsTable.setRowCount(0)
        self.descriptorsTable.setColumnCount(2)
        self.descriptorsTable.verticalHeader().setVisible(False)
        self.descriptorsTable.horizontalHeader().setVisible(True)
        self.descriptorsTable.setGridStyle(Qt.NoPen)
        self.descriptorsTable.setHorizontalHeaderLabels(self.headerdata_desc)

        self._updateSetLists()

        self._fillDescriptorsTable()

        self.descriptorsTable.resizeColumnsToContents()

        self.newDescriptorPushButton = PM_PushButton( pmGroupBox,
            text         =  "New",
            setAsDefault  =  True)

        self.newDescriptorPushButton.setFixedHeight(25)

        self.removeDescriptorPushButton = PM_PushButton( pmGroupBox,
            text         =  "Remove",
            setAsDefault  =  True)

        self.removeDescriptorPushButton.setFixedHeight(25)

        self.applyDescriptorPushButton = PM_PushButton( pmGroupBox,
            text         =  "Apply",
            setAsDefault  =  True)

        self.applyDescriptorPushButton.setFixedHeight(25)

        addDescriptorButtonList = [('PM_PushButton', self.newDescriptorPushButton, 0, 0),
            ('PM_PushButton', self.removeDescriptorPushButton, 1, 0),
            ('PM_PushButton', self.applyDescriptorPushButton, 2, 0) ]

        self.addDescriptorGrid = PM_WidgetGrid( pmGroupBox,
                                              alignment = "Center",
                                              widgetList = addDescriptorButtonList)

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in the second group box.
        """

        self.headerdata_seq = ['', 'ID', 'Set', 'BR', 'Descriptor']

        self.recenterViewCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Re-center view on selected residue",
                         setAsDefault  =  True,
                         widgetColumn  = 0,
                         state         = Qt.Unchecked)

        self.selectAllPushButton = PM_PushButton( pmGroupBox,
            text         =  "All",
            setAsDefault  =  True)

        self.selectAllPushButton.setFixedHeight(25)

        self.selectNonePushButton = PM_PushButton( pmGroupBox,
            text       =  "None",
            setAsDefault  =  True)

        self.selectNonePushButton.setFixedHeight(25)

        self.selectInvertPushButton = PM_PushButton( pmGroupBox,
            text       =  "Invert",
            setAsDefault  =  True)

        self.selectInvertPushButton.setFixedHeight(25)

        buttonList = [ ('PM_PushButton', self.selectAllPushButton, 0, 0),
                       ('PM_PushButton', self.selectNonePushButton, 1, 0),
                       ('PM_PushButton', self.selectInvertPushButton, 2, 0)]

        self.buttonGrid = PM_WidgetGrid( pmGroupBox,
                                         widgetList = buttonList)


        self.sequenceTable = PM_TableWidget( pmGroupBox)
        #self.sequenceTable.setModel(self.tableModel)
        self.sequenceTable.resizeColumnsToContents()
        self.sequenceTable.verticalHeader().setVisible(False)
        #self.sequenceTable.setRowCount(0)
        self.sequenceTable.setColumnCount(5)

        self.checkbox = QCheckBox()


        self.sequenceTable.setFixedHeight(345)

        self.sequenceTable.setGridStyle(Qt.NoPen)

        self.sequenceTable.setHorizontalHeaderLabels(self.headerdata_seq)
        ###self._fillSequenceTable()
        self.showSequencePushButton = PM_PushButton( pmGroupBox,
            text       =  "Show Sequence",
            setAsDefault  =  True,
            spanWidth = True)


    def _addWhatsThisText( self ):
        #from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditResidues_PropertyManager
        #WhatsThis_EditResidues_PropertyManager(self)
        pass

    def _addToolTipText(self):
        #from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager
        #ToolTip_EditProteinDisplayStyle_PropertyManager(self)
        pass

    def _fillSequenceTable(self):
        """
        Fills in the sequence table.
        """

        if not self.current_protein:
            return
        else:
            currentProteinChunk = self.current_protein

        self.editingItem = True

        aa_list = currentProteinChunk.protein.get_amino_acids()
        aa_list_len = len(aa_list)
        self.sequenceTable.setRowCount(aa_list_len)
        for index in range(aa_list_len):
            # Selection checkbox column
            item_widget = QTableWidgetItem("")
            item_widget.setFont(self.labelfont)
            item_widget.setCheckState(Qt.Checked)
            item_widget.setTextAlignment(Qt.AlignLeft)
            item_widget.setSizeHint(QSize(20,12))
            item_widget.setFlags(Qt.ItemIsSelectable |
                                 Qt.ItemIsEnabled |
                                 Qt.ItemIsUserCheckable)
            self.sequenceTable.setItem(index, 0, item_widget)

            # Amino acid index column
            item_widget = QTableWidgetItem(str(index+1))
            item_widget.setFont(self.labelfont)
            item_widget.setFlags(
                Qt.ItemIsSelectable |
                Qt.ItemIsEnabled)
            item_widget.setTextAlignment(Qt.AlignCenter)
            self.sequenceTable.setItem(index, 1, item_widget)

            # Mutation descriptor name column
            aa = self._get_aa_for_index(index)
            item_widget = QTableWidgetItem(self._get_descriptor_name(aa))
            item_widget.setFont(self.labelfont)
            item_widget.setFlags(Qt.ItemIsSelectable |
                                 Qt.ItemIsEnabled)
            item_widget.setTextAlignment(Qt.AlignCenter)
            self.sequenceTable.setItem(index, 2, item_widget)

            # Backrub checkbox column
            item_widget = QTableWidgetItem("")
            item_widget.setFont(self.labelfont)
            if aa.get_backrub_mode():
                item_widget.setCheckState(Qt.Checked)
            else:
                item_widget.setCheckState(Qt.Unchecked)
            item_widget.setTextAlignment(Qt.AlignLeft)
            item_widget.setSizeHint(QSize(20,12))
            item_widget.setFlags(Qt.ItemIsSelectable |
                                 Qt.ItemIsEnabled |
                                 Qt.ItemIsUserCheckable)
            self.sequenceTable.setItem(index, 3, item_widget)

            # Mutation descriptor column
            aa_string = self._get_mutation_descriptor(aa)
            item_widget = QTableWidgetItem(aa_string)
            item_widget.setFont(self.descriptorfont)
            self.sequenceTable.setItem(index, 4, item_widget)

            self.sequenceTable.setRowHeight(index, 16)

        self.editingItem = False

        self.sequenceTable.resizeColumnsToContents()

        self.sequenceTable.setColumnWidth(0, 35)
        self.sequenceTable.setColumnWidth(2, 80)
        self.sequenceTable.setColumnWidth(3, 35)
        return

    def _fillDescriptorsTable(self):
        """
        Fills in the descriptors table from descriptors user pref.
        """
        dstr = env.prefs[proteinCustomDescriptors_prefs_key].split(":")
        for i in range(len(dstr) / 2):
            self._addNewDescriptorTableRow(dstr[2*i], dstr[2*i+1])

    def _selectAll(self):
        """
        Select all rows in the sequence table.
        """
        for row in range(self.sequenceTable.rowCount()):
            self.sequenceTable.item(row, 0).setCheckState(Qt.Checked)

    def _selectNone(self):
        """
        Unselect all rows in the sequence table.
        """
        for row in range(self.sequenceTable.rowCount()):
            self.sequenceTable.item(row, 0).setCheckState(Qt.Unchecked)

    def _invertSelection(self):
        """
        Inverto row selection range in the sequence table.
        """
        for row in range(self.sequenceTable.rowCount()):
            item_widget = self.sequenceTable.item(row, 0)
            if item_widget.checkState() == Qt.Checked:
                item_widget.setCheckState(Qt.Unchecked)
            else:
                item_widget.setCheckState(Qt.Checked)

    def _get_mutation_descriptor(self, aa):
        """
        Get mutation descriptor string for a given amino acid.
        """
        aa_string = self.rosetta_all_set

        range = aa.get_mutation_range()
        aa_string = self.rosetta_all_set

        if range == "NATRO" or \
           range == "NATAA":
            code = aa.get_one_letter_code()
            aa_string = re.sub("[^"+code+"]",'_', aa_string)
        elif range == "POLAR":
            aa_string = self.rosetta_polar_set
        elif range == "APOLA":
            aa_string = self.rosetta_apolar_set
        elif range == "PIKAA":
            aa_string = aa.get_mutation_descriptor()

        return aa_string

    def _get_descriptor_name(self, aa):
        """
        Returns a mutation descriptor name for an amino acid.
        """
        range_name = aa.get_mutation_range()
        for i in range(len(self.rosetta_set_names)):
            if range_name == self.rosetta_set_names[i]:
                if range_name == "PIKAA":
                    # Find a descriptor with a list of
                    # custom descriptors.
                    dstr = self._makeProperAAString(aa.get_mutation_descriptor())
                    for i in range(5, len(self.descriptor_list)):
                        if dstr == self.descriptor_list[i]:
                            return self.set_names[i]
                else:
                    return self.set_names[i]
        return "Custom"

    def _get_aa_for_index(self, index, expand = False):
        """
        Get amino acid by index.
        @return: amino acid (Residue)
        """

        if not self.current_protein:
            return None
        else:
            currentProteinChunk = self.current_protein

        currentProteinChunk.protein.set_current_amino_acid_index(index)
        current_aa = currentProteinChunk.protein.get_current_amino_acid()
        if expand:
            currentProteinChunk.protein.collapse_all_rotamers()
            currentProteinChunk.protein.expand_rotamer(current_aa)
        return current_aa

    def _sequenceTableCellChanged(self, crow, ccol):
        """
        Slot for sequence table CellChanged event.
        """
        item = self.sequenceTable.item(crow, ccol)
        for row in range(self.sequenceTable.rowCount()):
            self.sequenceTable.removeCellWidget(row, 2)
            self.sequenceTable.setRowHeight(row, 16)
        if ccol == 2:
            # Make the row a little bit wider.
            self.sequenceTable.setRowHeight(crow, 22)
            # Create and insert a Combo Box into a current cell.
            self.setComboBox = QComboBox()
            self.setComboBox.addItems(self.set_names)

            self.win.connect(self.setComboBox,
                             SIGNAL("activated(int)"),
                             self._setComboBoxIndexChanged)

            self.sequenceTable.setCellWidget(crow, 2, self.setComboBox)

        current_aa = self._get_aa_for_index(crow, expand=True)
        if current_aa:
            # Center on the selected amino acid.
            if self.recenterViewCheckBox.isChecked():
                ca_atom = current_aa.get_c_alpha_atom()
                if ca_atom:
                    self.win.glpane.pov = -ca_atom.posn()
            self.win.glpane.gl_update()

            # Update backrub status for selected amino acid.
            if ccol == 3:
                cbox = self.sequenceTable.item(crow, 3)
                if cbox.checkState() == Qt.Checked:
                    current_aa.set_backrub_mode(True)
                else:
                    current_aa.set_backrub_mode(False)

        from PyQt4.Qt import QTextCursor
        cursor = self.sequenceEditor.sequenceTextEdit.textCursor()
        #boundary condition
        if crow == -1:
            crow = 0
        cursor.setPosition(crow, QTextCursor.MoveAnchor)
        cursor.setPosition(crow + 1, QTextCursor.KeepAnchor)
        self.sequenceEditor.sequenceTextEdit.setTextCursor( cursor )


    def _applyDescriptor(self):
        """
        Apply mutation descriptor to the selected amino acids.
        """
        cdes = self.descriptorsTable.currentRow()
        for row in range(self.sequenceTable.rowCount()):
            self._setComboBoxIndexChanged(cdes + 5, tablerow = row, selectedOnly = True)

    def _setComboBoxIndexChanged( self, index, tablerow = None, selectedOnly = False):
        """
        Slot for mutation descriptor combo box (in third column of the sequence
        table.)
        """
        if tablerow is None:
            crow = self.sequenceTable.currentRow()
        else:
            crow = tablerow
        item = self.sequenceTable.item(crow, 2)
        if item:
            self.editingItem = True

            cbox = self.sequenceTable.item(crow, 0)
            if not selectedOnly or \
               cbox.checkState() == Qt.Checked:
                item.setText(self.set_names[index])
                item = self.sequenceTable.item(crow, 4)
                aa = self._get_aa_for_index(crow)
                set_name = self.rosetta_set_names[index]
                aa.set_mutation_range(set_name)
                if set_name == "PIKAA":
                    aa.set_mutation_descriptor(self.descriptor_list[index])
                item.setText(self._get_mutation_descriptor(aa))
                for row in range(self.sequenceTable.rowCount()):
                    self.sequenceTable.removeCellWidget(row, 2)
                    self.sequenceTable.setRowHeight(row, 16)

            self.editingItem = False

    def scrollToPosition(self, index):
        """
        Scrolls the Sequence Table to a given sequence position.
        """
        item = self.sequenceTable.item(index, 0)
        if item:
            self.sequenceTable.scrollToItem(item)

    def _applyAny(self):
        """
        Apply "ALLAA" descriptor.
        """
        for row in range(self.sequenceTable.rowCount()):
            self._setComboBoxIndexChanged(0, tablerow = row, selectedOnly = True)

    def _applySame(self):
        """
        Apply "NATAA" descriptor.
        """
        for row in range(self.sequenceTable.rowCount()):
            self._setComboBoxIndexChanged(1, tablerow = row, selectedOnly = True)

    def _applyLocked(self):
        """
        Apply "NATRO" descriptor.
        """
        for row in range(self.sequenceTable.rowCount()):
            self._setComboBoxIndexChanged(2, tablerow = row, selectedOnly = True)

    def _applyPolar(self):
        """
        Apply "POLAR" descriptor.
        """
        for row in range(self.sequenceTable.rowCount()):
            self._setComboBoxIndexChanged(3, tablerow = row, selectedOnly = True)

    def _applyApolar(self):
        """
        Apply "APOLA" descriptor.
        """
        for row in range(self.sequenceTable.rowCount()):
            self._setComboBoxIndexChanged(4, tablerow = row, selectedOnly = True)

    def resizeEvent(self, event):
        """
        Called whenever PM width has changed. Sets correct width of the
        rows in descriptor and sequence tables.
        """
        self.descriptorsTable.setColumnWidth(1,
            self.descriptorsTable.width()-self.descriptorsTable.columnWidth(0)-20)

        self.sequenceTable.setColumnWidth(4,
            self.sequenceTable.width()-
            (self.sequenceTable.columnWidth(0) +
             self.sequenceTable.columnWidth(1) +
             self.sequenceTable.columnWidth(2) +
            self.sequenceTable.columnWidth(3))-20)


    def _addNewDescriptorTableRow(self, name, descriptor):
        """
        Adds a new row to the descriptor table.
        """
        row = self.descriptorsTable.rowCount()
        self.descriptorsTable.insertRow(row)

        item_widget = QTableWidgetItem(name)
        item_widget.setFont(self.labelfont)
        item_widget.setFlags(Qt.ItemIsSelectable |
                             Qt.ItemIsEnabled |
                             Qt.ItemIsEditable)
        item_widget.setTextAlignment(Qt.AlignLeft)
        self.descriptorsTable.setItem(row, 0, item_widget)
        self.descriptorsTable.resizeColumnToContents(0)

        s = self._makeProperAAString(descriptor)
        item_widget = QTableWidgetItem(s)
        item_widget.setFont(self.descriptorfont)
        item_widget.setFlags(Qt.ItemIsSelectable |
                             Qt.ItemIsEnabled |
                             Qt.ItemIsEditable)
        item_widget.setTextAlignment(Qt.AlignLeft)
        self.descriptorsTable.setItem(row, 1, item_widget)
        self.descriptorsTable.setColumnWidth(1,
            self.descriptorsTable.width()-self.descriptorsTable.columnWidth(0)-20)

        self.descriptorsTable.setRowHeight(row, 16)

    def _addNewDescriptor(self):
        """
        Adds a new descriptor to the descriptor table.
        """
        self._addNewDescriptorTableRow("New Set", "PGAVILMFWYCSTNQDEHKR")
        self._makeDescriptorUserPref()
        self._updateSetLists()

    def _removeDescriptor(self):
        """
        Removes a highlighted descriptor from the descriptors table.
        """
        crow = self.descriptorsTable.currentRow()
        if crow >= 0:
            self.descriptorsTable.removeRow(crow)
            self._makeDescriptorUserPref()
            self._updateSetLists()

    def _makeDescriptorUserPref(self):
        """
        Constructs a custom descriptors string.
        """
        dstr = ""
        for row in range(self.descriptorsTable.rowCount()):
            item0 = self.descriptorsTable.item(row, 0)
            item1 = self.descriptorsTable.item(row, 1)
            if item0 and \
               item1:
                dstr += item0.text() + \
                     ":" + \
                     item1.text() + \
                     ":"
        env.prefs[proteinCustomDescriptors_prefs_key] = dstr

    def _makeProperAAString(self, string):
        """
        Creates a proper amino acid string from an arbitrary string.
        """
        aa_string = str(string).upper()
        new_aa_string = ""
        for i in range(len(self.rosetta_all_set)):
            if aa_string.find(self.rosetta_all_set[i]) == -1:
                new_aa_string += "_"
            else:
                new_aa_string += self.rosetta_all_set[i]
        return new_aa_string

    def _sequenceTableItemChanged(self, item):
        """
        Called when an item in the sequence table has changed.
        """
        if self.editingItem:
            return
        if self.sequenceTable.column(item) == 4:
            self.editingItem = True
            crow = self.sequenceTable.currentRow()
            dstr = self._makeProperAAString(str(item.text()).upper())
            item.setText(dstr)
            aa = self._get_aa_for_index(crow)
            if aa:
                aa.set_mutation_range("PIKAA")
                aa.set_mutation_descriptor(dstr.replace("_",""))
            item = self.sequenceTable.item(crow, 2)
            if item:
                item.setText("Custom")
            self.editingItem = False

    def _descriptorsTableItemChanged(self, item):
        """
        Called when an item in the descriptors table has changed.
        """
        if self.editingItem:
            return
        if self.descriptorsTable.column(item) == 1:
            self.editingItem = True
            item.setText(self._makeProperAAString(str(item.text()).upper()))
            self.editingItem = False

        self._makeDescriptorUserPref()
        self._updateSetLists()

    def _updateSetLists(self):
        """
        Updates lists of descriptor sets and descriptor set names.
        """
        self.set_names = self.set_names[:5]
        self.descriptor_list = self.descriptor_list[:5]
        self.rosetta_set_names = self.rosetta_set_names[:5]

        dstr = env.prefs[proteinCustomDescriptors_prefs_key].split(":")
        for i in range(len(dstr) / 2):
            self.set_names.append(dstr[2*i])
            self.descriptor_list.append(dstr[2*i+1])
            self.rosetta_set_names.append("PIKAA")
            #self._addNewDescriptorTableRow(dstr[2*i], dstr[2*i+1])
        return

    def _update_UI_do_updates_TEMP(self):
        """
        Overrides superclass method.

        @see: Command_PropertyManager._update_UI_do_updates()
        """

        self.current_protein = self.win.assy.getSelectedProteinChunk()

        if self.current_protein is self.previous_protein:
            print "_update_UI_do_updates(): DO NOTHING."
            return

        # NOTE: Changing the display styles of the protein chunks can take some
        # time. We should put up the wait (hourglass) cursor here and restore
        # before returning.

        # Update all PM widgets that need to be since something has changed.
        print "_update_UI_do_updates(): UPDATING the PMGR."
        self.update_name_field()
        self.sequenceEditor.update()
        self.update_residue_combobox()


        if self.previous_protein:
            self.previous_protein.setDisplayStyle(self.previous_protein_display_style)

        self.previous_protein = self.current_protein

        if self.current_protein:
            self.previous_protein_display_style = self.current_protein.getDisplayStyle()
            self.current_protein.setDisplayStyle(diPROTEIN)

        return
Ejemplo n.º 7
0
class BreakOrJoinStrands_PropertyManager(Command_PropertyManager):

    _baseNumberLabelGroupBox = None

    def __init__(self, command):
        """
        Constructor for the property manager.
        """
        _superclass.__init__(self, command)
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        return

    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot 
                          method. 
        @type  isConnect: boolean
        """
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        # DNA Strand arrowhead display options signal-slot connections.

        self._connect_checkboxes_to_global_prefs_keys(isConnect)

        change_connect(self.fivePrimeEndColorChooser,
                       SIGNAL("editingFinished()"),
                       self.chooseCustomColorOnFivePrimeEnds)

        change_connect(self.threePrimeEndColorChooser,
                       SIGNAL("editingFinished()"),
                       self.chooseCustomColorOnThreePrimeEnds)

        change_connect(self.strandFivePrimeArrowheadsCustomColorCheckBox,
                       SIGNAL("toggled(bool)"),
                       self.allowChoosingColorsOnFivePrimeEnd)

        change_connect(self.strandThreePrimeArrowheadsCustomColorCheckBox,
                       SIGNAL("toggled(bool)"),
                       self.allowChoosingColorsOnThreePrimeEnd)

        self._baseNumberLabelGroupBox.connect_or_disconnect_signals(isConnect)

        return

    def show(self):
        """
        Shows the Property Manager. Extends superclass method. 
        @see: Command_PropertyManager.show()
        """
        _superclass.show(self)
        #Required to update the color combobox for Dna base number labels.
        self._baseNumberLabelGroupBox.updateWidgets()

    def _connect_checkboxes_to_global_prefs_keys(self, isConnect=True):
        """
        #doc
        """
        if not isConnect:
            return

        #ORDER of items in tuples checkboxes and prefs_keys is IMPORTANT!
        checkboxes = (self.arrowsOnThreePrimeEnds_checkBox,
                      self.arrowsOnFivePrimeEnds_checkBox,
                      self.strandThreePrimeArrowheadsCustomColorCheckBox,
                      self.strandFivePrimeArrowheadsCustomColorCheckBox,
                      self.arrowsOnBackBones_checkBox)

        prefs_keys = (self._prefs_key_arrowsOnThreePrimeEnds(),
                      self._prefs_key_arrowsOnFivePrimeEnds(),
                      self._prefs_key_useCustomColorForThreePrimeArrowheads(),
                      self._prefs_key_useCustomColorForFivePrimeArrowheads(),
                      arrowsOnBackBones_prefs_key)

        for checkbox, prefs_key in zip(checkboxes, prefs_keys):
            connect_checkbox_with_boolean_pref(checkbox, prefs_key)

        return

    #Load various widgets ====================

    def _loadBaseNumberLabelGroupBox(self, pmGroupBox):
        self._baseNumberLabelGroupBox = PM_DnaBaseNumberLabelsGroupBox(
            pmGroupBox, self.command)

    def _loadDisplayOptionsGroupBox(self, pmGroupBox):
        """
        Load widgets in the display options groupbox
        """
        title = "Arrowhead prefs in %s:" % self.command.featurename
        self._arrowheadPrefsGroupBox = PM_GroupBox(pmGroupBox, title=title)
        #load all the options
        self._load3PrimeEndArrowAndCustomColor(self._arrowheadPrefsGroupBox)
        self._load5PrimeEndArrowAndCustomColor(self._arrowheadPrefsGroupBox)
        self._loadArrowOnBackBone(pmGroupBox)
        return

    def _load3PrimeEndArrowAndCustomColor(self, pmGroupBox):
        """
        Loads 3' end arrow head and custom color checkbox and color chooser dialog
        """
        self.pmGroupBox3 = PM_GroupBox(pmGroupBox, title="3' end:")

        self.arrowsOnThreePrimeEnds_checkBox = PM_CheckBox(
            self.pmGroupBox3,
            text="Show arrowhead",
            widgetColumn=0,
            setAsDefault=True,
            spanWidth=True)

        self.strandThreePrimeArrowheadsCustomColorCheckBox = PM_CheckBox(
            self.pmGroupBox3,
            text="Display custom color",
            widgetColumn=0,
            setAsDefault=True,
            spanWidth=True)

        prefs_key = self._prefs_key_dnaStrandThreePrimeArrowheadsCustomColor()
        self.threePrimeEndColorChooser = \
            PM_ColorComboBox(self.pmGroupBox3,
                             color      = env.prefs[prefs_key])

        prefs_key = self._prefs_key_useCustomColorForThreePrimeArrowheads()
        if env.prefs[prefs_key]:
            self.strandThreePrimeArrowheadsCustomColorCheckBox.setCheckState(
                Qt.Checked)
            self.threePrimeEndColorChooser.show()
        else:
            self.strandThreePrimeArrowheadsCustomColorCheckBox.setCheckState(
                Qt.Unchecked)
            self.threePrimeEndColorChooser.hide()

        return

    def _load5PrimeEndArrowAndCustomColor(self, pmGroupBox):
        """
        Loads 5' end custom color checkbox and color chooser dialog
        """
        self.pmGroupBox2 = PM_GroupBox(pmGroupBox, title="5' end:")
        self.arrowsOnFivePrimeEnds_checkBox = PM_CheckBox(
            self.pmGroupBox2,
            text="Show arrowhead",
            widgetColumn=0,
            setAsDefault=True,
            spanWidth=True)

        self.strandFivePrimeArrowheadsCustomColorCheckBox = PM_CheckBox(
            self.pmGroupBox2,
            text="Display custom color",
            widgetColumn=0,
            setAsDefault=True,
            spanWidth=True)

        prefs_key = self._prefs_key_dnaStrandFivePrimeArrowheadsCustomColor()
        self.fivePrimeEndColorChooser = \
            PM_ColorComboBox(self.pmGroupBox2,
                             color      = env.prefs[prefs_key]
                             )

        prefs_key = self._prefs_key_useCustomColorForFivePrimeArrowheads()
        if env.prefs[prefs_key]:
            self.strandFivePrimeArrowheadsCustomColorCheckBox.setCheckState(
                Qt.Checked)
            self.fivePrimeEndColorChooser.show()
        else:
            self.strandFivePrimeArrowheadsCustomColorCheckBox.setCheckState(
                Qt.Unchecked)
            self.fivePrimeEndColorChooser.hide()

        return

    def _loadArrowOnBackBone(self, pmGroupBox):
        """
        Loads Arrow on the backbone checkbox
        """
        self.pmGroupBox4 = PM_GroupBox(pmGroupBox, title="Global preference:")
        self.arrowsOnBackBones_checkBox = PM_CheckBox(
            self.pmGroupBox4,
            text="Show arrows on back bones",
            widgetColumn=0,
            setAsDefault=True,
            spanWidth=True)
        return

    def allowChoosingColorsOnFivePrimeEnd(self, state):
        """
        Show or hide color chooser based on the 
        strandFivePrimeArrowheadsCustomColorCheckBox's state
        """
        if self.strandFivePrimeArrowheadsCustomColorCheckBox.isChecked():
            self.fivePrimeEndColorChooser.show()
        else:
            self.fivePrimeEndColorChooser.hide()
        return

    def allowChoosingColorsOnThreePrimeEnd(self, state):
        """
        Show or hide color chooser based on the 
        strandThreePrimeArrowheadsCustomColorCheckBox's state
        """
        if self.strandThreePrimeArrowheadsCustomColorCheckBox.isChecked():
            self.threePrimeEndColorChooser.show()
        else:
            self.threePrimeEndColorChooser.hide()
        return

    def chooseCustomColorOnThreePrimeEnds(self):
        """
        Choose custom color for 3' ends
        """
        color = self.threePrimeEndColorChooser.getColor()
        prefs_key = self._prefs_key_dnaStrandThreePrimeArrowheadsCustomColor()
        env.prefs[prefs_key] = color
        self.win.glpane.gl_update()
        return

    def chooseCustomColorOnFivePrimeEnds(self):
        """
        Choose custom color for 5' ends
        """
        color = self.fivePrimeEndColorChooser.getColor()
        prefs_key = self._prefs_key_dnaStrandFivePrimeArrowheadsCustomColor()
        env.prefs[prefs_key] = color
        self.win.glpane.gl_update()
        return

    #Return varius prefs_keys for arrowhead display options ui elements =======
    def _prefs_key_arrowsOnThreePrimeEnds(self):
        """
        Return the appropriate KEY of the preference for whether to
        draw arrows on 3' strand ends of PAM DNA.
        """
        return arrowsOnThreePrimeEnds_prefs_key

    def _prefs_key_arrowsOnFivePrimeEnds(self):
        """
        Return the appropriate KEY of the preference for whether to
        draw arrows on 5' strand ends of PAM DNA.
        """
        return arrowsOnFivePrimeEnds_prefs_key

    def _prefs_key_useCustomColorForThreePrimeArrowheads(self):
        """
        Return the appropriate KEY of the preference for whether to use a
        custom color for 3' arrowheads (if they are drawn)
        or for 3' strand end atoms (if arrowheads are not drawn)
        """
        return useCustomColorForThreePrimeArrowheads_prefs_key

    def _prefs_key_useCustomColorForFivePrimeArrowheads(self):
        """
        Return the appropriate KEY of the preference for whether to use a
        custom color for 5' arrowheads (if they are drawn)
        or for 5' strand end atoms (if arrowheads are not drawn).        
        """
        return useCustomColorForFivePrimeArrowheads_prefs_key

    def _prefs_key_dnaStrandThreePrimeArrowheadsCustomColor(self):
        """
        Return the appropriate KEY of the preference for what custom color
        to use when drawing 3' arrowheads (if they are drawn)
        or 3' strand end atoms (if arrowheads are not drawn).
        """
        return dnaStrandThreePrimeArrowheadsCustomColor_prefs_key

    def _prefs_key_dnaStrandFivePrimeArrowheadsCustomColor(self):
        """
        Return the appropriate KEY of the preference for what custom color
        to use when drawing 5' arrowheads (if they are drawn)
        or 5' strand end atoms (if arrowheads are not drawn).
        """
        return dnaStrandFivePrimeArrowheadsCustomColor_prefs_key
class StereoProperties_PropertyManager( PM_Dialog, DebugMenuMixin ):
    """
    The StereoProperties_PropertyManager class provides a Property Manager 
    for the Stereo View command. 

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title         =  "Stereo View"
    pmName        =  title
    iconPath      =  "ui/actions/View/Stereo_View.png"


    def __init__( self, parentCommand ):
        """
        Constructor for the property manager.
        """

        self.parentMode = parentCommand
        self.w = self.parentMode.w
        self.win = self.parentMode.w
        self.pw = self.parentMode.pw        
        self.o = self.win.glpane                 

        PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title)

        DebugMenuMixin._init1( self )

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Modify the Stereo View settings below."

        self.updateMessage(msg)

    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot 
                          method. 
        @type  isConnect: boolean
        """
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect 

        change_connect(self.stereoEnabledCheckBox, 
                       SIGNAL("toggled(bool)"), 
                       self._enableStereo ) 

        change_connect( self.stereoModeComboBox,
                        SIGNAL("currentIndexChanged(int)"),
                        self._stereoModeComboBoxChanged )

        change_connect(self.stereoSeparationSlider,
                       SIGNAL("valueChanged(int)"),
                       self._stereoModeSeparationSliderChanged )

        change_connect(self.stereoAngleSlider,
                       SIGNAL("valueChanged(int)"),
                       self._stereoModeAngleSliderChanged )

    def ok_btn_clicked(self):
        """
        Slot for the OK button
        """      
        self.win.toolsDone()

    def cancel_btn_clicked(self):
        """
        Slot for the Cancel button.
        """  
        #TODO: Cancel button needs to be removed. See comment at the top
        self.win.toolsDone()

    def show(self):
        """
        Shows the Property Manager. Overrides PM_Dialog.show.
        """
        PM_Dialog.show(self)
        # self.updateDnaDisplayStyleWidgets()
        self.connect_or_disconnect_signals(isConnect = True)

    def close(self):
        """
        Closes the Property Manager. Overrides PM_Dialog.close.
        """
        self.connect_or_disconnect_signals(False)
        PM_Dialog.close(self)

    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox( self, 
                                         title = "Settings")
        self._loadGroupBox1( self._pmGroupBox1 )

        #@ self._pmGroupBox1.hide()

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        #stereoSettingsGroupBox = PM_GroupBox( None )

        self.stereoEnabledCheckBox = \
            PM_CheckBox(pmGroupBox,
                        text         = 'Enable Stereo View',
                        widgetColumn = 1
                        )        

        stereoModeChoices = ['Relaxed view', 
                             'Cross-eyed view',
                             'Red/blue anaglyphs',
                             'Red/cyan anaglyphs',
                             'Red/green anaglyphs']

        self.stereoModeComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Stereo Mode:", 
                         choices       =  stereoModeChoices,
                         setAsDefault  =  True)

        self.stereoModeComboBox.setCurrentIndex(env.prefs[stereoViewMode_prefs_key]-1)
            
        self.stereoSeparationSlider =  \
            PM_Slider( pmGroupBox,
                       currentValue = 50,
                       minimum      = 0,
                       maximum      = 300,
                       label        = 'Separation'
                       )        

        self.stereoSeparationSlider.setValue(env.prefs[stereoViewSeparation_prefs_key])

        self.stereoAngleSlider =  \
            PM_Slider( pmGroupBox,
                       currentValue = 50,
                       minimum      = 0,
                       maximum      = 100,
                       label        = 'Angle'
                       )        

        self.stereoAngleSlider.setValue(env.prefs[stereoViewAngle_prefs_key])

        self._updateWidgets()
                
    def _addWhatsThisText( self ):
        """
        What's This text for widgets in the Stereo Property Manager.  
        """
        pass

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the Stereo Property Manager.  
        """
        pass

    def _enableStereo(self, enabled):
        """
        Enable stereo view.
        """        
        if self.o:
            self.o.stereo_enabled = enabled
            # switch to perspective mode
            if enabled:
                # store current projection mode
                self.o.last_ortho = self.o.ortho
                if self.o.ortho is not 0:
                    # dont use glpane.setViewProjection
                    # because we don't want to modify 
                    # default projection setting 
                    self.o.ortho = 0 
            else:
                # restore default mode
                if hasattr(self.o, "last_ortho"):
                    projection = self.o.last_ortho
                    if self.o.ortho != projection:
                        self.o.ortho = projection

            self._updateWidgets()
                    
            self.o.gl_update()
            
            
    def _stereoModeComboBoxChanged(self, mode):
        """
        Change stereo mode.
        """

        env.prefs[stereoViewMode_prefs_key] = mode + 1

        self._updateSeparationSlider()
        
        if self.o:
            self.o.gl_update()        

    def _stereoModeSeparationSliderChanged(self, value):
        """
        Change stereo view separation.
        """

        env.prefs[stereoViewSeparation_prefs_key] = value
        if self.o:
            self.o.gl_update()        

    def _stereoModeAngleSliderChanged(self, value):
        """
        Change stereo view angle.
        """

        env.prefs[stereoViewAngle_prefs_key] = value
        if self.o:
            self.o.gl_update()        

    def _updateSeparationSlider(self):
        if self.stereoModeComboBox.currentIndex() >= 2: 
            # for anaglyphs disable the separation slider 
            self.stereoSeparationSlider.setEnabled(False)
        else:
            # otherwise, enable the separation slider
            self.stereoSeparationSlider.setEnabled(True)

    def _updateWidgets(self):
        if self.stereoEnabledCheckBox.isChecked():
            self.stereoModeComboBox.setEnabled(True)
            self.stereoSeparationSlider.setEnabled(True)
            self.stereoAngleSlider.setEnabled(True)
            self._updateSeparationSlider()
        else:
            self.stereoModeComboBox.setEnabled(False)
            self.stereoSeparationSlider.setEnabled(False)
            self.stereoAngleSlider.setEnabled(False)
            
Ejemplo n.º 9
0
class StereoProperties_PropertyManager(Command_PropertyManager):
    """
    The StereoProperties_PropertyManager class provides a Property Manager 
    for the Stereo View command. 

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title = "Stereo View"
    pmName = title
    iconPath = "ui/actions/View/Stereo_View.png"

    def __init__(self, command):
        """
        Constructor for the property manager.
        """

        _superclass.__init__(self, command)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Modify the Stereo View settings below."

        self.updateMessage(msg)

    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot 
                          method. 
        @type  isConnect: boolean
        """
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self.stereoEnabledCheckBox, SIGNAL("toggled(bool)"),
                       self._enableStereo)

        change_connect(self.stereoModeComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self._stereoModeComboBoxChanged)

        change_connect(self.stereoSeparationSlider,
                       SIGNAL("valueChanged(int)"),
                       self._stereoModeSeparationSliderChanged)

        change_connect(self.stereoAngleSlider, SIGNAL("valueChanged(int)"),
                       self._stereoModeAngleSliderChanged)

    def _addGroupBoxes(self):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox(self, title="Settings")
        self._loadGroupBox1(self._pmGroupBox1)

        #@ self._pmGroupBox1.hide()

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        #stereoSettingsGroupBox = PM_GroupBox( None )

        self.stereoEnabledCheckBox = \
            PM_CheckBox(pmGroupBox,
                        text         = 'Enable Stereo View',
                        widgetColumn = 1
                        )

        stereoModeChoices = [
            'Relaxed view', 'Cross-eyed view', 'Red/blue anaglyphs',
            'Red/cyan anaglyphs', 'Red/green anaglyphs'
        ]

        self.stereoModeComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Stereo Mode:",
                         choices       =  stereoModeChoices,
                         setAsDefault  =  True)

        self.stereoModeComboBox.setCurrentIndex(
            env.prefs[stereoViewMode_prefs_key] - 1)

        self.stereoSeparationSlider =  \
            PM_Slider( pmGroupBox,
                       currentValue = 50,
                       minimum      = 0,
                       maximum      = 300,
                       label        = 'Separation'
                       )

        self.stereoSeparationSlider.setValue(
            env.prefs[stereoViewSeparation_prefs_key])

        self.stereoAngleSlider =  \
            PM_Slider( pmGroupBox,
                       currentValue = 50,
                       minimum      = 0,
                       maximum      = 100,
                       label        = 'Angle'
                       )

        self.stereoAngleSlider.setValue(env.prefs[stereoViewAngle_prefs_key])

        self._updateWidgets()

    def _addWhatsThisText(self):
        """
        What's This text for widgets in the Stereo Property Manager.  
        """
        pass

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the Stereo Property Manager.  
        """
        pass

    def _enableStereo(self, enabled):
        """
        Enable stereo view.
        """
        glpane = self.o
        if glpane:
            glpane.set_stereo_enabled(enabled)
            # switch to perspective mode
            if enabled:
                # store current projection mode
                glpane.__StereoProperties_last_ortho = glpane.ortho
                if glpane.ortho:
                    # dont use glpane.setViewProjection
                    # because we don't want to modify
                    # default projection setting
                    glpane.ortho = 0
            else:
                # restore default mode
                if hasattr(glpane, "__StereoProperties_last_ortho"):
                    projection = glpane.__StereoProperties_last_ortho
                    if glpane.ortho != projection:
                        glpane.ortho = projection

            self._updateWidgets()

            glpane.gl_update()

    def _stereoModeComboBoxChanged(self, mode):
        """
        Change stereo mode.
        
        @param mode: stereo mode (0=relaxed, 1=cross-eyed, 2=red/blue,
        3=red/cyan, 4=red/green)
        @type value: int
        """
        env.prefs[stereoViewMode_prefs_key] = mode + 1

        self._updateSeparationSlider()

    def _stereoModeSeparationSliderChanged(self, value):
        """
        Change stereo view separation.
        
        @param value: separation (0..300)
        @type value: int
        """
        env.prefs[stereoViewSeparation_prefs_key] = value

    def _stereoModeAngleSliderChanged(self, value):
        """
        Change stereo view angle.
        
        @param value: stereo angle (0..100)
        @type value: int
        """
        env.prefs[stereoViewAngle_prefs_key] = value

    def _updateSeparationSlider(self):
        """ 
        Update the separation slider widget.
        """
        if self.stereoModeComboBox.currentIndex() >= 2:
            # for anaglyphs disable the separation slider
            self.stereoSeparationSlider.setEnabled(False)
        else:
            # otherwise, enable the separation slider
            self.stereoSeparationSlider.setEnabled(True)

    def _updateWidgets(self):
        """
        Update stereo PM widgets.
        """
        if self.stereoEnabledCheckBox.isChecked():
            self.stereoModeComboBox.setEnabled(True)
            self.stereoSeparationSlider.setEnabled(True)
            self.stereoAngleSlider.setEnabled(True)
            self._updateSeparationSlider()
        else:
            self.stereoModeComboBox.setEnabled(False)
            self.stereoSeparationSlider.setEnabled(False)
            self.stereoAngleSlider.setEnabled(False)
Ejemplo n.º 10
0
class StereoProperties_PropertyManager(PM_Dialog, DebugMenuMixin):
    """
    The StereoProperties_PropertyManager class provides a Property Manager 
    for the Stereo View command. 

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title = "Stereo View"
    pmName = title
    iconPath = "ui/actions/View/Stereo_View.png"

    def __init__(self, parentCommand):
        """
        Constructor for the property manager.
        """

        self.parentMode = parentCommand
        self.w = self.parentMode.w
        self.win = self.parentMode.w
        self.pw = self.parentMode.pw
        self.o = self.win.glpane

        PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title)

        DebugMenuMixin._init1(self)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Modify the Stereo View settings below."

        self.updateMessage(msg)

    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot 
                          method. 
        @type  isConnect: boolean
        """
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self.stereoEnabledCheckBox, SIGNAL("toggled(bool)"),
                       self._enableStereo)

        change_connect(self.stereoModeComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self._stereoModeComboBoxChanged)

        change_connect(self.stereoSeparationSlider,
                       SIGNAL("valueChanged(int)"),
                       self._stereoModeSeparationSliderChanged)

        change_connect(self.stereoAngleSlider, SIGNAL("valueChanged(int)"),
                       self._stereoModeAngleSliderChanged)

    def ok_btn_clicked(self):
        """
        Slot for the OK button
        """
        self.win.toolsDone()

    def cancel_btn_clicked(self):
        """
        Slot for the Cancel button.
        """
        #TODO: Cancel button needs to be removed. See comment at the top
        self.win.toolsDone()

    def show(self):
        """
        Shows the Property Manager. Overrides PM_Dialog.show.
        """
        PM_Dialog.show(self)
        # self.updateDnaDisplayStyleWidgets()
        self.connect_or_disconnect_signals(isConnect=True)

    def close(self):
        """
        Closes the Property Manager. Overrides PM_Dialog.close.
        """
        self.connect_or_disconnect_signals(False)
        PM_Dialog.close(self)

    def _addGroupBoxes(self):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox(self, title="Settings")
        self._loadGroupBox1(self._pmGroupBox1)

        #@ self._pmGroupBox1.hide()

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        #stereoSettingsGroupBox = PM_GroupBox( None )

        self.stereoEnabledCheckBox = \
            PM_CheckBox(pmGroupBox,
                        text         = 'Enable Stereo View',
                        widgetColumn = 1
                        )

        stereoModeChoices = [
            'Relaxed view', 'Cross-eyed view', 'Red/blue anaglyphs',
            'Red/cyan anaglyphs', 'Red/green anaglyphs'
        ]

        self.stereoModeComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Stereo Mode:",
                         choices       =  stereoModeChoices,
                         setAsDefault  =  True)

        self.stereoModeComboBox.setCurrentIndex(
            env.prefs[stereoViewMode_prefs_key] - 1)

        self.stereoSeparationSlider =  \
            PM_Slider( pmGroupBox,
                       currentValue = 50,
                       minimum      = 0,
                       maximum      = 300,
                       label        = 'Separation'
                       )

        self.stereoSeparationSlider.setValue(
            env.prefs[stereoViewSeparation_prefs_key])

        self.stereoAngleSlider =  \
            PM_Slider( pmGroupBox,
                       currentValue = 50,
                       minimum      = 0,
                       maximum      = 100,
                       label        = 'Angle'
                       )

        self.stereoAngleSlider.setValue(env.prefs[stereoViewAngle_prefs_key])

        self._updateWidgets()

    def _addWhatsThisText(self):
        """
        What's This text for widgets in the Stereo Property Manager.  
        """
        pass

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the Stereo Property Manager.  
        """
        pass

    def _enableStereo(self, enabled):
        """
        Enable stereo view.
        """
        if self.o:
            self.o.stereo_enabled = enabled
            # switch to perspective mode
            if enabled:
                # store current projection mode
                self.o.last_ortho = self.o.ortho
                if self.o.ortho is not 0:
                    # dont use glpane.setViewProjection
                    # because we don't want to modify
                    # default projection setting
                    self.o.ortho = 0
            else:
                # restore default mode
                if hasattr(self.o, "last_ortho"):
                    projection = self.o.last_ortho
                    if self.o.ortho != projection:
                        self.o.ortho = projection

            self._updateWidgets()

            self.o.gl_update()

    def _stereoModeComboBoxChanged(self, mode):
        """
        Change stereo mode.
        """

        env.prefs[stereoViewMode_prefs_key] = mode + 1

        self._updateSeparationSlider()

        if self.o:
            self.o.gl_update()

    def _stereoModeSeparationSliderChanged(self, value):
        """
        Change stereo view separation.
        """

        env.prefs[stereoViewSeparation_prefs_key] = value
        if self.o:
            self.o.gl_update()

    def _stereoModeAngleSliderChanged(self, value):
        """
        Change stereo view angle.
        """

        env.prefs[stereoViewAngle_prefs_key] = value
        if self.o:
            self.o.gl_update()

    def _updateSeparationSlider(self):
        if self.stereoModeComboBox.currentIndex() >= 2:
            # for anaglyphs disable the separation slider
            self.stereoSeparationSlider.setEnabled(False)
        else:
            # otherwise, enable the separation slider
            self.stereoSeparationSlider.setEnabled(True)

    def _updateWidgets(self):
        if self.stereoEnabledCheckBox.isChecked():
            self.stereoModeComboBox.setEnabled(True)
            self.stereoSeparationSlider.setEnabled(True)
            self.stereoAngleSlider.setEnabled(True)
            self._updateSeparationSlider()
        else:
            self.stereoModeComboBox.setEnabled(False)
            self.stereoSeparationSlider.setEnabled(False)
            self.stereoAngleSlider.setEnabled(False)
class EditProtein_PropertyManager(Command_PropertyManager):
    """
    The ProteinDisplayStyle_PropertyManager class provides a Property Manager 
    for the B{Edit Protein} command on the Build Protein command toolbar. 
    
    The selected peptide/protein is displayed in the protein reduced display
    style. The user can select individual rotamers and edit their chi angles.
    This is useful for certain types of protein design protocols using a
    3rd party program like Rosetta.

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title         =  "Protein Properties"
    pmName        =  title
    iconPath      =  "ui/actions/Command Toolbar/BuildProtein/EditProtein.png"
    
    current_protein  = None # The currently selected peptide.
    previous_protein = None # The last peptide selected.
    current_aa       = None # The current amino acid.

    
    def __init__( self, command ):
        """
        Constructor for the property manager.
        """
        self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key]
        
        _superclass.__init__(self, command)
        
        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        return
        
    def connect_or_disconnect_signals(self, isConnect = True):
        
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect 
        
        change_connect(self.nameLineEdit,
                       SIGNAL("editingFinished()"),
                       self._nameChanged)
        
        change_connect(self.currentResidueComboBox,
                       SIGNAL("activated(int)"),
                       self.setCurrentAminoAcid)
        
        change_connect(self.prevButton, 
                       SIGNAL("clicked()"), 
                       self._expandPreviousRotamer)
        
        change_connect(self.nextButton, 
                       SIGNAL("clicked()"), 
                       self._expandNextRotamer)
        
        change_connect(self.recenterViewCheckBox,
                       SIGNAL("toggled(bool)"),
                       self._centerViewToggled)
        
        change_connect(self.showAllResiduesCheckBox,
                       SIGNAL("toggled(bool)"),
                       self._showAllResidues)
        
        # Rotamer control widgets.
        
        change_connect(self.chi1Dial,
                       SIGNAL("valueChanged(int)"),
                       self._rotateChi1)
        
                
        change_connect(self.chi2Dial,
                       SIGNAL("valueChanged(int)"),
                       self._rotateChi2)
        
        change_connect(self.chi3Dial,
                       SIGNAL("valueChanged(int)"),
                       self._rotateChi3)
        
        # Chi4 dial is hidden.
        change_connect(self.chi4Dial,
                       SIGNAL("valueChanged(double)"),
                       self._rotateChi4)
        return
    
    #==
    
    def _nameChanged(self):
        """
        Slot for "Name" field.
        
        @TODO: Include a validator for the name field.
        """
        if not self.current_protein:
            return
        
        _name = str(self.nameLineEdit.text())
        
        if not _name: # Minimal test. Need to implement a validator.
            if self.current_protein:
                self.nameLineEdit.setText(self.current_protein.name)
            return
        
        self.current_protein.name = _name
        msg = "Editing structure <b>%s</b>." % _name
        self.updateMessage(msg)
        
        return
    
    def update_name_field(self):
        """
        Update the name field showing the name of the currently selected protein.
        clear the combobox list.
        """
        if not self.current_protein:
            self.nameLineEdit.setText("")
        else:
            self.nameLineEdit.setText(self.current_protein.name)
        return
    
    def update_length_field(self):
        """
        Update the name field showing the name of the currently selected protein.
        clear the combobox list.
        """
        if not self.current_protein:
            self.lengthLineEdit.setText("")
        else:
            length_str = "%d residues" % self.current_protein.protein.count_amino_acids()
            self.lengthLineEdit.setText(length_str)
        return
    
    def update_residue_combobox(self):
        """
        Update the residue combobox with the amino acid sequence of the
        currently selected protein. If there is no currently selected protein,
        clear the combobox list.
        """
        
        self.currentResidueComboBox.clear()
        
        if not self.current_protein:
            return
        
        aa_list = self.current_protein.protein.get_amino_acid_id_list()
        for j in range(len(aa_list)):
            aa_id, residue_id = aa_list[j].strip().split(":")
            self.currentResidueComboBox.addItem(residue_id)
            pass
        
        self.setCurrentAminoAcid()
        return
    
    def close(self):
        """
        Closes the Property Manager. Overrides EditCommand_PM.close()
        """
        self.sequenceEditor.hide()
        env.history.statusbar_msg("")
        if self.current_protein:
            self.current_protein.setDisplayStyle(self.previous_protein_display_style)
            self.previous_protein = None
            
            # Update name in case the it was changed by the user.
            self.current_protein.name = str(self.nameLineEdit.text())
            
        _superclass.close(self)
        return
    
    def show(self):
        """
        Show the PM. Extends superclass method.
        @note: _update_UI_do_updates() gets called immediately after this and
               updates PM widgets with their correct values/settings.
        """
        _superclass.show(self)
        env.history.statusbar_msg("")
        return
    
    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox( self,
                                         title = "Parameters")
        self._loadGroupBox1( self._pmGroupBox1 )

        self._pmGroupBox2 = PM_GroupBox( self,
                                         title = "Rotamer Controls")
        self._loadGroupBox2( self._pmGroupBox2 )
        return


    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        
        self.nameLineEdit = PM_LineEdit( pmGroupBox,
                                                label = "Name:")
        
        self.lengthLineEdit = PM_LineEdit( pmGroupBox,
                                           label = "Length:")
        self.lengthLineEdit.setEnabled(False)
        
        self.currentResidueComboBox = PM_ComboBox( pmGroupBox,
                                 label         =  "Current residue:",
                                 setAsDefault  =  False)
        
        BUTTON_LIST = [
            ("QToolButton", 1, "Previous residue", 
             "ui/actions/Properties Manager/Previous.png", 
             "", "Previous residue", 0 ),

            ( "QToolButton", 2, "Next residue",  
              "ui/actions/Properties Manager/Next.png", 
              "", "Next residue", 1 )
            ]
        
        self.prevNextButtonRow = \
            PM_ToolButtonRow( pmGroupBox, 
                              title        =  "",
                              buttonList   =  BUTTON_LIST,
                              label        =  'Previous / Next:',
                              isAutoRaise  =  True,
                              isCheckable  =  False
                            )
        self.prevButton = self.prevNextButtonRow.getButtonById(1)
        self.nextButton = self.prevNextButtonRow.getButtonById(2)
        
        self.recenterViewCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Center view on current residue",
                         setAsDefault  =  True,
                         state         =  Qt.Unchecked,
                         widgetColumn  =  0,
                         spanWidth     =  True)
        
        self.lockEditedCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Lock edited rotamers",
                         setAsDefault  =  True,
                         state         =  Qt.Checked,
                         widgetColumn  =  0,
                         spanWidth     =  True)
        
        self.showAllResiduesCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Show all residues",
                         setAsDefault  =  False,
                         state         =  Qt.Unchecked,
                         widgetColumn  =  0,
                         spanWidth     =  True)
        return
        
    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        
        self.discreteStepsCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Use discrete steps",
                         setAsDefault  =  True,
                         state         = Qt.Unchecked)
        
        self.chi1Dial  =  \
            PM_Dial( pmGroupBox,
                              label         =  "Chi1:",
                              value         =  0.000,
                              setAsDefault  =  True,
                              minimum       =  -180.0,
                              maximum       =  180.0,
                              wrapping      =  True,
                              suffix        =  "deg",
                              spanWidth = False)
        
        self.chi1Dial.setEnabled(False)
        
        self.chi2Dial  =  \
            PM_Dial( pmGroupBox,
                              label         =  "Chi2:",
                              value         =  0.000,
                              setAsDefault  =  True,
                              minimum       =  -180.0,
                              maximum       =  180.0,
                              suffix        =  "deg",
                              spanWidth = False)
        
        self.chi2Dial.setEnabled(False)
        
        self.chi3Dial  =  \
            PM_Dial( pmGroupBox,
                              label         =  "Chi3:",
                              value         =  0.000,
                              setAsDefault  =  True,
                              minimum       =  -180.0,
                              maximum       =  180.0,
                              suffix        =  "deg",
                              spanWidth = False)
        
        self.chi3Dial.setEnabled(False)
        
        self.chi4Dial  =  \
            PM_Dial( pmGroupBox,
                              label         =  "Chi4:",
                              value         =  0.000,
                              setAsDefault  =  True,
                              minimum       =  -180.0,
                              maximum       =  180.0,
                              suffix        =  "deg",
                              spanWidth = False)
        
        self.chi4Dial.setEnabled(False)
        
        self.chi4Dial.hide()
        
        return
        
    def _addWhatsThisText( self ):
        
        pass
    
    def _addToolTipText(self):
        
        pass

    def _expandNextRotamer(self):
        """
        Displays the next rotamer in the chain.
        
        @attention: this only works when the GDS is a reduced display style.
        """
        if not self.current_protein:
            return
        
        self.current_protein.protein.traverse_forward()
        self.setCurrentAminoAcid()
        return
    
    def _expandPreviousRotamer(self):
        """
        Displays the previous rotamer in the chain.
        
        @attention: this only works when the GDS is a reduced display style.
        """
        if not self.current_protein:
            return
        
        self.current_protein.protein.traverse_backward()
        self.setCurrentAminoAcid()
        return
    
    def _centerViewToggled(self, checked):
        """
        Slot for "Center view on current residue" checkbox.
        """
        if checked:
            self.display_and_recenter()
        return
    
    def _showAllResidues(self, show):
        """
        Slot for "Show all residues" checkbox.
        """
        if not self.current_protein:
            return
        
        print "Show =",show
        if show:
            self._expandAllRotamers()
        else:
            self._collapseAllRotamers()
        return
    
    def _collapseAllRotamers(self):
        """
        Hides all the rotamers (except the current rotamer).
        """
        self.display_and_recenter()
        return
    
    def _expandAllRotamers(self):
        """
        Displays all the rotamers.
        """
        if not self.current_protein:
            return
        
        self.current_protein.protein.expand_all_rotamers()
        self.win.glpane.gl_update()
        return
        
    def display_and_recenter(self):
        """
        Recenter the view on the current amino acid selected in the 
        residue combobox (or the sequence editor). All rotamers 
        except the current rotamer are collapsed (hidden).
        """
        if not self.current_protein:
            return
        
        # Uncheck the "Show all residues" checkbox since they are being collapsed.
        # Disconnect signals so that showAllResiduesCheckBox won't general a signal.
        self.connect_or_disconnect_signals(isConnect = False)
        self.showAllResiduesCheckBox.setChecked(False)
        self.connect_or_disconnect_signals(isConnect = True)
        
        self.current_protein.protein.collapse_all_rotamers()
        
        # Display the current amino acid and center it in the view if the
        # "Center view on current residue" is checked.
        if self.current_aa:
            self.current_protein.protein.expand_rotamer(self.current_aa)
            self._update_chi_angles(self.current_aa)
            if self.recenterViewCheckBox.isChecked():
                ca_atom = self.current_aa.get_c_alpha_atom()
                if ca_atom:
                    self.win.glpane.pov = -ca_atom.posn()                            
            
            self.win.glpane.gl_update()
        return
    
    def _update_chi_angles(self, aa):
        """
        """
        angle = aa.get_chi_angle(0)
        if angle:
            self.chi1Dial.setEnabled(True)
            self.chi1Dial.setValue(angle)
        else:
            self.chi1Dial.setEnabled(False)
            self.chi1Dial.setValue(0.0)
        
        angle = aa.get_chi_angle(1)
        if angle:
            self.chi2Dial.setEnabled(True)
            self.chi2Dial.setValue(angle)
        else:
            self.chi2Dial.setEnabled(False)
            self.chi2Dial.setValue(0.0)
        
        angle = aa.get_chi_angle(2)
        if angle:
            self.chi3Dial.setEnabled(True)
            self.chi3Dial.setValue(angle)
        else:
            self.chi3Dial.setEnabled(False)
            self.chi3Dial.setValue(0.0)
        
        angle = aa.get_chi_angle(3)
        if angle:
            self.chi4Dial.setEnabled(True)
            self.chi4Dial.setValue(angle)
        else:
            self.chi4Dial.setEnabled(False)
            self.chi4Dial.setValue(0.0)
        return
        
    def setCurrentAminoAcid(self, aa_index = -1):
        """
        Set the current amino acid to I{aa_index} and update the 
        "Current residue" combobox and the sequence editor.
        @param aa_index: the amino acid index. If negative, update the PM and 
                         sequence editor based on the current aa_index.
        @type  aa_index: int
        @note: This is the slot for the "Current residue" combobox.
        """
        if not self.current_protein:
            return
        
        if aa_index < 0:
            aa_index = self.current_protein.protein.get_current_amino_acid_index()
        
        if 0: # Debugging statement
            print"setCurrentAminoAcid(): aa_index=", aa_index
        self.currentResidueComboBox.setCurrentIndex(aa_index)
        self.current_protein.protein.set_current_amino_acid_index(aa_index)
        self.current_aa = self.current_protein.protein.get_current_amino_acid()
        self.display_and_recenter()
        self.sequenceEditor.setCursorPosition(aa_index)
        return
    
    def _rotateChiAngle(self, chi, angle):
        """
        Rotate around chi1 angle.
        """
        if not self.current_protein:
            return
        
        if self.current_aa:
            self.current_protein.protein.expand_rotamer(self.current_aa)
            self.current_aa.set_chi_angle(chi, angle)
            self.win.glpane.gl_update()

        return
    
    def _rotateChi1(self, angle):
        """
        Slot for Chi1 dial.
        """
        self._rotateChiAngle(0, angle)
        self.chi1Dial.updateValueLabel()
        return
    
    def _rotateChi2(self, angle):
        """
        Slot for Chi2 dial.
        """
        self._rotateChiAngle(1, angle)
        self.chi2Dial.updateValueLabel()
        return
        
    def _rotateChi3(self, angle):
        """
        Slot for Chi3 dial.
        """
        self._rotateChiAngle(2, angle)
        self.chi3Dial.updateValueLabel()
        return
        
    def _rotateChi4(self, angle):
        """
        Slot for Chi4 dial. 
        @note: this dial is currently hidden and unused.
        """
        self._rotateChiAngle(3, angle)
        return
   
    def _update_UI_do_updates(self):
        """
        Overrides superclass method. 
        
        @see: Command_PropertyManager._update_UI_do_updates()
        """
        
        self.current_protein = self.win.assy.getSelectedProteinChunk()
        
        if self.current_protein is self.previous_protein:
            if 0:
                print "Edit Protein: _update_UI_do_updates() - DO NOTHING."
            return
        
        # It is common that the user will unselect the current protein.
        # If so, set current_protein to previous_protein so that it 
        # (the previously selected protein) remains the current protein 
        # in the PM and sequence editor.
        if not self.current_protein:
            self.current_protein = self.previous_protein
            return
        
        # Update all PM widgets that need to be since something has changed.
        if 0:
            print "Edit Protein: _update_UI_do_updates() - UPDATING THE PMGR."
        self.update_name_field()
        self.update_length_field()
        self.sequenceEditor.updateSequence(proteinChunk = self.current_protein)
        self.update_residue_combobox()
        
        # NOTE: Changing the display style of the protein chunks can take some
        # time. We should put up the wait (hourglass) cursor and restore 
        # before returning.
        if self.previous_protein:
            self.previous_protein.setDisplayStyle(self.previous_protein_display_style)
            
        self.previous_protein = self.current_protein
        
        if self.current_protein:
            self.previous_protein_display_style = self.current_protein.getDisplayStyle()
            self.current_protein.setDisplayStyle(diPROTEIN)
            
        if self.current_protein:
            msg = "Editing structure <b>%s</b>." % self.current_protein.name
        else:
            msg = "Select a single structure to edit."
        self.updateMessage(msg)
        
        return
class EditRotamers_PropertyManager( PM_Dialog, DebugMenuMixin ):
    """
    The ProteinDisplayStyle_PropertyManager class provides a Property Manager 
    for the B{Display Style} command on the flyout toolbar in the 
    Build > Protein mode. 

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title         =  "Edit Rotamers"
    pmName        =  title
    iconPath      =  "ui/actions/Edit/EditProteinDisplayStyle.png"

    
    def __init__( self, parentCommand ):
        """
        Constructor for the property manager.
        """

        self.parentMode = parentCommand
        self.w = self.parentMode.w
        self.win = self.parentMode.w

        self.pw = self.parentMode.pw        
        self.o = self.win.glpane                 
        self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key]
        
        PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title)

        DebugMenuMixin._init1( self )

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Edit protein rotamers."
        self.updateMessage(msg)

    def connect_or_disconnect_signals(self, isConnect = True):
        
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect 
        
        change_connect(self.nextAAPushButton,
                       SIGNAL("clicked()"),
                       self._expandNextRotamer)

        change_connect(self.previousAAPushButton,
                       SIGNAL("clicked()"),
                       self._expandPreviousRotamer)
        
        change_connect(self.expandAllPushButton,
                       SIGNAL("clicked()"),
                       self._expandAllRotamers)
        
        change_connect(self.collapseAllPushButton,
                       SIGNAL("clicked()"),
                       self._collapseAllRotamers)
        
        self.connect( self.aminoAcidsComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self._aminoAcidChanged)
        
    #Protein Display methods         

    def ok_btn_clicked(self):
        """
        Slot for the OK button
        """
        self.win.toolsDone()

    def cancel_btn_clicked(self):
        """
        Slot for the Cancel button.
        """
        #TODO: Cancel button needs to be removed. See comment at the top
        self.win.toolsDone()

    def show(self):
        """
        Shows the Property Manager. Overrides PM_Dialog.show.
        """
        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.sequenceEditor.hide()
        PM_Dialog.show(self)

        # Update all PM widgets, then establish their signal-slot connections.
        # note: It is important to update the widgets *first* since doing
        # it in the reverse order will generate signals when updating
        # the PM widgets (via updateDnaDisplayStyleWidgets()), causing
        # unneccessary repaints of the model view.
        self.connect_or_disconnect_signals(isConnect = True)

    def close(self):
        """
        Closes the Property Manager. Overrides PM_Dialog.close.
        """
        self.connect_or_disconnect_signals(False)
        PM_Dialog.close(self)

    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox( self,
                                         title = "Position")
        self._loadGroupBox1( self._pmGroupBox1 )

        self._pmGroupBox2 = PM_GroupBox( self,
                                         title = "Rotamer")
        self._loadGroupBox2( self._pmGroupBox2 )


    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        aa_list = []
        for mol in self.win.assy.molecules:
            if mol.isProteinChunk():
                aa_list = mol.protein.get_amino_acid_id_list()
                break
            
        self.aminoAcidsComboBox = PM_ComboBox( pmGroupBox,
                                 label         =  "Residue:",
                                 choices       =  aa_list,
                                 setAsDefault  =  False)

        
        self.previousAAPushButton  = \
            PM_PushButton( pmGroupBox,
                         text         =  "Previous AA",
                         setAsDefault  =  True)
        
        self.nextAAPushButton  = \
            PM_PushButton( pmGroupBox,
                         text         =  "Next AA",
                         setAsDefault  =  True)
        
        self.recenterViewCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Re-center view",
                         setAsDefault  =  True,
                         state         = Qt.Checked)
        
        self.expandAllPushButton  = \
            PM_PushButton( pmGroupBox,
                         text         =  "Expand All",
                         setAsDefault  =  True)
        
        self.collapseAllPushButton  = \
            PM_PushButton( pmGroupBox,
                         text         =  "Collapse All",
                         setAsDefault  =  True)
        
    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        
        self.discreteStepsCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Use discrete steps",
                         setAsDefault  =  True,
                         state         = Qt.Unchecked)
        
        self.chi1SpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Chi1 angle:",
                              value         =  0.000,
                              setAsDefault  =  True,
                              minimum       =  -180.0,
                              maximum       =  180.0,
                              decimals      =  1,
                              singleStep    =  1.0, 
                              spanWidth = False)
        
        self.chi2SpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Chi2 angle:",
                              value         =  0.000,
                              setAsDefault  =  True,
                              minimum       =  -180.0,
                              maximum       =  180.0,
                              decimals      =  1,
                              singleStep    =  1.0, 
                              spanWidth = False)
        
        self.chi3SpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Chi3 angle:",
                              value         =  0.000,
                              setAsDefault  =  True,
                              minimum       =  -180.0,
                              maximum       =  180.0,
                              decimals      =  1,
                              singleStep    =  1.0, 
                              spanWidth = False)
        
    def _addWhatsThisText( self ):
        
        #from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditRotamers_PropertyManager
        #WhatsThis_EditRotamers_PropertyManager(self)
        pass
    
    def _addToolTipText(self):
        #from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager 
        #ToolTip_EditProteinDisplayStyle_PropertyManager(self)
        pass
    
    def _expandNextRotamer(self):
        """
        """
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.traverse_forward()
                self._display_and_recenter()
                self._updateAminoAcidInfo(
                    chunk.protein.get_current_amino_acid_index())
                return

    def _expandPreviousRotamer(self):
        """
        """
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.traverse_backward()
                self._display_and_recenter()
                self._updateAminoAcidInfo(
                    chunk.protein.get_current_amino_acid_index())
                return
        
    def _collapseAllRotamers(self):
        """
        """
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.collapse_all_rotamers()
                self.win.glpane.gl_update()
                return
        
    def _expandAllRotamers(self):
        """
        """
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.expand_all_rotamers()
                self.win.glpane.gl_update()
                return
        
    def _display_and_recenter(self):
        """
        """
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.collapse_all_rotamers()
                current_aa = chunk.protein.get_current_amino_acid()
                if current_aa:
                    chunk.protein.expand_rotamer(current_aa)
                    if self.recenterViewCheckBox.isChecked():
                        ca_atom = current_aa.get_c_alpha_atom()
                        if ca_atom:
                            self.win.glpane.pov = -ca_atom.posn()                            
                    #self.win.glpane.gl_update()
                    self.win.glpane.gl_update()
        
    def _updateAminoAcidInfo(self, index):
        """
        """
        self.aminoAcidsComboBox.setCurrentIndex(index)
        
    def _aminoAcidChanged(self, index):
        """
        """
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.set_current_amino_acid_index(index)
                self._display_and_recenter()
                
class BreakOrJoinStrands_PropertyManager(PM_Dialog, DebugMenuMixin):
    def __init__(self, parentCommand):
        """
        Constructor for the property manager.
        """

        self.parentMode = parentCommand
        self.w = self.parentMode.w
        self.win = self.parentMode.w
        self.pw = self.parentMode.pw
        self.o = self.win.glpane

        PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title)

        DebugMenuMixin._init1(self)

        self.showTopRowButtons(PM_DONE_BUTTON | PM_WHATS_THIS_BUTTON)
        return

    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot 
                          method. 
        @type  isConnect: boolean
        """
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        # DNA Strand arrowhead display options signal-slot connections.

        self._connect_checkboxes_to_global_prefs_keys(isConnect)

        change_connect(
            self.fivePrimeEndColorChooser, SIGNAL("editingFinished()"), self.chooseCustomColorOnFivePrimeEnds
        )

        change_connect(
            self.threePrimeEndColorChooser, SIGNAL("editingFinished()"), self.chooseCustomColorOnThreePrimeEnds
        )

        change_connect(
            self.strandFivePrimeArrowheadsCustomColorCheckBox,
            SIGNAL("toggled(bool)"),
            self.allowChoosingColorsOnFivePrimeEnd,
        )

        change_connect(
            self.strandThreePrimeArrowheadsCustomColorCheckBox,
            SIGNAL("toggled(bool)"),
            self.allowChoosingColorsOnThreePrimeEnd,
        )
        return

    def show(self):
        """
        Shows the Property Manager. Overrides PM_Dialog.show.
        """
        PM_Dialog.show(self)
        self.connect_or_disconnect_signals(isConnect=True)
        return

    def close(self):
        """
        Closes the Property Manager. Overrides PM_Dialog.close.
        """
        # this is important since these pref keys are used in other command modes
        # as well and we do not want to see the 5' end arrow in Inset DNA mode

        self.connect_or_disconnect_signals(False)
        PM_Dialog.close(self)

    def _connect_checkboxes_to_global_prefs_keys(self, isConnect=True):
        """
        #doc
        """
        if not isConnect:
            return

        # ORDER of items in tuples checkboxes and prefs_keys is IMPORTANT!
        checkboxes = (
            self.arrowsOnThreePrimeEnds_checkBox,
            self.arrowsOnFivePrimeEnds_checkBox,
            self.strandThreePrimeArrowheadsCustomColorCheckBox,
            self.strandFivePrimeArrowheadsCustomColorCheckBox,
            self.arrowsOnBackBones_checkBox,
        )

        prefs_keys = (
            self._prefs_key_arrowsOnThreePrimeEnds(),
            self._prefs_key_arrowsOnFivePrimeEnds(),
            self._prefs_key_useCustomColorForThreePrimeArrowheads(),
            self._prefs_key_useCustomColorForFivePrimeArrowheads(),
            arrowsOnBackBones_prefs_key,
        )

        for checkbox, prefs_key in zip(checkboxes, prefs_keys):
            connect_checkbox_with_boolean_pref(checkbox, prefs_key)

        return

    def ok_btn_clicked(self):
        """
        Slot for the OK button
        """
        self.win.toolsDone()
        return

    # Load various widgets ====================

    def _loadDisplayOptionsGroupBox(self, pmGroupBox):
        """
        Load widgets in the display options groupbox
        """
        title = "Arrowhead prefs in %s:" % self.parentMode.featurename
        self._arrowheadPrefsGroupBox = PM_GroupBox(pmGroupBox, title=title)
        # load all the options
        self._load3PrimeEndArrowAndCustomColor(self._arrowheadPrefsGroupBox)
        self._load5PrimeEndArrowAndCustomColor(self._arrowheadPrefsGroupBox)
        self._loadArrowOnBackBone(pmGroupBox)
        return

    def _load3PrimeEndArrowAndCustomColor(self, pmGroupBox):
        """
        Loads 3' end arrow head and custom color checkbox and color chooser dialog
        """
        self.pmGroupBox3 = PM_GroupBox(pmGroupBox, title="3' end:")

        self.arrowsOnThreePrimeEnds_checkBox = PM_CheckBox(
            self.pmGroupBox3, text="Show arrowhead", widgetColumn=0, setAsDefault=True, spanWidth=True
        )

        prefs_key = self._prefs_key_arrowsOnThreePrimeEnds()
        if env.prefs[prefs_key]:
            self.arrowsOnThreePrimeEnds_checkBox.setCheckState(Qt.Checked)
        else:
            self.arrowsOnThreePrimeEnds_checkBox.setCheckState(Qt.Unchecked)

        self.strandThreePrimeArrowheadsCustomColorCheckBox = PM_CheckBox(
            self.pmGroupBox3, text="Display custom color", widgetColumn=0, setAsDefault=True, spanWidth=True
        )
        prefs_key = self._prefs_key_dnaStrandThreePrimeArrowheadsCustomColor()
        self.threePrimeEndColorChooser = PM_ColorComboBox(self.pmGroupBox3, color=env.prefs[prefs_key])

        prefs_key = self._prefs_key_useCustomColorForThreePrimeArrowheads()
        if env.prefs[prefs_key]:
            self.strandThreePrimeArrowheadsCustomColorCheckBox.setCheckState(Qt.Checked)
            self.threePrimeEndColorChooser.show()
        else:
            self.strandThreePrimeArrowheadsCustomColorCheckBox.setCheckState(Qt.Unchecked)
            self.threePrimeEndColorChooser.hide()

        return

    def _load5PrimeEndArrowAndCustomColor(self, pmGroupBox):
        """
        Loads 5' end custom color checkbox and color chooser dialog
        """
        self.pmGroupBox2 = PM_GroupBox(pmGroupBox, title="5' end:")
        self.arrowsOnFivePrimeEnds_checkBox = PM_CheckBox(
            self.pmGroupBox2, text="Show arrowhead", widgetColumn=0, setAsDefault=True, spanWidth=True
        )

        prefs_key = self._prefs_key_arrowsOnFivePrimeEnds()
        if env.prefs[prefs_key]:
            self.arrowsOnFivePrimeEnds_checkBox.setCheckState(Qt.Checked)
        else:
            self.arrowsOnFivePrimeEnds_checkBox.setCheckState(Qt.Unchecked)

        self.strandFivePrimeArrowheadsCustomColorCheckBox = PM_CheckBox(
            self.pmGroupBox2, text="Display custom color", widgetColumn=0, setAsDefault=True, spanWidth=True
        )

        prefs_key = self._prefs_key_dnaStrandFivePrimeArrowheadsCustomColor()
        self.fivePrimeEndColorChooser = PM_ColorComboBox(self.pmGroupBox2, color=env.prefs[prefs_key])

        prefs_key = self._prefs_key_useCustomColorForFivePrimeArrowheads()
        if env.prefs[prefs_key]:
            self.strandFivePrimeArrowheadsCustomColorCheckBox.setCheckState(Qt.Checked)
            self.fivePrimeEndColorChooser.show()
        else:
            self.strandFivePrimeArrowheadsCustomColorCheckBox.setCheckState(Qt.Unchecked)
            self.fivePrimeEndColorChooser.hide()

        return

    def _loadArrowOnBackBone(self, pmGroupBox):
        """
        Loads Arrow on the backbone checkbox
        """
        self.pmGroupBox4 = PM_GroupBox(pmGroupBox, title="Global preference:")
        self.arrowsOnBackBones_checkBox = PM_CheckBox(
            self.pmGroupBox4, text="Show arrows on back bones", widgetColumn=0, setAsDefault=True, spanWidth=True
        )

        prefs_key = arrowsOnBackBones_prefs_key
        if env.prefs[prefs_key] == True:
            self.arrowsOnBackBones_checkBox.setCheckState(Qt.Checked)
        else:
            self.arrowsOnBackBones_checkBox.setCheckState(Qt.Unchecked)
        return

    def allowChoosingColorsOnFivePrimeEnd(self, state):
        """
        Show or hide color chooser based on the 
        strandFivePrimeArrowheadsCustomColorCheckBox's state
        """
        if self.strandFivePrimeArrowheadsCustomColorCheckBox.isChecked():
            self.fivePrimeEndColorChooser.show()
        else:
            self.fivePrimeEndColorChooser.hide()
        return

    def allowChoosingColorsOnThreePrimeEnd(self, state):
        """
        Show or hide color chooser based on the 
        strandThreePrimeArrowheadsCustomColorCheckBox's state
        """
        if self.strandThreePrimeArrowheadsCustomColorCheckBox.isChecked():
            self.threePrimeEndColorChooser.show()
        else:
            self.threePrimeEndColorChooser.hide()
        return

    def chooseCustomColorOnThreePrimeEnds(self):
        """
        Choose custom color for 3' ends
        """
        color = self.threePrimeEndColorChooser.getColor()
        prefs_key = self._prefs_key_dnaStrandThreePrimeArrowheadsCustomColor()
        env.prefs[prefs_key] = color
        self.win.glpane.gl_update()
        return

    def chooseCustomColorOnFivePrimeEnds(self):
        """
        Choose custom color for 5' ends
        """
        color = self.fivePrimeEndColorChooser.getColor()
        prefs_key = self._prefs_key_dnaStrandFivePrimeArrowheadsCustomColor()
        env.prefs[prefs_key] = color
        self.win.glpane.gl_update()
        return

    # Return varius prefs_keys for arrowhead display options ui elements =======
    def _prefs_key_arrowsOnThreePrimeEnds(self):
        """
        Return the appropriate KEY of the preference for whether to
        draw arrows on 3' strand ends of PAM DNA.
        """
        return arrowsOnThreePrimeEnds_prefs_key

    def _prefs_key_arrowsOnFivePrimeEnds(self):
        """
        Return the appropriate KEY of the preference for whether to
        draw arrows on 5' strand ends of PAM DNA.
        """
        return arrowsOnFivePrimeEnds_prefs_key

    def _prefs_key_useCustomColorForThreePrimeArrowheads(self):
        """
        Return the appropriate KEY of the preference for whether to use a
        custom color for 3' arrowheads (if they are drawn)
        or for 3' strand end atoms (if arrowheads are not drawn)
        """
        return useCustomColorForThreePrimeArrowheads_prefs_key

    def _prefs_key_useCustomColorForFivePrimeArrowheads(self):
        """
        Return the appropriate KEY of the preference for whether to use a
        custom color for 5' arrowheads (if they are drawn)
        or for 5' strand end atoms (if arrowheads are not drawn).        
        """
        return useCustomColorForFivePrimeArrowheads_prefs_key

    def _prefs_key_dnaStrandThreePrimeArrowheadsCustomColor(self):
        """
        Return the appropriate KEY of the preference for what custom color
        to use when drawing 3' arrowheads (if they are drawn)
        or 3' strand end atoms (if arrowheads are not drawn).
        """
        return dnaStrandThreePrimeArrowheadsCustomColor_prefs_key

    def _prefs_key_dnaStrandFivePrimeArrowheadsCustomColor(self):
        """
        Return the appropriate KEY of the preference for what custom color
        to use when drawing 5' arrowheads (if they are drawn)
        or 5' strand end atoms (if arrowheads are not drawn).
        """
        return dnaStrandFivePrimeArrowheadsCustomColor_prefs_key
Ejemplo n.º 14
0
class EditRotamers_PropertyManager(PM_Dialog, DebugMenuMixin):
    """
    The ProteinDisplayStyle_PropertyManager class provides a Property Manager 
    for the B{Display Style} command on the flyout toolbar in the 
    Build > Protein mode. 

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title = "Edit Rotamers"
    pmName = title
    iconPath = "ui/actions/Edit/EditProteinDisplayStyle.png"

    def __init__(self, parentCommand):
        """
        Constructor for the property manager.
        """

        self.parentMode = parentCommand
        self.w = self.parentMode.w
        self.win = self.parentMode.w

        self.pw = self.parentMode.pw
        self.o = self.win.glpane
        self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key]

        PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title)

        DebugMenuMixin._init1(self)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Edit protein rotamers."
        self.updateMessage(msg)

    def connect_or_disconnect_signals(self, isConnect=True):

        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self.nextAAPushButton, SIGNAL("clicked()"),
                       self._expandNextRotamer)

        change_connect(self.previousAAPushButton, SIGNAL("clicked()"),
                       self._expandPreviousRotamer)

        change_connect(self.expandAllPushButton, SIGNAL("clicked()"),
                       self._expandAllRotamers)

        change_connect(self.collapseAllPushButton, SIGNAL("clicked()"),
                       self._collapseAllRotamers)

        self.connect(self.aminoAcidsComboBox,
                     SIGNAL("currentIndexChanged(int)"),
                     self._aminoAcidChanged)

    #Protein Display methods

    def ok_btn_clicked(self):
        """
        Slot for the OK button
        """
        self.win.toolsDone()

    def cancel_btn_clicked(self):
        """
        Slot for the Cancel button.
        """
        #TODO: Cancel button needs to be removed. See comment at the top
        self.win.toolsDone()

    def show(self):
        """
        Shows the Property Manager. Overrides PM_Dialog.show.
        """
        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.sequenceEditor.hide()
        PM_Dialog.show(self)

        # Update all PM widgets, then establish their signal-slot connections.
        # note: It is important to update the widgets *first* since doing
        # it in the reverse order will generate signals when updating
        # the PM widgets (via updateDnaDisplayStyleWidgets()), causing
        # unneccessary repaints of the model view.
        self.connect_or_disconnect_signals(isConnect=True)

    def close(self):
        """
        Closes the Property Manager. Overrides PM_Dialog.close.
        """
        self.connect_or_disconnect_signals(False)
        PM_Dialog.close(self)

    def _addGroupBoxes(self):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox(self, title="Position")
        self._loadGroupBox1(self._pmGroupBox1)

        self._pmGroupBox2 = PM_GroupBox(self, title="Rotamer")
        self._loadGroupBox2(self._pmGroupBox2)

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        aa_list = []
        for mol in self.win.assy.molecules:
            if mol.isProteinChunk():
                aa_list = mol.protein.get_amino_acid_id_list()
                break

        self.aminoAcidsComboBox = PM_ComboBox(pmGroupBox,
                                              label="Residue:",
                                              choices=aa_list,
                                              setAsDefault=False)


        self.previousAAPushButton  = \
            PM_PushButton( pmGroupBox,
                         text         =  "Previous AA",
                         setAsDefault  =  True)

        self.nextAAPushButton  = \
            PM_PushButton( pmGroupBox,
                         text         =  "Next AA",
                         setAsDefault  =  True)

        self.recenterViewCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Re-center view",
                         setAsDefault  =  True,
                         state         = Qt.Checked)

        self.expandAllPushButton  = \
            PM_PushButton( pmGroupBox,
                         text         =  "Expand All",
                         setAsDefault  =  True)

        self.collapseAllPushButton  = \
            PM_PushButton( pmGroupBox,
                         text         =  "Collapse All",
                         setAsDefault  =  True)

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        self.discreteStepsCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Use discrete steps",
                         setAsDefault  =  True,
                         state         = Qt.Unchecked)

        self.chi1SpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Chi1 angle:",
                              value         =  0.000,
                              setAsDefault  =  True,
                              minimum       =  -180.0,
                              maximum       =  180.0,
                              decimals      =  1,
                              singleStep    =  1.0,
                              spanWidth = False)

        self.chi2SpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Chi2 angle:",
                              value         =  0.000,
                              setAsDefault  =  True,
                              minimum       =  -180.0,
                              maximum       =  180.0,
                              decimals      =  1,
                              singleStep    =  1.0,
                              spanWidth = False)

        self.chi3SpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Chi3 angle:",
                              value         =  0.000,
                              setAsDefault  =  True,
                              minimum       =  -180.0,
                              maximum       =  180.0,
                              decimals      =  1,
                              singleStep    =  1.0,
                              spanWidth = False)

    def _addWhatsThisText(self):

        #from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditRotamers_PropertyManager
        #WhatsThis_EditRotamers_PropertyManager(self)
        pass

    def _addToolTipText(self):
        #from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager
        #ToolTip_EditProteinDisplayStyle_PropertyManager(self)
        pass

    def _expandNextRotamer(self):
        """
        """
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.traverse_forward()
                self._display_and_recenter()
                self._updateAminoAcidInfo(
                    chunk.protein.get_current_amino_acid_index())
                return

    def _expandPreviousRotamer(self):
        """
        """
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.traverse_backward()
                self._display_and_recenter()
                self._updateAminoAcidInfo(
                    chunk.protein.get_current_amino_acid_index())
                return

    def _collapseAllRotamers(self):
        """
        """
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.collapse_all_rotamers()
                self.win.glpane.gl_update()
                return

    def _expandAllRotamers(self):
        """
        """
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.expand_all_rotamers()
                self.win.glpane.gl_update()
                return

    def _display_and_recenter(self):
        """
        """
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.collapse_all_rotamers()
                current_aa = chunk.protein.get_current_amino_acid()
                if current_aa:
                    chunk.protein.expand_rotamer(current_aa)
                    if self.recenterViewCheckBox.isChecked():
                        ca_atom = current_aa.get_c_alpha_atom()
                        if ca_atom:
                            self.win.glpane.pov = -ca_atom.posn()
                    #self.win.glpane.gl_update()
                    self.win.glpane.gl_update()

    def _updateAminoAcidInfo(self, index):
        """
        """
        self.aminoAcidsComboBox.setCurrentIndex(index)

    def _aminoAcidChanged(self, index):
        """
        """
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.set_current_amino_acid_index(index)
                self._display_and_recenter()
class StereoProperties_PropertyManager(Command_PropertyManager):
    """
    The StereoProperties_PropertyManager class provides a Property Manager 
    for the Stereo View command. 

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title         =  "Stereo View"
    pmName        =  title
    iconPath      =  "ui/actions/View/Stereo_View.png"


    def __init__( self, command ):
        """
        Constructor for the property manager.
        """
        
        _superclass.__init__(self, command)
      
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Modify the Stereo View settings below."

        self.updateMessage(msg)
        
                   

    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot 
                          method. 
        @type  isConnect: boolean
        """
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect 

        change_connect(self.stereoEnabledCheckBox, 
                       SIGNAL("toggled(bool)"), 
                       self._enableStereo ) 

        change_connect( self.stereoModeComboBox,
                        SIGNAL("currentIndexChanged(int)"),
                        self._stereoModeComboBoxChanged )

        change_connect(self.stereoSeparationSlider,
                       SIGNAL("valueChanged(int)"),
                       self._stereoModeSeparationSliderChanged )

        change_connect(self.stereoAngleSlider,
                       SIGNAL("valueChanged(int)"),
                       self._stereoModeAngleSliderChanged )

 
    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox( self, 
                                         title = "Settings")
        self._loadGroupBox1( self._pmGroupBox1 )

        #@ self._pmGroupBox1.hide()

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        #stereoSettingsGroupBox = PM_GroupBox( None )

        self.stereoEnabledCheckBox = \
            PM_CheckBox(pmGroupBox,
                        text         = 'Enable Stereo View',
                        widgetColumn = 1
                        )        

        stereoModeChoices = ['Relaxed view', 
                             'Cross-eyed view',
                             'Red/blue anaglyphs',
                             'Red/cyan anaglyphs',
                             'Red/green anaglyphs']

        self.stereoModeComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Stereo Mode:", 
                         choices       =  stereoModeChoices,
                         setAsDefault  =  True)

        self.stereoModeComboBox.setCurrentIndex(env.prefs[stereoViewMode_prefs_key]-1)
            
        self.stereoSeparationSlider =  \
            PM_Slider( pmGroupBox,
                       currentValue = 50,
                       minimum      = 0,
                       maximum      = 300,
                       label        = 'Separation'
                       )        

        self.stereoSeparationSlider.setValue(env.prefs[stereoViewSeparation_prefs_key])

        self.stereoAngleSlider =  \
            PM_Slider( pmGroupBox,
                       currentValue = 50,
                       minimum      = 0,
                       maximum      = 100,
                       label        = 'Angle'
                       )

        self.stereoAngleSlider.setValue(env.prefs[stereoViewAngle_prefs_key])

        self._updateWidgets()
                
    def _addWhatsThisText( self ):
        """
        What's This text for widgets in the Stereo Property Manager.  
        """
        pass

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the Stereo Property Manager.  
        """
        pass

    def _enableStereo(self, enabled):
        """
        Enable stereo view.
        """
        glpane = self.o
        if glpane:
            glpane.set_stereo_enabled( enabled)
            # switch to perspective mode
            if enabled:
                # store current projection mode
                glpane.__StereoProperties_last_ortho = glpane.ortho
                if glpane.ortho:
                    # dont use glpane.setViewProjection
                    # because we don't want to modify 
                    # default projection setting 
                    glpane.ortho = 0 
            else:
                # restore default mode
                if hasattr(glpane, "__StereoProperties_last_ortho"):
                    projection = glpane.__StereoProperties_last_ortho
                    if glpane.ortho != projection:
                        glpane.ortho = projection

            self._updateWidgets()
                    
            glpane.gl_update()
            
    def _stereoModeComboBoxChanged(self, mode):
        """
        Change stereo mode.
        
        @param mode: stereo mode (0=relaxed, 1=cross-eyed, 2=red/blue,
        3=red/cyan, 4=red/green)
        @type value: int
        """
        env.prefs[stereoViewMode_prefs_key] = mode + 1

        self._updateSeparationSlider()
        
    def _stereoModeSeparationSliderChanged(self, value):
        """
        Change stereo view separation.
        
        @param value: separation (0..300)
        @type value: int
        """
        env.prefs[stereoViewSeparation_prefs_key] = value

    def _stereoModeAngleSliderChanged(self, value):
        """
        Change stereo view angle.
        
        @param value: stereo angle (0..100)
        @type value: int
        """
        env.prefs[stereoViewAngle_prefs_key] = value

    def _updateSeparationSlider(self):
        """ 
        Update the separation slider widget.
        """
        if self.stereoModeComboBox.currentIndex() >= 2: 
            # for anaglyphs disable the separation slider 
            self.stereoSeparationSlider.setEnabled(False)
        else:
            # otherwise, enable the separation slider
            self.stereoSeparationSlider.setEnabled(True)

    def _updateWidgets(self):
        """
        Update stereo PM widgets.
        """
        if self.stereoEnabledCheckBox.isChecked():
            self.stereoModeComboBox.setEnabled(True)
            self.stereoSeparationSlider.setEnabled(True)
            self.stereoAngleSlider.setEnabled(True)
            self._updateSeparationSlider()
        else:
            self.stereoModeComboBox.setEnabled(False)
            self.stereoSeparationSlider.setEnabled(False)
            self.stereoAngleSlider.setEnabled(False)
class PlanePropertyManager(EditCommand_PM):
    """
    The PlanePropertyManager class provides a Property Manager for a
    (reference) Plane.

    """

    # The title that appears in the Property Manager header.
    title = "Plane"
    # The name of this Property Manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    # The relative path to the PNG file that appears in the header
    iconPath = "ui/actions/Insert/Reference Geometry/Plane.png"

    def __init__(self, command):
        """
        Construct the Plane Property Manager.

        @param plane: The plane.
        @type  plane: L{Plane}
        """

        #see self.connect_or_disconnect_signals for comment about this flag
        self.isAlreadyConnected = False
        self.isAlreadyDisconnected = False

        self.gridColor = black
        self.gridXSpacing = 4.0
        self.gridYSpacing = 4.0
        self.gridLineType = 3
        self.displayLabels = False
        self.originLocation = PLANE_ORIGIN_LOWER_LEFT
        self.displayLabelStyle = LABELS_ALONG_ORIGIN

        EditCommand_PM.__init__( self, command)

        # Hide Preview and Restore defaults buttons
        self.hideTopRowButtons(PM_RESTORE_DEFAULTS_BUTTON)


    def _addGroupBoxes(self):
        """
        Add the 1st group box to the Property Manager.
        """
        # Placement Options radio button list to create radio button list.
        # Format: buttonId, buttonText, tooltip
        PLACEMENT_OPTIONS_BUTTON_LIST = [ \
            ( 0, "Parallel to screen",     "Parallel to screen"     ),
            ( 1, "Through selected atoms", "Through selected atoms" ),
            ( 2, "Offset to a plane",      "Offset to a plane"      ),
            ( 3, "Custom",                 "Custom"                 )
        ]

        self.pmPlacementOptions = \
            PM_RadioButtonList( self,
                                title      = "Placement Options",
                                buttonList = PLACEMENT_OPTIONS_BUTTON_LIST,
                                checkedId  = 3 )

        self.pmGroupBox1 = PM_GroupBox(self, title = "Parameters")
        self._loadGroupBox1(self.pmGroupBox1)

        #image groupbox
        self.pmGroupBox2 = PM_GroupBox(self, title = "Image")
        self._loadGroupBox2(self.pmGroupBox2)

        #grid plane groupbox
        self.pmGroupBox3 = PM_GroupBox(self, title = "Grid")
        self._loadGroupBox3(self.pmGroupBox3)

    def _loadGroupBox3(self, pmGroupBox):
        """
        Load widgets in the grid plane group box.

        @param pmGroupBox: The grid  group box in the PM.
        @type  pmGroupBox: L{PM_GroupBox}
        """
        self.gridPlaneCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Show grid",
                         widgetColumn  = 0,
                         setAsDefault = True,
                         spanWidth = True
                         )

        connect_checkbox_with_boolean_pref(
            self.gridPlaneCheckBox ,
            PlanePM_showGrid_prefs_key)


        self.gpXSpacingDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "X Spacing:",
                              value         =  4.000,
                              setAsDefault  =  True,
                              minimum       =  1.00,
                              maximum       =  200.0,
                              decimals      =  3,
                              singleStep    =  1.0,
                              spanWidth = False)

        self.gpYSpacingDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Y Spacing:",
                              value         =  4.000,
                              setAsDefault  =  True,
                              minimum       =  1.00,
                              maximum       =  200.0,
                              decimals      =  3,
                              singleStep    =  1.0,
                              spanWidth = False)

        lineTypeChoices = [ 'Dotted (default)',
                            'Dashed',
                            'Solid' ]

        self.gpLineTypeComboBox = \
            PM_ComboBox( pmGroupBox ,
                         label         =  "Line type:",
                         choices       =  lineTypeChoices,
                         setAsDefault  =  True)

        hhColorList = [ black, orange, red, magenta,
                        cyan, blue, white, yellow, gray ]
        hhColorNames = [ "Black (default)", "Orange", "Red", "Magenta",
                         "Cyan", "Blue", "White", "Yellow", "Other color..." ]

        self.gpColorTypeComboBox = \
            PM_ColorComboBox( pmGroupBox,
                              colorList = hhColorList,
                              colorNames = hhColorNames,
                              color = black )

        self.pmGroupBox5 = PM_GroupBox( pmGroupBox )

        self.gpDisplayLabels =\
            PM_CheckBox( self.pmGroupBox5,
                         text         = "Display labels",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True )

        originChoices = [ 'Lower left (default)',
                          'Upper left',
                          'Lower right',
                          'Upper right' ]

        self.gpOriginComboBox = \
            PM_ComboBox( self.pmGroupBox5 ,
                         label         =  "Origin:",
                         choices       =  originChoices,
                         setAsDefault  =  True )

        positionChoices = [ 'Origin axes (default)',
                            'Plane perimeter' ]

        self.gpPositionComboBox = \
            PM_ComboBox( self.pmGroupBox5 ,
                         label         =  "Position:",
                         choices       =  positionChoices,
                         setAsDefault  =  True)

        self._showHideGPWidgets()

        if env.prefs[PlanePM_showGridLabels_prefs_key]:
            self.displayLabels = True
            self.gpOriginComboBox.setEnabled( True )
            self.gpPositionComboBox.setEnabled( True )
        else:
            self.displayLabels = False
            self.gpOriginComboBox.setEnabled( False )
            self.gpPositionComboBox.setEnabled( False )

        return

    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot
                          method.
        @type  isConnect: boolean
        """
        #TODO: Fix for bug: When you invoke a temporary mode
        # entering such a temporary mode keeps the signals of
        #PM from the previous mode connected (
        #but while exiting that temporary mode and reentering the
        #previous mode, it actually reconnects the signal! This gives rise to
        #lots  of bugs. This needs more general fix in Temporary mode API.
        # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py

        #UPDATE: (comment copied and modifief from BuildNanotube_PropertyManager.
        #The general problem still remains -- Ninad 2008-06-25

        if isConnect and self.isAlreadyConnected:
            if debug_flags.atom_debug:
                print_compact_stack("warning: attempt to connect widgets"\
                                    "in this PM that are already connected." )
            return

        if not isConnect and self.isAlreadyDisconnected:
            if debug_flags.atom_debug:
                print_compact_stack("warning: attempt to disconnect widgets"\
                                    "in this PM that are already disconnected.")
            return

        self.isAlreadyConnected = isConnect
        self.isAlreadyDisconnected = not isConnect

        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self.pmPlacementOptions.buttonGroup,
                       SIGNAL("buttonClicked(int)"),
                       self.changePlanePlacement)

        change_connect(self.widthDblSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.change_plane_width)

        change_connect(self.heightDblSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.change_plane_height)

        change_connect(self.aspectRatioCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self._enableAspectRatioSpinBox)


        #signal slot connection for imageDisplayCheckBox
        change_connect(self.imageDisplayCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self.toggleFileChooserBehavior)

        #signal slot connection for imageDisplayFileChooser
        change_connect(self.imageDisplayFileChooser.lineEdit,
                       SIGNAL("editingFinished()"),
                       self.update_imageFile)

        #signal slot connection for heightfieldDisplayCheckBox
        change_connect(self.heightfieldDisplayCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self.toggleHeightfield)

        #signal slot connection for heightfieldHQDisplayCheckBox
        change_connect(self.heightfieldHQDisplayCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self.toggleHeightfieldHQ)

        #signal slot connection for heightfieldTextureCheckBox
        change_connect(self.heightfieldTextureCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self.toggleTexture)

        #signal slot connection for vScaleSpinBox
        change_connect(self.vScaleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.change_vertical_scale)

        change_connect(self.plusNinetyButton,
                       SIGNAL("clicked()"),
                       self.rotate_90)

        change_connect(self.minusNinetyButton,
                       SIGNAL("clicked()"),
                       self.rotate_neg_90)

        change_connect(self.flipButton,
                       SIGNAL("clicked()"),
                       self.flip_image)

        change_connect(self.mirrorButton,
                       SIGNAL("clicked()"),
                       self.mirror_image)

        change_connect(self.gridPlaneCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self.displayGridPlane)

        change_connect(self.gpXSpacingDoubleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.changeXSpacingInGP)

        change_connect(self.gpYSpacingDoubleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.changeYSpacingInGP)

        change_connect( self.gpLineTypeComboBox,
                        SIGNAL("currentIndexChanged(int)"),
                        self.changeLineTypeInGP )

        change_connect( self.gpColorTypeComboBox,
                        SIGNAL("editingFinished()"),
                        self.changeColorTypeInGP )

        change_connect( self.gpDisplayLabels,
                        SIGNAL("stateChanged(int)"),
                        self.displayLabelsInGP )

        change_connect( self.gpOriginComboBox,
                        SIGNAL("currentIndexChanged(int)"),
                        self.changeOriginInGP )

        change_connect( self.gpPositionComboBox,
                        SIGNAL("currentIndexChanged(int)"),
                        self.changePositionInGP )

        self._connect_checkboxes_to_global_prefs_keys()

        return

    def _connect_checkboxes_to_global_prefs_keys(self):
        """
        """
        connect_checkbox_with_boolean_pref(
            self.gridPlaneCheckBox ,
            PlanePM_showGrid_prefs_key)

        connect_checkbox_with_boolean_pref(
            self.gpDisplayLabels,
            PlanePM_showGridLabels_prefs_key)


    def changePositionInGP(self, idx):
        """
        Change Display of origin Labels (choices are along origin edges or along
        the plane perimeter.
        @param idx: Current index of the change grid label position combo box
        @type idx: int
        """
        if idx == 0:
            self.displayLabelStyle = LABELS_ALONG_ORIGIN
        elif idx == 1:
            self.displayLabelStyle = LABELS_ALONG_PLANE_EDGES
        else:
            print "Invalid index", idx
        return

    def changeOriginInGP(self, idx):
        """
        Change Display of origin Labels based on the location of the origin
        @param idx: Current index of the change origin position combo box
        @type idx: int
        """
        if idx == 0:
            self.originLocation = PLANE_ORIGIN_LOWER_LEFT
        elif idx ==1:
            self.originLocation = PLANE_ORIGIN_UPPER_LEFT
        elif idx == 2:
            self.originLocation = PLANE_ORIGIN_LOWER_RIGHT
        elif idx == 3:
            self.originLocation = PLANE_ORIGIN_UPPER_RIGHT
        else:
            print "Invalid index", idx
        return

    def displayLabelsInGP(self, state):
        """
        Choose to show or hide grid labels
        @param state: State of the Display Label Checkbox
        @type state: boolean
        """
        if env.prefs[PlanePM_showGridLabels_prefs_key]:
            self.gpOriginComboBox.setEnabled(True)
            self.gpPositionComboBox.setEnabled(True)
            self.displayLabels = True
            self.originLocation = PLANE_ORIGIN_LOWER_LEFT
            self.displayLabelStyle = LABELS_ALONG_ORIGIN
        else:
            self.gpOriginComboBox.setEnabled(False)
            self.gpPositionComboBox.setEnabled(False)
            self.displayLabels = False
        return

    def changeColorTypeInGP(self):
        """
        Change Color of grid
        """
        self.gridColor = self.gpColorTypeComboBox.getColor()
        return

    def changeLineTypeInGP(self, idx):
        """
        Change line type in grid
        @param idx: Current index of the Line type combo box
        @type idx: int
        """
        #line_type for actually drawing the grid is: 0=None, 1=Solid, 2=Dashed" or 3=Dotted
        if idx == 0:
            self.gridLineType = 3
        if idx == 1:
            self.gridLineType = 2
        if idx == 2:
            self.gridLineType = 1
        return

    def changeYSpacingInGP(self, val):
        """
        Change Y spacing on the grid
        @param val:value of Y spacing
        @type val: double
        """
        self.gridYSpacing = float(val)
        return

    def changeXSpacingInGP(self, val):
        """
        Change X spacing on the grid
        @param val:value of X spacing
        @type val: double
        """
        self.gridXSpacing = float(val)
        return

    def displayGridPlane(self, state):
        """
        Display or hide grid based on the state of the checkbox
        @param state: State of the Display Label Checkbox
        @type state: boolean
        """
        self._showHideGPWidgets()
        if self.gridPlaneCheckBox.isChecked():
            env.prefs[PlanePM_showGrid_prefs_key] = True
            self._makeGridPlane()
        else:
            env.prefs[PlanePM_showGrid_prefs_key] = False

        return

    def _makeGridPlane(self):
        """
        Show grid on the plane
        """
        #get all the grid related values in here
        self.gridXSpacing = float(self.gpXSpacingDoubleSpinBox.value())
        self.gridYSpacing = float(self.gpYSpacingDoubleSpinBox.value())

        #line_type for actually drawing the grid is: 0=None, 1=Solid, 2=Dashed" or 3=Dotted
        idx = self.gpLineTypeComboBox.currentIndex()
        self.changeLineTypeInGP(idx)
        self.gridColor = self.gpColorTypeComboBox.getColor()

        return


    def _showHideGPWidgets(self):
        """
        Enable Disable grid related widgets based on the state of the show grid
        checkbox.
        """
        if self.gridPlaneCheckBox.isChecked():
            self.gpXSpacingDoubleSpinBox.setEnabled(True)
            self.gpYSpacingDoubleSpinBox.setEnabled(True)
            self.gpLineTypeComboBox.setEnabled(True)
            self.gpColorTypeComboBox.setEnabled(True)
            self.gpDisplayLabels.setEnabled(True)
        else:
            self.gpXSpacingDoubleSpinBox.setEnabled(False)
            self.gpXSpacingDoubleSpinBox.setEnabled(False)
            self.gpYSpacingDoubleSpinBox.setEnabled(False)
            self.gpLineTypeComboBox.setEnabled(False)
            self.gpColorTypeComboBox.setEnabled(False)
            self.gpDisplayLabels.setEnabled(False)
        return

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in the image group box.

        @param pmGroupBox: The image group box in the PM.
        @type  pmGroupBox: L{PM_GroupBox}
        """
        self.imageDisplayCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Display image",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.imageDisplayFileChooser = \
            PM_FileChooser(pmGroupBox,
                           label     = 'Image file:',
                           text      = '' ,
                           spanWidth = True,
                           filter    = "PNG (*.png);;"\
                           "All Files (*.*)"
                           )
        self.imageDisplayFileChooser.setEnabled(False)
        # add change image properties button

        BUTTON_LIST = [
            ( "QToolButton", 1,  "+90",
              "ui/actions/Properties Manager/RotateImage+90.png",
              "+90", "", 0),
            ( "QToolButton", 2,  "-90",
              "ui/actions/Properties Manager/RotateImage-90.png",
              "-90", "", 1),
            ( "QToolButton", 3,  "FLIP",
              "ui/actions/Properties Manager/FlipImageVertical.png",
              "Flip", "", 2),
            ( "QToolButton", 4,  "MIRROR",
              "ui/actions/Properties Manager/FlipImageHorizontal.png",
              "Mirror", "", 3)
        ]

        #image change button groupbox
        self.pmGroupBox2 = PM_GroupBox(pmGroupBox, title = "Modify Image")

        self.imageChangeButtonGroup = \
            PM_ToolButtonRow( self.pmGroupBox2,
                              title        = "",
                              buttonList   = BUTTON_LIST,
                              spanWidth    = True,
                              isAutoRaise  = False,
                              isCheckable  = False,
                              setAsDefault = True,
                              )

        self.imageChangeButtonGroup.buttonGroup.setExclusive(False)

        self.plusNinetyButton  = self.imageChangeButtonGroup.getButtonById(1)
        self.minusNinetyButton    = self.imageChangeButtonGroup.getButtonById(2)
        self.flipButton = self.imageChangeButtonGroup.getButtonById(3)
        self.mirrorButton   = self.imageChangeButtonGroup.getButtonById(4)

        # buttons enabled when a valid image is loaded
        self.mirrorButton.setEnabled(False)
        self.plusNinetyButton.setEnabled(False)
        self.minusNinetyButton.setEnabled(False)
        self.flipButton.setEnabled(False)

        self.heightfieldDisplayCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Create 3D relief",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.heightfieldHQDisplayCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "High quality",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.heightfieldTextureCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Use texture",
                         widgetColumn  = 0,
                         state        = Qt.Checked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.vScaleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label        = " Vertical scale:",
                             value        = 1.0,
                             setAsDefault = True,
                             minimum      = -1000.0, # -1000 A
                             maximum      =  1000.0, # 1000 A
                             singleStep   = 0.1,
                             decimals     = 1,
                             suffix       = ' Angstroms')

        self.heightfieldDisplayCheckBox.setEnabled(False)
        self.heightfieldHQDisplayCheckBox.setEnabled(False)
        self.heightfieldTextureCheckBox.setEnabled(False)
        self.vScaleSpinBox.setEnabled(False)




    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in 1st group box.

        @param pmGroupBox: The 1st group box in the PM.
        @type  pmGroupBox: L{PM_GroupBox}
        """

        self.widthDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label        = "Width:",
                             value        = 16.0,
                             setAsDefault = True,
                             minimum      = 1.0,
                             maximum      = 10000.0, # 1000 nm
                             singleStep   = 1.0,
                             decimals     = 1,
                             suffix       = ' Angstroms')



        self.heightDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label        =" Height:",
                             value        = 16.0,
                             setAsDefault = True,
                             minimum      = 1.0,
                             maximum      = 10000.0, # 1000 nm
                             singleStep   = 1.0,
                             decimals     = 1,
                             suffix       = ' Angstroms')



        self.aspectRatioCheckBox = \
            PM_CheckBox(pmGroupBox,
                        text         = 'Maintain Aspect Ratio of:' ,
                        widgetColumn = 1,
                        state        = Qt.Unchecked
                        )


        self.aspectRatioSpinBox = \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "",
                              value         =  1.0,
                              setAsDefault  =  True,
                              minimum       =  0.1,
                              maximum       =  10.0,
                              singleStep    =  0.1,
                              decimals      =  2,
                              suffix        =  " to 1.00")

        if self.aspectRatioCheckBox.isChecked():
            self.aspectRatioSpinBox.setEnabled(True)
        else:
            self.aspectRatioSpinBox.setEnabled(False)

    def _addWhatsThisText(self):
        """
        What's This text for some of the widgets in this Property Manager.

        @note: Many PM widgets are still missing their "What's This" text.
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_PlanePropertyManager
        whatsThis_PlanePropertyManager(self)


    def toggleFileChooserBehavior(self, checked):
        """
        Enables FileChooser and displays image when checkbox is checked otherwise
        not
        """
        self.imageDisplayFileChooser.lineEdit.emit(SIGNAL("editingFinished()"))
        if checked == Qt.Checked:
            self.imageDisplayFileChooser.setEnabled(True)
        elif checked == Qt.Unchecked:
            self.imageDisplayFileChooser.setEnabled(False)
            # if an image is already displayed, that's need to be hidden as well
        else:
            pass

        self.command.struct.glpane.gl_update()


    def toggleHeightfield(self, checked):
        """
        Enables 3D relief drawing mode.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.display_heightfield = checked
            if checked:
                self.heightfieldHQDisplayCheckBox.setEnabled(True)
                self.heightfieldTextureCheckBox.setEnabled(True)
                self.vScaleSpinBox.setEnabled(True)
                plane.computeHeightfield()
            else:
                self.heightfieldHQDisplayCheckBox.setEnabled(False)
                self.heightfieldTextureCheckBox.setEnabled(False)
                self.vScaleSpinBox.setEnabled(False)
                plane.heightfield = None
            plane.glpane.gl_update()

    def toggleHeightfieldHQ(self, checked):
        """
        Enables high quality rendering in 3D relief mode.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.heightfield_hq = checked
            plane.computeHeightfield()
            plane.glpane.gl_update()

    def toggleTexture(self, checked):
        """
        Enables texturing in 3D relief mode.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.heightfield_use_texture = checked
            # It is not necessary to re-compute the heightfield coordinates
            # at this point, they are re-computed whenever the "3D relief image"
            # checkbox is set.
            plane.glpane.gl_update()

    def update_spinboxes(self):
        """
        Update the width and height spinboxes.
        @see: Plane.resizeGeometry()
        This typically gets called when the plane is resized from the
        3D workspace (which marks assy as modified) .So, update the spinboxes
        that represent the Plane's width and height, but do no emit 'valueChanged'
        signal when the spinbox value changes.

        @see: Plane.resizeGeometry()
        @see: self._update_UI_do_updates()
        @see: Plane_EditCommand.command_update_internal_state()
        """
        # blockSignals = True make sure that spinbox.valueChanged()
        # signal is not emitted after calling spinbox.setValue().  This is done
        #because the spinbox valu changes as a result of resizing the plane
        #from the 3D workspace.
        if self.command.hasValidStructure():
            self.heightDblSpinBox.setValue(self.command.struct.height,
                                           blockSignals = True)
            self.widthDblSpinBox.setValue(self.command.struct.width,
                                          blockSignals = True)


    def update_imageFile(self):
        """
        Loads image file if path is valid
        """

        # Update buttons and checkboxes.
        self.mirrorButton.setEnabled(False)
        self.plusNinetyButton.setEnabled(False)
        self.minusNinetyButton.setEnabled(False)
        self.flipButton.setEnabled(False)
        self.heightfieldDisplayCheckBox.setEnabled(False)
        self.heightfieldHQDisplayCheckBox.setEnabled(False)
        self.heightfieldTextureCheckBox.setEnabled(False)
        self.vScaleSpinBox.setEnabled(False)

        plane = self.command.struct

        # Delete current image and heightfield
        plane.deleteImage()
        plane.heightfield = None
        plane.display_image = self.imageDisplayCheckBox.isChecked()

        if plane.display_image:
            imageFile = str(self.imageDisplayFileChooser.lineEdit.text())

            from model.Plane import checkIfValidImagePath
            validPath = checkIfValidImagePath(imageFile)

            if validPath:
                from PIL import Image

                # Load image from file
                plane.image = Image.open(imageFile)
                plane.loadImage(imageFile)

                # Compute the relief image
                plane.computeHeightfield()

                if plane.image:
                    self.mirrorButton.setEnabled(True)
                    self.plusNinetyButton.setEnabled(True)
                    self.minusNinetyButton.setEnabled(True)
                    self.flipButton.setEnabled(True)
                    self.heightfieldDisplayCheckBox.setEnabled(True)
                    if plane.display_heightfield:
                        self.heightfieldHQDisplayCheckBox.setEnabled(True)
                        self.heightfieldTextureCheckBox.setEnabled(True)
                        self.vScaleSpinBox.setEnabled(True)


    def show(self):
        """
        Show the Plane Property Manager.
        """
        EditCommand_PM.show(self)
        #It turns out that if updateCosmeticProps is called before
        #EditCommand_PM.show, the 'preview' properties are not updated
        #when you are editing an existing plane. Don't know the cause at this
        #time, issue is trivial. So calling it in the end -- Ninad 2007-10-03

        if self.command.struct:

            plane = self.command.struct
            plane.updateCosmeticProps(previewing = True)
            if plane.imagePath:
                self.imageDisplayFileChooser.setText(plane.imagePath)
            self.imageDisplayCheckBox.setChecked(plane.display_image)

            #Make sure that the plane placement option is always set to
            #'Custom' when the Plane PM is shown. This makes sure that bugs like
            #2949 won't occur. Let the user change the plane placement option
            #explicitely
            button = self.pmPlacementOptions.getButtonById(3)
            button.setChecked(True)

    def setParameters(self, params):
        """
        """
        width, height, gridColor, gridLineType, \
             gridXSpacing, gridYSpacing, originLocation, \
             displayLabelStyle = params

        # blockSignals = True  flag makes sure that the
        # spinbox.valueChanged()
        # signal is not emitted after calling spinbox.setValue().
        self.widthDblSpinBox.setValue(width, blockSignals = True)
        self.heightDblSpinBox.setValue(height, blockSignals = True)
        self.win.glpane.gl_update()


        self.gpColorTypeComboBox.setColor(gridColor)
        self.gridLineType = gridLineType

        self.gpXSpacingDoubleSpinBox.setValue(gridXSpacing)
        self.gpYSpacingDoubleSpinBox.setValue(gridYSpacing)

        self.gpOriginComboBox.setCurrentIndex(originLocation)
        self.gpPositionComboBox.setCurrentIndex(displayLabelStyle)


    def getCurrrentDisplayParams(self):
        """
        Returns a tuple containing current display parameters such as current
        image path and grid display params.
        @see: Plane_EditCommand.command_update_internal_state() which uses this
        to decide whether to modify the structure (e.g. because of change in the
        image path or display parameters.)
        """
        imagePath = self.imageDisplayFileChooser.text
        gridColor = self.gpColorTypeComboBox.getColor()

        return (imagePath, gridColor, self.gridLineType,
                self.gridXSpacing, self.gridYSpacing,
                self.originLocation, self.displayLabelStyle)

    def getParameters(self):
        """
        """
        width = self.widthDblSpinBox.value()
        height = self.heightDblSpinBox.value()
        gridColor = self.gpColorTypeComboBox.getColor()

        params = (width, height, gridColor, self.gridLineType,
                  self.gridXSpacing, self.gridYSpacing, self.originLocation,
                  self.displayLabelStyle)

        return params


    def change_plane_width(self, newWidth):
        """
        Slot for width spinbox in the Property Manager.

        @param newWidth: width in Angstroms.
        @type  newWidth: float
        """
        if self.aspectRatioCheckBox.isChecked():
            self.command.struct.width   =  newWidth
            self.command.struct.height  =  self.command.struct.width / \
                self.aspectRatioSpinBox.value()
            self.update_spinboxes()
        else:
            self.change_plane_size()
        self._updateAspectRatio()

    def change_plane_height(self, newHeight):
        """
        Slot for height spinbox in the Property Manager.

        @param newHeight: height in Angstroms.
        @type  newHeight: float
        """
        if self.aspectRatioCheckBox.isChecked():
            self.command.struct.height  =  newHeight
            self.command.struct.width   =  self.command.struct.height * \
                self.aspectRatioSpinBox.value()
            self.update_spinboxes()
        else:
            self.change_plane_size()
        self._updateAspectRatio()

    def change_plane_size(self, gl_update = True):
        """
        Slot to change the Plane's width and height.

        @param gl_update: Forces an update of the glpane.
        @type  gl_update: bool
        """
        self.command.struct.width   =  self.widthDblSpinBox.value()
        self.command.struct.height  =  self.heightDblSpinBox.value()
        if gl_update:
            self.command.struct.glpane.gl_update()

    def change_vertical_scale(self, scale):
        """
        Changes vertical scaling of the heightfield.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.heightfield_scale = scale
            plane.computeHeightfield()
            plane.glpane.gl_update()

    def changePlanePlacement(self, buttonId):
        """
        Slot to change the placement of the plane depending upon the
        option checked in the "Placement Options" group box of the PM.

        @param buttonId: The button id of the selected radio button (option).
        @type  buttonId: int
        """

        if buttonId == 0:
            msg = "Create a Plane parallel to the screen. "\
                "With <b>Parallel to Screen</b> plane placement option, the "\
                "center of the plane is always (0,0,0)"
            self.updateMessage(msg)
            self.command.placePlaneParallelToScreen()
        elif buttonId == 1:
            msg = "Create a Plane with center coinciding with the common center "\
                "of <b> 3 or more selected atoms </b>. If exactly 3 atoms are "\
                "selected, the Plane will pass through those atoms."
            self.updateMessage(msg)
            self.command.placePlaneThroughAtoms()
            if self.command.logMessage:
                env.history.message(self.command.logMessage)
        elif buttonId == 2:
            msg = "Create a Plane at an <b>offset</b> to the selected plane "\
                "indicated by the direction arrow. "\
                "you can click on the direction arrow to reverse its direction."
            self.updateMessage(msg)
            self.command.placePlaneOffsetToAnother()
            if self.command.logMessage:
                env.history.message(self.command.logMessage)
        elif buttonId == 3:
            #'Custom' plane placement. Do nothing (only update message box)
            # Fixes bug 2439
            msg = "Create a plane with a <b>Custom</b> plane placement. "\
                "The plane is placed parallel to the screen, with "\
                "center at (0, 0, 0). User can then modify the plane placement."
            self.updateMessage(msg)


    def _enableAspectRatioSpinBox(self, enable):
        """
        Slot for "Maintain Aspect Ratio" checkbox which enables or disables
        the Aspect Ratio spin box.

        @param enable: True = enable, False = disable.
        @type  enable: bool
        """

        self.aspectRatioSpinBox.setEnabled(enable)

    def _updateAspectRatio(self):
        """
        Updates the Aspect Ratio spin box based on the current width and height.
        """
        aspectRatio = self.command.struct.width / self.command.struct.height
        self.aspectRatioSpinBox.setValue(aspectRatio)

    def _update_UI_do_updates(self):
        """
        Overrides superclass method.
        @see: Command_PropertyManager._update_UI_do_updates() for documentation.

        @see: Plane.resizeGeometry()
        @see: self.update_spinboxes()
        @see: Plane_EditCommand.command_update_internal_state()
        """
        #This typically gets called when the plane is resized from the
        #3D workspace (which marks assy as modified) . So, update the spinboxes
        #that represent the Plane's width and height.
        self.update_spinboxes()


    def update_props_if_needed_before_closing(self):
        """
        This updates some cosmetic properties of the Plane (e.g. fill color,
        border color, etc.) before closing the Property Manager.
        """

        # Example: The Plane Property Manager is open and the user is
        # 'previewing' the plane. Now the user clicks on "Build > Atoms"
        # to invoke the next command (without clicking "Done").
        # This calls openPropertyManager() which replaces the current PM
        # with the Build Atoms PM.  Thus, it creates and inserts the Plane
        # that was being previewed. Before the plane is permanently inserted
        # into the part, it needs to change some of its cosmetic properties
        # (e.g. fill color, border color, etc.) which distinguishes it as
        # a new plane in the part. This function changes those properties.
        # ninad 2007-06-13

        #called in updatePropertyManager in MWsemeantics.py --(Partwindow class)

        EditCommand_PM.update_props_if_needed_before_closing(self)

        #Don't draw the direction arrow when the object is finalized.
        if self.command.struct and \
           self.command.struct.offsetParentGeometry:

            dirArrow = self.command.struct.offsetParentGeometry.directionArrow
            dirArrow.setDrawRequested(False)

    def updateMessage(self, msg = ''):
        """
        Updates the message box with an informative message
        @param message: Message to be displayed in the Message groupbox of
                        the property manager
        @type  message: string
        """
        self.MessageGroupBox.insertHtmlMessage(msg,
                                               setAsDefault = False,
                                               minLines     = 5)

    def rotate_90(self):
        """
        Rotate the image clockwise.
        """
        if self.command.hasValidStructure():
            self.command.struct.rotateImage(0)
        return

    def rotate_neg_90(self):
        """
        Rotate the image counterclockwise.
        """
        if self.command.hasValidStructure():
            self.command.struct.rotateImage(1)
        return

    def flip_image(self):
        """
        Flip the image horizontally.
        """
        if self.command.hasValidStructure():
            self.command.struct.mirrorImage(1)
        return

    def mirror_image(self):
        """
        Flip the image vertically.
        """
        if self.command.hasValidStructure():
            self.command.struct.mirrorImage(0)
        return
Ejemplo n.º 17
0
class FixedBBProteinSim_PropertyManager(Command_PropertyManager):
    """
    The FixedBBProteinSim_PropertyManager class provides a Property Manager 
    for the B{Fixed backbone Protein Sequence Design} command on the flyout toolbar in the 
    Build > Protein > Simulate mode. 

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title         =  "Fixed Backbone Design"
    pmName        =  title
    iconPath      = "ui/actions/Command Toolbar/BuildProtein/FixedBackbone.png"

    
    def __init__( self, command ):
        """
        Constructor for the property manager.
        """

        _superclass.__init__(self, command)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Choose from the various options below to design "\
            "an optimized <b>fixed backbone protein sequence</b> with Rosetta."
        self.updateMessage(msg)            
        return
    

    def connect_or_disconnect_signals(self, isConnect = True):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot 
                          method. 
        @type  isConnect: boolean
        """
        
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect 
        
        
        change_connect(self.ex1Checkbox, SIGNAL("stateChanged(int)"), self.update_ex1)
        change_connect(self.ex1aroCheckbox, SIGNAL("stateChanged(int)"), self.update_ex1aro)
        change_connect(self.ex2Checkbox, SIGNAL("stateChanged(int)"), self.update_ex2)
        change_connect(self.ex2aroOnlyCheckbox, SIGNAL("stateChanged(int)"), self.update_ex2aro_only)
        change_connect(self.ex3Checkbox, SIGNAL("stateChanged(int)"), self.update_ex3)
        change_connect(self.ex4Checkbox, SIGNAL("stateChanged(int)"), self.update_ex4)
        change_connect(self.rotOptCheckbox, SIGNAL("stateChanged(int)"), self.update_rot_opt)
        change_connect(self.tryBothHisTautomersCheckbox, SIGNAL("stateChanged(int)"), self.update_try_both_his_tautomers)
        change_connect(self.softRepDesignCheckbox, SIGNAL("stateChanged(int)"), self.update_soft_rep_design)
        change_connect(self.useElecRepCheckbox, SIGNAL("stateChanged(int)"), self.update_use_elec_rep)
        change_connect(self.norepackDisulfCheckbox, SIGNAL("stateChanged(int)"), self.update_norepack_disulf)
        #signal slot connections for the push buttons
        change_connect(self.okButton, SIGNAL("clicked()"), self.runRosettaFixedBBSim)
        return
        
    #Protein Display methods         

    
    def show(self):
        """
        Shows the Property Manager. 
        """
        #@REVIEW: Why does it create sequence editor here? Also, is it
        #required to be done before the superclass.show call? Similar code 
        #found in CompareProteins_PM and some other files --Ninad 2008-10-02
        
        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.sequenceEditor.hide()
        
        _superclass.show(self)
        return
        
    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox( self,
                                         title = "Rosetta Fixed backbone sequence design")
        self._loadGroupBox1( self._pmGroupBox1 )
        return
    
        
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        
        self.numSimSpinBox = PM_SpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Number of simulations:",
                                         minimum = 1,
                                         maximum = 999,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        self.ex1Checkbox = PM_CheckBox(pmGroupBox,
                                       text = "Expand rotamer library for chi1 angle",
                                       state = Qt.Unchecked,
                                       setAsDefault  =  False,
                                       widgetColumn  = 0,
                                       spanWidth = True)
        
        self.ex1aroCheckbox = PM_CheckBox(pmGroupBox,
                                          text = "Use large chi1 library for aromatic residues",
                                          state = Qt.Unchecked,
                                          setAsDefault  =  False,
                                          widgetColumn  = 0,
                                          spanWidth = True)
        
        self.ex2Checkbox = PM_CheckBox(pmGroupBox,
                                       text = "Expand rotamer library for chi2 angle",
                                       state = Qt.Unchecked,
                                       setAsDefault  =  False,
                                       widgetColumn  = 0,
                                       spanWidth = True)
        
        self.ex2aroOnlyCheckbox = PM_CheckBox(pmGroupBox,
                                              text = "Use large chi2 library only for aromatic residues",
                                              state = Qt.Unchecked,
                                              setAsDefault  =  False,
                                              widgetColumn  = 0,
                                              spanWidth = True)
                                              
        self.ex3Checkbox = PM_CheckBox(pmGroupBox,
                                     text = "Expand rotamer library for chi3 angle",
                                     state = Qt.Unchecked,
                                     setAsDefault  =  False,
                                     widgetColumn  = 0,
                                     spanWidth = True)
        
        self.ex4Checkbox = PM_CheckBox(pmGroupBox,
                                       text ="Expand rotamer library for chi4 angle",
                                       state = Qt.Unchecked,
                                       setAsDefault  =  False,
                                       widgetColumn  = 0,
                                       spanWidth = True)
        
        self.rotOptCheckbox = PM_CheckBox(pmGroupBox,
                                          text ="Optimize one-body energy",
                                          state = Qt.Unchecked,
                                          setAsDefault  =  False,
                                          widgetColumn  = 0,
                                          spanWidth = True)
        
        self.tryBothHisTautomersCheckbox = PM_CheckBox(pmGroupBox,
                                                       text ="Try both histidine tautomers",
                                                       state = Qt.Unchecked,
                                                       setAsDefault  =  False,
                                                       widgetColumn  = 0,
                                                       spanWidth = True)
        
        self.softRepDesignCheckbox = PM_CheckBox(pmGroupBox,
                                                 text ="Use softer Lennard-Jones repulsive term",
                                                 state = Qt.Unchecked,
                                                 setAsDefault  =  False,
                                                 widgetColumn  = 0,
                                                 spanWidth = True)
        
        self.useElecRepCheckbox = PM_CheckBox(pmGroupBox,
                                              text ="Use electrostatic repulsion",
                                              state = Qt.Unchecked,
                                              setAsDefault  =  False,
                                              widgetColumn  = 0,
                                              spanWidth = True)
        
        self.norepackDisulfCheckbox = PM_CheckBox(pmGroupBox,
                                                  text ="Don't re-pack disulphide bonds",
                                                  state = Qt.Unchecked,
                                                  setAsDefault  =  False,
                                                  widgetColumn  = 0,
                                                  spanWidth = True)
        
        
        self.otherCommandLineOptions = PM_TextEdit(pmGroupBox,
                                                   label = "Command line options:",
                                                   spanWidth = True)
        self.otherCommandLineOptions.setFixedHeight(80)
        
        self.okButton = PM_PushButton( pmGroupBox,
                         text         =  "Launch Rosetta",
                         setAsDefault  =  True,
                         spanWidth = True)
        return
    
    def _addWhatsThisText( self ):
        """
        What's This text for widgets in this Property Manager.  
        """
        pass
                
    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.  
        """
        pass
    
    def update_ex1(self, state):
        """
        Update the command text edit depending on the state of the update_ex1
        checkbox
        @param state:state of the update_ex1 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex1Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex1 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex1 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex1aro(self, state):
        """
        Update the command text edit depending on the state of the update_ex1aro
        checkbox
        @param state:state of the update_ex1aro checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex1aroCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex1aro '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex1aro ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex2(self, state):
        """
        Update the command text edit depending on the state of the update_ex2
        checkbox
        @param state:state of the update_ex2 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex2Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex2 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex2 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex2aro_only(self, state):
        """
        Update the command text edit depending on the state of the update_ex2aro_only
        checkbox
        @param state:state of the update_ex2aro_only checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex2aroOnlyCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex2aro_only '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex2aro_only ', '')    
            
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex3(self, state):
        """
        Update the command text edit depending on the state of the update_ex3
        checkbox
        @param state:state of the update_ex3 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex3Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex3 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex3 ', '')
        
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex4(self, state):
        """
        Update the command text edit depending on the state of the update_ex4
        checkbox
        @param state:state of the update_ex4 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex4Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex4 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex4 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_rot_opt(self, state):
        """
        Update the command text edit depending on the state of the update_rot_opt
        checkbox
        @param state:state of the update_rot_opt checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.rotOptCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -rot_opt '
        else:
            otherOptionsText = otherOptionsText.replace(' -rot_opt ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_try_both_his_tautomers(self, state):
        """
        Update the command text edit depending on the state of the update_try_both_his_tautomers
        checkbox
        @param state:state of the update_try_both_his_tautomers checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.tryBothHisTautomersCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -try_both_his_tautomers '
        else:
            otherOptionsText = otherOptionsText.replace(' -try_both_his_tautomers ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_soft_rep_design(self, state):
        """
        Update the command text edit depending on the state of the update_soft_rep_design
        checkbox
        @param state:state of the update_soft_rep_design checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.softRepDesignCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -soft_rep_design '
        else:
            otherOptionsText = otherOptionsText.replace(' -soft_rep_design ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_use_elec_rep(self, state):
        """
        Update the command text edit depending on the state of the update_use_elec_rep
        checkbox
        @param state:state of the update_use_elec_rep checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.useElecRepCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -use_electrostatic_repulsion '
        else:
            otherOptionsText = otherOptionsText.replace(' -use_electrostatic_repulsion ', '')    
        self.otherCommandLineOptions.setText(otherOptionsText)        
        return
    
    def update_norepack_disulf(self, state):
        """
        Update the command text edit depending on the state of the update_no_repack
        checkbox
        @param state:state of the update_no_repack checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.norepackDisulfCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -norepack_disulf '
        else:
            otherOptionsText = otherOptionsText.replace(' -norepack_disulf ', '')      
        self.otherCommandLineOptions.setText(otherOptionsText)        
        return
    
    def runRosettaFixedBBSim(self):
        """
        Get all the parameters from the PM and run a rosetta simulation.
        """
        proteinChunk = self.win.assy.getSelectedProteinChunk()
        if not proteinChunk:
            msg = "You must select a single protein to run a Rosetta <i>Fixed Backbone</i> simulation."
            self.updateMessage(msg)
            return
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        numSim = self.numSimSpinBox.value()
        argList = [numSim, otherOptionsText, proteinChunk.name]
        
        from simulation.ROSETTA.rosetta_commandruns import rosettaSetup_CommandRun
        if argList[0] > 0:
            cmdrun = rosettaSetup_CommandRun(self.win, argList, "ROSETTA_FIXED_BACKBONE_SEQUENCE_DESIGN")
            cmdrun.run() 
        return    
Ejemplo n.º 18
0
class EditResidues_PropertyManager(PM_Dialog, DebugMenuMixin):
    """
    The ProteinDisplayStyle_PropertyManager class provides a Property Manager 
    for the B{Display Style} command on the flyout toolbar in the 
    Build > Protein mode. 

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title = "Edit Residues"
    pmName = title
    iconPath = "ui/actions/Edit/EditProteinDisplayStyle.png"

    def __init__(self, parentCommand):
        """
        Constructor for the property manager.
        """

        self.parentMode = parentCommand
        self.w = self.parentMode.w
        self.win = self.parentMode.w

        self.pw = self.parentMode.pw
        self.o = self.win.glpane
        self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key]

        PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title)

        DebugMenuMixin._init1(self)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Edit residues."
        self.updateMessage(msg)

    def connect_or_disconnect_signals(self, isConnect=True):

        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        #change_connect(self.nextAAPushButton,
        #               SIGNAL("clicked()"),
        #               self._expandNextRotamer)

    def ok_btn_clicked(self):
        """
        Slot for the OK button
        """
        self.win.toolsDone()

    def cancel_btn_clicked(self):
        """
        Slot for the Cancel button.
        """
        #TODO: Cancel button needs to be removed. See comment at the top
        self.win.toolsDone()

    def show(self):
        """
        Shows the Property Manager. Overrides PM_Dialog.show.
        """
        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.sequenceEditor.hide()
        PM_Dialog.show(self)

        # Update all PM widgets, then establish their signal-slot connections.
        # note: It is important to update the widgets *first* since doing
        # it in the reverse order will generate signals when updating
        # the PM widgets (via updateDnaDisplayStyleWidgets()), causing
        # unneccessary repaints of the model view.

        self._fillSequenceTable()

        self.connect_or_disconnect_signals(isConnect=True)

    def close(self):
        """
        Closes the Property Manager. Overrides PM_Dialog.close.
        """
        self.connect_or_disconnect_signals(False)
        PM_Dialog.close(self)

    def _addGroupBoxes(self):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox(self, title="Sequence")
        self._loadGroupBox1(self._pmGroupBox1)

        #self._pmGroupBox2 = PM_GroupBox( self,
        #                                 title = "Rotamer")
        #self._loadGroupBox2( self._pmGroupBox2 )

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        self.labelfont = QFont("Helvetica", 12)
        self.descriptorfont = QFont("Courier New", 12)

        self.headerdata = ['', 'ID', 'Set', 'Descriptor']

        self.set_names = ["Any", "Same", "Locked", "Polar", "Apolar"]
        self.rosetta_set_names = ["ALLAA", "NATRO", "NATAA", "POLAR", "APOLA"]
        self.descriptor_list = [
            "GAVILMFWCSTYNQDEHKRP", "____________________",
            "____________________", "________CSTYNQDEHKR_",
            "GAVILMFW___________P"
        ]

        self.descriptorsTable = PM_TableWidget(pmGroupBox)
        self.descriptorsTable.setFixedHeight(100)
        self.descriptorsTable.setRowCount(len(self.set_names))
        self.descriptorsTable.setColumnCount(2)
        self.descriptorsTable.verticalHeader().setVisible(False)
        self.descriptorsTable.horizontalHeader().setVisible(False)

        for index in range(len(self.set_names)):
            item_widget = QTableWidgetItem(self.set_names[index])
            item_widget.setFont(self.labelfont)
            item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled
                                 | Qt.ItemIsEditable)
            item_widget.setTextAlignment(Qt.AlignCenter)
            self.descriptorsTable.setItem(index, 0, item_widget)

            item_widget = QTableWidgetItem(self.descriptor_list[index])
            item_widget.setFont(self.descriptorfont)
            item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled
                                 | Qt.ItemIsEditable)
            item_widget.setTextAlignment(Qt.AlignCenter)
            self.descriptorsTable.setItem(index, 1, item_widget)

            self.descriptorsTable.setRowHeight(index, 16)

            pass

        self.descriptorsTable.resizeColumnsToContents()

        self.applyDescriptorPushButton = PM_PushButton(pmGroupBox,
                                                       text="Apply",
                                                       setAsDefault=True)

        self.selectAllPushButton = PM_PushButton(pmGroupBox,
                                                 text="All",
                                                 setAsDefault=True)

        self.selectNonePushButton = PM_PushButton(pmGroupBox,
                                                  text="None",
                                                  setAsDefault=True)

        self.selectInvertPushButton = PM_PushButton(pmGroupBox,
                                                    text="Invert",
                                                    setAsDefault=True)

        self.win.connect(self.applyDescriptorPushButton, SIGNAL("clicked()"),
                         self._applyDescriptor)

        self.win.connect(self.selectAllPushButton, SIGNAL("clicked()"),
                         self._selectAll)

        self.win.connect(self.selectNonePushButton, SIGNAL("clicked()"),
                         self._selectNone)

        self.win.connect(self.selectInvertPushButton, SIGNAL("clicked()"),
                         self._invertSelection)

        buttonList = [('PM_PushButton', self.applyDescriptorPushButton, 0, 0),
                      ('QSpacerItem', 5, 5, 1, 0),
                      ('PM_PushButton', self.selectAllPushButton, 2, 0),
                      ('PM_PushButton', self.selectNonePushButton, 3, 0),
                      ('PM_PushButton', self.selectInvertPushButton, 4, 0)]

        self.buttonGrid = PM_WidgetGrid(pmGroupBox, widgetList=buttonList)


        self.recenterViewCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Re-center view",
                         setAsDefault  =  True,
                         state         = Qt.Checked)

        self.sequenceTable = PM_TableWidget(pmGroupBox)
        #self.sequenceTable.setModel(self.tableModel)
        self.sequenceTable.resizeColumnsToContents()
        self.sequenceTable.verticalHeader().setVisible(False)
        #self.sequenceTable.setRowCount(0)
        self.sequenceTable.setColumnCount(4)

        self.checkbox = QCheckBox()

        self.sequenceTable.setFixedHeight(345)

        self.sequenceTable.setHorizontalHeaderLabels(self.headerdata)
        ###self._fillSequenceTable()

    def _fillSequenceTable(self):
        """
        """

        self.setComboBox = QComboBox()

        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                aa_list = chunk.protein.get_amino_acids()
                aa_list_len = len(aa_list)
                self.sequenceTable.setRowCount(aa_list_len)
                for index in range(aa_list_len):
                    item_widget = QTableWidgetItem("")
                    item_widget.setFont(self.labelfont)
                    item_widget.setCheckState(Qt.Checked)
                    item_widget.setTextAlignment(Qt.AlignLeft)
                    item_widget.setSizeHint(QSize(20, 12))
                    item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled
                                         | Qt.ItemIsUserCheckable)
                    self.sequenceTable.setItem(index, 0, item_widget)

                    item_widget = QTableWidgetItem(str(index + 1))
                    item_widget.setFont(self.labelfont)
                    item_widget.setFlags(Qt.ItemIsSelectable
                                         | Qt.ItemIsEnabled)
                    item_widget.setTextAlignment(Qt.AlignCenter)
                    self.sequenceTable.setItem(index, 1, item_widget)

                    item_widget = QTableWidgetItem("Any")
                    item_widget.setFont(self.labelfont)
                    item_widget.setFlags(Qt.ItemIsSelectable
                                         | Qt.ItemIsEnabled)
                    item_widget.setTextAlignment(Qt.AlignCenter)
                    self.sequenceTable.setItem(index, 2, item_widget)

                    aa_string = self._get_mutation_descriptor(
                        self._get_aa_for_index(index))

                    item_widget = QTableWidgetItem(aa_string)
                    item_widget.setFont(self.descriptorfont)
                    self.sequenceTable.setItem(index, 3, item_widget)

                    self.sequenceTable.setRowHeight(index, 16)

        self.win.connect(self.sequenceTable, SIGNAL("cellClicked(int, int)"),
                         self._sequenceTableCellChanged)

        self.sequenceTable.resizeColumnsToContents()

        self.sequenceTable.setColumnWidth(0, 35)
        self.sequenceTable.setColumnWidth(2, 80)

    def _selectAll(self):
        for row in range(self.sequenceTable.rowCount()):
            self.sequenceTable.item(row, 0).setCheckState(Qt.Checked)

    def _selectNone(self):
        for row in range(self.sequenceTable.rowCount()):
            self.sequenceTable.item(row, 0).setCheckState(Qt.Unchecked)

    def _invertSelection(self):
        for row in range(self.sequenceTable.rowCount()):
            item_widget = self.sequenceTable.item(row, 0)
            if item_widget.checkState() == Qt.Checked:
                item_widget.setCheckState(Qt.Unchecked)
            else:
                item_widget.setCheckState(Qt.Checked)

    def _get_mutation_descriptor(self, aa):
        """
        """
        aa_string = "GAVILMFWCSTYNQDEHKRP"

        range = aa.get_mutation_range()
        if range == "NATRO" or \
           range == "NATAA":
            code = aa.get_one_letter_code()
            aa_string = re.sub("[^" + code + "]", '_', aa_string)
        elif range == "POLAR":
            aa_string = "________CSTYNQDEHKR_"
        elif range == "APOLA":
            aa_string = "GAVILMFW___________P"

        return aa_string

    def _get_aa_for_index(self, index, expand=False):
        """
        """
        # Center on a selected amino acid.
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.set_current_amino_acid_index(index)
                current_aa = chunk.protein.get_current_amino_acid()
                if expand:
                    chunk.protein.collapse_all_rotamers()
                    chunk.protein.expand_rotamer(current_aa)
                return current_aa

        return None

    def _sequenceTableCellChanged(self, crow, ccol):
        #print "CELL CHANGED: ", (crow, ccol)
        item = self.sequenceTable.item(crow, ccol)
        #print "ITEM = ", item

        for row in range(self.sequenceTable.rowCount()):
            self.sequenceTable.removeCellWidget(row, 2)
            self.sequenceTable.setRowHeight(row, 16)
        if ccol == 2:
            # Make the row a little bit wider.
            self.sequenceTable.setRowHeight(crow, 22)
            # Create and insert a Combo Box into a current cell.
            self.setComboBox = QComboBox()
            self.setComboBox.addItems(self.set_names)
            self.win.connect(self.setComboBox,
                             SIGNAL("currentIndexChanged(int)"),
                             self._setComboBoxIndexChanged)

            self.sequenceTable.setCellWidget(crow, 2, self.setComboBox)

        current_aa = self._get_aa_for_index(crow, expand=True)
        if current_aa:
            # Center on the selected amino acid.
            if self.recenterViewCheckBox.isChecked():
                ca_atom = current_aa.get_c_alpha_atom()
                if ca_atom:
                    self.win.glpane.pov = -ca_atom.posn()
            self.win.glpane.gl_update()

    def _applyDescriptor(self):
        """        
        """
        cdes = self.descriptorsTable.currentRow()
        for row in range(self.sequenceTable.rowCount()):
            #print "row = ", row
            self._setComboBoxIndexChanged(cdes,
                                          tablerow=row,
                                          selectedOnly=True)

    def _setComboBoxIndexChanged(self,
                                 index,
                                 tablerow=None,
                                 selectedOnly=False):
        """
        """
        #print "INDEX = ", index
        if tablerow is None:
            crow = self.sequenceTable.currentRow()
        else:
            crow = tablerow
        #print "current row: ", crow
        item = self.sequenceTable.item(crow, 2)
        if item:
            cbox = self.sequenceTable.item(crow, 0)
            if not selectedOnly or \
               cbox.checkState() == Qt.Checked:
                item.setText(self.set_names[index])
                item = self.sequenceTable.item(crow, 3)
                aa = self._get_aa_for_index(crow)
                aa.set_mutation_range(self.rosetta_set_names[index])
                item.setText(self._get_mutation_descriptor(aa))

        ###self._write_resfile()

    def _write_resfile(self):
        from protein.model.Protein import write_rosetta_resfile
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                write_rosetta_resfile("/Users/piotr/test.resfile", chunk)
                return

    def _addWhatsThisText(self):

        #from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditResidues_PropertyManager
        #WhatsThis_EditResidues_PropertyManager(self)
        pass

    def _addToolTipText(self):
        #from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager
        #ToolTip_EditProteinDisplayStyle_PropertyManager(self)
        pass

    def scrollToPosition(self, index):
        """
        Scrolls the Sequence Table to a given sequence position.
        """
        item = self.sequenceTable.item(index, 0)
        if item:
            self.sequenceTable.scrollToItem(item)
class Ui_BuildAtomsPropertyManager(Command_PropertyManager):
    """
    The Ui_BuildAtomsPropertyManager class defines UI elements for the Property 
    Manager of the B{Build Atoms mode}.
    
    @ivar title: The title that appears in the property manager header.
    @type title: str
    
    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str
    
    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    # The title that appears in the Property Manager header
    title = "Build Atoms"
    # The name of this Property Manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    # The relative path to the PNG file that appears in the header
    iconPath = "ui/actions/Tools/Build Structures/BuildAtoms.png"

    def __init__(self, command):
        """
        Constructor for the B{Build Atoms} property manager class that defines 
        its UI.
        
        @param command: The parent mode where this Property Manager is used
        @type  command: L{depositMode}        
        """

        self.previewGroupBox = None
        self.regularElementChooser = None
        self.PAM5Chooser = None
        self.PAM3Chooser = None
        self.elementChooser = None
        self.advancedOptionsGroupBox = None
        self.bondToolsGroupBox = None

        self.selectionFilterCheckBox = None
        self.filterlistLE = None
        self.selectedAtomInfoLabel = None

        #Initialize the following to None. (subclasses may not define this)
        #Make sure you initialize it before adding groupboxes!
        self.selectedAtomPosGroupBox = None
        self.showSelectedAtomInfoCheckBox = None

        _superclass.__init__(self, command)

        self.showTopRowButtons(PM_DONE_BUTTON | PM_WHATS_THIS_BUTTON)
        msg = ''
        self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=False)

    def _addGroupBoxes(self):
        """
        Add various group boxes to the Build Atoms Property manager. 
        """
        self._addPreviewGroupBox()
        self._addAtomChooserGroupBox()
        self._addBondToolsGroupBox()

        #@@@TODO HIDE the bonds tool groupbox initially as the
        #by default, the atoms tool is active when BuildAtoms command is
        #finist invoked.
        self.bondToolsGroupBox.hide()

        self._addSelectionOptionsGroupBox()
        self._addAdvancedOptionsGroupBox()

    def _addPreviewGroupBox(self):
        """
        Adde the preview groupbox that shows the element selected in the 
        element chooser. 
        """
        self.previewGroupBox = PM_PreviewGroupBox(self, glpane=self.o)

    def _addAtomChooserGroupBox(self):
        """
        Add the Atom Chooser groupbox. This groupbox displays one of the 
        following three groupboxes depending on the choice selected in the 
        combobox:
          a) Periodic Table Elements L{self.regularElementChooser}
          b) PAM5 Atoms  L{self.PAM5Chooser}
          c) PAM3 Atoms  L{self.PAM3Chooser}
        @see: L{self.__updateAtomChooserGroupBoxes}
        """
        self.atomChooserGroupBox = \
            PM_GroupBox(self, title = "Atom Chooser")
        self._loadAtomChooserGroupBox(self.atomChooserGroupBox)

        self._updateAtomChooserGroupBoxes(currentIndex=0)

    def _addElementChooserGroupBox(self, inPmGroupBox):
        """
        Add the 'Element Chooser' groupbox. (present within the 
        Atom Chooser Groupbox) 
        """
        if not self.previewGroupBox:
            return

        elementViewer = self.previewGroupBox.elementViewer
        self.regularElementChooser = \
            PM_ElementChooser( inPmGroupBox,
                               parentPropMgr = self,
                               elementViewer = elementViewer)

    def _add_PAM5_AtomChooserGroupBox(self, inPmGroupBox):
        """
        Add the 'PAM5 Atom Chooser' groupbox (present within the 
        Atom Chooser Groupbox) 
        """
        if not self.previewGroupBox:
            return

        elementViewer = self.previewGroupBox.elementViewer
        self.PAM5Chooser = \
            PM_PAM5_AtomChooser( inPmGroupBox,
                                 parentPropMgr = self,
                                 elementViewer = elementViewer)

    def _add_PAM3_AtomChooserGroupBox(self, inPmGroupBox):
        """
        Add the 'PAM3 Atom Chooser' groupbox (present within the 
        Atom Chooser Groupbox)
        """
        if not self.previewGroupBox:
            return

        elementViewer = self.previewGroupBox.elementViewer
        self.PAM3Chooser = \
            PM_PAM3_AtomChooser( inPmGroupBox,
                                 parentPropMgr = self,
                                 elementViewer = elementViewer)

    def _hideAllAtomChooserGroupBoxes(self):
        """
        Hides all Atom Chooser group boxes.
        """
        if self.regularElementChooser:
            self.regularElementChooser.hide()
        if self.PAM5Chooser:
            self.PAM5Chooser.hide()
        if self.PAM3Chooser:
            self.PAM3Chooser.hide()

    def _addBondToolsGroupBox(self):
        """
        Add the 'Bond Tools' groupbox.
        """
        self.bondToolsGroupBox = \
            PM_GroupBox( self, title = "Bond Tools")

        self._loadBondToolsGroupBox(self.bondToolsGroupBox)

    def _addSelectionOptionsGroupBox(self):
        """
        Add 'Selection Options' groupbox
        """
        self.selectionOptionsGroupBox = \
            PM_GroupBox( self, title = "Selection Options" )

        self._loadSelectionOptionsGroupBox(self.selectionOptionsGroupBox)

    def _loadAtomChooserGroupBox(self, inPmGroupBox):
        """
        Load the widgets inside the Atom Chooser groupbox.
        @param inPmGroupBox: The Atom Chooser box in the PM
        @type  inPmGroupBox: L{PM_GroupBox} 
        """
        atomChooserChoices = [
            "Periodic Table Elements", "PAM5 Atoms", "PAM3 Atoms"
        ]

        self.atomChooserComboBox = \
            PM_ComboBox( inPmGroupBox,
                         label        = '',
                         choices      = atomChooserChoices,
                         index        = 0,
                         setAsDefault = False,
                         spanWidth    = True )

        #Following fixes bug 2550
        self.atomChooserComboBox.setFocusPolicy(Qt.NoFocus)

        self._addElementChooserGroupBox(inPmGroupBox)
        self._add_PAM5_AtomChooserGroupBox(inPmGroupBox)
        self._add_PAM3_AtomChooserGroupBox(inPmGroupBox)

    def _loadSelectionOptionsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Selection Options group box.
        @param inPmGroupBox: The Selection Options box in the PM
        @type  inPmGroupBox: L{PM_GroupBox} 
        """

        self.selectionFilterCheckBox = \
            PM_CheckBox( inPmGroupBox,
                         text  = "Enable atom selection filter",
                         widgetColumn = 0,
                         state        = Qt.Unchecked  )
        self.selectionFilterCheckBox.setDefaultValue(False)

        self.filterlistLE = PM_LineEdit(inPmGroupBox,
                                        label="",
                                        text="",
                                        setAsDefault=False,
                                        spanWidth=True)
        self.filterlistLE.setReadOnly(True)

        if self.selectionFilterCheckBox.isChecked():
            self.filterlistLE.setEnabled(True)
        else:
            self.filterlistLE.setEnabled(False)

        self.showSelectedAtomInfoCheckBox = \
            PM_CheckBox(
                inPmGroupBox,
                text  = "Show Selected Atom Info",
                widgetColumn = 0,
                state        = Qt.Unchecked)

        self.selectedAtomPosGroupBox = \
            PM_GroupBox( inPmGroupBox, title = "")
        self._loadSelectedAtomPosGroupBox(self.selectedAtomPosGroupBox)

        self.toggle_selectedAtomPosGroupBox(show=0)
        self.enable_or_disable_selectedAtomPosGroupBox(bool_enable=False)

        self.reshapeSelectionCheckBox = \
            PM_CheckBox( inPmGroupBox,
                         text         = 'Dragging reshapes selection',
                         widgetColumn = 0,
                         state        = Qt.Unchecked  )

        connect_checkbox_with_boolean_pref(self.reshapeSelectionCheckBox,
                                           reshapeAtomsSelection_prefs_key)

        env.prefs[reshapeAtomsSelection_prefs_key] = False

        self.waterCheckBox = \
            PM_CheckBox( inPmGroupBox,
                         text         = "Z depth filter (water surface)",
                         widgetColumn = 0,
                         state        = Qt.Unchecked  )

    def _loadSelectedAtomPosGroupBox(self, inPmGroupBox):
        """
        Load the selected Atoms position groupbox It is a sub-gropbox of 
        L{self.selectionOptionsGroupBox)
        @param inPmGroupBox: 'The Selected Atom Position Groupbox'
        @type  inPmGroupBox: L{PM_GroupBox} 
        """

        self.selectedAtomLineEdit = PM_LineEdit(inPmGroupBox,
                                                label="Selected Atom:",
                                                text="",
                                                setAsDefault=False,
                                                spanWidth=False)

        self.selectedAtomLineEdit.setReadOnly(True)
        self.selectedAtomLineEdit.setEnabled(False)

        self.coordinateSpinboxes = PM_CoordinateSpinBoxes(inPmGroupBox)

        # User input to specify x-coordinate
        self.xCoordOfSelectedAtom = self.coordinateSpinboxes.xSpinBox
        # User input to specify y-coordinate
        self.yCoordOfSelectedAtom = self.coordinateSpinboxes.ySpinBox
        # User input to specify z-coordinate
        self.zCoordOfSelectedAtom = self.coordinateSpinboxes.zSpinBox

    def _addAdvancedOptionsGroupBox(self):
        """
        Add 'Advanced Options' groupbox
        """
        self.advancedOptionsGroupBox = \
            PM_GroupBox( self, title = "Advanced Options" )

        self._loadAdvancedOptionsGroupBox(self.advancedOptionsGroupBox)

    def _loadAdvancedOptionsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Advanced Options group box.
        @param inPmGroupBox: The Advanced Options box in the PM
        @type  inPmGroupBox: L{PM_GroupBox} 
        """

        self.autoBondCheckBox = \
            PM_CheckBox( inPmGroupBox,
                         text         = 'Auto bond',
                         widgetColumn = 0,
                         state        = Qt.Checked  )

        self.highlightingCheckBox = \
            PM_CheckBox( inPmGroupBox,
                         text         = "Hover highlighting",
                         widgetColumn = 0,
                         state        = Qt.Checked )

    def _loadBondToolsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Bond Tools group box.
        @param inPmGroupBox: The Bond Tools box in the PM
        @type  inPmGroupBox: L{PM_GroupBox}        
        """
        # Button list to create a toolbutton row.
        # Format:
        # - buttonId,
        # - buttonText ,
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        BOND_TOOL_BUTTONS = \
                          [ ( "QToolButton", 0,  "SINGLE",    "", "", None, 0),
                            ( "QToolButton", 1,  "DOUBLE",    "", "", None, 1),
                            ( "QToolButton", 2,  "TRIPLE",    "", "", None, 2),
                            ( "QToolButton", 3,  "AROMATIC",  "", "", None, 3),
                            ( "QToolButton", 4,  "GRAPHITIC", "", "", None, 4),
                            ( "QToolButton", 5,  "CUTBONDS",  "", "", None, 5)
                          ]


        self.bondToolButtonRow = \
            PM_ToolButtonRow(
                inPmGroupBox,
                title        = "",
                buttonList   = BOND_TOOL_BUTTONS,
                checkedId    = None,
                setAsDefault = True )

    def _addWhatsThisText(self):
        """
        "What's This" text for widgets in this Property Manager.
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_BuildAtomsPropertyManager
        whatsThis_BuildAtomsPropertyManager(self)

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.  
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_BuildAtomsPropertyManager
        ToolTip_BuildAtomsPropertyManager(self)

    def toggle_selectedAtomPosGroupBox(self, show=0):
        """
        Show or hide L{self.selectedAtomPosGroupBox} depending on the state of
        the checkbox (L{self.showSelectedAtomInfoCheckBox}) 
        @param show: Flag that shows or hides the groupbox (can have values 
                     0 or 1
        @type  show: int
        """
        if show:
            self.selectedAtomPosGroupBox.show()
        else:
            self.selectedAtomPosGroupBox.hide()

    def enable_or_disable_selectedAtomPosGroupBox(self, bool_enable=False):
        """
        Enable or disable Selected AtomPosGroupBox present within 
        'selection options' and also the checkbox that shows or hide this 
        groupbox. These two widgets are enabled when only a single atom is 
        selected from the 3D workspace. 
        @param bool_enable: Flag that enables or disables widgets
        @type  bool_enable: boolean
        """
        if self.showSelectedAtomInfoCheckBox:
            self.showSelectedAtomInfoCheckBox.setEnabled(bool_enable)
        if self.selectedAtomPosGroupBox:
            self.selectedAtomPosGroupBox.setEnabled(bool_enable)

    def _updateAtomChooserGroupBoxes(self, currentIndex):
        """
        Updates the Atom Chooser Groupbox. It displays one of the 
        following three groupboxes depending on the choice selected in the 
        combobox:
          a) Periodic Table Elements L{self.regularElementChooser}
          b) PAM5 Atoms  L{self.PAM5Chooser}
          c) PAM3 Atoms  L{self.PAM3Chooser}
        It also sets self.elementChooser to the current active Atom chooser 
        and updates the display accordingly in the Preview groupbox.
        """
        self._hideAllAtomChooserGroupBoxes()

        if currentIndex is 0:
            self.elementChooser = self.regularElementChooser
            self.regularElementChooser.show()
        if currentIndex is 1:
            self.elementChooser = self.PAM5Chooser
            self.PAM5Chooser.show()
        if currentIndex is 2:
            self.elementChooser = self.PAM3Chooser
            self.PAM3Chooser.show()

        if self.elementChooser:
            self.elementChooser.updateElementViewer()

        self.updateMessage()

    def updateMessage(self):
        """
        Update the Message groupbox with informative message. 
        Subclasses should override this.
        """
        pass
Ejemplo n.º 20
0
class BackrubProteinSim_PropertyManager(Command_PropertyManager):
    """
    The BackrubProteinSim_PropertyManager class provides a Property Manager 
    for the B{Fixed backbone Protein Sequence Design} command on the flyout toolbar in the 
    Build > Protein > Simulate mode. 

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title         =  "Backrub Motion"
    pmName        =  title
    iconPath      = "ui/actions/Command Toolbar/BuildProtein/Backrub.png"

    
    def __init__( self, command ):
        """
        Constructor for the property manager.
        """                  
        _superclass.__init__(self, command)
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        msg = "Choose various parameters from below to design an optimized" \
            " protein sequence with Rosetta with backrub motion allowed."
        self.updateMessage(msg)
        
    def connect_or_disconnect_signals(self, isConnect = True):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot 
                          method. 
        @type  isConnect: boolean
        """
        
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect 
        
        change_connect(self.ex1Checkbox, SIGNAL("stateChanged(int)"), self.update_ex1)
        change_connect(self.ex1aroCheckbox, SIGNAL("stateChanged(int)"), self.update_ex1aro)
        change_connect(self.ex2Checkbox, SIGNAL("stateChanged(int)"), self.update_ex2)
        change_connect(self.ex2aroOnlyCheckbox, SIGNAL("stateChanged(int)"), self.update_ex2aro_only)
        change_connect(self.ex3Checkbox, SIGNAL("stateChanged(int)"), self.update_ex3)
        change_connect(self.ex4Checkbox, SIGNAL("stateChanged(int)"), self.update_ex4)
        change_connect(self.rotOptCheckbox, SIGNAL("stateChanged(int)"), self.update_rot_opt)
        change_connect(self.tryBothHisTautomersCheckbox, SIGNAL("stateChanged(int)"), self.update_try_both_his_tautomers)
        change_connect(self.softRepDesignCheckbox, SIGNAL("stateChanged(int)"), self.update_soft_rep_design)
        change_connect(self.useElecRepCheckbox, SIGNAL("stateChanged(int)"), self.update_use_elec_rep)
        change_connect(self.norepackDisulfCheckbox, SIGNAL("stateChanged(int)"), self.update_norepack_disulf)
        #signal slot connections for the push buttons
        change_connect(self.okButton, SIGNAL("clicked()"), self.runRosettaBackrubSim)
        return
    
    #Protein Display methods         

    def show(self):
        """
        Shows the Property Manager. Exends superclass method. 
        """
        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.sequenceEditor.hide()
        #update the min and max residues spinbox max values based on the length
        #of the current protein
        numResidues = self._getNumResiduesForCurrentProtein()
        if numResidues == 0:
            self.minresSpinBox.setMaximum(numResidues + 2)
            self.maxresSpinBox.setMaximum(numResidues + 2)
        else:    
            self.minresSpinBox.setMaximum(numResidues)
            self.maxresSpinBox.setMaximum(numResidues)
        
        _superclass.show(self)       
       
        return

    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox2 = PM_GroupBox( self,
                                         title = "Backrub Specific Parameters")
        self._loadGroupBox2( self._pmGroupBox2 )
        
        self._pmGroupBox1 = PM_GroupBox( self,
                                         title = "Rosetta Sequence Design Parameters")
        self._loadGroupBox1( self._pmGroupBox1 )
        
        return
    
    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        self.bondAngleWeightSimSpinBox = PM_DoubleSpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Bond angle weight:",
                                         minimum = 0.01,
                                         decimals     = 2, 
                                         maximum = 1.0,
                                         singleStep = 0.01,
                                         value = 1.0,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        bond_angle_param_list = ['Amber', 'Charmm']
        
        self.bondAngleParamComboBox = PM_ComboBox( pmGroupBox,
                                                   label         =  "Bond angle parameters:",
                                                   choices       =  bond_angle_param_list,
                                                   setAsDefault  =  False)
        
        self.onlybbSpinBox = PM_DoubleSpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Only backbone rotation:",
                                         minimum  = 0.01,
                                         maximum  = 1.0,
                                         value    = 0.75, 
                                         decimals = 2, 
                                         singleStep = 0.01,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        self.onlyrotSpinBox = PM_DoubleSpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Only rotamer rotation:",
                                         minimum  = 0.01,
                                         maximum  = 1.0,
                                         decimals = 2, 
                                         value    = 0.25, 
                                         singleStep = 0.01,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        self.mctempSpinBox = PM_DoubleSpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "MC simulation temperature:",
                                         minimum  = 0.1,
                                         value    = 0.6, 
                                         maximum  = 1.0,
                                         decimals = 2, 
                                         singleStep = 0.1,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        numResidues = self._getNumResiduesForCurrentProtein()
        self.minresSpinBox = PM_SpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Minimum number of residues:",
                                         minimum = 2,
                                         maximum = numResidues,
                                         singleStep = 1,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        self.maxresSpinBox = PM_SpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Maximum number of residues:",
                                         minimum = 2,
                                         maximum = numResidues,
                                         singleStep = 1,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        if numResidues == 0:
            self.minresSpinBox.setMaximum(numResidues + 2)
            self.maxresSpinBox.setMaximum(numResidues + 2)
        return
    
    
    def _addWhatsThisText( self ):
        """
        What's This text for widgets in this Property Manager.  
        """
        pass
                
    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.  
        """
        pass
    
    def _getNumResiduesForCurrentProtein(self):
        """
        Get number of residues for the current protein
        """
        _current_protein = self.win.assy.getSelectedProteinChunk()
        if _current_protein:
            return len(_current_protein.protein.get_sequence_string())
        return 0
    
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        
        self.numSimSpinBox = PM_SpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Number of trials:",
                                         minimum = 1000,
                                         maximum = 1000000,
                                         singleStep = 1000,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        self.ex1Checkbox = PM_CheckBox(pmGroupBox,
                                       text = "Expand rotamer library for chi1 angle",
                                       state = Qt.Unchecked,
                                       setAsDefault  =  False,
                                       widgetColumn  = 0,
                                       spanWidth = True)
        
        self.ex1aroCheckbox = PM_CheckBox(pmGroupBox,
                                          text = "Use large chi1 library for aromatic residues",
                                          state = Qt.Unchecked,
                                          setAsDefault  =  False,
                                          widgetColumn  = 0,
                                          spanWidth = True)
        
        self.ex2Checkbox = PM_CheckBox(pmGroupBox,
                                       text = "Expand rotamer library for chi2 angle",
                                       state = Qt.Unchecked,
                                       setAsDefault  =  False,
                                       widgetColumn  = 0,
                                       spanWidth = True)
        
        self.ex2aroOnlyCheckbox = PM_CheckBox(pmGroupBox,
                                              text = "Use large chi2 library only for aromatic residues",
                                              state = Qt.Unchecked,
                                              setAsDefault  =  False,
                                              widgetColumn  = 0,
                                              spanWidth = True)
                                              
        self.ex3Checkbox = PM_CheckBox(pmGroupBox,
                                     text = "Expand rotamer library for chi3 angle",
                                     state = Qt.Unchecked,
                                     setAsDefault  =  False,
                                     widgetColumn  = 0,
                                     spanWidth = True)
        
        self.ex4Checkbox = PM_CheckBox(pmGroupBox,
                                       text ="Expand rotamer library for chi4 angle",
                                       state = Qt.Unchecked,
                                       setAsDefault  =  False,
                                       widgetColumn  = 0,
                                       spanWidth = True)
        
        self.rotOptCheckbox = PM_CheckBox(pmGroupBox,
                                          text ="Optimize one-body energy",
                                          state = Qt.Unchecked,
                                          setAsDefault  =  False,
                                          widgetColumn  = 0,
                                          spanWidth = True)
        
        self.tryBothHisTautomersCheckbox = PM_CheckBox(pmGroupBox,
                                                       text ="Try both histidine tautomers",
                                                       state = Qt.Unchecked,
                                                       setAsDefault  =  False,
                                                       widgetColumn  = 0,
                                                       spanWidth = True)
        
        self.softRepDesignCheckbox = PM_CheckBox(pmGroupBox,
                                                 text ="Use softer Lennard-Jones repulsive term",
                                                 state = Qt.Unchecked,
                                                 setAsDefault  =  False,
                                                 widgetColumn  = 0,
                                                 spanWidth = True)
        
        self.useElecRepCheckbox = PM_CheckBox(pmGroupBox,
                                              text ="Use electrostatic repulsion",
                                              state = Qt.Unchecked,
                                              setAsDefault  =  False,
                                              widgetColumn  = 0,
                                              spanWidth = True)
        
        self.norepackDisulfCheckbox = PM_CheckBox(pmGroupBox,
                                                  text ="Don't re-pack disulphide bonds",
                                                  state = Qt.Unchecked,
                                                  setAsDefault  =  False,
                                                  widgetColumn  = 0,
                                                  spanWidth = True)
        
        
        self.otherCommandLineOptions = PM_TextEdit(pmGroupBox,
                                                   label = "Command line options:",
                                                   spanWidth = True)
        self.otherCommandLineOptions.setFixedHeight(80)
        
        self.okButton = PM_PushButton( pmGroupBox,
                         text         =  "Run Rosetta",
                         setAsDefault  =  True,
                         spanWidth = True)
        return
    
    
    def update_ex1(self, state):
        """
        Update the command text edit depending on the state of the update_ex1
        checkbox
        @param state:state of the update_ex1 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex1Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex1 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex1 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex1aro(self, state):
        """
        Update the command text edit depending on the state of the update_ex1aro
        checkbox
        @param state:state of the update_ex1aro checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex1aroCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex1aro '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex1aro ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex2(self, state):
        """
        Update the command text edit depending on the state of the update_ex2
        checkbox
        @param state:state of the update_ex2 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex2Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex2 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex2 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex2aro_only(self, state):
        """
        Update the command text edit depending on the state of the update_ex2aro_only
        checkbox
        @param state:state of the update_ex2aro_only checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex2aroOnlyCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex2aro_only '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex2aro_only ', '')    
            
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex3(self, state):
        """
        Update the command text edit depending on the state of the update_ex3
        checkbox
        @param state:state of the update_ex3 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex3Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex3 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex3 ', '')
        
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex4(self, state):
        """
        Update the command text edit depending on the state of the update_ex4
        checkbox
        @param state:state of the update_ex4 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex4Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex4 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex4 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_rot_opt(self, state):
        """
        Update the command text edit depending on the state of the update_rot_opt
        checkbox
        @param state:state of the update_rot_opt checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.rotOptCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -rot_opt '
        else:
            otherOptionsText = otherOptionsText.replace(' -rot_opt ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_try_both_his_tautomers(self, state):
        """
        Update the command text edit depending on the state of the update_try_both_his_tautomers
        checkbox
        @param state:state of the update_try_both_his_tautomers checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.tryBothHisTautomersCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -try_both_his_tautomers '
        else:
            otherOptionsText = otherOptionsText.replace(' -try_both_his_tautomers ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_soft_rep_design(self, state):
        """
        Update the command text edit depending on the state of the update_soft_rep_design
        checkbox
        @param state:state of the update_soft_rep_design checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.softRepDesignCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -soft_rep_design '
        else:
            otherOptionsText = otherOptionsText.replace(' -soft_rep_design ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_use_elec_rep(self, state):
        """
        Update the command text edit depending on the state of the update_use_elec_rep
        checkbox
        @param state:state of the update_use_elec_rep checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.useElecRepCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -use_electrostatic_repulsion '
        else:
            otherOptionsText = otherOptionsText.replace(' -use_electrostatic_repulsion ', '')    
        self.otherCommandLineOptions.setText(otherOptionsText)        
        return
    
    def update_norepack_disulf(self, state):
        """
        Update the command text edit depending on the state of the update_no_repack
        checkbox
        @param state:state of the update_no_repack checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.norepackDisulfCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -norepack_disulf '
        else:
            otherOptionsText = otherOptionsText.replace(' -norepack_disulf ', '')      
        self.otherCommandLineOptions.setText(otherOptionsText)        
        return
    
    def runRosettaBackrubSim(self):
        """
        Get all the parameters from the PM and run a rosetta simulation
        """
        proteinChunk = self.win.assy.getSelectedProteinChunk()
        if not proteinChunk:
            msg = "You must select a single protein to run a Rosetta <i>Backrub</i> simulation."
            self.updateMessage(msg)
            return
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        numSim = self.numSimSpinBox.value()
        argList = [numSim, otherOptionsText, proteinChunk.name]
        backrubSpecificArgList = self.getBackrubSpecificArgumentList()
        from simulation.ROSETTA.rosetta_commandruns import rosettaSetup_CommandRun
        if argList[0] > 0:
            env.prefs[rosetta_backrub_enabled_prefs_key] = True
            cmdrun = rosettaSetup_CommandRun(self.win, argList, "BACKRUB_PROTEIN_SEQUENCE_DESIGN", backrubSpecificArgList)
            cmdrun.run() 
        return    
    
    def getBackrubSpecificArgumentList(self):
        """
        get list of backrub specific parameters from PM
        """
        listOfArgs = []
        
        bond_angle_weight = str(self.bondAngleWeightSimSpinBox.value())
        listOfArgs.append('-bond_angle_weight')
        listOfArgs.append( bond_angle_weight)
        
        if self.bondAngleParamComboBox.currentIndex() == 0:
            bond_angle_params = 'bond_angle_amber_rosetta'
        else:
            bond_angle_params = 'bond_angle_charmm_rosetta'
            
        listOfArgs.append('-bond_angle_params')            
        listOfArgs.append(bond_angle_params)    
        
        only_bb = str(self.onlybbSpinBox.value())
        listOfArgs.append('-only_bb')
        listOfArgs.append( only_bb)
        
        only_rot = str(self.onlyrotSpinBox.value())
        listOfArgs.append('-only_rot')
        listOfArgs.append( only_rot)
        
        mc_temp = str(self.mctempSpinBox.value())
        listOfArgs.append('-mc_temp')
        listOfArgs.append( mc_temp)
        
        min_res = self.minresSpinBox.value()
        max_res = self.maxresSpinBox.value()
        if max_res < min_res:
            msg = redmsg("Maximum number of residues for rosetta simulation with backrub" \
                " motion cannot be less than minimum number of residues."\
                " Neglecting this parameter for this simulation.")
            
            env.history.message("BACKRUB SIMULATION: " + msg)
        else:
            listOfArgs.append('-min_res')
            listOfArgs.append( str(min_res))
            listOfArgs.append('-max_res')
            listOfArgs.append( str(max_res))
        
        return listOfArgs
class BackrubProteinSim_PropertyManager(Command_PropertyManager):
    """
    The BackrubProteinSim_PropertyManager class provides a Property Manager
    for the B{Fixed backbone Protein Sequence Design} command on the flyout toolbar in the
    Build > Protein > Simulate mode.

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title = "Backrub Motion"
    pmName = title
    iconPath = "ui/actions/Command Toolbar/BuildProtein/Backrub.png"

    def __init__(self, command):
        """
        Constructor for the property manager.
        """
        _superclass.__init__(self, command)
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        msg = "Choose various parameters from below to design an optimized" \
            " protein sequence with Rosetta with backrub motion allowed."
        self.updateMessage(msg)

    def connect_or_disconnect_signals(self, isConnect=True):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot
                          method.
        @type  isConnect: boolean
        """

        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self.ex1Checkbox, SIGNAL("stateChanged(int)"),
                       self.update_ex1)
        change_connect(self.ex1aroCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_ex1aro)
        change_connect(self.ex2Checkbox, SIGNAL("stateChanged(int)"),
                       self.update_ex2)
        change_connect(self.ex2aroOnlyCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_ex2aro_only)
        change_connect(self.ex3Checkbox, SIGNAL("stateChanged(int)"),
                       self.update_ex3)
        change_connect(self.ex4Checkbox, SIGNAL("stateChanged(int)"),
                       self.update_ex4)
        change_connect(self.rotOptCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_rot_opt)
        change_connect(self.tryBothHisTautomersCheckbox,
                       SIGNAL("stateChanged(int)"),
                       self.update_try_both_his_tautomers)
        change_connect(self.softRepDesignCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_soft_rep_design)
        change_connect(self.useElecRepCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_use_elec_rep)
        change_connect(self.norepackDisulfCheckbox,
                       SIGNAL("stateChanged(int)"),
                       self.update_norepack_disulf)
        #signal slot connections for the push buttons
        change_connect(self.okButton, SIGNAL("clicked()"),
                       self.runRosettaBackrubSim)
        return

    #Protein Display methods

    def show(self):
        """
        Shows the Property Manager. Exends superclass method.
        """
        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.sequenceEditor.hide()
        #update the min and max residues spinbox max values based on the length
        #of the current protein
        numResidues = self._getNumResiduesForCurrentProtein()
        if numResidues == 0:
            self.minresSpinBox.setMaximum(numResidues + 2)
            self.maxresSpinBox.setMaximum(numResidues + 2)
        else:
            self.minresSpinBox.setMaximum(numResidues)
            self.maxresSpinBox.setMaximum(numResidues)

        _superclass.show(self)

        return

    def _addGroupBoxes(self):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox2 = PM_GroupBox(self,
                                        title="Backrub Specific Parameters")
        self._loadGroupBox2(self._pmGroupBox2)

        self._pmGroupBox1 = PM_GroupBox(
            self, title="Rosetta Sequence Design Parameters")
        self._loadGroupBox1(self._pmGroupBox1)

        return

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        self.bondAngleWeightSimSpinBox = PM_DoubleSpinBox(
            pmGroupBox,
            labelColumn=0,
            label="Bond angle weight:",
            minimum=0.01,
            decimals=2,
            maximum=1.0,
            singleStep=0.01,
            value=1.0,
            setAsDefault=False,
            spanWidth=False)

        bond_angle_param_list = ['Amber', 'Charmm']

        self.bondAngleParamComboBox = PM_ComboBox(
            pmGroupBox,
            label="Bond angle parameters:",
            choices=bond_angle_param_list,
            setAsDefault=False)

        self.onlybbSpinBox = PM_DoubleSpinBox(pmGroupBox,
                                              labelColumn=0,
                                              label="Only backbone rotation:",
                                              minimum=0.01,
                                              maximum=1.0,
                                              value=0.75,
                                              decimals=2,
                                              singleStep=0.01,
                                              setAsDefault=False,
                                              spanWidth=False)

        self.onlyrotSpinBox = PM_DoubleSpinBox(pmGroupBox,
                                               labelColumn=0,
                                               label="Only rotamer rotation:",
                                               minimum=0.01,
                                               maximum=1.0,
                                               decimals=2,
                                               value=0.25,
                                               singleStep=0.01,
                                               setAsDefault=False,
                                               spanWidth=False)

        self.mctempSpinBox = PM_DoubleSpinBox(
            pmGroupBox,
            labelColumn=0,
            label="MC simulation temperature:",
            minimum=0.1,
            value=0.6,
            maximum=1.0,
            decimals=2,
            singleStep=0.1,
            setAsDefault=False,
            spanWidth=False)

        numResidues = self._getNumResiduesForCurrentProtein()
        self.minresSpinBox = PM_SpinBox(pmGroupBox,
                                        labelColumn=0,
                                        label="Minimum number of residues:",
                                        minimum=2,
                                        maximum=numResidues,
                                        singleStep=1,
                                        setAsDefault=False,
                                        spanWidth=False)

        self.maxresSpinBox = PM_SpinBox(pmGroupBox,
                                        labelColumn=0,
                                        label="Maximum number of residues:",
                                        minimum=2,
                                        maximum=numResidues,
                                        singleStep=1,
                                        setAsDefault=False,
                                        spanWidth=False)
        if numResidues == 0:
            self.minresSpinBox.setMaximum(numResidues + 2)
            self.maxresSpinBox.setMaximum(numResidues + 2)
        return

    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.
        """
        pass

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.
        """
        pass

    def _getNumResiduesForCurrentProtein(self):
        """
        Get number of residues for the current protein
        """
        _current_protein = self.win.assy.getSelectedProteinChunk()
        if _current_protein:
            return len(_current_protein.protein.get_sequence_string())
        return 0

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        self.numSimSpinBox = PM_SpinBox(pmGroupBox,
                                        labelColumn=0,
                                        label="Number of trials:",
                                        minimum=1000,
                                        maximum=1000000,
                                        singleStep=1000,
                                        setAsDefault=False,
                                        spanWidth=False)

        self.ex1Checkbox = PM_CheckBox(
            pmGroupBox,
            text="Expand rotamer library for chi1 angle",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex1aroCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Use large chi1 library for aromatic residues",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex2Checkbox = PM_CheckBox(
            pmGroupBox,
            text="Expand rotamer library for chi2 angle",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex2aroOnlyCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Use large chi2 library only for aromatic residues",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex3Checkbox = PM_CheckBox(
            pmGroupBox,
            text="Expand rotamer library for chi3 angle",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex4Checkbox = PM_CheckBox(
            pmGroupBox,
            text="Expand rotamer library for chi4 angle",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.rotOptCheckbox = PM_CheckBox(pmGroupBox,
                                          text="Optimize one-body energy",
                                          state=Qt.Unchecked,
                                          setAsDefault=False,
                                          widgetColumn=0,
                                          spanWidth=True)

        self.tryBothHisTautomersCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Try both histidine tautomers",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.softRepDesignCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Use softer Lennard-Jones repulsive term",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.useElecRepCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Use electrostatic repulsion",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.norepackDisulfCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Don't re-pack disulphide bonds",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.otherCommandLineOptions = PM_TextEdit(
            pmGroupBox, label="Command line options:", spanWidth=True)
        self.otherCommandLineOptions.setFixedHeight(80)

        self.okButton = PM_PushButton(pmGroupBox,
                                      text="Run Rosetta",
                                      setAsDefault=True,
                                      spanWidth=True)
        return

    def update_ex1(self, state):
        """
        Update the command text edit depending on the state of the update_ex1
        checkbox
        @param state:state of the update_ex1 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex1Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex1 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex1 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex1aro(self, state):
        """
        Update the command text edit depending on the state of the update_ex1aro
        checkbox
        @param state:state of the update_ex1aro checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex1aroCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex1aro '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex1aro ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex2(self, state):
        """
        Update the command text edit depending on the state of the update_ex2
        checkbox
        @param state:state of the update_ex2 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex2Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex2 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex2 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex2aro_only(self, state):
        """
        Update the command text edit depending on the state of the update_ex2aro_only
        checkbox
        @param state:state of the update_ex2aro_only checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex2aroOnlyCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex2aro_only '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex2aro_only ', '')

        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex3(self, state):
        """
        Update the command text edit depending on the state of the update_ex3
        checkbox
        @param state:state of the update_ex3 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex3Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex3 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex3 ', '')

        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex4(self, state):
        """
        Update the command text edit depending on the state of the update_ex4
        checkbox
        @param state:state of the update_ex4 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex4Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex4 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex4 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_rot_opt(self, state):
        """
        Update the command text edit depending on the state of the update_rot_opt
        checkbox
        @param state:state of the update_rot_opt checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.rotOptCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -rot_opt '
        else:
            otherOptionsText = otherOptionsText.replace(' -rot_opt ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_try_both_his_tautomers(self, state):
        """
        Update the command text edit depending on the state of the update_try_both_his_tautomers
        checkbox
        @param state:state of the update_try_both_his_tautomers checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.tryBothHisTautomersCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -try_both_his_tautomers '
        else:
            otherOptionsText = otherOptionsText.replace(
                ' -try_both_his_tautomers ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_soft_rep_design(self, state):
        """
        Update the command text edit depending on the state of the update_soft_rep_design
        checkbox
        @param state:state of the update_soft_rep_design checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.softRepDesignCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -soft_rep_design '
        else:
            otherOptionsText = otherOptionsText.replace(
                ' -soft_rep_design ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_use_elec_rep(self, state):
        """
        Update the command text edit depending on the state of the update_use_elec_rep
        checkbox
        @param state:state of the update_use_elec_rep checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.useElecRepCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -use_electrostatic_repulsion '
        else:
            otherOptionsText = otherOptionsText.replace(
                ' -use_electrostatic_repulsion ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_norepack_disulf(self, state):
        """
        Update the command text edit depending on the state of the update_no_repack
        checkbox
        @param state:state of the update_no_repack checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.norepackDisulfCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -norepack_disulf '
        else:
            otherOptionsText = otherOptionsText.replace(
                ' -norepack_disulf ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def runRosettaBackrubSim(self):
        """
        Get all the parameters from the PM and run a rosetta simulation
        """
        proteinChunk = self.win.assy.getSelectedProteinChunk()
        if not proteinChunk:
            msg = "You must select a single protein to run a Rosetta <i>Backrub</i> simulation."
            self.updateMessage(msg)
            return
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        numSim = self.numSimSpinBox.value()
        argList = [numSim, otherOptionsText, proteinChunk.name]
        backrubSpecificArgList = self.getBackrubSpecificArgumentList()
        from simulation.ROSETTA.rosetta_commandruns import rosettaSetup_CommandRun
        if argList[0] > 0:
            env.prefs[rosetta_backrub_enabled_prefs_key] = True
            cmdrun = rosettaSetup_CommandRun(
                self.win, argList, "BACKRUB_PROTEIN_SEQUENCE_DESIGN",
                backrubSpecificArgList)
            cmdrun.run()
        return

    def getBackrubSpecificArgumentList(self):
        """
        get list of backrub specific parameters from PM
        """
        listOfArgs = []

        bond_angle_weight = str(self.bondAngleWeightSimSpinBox.value())
        listOfArgs.append('-bond_angle_weight')
        listOfArgs.append(bond_angle_weight)

        if self.bondAngleParamComboBox.currentIndex() == 0:
            bond_angle_params = 'bond_angle_amber_rosetta'
        else:
            bond_angle_params = 'bond_angle_charmm_rosetta'

        listOfArgs.append('-bond_angle_params')
        listOfArgs.append(bond_angle_params)

        only_bb = str(self.onlybbSpinBox.value())
        listOfArgs.append('-only_bb')
        listOfArgs.append(only_bb)

        only_rot = str(self.onlyrotSpinBox.value())
        listOfArgs.append('-only_rot')
        listOfArgs.append(only_rot)

        mc_temp = str(self.mctempSpinBox.value())
        listOfArgs.append('-mc_temp')
        listOfArgs.append(mc_temp)

        min_res = self.minresSpinBox.value()
        max_res = self.maxresSpinBox.value()
        if max_res < min_res:
            msg = redmsg("Maximum number of residues for rosetta simulation with backrub" \
                " motion cannot be less than minimum number of residues."\
                " Neglecting this parameter for this simulation.")

            env.history.message("BACKRUB SIMULATION: " + msg)
        else:
            listOfArgs.append('-min_res')
            listOfArgs.append(str(min_res))
            listOfArgs.append('-max_res')
            listOfArgs.append(str(max_res))

        return listOfArgs
class EditResidues_PropertyManager( PM_Dialog, DebugMenuMixin ):
    """
    The ProteinDisplayStyle_PropertyManager class provides a Property Manager 
    for the B{Display Style} command on the flyout toolbar in the 
    Build > Protein mode. 

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title         =  "Edit Residues"
    pmName        =  title
    iconPath      =  "ui/actions/Edit/EditProteinDisplayStyle.png"

    
    def __init__( self, parentCommand ):
        """
        Constructor for the property manager.
        """

        self.parentMode = parentCommand
        self.w = self.parentMode.w
        self.win = self.parentMode.w

        self.pw = self.parentMode.pw        
        self.o = self.win.glpane                 
        self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key]
        
        PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title)

        DebugMenuMixin._init1( self )

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Edit residues."
        self.updateMessage(msg)

    def connect_or_disconnect_signals(self, isConnect = True):
        
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect 
        
        #change_connect(self.nextAAPushButton,
        #               SIGNAL("clicked()"),
        #               self._expandNextRotamer)
        

    def ok_btn_clicked(self):
        """
        Slot for the OK button
        """
        self.win.toolsDone()

    def cancel_btn_clicked(self):
        """
        Slot for the Cancel button.
        """
        #TODO: Cancel button needs to be removed. See comment at the top
        self.win.toolsDone()

    def show(self):
        """
        Shows the Property Manager. Overrides PM_Dialog.show.
        """
        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.sequenceEditor.hide()
        PM_Dialog.show(self)

        # Update all PM widgets, then establish their signal-slot connections.
        # note: It is important to update the widgets *first* since doing
        # it in the reverse order will generate signals when updating
        # the PM widgets (via updateDnaDisplayStyleWidgets()), causing
        # unneccessary repaints of the model view.
        
        self._fillSequenceTable()
        
        self.connect_or_disconnect_signals(isConnect = True)

    def close(self):
        """
        Closes the Property Manager. Overrides PM_Dialog.close.
        """
        self.connect_or_disconnect_signals(False)
        PM_Dialog.close(self)

    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox( self,
                                         title = "Sequence")
        self._loadGroupBox1( self._pmGroupBox1 )

        #self._pmGroupBox2 = PM_GroupBox( self,
        #                                 title = "Rotamer")
        #self._loadGroupBox2( self._pmGroupBox2 )


    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
            
        self.labelfont = QFont("Helvetica", 12)
        self.descriptorfont = QFont("Courier New", 12)        

        self.headerdata = ['', 'ID', 'Set', 'Descriptor']
        
        self.set_names = ["Any", "Same", "Locked", "Polar", "Apolar"]
        self.rosetta_set_names = ["ALLAA", "NATRO", "NATAA", "POLAR", "APOLA"]
        self.descriptor_list = ["GAVILMFWCSTYNQDEHKRP", 
                                "____________________", 
                                "____________________", 
                                "________CSTYNQDEHKR_", 
                                "GAVILMFW___________P"]
        
        self.descriptorsTable = PM_TableWidget( pmGroupBox)
        self.descriptorsTable.setFixedHeight(100)
        self.descriptorsTable.setRowCount(len(self.set_names))
        self.descriptorsTable.setColumnCount(2)
        self.descriptorsTable.verticalHeader().setVisible(False)
        self.descriptorsTable.horizontalHeader().setVisible(False)
        
        for index in range(len(self.set_names)):
            item_widget = QTableWidgetItem(self.set_names[index])
            item_widget.setFont(self.labelfont)
            item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable)
            item_widget.setTextAlignment(Qt.AlignCenter)
            self.descriptorsTable.setItem(index, 0, item_widget)
            
            item_widget = QTableWidgetItem(self.descriptor_list[index])
            item_widget.setFont(self.descriptorfont)
            item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable)
            item_widget.setTextAlignment(Qt.AlignCenter)
            self.descriptorsTable.setItem(index, 1, item_widget)

            self.descriptorsTable.setRowHeight(index, 16)

            pass
        
        self.descriptorsTable.resizeColumnsToContents()

        self.applyDescriptorPushButton = PM_PushButton( pmGroupBox,
            text         =  "Apply",
            setAsDefault  =  True)

        self.selectAllPushButton = PM_PushButton( pmGroupBox,
            text         =  "All",
            setAsDefault  =  True)

        self.selectNonePushButton = PM_PushButton( pmGroupBox,
            text       =  "None",
            setAsDefault  =  True)

        self.selectInvertPushButton = PM_PushButton( pmGroupBox,
            text       =  "Invert",
            setAsDefault  =  True)

        self.win.connect(self.applyDescriptorPushButton,
                         SIGNAL("clicked()"),
                         self._applyDescriptor)
        
        self.win.connect(self.selectAllPushButton,
                         SIGNAL("clicked()"),
                         self._selectAll)
        
        self.win.connect(self.selectNonePushButton,
                         SIGNAL("clicked()"),
                         self._selectNone)
        
        self.win.connect(self.selectInvertPushButton,
                         SIGNAL("clicked()"),
                         self._invertSelection)
        
        buttonList = [('PM_PushButton', self.applyDescriptorPushButton, 0, 0),
                      ('QSpacerItem', 5, 5, 1, 0), 
                      ('PM_PushButton', self.selectAllPushButton, 2, 0),
                      ('PM_PushButton', self.selectNonePushButton, 3, 0),
                      ('PM_PushButton', self.selectInvertPushButton, 4, 0)]

        self.buttonGrid = PM_WidgetGrid( pmGroupBox, 
                                         widgetList = buttonList)
                                         
        
        self.recenterViewCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Re-center view",
                         setAsDefault  =  True,
                         state         = Qt.Checked)

        self.sequenceTable = PM_TableWidget( pmGroupBox)
        #self.sequenceTable.setModel(self.tableModel)
        self.sequenceTable.resizeColumnsToContents()
        self.sequenceTable.verticalHeader().setVisible(False)
        #self.sequenceTable.setRowCount(0)
        self.sequenceTable.setColumnCount(4)
        
        self.checkbox = QCheckBox()
        
        
        self.sequenceTable.setFixedHeight(345)
        
        self.sequenceTable.setHorizontalHeaderLabels(self.headerdata) 
        ###self._fillSequenceTable()
        

    def _fillSequenceTable(self):
        """
        """        
        
        self.setComboBox = QComboBox()
        
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                aa_list = chunk.protein.get_amino_acids()
                aa_list_len = len(aa_list)
                self.sequenceTable.setRowCount(aa_list_len)
                for index in range(aa_list_len):                    
                    item_widget = QTableWidgetItem("")
                    item_widget.setFont(self.labelfont)
                    item_widget.setCheckState(Qt.Checked)
                    item_widget.setTextAlignment(Qt.AlignLeft)
                    item_widget.setSizeHint(QSize(20,12))
                    item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
                    self.sequenceTable.setItem(index, 0, item_widget)
                
                    item_widget = QTableWidgetItem(str(index+1))
                    item_widget.setFont(self.labelfont)
                    item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)            
                    item_widget.setTextAlignment(Qt.AlignCenter)
                    self.sequenceTable.setItem(index, 1, item_widget)
                    
                    item_widget = QTableWidgetItem("Any")
                    item_widget.setFont(self.labelfont)
                    item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                    item_widget.setTextAlignment(Qt.AlignCenter)
                    self.sequenceTable.setItem(index, 2, item_widget)
                    
                    aa_string = self._get_mutation_descriptor(
                        self._get_aa_for_index(index))

                    item_widget = QTableWidgetItem(aa_string)
                    item_widget.setFont(self.descriptorfont)
                    self.sequenceTable.setItem(index, 3, item_widget)
        
                    self.sequenceTable.setRowHeight(index, 16)
                    
        self.win.connect(self.sequenceTable,
                         SIGNAL("cellClicked(int, int)"),
                         self._sequenceTableCellChanged)
        
        self.sequenceTable.resizeColumnsToContents()
        
        self.sequenceTable.setColumnWidth(0, 35)
        self.sequenceTable.setColumnWidth(2, 80)
        
    def _selectAll(self):
        for row in range(self.sequenceTable.rowCount()):
            self.sequenceTable.item(row, 0).setCheckState(Qt.Checked)
            
    def _selectNone(self):
        for row in range(self.sequenceTable.rowCount()):
            self.sequenceTable.item(row, 0).setCheckState(Qt.Unchecked)
            
    def _invertSelection(self):
        for row in range(self.sequenceTable.rowCount()):
            item_widget = self.sequenceTable.item(row, 0)
            if item_widget.checkState() == Qt.Checked:
                item_widget.setCheckState(Qt.Unchecked)
            else:
                item_widget.setCheckState(Qt.Checked)
                
    def _get_mutation_descriptor(self, aa):
        """
        """
        aa_string = "GAVILMFWCSTYNQDEHKRP"
        
        range = aa.get_mutation_range()                    
        if range == "NATRO" or \
           range == "NATAA":
            code = aa.get_one_letter_code()                    
            aa_string = re.sub("[^"+code+"]",'_', aa_string)
        elif range == "POLAR":
            aa_string = "________CSTYNQDEHKR_"
        elif range == "APOLA":
            aa_string = "GAVILMFW___________P"

        return aa_string
    
    def _get_aa_for_index(self, index, expand=False):
        """
        """
        # Center on a selected amino acid.
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                chunk.protein.set_current_amino_acid_index(index)
                current_aa = chunk.protein.get_current_amino_acid()
                if expand:
                    chunk.protein.collapse_all_rotamers()
                    chunk.protein.expand_rotamer(current_aa)
                return current_aa 

        return None
    
    def _sequenceTableCellChanged(self, crow, ccol):
        #print "CELL CHANGED: ", (crow, ccol)
        item = self.sequenceTable.item(crow, ccol)
        #print "ITEM = ", item
        
        for row in range(self.sequenceTable.rowCount()):
            self.sequenceTable.removeCellWidget(row, 2)
            self.sequenceTable.setRowHeight(row, 16)
        if ccol == 2:
            # Make the row a little bit wider.
            self.sequenceTable.setRowHeight(crow, 22)
            # Create and insert a Combo Box into a current cell. 
            self.setComboBox = QComboBox()
            self.setComboBox.addItems(self.set_names)
            self.win.connect(self.setComboBox,
                             SIGNAL("currentIndexChanged(int)"),
                             self._setComboBoxIndexChanged)
            
            self.sequenceTable.setCellWidget(crow, 2, self.setComboBox)
        
        current_aa = self._get_aa_for_index(crow, expand=True)
        if current_aa:
            # Center on the selected amino acid.
            if self.recenterViewCheckBox.isChecked():
                ca_atom = current_aa.get_c_alpha_atom()
                if ca_atom:
                    self.win.glpane.pov = -ca_atom.posn()                            
            self.win.glpane.gl_update()
        
    def _applyDescriptor(self):
        """        
        """
        cdes = self.descriptorsTable.currentRow()
        for row in range(self.sequenceTable.rowCount()):
            #print "row = ", row
            self._setComboBoxIndexChanged(cdes, tablerow = row, selectedOnly = True)
            
    def _setComboBoxIndexChanged( self, index, tablerow = None, selectedOnly = False):
        """
        """
        #print "INDEX = ", index
        if tablerow is None: 
            crow = self.sequenceTable.currentRow()
        else:
            crow = tablerow
        #print "current row: ", crow
        item = self.sequenceTable.item(crow, 2)
        if item:
            cbox = self.sequenceTable.item(crow, 0)
            if not selectedOnly or \
               cbox.checkState() == Qt.Checked:
                item.setText(self.set_names[index])
                item = self.sequenceTable.item(crow, 3)
                aa = self._get_aa_for_index(crow)
                aa.set_mutation_range(self.rosetta_set_names[index])
                item.setText(self._get_mutation_descriptor(aa))
        
        ###self._write_resfile()
        
    def _write_resfile(self):
        from protein.model.Protein import write_rosetta_resfile
        for chunk in self.win.assy.molecules:
            if chunk.isProteinChunk():
                write_rosetta_resfile("/Users/piotr/test.resfile", chunk)
                return
        
    def _addWhatsThisText( self ):
        
        #from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditResidues_PropertyManager
        #WhatsThis_EditResidues_PropertyManager(self)
        pass
    
    def _addToolTipText(self):
        #from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager 
        #ToolTip_EditProteinDisplayStyle_PropertyManager(self)
        pass
        
    def scrollToPosition(self, index):
        """
        Scrolls the Sequence Table to a given sequence position.
        """
        item = self.sequenceTable.item(index, 0)
        if item:
            self.sequenceTable.scrollToItem(item)