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
Beispiel #2
0
    def _loadGroupBox1(self, pmGroupBox):
        """
        load widgets in groupbox1
        """

        self._loadSegmentListWidget(pmGroupBox)
        self.crossoversBetGivenSegmentsOnly_checkBox = PM_CheckBox(
            pmGroupBox,
            text="Between above segments only",
            widgetColumn=0,
            setAsDefault=True,
            spanWidth=True,
        )

        #If this preferece value is True, the search algotithm will search for
        #the potential crossover sites only *between* the segments in the
        #segment list widget (thus ignoring other segments not in that list)
        if env.prefs[
                makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key]:
            self.crossoversBetGivenSegmentsOnly_checkBox.setCheckState(
                Qt.Checked)
        else:
            self.crossoversBetGivenSegmentsOnly_checkBox.setCheckState(
                Qt.Unchecked)

        self.makeCrossoverPushButton = PM_PushButton(
            pmGroupBox, label="", text="Make All Crossovers", spanWidth=True)
Beispiel #3
0
 def _loadPM_CheckBox(self, inPmGroupBox):
     """
     PM_CheckBox.
     """
     self.checkBoxGroupBox = \
         PM_GroupBox( inPmGroupBox, 
                      title          = "<b> PM_CheckBox examples</b>" )
     
     self.checkBox1 = \
         PM_CheckBox( self.checkBoxGroupBox,
                      text         = "Label on left:",
                      widgetColumn = 1,
                      state        = Qt.Checked,
                      setAsDefault = True,
                     )
     
     self.checkBox2 = \
         PM_CheckBox( self.checkBoxGroupBox,
                      text          = ": Label on right",
                      widgetColumn  = 1,
                      state         = Qt.Checked,
                      setAsDefault  = True,
                     )
     
     self.checkBox3 = \
         PM_CheckBox( self.checkBoxGroupBox,
                      text         = "CheckBox (spanWidth = True):",
                      state        = Qt.Unchecked,
                      setAsDefault = False,
                    )
 def _loadJoinOptionsGroupbox(self, pmGroupBox):
     """
     Load widgets in this group box.
     """        
     
     self.clickToJoinDnaStrandsCheckBox = \
         PM_CheckBox(pmGroupBox ,
                     text         = 'Click on strand to join',
                     widgetColumn = 0, 
                     spanWidth = True)
     
     connect_checkbox_with_boolean_pref(
         self.clickToJoinDnaStrandsCheckBox, 
         joinStrandsCommand_clickToJoinDnaStrands_prefs_key )
     
     self.recursive_clickToJoinDnaStrandsCheckBox = \
         PM_CheckBox(pmGroupBox ,
                     text         = 'Recursively join strands',
                     widgetColumn = 1, 
                     spanWidth = True)
     
     connect_checkbox_with_boolean_pref(
         self.recursive_clickToJoinDnaStrandsCheckBox, 
         joinStrandsCommand_recursive_clickToJoinDnaStrands_prefs_key)
     
     if not env.prefs[joinStrandsCommand_clickToJoinDnaStrands_prefs_key]:
         self.recursive_clickToJoinDnaStrandsCheckBox.setEnabled(False)
    def _loadMergeOptionsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Merge Options groupbox (which is a groupbox within
        the B{Advanced Options group box}).
        @param inPmGroupBox: The Merge Options groupbox
        @type  inPmGroupBox: L{PM_GroupBox}
        @WARNING: This method initializes some instance varaiables for various
        checkboxes. (Example: self.mergeCopiesCheckBox.default = False). This
        won't be needed once extrudeMode.py is cleaned up.
        """
        self.mergeCopiesCheckBox = \
            PM_CheckBox(inPmGroupBox,
                        text         = 'Merge copies' ,
                        widgetColumn = 1,
                        state        = Qt.Unchecked
                    )
        self.mergeCopiesCheckBox.default = False
        self.mergeCopiesCheckBox.attr = 'whendone_all_one_part'
        self.mergeCopiesCheckBox.repaintQ = False


        self.extrudePrefMergeSelection = \
            PM_CheckBox(inPmGroupBox,
                        text         = 'Merge selection' ,
                        widgetColumn = 1,
                        state        = Qt.Unchecked
                    )
        self.extrudePrefMergeSelection.default = False
        self.extrudePrefMergeSelection.attr = 'whendone_merge_selection'
        self.extrudePrefMergeSelection.repaintQ = False
    def _loadDisplayOptionsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Display Options groupbox.
        @param inPmGroupBox: The Display Options groupbox 
        @type  inPmGroupBox: L{PM_GroupBox} 
        """

        displayChoices = ['Tubes', 'Spheres']

        self.dispModeComboBox = \
            PM_ComboBox( inPmGroupBox,
                         label        = 'Display style:',
                         choices      = displayChoices,
                         index        = 0,
                         setAsDefault = False,
                         spanWidth    = False )

        self.gridLineCheckBox = PM_CheckBox(inPmGroupBox,
                                            text="Show grid lines",
                                            widgetColumn=0,
                                            state=Qt.Checked)

        self.fullModelCheckBox = PM_CheckBox(inPmGroupBox,
                                             text="Show model",
                                             widgetColumn=0,
                                             state=Qt.Unchecked)
    def _loadDisplayOptionsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Display Options groupbox (which is a groupbox within
        the B{Advanced Options group box} ) .
        @param inPmGroupBox: The Display Options groupbox
        @type  inPmGroupBox: L{PM_GroupBox}
        @WARNING: This method initializes some instance varaiables for various
        checkboxes. (Example: self.mergeCopiesCheckBox.default = False). This
        won't be needed once extrudeMode.py is cleaned up.
        """
        self.showEntireModelCheckBox = \
            PM_CheckBox(inPmGroupBox,
                        text         = 'Show entire model' ,
                        widgetColumn = 1,
                        state        = Qt.Unchecked
                    )
        self.showEntireModelCheckBox.default = False
        self.showEntireModelCheckBox.attr = 'show_entire_model'
        self.showEntireModelCheckBox.repaintQ = True

        self.showBondOffsetCheckBox = \
            PM_CheckBox(inPmGroupBox,
                        text         = 'Show bond-offset spheres' ,
                        widgetColumn = 1,
                        state        = Qt.Unchecked
                    )
        self.showBondOffsetCheckBox.default = False
        self.showBondOffsetCheckBox.attr = 'show_bond_offsets'
        self.showBondOffsetCheckBox.repaintQ = True
Beispiel #8
0
    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
Beispiel #9
0
    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)
Beispiel #10
0
    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 _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  )
Beispiel #12
0
    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box.
        
        @param pmGroupBox: group box that contains protein display choices
        @see: L{PM_GroupBox}  
        
        """
        proteinStyleChoices = [
            'CA trace (wire)', 'CA trace (cylinders)',
            'CA trace (ball and stick)', 'Tube', 'Ladder', 'Zigzag',
            'Flat ribbon', 'Solid ribbon', 'Cartoons', 'Fancy cartoons',
            'Peptide tiles'
        ]

        self.proteinStyleComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Style:",
                         choices       =  proteinStyleChoices,
                         setAsDefault  =  True)

        scaleChoices = ['Constant', 'Secondary structure', 'B-factor']

        self.scaleComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Scaling:",
                         choices       =  scaleChoices,
                         setAsDefault  =  True)
        self.scaleFactorDoubleSpinBox = \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Scaling factor:",
                              value         =  1.00,
                              setAsDefault  =  True,
                              minimum       =  0.1,
                              maximum       =  3.0,
                              decimals      =  1,
                              singleStep    =  0.1 )

        self.splineDoubleSpinBox = \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Resolution:",
                              value         =  3,
                              setAsDefault  =  True,
                              minimum       =  2,
                              maximum       =  8,
                              decimals      =  0,
                              singleStep    =  1 )

        self.smoothingCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Smoothing",
                         setAsDefault = True)
Beispiel #13
0
    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 _loadRotateGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Rotate group box, 
        @param inPmGroupBox: The Rotate GroupBox in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """

        rotateChoices = ["Free Drag", "By Specified Angle"]

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

        self.rotateAsUnitCB = \
            PM_CheckBox( inPmGroupBox,
                         text         = 'Rotate as a unit' ,
                         widgetColumn = 0,
                         state        = Qt.Checked )

        self.freeDragRotateGroupBox = PM_GroupBox(inPmGroupBox)
        self._loadFreeDragRotateGroupBox(self.freeDragRotateGroupBox)

        self.bySpecifiedAngleGroupBox = PM_GroupBox(inPmGroupBox)
        self._loadBySpecifiedAngleGroupBox(self.bySpecifiedAngleGroupBox)

        self.updateRotateGroupBoxes(0)
    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 _loadJoinOptionsGroupbox(self, pmGroupBox):
        """
        Load widgets in this group box.
        """

        self.clickToJoinDnaStrandsCheckBox = \
            PM_CheckBox(pmGroupBox ,
                        text         = 'Click on strand to join',
                        widgetColumn = 0,
                        spanWidth = True)

        connect_checkbox_with_boolean_pref(
            self.clickToJoinDnaStrandsCheckBox,
            joinStrandsCommand_clickToJoinDnaStrands_prefs_key )

        self.recursive_clickToJoinDnaStrandsCheckBox = \
            PM_CheckBox(pmGroupBox ,
                        text         = 'Recursively join strands',
                        widgetColumn = 1,
                        spanWidth = True)

        connect_checkbox_with_boolean_pref(
            self.recursive_clickToJoinDnaStrandsCheckBox,
            joinStrandsCommand_recursive_clickToJoinDnaStrands_prefs_key)

        if not env.prefs[joinStrandsCommand_clickToJoinDnaStrands_prefs_key]:
            self.recursive_clickToJoinDnaStrandsCheckBox.setEnabled(False)
    def _loadGroupBox3(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        self.enableMaterialPropertiesComboBox = \
            PM_CheckBox( pmGroupBox, text = "On")
        self.finishDoubleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             maximum = 1.0,
                             minimum = 0.0,
                             decimals = 2,
                             singleStep = .1,
                             label = "Finish:")
        self.shininessDoubleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             maximum = 60,
                             minimum = 15,
                             decimals = 2,
                             label = "Shininess:")
        self.brightnessDoubleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             maximum = 1.0,
                             minimum = 0.0,
                             decimals = 2,
                             singleStep = .1,
                             label = "Brightness:")
        return
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box 1.
        """

        self.nameLineEdit = PM_LineEdit(pmGroupBox,
                                        label="Name:",
                                        text="",
                                        setAsDefault=False)

        self.numberOfBasesSpinBox = \
            PM_SpinBox( pmGroupBox,
                        label         =  "Number of bases:",
                        value         =  self._numberOfBases,
                        setAsDefault  =  False,
                        minimum       =  2,
                        maximum       =  10000 )

        self.disableStructHighlightingCheckbox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Don't highlight while editing DNA",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        #As of 2008-03-31, the properties such as number of bases will be
        #editable only by using the resize handles.
        self.numberOfBasesSpinBox.setEnabled(False)
        return
    def _loadProductSpecsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Product specifications group box.
        @param inPmGroupBox: The roduct specifications box in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """

        productChoices = ['Rod', 'Ring']

        self.extrude_productTypeComboBox = \
            PM_ComboBox( inPmGroupBox,
                         label        = 'Final product:',
                         labelColumn  = 0,
                         choices      = productChoices,
                         index        = 0,
                         setAsDefault = True,
                         spanWidth    = False )

        # names used in the code, same order
        #if you comment out items from combobox, you also have to remove them
        # from this list unless they are at the end!!!
        self.extrude_productTypeComboBox_ptypes = ["straight rod", \
                                                   "closed ring", \
                                                   "corkscrew"]

        self.extrudeSpinBox_n = \
            PM_SpinBox( inPmGroupBox,
                        label         =  "Number of copies:",
                        labelColumn   =  0,
                        value         =  3,
                        minimum       =  1,
                        maximum       =  99
                    )
        #@WARNING: This method initializes some instance varaiables for various
        #checkboxes. (Example: self.mergeCopiesCheckBox.default = False).
        #These values are needed in extrudemode.py. This
        #won't be needed once extrudeMode.py is cleaned up. -- ninad 2007-09-10

        self.extrudeBondCriterionSlider =  \
            PM_Slider( inPmGroupBox,
                       currentValue = 100,
                       minimum      = 0,
                       maximum      = 300,
                       label        = 'Tolerence'
                   )
        self.extrudeBondCriterionLabel = \
            self.extrudeBondCriterionSlider.labelWidget

        self.extrudeBondCriterionSlider_dflt = 100
        self.extrudeBondCriterionSlider.setPageStep(5)

        self.makeBondsCheckBox = \
            PM_CheckBox(inPmGroupBox,
                        text         = 'Make bonds' ,
                        widgetColumn = 0,
                        state        = Qt.Checked
                    )
        self.makeBondsCheckBox.default = True
        self.makeBondsCheckBox.attr = 'whendone_make_bonds'
        self.makeBondsCheckBox.repaintQ = False
Beispiel #20
0
    def _loadDisplayOptionsGroupBox(self, pmGroupBox):
        """
        Load widgets in the Display Options GroupBox
        @see: DnaOrCnt_PropertyManager. _loadDisplayOptionsGroupBox
        """
        #Call the superclass method that loads the cursor text checkboxes.
        #Note, as of 2008-05-19, the superclass, DnaOrCnt_PropertyManager
        #only loads the cursor text groupboxes. Subclasses like this can
        #call custom methods like self._loadCursorTextCheckBoxes etc if they
        #don't need all groupboxes that the superclass loads.
        _superclass._loadDisplayOptionsGroupBox(self, pmGroupBox)

        self._rubberbandLineGroupBox = PM_GroupBox(pmGroupBox,
                                                   title='Rubber band line:')

        dnaLineChoices = ['Ribbons', 'Ladder']
        self.dnaRubberBandLineDisplayComboBox = \
            PM_ComboBox( self._rubberbandLineGroupBox ,
                         label         =  " Display as:",
                         choices       =  dnaLineChoices,
                         setAsDefault  =  True)

        self.lineSnapCheckBox = \
            PM_CheckBox(self._rubberbandLineGroupBox ,
                        text         = 'Enable line snap' ,
                        widgetColumn = 1,
                        state        = Qt.Checked
                    )
    def _loadGroupBox1(self, pmGroupBox):
        """
        load widgets in groupbox1
        """

        self._loadSegmentListWidget(pmGroupBox)  
        self.crossoversBetGivenSegmentsOnly_checkBox = PM_CheckBox( 
            pmGroupBox,
            text         = "Between above segments only",
            widgetColumn  = 0,
            setAsDefault = True,
            spanWidth = True,
            )
        
        #If this preferece value is True, the search algotithm will search for
        #the potential crossover sites only *between* the segments in the 
        #segment list widget (thus ignoring other segments not in that list)
        if env.prefs[makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key]:
            self.crossoversBetGivenSegmentsOnly_checkBox.setCheckState(Qt.Checked) 
        else:
            self.crossoversBetGivenSegmentsOnly_checkBox.setCheckState(Qt.Unchecked)
        
        self.makeCrossoverPushButton = PM_PushButton( 
            pmGroupBox,
            label     = "",
            text      = "Make All Crossovers",
            spanWidth = True )
Beispiel #22
0
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in MotorParamsGroupBox.
        """
        if self.editCommand and self.editCommand.struct:
            force = self.editCommand.struct.force
            stiffness = self.editCommand.struct.stiffness
            enable_minimize = self.editCommand.struct.enable_minimize
        else:
            force = 0.0
            stiffness = 0.0
            enable_minimize = False

        self.forceDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label = "Force:",
                             value = force,
                             setAsDefault = True,
                             minimum    = 0.0,
                             maximum    = 5000.0,
                             singleStep = 1.0,
                             decimals   = 1,
                             suffix     =' pN')
        self.stiffnessDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label = "Stiffness:",
                             value = stiffness,
                             setAsDefault = True,
                             minimum    = 0.0,
                             maximum    = 1000.0,
                             singleStep = 1.0,
                             decimals   = 1,
                             suffix     =' N/m')

        self.enableMinimizeCheckBox = \
            PM_CheckBox(pmGroupBox,
                        text ="Enable in minimize",
                        widgetColumn = 1
                        )
        self.enableMinimizeCheckBox.setChecked(enable_minimize)

        self.directionPushButton = \
            PM_PushButton(pmGroupBox,
                          label = "Direction :",
                          text = "Reverse",
                          spanWidth = False)
        return
Beispiel #23
0
    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box.
        
        @param pmGroupBox: group box that contains protein display choices
        @see: L{PM_GroupBox}  
        
        """
        proteinStyleChoices = ['CA trace (wire)', 
                               'CA trace (cylinders)', 
                               'CA trace (ball and stick)',
                               'Tube',
                               'Ladder',
                               'Zigzag',
                               'Flat ribbon',
                               'Solid ribbon',
                               'Cartoons',
                               'Fancy cartoons',
                               'Peptide tiles'
                               ]

        self.proteinStyleComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Style:",
                         choices       =  proteinStyleChoices,
                         setAsDefault  =  True)
            
        scaleChoices = ['Constant', 'Secondary structure', 'B-factor']

        self.scaleComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Scaling:",
                         choices       =  scaleChoices,
                         setAsDefault  =  True)
        self.scaleFactorDoubleSpinBox = \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Scaling factor:",
                              value         =  1.00,
                              setAsDefault  =  True,
                              minimum       =  0.1,
                              maximum       =  3.0,
                              decimals      =  1,
                              singleStep    =  0.1 )
   
        self.splineDoubleSpinBox = \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Resolution:",
                              value         =  3,
                              setAsDefault  =  True,
                              minimum       =  2,
                              maximum       =  8,
                              decimals      =  0,
                              singleStep    =  1 )
        
        self.smoothingCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Smoothing",
                         setAsDefault = True)
    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 _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)
Beispiel #26
0
    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 _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.snapGridCheckBox = \
            PM_CheckBox(inPmGroupBox,
                        text = "Snap to grid",
                        state = Qt.Checked
                        )
        tooltip = "Snap selection point to a nearest cell grid point."
        self.snapGridCheckBox.setToolTip(tooltip)

        self.freeViewCheckBox = \
            PM_CheckBox(inPmGroupBox,
                        text = "Enable free view",
                        state = Qt.Unchecked
                    )
Beispiel #28
0
    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)
Beispiel #29
0
    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
Beispiel #30
0
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box 4.
        """

        self.nameLineEdit = PM_LineEdit(pmGroupBox,
                                        label="Strand name:",
                                        text="",
                                        setAsDefault=False)

        self.numberOfBasesSpinBox = \
            PM_SpinBox( pmGroupBox,
                        label         =  "Number of bases:",
                        value         =  self._numberOfBases,
                        setAsDefault  =  False,
                        minimum       =  2,
                        maximum       =  10000 )

        self.basesPerTurnDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Bases per turn:",
                              value         =  self.basesPerTurn,
                              setAsDefault  =  True,
                              minimum       =  8.0,
                              maximum       =  20.0,
                              decimals      =  2,
                              singleStep    =  0.1 )

        self.duplexRiseDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Rise:",
                              value         =  self.duplexRise,
                              setAsDefault  =  True,
                              minimum       =  2.0,
                              maximum       =  4.0,
                              decimals      =  3,
                              singleStep    =  0.01 )

        self.disableStructHighlightingCheckbox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Don't highlight while editing DNA",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        #As of 2008-03-31, the properties such as number of bases will be
        #editable only by using the resize handles. post FNANO we will support
        #the
        self.numberOfBasesSpinBox.setEnabled(False)
        self.basesPerTurnDoubleSpinBox.setEnabled(False)
        self.duplexRiseDoubleSpinBox.setEnabled(False)
Beispiel #31
0
 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 _loadBreakOptionsGroupbox(self, pmGroupBox):
     """
     Load widgets in this group box.
     """
             
     self.assignColorToBrokenDnaStrandsCheckBox = \
         PM_CheckBox(pmGroupBox ,
                     text         = 'Assign new color to broken strands',
                     widgetColumn = 1   )
     
     connect_checkbox_with_boolean_pref(
         self.assignColorToBrokenDnaStrandsCheckBox, 
         assignColorToBrokenDnaStrands_prefs_key )
Beispiel #33
0
    def loadCheckBoxGroupBox(self, inPmGroupBox):
        """
        Load PM_CheckBox test widgets in group box.
        """
        self.checkBoxGroupBox = \
            PM_GroupBox( inPmGroupBox,
                         title          = "<b> PM_CheckBox examples</b>" )

        self.checkBox1 = \
            PM_CheckBox( self.checkBoxGroupBox,
                         text         = "Widget on left:",
                         widgetColumn = 1,
                         state        = Qt.Checked,
                         setAsDefault = True,
                        )

        self.checkBox2 = \
            PM_CheckBox( self.checkBoxGroupBox,
                         text         = "Widget on right",
                         widgetColumn  = 1,
                         state        = Qt.Checked,
                         setAsDefault = True,
                         )
    def _addCheckBoxes(self, paramsForCheckBoxes):
        """
        Creates PM_CheckBoxes within the groupbox and also connects each one
        with its individual prefs key.
        """
        for checkBoxText, prefs_key in paramsForCheckBoxes:
            checkBox = \
                PM_CheckBox( self,
                             text  = checkBoxText,
                             widgetColumn = self._checkBoxColumn,
                             state        = Qt.Checked)

            connect_checkbox_with_boolean_pref(checkBox, prefs_key)

            self.checkBoxes.append(checkBox)
    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 _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 _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 _loadFuseOptionsGroupBox(self, inPmGroupBox):
     """
     Load the widgets inside the Fuse Options groupbox.
     """
     
     #@ Warning: If you change fuseChoices, you must also change the
     #  constants MAKEBONDS and FUSEATOMS in FuseChunks_Command.py.
     #  This implementation is fragile and should be fixed. Mark 2008-07-16
     
     fuseChoices = ['Make bonds between chunks', 
                    'Fuse overlapping atoms']
     
     self.fuseComboBox = \
         PM_ComboBox( inPmGroupBox,
                      label        = '', 
                      choices      = fuseChoices, 
                      index        = 0, 
                      setAsDefault = False,
                      spanWidth    = True)
     
     self.connect(self.fuseComboBox, 
                  SIGNAL("activated(const QString&)"), 
                  self.parentMode.change_fuse_mode)
     
     self.fusePushButton = PM_PushButton( inPmGroupBox,
                                          label     = "",
                                          text      = "Make Bonds",
                                          spanWidth = True )
     
     self.connect( self.fusePushButton,
                   SIGNAL("clicked()"),
                   self.parentMode.fuse_something)
     
     self.toleranceSlider =  PM_Slider( inPmGroupBox,
                                        currentValue = 100,
                                        minimum      = 0,
                                        maximum      = 300,
                                        label        = \
                                        'Tolerance:100% => 0 bondable pairs'
                                      )
     self.connect(self.toleranceSlider,
                    SIGNAL("valueChanged(int)"),
                    self.parentMode.tolerance_changed)
     
     self.mergeChunksCheckBox = PM_CheckBox( inPmGroupBox,
                                             text         = 'Merge chunks',
                                             widgetColumn = 0,
                                             state        = Qt.Checked )
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in MotorParamsGroupBox.
        """
        if self.command and self.command.struct:
            force = self.command.struct.force
            stiffness = self.command.struct.stiffness
            enable_minimize = self.command.struct.enable_minimize
        else:
            force = 0.0
            stiffness = 0.0
            enable_minimize = False

        self.forceDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label = "Force:",
                             value = force,
                             setAsDefault = True,
                             minimum    = 0.0,
                             maximum    = 5000.0,
                             singleStep = 1.0,
                             decimals   = 1,
                             suffix     =' pN')
        self.stiffnessDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label = "Stiffness:",
                             value = stiffness,
                             setAsDefault = True,
                             minimum    = 0.0,
                             maximum    = 1000.0,
                             singleStep = 1.0,
                             decimals   = 1,
                             suffix     =' N/m')

        self.enableMinimizeCheckBox = \
            PM_CheckBox(pmGroupBox,
                        text ="Enable in minimize",
                        widgetColumn = 1
                        )
        self.enableMinimizeCheckBox.setChecked(enable_minimize)

        self.directionPushButton = \
            PM_PushButton(pmGroupBox,
                          label = "Direction :",
                          text = "Reverse",
                          spanWidth = False)
        return
 def _loadMovieControlsGroupBox(self, inPmGroupBox):
     """
     Load widgets in the Movie Controls group box.
     @param inPmGroupBox: The Movie Controls groupbox in the PM
     @type  inPmGroupBox: L{PM_GroupBox} 
     """
     #Movie Slider
     self.frameNumberSlider = \
         PM_Slider( inPmGroupBox,
                    currentValue = 0,
                    minimum      = 0,
                    maximum      = 999999,
                    label        = 'Current Frame: 0/900'
                  )
     
     self.movieFrameUpdateLabel = self.frameNumberSlider.labelWidget
     
     #Movie Controls
     
     self.movieButtonsToolBar = NE1ToolBar(inPmGroupBox)
     
     _movieActionList = [self.movieResetAction,
                         self.moviePlayRevActiveAction,
                         self.moviePlayRevAction,
                         self.moviePauseAction,
                         self.moviePlayAction,
                         self.moviePlayActiveAction,
                         self.movieMoveToEndAction
                         ]
     
     for _action in _movieActionList:
         self.movieButtonsToolBar.addAction(_action)
             
     self.moviePlayActiveAction.setVisible(0)
     self.moviePlayRevActiveAction.setVisible(0)
     
     WIDGET_LIST = [("PM_", self.movieButtonsToolBar, 0)]
     
     self.moviecontrolsWidgetRow = PM_WidgetRow(inPmGroupBox, 
                                                widgetList = WIDGET_LIST,
                                                spanWidth = True)
     
     self.movieLoop_checkbox = PM_CheckBox(inPmGroupBox,
                                           text = "Loop",
                                           widgetColumn = 0,
                                           state = Qt.Unchecked)
    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.snapGridCheckBox = \
            PM_CheckBox(inPmGroupBox,
                        text = "Snap to grid",
                        state = Qt.Checked
                        )
        tooltip = "Snap selection point to a nearest cell grid point."
        self.snapGridCheckBox.setToolTip(tooltip)

        self.freeViewCheckBox = \
            PM_CheckBox(inPmGroupBox,
                        text = "Enable free view",
                        state = Qt.Unchecked
                    )
    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.
        """
        proteinStyleChoices = [
            "CA trace (wire)",
            "CA trace (cylinders)",
            "CA trace (ball and stick)",
            "Tube",
            "Ladder",
            "Zigzag",
            "Flat ribbon",
            "Solid ribbon",
            "Cartoons",
            "Fancy cartoons",
            "Peptide tiles",
        ]

        self.proteinStyleComboBox = PM_ComboBox(
            pmGroupBox, label="Style:", choices=proteinStyleChoices, setAsDefault=True
        )

        scaleChoices = ["Constant", "Secondary structure", "B-factor"]

        self.scaleComboBox = PM_ComboBox(pmGroupBox, label="Scaling:", choices=scaleChoices, setAsDefault=True)
        self.scaleFactorDoubleSpinBox = PM_DoubleSpinBox(
            pmGroupBox,
            label="Scaling factor:",
            value=1.00,
            setAsDefault=True,
            minimum=0.1,
            maximum=3.0,
            decimals=1,
            singleStep=0.1,
        )

        self.splineDoubleSpinBox = PM_DoubleSpinBox(
            pmGroupBox, label="Resolution:", value=4, setAsDefault=True, minimum=2, maximum=8, decimals=0, singleStep=1
        )

        self.smoothingCheckBox = PM_CheckBox(pmGroupBox, text="Smoothing", setAsDefault=True)
class test_connectWithState_PM( ExampleCommand1_PM):

    # does not use GBC; at least Done & Cancel should work
    
    title = "test connectWithState"
    
    def _addGroupBoxes(self):
        """Add the groupboxes for this Property Manager."""
        self.pmGroupBox1 = PM_GroupBox( self, title =  "settings")
        self._loadGroupBox1(self.pmGroupBox1)
        self.pmGroupBox2 = PM_GroupBox( self, title =  "commands")
        self._loadGroupBox2(self.pmGroupBox2)
        return

    _sMaxCylinderHeight = 20 ### TODO: ask the stateref for this
    
    def _loadGroupBox1(self, pmGroupBox):
        """Load widgets into groupbox 1 (passed as pmGroupBox)."""

        # cylinder height (a double, stored as a preferences value)

        cylinderHeight_stateref = Preferences_StateRef_double(
            CYLINDER_HEIGHT_PREFS_KEY,
            CYLINDER_HEIGHT_DEFAULT_VALUE )
            ### TODO: ask model object for this ref; this code should not need to know what kind it is (from prefs or model)
        
        self.cylinderHeightSpinbox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "cylinder height:",
##                              value         =  CYLINDER_HEIGHT_DEFAULT_VALUE,
##                              # guess: default value or initial value (guess they can't be distinguished -- bug -- yes, doc confirms)
##                              setAsDefault  =  True,
                              ### TODO: get all the following from the stateref, whenever the connection to state is made
                              minimum       =  3,
                              maximum       =  self._sMaxCylinderHeight,
                              singleStep    =  0.25,
                              decimals      =  self._sCoordinateDecimals,
                              suffix        =  ' ' + self._sCoordinateUnits )
        # REVIEW: is it ok that the above will set some wrong defaultValue,
        # to be immediately corrected by the following connection with state?
        self.cylinderHeightSpinbox.connectWithState(
            cylinderHeight_stateref,
            debug_metainfo = True
         )

        # ==
        
        # cylinder width (a double, stored in the command object,
        #  defined there using the State macro -- note, this is not yet a good
        #  enough example for state stored in a Node)

        cylinderWidth_stateref = ObjAttr_StateRef( self.commandrun, 'cylinderWidth')

        ## TEMPORARY: just make sure it's defined in there
        junk = cylinderWidth_stateref.defaultValue
        
        self.cylinderWidthSpinbox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "cylinder width:",
##                              value         =  defaultValue,
##                              setAsDefault  =  True,
##                                  ### REVISE: the default value should come from the cylinderWidth_stateref
                                  # (and so, probably, should min, max, step, units...)
                              minimum       =  0.1,
                              maximum       =  15.0,
                              singleStep    =  0.1,
                              decimals      =  self._sCoordinateDecimals,
                              suffix        =  ' ' + self._sCoordinateUnits )
        
        self.cylinderWidthSpinbox.connectWithState(
                                cylinderWidth_stateref,
                                debug_metainfo = True )

        # ==
        
        # cylinder round caps (boolean)
        
        cylinderRoundCaps_stateref = Preferences_StateRef( CYLINDER_ROUND_CAPS_PREFS_KEY,
                                                           CYLINDER_ROUND_CAPS_DEFAULT_VALUE ) ### TODO: get from model
        ## TEMPORARY: just make sure it's defined in there
        junk = cylinderRoundCaps_stateref.defaultValue
        
        self.cylinderRoundCapsCheckbox = PM_CheckBox(pmGroupBox, text = 'round caps on cylinder')
##        self.cylinderRoundCapsCheckbox.setDefaultValue(CYLINDER_ROUND_CAPS_DEFAULT_VALUE)
##            # note: setDefaultValue is an extension to the PM_CheckBox API, not yet finalized
        self.cylinderRoundCapsCheckbox.connectWithState(
                                cylinderRoundCaps_stateref,
                                debug_metainfo = True )

        # ==
        
        # cylinder vertical or horizontal (boolean)
        cylinderVertical_stateref = ObjAttr_StateRef( self.commandrun, 'cylinderVertical' )
        
        self.cylinderVerticalCheckbox = PM_CheckBox(pmGroupBox, text = 'cylinder is vertical')
##        self.cylinderVerticalCheckbox.setDefaultValue(CYLINDER_VERTICAL_DEFAULT_VALUE)
##            ### REVISE: the default value should come from the stateref
        self.cylinderVerticalCheckbox.connectWithState(
                                cylinderVertical_stateref,
                                debug_metainfo = True )
        
        return # from _loadGroupBox1

    def _loadGroupBox2(self, pmGroupBox): ### RENAME button attrs
        self.startButton = \
            PM_PushButton( pmGroupBox,
                           label     = "",
                           text      = "Bigger",
                           spanWidth = False ) ###BUG: button spans PM width, in spite of this setting
        self.startButton.setAction( self.button_Bigger, cmdname = "Bigger")
        
        self.stopButton = \
            PM_PushButton( pmGroupBox,
                           label     = "",
                           text      = "Smaller",
                           spanWidth = False )
        self.stopButton.setAction( self.button_Smaller, cmdname = "Smaller")

        return
        
    def button_Bigger(self):
        self.commandrun.cmd_Bigger()

    def button_Smaller(self):
        self.commandrun.cmd_Smaller()
        
    def _addWhatsThisText(self):
        """What's This text for some of the widgets in the Property Manager."""
        self.cylinderHeightSpinbox.setWhatsThis("cylinder height (stored in prefs)")
        self.cylinderWidthSpinbox.setWhatsThis("cylinder width (stored as State in the command object)")
        return
    
    pass # end of class
class MakeCrossovers_PropertyManager( Command_PropertyManager, 
                                      ListWidgetItems_PM_Mixin ):
    """
    The MakeCrossovers_PropertyManager class provides a Property Manager 
    for the B{Make Crossovers} command on the flyout toolbar in the 
    Build > Dna 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         =  "Make Crossovers"
    pmName        =  title
    iconPath      =  "ui/actions/Command Toolbar/BuildDna/MakeCrossovers.png"


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

            

        self.isAlreadyConnected = False
        self.isAlreadyDisconnected = False

        self._previous_model_changed_params = None

        _superclass.__init__(self, command)

        
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        
        self.defaultLogMessage = """Pairs of white cylinders (if any) in the 
        3D workspace indicate potential crossover sites. Clicking on such a 
         cylinder pair will make that crossover."""

        self.updateMessage(self.defaultLogMessage)
        
      
    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: This is a temporary fix for a 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 atucally 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

        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 

        self.segmentListWidget.connect_or_disconnect_signals(isConnect) 
        change_connect(self.addSegmentsToolButton, 
                       SIGNAL("toggled(bool)"), 
                       self.activateAddSegmentsTool)
        change_connect(self.removeSegmentsToolButton, 
                       SIGNAL("toggled(bool)"), 
                       self.activateRemoveSegmentsTool)

        change_connect(self.makeCrossoverPushButton,
                       SIGNAL("clicked()"),
                       self._makeAllCrossovers)
        
        connect_checkbox_with_boolean_pref(
             self.crossoversBetGivenSegmentsOnly_checkBox,
            makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key)
        
                                                          
    def show(self):
        """
        Overrides the superclass method
        @see: self._deactivateAddRemoveSegmentsTool
        """
        _superclass.show(self)             
        self._deactivateAddRemoveSegmentsTool()
     
    

    def _makeAllCrossovers(self):
        self.command.makeAllCrossovers()


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


    def _loadGroupBox1(self, pmGroupBox):
        """
        load widgets in groupbox1
        """

        self._loadSegmentListWidget(pmGroupBox)  
        self.crossoversBetGivenSegmentsOnly_checkBox = PM_CheckBox( 
            pmGroupBox,
            text         = "Between above segments only",
            widgetColumn  = 0,
            setAsDefault = True,
            spanWidth = True,
            )
        
        #If this preferece value is True, the search algotithm will search for
        #the potential crossover sites only *between* the segments in the 
        #segment list widget (thus ignoring other segments not in that list)
        if env.prefs[makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key]:
            self.crossoversBetGivenSegmentsOnly_checkBox.setCheckState(Qt.Checked) 
        else:
            self.crossoversBetGivenSegmentsOnly_checkBox.setCheckState(Qt.Unchecked)
        
        self.makeCrossoverPushButton = PM_PushButton( 
            pmGroupBox,
            label     = "",
            text      = "Make All Crossovers",
            spanWidth = True )

    def _update_UI_do_updates(self):
        """
        @see: Command_PropertyManager._update_UI_do_updates()
        @see: DnaSegment_EditCommand.command_update_UI()
        @see: DnaSegment_EditCommand.hasResizableStructure()
        @see: self._current_model_changed_params()
        """

        currentParams = self._current_model_changed_params()
        
        #Optimization. Return from the model_changed method if the 
        #params are the same. 
        if same_vals(currentParams, self._previous_model_changed_params):
            return 
        

        number_of_segments, \
                          crossover_search_pref_junk,\
                          bool_valid_segmentList_junk = currentParams
                
        #update the self._previous_model_changed_params with this new param set.
        self._previous_model_changed_params = currentParams       
        #Ensures that there are only PAM3 DNA segments in the commad's tructure 
        #list (command._structList. Call this before updating the list widgets!
        self.command.ensureValidSegmentList()
        self.updateListWidgets()   
        self.command.updateCrossoverSites()

    def _current_model_changed_params(self):
        """
        Returns a tuple containing the parameters that will be compared
        against the previously stored parameters. This provides a quick test
        to determine whether to do more things in self.model_changed()
        @see: self.model_changed() which calls this
        @see: self._previous_model_changed_params attr. 
        """
        params = None

        if self.command:
            #update the list first. 
            self.command.updateSegmentList()
            bool_valid_segmentList = self.command.ensureValidSegmentList()
            number_of_segments = len(self.command.getSegmentList()) 
            crossover_search_pref = \
                                  env.prefs[makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key]
            params = (number_of_segments, 
                      crossover_search_pref, 
                      bool_valid_segmentList
                  )

        return params

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

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the DNA Property Manager.  
        """
        pass
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
 def _loadGroupBox1(self, pmGroupBox):
     """
     Load widgets in MotorParamsGroupBox.
     """    
     if self.editCommand and self.editCommand.struct:
         torque = self.editCommand.struct.torque
         initial_speed = self.editCommand.struct.initial_speed
         final_speed = self.editCommand.struct.speed
         dampers_enabled = self.editCommand.struct.dampers_enabled
         enable_minimize = self.editCommand.struct.enable_minimize
     else:
         torque = 0.0
         initial_speed = 0.0
         final_speed = 0.0
         dampers_enabled = False
         enable_minimize = False
     
     self.torqueDblSpinBox = \
         PM_DoubleSpinBox(pmGroupBox, 
                             label = "Torque :", 
                             value = torque, 
                             setAsDefault = True,
                             minimum    = 0.0, 
                             maximum    = 1000.0, 
                             singleStep = 1.0, 
                             decimals   = 1, 
                             suffix     =' nN-nm')
     
     self.initialSpeedDblSpinBox = \
         PM_DoubleSpinBox(pmGroupBox,
                             label = "Initial speed :", 
                             value = initial_speed, 
                             setAsDefault = True,
                             minimum    = 0.0, 
                             maximum    = 100.0, 
                             singleStep = 1.0, 
                             decimals   = 1, 
                             suffix     = ' GHz')
     
     self.finalSpeedDblSpinBox = \
         PM_DoubleSpinBox(pmGroupBox,
                             label = "Final speed :", 
                             value = final_speed, 
                             setAsDefault = True,
                             minimum  = 0.0, 
                             maximum  = 100.0, 
                             singleStep = 1.0, 
                             decimals = 1, 
                             suffix = ' GHz')
     
     self.dampersCheckBox = \
         PM_CheckBox(pmGroupBox,
                     text = "Dampers",
                     widgetColumn = 0
                     )
                           
     
     self.dampersCheckBox.setChecked(dampers_enabled)
     
     self.enableMinimizeCheckBox = \
         PM_CheckBox(pmGroupBox,
                     text = "Enable in minimize",
                     widgetColumn = 0
                     )
     self.enableMinimizeCheckBox.setChecked(enable_minimize)
     
     self.directionPushButton = \
         PM_PushButton(pmGroupBox,
                       label = "Direction :",
                       text = "Reverse",
                       spanWidth = False)
     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
class LinearMotorPropertyManager(MotorPropertyManager):
    """
    The LinearMotorProperty manager class provides UI and propMgr object for the
    LinearMotor_EditCommand.
    """
    # The title that appears in the Property Manager header.
    title = "Linear Motor"
    # 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/Simulation/LinearMotor.png"


    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

        MotorPropertyManager.connect_or_disconnect_signals(self, isConnect)

        change_connect(self.directionPushButton,
                     SIGNAL("clicked()"),
                     self.reverse_direction)
        change_connect(self.motorLengthDblSpinBox,
                     SIGNAL("valueChanged(double)"),
                     self.change_motor_size)
        change_connect(self.motorWidthDblSpinBox,
                     SIGNAL("valueChanged(double)"),
                     self.change_motor_size)
        change_connect(self.spokeRadiusDblSpinBox,
                     SIGNAL("valueChanged(double)"),
                     self.change_motor_size)
        change_connect(self.motorColorComboBox,
                       SIGNAL("editingFinished()"),
                       self.change_jig_color)
        return

    def _update_widgets_in_PM_before_show(self):
        """
        Update various widgets  in this Property manager.
        Overrides MotorPropertyManager._update_widgets_in_PM_before_show.
        The various  widgets , (e.g. spinboxes) will get values from the
        structure for which this propMgr is constructed for
        (self.editcCntroller.struct)

        @see: MotorPropertyManager._update_widgets_in_PM_before_show
        @see: self.show where it is called.
        """
        if self.command and self.command.struct:
            force = self.command.struct.force
            stiffness = self.command.struct.stiffness
            enable_minimize = self.command.struct.enable_minimize

            length = self.command.struct.length
            width = self.command.struct.width
            spoke_radius = self.command.struct.sradius
            normcolor = self.command.struct.normcolor
        else:
            force = 0.0
            stiffness = 0.0
            enable_minimize = False

            length = 10
            width = 1
            spoke_radius = 0.2
            normcolor = gray

        self.forceDblSpinBox.setValue(force)
        self.stiffnessDblSpinBox.setValue(stiffness)
        self.enableMinimizeCheckBox.setChecked(enable_minimize)

        self.motorLengthDblSpinBox.setValue(length)
        self.motorWidthDblSpinBox.setValue(width)
        self.spokeRadiusDblSpinBox.setValue(spoke_radius)
        return

    def change_motor_size(self, gl_update=True):
        """
        Slot method to change the jig's length, width and/or spoke radius.
        """
        self.command.struct.length = self.motorLengthDblSpinBox.value()
        self.command.struct.width =  self.motorWidthDblSpinBox.value()
        # spoke radius --
        self.command.struct.sradius = self.spokeRadiusDblSpinBox.value()
        if gl_update:
            self.glpane.gl_update()
        return

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in MotorParamsGroupBox.
        """
        if self.command and self.command.struct:
            force = self.command.struct.force
            stiffness = self.command.struct.stiffness
            enable_minimize = self.command.struct.enable_minimize
        else:
            force = 0.0
            stiffness = 0.0
            enable_minimize = False

        self.forceDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label = "Force:",
                             value = force,
                             setAsDefault = True,
                             minimum    = 0.0,
                             maximum    = 5000.0,
                             singleStep = 1.0,
                             decimals   = 1,
                             suffix     =' pN')
        self.stiffnessDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label = "Stiffness:",
                             value = stiffness,
                             setAsDefault = True,
                             minimum    = 0.0,
                             maximum    = 1000.0,
                             singleStep = 1.0,
                             decimals   = 1,
                             suffix     =' N/m')

        self.enableMinimizeCheckBox = \
            PM_CheckBox(pmGroupBox,
                        text ="Enable in minimize",
                        widgetColumn = 1
                        )
        self.enableMinimizeCheckBox.setChecked(enable_minimize)

        self.directionPushButton = \
            PM_PushButton(pmGroupBox,
                          label = "Direction :",
                          text = "Reverse",
                          spanWidth = False)
        return

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in groubox 2.
        """

        if self.command and self.command.struct:
            length = self.command.struct.length
            width = self.command.struct.width
            spoke_radius = self.command.struct.sradius
            normcolor = self.command.struct.normcolor
        else:
            length = 10
            width = 1
            spoke_radius = 0.2
            normcolor = gray


        self.motorLengthDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                                label = "Motor length :",
                                value = length,
                                setAsDefault = True,
                                minimum = 0.5,
                                maximum = 500.0,
                                singleStep = 0.5,
                                decimals = 1,
                                suffix = ' Angstroms')


        self.motorWidthDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                                label="Motor width :",
                                value = width,
                                setAsDefault = True,
                                minimum = 0.1,
                                maximum = 50.0,
                                singleStep = 0.1,
                                decimals = 1,
                                suffix = ' Angstroms')


        self.spokeRadiusDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                                label = "Spoke radius :",
                                value = spoke_radius,
                                setAsDefault = True,
                                minimum = 0.1,
                                maximum = 50.0,
                                singleStep = 0.1,
                                decimals = 1,
                                suffix = ' Angstroms')

        self.motorColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                             color = normcolor)
        return

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

    def _addToolTipText(self):
        """
        What's Tool Tip text for widgets in this Property Manager.
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_LinearMotorPropertyManager
        ToolTip_LinearMotorPropertyManager(self)
        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)
class Ui_BuildCrystal_PropertyManager(Command_PropertyManager):
    """
    The Ui_BuildCrystal_PropertyManager class defines UI elements for the Property
    Manager of the B{Crystal 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> - the title that appears in the property manager header.
    title = "Build Crystal"
    # <iconPath> - full path to PNG file that appears in the header.
    # The name of this Property Manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    iconPath = "ui/actions/Tools/Build Structures/Build Crystal.png"

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

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


        _superclass.__init__(self, command)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_CANCEL_BUTTON | \
                                PM_WHATS_THIS_BUTTON)


    def _addGroupBoxes(self):
        """
        Add various group boxes to the Property manager.
        """
        self._addCrystalSpecsGroupbox()
        self._addLayerPropertiesGroupBox()
        self._addDisplayOptionsGroupBox()
        self._addAdvancedOptionsGroupBox()

    def _addCrystalSpecsGroupbox(self):
        """
        Add 'Crystal groupbox' to the PM
        """
        self.crystalSpecsGroupBox = \
            PM_GroupBox(self, title = "Crystal Specifications")
        self._loadCrystalSpecsGroupBox(self.crystalSpecsGroupBox)

    def _addLayerPropertiesGroupBox(self):
        """
        Add 'Layer Properties' groupbox to the PM
        """
        self.layerPropertiesGroupBox = \
            PM_GroupBox(self, title = "Layer Properties")
        self._loadLayerPropertiesGroupBox(self.layerPropertiesGroupBox)


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

    def _addDisplayOptionsGroupBox(self):
        """
        Add 'Display Options' groupbox
        """
        self.displayOptionsGroupBox = PM_GroupBox(self,
                                                  title = 'Display Options')
        self._loadDisplayOptionsGroupBox(self.displayOptionsGroupBox)

    def _loadCrystalSpecsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Crystal Specifications group box.
        @param inPmGroupBox: The Crystal Specifications groupbox in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        latticeChoices = ["Diamond", "Lonsdaleite"]

        self.latticeCBox = \
            PM_ComboBox( inPmGroupBox,
                         label        = 'Lattice:',
                         labelColumn  = 0,
                         choices      = latticeChoices,
                         index        = 0,
                         setAsDefault = True,
                         spanWidth    = False )

        # Button list to create a toolbutton row.
        # Format:
        # - buttonType,
        # - buttonId,
        # - buttonText ,
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        BUTTON_LIST = [
            ( "QToolButton", 0,  "Surface 100",
              "ui/actions/Properties Manager/Surface100.png",
              "Surface 100", "", 0),

            ( "QToolButton", 1,  "Surface 110",
              "ui/actions/Properties Manager/Surface110.png",
              "Surface 110", "", 1),

            ( "QToolButton", 2,  "Surface 111",
              "ui/actions/Properties Manager/Surface111.png",
              "Surface 110", "", 2)
            ]
        self.gridOrientationButtonRow = \
            PM_ToolButtonRow(inPmGroupBox,
                               title        = "",
                               label        = "Orientation:",
                               buttonList   = BUTTON_LIST,
                               checkedId    = 0,
                               setAsDefault = True,
                               spanWidth   = False
                               )

        self.orientButtonGroup = self.gridOrientationButtonRow.buttonGroup
        self.surface100_btn = self.gridOrientationButtonRow.getButtonById(0)
        self.surface110_btn = self.gridOrientationButtonRow.getButtonById(1)
        self.surface111_btn = self.gridOrientationButtonRow.getButtonById(2)

        self.rotateGridByAngleSpinBox = \
            PM_SpinBox( inPmGroupBox,
                        label         =  "Rotate by: ",
                        labelColumn   =  0,
                        value         =  45,
                        minimum       =  0,
                        maximum       =  360,
                        singleStep    =  5,
                        suffix        = " degrees")

        GRID_ANGLE_BUTTONS = [
                        ("QToolButton", 0,  "Anticlockwise",
                         "ui/actions/Properties Manager/rotate_minus.png",
                         "", "+", 0 ),

                        ( "QToolButton", 1,  "Clockwise",
                          "ui/actions/Properties Manager/rotate_plus.png",
                          "", "-", 1 )
                        ]

        self.gridRotateButtonRow = \
            PM_ToolButtonRow( inPmGroupBox,
                              title        = "",
                              buttonList   = GRID_ANGLE_BUTTONS,
                              label        = 'Rotate grid:',
                              isAutoRaise  =  False,
                              isCheckable  =  False
                            )
        self.rotGridAntiClockwiseButton = \
            self.gridRotateButtonRow.getButtonById(0)
        self.rotGridClockwiseButton = \
            self.gridRotateButtonRow.getButtonById(1)

    def _loadLayerPropertiesGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Layer Properties group box.
        @param inPmGroupBox: The Layer Properties groupbox in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """

        self.currentLayerComboBox = \
            PM_ComboBox( inPmGroupBox,
                         index     = 0,
                         spanWidth = True
                        )

        self.addLayerButton = PM_PushButton(inPmGroupBox)
        self.addLayerButton.setIcon(
            geticon('ui/actions/Properties Manager/addlayer.png'))
        self.addLayerButton.setFixedSize(QSize(26, 26))
        self.addLayerButton.setIconSize(QSize(22, 22))

        # A widget list to create a widget row.
        # Format:
        # - Widget type,
        # - widget object,
        # - column

        firstRowWidgetList = [('PM_ComboBox', self.currentLayerComboBox, 1),
                              ('PM_PushButton', self.addLayerButton, 2)
                              ]

        widgetRow = PM_WidgetRow(inPmGroupBox,
                                 title     = '',
                                 widgetList = firstRowWidgetList,
                                 label = "Layer:",
                                 labelColumn  = 0,
                                 )

        self.layerCellsSpinBox = \
             PM_SpinBox( inPmGroupBox,
                        label         =  "Lattice cells:",
                        labelColumn   =  0,
                        value         =  2,
                        minimum       =  1,
                        maximum       =  25
                      )

        self.layerThicknessLineEdit = PM_LineEdit(inPmGroupBox,
                                         label        = "Thickness:",
                                         text         = "",
                                         setAsDefault = False,
                                         spanWidth    = False )

        #self.layerThicknessLineEdit.setReadOnly(True)
        self.layerThicknessLineEdit.setDisabled(True)
        tooltip = "Thickness of layer in Angstroms"
        self.layerThicknessLineEdit.setToolTip(tooltip)


    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.snapGridCheckBox = \
            PM_CheckBox(inPmGroupBox,
                        text = "Snap to grid",
                        state = Qt.Checked
                        )
        tooltip = "Snap selection point to a nearest cell grid point."
        self.snapGridCheckBox.setToolTip(tooltip)

        self.freeViewCheckBox = \
            PM_CheckBox(inPmGroupBox,
                        text = "Enable free view",
                        state = Qt.Unchecked
                    )

    def _loadDisplayOptionsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Display Options groupbox.
        @param inPmGroupBox: The Display Options groupbox
        @type  inPmGroupBox: L{PM_GroupBox}
        """

        displayChoices = ['Tubes', 'Spheres']

        self.dispModeComboBox = \
            PM_ComboBox( inPmGroupBox,
                         label        = 'Display style:',
                         choices      = displayChoices,
                         index        = 0,
                         setAsDefault = False,
                         spanWidth    = False )


        self.gridLineCheckBox = PM_CheckBox(inPmGroupBox,
                                            text = "Show grid lines",
                                            widgetColumn = 0,
                                            state        = Qt.Checked)


        self.fullModelCheckBox = PM_CheckBox(inPmGroupBox,
                                            text = "Show model",
                                            widgetColumn = 0,
                                            state        = Qt.Unchecked)

    def _addWhatsThisText(self):
        """
        What's This text for 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_CookiePropertyManager
        whatsThis_CookiePropertyManager(self)

    def _addToolTipText(self):
        """
        What's Tool Tip text for widgets in this Property Manager.
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_CookiePropertyManager
        ToolTip_CookiePropertyManager(self)
Beispiel #52
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 TestGraphics_PropertyManager(Command_PropertyManager):
    """
    The TestGraphics_PropertyManager class provides a Property Manager
    for the Test Graphics 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         =  "Test Graphics"
    pmName        =  title
    iconPath      =  None ###k "ui/actions/View/Stereo_View.png" ### FIX - use some generic or default icon


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

        self.showTopRowButtons( PM_DONE_BUTTON |
                                PM_WHATS_THIS_BUTTON)

        msg = "Test the performance effect of graphics settings below. " \
              "(To avoid bugs, choose testCase before bypassing paintGL.)"

        self.updateMessage(msg)


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

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        from widgets.prefs_widgets  import ObjAttr_StateRef ### toplevel

        self._cb2 = \
            PM_CheckBox(pmGroupBox,
                        text         = "redraw continuously",
                        )
        self._cb2.connectWithState( ObjAttr_StateRef( self.command, 'redraw_continuously' ))

        self._cb3 = \
            PM_CheckBox(pmGroupBox,
                        text         = "spin model",
                        )
        self._cb3.connectWithState( ObjAttr_StateRef( self.command, 'spin_model' ))

        self._cb4 = \
            PM_CheckBox(pmGroupBox,
                        text         = "print fps to console",
                        )
        self._cb4.connectWithState( ObjAttr_StateRef( self.command, 'print_fps' ))

        self._cb1 = \
            PM_CheckBox(pmGroupBox,
                        text         = "replace paintGL with testCase",
                        )
        self._cb1.connectWithState( ObjAttr_StateRef( self.command, 'bypass_paintgl' ))
            # note: this state (unlike the highest-quality staterefs)
            # is not change-tracked [as of 081003], so nothing aside from
            # user clicks on this checkbox should modify it after this runs,
            # or our UI state will become out of sync with the state.

        self.testCase_ComboBox = PM_ComboBox(pmGroupBox,
                                      label =  "testCase:", labelColumn = 0,
                                      choices = self.command.testCaseChoicesText,
                                      setAsDefault = False )
        self.testCase_ComboBox.setCurrentIndex(self.command.testCaseIndex)

        self.nSpheres_ComboBox = PM_ComboBox(pmGroupBox,
                                      label =  "n x n spheres:", labelColumn = 0,
                                      choices = self.command._NSPHERES_CHOICES,
                                      setAsDefault = False )
        nSpheres_index = self.command._NSPHERES_CHOICES.index( str( self.command.nSpheres) )
        self.nSpheres_ComboBox.setCurrentIndex( nSpheres_index)
        self._set_nSpheresIndex( nSpheres_index)

        self.detail_level_ComboBox = PM_ComboBox(pmGroupBox,
                                      label =  "Level of detail:", labelColumn = 0,
                                      choices = ["Low", "Medium", "High", "Variable"],
                                      setAsDefault = False )
        lod = env.prefs[levelOfDetail_prefs_key]
        if lod > 2:
            lod = 2
        if lod < 0: # only lod == -1 is legal here
            lod = 3
        self.detail_level_ComboBox.setCurrentIndex(lod)
        self.set_level_of_detail_index(lod)

        self._updateWidgets()

##    def updateUI(self): # BUG: this is not being called -- I guess the bypassed paintGL doesn't call it.
##        self._updateWidgets() ### will this be too slow?

    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 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.testCase_ComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.command._set_testCaseIndex )

        change_connect(self.nSpheres_ComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self._set_nSpheresIndex )

        change_connect(self.detail_level_ComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                           # in current code, SIGNAL("activated(int)")
                       self.set_level_of_detail_index )

        return

    # ==

    def _set_nSpheresIndex(self, index):
        self.command.nSpheres = int( self.command._NSPHERES_CHOICES[index] )

    def set_level_of_detail_index(self, level_of_detail_index): # copied from other code, renamed, revised
        """
        Change the level of detail, where <level_of_detail_index> is a value
        between 0 and 3 where:
            - 0 = low
            - 1 = medium
            - 2 = high
            - 3 = variable (based on number of atoms in the part)

        @note: the prefs db value for 'variable' is -1, to allow for higher LOD
               levels in the future.
        """
        lod = level_of_detail_index
        if lod == 3:
            lod = -1
        self.command.detailLevel = lod

    def _updateWidgets(self):
        """
        Update widget configuration based on state of prior widgets.
        """
##        # presently, the LOD is not noticed by the test cases... oops, not true!
##        self.detail_level_ComboBox.setEnabled( not self.command.bypass_paintgl )
        return

    pass
Beispiel #54
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    
Beispiel #55
0
 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 _loadGroupBox1(self, pmGroupBox):
        """Load widgets into groupbox 1 (passed as pmGroupBox)."""

        # cylinder height (a double, stored as a preferences value)

        cylinderHeight_stateref = Preferences_StateRef_double(
            CYLINDER_HEIGHT_PREFS_KEY,
            CYLINDER_HEIGHT_DEFAULT_VALUE )
            ### TODO: ask model object for this ref; this code should not need to know what kind it is (from prefs or model)
        
        self.cylinderHeightSpinbox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "cylinder height:",
##                              value         =  CYLINDER_HEIGHT_DEFAULT_VALUE,
##                              # guess: default value or initial value (guess they can't be distinguished -- bug -- yes, doc confirms)
##                              setAsDefault  =  True,
                              ### TODO: get all the following from the stateref, whenever the connection to state is made
                              minimum       =  3,
                              maximum       =  self._sMaxCylinderHeight,
                              singleStep    =  0.25,
                              decimals      =  self._sCoordinateDecimals,
                              suffix        =  ' ' + self._sCoordinateUnits )
        # REVIEW: is it ok that the above will set some wrong defaultValue,
        # to be immediately corrected by the following connection with state?
        self.cylinderHeightSpinbox.connectWithState(
            cylinderHeight_stateref,
            debug_metainfo = True
         )

        # ==
        
        # cylinder width (a double, stored in the command object,
        #  defined there using the State macro -- note, this is not yet a good
        #  enough example for state stored in a Node)

        cylinderWidth_stateref = ObjAttr_StateRef( self.commandrun, 'cylinderWidth')

        ## TEMPORARY: just make sure it's defined in there
        junk = cylinderWidth_stateref.defaultValue
        
        self.cylinderWidthSpinbox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "cylinder width:",
##                              value         =  defaultValue,
##                              setAsDefault  =  True,
##                                  ### REVISE: the default value should come from the cylinderWidth_stateref
                                  # (and so, probably, should min, max, step, units...)
                              minimum       =  0.1,
                              maximum       =  15.0,
                              singleStep    =  0.1,
                              decimals      =  self._sCoordinateDecimals,
                              suffix        =  ' ' + self._sCoordinateUnits )
        
        self.cylinderWidthSpinbox.connectWithState(
                                cylinderWidth_stateref,
                                debug_metainfo = True )

        # ==
        
        # cylinder round caps (boolean)
        
        cylinderRoundCaps_stateref = Preferences_StateRef( CYLINDER_ROUND_CAPS_PREFS_KEY,
                                                           CYLINDER_ROUND_CAPS_DEFAULT_VALUE ) ### TODO: get from model
        ## TEMPORARY: just make sure it's defined in there
        junk = cylinderRoundCaps_stateref.defaultValue
        
        self.cylinderRoundCapsCheckbox = PM_CheckBox(pmGroupBox, text = 'round caps on cylinder')
##        self.cylinderRoundCapsCheckbox.setDefaultValue(CYLINDER_ROUND_CAPS_DEFAULT_VALUE)
##            # note: setDefaultValue is an extension to the PM_CheckBox API, not yet finalized
        self.cylinderRoundCapsCheckbox.connectWithState(
                                cylinderRoundCaps_stateref,
                                debug_metainfo = True )

        # ==
        
        # cylinder vertical or horizontal (boolean)
        cylinderVertical_stateref = ObjAttr_StateRef( self.commandrun, 'cylinderVertical' )
        
        self.cylinderVerticalCheckbox = PM_CheckBox(pmGroupBox, text = 'cylinder is vertical')
##        self.cylinderVerticalCheckbox.setDefaultValue(CYLINDER_VERTICAL_DEFAULT_VALUE)
##            ### REVISE: the default value should come from the stateref
        self.cylinderVerticalCheckbox.connectWithState(
                                cylinderVertical_stateref,
                                debug_metainfo = True )
        
        return # from _loadGroupBox1
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
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        from widgets.prefs_widgets  import ObjAttr_StateRef ### toplevel

        self._cb2 = \
            PM_CheckBox(pmGroupBox,
                        text         = "redraw continuously",
                        )
        self._cb2.connectWithState( ObjAttr_StateRef( self.command, 'redraw_continuously' ))

        self._cb3 = \
            PM_CheckBox(pmGroupBox,
                        text         = "spin model",
                        )
        self._cb3.connectWithState( ObjAttr_StateRef( self.command, 'spin_model' ))

        self._cb4 = \
            PM_CheckBox(pmGroupBox,
                        text         = "print fps to console",
                        )
        self._cb4.connectWithState( ObjAttr_StateRef( self.command, 'print_fps' ))

        self._cb1 = \
            PM_CheckBox(pmGroupBox,
                        text         = "replace paintGL with testCase",
                        )
        self._cb1.connectWithState( ObjAttr_StateRef( self.command, 'bypass_paintgl' ))
            # note: this state (unlike the highest-quality staterefs)
            # is not change-tracked [as of 081003], so nothing aside from
            # user clicks on this checkbox should modify it after this runs,
            # or our UI state will become out of sync with the state.

        self.testCase_ComboBox = PM_ComboBox(pmGroupBox,
                                      label =  "testCase:", labelColumn = 0,
                                      choices = self.command.testCaseChoicesText,
                                      setAsDefault = False )
        self.testCase_ComboBox.setCurrentIndex(self.command.testCaseIndex)

        self.nSpheres_ComboBox = PM_ComboBox(pmGroupBox,
                                      label =  "n x n spheres:", labelColumn = 0,
                                      choices = self.command._NSPHERES_CHOICES,
                                      setAsDefault = False )
        nSpheres_index = self.command._NSPHERES_CHOICES.index( str( self.command.nSpheres) )
        self.nSpheres_ComboBox.setCurrentIndex( nSpheres_index)
        self._set_nSpheresIndex( nSpheres_index)

        self.detail_level_ComboBox = PM_ComboBox(pmGroupBox,
                                      label =  "Level of detail:", labelColumn = 0,
                                      choices = ["Low", "Medium", "High", "Variable"],
                                      setAsDefault = False )
        lod = env.prefs[levelOfDetail_prefs_key]
        if lod > 2:
            lod = 2
        if lod < 0: # only lod == -1 is legal here
            lod = 3
        self.detail_level_ComboBox.setCurrentIndex(lod)
        self.set_level_of_detail_index(lod)

        self._updateWidgets()
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)
Beispiel #60
0
class ProteinDisplayStyle_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 Protein Display Style"
    pmName        =  title
    iconPath      =  "ui/actions/Edit/EditProteinDisplayStyle.png"
    
    def __init__( self, command ):
        """
        Constructor for the property manager.
        """

                     
        self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key]
        
        _superclass.__init__(self, command)        
        

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        
     
        msg = "Modify the protein display settings below."
        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 
        
        # Favorite buttons signal-slot connections.
        change_connect( self.applyFavoriteButton,
                        SIGNAL("clicked()"), 
                       self.applyFavorite)
        

        change_connect( self.addFavoriteButton,
                        SIGNAL("clicked()"), 
                       self.addFavorite)
        
        change_connect( self.deleteFavoriteButton,
                        SIGNAL("clicked()"), 
                       self.deleteFavorite)
        
        change_connect( self.saveFavoriteButton,
                        SIGNAL("clicked()"), 
                       self.saveFavorite)
        
        change_connect( self.loadFavoriteButton,
                        SIGNAL("clicked()"), 
                       self.loadFavorite)
        
        #Display group box signal slot connections
        change_connect(self.proteinStyleComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.changeProteinDisplayStyle)
        
        change_connect(self.smoothingCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self.smoothProteinDisplay)
        change_connect(self.scaleComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.changeProteinDisplayScale)
        change_connect(self.splineDoubleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.changeProteinSplineValue)
        change_connect(self.scaleFactorDoubleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.changeProteinScaleFactor)
        
        #color groupbox
        change_connect(self.proteinComponentComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.chooseProteinComponent)
        
        change_connect(self.proteinAuxComponentComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.chooseAuxilliaryProteinComponent)        
        
        change_connect(self.customColorComboBox,
                       SIGNAL("editingFinished()"),
                       self.chooseCustomColor)
        
        change_connect(self.auxColorComboBox,
                       SIGNAL("editingFinished()"),
                       self.chooseAuxilliaryColor)
        
        #change_connect(self.discColorCheckBox,
        #               SIGNAL("stateChanged(int)"),
        #               self.setDiscreteColors)
        
        change_connect(self.helixColorComboBox,
                       SIGNAL("editingFinished()"),
                       self.chooseHelixColor)
        
        change_connect(self.strandColorComboBox,
                       SIGNAL("editingFinished()"),
                       self.chooseStrandColor)
        
        change_connect(self.coilColorComboBox,
                       SIGNAL("editingFinished()"),
                       self.chooseCoilColor)

    #Protein Display methods         
        
    def  changeProteinDisplayStyle(self, idx):
        """
        Change protein display style
        
        @param idx: index of the protein display style combo box
        @type idx: int
        """
        env.prefs[proteinStyle_prefs_key] = idx
        return
    
    def  changeProteinDisplayQuality(self, idx):
        
        env.prefs[proteinStyleQuality_prefs_key] = idx
        return
    
    def  smoothProteinDisplay(self, state):
        """
        Smoooth protein display.
        
        @param state: state of the smooth protein display check box.
        @type state: int
        """
        if state == Qt.Checked:
            env.prefs[proteinStyleSmooth_prefs_key] = True
        else:
            env.prefs[proteinStyleSmooth_prefs_key] = False
        return
    
    def  changeProteinDisplayScale(self, idx):
        """
        Change protein display scale
        
        @param idx: index of the protein display scaling choices combo box
        @type idx: int
        """
        env.prefs[proteinStyleScaling_prefs_key] = idx
        return
    
    def changeProteinSplineValue(self, val):
        """
        Change protein display resolution
        @param val: value in the protein display resolution double spinbox
        @type val: double
        """
        env.prefs[proteinStyleQuality_prefs_key] = val
        return
    
    def changeProteinScaleFactor(self, val):
        """
        Change protein display scale factor
        
        @param val: value in the protein display scale factor double spinbox
        @type val: double
        """
        env.prefs[proteinStyleScaleFactor_prefs_key] = val
        return
    
    def chooseProteinComponent(self, idx):
        """
        Choose protein component to set the color of 
        
        @param idx: index of the protein component choices combo box
        @type idx: int
        """
        env.prefs[proteinStyleColors_prefs_key] = idx
        return
    
    def chooseAuxilliaryProteinComponent(self, idx):
        """
        Choose auxilliary protein component to set the color of 
        
        @param idx: index of the auxilliary protein component choices combo box
        @type idx: int
        """
        env.prefs[proteinStyleAuxColors_prefs_key] = idx - 1
        return
    
    def chooseCustomColor(self):
        """
        Choose custom color of the chosen protein component
        """
        color = self.customColorComboBox.getColor()
        env.prefs[proteinStyleCustomColor_prefs_key] = color
        return
    
    def chooseAuxilliaryColor(self):
        """
        Choose custom color of the chosen auxilliary protein component
        """
        color = self.auxColorComboBox.getColor()
        env.prefs[proteinStyleAuxCustomColor_prefs_key] = color
        return  
    
        
    def chooseHelixColor(self):
        """
        Choose helix color
        """
        color = self.helixColorComboBox.getColor()
        env.prefs[proteinStyleHelixColor_prefs_key] = color
        return
    
    def chooseStrandColor(self):
        """
        Choose strand color
        """
        color = self.strandColorComboBox.getColor()
        env.prefs[proteinStyleStrandColor_prefs_key] = color
        return     
    
    def chooseCoilColor(self):
        """
        Choose coil color
        """
        color = self.coilColorComboBox.getColor()
        env.prefs[proteinStyleCoilColor_prefs_key] = color
        return     
    
    def setDiscreteColors(self, state):
        """
        Set discrete colors.
        
        @param state: state of the set discrete colors check box.
        @type state: int
        """
        if state == Qt.Checked:
            env.prefs[proteinStyleColorsDiscrete_prefs_key] = True
        else:
            env.prefs[proteinStyleColorsDiscrete_prefs_key] = False
        return
    
    
    def show_OLD(self):
        """
        Shows the Property Manager.Extends superclass method. 
        """
        #@REVIEW: See comment in CompareProteins_PropertyManager
        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.sequenceEditor.hide()        
        
        self.updateProteinDisplayStyleWidgets()
        
        _superclass.show(self)
        
    def show(self):
        """
        Shows the Property Manager. Extends superclass method
        """
        _superclass.show(self)
        
        #@REVIEW: Is it safe to do the follwoing before calling superclass.show()?
        #-- Ninad 2008-10-02

        # Force the Global Display Style to "DNA Cylinder" so the user
        # can see the display style setting effects on any DNA in the current
        # model. The current global display style will be restored when leaving
        # this command (via self.close()).
        self.originalDisplayStyle = self.o.displayMode
            # TODO: rename that public attr of GLPane (widely used)
            # from displayMode to displayStyle. [bruce 080910 comment]
        self.o.setGlobalDisplayStyle(diPROTEIN)

        # Update all PM widgets, .
        # note: It is important to update the widgets by blocking the 
        # 'signals'. If done in the reverse order, it will generate signals 
        #when updating the PM widgets (via updateDnaDisplayStyleWidgets()), 
        #causing unneccessary repaints of the model view.
        self.updateProteinDisplayStyleWidgets()#@@@ blockSignals = True)
        return
    
    def close(self):
        """
        Closes the Property Manager. Extends superclass method.
        """
        _superclass.close(self)

        # Restore the original global display style.
        self.o.setGlobalDisplayStyle(self.originalDisplayStyle)
        return
    
    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox( self,
                                         title = "Favorites")
        self._loadGroupBox1( self._pmGroupBox1 )

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

        self._pmGroupBox3 = PM_GroupBox( self,
                                         title = "Color")
        self._loadGroupBox3( self._pmGroupBox3 )

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        @param pmGroupBox: group box that contains various favorite buttons
        @see: L{PM_GroupBox}  
        """
        # Other info
        # Not only loads the factory default settings but also all the favorite
        # files stored in the ~/Nanorex/Favorites/ProteinDisplayStyle directory
        favoriteChoices = ['Factory default settings']

        #look for all the favorite files in the favorite folder and add them to
        # the list
        from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
        _dir = find_or_make_Nanorex_subdir('Favorites/ProteinDisplayStyle')

        for file in os.listdir(_dir):
            fullname = os.path.join( _dir, file)
            if os.path.isfile(fullname):
                if fnmatch.fnmatch( file, "*.txt"):
                    # leave the extension out
                    favoriteChoices.append(file[0:len(file)-4])
        self.favoritesComboBox  = \
            PM_ComboBox( pmGroupBox,
                         choices       =  favoriteChoices,
                         spanWidth  =  True)
        self.favoritesComboBox.setWhatsThis(
            """<b> List of Favorites </b>
            <p>
            Creates a list of favorite Protein display styles. Once favorite
            styles have been added to the list using the Add Favorite button,
            the list will display the chosen favorites.
            To change the current favorite, select a current favorite from
            the list, and push the Apply Favorite button.""")

        # PM_ToolButtonRow ===============

        # Button list to create a toolbutton row.
        # Format:
        # - QToolButton, buttonId, buttonText,
        # - iconPath,
        # - tooltip, shortcut, column

        BUTTON_LIST = [
            ( "QToolButton", 1,  "APPLY_FAVORITE","ui/actions/Properties Manager/ApplyPeptideDisplayStyleFavorite.png",
              "Apply Favorite", "", 0),   
            ( "QToolButton", 2,  "ADD_FAVORITE",
              "ui/actions/Properties Manager/AddFavorite.png","Add Favorite", "", 1),
            ( "QToolButton", 3,  "DELETE_FAVORITE", "ui/actions/Properties Manager/DeleteFavorite.png",
              "Delete Favorite", "", 2),
            ( "QToolButton", 4,  "SAVE_FAVORITE",
              "ui/actions/Properties Manager/SaveFavorite.png",
              "Save Favorite", "", 3),
            ( "QToolButton", 5,  "LOAD_FAVORITE",
              "ui/actions/Properties Manager/LoadFavorite.png",
              "Load Favorite", \
              "", 4)
            ]

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

        self.favsButtonGroup.buttonGroup.setExclusive(False)
        self.applyFavoriteButton  = self.favsButtonGroup.getButtonById(1)
        self.addFavoriteButton    = self.favsButtonGroup.getButtonById(2)
        self.deleteFavoriteButton = self.favsButtonGroup.getButtonById(3)
        self.saveFavoriteButton   = self.favsButtonGroup.getButtonById(4)
        self.loadFavoriteButton   = self.favsButtonGroup.getButtonById(5)

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box.
        
        @param pmGroupBox: group box that contains protein display choices
        @see: L{PM_GroupBox}  
        
        """
        proteinStyleChoices = ['CA trace (wire)', 
                               'CA trace (cylinders)', 
                               'CA trace (ball and stick)',
                               'Tube',
                               'Ladder',
                               'Zigzag',
                               'Flat ribbon',
                               'Solid ribbon',
                               'Cartoons',
                               'Fancy cartoons',
                               'Peptide tiles'
                               ]

        self.proteinStyleComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Style:",
                         choices       =  proteinStyleChoices,
                         setAsDefault  =  True)
            
        scaleChoices = ['Constant', 'Secondary structure', 'B-factor']

        self.scaleComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Scaling:",
                         choices       =  scaleChoices,
                         setAsDefault  =  True)
        self.scaleFactorDoubleSpinBox = \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Scaling factor:",
                              value         =  1.00,
                              setAsDefault  =  True,
                              minimum       =  0.1,
                              maximum       =  3.0,
                              decimals      =  1,
                              singleStep    =  0.1 )
   
        self.splineDoubleSpinBox = \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Resolution:",
                              value         =  3,
                              setAsDefault  =  True,
                              minimum       =  2,
                              maximum       =  8,
                              decimals      =  0,
                              singleStep    =  1 )
        
        self.smoothingCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Smoothing",
                         setAsDefault = True)
        
    def _loadGroupBox3(self, pmGroupBox):
        """
        Load widgets in group box.
        @param pmGroupBox: group box that contains various color choices
        @see: L{PM_GroupBox} 
        """
        colorChoices = ['Chunk', 'Chain', 'Order', 'Hydropathy', 'Polarity',
                        'Acidity', 'Size', 'Character', 'Number of contacts',
                        'Secondary structure type', 'Secondary structure order',
                        'B-factor', 'Occupancy', 'Custom']

        self.proteinComponentComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Color by:",
                         choices       =  colorChoices,
                         setAsDefault  =  True)

        colorList = [orange, yellow, red, magenta, 
                       cyan, blue, white, black, gray]
        
        colorNames = ["Orange(default)", "Yellow", "Red", "Magenta", 
                        "Cyan", "Blue", "White", "Black", "Other color..."]
        
        self.customColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                            colorList = colorList,
                            colorNames = colorNames,
                            label      = "Custom:",
                            color      = orange,
                            setAsDefault  =  True)
                            
        colorChoices1 = [ 'Same as main color', 'Lighter', 'Darker', 
                          'Gray', 'Custom']
        
        self.proteinAuxComponentComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Aux:",
                         choices       =  colorChoices1,
                         setAsDefault  =  True)
        
        colorListAux = [orange, yellow, red, magenta,cyan, blue, white, black, gray]
        
        colorNamesAux = ["Orange(default)", "Yellow", "Red", "Magenta", "Cyan", 
                         "Blue", "White", "Black", "Other color..."]
        
        self.auxColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                             colorList = colorListAux,
                             colorNames = colorNamesAux, 
                             label = "Custom aux:",
                             color = gray,
                             setAsDefault  =  True)

        #self.discColorCheckBox = \
        #    PM_CheckBox( pmGroupBox,
        #                 text = "Discretize colors",
        #                 setAsDefault = True
        #                 )
        # 
        colorListHelix = [red, yellow, gray, magenta, 
                          cyan, blue, white, black, orange]
        
        colorNamesHelix = ["Red(default)", "Yellow", "Gray", "Magenta", 
                           "Cyan", "Blue", "White", "Black", "Other color..."]
        
        self.helixColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                            colorList = colorListHelix,
                            colorNames = colorNamesHelix,  
                            label      = "Helix:",
                            color      = red,
                            setAsDefault  =  True)
        
        colorListStrand = [cyan, yellow, gray, magenta, 
                           red, blue, white, black, orange]
        
        colorNamesStrand = ["Cyan(default)", "Yellow", "Gray", "Magenta", 
                            "Red", "Blue", "White", "Black", "Other color..."]
        
        self.strandColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                            colorList = colorListStrand,
                            colorNames = colorNamesStrand, 
                            label      = "Strand:",
                            color      = cyan,
                            setAsDefault  =  True)

        self.coilColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                            colorList = colorListAux,
                            colorNames = colorNamesAux,
                            label      = "Coil:",
                            color      = orange,
                            setAsDefault  =  True)

    def updateProteinDisplayStyleWidgets( self ):
        """
        Updates all the Protein Display style widgets based on the current pref keys
        values
        """
        self.proteinStyleComboBox.setCurrentIndex(env.prefs[proteinStyle_prefs_key]) 
        self.splineDoubleSpinBox.setValue(env.prefs[proteinStyleQuality_prefs_key])  
        if env.prefs[proteinStyleSmooth_prefs_key] == True:        
            self.smoothingCheckBox.setCheckState(Qt.Checked)
        else:
            self.smoothingCheckBox.setCheckState(Qt.Unchecked)
        self.scaleComboBox.setCurrentIndex(env.prefs[proteinStyleScaling_prefs_key])
        self.scaleFactorDoubleSpinBox.setValue(env.prefs[proteinStyleScaleFactor_prefs_key])         
        self.proteinComponentComboBox.setCurrentIndex(env.prefs[proteinStyleColors_prefs_key])         
        self.customColorComboBox.setColor(env.prefs[proteinStyleCustomColor_prefs_key])
        self.proteinAuxComponentComboBox.setCurrentIndex(env.prefs[proteinStyleAuxColors_prefs_key])        
        self.auxColorComboBox.setColor(env.prefs[proteinStyleAuxCustomColor_prefs_key])
        #if env.prefs[proteinStyleColorsDiscrete_prefs_key] == True:        
        #    self.discColorCheckBox.setCheckState(Qt.Checked)  
        #else:
        #    self.discColorCheckBox.setCheckState(Qt.Unchecked)   
        self.helixColorComboBox.setColor(env.prefs[proteinStyleHelixColor_prefs_key])
        self.strandColorComboBox.setColor(env.prefs[proteinStyleStrandColor_prefs_key])
        self.coilColorComboBox.setColor(env.prefs[proteinStyleCoilColor_prefs_key])      
        return

    def applyFavorite(self):
        """
        Apply a favorite to the current display chosen in the favorites combo box
        """
        current_favorite = self.favoritesComboBox.currentText()
        if current_favorite == 'Factory default settings':
            env.prefs.restore_defaults(proteinDisplayStylePrefsList)
        else:
            favfilepath = getFavoritePathFromBasename(current_favorite)
            loadFavoriteFile(favfilepath)

        self.updateProteinDisplayStyleWidgets()
        return

    def addFavorite(self):
        """
        create and add favorite to favorites directory and favorites combo box
        in PM
        @note: Rules and other info:
         - The new favorite is defined by the current Protein display style 
           settings.
         - The user is prompted to type in a name for the new
           favorite.
         - The Protein display style settings are written to a file in a special
           directory on the disk
          (i.e. $HOME/Nanorex/Favorites/ProteinDisplayStyle/$FAV_NAME.txt).
         - The name of the new favorite is added to the list of favorites in
           the combobox, which becomes the current option.
           Existence of a favorite with the same name is checked in the above
           mentioned location and if a duplicate exists, then the user can either
           overwrite and provide a new name.
        """


        # Prompt user for a favorite name to add.
        from widgets.simple_dialogs import grab_text_line_using_dialog

        ok1, name = \
          grab_text_line_using_dialog(
              title = "Add new favorite",
              label = "favorite name:",
              iconPath = "ui/actions/Properties Manager/AddFavorite.png",
              default = "" )
        if ok1:
            # check for duplicate files in the
            # $HOME/Nanorex/Favorites/DnaDisplayStyle/ directory

            fname = getFavoritePathFromBasename( name )
            if os.path.exists(fname):

                #favorite file already exists!

                _ext= ".txt"
                ret = QMessageBox.warning( self, "Warning!",
                "The favorite file \"" + name + _ext + "\"already exists.\n"
                "Do you want to overwrite the existing file?",
                "&Overwrite", "&Cancel", "",
                0,    # Enter == button 0
                1)   # Escape == button 1

                if ret == 0:
                    #overwrite favorite file
                    ok2, text = writeProteinDisplayStyleSettingsToFavoritesFile(name)
                    indexOfDuplicateItem = self.favoritesComboBox.findText(name)
                    self.favoritesComboBox.removeItem(indexOfDuplicateItem)
                    print "Add Favorite: removed duplicate favorite item."
                else:
                    env.history.message("Add Favorite: cancelled overwriting favorite item.")
                    return

            else:
                ok2, text = writeProteinDisplayStyleSettingsToFavoritesFile(name)
        else:
            # User cancelled.
            return
        if ok2:

            self.favoritesComboBox.addItem(name)
            _lastItem = self.favoritesComboBox.count()
            self.favoritesComboBox.setCurrentIndex(_lastItem - 1)
            msg = "New favorite [%s] added." % (text)
        else:
            msg = "Can't add favorite [%s]: %s" % (name, text) # text is reason why not

        env.history.message(msg)

        return

    def deleteFavorite(self):
        """
        Delete favorite file from the favorites directory
        """
        currentIndex = self.favoritesComboBox.currentIndex()
        currentText = self.favoritesComboBox.currentText()
        if currentIndex == 0:
            msg = "Cannot delete '%s'." % currentText
        else:
            self.favoritesComboBox.removeItem(currentIndex)
            # delete file from the disk
            deleteFile= getFavoritePathFromBasename( currentText )
            os.remove(deleteFile)
            msg = "Deleted favorite named [%s].\n" \
                "and the favorite file [%s.txt]." \
                % (currentText, currentText)
        env.history.message(msg)
        return

    def saveFavorite(self):
        """
        Save favorite file in a user chosen location
        """
        cmd = greenmsg("Save Favorite File: ")
        env.history.message(greenmsg("Save Favorite File:"))
        current_favorite = self.favoritesComboBox.currentText()
        favfilepath = getFavoritePathFromBasename(current_favorite)
        formats = \
                "Favorite (*.txt);;"\
                "All Files (*.*)"
        directory = self.currentWorkingDirectory
        saveLocation = directory + "/" + current_favorite + ".txt"
        fn = QFileDialog.getSaveFileName(
            self,
            "Save Favorite As", # caption
            favfilepath, #where to save
            formats, # file format options
            QString("Favorite (*.txt)") # selectedFilter
            )
        if not fn:
            env.history.message(cmd + "Cancelled")
        else:
            dir, fil = os.path.split(str(fn))
            self.setCurrentWorkingDirectory(dir)
            saveFavoriteFile(str(fn), favfilepath)
        return

    def setCurrentWorkingDirectory(self, dir = None):
        """
        Set dir as current working diretcory
        
        @param dir: dirname
        @type dir: str
        """
        if os.path.isdir(dir):
            self.currentWorkingDirectory = dir
            self._setWorkingDirectoryInPrefsDB(dir)
        else:
            self.currentWorkingDirectory =  getDefaultWorkingDirectory()
        return    
    
    def _setWorkingDirectoryInPrefsDB(self, workdir = None):
        """
        Set workdir as current working diretcory in prefDB
        
        @param workdir: dirname
        @type workdir: str
        """
        if not workdir:
            return    
        workdir = str(workdir)
        if os.path.isdir(workdir):
            workdir = os.path.normpath(workdir)
            env.prefs[workingDirectory_prefs_key] = workdir # Change pref in prefs db.            
        else:
            msg = "[" + workdir + "] is not a directory. Working directory was not changed."
            env.history.message( redmsg(msg))
        return
    
    def loadFavorite(self):
        """
        Load a favorite file
        """ 
        # If the file already exists in the favorites folder then the user is
        # given the option of overwriting it or renaming it

        env.history.message(greenmsg("Load Favorite File:"))
        formats = \
                    "Favorite (*.txt);;"\
                    "All Files (*.*)"

        directory = self.currentWorkingDirectory
        if directory == '':
            directory= getDefaultWorkingDirectory()
        fname = QFileDialog.getOpenFileName(self,
                                         "Choose a file to load",
                                         directory,
                                         formats)
        if not fname:
            env.history.message("User cancelled loading file.")
            return
        else:
            dir, fil = os.path.split(str(fname))
            self.setCurrentWorkingDirectory(dir)
            canLoadFile=loadFavoriteFile(fname)
            if canLoadFile == 1:
                #get just the name of the file for loading into the combobox
                favName = os.path.basename(str(fname))
                name = favName[0:len(favName)-4]
                indexOfDuplicateItem = self.favoritesComboBox.findText(name)
                #duplicate exists in combobox
                if indexOfDuplicateItem != -1:
                    ret = QMessageBox.warning( self, "Warning!",
                                               "The favorite file \"" + name +
                                               "\"already exists.\n"
                                               "Do you want to overwrite the existing file?",
                                               "&Overwrite", "&Rename", "&Cancel",
                                               0,    # Enter == button 0
                                               1   # button 1
                                               )
                    if ret == 0:
                        self.favoritesComboBox.removeItem(indexOfDuplicateItem)
                        self.favoritesComboBox.addItem(name)
                        _lastItem = self.favoritesComboBox.count()
                        self.favoritesComboBox.setCurrentIndex(_lastItem - 1)
                        ok2, text = writeProteinDisplayStyleSettingsToFavoritesFile(name)
                        msg = "Overwrote favorite [%s]." % (text)
                        env.history.message(msg)
                    elif ret == 1:
                        # add new item to favorites folder as well as combobox
                        self.addFavorite()
                    else:
                        #reset the display setting values to factory default
                        factoryIndex = self.favoritesComboBox.findText(
                                             'Factory default settings')
                        self.favoritesComboBox.setCurrentIndex(factoryIndex)
                        env.prefs.restore_defaults(proteinDisplayStylePrefsList)

                        env.history.message("Cancelled overwriting favorite file.")
                        return
                else:
                    self.favoritesComboBox.addItem(name)
                    _lastItem = self.favoritesComboBox.count()
                    self.favoritesComboBox.setCurrentIndex(_lastItem - 1)
                    msg = "Loaded favorite [%s]." % (name)
                    env.history.message(msg) 
                self.updateProteinDisplayStyleWidgets()  
        return

    def _addWhatsThisText( self ):
        """
        Add what's this text for this PM
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditDnaDisplayStyle_PropertyManager
        WhatsThis_EditDnaDisplayStyle_PropertyManager(self)

    def _addToolTipText(self):
        """
        Add tool tip text to all widgets.
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager 
        ToolTip_EditProteinDisplayStyle_PropertyManager(self)