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

        includeStrandsChoices = [
            "All strands in model", "Selected strands only"
        ]

        self.includeStrandsComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Include strands:",
                         choices       =  includeStrandsChoices,
                         setAsDefault  =  True)

        self.numberOfBasesLineEdit  = \
            PM_LineEdit( pmGroupBox,
                         label  =  "Total nucleotides:",
                         text   = str(self.getNumberOfBases()))
        self.numberOfBasesLineEdit.setEnabled(False)

        self.numberOfXBasesLineEdit  = \
            PM_LineEdit( pmGroupBox,
                         label  =  "Unassigned:",
                         text   = str(self.getNumberOfBases(unassignedOnly = True)))
        self.numberOfXBasesLineEdit.setEnabled(False)

        self.viewDnaOrderFileButton = \
            PM_PushButton( pmGroupBox,
                           label     = "",
                           text      = "View DNA Order File...",
                           spanWidth = True)
        return
    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 _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        self.structure1LineEdit = PM_LineEdit(pmGroupBox, label="First structure:", setAsDefault=False)
        self.structure1LineEdit.setEnabled(False)

        self.structure2LineEdit = PM_LineEdit(pmGroupBox, label="Second structure:", setAsDefault=False)
        self.structure2LineEdit.setEnabled(False)

        self.thresholdDoubleSpinBox = PM_DoubleSpinBox(
            pmGroupBox,
            label="Threshold:",
            value=self.threshold,
            setAsDefault=True,
            minimum=0.0,
            maximum=360.0,
            decimals=1,
            singleStep=30.0,
            suffix=" deg",
            spanWidth=False,
        )

        self.comparePushButton = PM_PushButton(pmGroupBox, text="Compare", setAsDefault=True)

        self.hidePushButton = PM_PushButton(pmGroupBox, text="Hide differences", setAsDefault=True)
        return
    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)
Esempio n. 5
0
    def _loadGroupBox2(self, pmGroupBox):
        """
        load widgets in groupbox2
        """

        self.strandListWidget = PM_SelectionListWidget(pmGroupBox,
                                                       self.win,
                                                       label="",
                                                       heightByRows=9)
        self.strandListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')

        self.editStrandPropertiesButton = PM_PushButton(
            pmGroupBox, label="", text="Edit Properties...")
        self.editStrandPropertiesButton.setEnabled(False)
Esempio n. 6
0
 def _loadPM_PushButton(self, inPmGroupBox):
     """
     PM_PushButton widgets.
     """
     
     self.pushButton1 = \
         PM_PushButton( inPmGroupBox,
                        label = "",
                        text  = "PushButton 1" )
     
     self.pushButton2 = \
         PM_PushButton( inPmGroupBox,
                        label     = "",
                        text      = "PushButton 2",
                        spanWidth = True )
    def _loadGroupBox2(self, pmGroupBox):
        """
        load widgets in groupbox3
        """

        self.segmentListWidget = PM_SelectionListWidget(pmGroupBox,
                                                        self.win,
                                                        label="",
                                                        heightByRows=12)
        self.segmentListWidget.setObjectName('Segment_list_widget')
        self.segmentListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')

        self.editSegmentPropertiesButton = PM_PushButton(
            pmGroupBox, label="", text="Edit Properties...")
        self.editSegmentPropertiesButton.setEnabled(False)
    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 _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
Esempio n. 10
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)
Esempio n. 11
0
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box 1.
        @param pmGroupBox: group box that contains protein name combo box and 
                        number of amino acids spin box
        @see: L{PM_GroupBox}                
        """
        self._updateProteinList()
        if len(self.protein_name_list) >= 1:
            self.set_current_protein_chunk_name(self.protein_name_list[0])
        self.structureComboBox = PM_ComboBox(pmGroupBox,
                                             label="Name:",
                                             choices=self.protein_name_list,
                                             setAsDefault=False)

        #Urmi 20080713: May be useful to set the minimum value to not zero
        #Now it does not matter, since its disabled. But zero as the minimum
        #value in a spinbox does not work otherwise.
        self.numberOfAASpinBox = \
            PM_SpinBox( pmGroupBox,
                        label         =  "Amino Acids:",
                        value         =  0,
                        setAsDefault  =  False,
                        minimum       =  0,
                        maximum       =  10000 )
        #for now we do not allow changing number of residues
        self.numberOfAASpinBox.setEnabled(False)
        self.editPropertiesPushButton = PM_PushButton(pmGroupBox,
                                                      text="Edit Sequence",
                                                      setAsDefault=True)
 def _loadGroupBox1(self, pmGroupBox):
     """
     Load widgets in group box.
     """
     
     includeStrandsChoices = ["All strands in model",
                              "Selected strands only"]
     
     self.includeStrandsComboBox  = \
         PM_ComboBox( pmGroupBox,
                      label         =  "Include strands:", 
                      choices       =  includeStrandsChoices,
                      setAsDefault  =  True)
     
     self.numberOfBasesLineEdit  = \
         PM_LineEdit( pmGroupBox,
                      label  =  "Number of bases:",
                      text   = str(self.getNumberOfBases()))
     self.numberOfBasesLineEdit.setEnabled(False)
     
     self.viewDnaOrderFileButton = \
         PM_PushButton( pmGroupBox,
                        label     = "",
                        text      = "View DNA Order File...",
                        spanWidth = True)
Esempio n. 13
0
    def _loadBreakOptionsGroupbox(self, pmGroupBox):
        """
        Load widgets in this group box.
        """

        self.assignColorToBrokenDnaStrandsCheckBox = \
            PM_CheckBox(pmGroupBox ,
                        text         = 'Assign new color to broken strands',
                        widgetColumn = 0,
                        spanWidth = True)

        connect_checkbox_with_boolean_pref(
            self.assignColorToBrokenDnaStrandsCheckBox,
            assignColorToBrokenDnaStrands_prefs_key)



        self.basesBeforeNextBreakSpinBox = \
            PM_SpinBox( pmGroupBox,
                        label         =  "Break Every:",
                        value         =  3,
                        setAsDefault  =  False,
                        minimum       =  1,
                        maximum       =  10000,
                        suffix       = " bases"
                        )

        connect_spinBox_with_pref(
            self.basesBeforeNextBreakSpinBox,
            breakStrandsCommand_numberOfBasesBeforeNextBreak_prefs_key)

        self.breakAllStrandsButton = PM_PushButton(pmGroupBox,
                                                   label="",
                                                   text="do it")

        self._dnaStrandChooserGroupBox = PM_ObjectChooser(
            pmGroupBox,
            self.command,
            modelObjectType=self.win.assy.DnaStrand,
            title="Choose strands ")

        if not DEBUG_BREAK_OPTIONS_FEATURE:
            self._dnaStrandChooserGroupBox.hide()
            self.breakAllStrandsButton.hide()
            self.basesBeforeNextBreakSpinBox.hide()
    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)
Esempio n. 15
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)
Esempio n. 16
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)
    def _loadGroupBox1(self, pmGroupBox):
        """
        load widgets in groupbox1
        """

        self.nanotubeListWidget = PM_SelectionListWidget(pmGroupBox, self.win, label="", heightByRows=12)
        self.nanotubeListWidget.setObjectName("nanotubeListWidget")
        self.nanotubeListWidget.setTagInstruction("PICK_ITEM_IN_GLPANE")

        self.editNanotubePropertiesButton = PM_PushButton(pmGroupBox, label="", text="Edit Properties...")
        self.editNanotubePropertiesButton.setEnabled(False)
        return
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        self.structure1LineEdit = \
            PM_LineEdit( pmGroupBox,
                         label         =  "First structure:",
                         setAsDefault  =  False)
        self.structure1LineEdit.setEnabled(False)

        self.structure2LineEdit = \
            PM_LineEdit( pmGroupBox,
                         label         =  "Second structure:",
                         setAsDefault  =  False)
        self.structure2LineEdit.setEnabled(False)

        self.thresholdDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Threshold:",
                              value         =  self.threshold,
                              setAsDefault  =  True,
                              minimum       =  0.0,
                              maximum       =  360.0,
                              decimals      =  1,
                              singleStep    =  30.0,
                              suffix        = " deg",
                              spanWidth = False)

        self.comparePushButton  = \
            PM_PushButton( pmGroupBox,
                         text         =  "Compare",
                         setAsDefault  =  True)

        self.hidePushButton  = \
            PM_PushButton( pmGroupBox,
                         text         =  "Hide differences",
                         setAsDefault  =  True)
        return
Esempio n. 19
0
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in groupbox1.
        """

        self.proteinListWidget = PM_SelectionListWidget(pmGroupBox,
                                                        self.win,
                                                        label="",
                                                        heightByRows=6)
        self.proteinListWidget.setObjectName('Peptide_list_widget')
        self.proteinListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')

        self.editPeptidePropertiesButton = PM_PushButton(
            pmGroupBox, label="", text="Edit Properties...")
        self.editPeptidePropertiesButton.setEnabled(False)

        self.compareProteinsButton = PM_PushButton(pmGroupBox,
                                                   label="",
                                                   text="Compare Proteins...")
        self.compareProteinsButton.setEnabled(False)

        return
Esempio n. 20
0
 def _loadGroupBox1(self, pmGroupBox):
     """
     Load widgets in groupbox1.
     """
     
     self.proteinListWidget = PM_SelectionListWidget(pmGroupBox,
                                                    self.win,
                                                    label = "",
                                                    heightByRows = 6 )
     self.proteinListWidget.setObjectName('Peptide_list_widget')
     self.proteinListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')
     
     self.editPeptidePropertiesButton = PM_PushButton(pmGroupBox,
                                                      label = "",
                                                      text  = "Edit Properties..." )
     self.editPeptidePropertiesButton.setEnabled(False)
     
     self.compareProteinsButton = PM_PushButton(pmGroupBox,
                                                      label = "",
                                                      text  = "Compare Proteins..." )
     self.compareProteinsButton.setEnabled(False)
     
     return
 def _loadGroupBox3(self, pmGroupBox):
     """
     load widgets in groupbox3
     """
     
     self.segmentListWidget = PM_SelectionListWidget(pmGroupBox,
                                                    self.win,
                                                    label = "",
                                                    heightByRows = 4 )
     self.segmentListWidget.setObjectName('Segment_list_widget')
     self.segmentListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')
     
 
     self.editSegmentPropertiesButton = PM_PushButton( 
         pmGroupBox,
         label = "",
         text  = "Edit Properties..." )
     self.editSegmentPropertiesButton.setEnabled(False)
     
     self.searchForCrossoversButton = PM_PushButton( 
         pmGroupBox,
         label = "",
         text  = "Search For Crossovers..." )
     self.searchForCrossoversButton.setEnabled(False)
 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 _loadGroupBox2(self, pmGroupBox):
     """
     load widgets in groupbox2
     """
     
     self.strandListWidget = PM_SelectionListWidget(pmGroupBox,
                                                    self.win,
                                                    label = "",
                                                    heightByRows = 9 )
     self.strandListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')
 
     self.editStrandPropertiesButton = PM_PushButton( 
         pmGroupBox,
         label = "",
         text  = "Edit Properties..." )
     self.editStrandPropertiesButton.setEnabled(False)
Esempio n. 24
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
    def _loadBreakOptionsGroupbox(self, pmGroupBox):
        """
        Load widgets in this group box.
        """

        self.assignColorToBrokenDnaStrandsCheckBox = \
            PM_CheckBox(pmGroupBox ,
                        text         = 'Assign new color to broken strands',
                        widgetColumn = 0,
                        spanWidth = True)

        connect_checkbox_with_boolean_pref(
            self.assignColorToBrokenDnaStrandsCheckBox,
            assignColorToBrokenDnaStrands_prefs_key )



        self.basesBeforeNextBreakSpinBox = \
            PM_SpinBox( pmGroupBox,
                        label         =  "Break Every:",
                        value         =  3,
                        setAsDefault  =  False,
                        minimum       =  1,
                        maximum       =  10000,
                        suffix       = " bases"
                        )

        connect_spinBox_with_pref(
            self.basesBeforeNextBreakSpinBox,
            breakStrandsCommand_numberOfBasesBeforeNextBreak_prefs_key)

        self.breakAllStrandsButton = PM_PushButton(
            pmGroupBox,
            label = "",
            text  = "do it" )


        self._dnaStrandChooserGroupBox = PM_ObjectChooser(
            pmGroupBox,
            self.command,
            modelObjectType = self.win.assy.DnaStrand,
            title = "Choose strands " )

        if not DEBUG_BREAK_OPTIONS_FEATURE:
            self._dnaStrandChooserGroupBox.hide()
            self.breakAllStrandsButton.hide()
            self.basesBeforeNextBreakSpinBox.hide()
    def _loadToPositionGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Translate To a given Position group box, which is 
        present within the Translate groupbox.
        @param inPmGroupBox: Translate To Position group box in the Translate 
                             group box.
        @type  inPmGroupBox: L{PM_GroupBox}
        """

        self.toPositionspinboxes = PM_CoordinateSpinBoxes(inPmGroupBox)

        self.moveXSpinBox = self.toPositionspinboxes.xSpinBox
        self.moveYSpinBox = self.toPositionspinboxes.ySpinBox
        self.moveZSpinBox = self.toPositionspinboxes.zSpinBox


        self.moveAbsoluteButton = \
            PM_PushButton( inPmGroupBox,
                           label     = "",
                           text      = "Move Selection",
                           spanWidth = True )
Esempio n. 27
0
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        convertChoices = [
            "Convert from PAM3 to PAM5", "Convert from PAM5 to PAM3"
        ]

        self._convertChoiceComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "",
                         choices       =  convertChoices,
                         index         =  0,
                         setAsDefault  =  True,
                         spanWidth     =  True)

        self._convertButton = \
            PM_PushButton( pmGroupBox,
                           label     = "",
                           text      = "Convert Selection Now",
                           spanWidth = True)
        return
Esempio n. 28
0
class BuildProtein_PropertyManager(EditCommand_PM):
    """
    The BuildProtein_PropertyManager class provides a Property Manager 
    for the B{Build Protein} 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 = "Build Protein"
    pmName = title
    iconPath = "ui/actions/Command Toolbar/BuildProtein/BuildProtein.png"

    current_protein = ""  # name of the single selected peptide. To be deprecated soon. --Mark 2008-12-14

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

        #Attributes for self._update_UI_do_updates() to keep track of changes
        #in these , since the last call of that method. These are used to
        #determine whether certain UI updates are needed.
        self._previousSelectionParams = None
        self._previousStructureParams = None
        self._previousCommandStackParams = None

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

        EditCommand_PM.__init__(self, command)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_CANCEL_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 and self.isAlreadyConnected:
            return

        if not isConnect and self.isAlreadyDisconnected:
            return

        self.isAlreadyConnected = isConnect
        self.isAlreadyDisconnected = not isConnect

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

        self.proteinListWidget.connect_or_disconnect_signals(isConnect)

        change_connect(self.editPeptidePropertiesButton, SIGNAL("clicked()"),
                       self._editPeptide)

        change_connect(self.compareProteinsButton, SIGNAL("clicked()"),
                       self._compareProteins)

        return

    def enable_or_disable_gui_actions(self, bool_enable=False):
        """
        Enable or disable some gui actions when this property manager is 
        opened or closed, depending on the bool_enable. 
        
        """

        #For new command API, we will always show the exit button to check
        #if Exit button really exits the subcommand and the parent command
        #(earlier there were bugs) . Regaring 'whether this should be the
        #default behavior', its a UI design issue and we will worry about it
        #later -- Ninad 2008-08-27 (based on an email exchanged with Bruce)
        pass

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

        newSelectionParams = self._currentSelectionParams()

        current_struct_params = self._currentStructureParams()

        selection_params_unchanged = same_vals(newSelectionParams,
                                               self._previousSelectionParams)

        #introducing self._previousStructureParams and
        #adding structure_params_unchanged check to the 'if' condition below
        #fixes bug 2910.
        structure_params_unchanged = same_vals(self._previousStructureParams,
                                               current_struct_params)

        current_command_stack_params = self._currentCommandStackParams()

        #Check if command stack params changed since last call of this
        #PM update method. This is used to fix bugs like 2940
        command_stack_params_unchanged = same_vals(
            self._previousCommandStackParams, current_command_stack_params)

        #No need to proceed if any of the selection/ structure and commandstack
        #parameters remained unchanged since last call. --- [CONDITION A]
        if selection_params_unchanged and structure_params_unchanged and command_stack_params_unchanged:
            #This second condition above fixes bug 2888
            if 0:
                print "Build Protein: _update_UI_do_updates() - DO NOTHING"
            return

        self._previousStructureParams = current_struct_params
        self._previousSelectionParams = newSelectionParams
        self._previousCommandStackParams = current_command_stack_params

        ##if not selection_params_unchanged or not command_stack_params_unchanged and structure_params_unchanged:
        if structure_params_unchanged:
            #NOTE: We checked if either of the selection struct or command stack
            #parameters or both changed. (this was referred as '[CONDITION A]'
            #above). So, this condition (structure_params_unchanged)also means
            #either selection or command stack or both parameters were changed.

            if not command_stack_params_unchanged:
                #update the protein list widget *before* updating the selection if
                #the command stack changed. This ensures that the selection box
                #appears around the list widget items that are selected.
                self.updateProteinListWidget()

            selectedProteins = newSelectionParams

            self.proteinListWidget.updateSelection(selectedProteins)

            # Enable/disable "Edit Sequence" button.
            if len(selectedProteins) == 1:
                self.editPeptidePropertiesButton.setEnabled(True)
            else:
                self.editPeptidePropertiesButton.setEnabled(False)

                # Enable/disable "Compare Proteins" button.
            if len(selectedProteins) == 2:
                self.compareProteinsButton.setEnabled(True)
            else:
                self.compareProteinsButton.setEnabled(False)

            return

        self.updateProteinListWidget()
        return

    def _currentCommandStackParams(self):
        """
        The return value is supposed to be used by BUILD_PROTEIN command PM ONLY
        and NOT by any subclasses.         
        
        Returns a tuple containing current command stack change indicator and 
        the name of the command 'BUILD_PROTEIN'. These 
        parameters are then used to decide whether updating widgets
        in this property manager is needed, when self._update_UI_do_updates()
        is called. 
        
        @NOTE: 
        - Command_PropertyManager.update_UI() already does a check to see if 
          any of the global change indicators in assembly (command_stack_change, 
          model_change, selection_change) changed since last call and then only
          calls self._update_UI_do_updates(). 
        - But this method is just used to keep track of the 
          local command stack change counter in order to update the list 
          widgets.      
        - This is used to fix bug 2940
        
        @see: self._update_UI_do_updates()
        """
        commandStackCounter = self.command.assy.command_stack_change_indicator(
        )
        #Append 'BUILD_PROTEIN to the tuple to be returned. This is just to remind
        #us that this method is meant for BUILD_PROTEIN command PM only. (and not
        #by any subclasses) Should we assert this? I think it will slow things
        #down so this comment is enough -- Ninad 2008-09-30
        return (commandStackCounter, 'BUILD_PROTEIN')

    def _currentSelectionParams(self):
        """
        Returns a tuple containing current selection parameters. These 
        parameters are then used to decide whether updating widgets
        in this property manager is needed when L{self.model_changed}
        method is called.
        
        @return: A tuple that contains total number of selected peptides.
        @rtype:  tuple
        
        @NOTE: This method may be renamed in future. 
        It's possible that there are other groupboxes in the PM that need to be 
        updated when something changes in the glpane.        
        """

        selectedProteins = []
        if self.command is not None:  # and self.command.hasValidStructure():
            selectedProteins = self.win.assy.getSelectedProteinChunks()
        return (selectedProteins)

    def _currentStructureParams(self):
        """
        Return current structure parameters of interest to self.model_changed. 
        Right now it only returns the number of peptides within the structure
        (or None). This is a good enough check (and no need to compare 
        each and every peptide within the structure with a previously stored 
        set of strands).
        """
        #Can it happen that the total number of peptides remains the same even
        #after some alterations to the peptides? Unlikely. (Example: a single
        #(future) Break peptide operation will increase the number of peptides
        #by one. Or Join peptides decrease it by 1)
        params = None

        if self.command:  # and self.command.hasValidStructure():
            proteinList = []
            proteinList = getAllProteinChunksInPart(self.win.assy)
            params = len(proteinList)
        return params

    def close(self):
        """
        Closes the Property Manager. Overrides EditCommand_PM.close()
        """
        #Clear tags, if any, due to the selection in the self.strandListWidget.
        #self.proteinListWidget.clear()
        env.history.statusbar_msg("")
        EditCommand_PM.close(self)
        return

    def show(self):
        """
        Show the PM. Extends superclass method.
        @note: _update_UI_do_updates() gets called immediately after this and
               updates PM widgets with their correct values/settings. 
        """

        env.history.statusbar_msg("")
        EditCommand_PM.show(self)

        # NOTE: Think about moving this msg to _update_UI_do_updates() where
        # custom msgs can be created based on the current selection, etc.
        # Mark 2008-12-14
        msg = "Select <b>Insert Peptide</b> to create a peptide chain or "\
            "select another modeling tool to modify an existing protein."
        self.updateMessage(msg)
        return

    def _editPeptide(self):
        """
        Slot for the "Edit Properties" button. 
        """

        #if not self.command.hasValidStructure():
        #    return

        proteinChunk = self.win.assy.getSelectedProteinChunk()

        if proteinChunk:
            proteinChunk.protein.edit(self.win)
        return

    def _compareProteins(self):
        """
        Slot for the "Compare Proteins" button.
        """
        self.win.commandSequencer.userEnterCommand('COMPARE_PROTEINS')
        return

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

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

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

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

        self.proteinListWidget = PM_SelectionListWidget(pmGroupBox,
                                                        self.win,
                                                        label="",
                                                        heightByRows=6)
        self.proteinListWidget.setObjectName('Peptide_list_widget')
        self.proteinListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')

        self.editPeptidePropertiesButton = PM_PushButton(
            pmGroupBox, label="", text="Edit Properties...")
        self.editPeptidePropertiesButton.setEnabled(False)

        self.compareProteinsButton = PM_PushButton(pmGroupBox,
                                                   label="",
                                                   text="Compare Proteins...")
        self.compareProteinsButton.setEnabled(False)

        return

    def updateProteinListWidget(self):
        """
        Update the peptide list widget. It shows all peptides in the part.
        """
        proteinChunkList = getAllProteinChunksInPart(self.win.assy)

        if proteinChunkList:
            self.proteinListWidget.insertItems(row=0, items=proteinChunkList)
        else:
            self.proteinListWidget.clear()
        return
class OrderDna_PropertyManager( PM_Dialog, DebugMenuMixin ):
    """
    The OrderDna_PropertyManager class provides a Property Manager 
    for the B{Order Dna} 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         =  "Order Dna"
    pmName        =  title
    iconPath      =  "ui/actions/Command Toolbar/Order_DNA.png"
    
    def __init__( self, parentCommand ):
        """
        Constructor for the property manager.
        """

        self.parentMode = parentCommand
        self.w = self.parentMode.w
        self.win = self.parentMode.w
        self.pw = self.parentMode.pw        
        self.o = self.win.glpane
        self.assy = self.win.assy
                    
        PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title)
        
        DebugMenuMixin._init1( self )

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        
        self.update_includeStrands() # Updates the message box.
        """
        if self.getNumberOfBases():
            msg = "Click on <b>View DNA Order File...</b> to preview a "\
                "DNA order for all DNA strands in the current model."
        else:
            msg = "<font color=red>There is no DNA in the current model."
        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.viewDnaOrderFileButton,
                        SIGNAL("clicked()"), 
                        self.viewDnaOrderFile)
        
        change_connect( self.includeStrandsComboBox,
                      SIGNAL("activated(int)"),
                      self.update_includeStrands )
        
    def ok_btn_clicked(self):
        """
        Slot for the OK button
        """      
        self.win.toolsDone()
        
    def show(self):
        """
        Shows the Property Manager. Overrides PM_Dialog.show.
        """
        PM_Dialog.show(self)
        self.connect_or_disconnect_signals(isConnect = True)

    def close(self):
        """
        Closes the Property Manager. Overrides PM_Dialog.close.
        """
        self.connect_or_disconnect_signals(False)
        PM_Dialog.close(self)
    
    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """        
        self._pmGroupBox1 = PM_GroupBox( self, title = "Options" )
        self._loadGroupBox1( self._pmGroupBox1 )
    
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        
        includeStrandsChoices = ["All strands in model",
                                 "Selected strands only"]
        
        self.includeStrandsComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Include strands:", 
                         choices       =  includeStrandsChoices,
                         setAsDefault  =  True)
        
        self.numberOfBasesLineEdit  = \
            PM_LineEdit( pmGroupBox,
                         label  =  "Number of bases:",
                         text   = str(self.getNumberOfBases()))
        self.numberOfBasesLineEdit.setEnabled(False)
        
        self.viewDnaOrderFileButton = \
            PM_PushButton( pmGroupBox,
                           label     = "",
                           text      = "View DNA Order File...",
                           spanWidth = True)
    
    def _addWhatsThisText( self ):
        """
        What's This text for widgets in the DNA Property Manager.  
        """
        pass
                
    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the DNA Property Manager.  
        """
        pass
    
    # Ask Bruce where this should live (i.e. class Part?) --Mark
    def getAllDnaStrands(self, selectedOnly = False):
        """
        Returns a list of all the DNA strands in the current part, or only
        the selected strands if I{selectedOnly} is True.
        
        @param selectedOnly: If True, return only the selected DNA strands.
        @type  selectedOnly: bool
        """
        
        dnaStrandList = []
         
        def func(node):
            if isinstance(node, DnaStrand):
                if selectedOnly:
                    if node.picked:
                        dnaStrandList.append(node)
                else:
                    dnaStrandList.append(node)
                    
        self.win.assy.part.topnode.apply2all(func)
        
        return dnaStrandList
    
    def getNumberOfBases(self, selectedOnly = False):
        """
        Returns the number of bases count for all the DNA strands in the 
        current part, or only the selected strand if I{selectedOnly} is True.
        
        @param selectedOnly: If True, return only the selected DNA strands.
        @type  selectedOnly: bool
        """
        dnaSequenceString = ''
        selectedOnly = self.includeStrandsComboBox.currentIndex()
        strandList = self.getAllDnaStrands(selectedOnly)
        
        for strand in strandList:
            strandSequenceString = str(strand.getStrandSequence())
            dnaSequenceString += strandSequenceString
            
        return len(dnaSequenceString)
        
    def getDnaSequence(self, format = 'CSV'):
        """
        Return the complete Dna sequence information string (i.e. all strand 
        sequences) in the specified format. 
        
        @return: The Dna sequence string
        @rtype: string
        
        """
        if format == 'CSV': #comma separated values.
            separator = ','
            
        dnaSequenceString = ''
        selectedOnly = self.includeStrandsComboBox.currentIndex()
        strandList = self.getAllDnaStrands(selectedOnly)
        
        for strand in strandList:
            dnaSequenceString = dnaSequenceString + strand.name + separator
            strandSequenceString = str(strand.getStrandSequence())
            if strandSequenceString: 
                strandSequenceString = strandSequenceString.upper()
                dnaSequenceString = dnaSequenceString + strandSequenceString
                
            dnaSequenceString = dnaSequenceString + "\n"
            
        return dnaSequenceString
        
    def viewDnaOrderFile(self, openFileInEditor = True):
        """
        Opens a text editor and loads a temporary text file containing all the 
        DNA strand names and their sequences in the current DNA object. It will
        look something like this: 

        Strand1,ATCAGCTACGCATCGCT
        Strand2,TAGTCGATGCGTAGCGA
        ...
        Strandn, ...

        The user can then save the file to a permanent location using the 
        text editor the file is loaded (and displayed) in.

        @see: Ui_DnaFlyout.orderDnaCommand
        @see: writeDnaOrderFile()
        @TODO: assy.getAllDnaObjects(). 
        """
        dnaSequence = self.getDnaSequence(format = 'CSV')

        if dnaSequence: 
            tmpdir = find_or_make_Nanorex_subdir('temp')
            fileBaseName = 'DnaOrder'
            temporaryFile = os.path.join(tmpdir, "%s.csv" % fileBaseName)            
            writeDnaOrderFile(temporaryFile, 
                              self.assy,
                              dnaSequence)      

            if openFileInEditor:
                open_file_in_editor(temporaryFile)

    def update_includeStrands(self, ignoreVal = 0):
        """
        Slot method for "Include (strands)" combobox.
        """
        
        idx = self.includeStrandsComboBox.currentIndex()
        
        includeType = ["model", "selection"]
        
        _numberOfBases = self.getNumberOfBases()
        self.numberOfBasesLineEdit.setText(str(_numberOfBases))
        
        if _numberOfBases > 0:
            self.viewDnaOrderFileButton.setEnabled(True)
            msg = "Click on <b>View DNA Order File...</b> to preview a " \
                "DNA order for all DNA strands in the current %s." \
                % includeType[idx]
        else:
            self.viewDnaOrderFileButton.setEnabled(False)
            msg = "<font color=red>" \
                "There are no DNA strands in the current %s." \
                % includeType[idx]
                
        self.updateMessage(msg)
            
class BuildDna_PropertyManager( EditCommand_PM, DebugMenuMixin ):
    """
    The BuildDna_PropertyManager class provides a Property Manager 
    for the B{Build > DNA } 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         =  "Build DNA"
    pmName        =  title
    iconPath      =  "ui/actions/Tools/Build Structures/DNA.png"

    def __init__( self, win, editCommand ):
        """
        Constructor for the Build DNA property manager.
        """
        
        #For model changed signal
        self._previousSelectionParams = None
        
        self._previousStructureParams = None
                
        #see self.connect_or_disconnect_signals for comment about this flag
        self.isAlreadyConnected = False
        self.isAlreadyDisconnected = False           
        
        EditCommand_PM.__init__( self, 
                                    win,
                                    editCommand)


        DebugMenuMixin._init1( self )

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

    
    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.strandListWidget.connect_or_disconnect_signals(isConnect)        
        self.segmentListWidget.connect_or_disconnect_signals(isConnect)
        
        change_connect(self.editStrandPropertiesButton,
                      SIGNAL("clicked()"),
                      self._editDnaStrand)
        
        change_connect(self.editSegmentPropertiesButton,
                      SIGNAL("clicked()"),
                      self._editDnaSegment)
        
        change_connect(self.searchForCrossoversButton,
                      SIGNAL("clicked()"),
                      self._enterMakeCrossoversCommand)
 
    
    def enable_or_disable_gui_actions(self, bool_enable = False):
        """
        Enable or disable some gui actions when this property manager is 
        opened or closed, depending on the bool_enable. 
        
        """
        #TODO: This is bad. It would have been much better to enable/disable 
        #gui actions using a API method in command/commandSequencer which gets 
        #called when you enter another command exiting or suspending the 
        #previous one. . At present. it doesn't exist (first needs cleanup in 
        #command/command sequencer (Done and other methods._)-- Ninad 2008-01-09
        if hasattr(self.editCommand, 'flyoutToolbar') and \
           self.editCommand.flyoutToolbar:            
            self.editCommand.flyoutToolbar.exitDnaAction.setEnabled(not bool_enable)
            
                    
    def model_changed(self):
        """       
        When the editCommand is treated as a 'command' by the 
        commandSequencer. this method will override basicCommand.model_changed.
        
        @WARNING: Ideally this property manager should implement both
               model_changed and selection_changed methods in the mode/command
               API. 
               model_changed method will be used here when the selected atom is 
               dragged, transmuted etc. The selection_changed method will be 
               used when the selection (picking/ unpicking) changes. 
               At present, selection_changed and model_changed methods are 
               called too frequently that it doesn't matter which one you use. 
               Its better to use only a single method for preformance reasons 
               (at the moment). This should change when the original 
               methods in the API are revised to be called at appropiraite 
               time. 
        """  
        
        newSelectionParams = self._currentSelectionParams()   
        
        selection_params_unchanged = same_vals(newSelectionParams, 
                                                  self._previousSelectionParams)
        
        #introduing self._previousStructureParams and adding structure_params_unchanged
        #check to the if condition below fixes bug 2910. 
        structure_params_unchanged = same_vals(self._previousStructureParams, 
                                                self._currentStructureParams())
        
        if selection_params_unchanged and \
           structure_params_unchanged:
            #This second condition above fixes bug 2888
            return
        
        self._previousStructureParams = self._currentStructureParams()
        
        if not selection_params_unchanged and structure_params_unchanged:            
            
            self._previousSelectionParams = newSelectionParams  
            
            selectedStrands, selectedSegments = newSelectionParams
            
            self.strandListWidget.updateSelection(selectedStrands) 
            self.segmentListWidget.updateSelection(selectedSegments)
            
            if len(selectedStrands) == 1:
                self.editStrandPropertiesButton.setEnabled(True)                         
            else:
                self.editStrandPropertiesButton.setEnabled(False)  
            
            if len(selectedSegments) == 1:
                self.editSegmentPropertiesButton.setText("Edit Properties...")
                self.editSegmentPropertiesButton.setEnabled(True)
            elif len(selectedSegments) > 1:
                resizeString = "Resize Selected Segments (%d)..."%len(selectedSegments)
                self.editSegmentPropertiesButton.setText(resizeString)
                self.editSegmentPropertiesButton.setEnabled(True)
                self.searchForCrossoversButton.setEnabled(True)
            else:
                self.editSegmentPropertiesButton.setText("Edit Properties...")
                self.editSegmentPropertiesButton.setEnabled(False)
                self.searchForCrossoversButton.setEnabled(False)
                         
        #Update the strand and segmment list widgets. 
        #Ideally it should only update when the structure is modified 
        #example --when structure is deleted. But as of 2008-02-21
        #this feature is not easily available in the API method. 
        #see Command class for some proposed methods such as 'something_changed'
        #etc. The list widgets are updated even when selection changes.         
        #NOTE: If this is called before listwidget's 'updateSelection' call, 
        #done above, it 'may give' (as of 2008-02-25, it is unlikely to happen 
        #because of a better implementation)  C/C++ object deleted errors. 
        #So better to do it in the end. Cause -- unknown. 
        #Guess : something to do with clearing the widget list and them readding
        #items (done by self.updateListWidgets)
        #..This probably interferes with the selection
        #within that list. So better to do it after updating the selection.
        if not structure_params_unchanged:  
            self.updateListWidgets()   
                      
    def _currentSelectionParams(self):
        """
        This needs commandSequencer to treat various 
        edit controllers as commands. Until then, the 'model_changed' method 
        (and thus this method) will  never be called.
        
        Returns a tuple containing current selection parameters. These 
        parameters are then used to decide whether updating widgets
        in this property manager is needed when L{self.model_changed} or 
        L{self.selection_changed} methods are called. 
        @return: A tuple that contains following selection parameters
                   - Total number of selected atoms (int)
                   - Selected Atom if a single atom is selected, else None
                   - Position vector of the single selected atom or None
        @rtype:  tuple
        @NOTE: The method name may be renamed in future. 
        Its possible that there are other groupboxes in the PM that need to be 
        updated when something changes in the glpane.        
        """
         
        selectedStrands = []
        selectedSegments = []
        if self.editCommand is not None and self.editCommand.hasValidStructure():
            selectedStrands = self.editCommand.struct.getSelectedStrands()
            selectedSegments = self.editCommand.struct.getSelectedSegments()             
                    
        return (selectedStrands, selectedSegments)
    
    def _currentStructureParams(self):
        """
        Return current structure parameters of interest to self.model_changed. 
        Right now it only returns the number of strands within the structure
        (or None) .  This is a good enough check (and no need to compare 
        each and evry strand within the structure with a previously stored 
        set of strands)         
        """
        #Can it happen that the total number of strands remains the same even 
        #after some alterations to the strands? Unlikely. (Example: a single
        #Break strands operation will increase the number of strands by one. 
        #Or Join strands decrease it by 1)
        params = None
        
        if self.editCommand and self.editCommand.hasValidStructure():
            strandList = []
            strandList = self.editCommand.struct.getStrands()
            params = len(strandList)
            
        return params 
    
  
    def ok_btn_clicked(self):
        """
        Slot for the OK button
        """   
        if self.editCommand:
            self.editCommand.preview_or_finalize_structure(previewing = False)
        self.win.toolsDone()
    
    def cancel_btn_clicked(self):
        """
        Slot for the Cancel button.
        """
        if self.editCommand:
            self.editCommand.cancelStructure()            
        self.win.toolsCancel()
        
    
    def close(self):
        """
        Closes the Property Manager. Overrides EditCommand_PM.close()
        """
        #Clear tags, if any, due to the selection in the self.strandListWidget.
        if self.strandListWidget:
            self.strandListWidget.clear()
        
        if self.segmentListWidget:
            self.segmentListWidget.clear()
            
        EditCommand_PM.close(self)
    
    def show(self):
        """
        Show this PM 
        As of 2007-11-20, it also shows the Sequence Editor widget and hides 
        the history widget. This implementation may change in the near future
        """
        EditCommand_PM.show(self) 
        self.updateListWidgets()    
        
    def _editDnaStrand(self):  
        """
        Enter the DnaStrand_EditCommand to edit the selected strand. 
        """
        
        if not self.editCommand.hasValidStructure():
            return
        
        selectedStrandList = self.editCommand.struct.getSelectedStrands()
        
        if len(selectedStrandList) == 1:     
            strand = selectedStrandList[0]
            strand.edit()


    def _editDnaSegment(self):
        """
        """
        if self.editCommand is not None and self.editCommand.hasValidStructure(): 
            selectedSegments = self.editCommand.struct.getSelectedSegments()
            if len(selectedSegments) == 1:
                selectedSegments[0].edit()
            elif len(selectedSegments) > 1:
                self.win.resizeSelectedDnaSegments()
    
    def _enterMakeCrossoversCommand(self):
        """
        If more than one segments in the segment list widget 
        are selected, enter make crossovers  command
        
        @BUG: This enters Make Crossover command which searches for *ALL* 
        of the selected DnaSegments in the model and not just the selected 
        segments of the DnaGroup you are editing in the BuildDna command
        This is misleading.
        
        """
        self.win.enterMakeCrossoversCommand()
                       
        
    def _update_widgets_in_PM_before_show(self):
        """
        Update various widgets  in this Property manager.
        Overrides EditCommand_PM._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.editcCommand.struct)
        
        @see: MotorPropertyManager._update_widgets_in_PM_before_show
        @see: self.show  
        """  
        self.updateListWidgets()
        
    
    def updateListWidgets(self):
        """
        Update List Widgets (strand list and segment list)
        in this property manager
        @see: self.updateSegmentListWidgets, self.updateStrandListWidget
        """
        self.updateStrandListWidget() 
        self.updateSegmentListWidget()
          
       
    def updateStrandListWidget(self):   
        """
        Update the list of items inside the strandlist widget 
        Example: Origianally it shows two srands. User now edits an
        existing dna, and deletes some of the strands, hits done. User then 
        again invokes the Edit command for this dna object -- now the strand 
        list widget must be updated so that it shows only the existing strands.
        
        @see: B{Chunk.isStrandChunk}
        @see: self.updateListWidgets, self.updateSegmentListWidget
        """
        #TODO: 
        #Filter out only the chunks inside the dna group. the DnaDuplex.make 
        #doesn't  implement the dan data model yet. Until thats implemented ,we
        #will do an isinstance(node, Chunk) check . Note that it includes both  
        #Strands and Axis chunks -- Ninad 2008-01-09
        
        if self.editCommand and self.editCommand.hasValidStructure():
            strandChunkList = self.editCommand.struct.getStrands()
                        
            self.strandListWidget.insertItems(
                row = 0,
                items = strandChunkList)
        else:
            self.strandListWidget.clear()
    
    def updateSegmentListWidget(self):
        """
        Update the list of segments shown in the segments list widget
        @see: self.updateListWidgets, self.updateStrandListWidget
        """
        
        segmentList = []
        if self.editCommand and self.editCommand.hasValidStructure(): 
            def func(node):
                if isinstance(node, self.win.assy.DnaSegment):
                    segmentList.append(node)    
                    
            self.editCommand.struct.apply2all(func)
            self.segmentListWidget.insertItems(
                row = 0,
                items = segmentList)
        else:
            self.segmentListWidget.clear()
             
            
    def _addGroupBoxes( self ):
        """
        Add the DNA Property Manager group boxes.
        """        
        #Unused 'References List Box' to be revided. (just commented out for the
        #time being. 
        ##self._pmGroupBox1 = PM_GroupBox( self, title = "Reference Plane" )
        ##self._loadGroupBox1( self._pmGroupBox1 )
        
        self._pmGroupBox2 = PM_GroupBox( self, title = "Strands" )
        self._loadGroupBox2( self._pmGroupBox2 )
        
        self._pmGroupBox3 = PM_GroupBox( self, title = "Segments" )
        self._loadGroupBox3( self._pmGroupBox3 )
        
        
    def _loadGroupBox1(self, pmGroupBox):
        """
        load widgets in groupbox1
        """
        self.referencePlaneListWidget = PM_SelectionListWidget(
            pmGroupBox,
            self.win,
            label = "",
            color = pmReferencesListWidgetColor,
            heightByRows = 2)
    
    def _loadGroupBox2(self, pmGroupBox):
        """
        load widgets in groupbox2
        """
        
        self.strandListWidget = PM_SelectionListWidget(pmGroupBox,
                                                       self.win,
                                                       label = "",
                                                       heightByRows = 9 )
        self.strandListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')
    
        self.editStrandPropertiesButton = PM_PushButton( 
            pmGroupBox,
            label = "",
            text  = "Edit Properties..." )
        self.editStrandPropertiesButton.setEnabled(False)
        
    def _loadGroupBox3(self, pmGroupBox):
        """
        load widgets in groupbox3
        """
        
        self.segmentListWidget = PM_SelectionListWidget(pmGroupBox,
                                                       self.win,
                                                       label = "",
                                                       heightByRows = 4 )
        self.segmentListWidget.setObjectName('Segment_list_widget')
        self.segmentListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')
        
    
        self.editSegmentPropertiesButton = PM_PushButton( 
            pmGroupBox,
            label = "",
            text  = "Edit Properties..." )
        self.editSegmentPropertiesButton.setEnabled(False)
        
        self.searchForCrossoversButton = PM_PushButton( 
            pmGroupBox,
            label = "",
            text  = "Search For Crossovers..." )
        self.searchForCrossoversButton.setEnabled(False)
    
 
    def _addWhatsThisText( self ):
        """
        What's This text for widgets in the DNA Property Manager.  
        """
        pass
                
    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the DNA Property Manager.  
        """
        pass
Esempio n. 31
0
class EditResidues_PropertyManager(Command_PropertyManager):
    """
    The ProteinDisplayStyle_PropertyManager class provides a Property Manager 
    for the B{Display Style} command on the flyout toolbar in the 
    Build > Protein mode. 

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

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

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

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

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

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

        self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key]

        _superclass.__init__(self, command)

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

        self.editingItem = False
        return

    def connect_or_disconnect_signals(self, isConnect=True):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        _superclass.show(self)

        self._fillSequenceTable()
        self.updateMessage(msg)

        return

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self._updateSetLists()

        self._fillDescriptorsTable()

        self.descriptorsTable.resizeColumnsToContents()

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

        self.newDescriptorPushButton.setFixedHeight(25)

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

        self.removeDescriptorPushButton.setFixedHeight(25)

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

        self.applyDescriptorPushButton.setFixedHeight(25)

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

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

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

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

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

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

        self.selectAllPushButton.setFixedHeight(25)

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

        self.selectNonePushButton.setFixedHeight(25)

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

        self.selectInvertPushButton.setFixedHeight(25)

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

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

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

        self.checkbox = QCheckBox()

        self.sequenceTable.setFixedHeight(345)

        self.sequenceTable.setGridStyle(Qt.NoPen)

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

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

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

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

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

        self.editingItem = True

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

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

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

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

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

            self.sequenceTable.setRowHeight(index, 16)

        self.editingItem = False

        self.sequenceTable.resizeColumnsToContents()

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

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

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

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

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

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

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

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

        return aa_string

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

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

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

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

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

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

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

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

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

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

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

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

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

            self.editingItem = False

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

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

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

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

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

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

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

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

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

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

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

        self.descriptorsTable.setRowHeight(row, 16)

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

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

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

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

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

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

        self._makeDescriptorUserPref()
        self._updateSetLists()

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

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

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

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

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

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

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

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

        self.previous_protein = self.current_protein

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

        return
    def _loadMenuWidgets(self):
        """
        Load the various menu widgets (e.g. Open, save sequence options,
        Find and replace widgets etc.
        """

        self.loadSequenceButton = PM_ToolButton(
            self,
            iconPath = "ui/actions/Properties Manager/Open.png")

        self.saveSequenceButton = PM_ToolButton(
            self,
            iconPath = "ui/actions/Properties Manager/Save_Strand_Sequence.png")

        self.loadSequenceButton.setAutoRaise(True)
        self.saveSequenceButton.setAutoRaise(True)

        # Hide load and save buttons until they are implemented. -Mark 2008-12-20.
        self.loadSequenceButton.hide()
        self.saveSequenceButton.hide()

        #Find and replace widgets --
        self.findLineEdit = \
            PM_LineEdit( self,
                         label        = "",
                         spanWidth    = False)
        self.findLineEdit.setMaximumWidth(60)

        self.replaceLineEdit = \
            PM_LineEdit( self,
                         label        = "  Replace:",
                         spanWidth    = False)
        self.replaceLineEdit.setMaximumWidth(60)

        self.findOptionsToolButton = PM_ToolButton(self)
        self.findOptionsToolButton.setMaximumWidth(12)
        self.findOptionsToolButton.setAutoRaise(True)

        self.findOptionsToolButton.setPopupMode(QToolButton.MenuButtonPopup)

        self._setFindOptionsToolButtonMenu()

        self.findNextToolButton = PM_ToolButton(
            self,
            iconPath = "ui/actions/Properties Manager/Find_Next.png")
        self.findNextToolButton.setAutoRaise(True)

        self.findPreviousToolButton = PM_ToolButton(
            self,
            iconPath = "ui/actions/Properties Manager/Find_Previous.png")
        self.findPreviousToolButton.setAutoRaise(True)

        self.replacePushButton = PM_PushButton(self, text = "Replace")

        # Hide Replace widgets until we add support for transmuting residues.
        # Mark 2008-12-19
        #self.replaceLabel.hide()
        self.replacePushButton.hide()
        self.replaceLineEdit.hide()

        self.warningSign = QLabel(self)
        self.warningSign.setPixmap(
            getpixmap('ui/actions/Properties Manager/Warning.png'))
        self.warningSign.hide()

        self.phraseNotFoundLabel = QLabel(self)
        self.phraseNotFoundLabel.setText("Sequence Not Found")
        self.phraseNotFoundLabel.hide()

        #Widgets to include in the widget row.
        widgetList = [('PM_ToolButton', self.loadSequenceButton, 0),
                      ('PM_ToolButton', self.saveSequenceButton, 1),
                      ('QLabel', "                                     Find:", 4),
                      ('PM_LineEdit',   self.findLineEdit, 5),
                      ('PM_ToolButton', self.findOptionsToolButton, 6),
                      ('PM_ToolButton', self.findPreviousToolButton, 7),
                      ('PM_ToolButton', self.findNextToolButton, 8),
                      #('PM_Label',      self.replaceLabel, 9),
                      ('PM_TextEdit',   self.replaceLineEdit, 9),
                      ('PM_PushButton', self.replacePushButton, 10),
                      ('PM_Label', self.warningSign, 11),
                      ('PM_Label', self.phraseNotFoundLabel, 12),
                      ('QSpacerItem', 5, 5, 13) ]

        widgetRow = PM_WidgetRow(self,
                                 title     = '',
                                 widgetList = widgetList,
                                 label = "",
                                 spanWidth = True )
        return
Esempio n. 33
0
    def _loadMenuWidgets(self):
        """
        Load the various menu widgets (e.g. Open, save sequence options, 
        Find and replace widgets etc. 
        """
        #Note: Find and replace widgets might be moved to their own class.

        self.loadSequenceButton = PM_ToolButton(
            self, iconPath="ui/actions/Properties Manager/Open.png")

        self.saveSequenceButton = PM_ToolButton(
            self,
            iconPath="ui/actions/Properties Manager/Save_Strand_Sequence.png")

        self.loadSequenceButton.setAutoRaise(True)
        self.saveSequenceButton.setAutoRaise(True)

        # Only supporting 5' to 3' direction until bug 2956 is fixed.
        # Mark 2008-12-19
        editDirectionChoices = ["5' to 3'"]  # , "3' to 5'"]
        self.baseDirectionChoiceComboBox = \
            PM_ComboBox( self,
                         choices = editDirectionChoices,
                         index     = 0,
                         spanWidth = False )

        #Find and replace widgets --
        self.findLineEdit = \
            PM_LineEdit( self,
                         label        = "",
                         spanWidth    = False)
        self.findLineEdit.setMaximumWidth(60)


        self.replaceLineEdit = \
            PM_LineEdit( self,
                         label        = "",
                         spanWidth    = False)
        self.replaceLineEdit.setMaximumWidth(60)

        self.findOptionsToolButton = PM_ToolButton(self)
        self.findOptionsToolButton.setMaximumWidth(12)
        self.findOptionsToolButton.setAutoRaise(True)

        self.findOptionsToolButton.setPopupMode(QToolButton.MenuButtonPopup)

        self._setFindOptionsToolButtonMenu()

        self.findNextToolButton = PM_ToolButton(
            self, iconPath="ui/actions/Properties Manager/Find_Next.png")
        self.findNextToolButton.setAutoRaise(True)

        self.findPreviousToolButton = PM_ToolButton(
            self, iconPath="ui/actions/Properties Manager/Find_Previous.png")
        self.findPreviousToolButton.setAutoRaise(True)

        self.replacePushButton = PM_PushButton(self, text="Replace")

        self.warningSign = QLabel(self)
        self.warningSign.setPixmap(
            getpixmap('ui/actions/Properties Manager/Warning.png'))
        self.warningSign.hide()

        self.phraseNotFoundLabel = QLabel(self)
        self.phraseNotFoundLabel.setText("Sequence Not Found")
        self.phraseNotFoundLabel.hide()

        # NOTE: Following needs cleanup in the PM_WidgetRow/ PM_WidgetGrid
        # but this explanation is sufficient  until thats done --

        # When the widget type starts with the word 'PM_' , the
        # PM_WidgetRow treats it as a well defined widget and thus doesn't try
        # to create a QWidget object (or its subclasses)
        # This is the reason why qLabels such as self.warningSign and
        # self.phraseNotFoundLabel  are defined as PM_Labels and not 'QLabels'
        # If they were defined as 'QLabel'(s) then PM_WidgetRow would have
        # recreated the label. Since we want to show/hide the above mentioned
        # labels (and if they were recreated as mentioned above),
        # we would have needed to define  those something like this:
        # self.phraseNotFoundLabel = widgetRow._widgetList[-2]
        #Cleanup in PM_widgetGrid could be to check if the widget starts with
        #'Q'  instead of 'PM_'

        #Widgets to include in the widget row.
        widgetList = [('PM_ToolButton', self.loadSequenceButton, 0),
                      ('PM_ToolButton', self.saveSequenceButton, 1),
                      ('QLabel', "     Sequence direction:", 2),
                      ('PM_ComboBox', self.baseDirectionChoiceComboBox, 3),
                      ('QLabel', "     Find:", 4),
                      ('PM_LineEdit', self.findLineEdit, 5),
                      ('PM_ToolButton', self.findOptionsToolButton, 6),
                      ('PM_ToolButton', self.findPreviousToolButton, 7),
                      ('PM_ToolButton', self.findNextToolButton, 8),
                      ('QLabel', "     Replace:", 9),
                      ('PM_TextEdit', self.replaceLineEdit, 10),
                      ('PM_PushButton', self.replacePushButton, 11),
                      ('PM_Label', self.warningSign, 12),
                      ('PM_Label', self.phraseNotFoundLabel, 13),
                      ('QSpacerItem', 5, 5, 14)]

        widgetRow = PM_WidgetRow(self,
                                 title='',
                                 widgetList=widgetList,
                                 label="",
                                 spanWidth=True)
        return
class BuildDna_PropertyManager(EditCommand_PM):
    """
    The BuildDna_PropertyManager class provides a Property Manager
    for the B{Build > DNA } 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         =  "Build DNA"
    pmName        =  title
    iconPath      =  "ui/actions/Tools/Build Structures/DNA.png"
    sponsor_keyword = None # Nanorex is the sponsor. Change to 'DNA' to the
                             # the NUPACK logo.

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

        #Attributes for self._update_UI_do_updates() to keep track of changes
        #in these , since the last call of that method. These are used to
        #determine whether certain UI updates are needed.
        self._previousSelectionParams = None
        self._previousStructureParams = None
        self._previousCommandStackParams = None

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

        EditCommand_PM.__init__( self, command)

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



    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.strandListWidget.connect_or_disconnect_signals(isConnect)
        self.segmentListWidget.connect_or_disconnect_signals(isConnect)

        change_connect(self.editStrandPropertiesButton,
                      SIGNAL("clicked()"),
                      self._editDnaStrand)

        change_connect(self.editSegmentPropertiesButton,
                      SIGNAL("clicked()"),
                      self._editDnaSegment)

        change_connect(self.searchForCrossoversButton,
                      SIGNAL("clicked()"),
                      self._enterMakeCrossoversCommand)

        self._baseNumberLabelGroupBox.connect_or_disconnect_signals(isConnect)


    def enable_or_disable_gui_actions(self, bool_enable = False):
        """
        Enable or disable some gui actions when this property manager is
        opened or closed, depending on the bool_enable.

        """

        #For new command API, we will always show the exit button to check
        #if Exit button really exits the subcommand and the parent command
        #(earlier there were bugs) . Regaring 'whether this should be the
        #default behavior', its a UI design issue and we will worry about it
        #later -- Ninad 2008-08-27 (based on an email exchanged with Bruce)
        pass


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

        newSelectionParams = self._currentSelectionParams()

        current_struct_params = self._currentStructureParams()

        selection_params_unchanged = same_vals(newSelectionParams,
                                               self._previousSelectionParams)

        #introducing self._previousStructureParams and
        #adding structure_params_unchanged check to the 'if' condition below
        #fixes bug 2910.
        structure_params_unchanged = same_vals(self._previousStructureParams,
                                                current_struct_params)

        current_command_stack_params = self._currentCommandStackParams()

        #Check if command stack params changed since last call of this
        #PM update method. This is used to fix bugs like 2940
        command_stack_params_unchanged = same_vals(
            self._previousCommandStackParams, current_command_stack_params)

        #No need to proceed if any of the selection/ structure and commandstack
        #parameters remained unchanged since last call. --- [CONDITION A]
        if selection_params_unchanged and structure_params_unchanged and command_stack_params_unchanged:
            #This second condition above fixes bug 2888
            return

        self._previousStructureParams = current_struct_params
        self._previousSelectionParams =  newSelectionParams
        self._previousCommandStackParams  = current_command_stack_params

        ##if not selection_params_unchanged or not command_stack_params_unchanged and structure_params_unchanged:
        if structure_params_unchanged:
            #NOTE: We checked if either of the selection struct or command stack
            #parameters or both changed. (this was referred as '[CONDITION A]'
            #above). So, this condition (structure_params_unchanged)also means
            #either selection or command stack or both parameters were changed.

            if not command_stack_params_unchanged:
                #update the list widgets *before* updating the selection if
                #the command stack changed. This ensures that the selection box
                #appears around the list widget items that are selected.
                self.updateListWidgets()

            selectedStrands, selectedSegments = newSelectionParams

            self.strandListWidget.updateSelection(selectedStrands)
            self.segmentListWidget.updateSelection(selectedSegments)

            if len(selectedStrands) == 1:
                self.editStrandPropertiesButton.setEnabled(True)
            else:
                self.editStrandPropertiesButton.setEnabled(False)

            if len(selectedSegments) == 1:
                self.editSegmentPropertiesButton.setText("Edit Properties...")
                self.editSegmentPropertiesButton.setEnabled(True)
            elif len(selectedSegments) > 1:
                resizeString = "Resize Selected Segments (%d)..." % len(selectedSegments)
                self.editSegmentPropertiesButton.setText(resizeString)
                self.editSegmentPropertiesButton.setEnabled(True)
                self.searchForCrossoversButton.setEnabled(True)
            else:
                self.editSegmentPropertiesButton.setText("Edit Properties...")
                self.editSegmentPropertiesButton.setEnabled(False)
                self.searchForCrossoversButton.setEnabled(False)

            return

        # Calling updateListWidgets() here fixes bug 2950 without undoing the
        # fix to bug 2940. --Mark 2008-12-13.
        self.updateListWidgets()
        return


    def _currentCommandStackParams(self):
        """
        The return value is supposed to be used by BUILD_DNA command PM ONLY
        and NOT by any subclasses.

        Returns a tuple containing current scommand stack change indicator and
        the name of the command 'BUILD_DNA'. These
        parameters are then used to decide whether updating widgets
        in this property manager is needed, when self._update_UI_do_updates()
        is called.

        @NOTE:
        - Command_PropertyManager.update_UI() already does a check to see if
          any of the global change indicators in assembly (command_stack_change,
          model_change, selection_change) changed since last call and then only
          calls self._update_UI_do_updates().
        - But this method is just used to keep track of the
          local command stack change counter in order to update the list
          widgets.
        - This is used to fix bug 2940

        @see: self._update_UI_do_updates()
        """
        commandStackCounter = self.command.assy.command_stack_change_indicator()
        #Append 'BUILD_DNA to the tuple to be returned. This is just to remind
        #us that this method is meant for BUIL_DNA command PM only. (and not
        #by any subclasses) Should we assert this? I think it will slow things
        #down so this comment is enough -- Ninad 2008-09-30
        return (commandStackCounter, 'BUILD_DNA')

    def _currentSelectionParams(self):
        """
        Returns a tuple containing current selection parameters. These
        parameters are then used to decide whether updating widgets
        in this property manager is needed when L{self.model_changed}
        method is called.

        @return: A tuple that contains following selection parameters
                   - Total number of selected atoms (int)
                   - Selected Atom if a single atom is selected, else None
                   - Position vector of the single selected atom or None
        @rtype:  tuple

        @NOTE: This method may be renamed in future.
        It's possible that there are other groupboxes in the PM that need to be
        updated when something changes in the glpane.
        """

        selectedStrands = []
        selectedSegments = []
        if self.command is not None and self.command.hasValidStructure():
            selectedStrands = self.command.struct.getSelectedStrands()
            selectedSegments = self.command.struct.getSelectedSegments()

        return (selectedStrands, selectedSegments)

    def _currentStructureParams(self):
        """
        Return current structure parameters of interest to self.model_changed.
        Right now it only returns the number of strands within the structure
        (or None). This is a good enough check (and no need to compare
        each and every strand within the structure with a previously stored
        set of strands).
        """
        #Can it happen that the total number of strands remains the same even
        #after some alterations to the strands? Unlikely. (Example: a single
        #Break strands operation will increase the number of strands by one.
        #Or Join strands decrease it by 1)
        params = None

        if self.command and self.command.hasValidStructure():
            strandList = []
            strandList = self.command.struct.getStrands()
            params = len(strandList)

        return params


    def close(self):
        """
        Closes the Property Manager. Overrides EditCommand_PM.close()
        """
        #Clear tags, if any, due to the selection in the self.strandListWidget.
        if self.strandListWidget:
            self.strandListWidget.clear()

        if self.segmentListWidget:
            self.segmentListWidget.clear()

        EditCommand_PM.close(self)

    def show(self):
        """
        Show this PM
        As of 2007-11-20, it also shows the Sequence Editor widget and hides
        the history widget. This implementation may change in the near future
        """
        EditCommand_PM.show(self)

        self.updateMessage("Use appropriate command in the command "\
                               "toolbar to create or modify a DNA Object"\
                               "<br>" )

    def _editDnaStrand(self):
        """
        Enter the DnaStrand_EditCommand to edit the selected strand.
        """

        if not self.command.hasValidStructure():
            return

        selectedStrandList = self.command.struct.getSelectedStrands()

        if len(selectedStrandList) == 1:
            strand = selectedStrandList[0]
            strand.edit()


    def _editDnaSegment(self):
        """
        """
        if self.command is not None and self.command.hasValidStructure():
            selectedSegments = self.command.struct.getSelectedSegments()
            if len(selectedSegments) == 1:
                selectedSegments[0].edit()
            elif len(selectedSegments) > 1:
                self.win.resizeSelectedDnaSegments()

    def _enterMakeCrossoversCommand(self):
        """
        If more than one segments in the segment list widget
        are selected, enter make crossovers  command

        @BUG: This enters Make Crossover command which searches for *ALL*
        of the selected DnaSegments in the model and not just the selected
        segments of the DnaGroup you are editing in the BuildDna command
        This is misleading.

        """
        self.win.enterMakeCrossoversCommand()


    def updateListWidgets(self):
        """
        Update List Widgets (strand list and segment list)
        in this property manager
        @see: self.updateSegmentListWidgets, self.updateStrandListWidget
        """
        self.updateStrandListWidget()
        self.updateSegmentListWidget()


    def updateStrandListWidget(self):
        """
        Update the list of items inside the strandlist widget
        Example: Origianally it shows two srands. User now edits an
        existing dna, and deletes some of the strands, hits done. User then
        again invokes the Edit command for this dna object -- now the strand
        list widget must be updated so that it shows only the existing strands.

        @see: B{Chunk.isStrandChunk}
        @see: self.updateListWidgets, self.updateSegmentListWidget
        """
        #TODO:
        #Filter out only the chunks inside the dna group. the DnaDuplex.make
        #doesn't implement the dna data model yet. Until that's implemented, we
        #will do an isinstance(node, Chunk) check. Note that it includes both
        #Strands and Axis chunks -- Ninad 2008-01-09

        if self.command.hasValidStructure():
            strandChunkList = self.command.struct.getStrands()

            self.strandListWidget.insertItems(
                row = 0,
                items = strandChunkList)
        else:
            self.strandListWidget.clear()

    def updateSegmentListWidget(self):
        """
        Update the list of segments shown in the segments list widget
        @see: self.updateListWidgets, self.updateStrandListWidget
        """

        segmentList = []
        if self.command.isCurrentCommand():
            if self.command.hasValidStructure():
                def func(node):
                    if isinstance(node, self.win.assy.DnaSegment):
                        segmentList.append(node)

                self.command.struct.apply2all(func)
                self.segmentListWidget.insertItems(
                    row = 0,
                    items = segmentList)
            else:
                self.segmentListWidget.clear()


    def _addGroupBoxes( self ):
        """
        Add the DNA Property Manager group boxes.
        """
        #Unused 'References List Box' to be revided. (just commented out for the
        #time being.
        ##self._pmGroupBox1 = PM_GroupBox( self, title = "Reference Plane" )
        ##self._loadGroupBox1( self._pmGroupBox1 )

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

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

        self._loadBaseNumberLabelGroupBox(self)


    def _loadGroupBox1(self, pmGroupBox):
        """
        load widgets in groupbox1
        """
        self.referencePlaneListWidget = PM_SelectionListWidget(
            pmGroupBox,
            self.win,
            label = "",
            color = pmReferencesListWidgetColor,
            heightByRows = 2)

    def _loadGroupBox2(self, pmGroupBox):
        """
        load widgets in groupbox2
        """

        self.strandListWidget = PM_SelectionListWidget(pmGroupBox,
                                                       self.win,
                                                       label = "",
                                                       heightByRows = 9 )
        self.strandListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')

        self.editStrandPropertiesButton = PM_PushButton(
            pmGroupBox,
            label = "",
            text  = "Edit Properties..." )
        self.editStrandPropertiesButton.setEnabled(False)

    def _loadGroupBox3(self, pmGroupBox):
        """
        load widgets in groupbox3
        """

        self.segmentListWidget = PM_SelectionListWidget(pmGroupBox,
                                                       self.win,
                                                       label = "",
                                                       heightByRows = 4 )
        self.segmentListWidget.setObjectName('Segment_list_widget')
        self.segmentListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')


        self.editSegmentPropertiesButton = PM_PushButton(
            pmGroupBox,
            label = "",
            text  = "Edit Properties..." )
        self.editSegmentPropertiesButton.setEnabled(False)

        self.searchForCrossoversButton = PM_PushButton(
            pmGroupBox,
            label = "",
            text  = "Search For Crossovers..." )
        self.searchForCrossoversButton.setEnabled(False)


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

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

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the DNA Property Manager.
        """
        pass
class Ui_CookiePropertyManager(PM_Dialog):
    """
    The Ui_CookiePropertyManager 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, parentMode):
        """
        Constructor for the B{Crystal} property manager class that defines 
        its UI.
        
        @param parentMode: The parent mode where this Property Manager is used
        @type  parentMode: L{cookieMode}  
        """
        self.parentMode = parentMode
        self.w = self.parentMode.w
        self.win = self.parentMode.w
        self.pw = self.parentMode.pw
        self.o = self.parentMode.o

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

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

        msg = ''
        self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=False)

    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)
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)
Esempio n. 37
0
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        self.labelfont = QFont("Helvetica", 12)
        self.descriptorfont = QFont("Courier New", 12)

        self.headerdata = ['', 'ID', 'Set', 'Descriptor']

        self.set_names = ["Any", "Same", "Locked", "Polar", "Apolar"]
        self.rosetta_set_names = ["ALLAA", "NATRO", "NATAA", "POLAR", "APOLA"]
        self.descriptor_list = [
            "GAVILMFWCSTYNQDEHKRP", "____________________",
            "____________________", "________CSTYNQDEHKR_",
            "GAVILMFW___________P"
        ]

        self.descriptorsTable = PM_TableWidget(pmGroupBox)
        self.descriptorsTable.setFixedHeight(100)
        self.descriptorsTable.setRowCount(len(self.set_names))
        self.descriptorsTable.setColumnCount(2)
        self.descriptorsTable.verticalHeader().setVisible(False)
        self.descriptorsTable.horizontalHeader().setVisible(False)

        for index in range(len(self.set_names)):
            item_widget = QTableWidgetItem(self.set_names[index])
            item_widget.setFont(self.labelfont)
            item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled
                                 | Qt.ItemIsEditable)
            item_widget.setTextAlignment(Qt.AlignCenter)
            self.descriptorsTable.setItem(index, 0, item_widget)

            item_widget = QTableWidgetItem(self.descriptor_list[index])
            item_widget.setFont(self.descriptorfont)
            item_widget.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled
                                 | Qt.ItemIsEditable)
            item_widget.setTextAlignment(Qt.AlignCenter)
            self.descriptorsTable.setItem(index, 1, item_widget)

            self.descriptorsTable.setRowHeight(index, 16)

            pass

        self.descriptorsTable.resizeColumnsToContents()

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

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

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

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

        self.win.connect(self.applyDescriptorPushButton, SIGNAL("clicked()"),
                         self._applyDescriptor)

        self.win.connect(self.selectAllPushButton, SIGNAL("clicked()"),
                         self._selectAll)

        self.win.connect(self.selectNonePushButton, SIGNAL("clicked()"),
                         self._selectNone)

        self.win.connect(self.selectInvertPushButton, SIGNAL("clicked()"),
                         self._invertSelection)

        buttonList = [('PM_PushButton', self.applyDescriptorPushButton, 0, 0),
                      ('QSpacerItem', 5, 5, 1, 0),
                      ('PM_PushButton', self.selectAllPushButton, 2, 0),
                      ('PM_PushButton', self.selectNonePushButton, 3, 0),
                      ('PM_PushButton', self.selectInvertPushButton, 4, 0)]

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


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

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

        self.checkbox = QCheckBox()

        self.sequenceTable.setFixedHeight(345)

        self.sequenceTable.setHorizontalHeaderLabels(self.headerdata)
class OrderDna_PropertyManager(Command_PropertyManager):
    """
    The OrderDna_PropertyManager class provides a Property Manager 
    for the B{Order Dna} 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         =  "Order DNA"
    pmName        =  title
    iconPath      =  "ui/actions/Command Toolbar/BuildDna/OrderDna.png"
    
    def __init__( self, command ):
        """
        Constructor for the property manager.
        """
        
        _superclass.__init__(self, command)
        
        self.assy = self.win.assy

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        
        self.update_includeStrands() # Updates the message box.
        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 
        
        change_connect( self.viewDnaOrderFileButton,
                        SIGNAL("clicked()"), 
                        self.viewDnaOrderFile)
        
        change_connect( self.includeStrandsComboBox,
                      SIGNAL("activated(int)"),
                      self.update_includeStrands )
        return
       
    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """        
        self._pmGroupBox1 = PM_GroupBox( self, title = "Options" )
        self._loadGroupBox1( self._pmGroupBox1 )
    
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        
        includeStrandsChoices = ["All strands in model",
                                 "Selected strands only"]
        
        self.includeStrandsComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Include strands:", 
                         choices       =  includeStrandsChoices,
                         setAsDefault  =  True)
        
        self.numberOfBasesLineEdit  = \
            PM_LineEdit( pmGroupBox,
                         label  =  "Total nucleotides:",
                         text   = str(self.getNumberOfBases()))
        self.numberOfBasesLineEdit.setEnabled(False)
        
        self.numberOfXBasesLineEdit  = \
            PM_LineEdit( pmGroupBox,
                         label  =  "Unassigned:",
                         text   = str(self.getNumberOfBases(unassignedOnly = True)))
        self.numberOfXBasesLineEdit.setEnabled(False)
        
        self.viewDnaOrderFileButton = \
            PM_PushButton( pmGroupBox,
                           label     = "",
                           text      = "View DNA Order File...",
                           spanWidth = True)
        return
    
    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.
        """
        whatsThis_OrderDna_PropertyManager(self)
        return
    
    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the DNA Property Manager.  
        """
        pass
    
    # Ask Bruce where this should live (i.e. class Part?) --Mark
    def getAllDnaStrands(self, selectedOnly = False):
        """
        Returns a list of all the DNA strands in the current part, or only
        the selected strands if I{selectedOnly} is True.
        
        @param selectedOnly: If True, return only the selected DNA strands.
        @type  selectedOnly: bool
        """
        
        dnaStrandList = []
         
        def func(node):
            if isinstance(node, DnaStrand):
                if selectedOnly:
                    if node.picked:
                        dnaStrandList.append(node)
                else:
                    dnaStrandList.append(node)
                    
        self.win.assy.part.topnode.apply2all(func)
        
        return dnaStrandList
    
    def getNumberOfBases(self, selectedOnly = False, unassignedOnly = False):
        """
        Returns the number of bases count for all the DNA strands in the 
        current part, or only the selected strand if I{selectedOnly} is True.
        
        @param selectedOnly: If True, return only the number of bases in the
                             selected DNA strands.
        @type  selectedOnly: bool
        
        @param unassignedOnly: If True, return only the number of unassigned
                               bases (i.e. base letters = X).
        @type  unassignedOnly: bool
        """
        dnaSequenceString = ''
        selectedOnly = self.includeStrandsComboBox.currentIndex()
        strandList = self.getAllDnaStrands(selectedOnly)
        
        for strand in strandList:
            strandSequenceString = str(strand.getStrandSequence())
            dnaSequenceString += strandSequenceString
        
        if unassignedOnly:
            return dnaSequenceString.count("X")
        
        return len(dnaSequenceString)
    
    def _update_UI_do_updates(self):
        """
        Overrides superclass method.
        """
        self.update_includeStrands()
        return
        
    def getDnaSequence(self, format = 'CSV'):
        """
        Return the complete Dna sequence information string (i.e. all strand 
        sequences) in the specified format. 
        
        @return: The Dna sequence string
        @rtype: string
        
        """
        if format == 'CSV': #comma separated values.
            separator = ','
            
        dnaSequenceString = ''
        selectedOnly = self.includeStrandsComboBox.currentIndex()
        strandList = self.getAllDnaStrands(selectedOnly)
        
        for strand in strandList:
            dnaSequenceString = dnaSequenceString + strand.name + separator
            strandSequenceString = str(strand.getStrandSequence())
            if strandSequenceString: 
                strandSequenceString = strandSequenceString.upper()
                strandLength = str(len(strandSequenceString)) + separator
                dnaSequenceString = dnaSequenceString + strandLength + strandSequenceString
                
            dnaSequenceString = dnaSequenceString + "\n"
            
        return dnaSequenceString
        
    def viewDnaOrderFile(self, openFileInEditor = True):
        """
        Writes a DNA Order file in comma-separated values (CSV) format 
        and opens it in a text editor.

        The user must save the file to a permanent location using the 
        text editor.

        @see: Ui_DnaFlyout.orderDnaCommand
        @see: writeDnaOrderFile()
        @TODO: assy.getAllDnaObjects(). 
        """
        dnaSequence = self.getDnaSequence(format = 'CSV')

        if dnaSequence: 
            tmpdir = find_or_make_Nanorex_subdir('temp')
            fileBaseName = 'DnaOrder'
            temporaryFile = os.path.join(tmpdir, "%s.csv" % fileBaseName)            
            writeDnaOrderFile(temporaryFile, 
                              self.assy,
                              self.getNumberOfBases(),
                              self.getNumberOfBases(unassignedOnly = True),
                              dnaSequence)      

            if openFileInEditor:
                open_file_in_editor(temporaryFile)
                
        return

    def update_includeStrands(self, ignoreVal = 0):
        """
        Slot method for "Include (strands)" combobox.
        """
        
        idx = self.includeStrandsComboBox.currentIndex()
        
        includeType = ["model", "selection"]
        
        _numberOfBases = self.getNumberOfBases()
        self.numberOfBasesLineEdit.setText(str(_numberOfBases) + " bases")
        
        _numberOfXBases = self.getNumberOfBases(unassignedOnly = True)
        self.numberOfXBasesLineEdit.setText(str(_numberOfXBases) + " bases")
        
        # Make the background color red if there are any unassigned bases.
        if _numberOfXBases:
            self.numberOfXBasesLineEdit.setStyleSheet(\
                "QLineEdit {"\
                "background-color: rgb(255, 0, 0)"\
                "}")
        else:
            self.numberOfXBasesLineEdit.setStyleSheet(\
                "QLineEdit {"\
                "background-color: rgb(255, 255, 255)"\
                "}")
        
        if _numberOfBases > 0:
            self.viewDnaOrderFileButton.setEnabled(True)
            msg = "Click on <b>View DNA Order File...</b> to preview a " \
                "DNA order for all DNA strands in the current %s." \
                % includeType[idx]
        else:
            self.viewDnaOrderFileButton.setEnabled(False)
            msg = "<font color=red>" \
                "There are no DNA strands in the current %s." \
                % includeType[idx]
                
        self.updateMessage(msg)
        return
class BuildNanotube_PropertyManager(EditCommand_PM):
    """
    The BuildNanotube_PropertyManager class provides a Property Manager 
    for the B{Build > CNT } 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         =  "Build Nanotube"
    pmName        =  title
    iconPath      =  "ui/actions/Command Toolbar/BuildNanotube/BuildNanotube.png"

    def __init__( self, command ):
        """
        Constructor for the Build Nanotube property manager.
        """
        
        #Attributes for self._update_UI_do_updates() to keep track of changes
        #in these , since the last call of that method. These are used to 
        #determine whether certain UI updates are needed. 
        self._previousSelectionParams = None        
        self._previousStructureParams = None
        self._previousCommandStackParams = None

        #see self.connect_or_disconnect_signals for comment about this flag
        self.isAlreadyConnected = False
        self.isAlreadyDisconnected = False
        
        EditCommand_PM.__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
        """
        #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 actually reconnects the signal! 
        #This gives rise to lots of bugs. This needs a more general fix in 
        #the Temporary mode API. 
        # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py
        
        if isConnect and self.isAlreadyConnected:
            return 
        
        if not isConnect and self.isAlreadyDisconnected:
            return
        
        self.isAlreadyConnected = isConnect
        self.isAlreadyDisconnected = not isConnect
        
        if isConnect:
            change_connect = self.win.connect     
        else:
            change_connect = self.win.disconnect 
        
        self.nanotubeListWidget.connect_or_disconnect_signals(isConnect)
        
        change_connect(self.editNanotubePropertiesButton,
                      SIGNAL("clicked()"),
                      self._editNanotube)
        return
    
    def enable_or_disable_gui_actions(self, bool_enable = False):
        """
        Enable or disable some gui actions when this property manager is 
        opened or closed, depending on the bool_enable. 
        
        """
        
        #For new command API, we will always show the exit button to check 
        #if Exit button really exits the subcommand and the parent command 
        #(earlier there were bugs) . Regaring 'whether this should be the 
        #default behavior', its a UI design issue and we will worry about it 
        #later -- Ninad 2008-08-27 (based on an email exchanged with Bruce)
        pass
    
    def _update_UI_do_updates(self):
        """
        Overrides superclass method. 
        
        @see: Command_PropertyManager._update_UI_do_updates()
        """
        
        newSelectionParams = self._currentSelectionParams()
        current_struct_params = self._currentStructureParams()
        
        selection_params_unchanged = same_vals(newSelectionParams,
                                               self._previousSelectionParams)
        
        #introducing self._previousStructureParams and 
        #adding structure_params_unchanged check to the 'if' condition below 
        #fixes bug 2910. 
        structure_params_unchanged = same_vals(self._previousStructureParams, 
                                                current_struct_params)
        
        current_command_stack_params = self._currentCommandStackParams()
        
        #Check if command stack params changed since last call of this 
        #PM update method. This is used to fix bugs like 2940
        command_stack_params_unchanged = same_vals(
            self._previousCommandStackParams, current_command_stack_params)
              
        #No need to proceed if any of the selection/ structure and commandstack 
        #parameters remained unchanged since last call. --- [CONDITION A]
        if selection_params_unchanged and \
           structure_params_unchanged and \
           command_stack_params_unchanged:
            return
        
        self._previousStructureParams = current_struct_params
        self._previousSelectionParams =  newSelectionParams         
        self._previousCommandStackParams  = current_command_stack_params
        
        if structure_params_unchanged: 
            #NOTE: We checked if either of the selection struct or command stack
            #parameters or both changed. (this was referred as '[CONDITION A]' 
            #above). So, this condition (structure_params_unchanged)also means 
            #either selection or command stack or both parameters were changed.    
            
            if not command_stack_params_unchanged:
                #update the nanotube list widget *before* updating the selection if 
                #the command stack changed. This ensures that the selection box
                #appears around the list widget items that are selected.
                self.updateNanotubesListWidget()
                
            selectedNanotubeSegments = newSelectionParams    
            
            self.nanotubeListWidget.updateSelection(selectedNanotubeSegments) 
            
            self.updateNanotubePropertiesButton()
            return
        
        self.updateNanotubesListWidget()
        return
    
    def _currentCommandStackParams(self):
        """
        The return value is supposed to be used by BUILD_NANOTUBE command PM ONLY
        and NOT by any subclasses.         
        
        Returns a tuple containing current command stack change indicator and 
        the name of the command 'BUILD_NANOTUBE'. These 
        parameters are then used to decide whether updating widgets
        in this property manager is needed, when self._update_UI_do_updates()
        is called. 
        
        @NOTE: 
        - Command_PropertyManager.update_UI() already does a check to see if 
          any of the global change indicators in assembly (command_stack_change, 
          model_change, selection_change) changed since last call and then only
          calls self._update_UI_do_updates(). 
        - But this method is just used to keep track of the 
          local command stack change counter in order to update the list 
          widgets.      
        - This is used to fix bug 2940
        
        @see: self._update_UI_do_updates()
        """
        commandStackCounter = self.command.assy.command_stack_change_indicator()
        #Append 'BUILD_NANOTUBE to the tuple to be returned. This is just to remind 
        #us that this method is meant for BUILD_NANOTUBE command PM only. (and not 
        #by any subclasses) Should we assert this? I think it will slow things 
        #down so this comment is enough -- Ninad 2008-09-30
        return (commandStackCounter, 'BUILD_NANOTUBE')
        
    def _currentSelectionParams(self):
        """
        Returns a tuple containing current selection parameters. These 
        parameters are then used to decide whether updating widgets
        in this property manager is needed when L{self.model_changed}
        method is called.
        
        @return: A tuple that contains total number of selected nanotubes.
        @rtype:  tuple
        
        @NOTE: This method may be renamed in future. 
        It's possible that there are other groupboxes in the PM that need to be 
        updated when something changes in the glpane.        
        """
        selectedNanotubeSegments = []
        if self.command is not None: # and self.command.hasValidStructure():
            selectedNanotubeSegments = self.win.assy.getSelectedNanotubeSegments()          
        return (selectedNanotubeSegments)
    
    def _currentStructureParams(self):
        """
        Return current structure parameters of interest to self.model_changed. 
        Right now it only returns the number of nanotubes within the structure
        (or None). This is a good enough check (and no need to compare 
        each and every nanotube within the structure with a previously stored 
        set of strands).
        """
        params = None
        
        if self.command: # and self.command.hasValidStructure():
            nanotubeSegmentList = []
            nanotubeSegmentList = getAllNanotubeSegmentsInPart(self.win.assy)
            params = len(nanotubeSegmentList)
        
        return params
    
    def close(self):
        """
        Closes the Property Manager. Overrides EditCommand_PM.close()
        """
        #Clear tags, if any, due to the selection in the self.strandListWidget.
        #self.nanotubeListWidget.clear()
        env.history.statusbar_msg("")
        EditCommand_PM.close(self)
        return
    
    def show(self):
        """
        Show the PM. Extends superclass method.
        @note: _update_UI_do_updates() gets called immediately after this and
               updates PM widgets with their correct values/settings. 
        """
        
        env.history.statusbar_msg("")
        EditCommand_PM.show(self)
        
        # NOTE: Think about moving this msg to _update_UI_do_updates() where
        # custom msgs can be created based on the current selection, etc.
        # Mark 2008-12-14
        msg = "Select <b>Insert Nanotube</b> to create a nanotube or "\
            "select an existing nantube to modify it."
        self.updateMessage(msg)
        return
    
    def _editNanotube(self):
        """
        Slot for the "Edit Properties" button. 
        """
        
        #if not self.command.hasValidStructure():
        #    return
        
        nanotubeSegment = self.win.assy.getSelectedNanotubeSegment()
        
        if nanotubeSegment:
            nanotubeSegment.edit()
        return
    
    def _addWhatsThisText( self ):
        """
        What's This text for widgets in the CNT Property Manager.  
        """
        pass
                
    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the CNT Property Manager.  
        """
        pass
    
    def _addGroupBoxes( self ):
        """
        Add the Nanotube Property Manager group boxes.
        """        
        self._pmGroupBox1 = PM_GroupBox( self, title = "Nanotubes" )
        self._loadGroupBox1( self._pmGroupBox1 )
        return
    
    def _loadGroupBox1(self, pmGroupBox):
        """
        load widgets in groupbox1
        """
        
        self.nanotubeListWidget = PM_SelectionListWidget(pmGroupBox,
                                                         self.win,
                                                         label = "",
                                                         heightByRows = 12)
        self.nanotubeListWidget.setObjectName('nanotubeListWidget')
        self.nanotubeListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')
        
        self.editNanotubePropertiesButton = PM_PushButton(pmGroupBox,
                                                          label = "",
                                                          text  = "Edit Properties..." )
        self.editNanotubePropertiesButton.setEnabled(False)
        return
    
    def updateNanotubesListWidget(self):   
        """
        Updates the nanotubes (selection) groupbox. This includes both the 
        nanotube selection list widget (showing all nanotubes in the part) 
        and the B{Edit Properties} button just below it (enabled if only 
        one of the nanotubes is selected).
        """
        nanotubeSegmentList = getAllNanotubeSegmentsInPart(self.win.assy)
        
        if nanotubeSegmentList:
            self.nanotubeListWidget.insertItems(
                row = 0,
                items = nanotubeSegmentList)
        else:           
            self.nanotubeListWidget.clear()
        
        self.updateNanotubePropertiesButton()
        return
    
    def updateNanotubePropertiesButton(self):
        """
        Enables the B{Edit Properties} button if a single nanotube is currently 
        selected. Otherwise, the button is disabled.
        """
        self.editNanotubePropertiesButton.setEnabled(
            bool(self.win.assy.getSelectedNanotubeSegment()))
        return
Esempio n. 40
0
class BuildProtein_PropertyManager(EditCommand_PM):
    """
    The BuildProtein_PropertyManager class provides a Property Manager 
    for the B{Build Protein} 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         =  "Build Protein"
    pmName        =  title
    iconPath      =  "ui/actions/Command Toolbar/BuildProtein/BuildProtein.png"
    
    current_protein = "" # name of the single selected peptide. To be deprecated soon. --Mark 2008-12-14

    def __init__( self, command):
        """
        Constructor for the Build Protein property manager.
        """
        
        #Attributes for self._update_UI_do_updates() to keep track of changes
        #in these , since the last call of that method. These are used to 
        #determine whether certain UI updates are needed. 
        self._previousSelectionParams = None        
        self._previousStructureParams = None        
        self._previousCommandStackParams = None
        
        #see self.connect_or_disconnect_signals for comment about this flag
        self.isAlreadyConnected = False
        self.isAlreadyDisconnected = False           
        
        EditCommand_PM.__init__( self, command)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_CANCEL_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 and self.isAlreadyConnected:
            return 
        
        if not isConnect and self.isAlreadyDisconnected:
            return
        
        self.isAlreadyConnected = isConnect
        self.isAlreadyDisconnected = not isConnect
        
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect
        
        self.proteinListWidget.connect_or_disconnect_signals(isConnect)
        
        change_connect(self.editPeptidePropertiesButton, 
                       SIGNAL("clicked()"),
                       self._editPeptide)
        
        change_connect(self.compareProteinsButton, 
                       SIGNAL("clicked()"),
                       self._compareProteins)
        
        return
    
    def enable_or_disable_gui_actions(self, bool_enable = False):
        """
        Enable or disable some gui actions when this property manager is 
        opened or closed, depending on the bool_enable. 
        
        """
        
        #For new command API, we will always show the exit button to check 
        #if Exit button really exits the subcommand and the parent command 
        #(earlier there were bugs) . Regaring 'whether this should be the 
        #default behavior', its a UI design issue and we will worry about it 
        #later -- Ninad 2008-08-27 (based on an email exchanged with Bruce)
        pass
    
    def _update_UI_do_updates(self):
        """
        Overrides superclass method. 
        
        @see: Command_PropertyManager._update_UI_do_updates()
        """
        
        newSelectionParams = self._currentSelectionParams()   
        
        current_struct_params = self._currentStructureParams()
        
        selection_params_unchanged = same_vals(newSelectionParams,
                                               self._previousSelectionParams)
        
        #introducing self._previousStructureParams and 
        #adding structure_params_unchanged check to the 'if' condition below 
        #fixes bug 2910. 
        structure_params_unchanged = same_vals(self._previousStructureParams, 
                                                current_struct_params)
        
        current_command_stack_params = self._currentCommandStackParams()
        
        #Check if command stack params changed since last call of this 
        #PM update method. This is used to fix bugs like 2940
        command_stack_params_unchanged = same_vals(
            self._previousCommandStackParams, current_command_stack_params)
              
        #No need to proceed if any of the selection/ structure and commandstack 
        #parameters remained unchanged since last call. --- [CONDITION A]
        if selection_params_unchanged and structure_params_unchanged and command_stack_params_unchanged:
            #This second condition above fixes bug 2888
            if 0:
                print "Build Protein: _update_UI_do_updates() - DO NOTHING"
            return
        
        self._previousStructureParams = current_struct_params
        self._previousSelectionParams =  newSelectionParams         
        self._previousCommandStackParams  = current_command_stack_params
        
        ##if not selection_params_unchanged or not command_stack_params_unchanged and structure_params_unchanged: 
        if structure_params_unchanged: 
            #NOTE: We checked if either of the selection struct or command stack
            #parameters or both changed. (this was referred as '[CONDITION A]' 
            #above). So, this condition (structure_params_unchanged)also means 
            #either selection or command stack or both parameters were changed.    
            
            if not command_stack_params_unchanged:
                #update the protein list widget *before* updating the selection if 
                #the command stack changed. This ensures that the selection box
                #appears around the list widget items that are selected.
                self.updateProteinListWidget()
                
            selectedProteins = newSelectionParams    
            
            self.proteinListWidget.updateSelection(selectedProteins) 
            
            # Enable/disable "Edit Sequence" button.
            if len(selectedProteins) == 1:
                self.editPeptidePropertiesButton.setEnabled(True)
            else:
                self.editPeptidePropertiesButton.setEnabled(False)
            
                # Enable/disable "Compare Proteins" button.
            if len(selectedProteins) == 2:
                self.compareProteinsButton.setEnabled(True)
            else:
                self.compareProteinsButton.setEnabled(False)
                
            return
        
        self.updateProteinListWidget()
        return
    
    def _currentCommandStackParams(self):
        """
        The return value is supposed to be used by BUILD_PROTEIN command PM ONLY
        and NOT by any subclasses.         
        
        Returns a tuple containing current command stack change indicator and 
        the name of the command 'BUILD_PROTEIN'. These 
        parameters are then used to decide whether updating widgets
        in this property manager is needed, when self._update_UI_do_updates()
        is called. 
        
        @NOTE: 
        - Command_PropertyManager.update_UI() already does a check to see if 
          any of the global change indicators in assembly (command_stack_change, 
          model_change, selection_change) changed since last call and then only
          calls self._update_UI_do_updates(). 
        - But this method is just used to keep track of the 
          local command stack change counter in order to update the list 
          widgets.      
        - This is used to fix bug 2940
        
        @see: self._update_UI_do_updates()
        """
        commandStackCounter = self.command.assy.command_stack_change_indicator()
        #Append 'BUILD_PROTEIN to the tuple to be returned. This is just to remind 
        #us that this method is meant for BUILD_PROTEIN command PM only. (and not 
        #by any subclasses) Should we assert this? I think it will slow things 
        #down so this comment is enough -- Ninad 2008-09-30
        return (commandStackCounter, 'BUILD_PROTEIN')
                      
    def _currentSelectionParams(self):
        """
        Returns a tuple containing current selection parameters. These 
        parameters are then used to decide whether updating widgets
        in this property manager is needed when L{self.model_changed}
        method is called.
        
        @return: A tuple that contains total number of selected peptides.
        @rtype:  tuple
        
        @NOTE: This method may be renamed in future. 
        It's possible that there are other groupboxes in the PM that need to be 
        updated when something changes in the glpane.        
        """
         
        selectedProteins = []
        if self.command is not None: # and self.command.hasValidStructure():
            selectedProteins = self.win.assy.getSelectedProteinChunks()          
        return (selectedProteins)
    
    def _currentStructureParams(self):
        """
        Return current structure parameters of interest to self.model_changed. 
        Right now it only returns the number of peptides within the structure
        (or None). This is a good enough check (and no need to compare 
        each and every peptide within the structure with a previously stored 
        set of strands).
        """
        #Can it happen that the total number of peptides remains the same even 
        #after some alterations to the peptides? Unlikely. (Example: a single
        #(future) Break peptide operation will increase the number of peptides
        #by one. Or Join peptides decrease it by 1)
        params = None
        
        if self.command: # and self.command.hasValidStructure():
            proteinList = []
            proteinList = getAllProteinChunksInPart(self.win.assy)
            params = len(proteinList)
        return params
    
    def close(self):
        """
        Closes the Property Manager. Overrides EditCommand_PM.close()
        """
        #Clear tags, if any, due to the selection in the self.strandListWidget.
        #self.proteinListWidget.clear()
        env.history.statusbar_msg("")
        EditCommand_PM.close(self)
        return
    
    def show(self):
        """
        Show the PM. Extends superclass method.
        @note: _update_UI_do_updates() gets called immediately after this and
               updates PM widgets with their correct values/settings. 
        """
        
        env.history.statusbar_msg("")
        EditCommand_PM.show(self)
        
        # NOTE: Think about moving this msg to _update_UI_do_updates() where
        # custom msgs can be created based on the current selection, etc.
        # Mark 2008-12-14
        msg = "Select <b>Insert Peptide</b> to create a peptide chain or "\
            "select another modeling tool to modify an existing protein."
        self.updateMessage(msg)
        return
    
    def _editPeptide(self):  
        """
        Slot for the "Edit Properties" button. 
        """
        
        #if not self.command.hasValidStructure():
        #    return
        
        proteinChunk = self.win.assy.getSelectedProteinChunk()
        
        if proteinChunk:
            proteinChunk.protein.edit(self.win)
        return
    
    def _compareProteins(self):
        """
        Slot for the "Compare Proteins" button.
        """
        self.win.commandSequencer.userEnterCommand('COMPARE_PROTEINS')
        return
    
    def _addWhatsThisText( self ):
        """
        What's This text for widgets in the DNA Property Manager.  
        """
        pass
                
    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the DNA Property Manager.  
        """
        pass

    def _addGroupBoxes(self):
        """
        Add the Build Protein Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox(self, title = "Peptides")
        self._loadGroupBox1(self._pmGroupBox1)
        return
    
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in groupbox1.
        """
        
        self.proteinListWidget = PM_SelectionListWidget(pmGroupBox,
                                                       self.win,
                                                       label = "",
                                                       heightByRows = 6 )
        self.proteinListWidget.setObjectName('Peptide_list_widget')
        self.proteinListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')
        
        self.editPeptidePropertiesButton = PM_PushButton(pmGroupBox,
                                                         label = "",
                                                         text  = "Edit Properties..." )
        self.editPeptidePropertiesButton.setEnabled(False)
        
        self.compareProteinsButton = PM_PushButton(pmGroupBox,
                                                         label = "",
                                                         text  = "Compare Proteins..." )
        self.compareProteinsButton.setEnabled(False)
        
        return
    
    def updateProteinListWidget(self):   
        """
        Update the peptide list widget. It shows all peptides in the part.
        """
        proteinChunkList = getAllProteinChunksInPart(self.win.assy)
        
        if proteinChunkList:
            self.proteinListWidget.insertItems(
                row = 0,
                items = proteinChunkList)
        else:           
            self.proteinListWidget.clear()
        return
class CompareProteins_PropertyManager(Command_PropertyManager):
    """
    The CompareProteins_PropertyManager class provides a Property Manager
    for the B{Compare Proteins} command on the Build Protein flyout toolbar.

    @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

    @ivar proteinChunk1: The first currently selected protein to be compared.
    @type proteinChunk1: protein chunk

    @ivar proteinChunk2: The second currently selected protein to be compared.
    @type proteinChunk2: protein chunk
    """

    title = "Compare Proteins"
    pmName = title
    iconPath = "ui/actions/Command Toolbar/BuildProtein/Compare.png"
    proteinChunk1 = None
    proteinChunk2 = None

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

        _superclass.__init__(self, command)

        self.showTopRowButtons(PM_DONE_BUTTON | PM_WHATS_THIS_BUTTON)
        return

    def connect_or_disconnect_signals(self, isConnect=True):

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

        change_connect(self.comparePushButton, SIGNAL("clicked()"), self._compareProteins)

        change_connect(self.thresholdDoubleSpinBox, SIGNAL("valueChanged(double)"), self._thresholdChanged)

        change_connect(self.hidePushButton, SIGNAL("clicked()"), self._hideDifferences)
        return

    def close(self):
        """
        Closes the Property Manager. Overrides EditCommand_PM.close()
        """

        env.history.statusbar_msg("")
        self._resetAminoAcids()
        _superclass.close(self)

        # Restore the original global display style.
        self.o.setGlobalDisplayStyle(self.originalDisplayStyle)
        return

    def show(self):
        """
        Show the PM. Extends superclass method.

        @note: _update_UI_do_updates() gets called immediately after this and
               updates PM widgets with their correct values/settings.
        """
        _superclass.show(self)
        env.history.statusbar_msg("")

        # Force the Global Display Style to "Protein" since this is the only way
        # to see comparisons. The global display style will be restored when leaving
        # this command (via self.close()).
        self.originalDisplayStyle = self.o.displayMode
        self.o.setGlobalDisplayStyle(diPROTEIN)
        return

    def _addGroupBoxes(self):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox(self, title="Compare")
        self._loadGroupBox1(self._pmGroupBox1)
        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 _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        self.structure1LineEdit = PM_LineEdit(pmGroupBox, label="First structure:", setAsDefault=False)
        self.structure1LineEdit.setEnabled(False)

        self.structure2LineEdit = PM_LineEdit(pmGroupBox, label="Second structure:", setAsDefault=False)
        self.structure2LineEdit.setEnabled(False)

        self.thresholdDoubleSpinBox = PM_DoubleSpinBox(
            pmGroupBox,
            label="Threshold:",
            value=self.threshold,
            setAsDefault=True,
            minimum=0.0,
            maximum=360.0,
            decimals=1,
            singleStep=30.0,
            suffix=" deg",
            spanWidth=False,
        )

        self.comparePushButton = PM_PushButton(pmGroupBox, text="Compare", setAsDefault=True)

        self.hidePushButton = PM_PushButton(pmGroupBox, text="Hide differences", setAsDefault=True)
        return

    def _compareProteins(self):
        """
        Slot for Compare button.

        Compares two selected proteins of the same length.
        Amino acids that differ greater than the "threshold"
        value are displayed in two colors (red for the first protein
        and yellow for the second protein) and are only visible when
        the two proteins are displayed in the
        reduced display style.
        """
        from utilities.constants import red, orange, green, cyan

        if not self.proteinChunk1 or not self.proteinChunk2:
            return

        protein_1 = self.proteinChunk1.protein
        protein_2 = self.proteinChunk2.protein

        if protein_1 and protein_2:
            aa_list_1 = protein_1.get_amino_acids()
            aa_list_2 = protein_2.get_amino_acids()
            protein_1.collapse_all_rotamers()
            protein_2.collapse_all_rotamers()
            if len(aa_list_1) == len(aa_list_2):
                for aa1, aa2 in zip(aa_list_1, aa_list_2):
                    aa1.color = None
                    aa2.color = None
                    # aa1.collapse()
                    # aa2.collapse()
                    if aa1.get_one_letter_code() != aa2.get_one_letter_code():
                        aa1.set_color(red)
                        aa1.expand()
                        aa2.set_color(yellow)
                        aa2.expand()
                    else:
                        max = 0.0
                        for chi in range(0, 3):
                            angle1 = aa1.get_chi_angle(chi)
                            angle2 = aa2.get_chi_angle(chi)
                            if angle1 and angle2:
                                if angle1 < 0.0:
                                    angle1 += 360.0
                                if angle2 < 0.0:
                                    angle2 += 360.0
                                diff = abs(angle1 - angle2)
                                if diff > max:
                                    max = diff
                        if max >= self.threshold:
                            # This be a parameter.
                            aa1.set_color(green)
                            aa1.expand()
                            aa2.set_color(cyan)
                            aa2.expand()

                self.win.glpane.gl_update()
            else:
                msg = "The lengths of compared proteins are not equal."
                self.updateMessage(msg)
                env.history.redmsg(msg)
        return

    def _hideDifferences(self):
        """
        Slot for the "Hide differences" button.

        Hides amino acids that differ greater than the "threshold" value.

        @warning: Untested. Code looks suspicious.
        """
        if not self.proteinChunk1 or not self.proteinChunk2:
            return

        protein_1 = self.proteinChunk1.protein
        protein_2 = self.proteinChunk2.protein

        if protein_1 and protein_2:
            aa_list_1 = protein_1.get_amino_acids()
            aa_list_2 = protein_2.get_amino_acids()
            if len(aa_list_1) == len(aa_list_2):
                protein_1.collapse_all_rotamers()  # @@@
                protein_2.collapse_all_rotamers()  # @@@
                for aa1, aa2 in zip(aa_list_1, aa_list_2):
                    aa1.color = None
                    aa2.color = None
                    aa1.collapse()
                    aa2.collapse()
            self.win.glpane.gl_update()
        return

    def _thresholdChanged(self, value):
        """
        Slot for Threshold spinbox.
        """
        self.threshold = value
        self._compareProteins()
        return

    def _resetAminoAcids(self):
        """
        Resets the color and collapse all amino acids of all proteins.
        """

        proteinChunkList = getAllProteinChunksInPart(self.win.assy)

        for proteinChunk in proteinChunkList:
            proteinChunk.protein.collapse_all_rotamers()
            aa_list = proteinChunk.protein.get_amino_acids()
            for aa in aa_list:
                aa.color = None
                aa.collapse()

        self.win.glpane.gl_update()
        return

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

        @see: Command_PropertyManager._update_UI_do_updates()
        """

        self.proteinChunk1 = None
        self.proteinChunk2 = None
        self.comparePushButton.setEnabled(False)
        self.hidePushButton.setEnabled(False)

        selectedProteinList = self.win.assy.getSelectedProteinChunks()

        if len(selectedProteinList) == 0:
            self.structure1LineEdit.setText("")
            self.structure2LineEdit.setText("")
            msg = (
                "Select two structures of the same length in the graphics area, "
                "then click the <b>Compare</b> button to compare them."
            )

        elif len(selectedProteinList) == 1:
            self.proteinChunk1 = selectedProteinList[0]
            aa1_count = " (%d)" % self.proteinChunk1.protein.count_amino_acids()
            self.structure1LineEdit.setText(self.proteinChunk1.name + aa1_count)
            self.structure2LineEdit.setText("")
            msg = (
                "Select one more structure in the graphics area that is the same "
                "length as <b>" + self.proteinChunk1.name + "</b>. "
                "Then click the <b>Compare</b> button to compare them."
            )

        elif len(selectedProteinList) == 2:
            self.proteinChunk1 = selectedProteinList[0]
            aa1_count = " (%d)" % self.proteinChunk1.protein.count_amino_acids()
            self.structure1LineEdit.setText(self.proteinChunk1.name + aa1_count)

            self.proteinChunk2 = selectedProteinList[1]
            aa2_count = " (%d)" % self.proteinChunk2.protein.count_amino_acids()
            self.structure2LineEdit.setText(self.proteinChunk2.name + aa2_count)

            if aa1_count == aa2_count:
                self.comparePushButton.setEnabled(True)
                self.hidePushButton.setEnabled(True)
                msg = "Click the <b>Compare</b> button to compare the two selected structures."
            else:
                msg = "<b>%s</b> and <b>%s</b> are not the same length." % (
                    self.proteinChunk1.name,
                    self.proteinChunk2.name,
                )
                msg = redmsg(msg)

        else:
            self.structure1LineEdit.setText("")
            self.structure2LineEdit.setText("")
            msg = redmsg("Too many proteins selected.")

        self.updateMessage(msg)
        env.history.redmsg(msg)
        return
    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)
class BreakStrands_PropertyManager( BreakOrJoinStrands_PropertyManager):
    """
    The BreakStrands_PropertyManager class provides a Property Manager
    for the B{Break Strands} 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         =  "Break Strands"
    pmName        =  title
    iconPath      =  "ui/actions/Command Toolbar/BuildDna/BreakStrand.png"


    def __init__( self, command ):
        """
        Constructor for the property manager.
        """
        self._previous_model_changed_params = None
        #see self.connect_or_disconnect_signals for comment about this flag
        self.isAlreadyConnected = False
        self.isAlreadyDisconnected = False

        _superclass.__init__(self, command)

        msg = "Click on a strand's backbone bond to break a strand."
        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
        """
        #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

        _superclass.connect_or_disconnect_signals(self, isConnect = isConnect)


        if DEBUG_BREAK_OPTIONS_FEATURE:

            self._dnaStrandChooserGroupBox.connect_or_disconnect_signals(isConnect = isConnect)

            change_connect(self.breakAllStrandsButton,
                          SIGNAL("clicked()"),
                          self.command.breakStrandBonds)

            change_connect(self.basesBeforeNextBreakSpinBox,
                           SIGNAL("valueChanged(int)"),
                           self.valueChanged_basesBeforeNextBreak)


    def _update_UI_do_updates(self):
        """
        Overrides superclass method.
        @see: Command_PropertyManager._update_UI_do_updates()
        @see: DnaSegment_EditCommand.hasResizableStructure()
        @see: self._current_model_changed_params()
        """
        if not DEBUG_BREAK_OPTIONS_FEATURE:
            return



        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

        basesBeforeNextBreak = currentParams

        #update the self._previous_model_changed_params with this new param set.
        self._previous_model_changed_params = currentParams
        self.command.updateBreakSites()

    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:
            params = (env.prefs[breakStrandsCommand_numberOfBasesBeforeNextBreak_prefs_key])

        return params

    def valueChanged_basesBeforeNextBreak(self, val):
        self.win.glpane.gl_update()

    def getNumberOfBasesBeforeNextBreak(self):
        return self.basesBeforeNextBreakSpinBox.value()

    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """
        self._breakOptionsGroupbox = PM_GroupBox( self, title = "Break Options" )
        self._loadBreakOptionsGroupbox( self._breakOptionsGroupbox )


        self._displayOptionsGroupBox = PM_GroupBox( self, title = "Display Options" )
        self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox )

        self._baseNumberLabelGroupBox = PM_GroupBox( self, title = "Base Number Labels" )
        self._loadBaseNumberLabelGroupBox(self._baseNumberLabelGroupBox)


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

        self.assignColorToBrokenDnaStrandsCheckBox = \
            PM_CheckBox(pmGroupBox ,
                        text         = 'Assign new color to broken strands',
                        widgetColumn = 0,
                        spanWidth = True)

        connect_checkbox_with_boolean_pref(
            self.assignColorToBrokenDnaStrandsCheckBox,
            assignColorToBrokenDnaStrands_prefs_key )



        self.basesBeforeNextBreakSpinBox = \
            PM_SpinBox( pmGroupBox,
                        label         =  "Break Every:",
                        value         =  3,
                        setAsDefault  =  False,
                        minimum       =  1,
                        maximum       =  10000,
                        suffix       = " bases"
                        )

        connect_spinBox_with_pref(
            self.basesBeforeNextBreakSpinBox,
            breakStrandsCommand_numberOfBasesBeforeNextBreak_prefs_key)

        self.breakAllStrandsButton = PM_PushButton(
            pmGroupBox,
            label = "",
            text  = "do it" )


        self._dnaStrandChooserGroupBox = PM_ObjectChooser(
            pmGroupBox,
            self.command,
            modelObjectType = self.win.assy.DnaStrand,
            title = "Choose strands " )

        if not DEBUG_BREAK_OPTIONS_FEATURE:
            self._dnaStrandChooserGroupBox.hide()
            self.breakAllStrandsButton.hide()
            self.basesBeforeNextBreakSpinBox.hide()



    #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 breakStrandsCommand_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 breakStrandsCommand_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 breakStrandsCommand_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 breakStrandsCommand_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 breakStrandsCommand_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 breakStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key


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

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the DNA Property Manager.
        """
        pass
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 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
Esempio n. 46
0
    def loadTestWidgets1(self, inPmGroupBox):
        """
        Adds widgets to <inPmGroupBox>.
        Used for testing purposes. Mark 2007-05-24
        """

        # I intend to create a special PropMgr to display all widget types
        # for testing purposes. For now, I just add them to the end of the
        # Graphene Sheet property manager. Mark 2007-05-22

        self.spinBox = \
            PM_SpinBox( inPmGroupBox,
                        label        = "Spinbox:",
                        value        = 5,
                        setAsDefault = True,
                        minimum      = 2,
                        maximum      = 10,
                        suffix       = ' things',
                        spanWidth    = True )

        self.doubleSpinBox = \
            PM_DoubleSpinBox( inPmGroupBox,
                              #label="Spanning DoubleSpinBox :",
                              label        = "", # No label
                              value        = 5.0,
                              setAsDefault = True,
                              minimum      = 1.0,
                              maximum      = 10.0,
                              singleStep   = 1.0,
                              decimals     = 1,
                              suffix       = ' Suffix',
                              spanWidth    = True )

        # Add a prefix example.
        self.doubleSpinBox.setPrefix("Prefix ")

        choices = [ "First", "Second", "Third (Default)", "Forth" ]

        self.comboBox1= \
            PM_ComboBox( inPmGroupBox,
                         label        = 'Choices: ',
                         choices      = choices,
                         index        = 2,
                         setAsDefault = True,
                         spanWidth    = False )

        self.comboBox2= \
            PM_ComboBox( inPmGroupBox,
                         label        = ' :Choices',
                         labelColumn  = 1,
                         choices      = choices,
                         index        = 2,
                         setAsDefault = True,
                         spanWidth    = False )

        self.comboBox3= \
            PM_ComboBox( inPmGroupBox,
                         label        = ' Choices (SpanWidth = True):',
                         labelColumn  = 1,
                         choices      = choices,
                         index        = 2,
                         setAsDefault = True,
                         spanWidth    = True )

        self.textEdit = \
            PM_TextEdit( inPmGroupBox,
                         label     = "TextEdit:",
                         spanWidth = False )


        self.spanTextEdit = \
            PM_TextEdit( inPmGroupBox,
                         label     = "",
                         spanWidth = True )


        self.groupBox = \
            PM_GroupBox( inPmGroupBox,
                         title          = "Group Box Title" )

        self.comboBox2= \
            PM_ComboBox( self.groupBox,
                         label        = "Choices:",
                         choices      = choices,
                         index        = 2,
                         setAsDefault = True,
                         spanWidth    = False )

        self.groupBox2 = \
            PM_GroupBox( inPmGroupBox,
                         title          = "Group Box Title" )

        self.comboBox3= \
            PM_ComboBox( self.groupBox2,
                         label        = "Choices:",
                         choices      = choices,
                         index        = 2,
                         setAsDefault = True,
                         spanWidth    = True )

        self.pushButton1 = \
            PM_PushButton( inPmGroupBox,
                           label = "",
                           text  = "PushButton1" )

        self.pushButton2 = \
            PM_PushButton( inPmGroupBox,
                           label     = "",
                           text      = "PushButton2",
                           spanWidth = True )
Esempio n. 47
0
    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)
Esempio n. 48
0
class BuildNanotube_PropertyManager(EditCommand_PM):
    """
    The BuildNanotube_PropertyManager class provides a Property Manager
    for the B{Build > CNT } 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 = "Build Nanotube"
    pmName = title
    iconPath = "ui/actions/Command Toolbar/BuildNanotube/BuildNanotube.png"

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

        #Attributes for self._update_UI_do_updates() to keep track of changes
        #in these , since the last call of that method. These are used to
        #determine whether certain UI updates are needed.
        self._previousSelectionParams = None
        self._previousStructureParams = None
        self._previousCommandStackParams = None

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

        EditCommand_PM.__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
        """
        #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 actually reconnects the signal!
        #This gives rise to lots of bugs. This needs a more general fix in
        #the Temporary mode API.
        # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py

        if isConnect and self.isAlreadyConnected:
            return

        if not isConnect and self.isAlreadyDisconnected:
            return

        self.isAlreadyConnected = isConnect
        self.isAlreadyDisconnected = not isConnect

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

        self.nanotubeListWidget.connect_or_disconnect_signals(isConnect)

        change_connect(self.editNanotubePropertiesButton, SIGNAL("clicked()"),
                       self._editNanotube)
        return

    def enable_or_disable_gui_actions(self, bool_enable=False):
        """
        Enable or disable some gui actions when this property manager is
        opened or closed, depending on the bool_enable.

        """

        #For new command API, we will always show the exit button to check
        #if Exit button really exits the subcommand and the parent command
        #(earlier there were bugs) . Regaring 'whether this should be the
        #default behavior', its a UI design issue and we will worry about it
        #later -- Ninad 2008-08-27 (based on an email exchanged with Bruce)
        pass

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

        @see: Command_PropertyManager._update_UI_do_updates()
        """

        newSelectionParams = self._currentSelectionParams()
        current_struct_params = self._currentStructureParams()

        selection_params_unchanged = same_vals(newSelectionParams,
                                               self._previousSelectionParams)

        #introducing self._previousStructureParams and
        #adding structure_params_unchanged check to the 'if' condition below
        #fixes bug 2910.
        structure_params_unchanged = same_vals(self._previousStructureParams,
                                               current_struct_params)

        current_command_stack_params = self._currentCommandStackParams()

        #Check if command stack params changed since last call of this
        #PM update method. This is used to fix bugs like 2940
        command_stack_params_unchanged = same_vals(
            self._previousCommandStackParams, current_command_stack_params)

        #No need to proceed if any of the selection/ structure and commandstack
        #parameters remained unchanged since last call. --- [CONDITION A]
        if selection_params_unchanged and \
           structure_params_unchanged and \
           command_stack_params_unchanged:
            return

        self._previousStructureParams = current_struct_params
        self._previousSelectionParams = newSelectionParams
        self._previousCommandStackParams = current_command_stack_params

        if structure_params_unchanged:
            #NOTE: We checked if either of the selection struct or command stack
            #parameters or both changed. (this was referred as '[CONDITION A]'
            #above). So, this condition (structure_params_unchanged)also means
            #either selection or command stack or both parameters were changed.

            if not command_stack_params_unchanged:
                #update the nanotube list widget *before* updating the selection if
                #the command stack changed. This ensures that the selection box
                #appears around the list widget items that are selected.
                self.updateNanotubesListWidget()

            selectedNanotubeSegments = newSelectionParams

            self.nanotubeListWidget.updateSelection(selectedNanotubeSegments)

            self.updateNanotubePropertiesButton()
            return

        self.updateNanotubesListWidget()
        return

    def _currentCommandStackParams(self):
        """
        The return value is supposed to be used by BUILD_NANOTUBE command PM ONLY
        and NOT by any subclasses.

        Returns a tuple containing current command stack change indicator and
        the name of the command 'BUILD_NANOTUBE'. These
        parameters are then used to decide whether updating widgets
        in this property manager is needed, when self._update_UI_do_updates()
        is called.

        @NOTE:
        - Command_PropertyManager.update_UI() already does a check to see if
          any of the global change indicators in assembly (command_stack_change,
          model_change, selection_change) changed since last call and then only
          calls self._update_UI_do_updates().
        - But this method is just used to keep track of the
          local command stack change counter in order to update the list
          widgets.
        - This is used to fix bug 2940

        @see: self._update_UI_do_updates()
        """
        commandStackCounter = self.command.assy.command_stack_change_indicator(
        )
        #Append 'BUILD_NANOTUBE to the tuple to be returned. This is just to remind
        #us that this method is meant for BUILD_NANOTUBE command PM only. (and not
        #by any subclasses) Should we assert this? I think it will slow things
        #down so this comment is enough -- Ninad 2008-09-30
        return (commandStackCounter, 'BUILD_NANOTUBE')

    def _currentSelectionParams(self):
        """
        Returns a tuple containing current selection parameters. These
        parameters are then used to decide whether updating widgets
        in this property manager is needed when L{self.model_changed}
        method is called.

        @return: A tuple that contains total number of selected nanotubes.
        @rtype:  tuple

        @NOTE: This method may be renamed in future.
        It's possible that there are other groupboxes in the PM that need to be
        updated when something changes in the glpane.
        """
        selectedNanotubeSegments = []
        if self.command is not None:  # and self.command.hasValidStructure():
            selectedNanotubeSegments = self.win.assy.getSelectedNanotubeSegments(
            )
        return (selectedNanotubeSegments)

    def _currentStructureParams(self):
        """
        Return current structure parameters of interest to self.model_changed.
        Right now it only returns the number of nanotubes within the structure
        (or None). This is a good enough check (and no need to compare
        each and every nanotube within the structure with a previously stored
        set of strands).
        """
        params = None

        if self.command:  # and self.command.hasValidStructure():
            nanotubeSegmentList = []
            nanotubeSegmentList = getAllNanotubeSegmentsInPart(self.win.assy)
            params = len(nanotubeSegmentList)

        return params

    def close(self):
        """
        Closes the Property Manager. Overrides EditCommand_PM.close()
        """
        #Clear tags, if any, due to the selection in the self.strandListWidget.
        #self.nanotubeListWidget.clear()
        env.history.statusbar_msg("")
        EditCommand_PM.close(self)
        return

    def show(self):
        """
        Show the PM. Extends superclass method.
        @note: _update_UI_do_updates() gets called immediately after this and
               updates PM widgets with their correct values/settings.
        """

        env.history.statusbar_msg("")
        EditCommand_PM.show(self)

        # NOTE: Think about moving this msg to _update_UI_do_updates() where
        # custom msgs can be created based on the current selection, etc.
        # Mark 2008-12-14
        msg = "Select <b>Insert Nanotube</b> to create a nanotube or "\
            "select an existing nantube to modify it."
        self.updateMessage(msg)
        return

    def _editNanotube(self):
        """
        Slot for the "Edit Properties" button.
        """

        #if not self.command.hasValidStructure():
        #    return

        nanotubeSegment = self.win.assy.getSelectedNanotubeSegment()

        if nanotubeSegment:
            nanotubeSegment.edit()
        return

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

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

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

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

        self.nanotubeListWidget = PM_SelectionListWidget(pmGroupBox,
                                                         self.win,
                                                         label="",
                                                         heightByRows=12)
        self.nanotubeListWidget.setObjectName('nanotubeListWidget')
        self.nanotubeListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')

        self.editNanotubePropertiesButton = PM_PushButton(
            pmGroupBox, label="", text="Edit Properties...")
        self.editNanotubePropertiesButton.setEnabled(False)
        return

    def updateNanotubesListWidget(self):
        """
        Updates the nanotubes (selection) groupbox. This includes both the
        nanotube selection list widget (showing all nanotubes in the part)
        and the B{Edit Properties} button just below it (enabled if only
        one of the nanotubes is selected).
        """
        nanotubeSegmentList = getAllNanotubeSegmentsInPart(self.win.assy)

        if nanotubeSegmentList:
            self.nanotubeListWidget.insertItems(row=0,
                                                items=nanotubeSegmentList)
        else:
            self.nanotubeListWidget.clear()

        self.updateNanotubePropertiesButton()
        return

    def updateNanotubePropertiesButton(self):
        """
        Enables the B{Edit Properties} button if a single nanotube is currently
        selected. Otherwise, the button is disabled.
        """
        self.editNanotubePropertiesButton.setEnabled(
            bool(self.win.assy.getSelectedNanotubeSegment()))
        return
class Ui_ProteinSequenceEditor(PM_DockWidget):
    """
    The Ui_DnaSequenceEditor class defines UI elements for the Sequence Editor
    object. The sequence editor is usually visible while in DNA edit mode.
    It is a DockWidget that is doced at the bottom of the MainWindow
    """
    _title          =  "Sequence Editor"
    _groupBoxCount  =  0
    _lastGroupBox   =  None

    def __init__(self, win):
        """
        Constructor for the Ui_DnaSequenceEditor
        @param win: The parentWidget (MainWindow) for the sequence editor
        """
        self.win = win
        parentWidget = win
        _superclass.__init__(self, parentWidget, title = self._title)
        self._reportsDockWidget_closed_in_show_method = False
        self.setFixedHeight(90)
        return

    def show(self):
        """
        Shows the sequence editor. While doing this, it also closes the reports
        dock widget (if visible) the state of the reports dockwidget will be
        restored when the sequence editor is closed.
        @see:self.closeEvent()
        """
        self._reportsDockWidget_closed_in_show_method = False
        if self.win.viewFullScreenAction.isChecked() or \
           self.win.viewSemiFullScreenAction.isChecked():
            pass
        else:
            if self.win.reportsDockWidget.isVisible():
                self.win.reportsDockWidget.close()
                self._reportsDockWidget_closed_in_show_method = True
        _superclass.show(self)
        return

    def closeEvent(self, event):
        """
        Overrides close event. Makes sure that the visible state of the reports
        widgetis restored when the sequence editor is closed.
        @see: self.show()
        """
        _superclass.closeEvent(self, event)

        if self.win.viewFullScreenAction.isChecked() or \
           self.win.viewSemiFullScreenAction.isChecked():
            pass
        else:
            if self._reportsDockWidget_closed_in_show_method:
                self.win.viewReportsAction.setChecked(True)
                self._reportsDockWidget_closed_in_show_method = False
        return

    def _loadWidgets(self):
        """
        Overrides PM.PM_DockWidget._loadWidgets. Loads the widget in this
        dockwidget.
        """
        self._loadMenuWidgets()
        self._loadTextEditWidget()
        return

    def _loadMenuWidgets(self):
        """
        Load the various menu widgets (e.g. Open, save sequence options,
        Find and replace widgets etc.
        """

        self.loadSequenceButton = PM_ToolButton(
            self,
            iconPath = "ui/actions/Properties Manager/Open.png")

        self.saveSequenceButton = PM_ToolButton(
            self,
            iconPath = "ui/actions/Properties Manager/Save_Strand_Sequence.png")

        self.loadSequenceButton.setAutoRaise(True)
        self.saveSequenceButton.setAutoRaise(True)

        # Hide load and save buttons until they are implemented. -Mark 2008-12-20.
        self.loadSequenceButton.hide()
        self.saveSequenceButton.hide()

        #Find and replace widgets --
        self.findLineEdit = \
            PM_LineEdit( self,
                         label        = "",
                         spanWidth    = False)
        self.findLineEdit.setMaximumWidth(60)

        self.replaceLineEdit = \
            PM_LineEdit( self,
                         label        = "  Replace:",
                         spanWidth    = False)
        self.replaceLineEdit.setMaximumWidth(60)

        self.findOptionsToolButton = PM_ToolButton(self)
        self.findOptionsToolButton.setMaximumWidth(12)
        self.findOptionsToolButton.setAutoRaise(True)

        self.findOptionsToolButton.setPopupMode(QToolButton.MenuButtonPopup)

        self._setFindOptionsToolButtonMenu()

        self.findNextToolButton = PM_ToolButton(
            self,
            iconPath = "ui/actions/Properties Manager/Find_Next.png")
        self.findNextToolButton.setAutoRaise(True)

        self.findPreviousToolButton = PM_ToolButton(
            self,
            iconPath = "ui/actions/Properties Manager/Find_Previous.png")
        self.findPreviousToolButton.setAutoRaise(True)

        self.replacePushButton = PM_PushButton(self, text = "Replace")

        # Hide Replace widgets until we add support for transmuting residues.
        # Mark 2008-12-19
        #self.replaceLabel.hide()
        self.replacePushButton.hide()
        self.replaceLineEdit.hide()

        self.warningSign = QLabel(self)
        self.warningSign.setPixmap(
            getpixmap('ui/actions/Properties Manager/Warning.png'))
        self.warningSign.hide()

        self.phraseNotFoundLabel = QLabel(self)
        self.phraseNotFoundLabel.setText("Sequence Not Found")
        self.phraseNotFoundLabel.hide()

        #Widgets to include in the widget row.
        widgetList = [('PM_ToolButton', self.loadSequenceButton, 0),
                      ('PM_ToolButton', self.saveSequenceButton, 1),
                      ('QLabel', "                                     Find:", 4),
                      ('PM_LineEdit',   self.findLineEdit, 5),
                      ('PM_ToolButton', self.findOptionsToolButton, 6),
                      ('PM_ToolButton', self.findPreviousToolButton, 7),
                      ('PM_ToolButton', self.findNextToolButton, 8),
                      #('PM_Label',      self.replaceLabel, 9),
                      ('PM_TextEdit',   self.replaceLineEdit, 9),
                      ('PM_PushButton', self.replacePushButton, 10),
                      ('PM_Label', self.warningSign, 11),
                      ('PM_Label', self.phraseNotFoundLabel, 12),
                      ('QSpacerItem', 5, 5, 13) ]

        widgetRow = PM_WidgetRow(self,
                                 title     = '',
                                 widgetList = widgetList,
                                 label = "",
                                 spanWidth = True )
        return

    def _loadTextEditWidget(self):
        """
        Load the SequenceTexteditWidgets.
        """
        self.aaRulerTextEdit = \
            PM_TextEdit( self,
                         label = "",
                         spanWidth = False,
                         permit_enter_keystroke = False)

        palette = getPalette(None,
                             QPalette.Base,
                             pmGrpBoxColor)
        self.aaRulerTextEdit.setPalette(palette)
        self.aaRulerTextEdit.setWordWrapMode( QTextOption.WrapAnywhere )
        self.aaRulerTextEdit.setFixedHeight(20)
        self.aaRulerTextEdit.setReadOnly(True)

        self.sequenceTextEdit = \
            PM_TextEdit( self,
                         label = " Sequence: ",
                         spanWidth = False,
                         permit_enter_keystroke = False)
        #self.sequenceTextEdit.setReadOnly(True) #@@@

        self.sequenceTextEdit.setCursorWidth(2)
        self.sequenceTextEdit.setWordWrapMode( QTextOption.WrapAnywhere )
        self.sequenceTextEdit.setFixedHeight(20)

        self.secStrucTextEdit = \
            PM_TextEdit( self,
                         label = " Secondary structure: ",
                         spanWidth = False,
                         permit_enter_keystroke = False)

        palette = getPalette(None,
                             QPalette.Base,
                             sequenceEditStrandMateBaseColor)
        self.secStrucTextEdit.setPalette(palette)
        self.secStrucTextEdit.setWordWrapMode( QTextOption.WrapAnywhere )
        self.secStrucTextEdit.setFixedHeight(20)
        self.secStrucTextEdit.setReadOnly(True)

        #Important to make sure that the horizontal and vertical scrollbars
        #for these text edits are never displayed.

        self.sequenceTextEdit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.sequenceTextEdit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.secStrucTextEdit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.secStrucTextEdit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.aaRulerTextEdit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.aaRulerTextEdit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        return

    def _getFindLineEditStyleSheet(self):
        """
        Return the style sheet for the findLineEdit. This sets the following
        properties only:
         - background-color

        This style is set whenever the searchStrig can't be found (sets
        a light red color background to the lineedit when this happens)

        @return: The line edit style sheet.
        @rtype:  str

        """
        styleSheet = "QLineEdit {"\
                   "background-color: rgb(255, 102, 102)"\
                   "}"

        return styleSheet

    def _setFindOptionsToolButtonMenu(self):
        """
        Sets the menu for the findOptionstoolbutton that appears a small
        menu button next to the findLineEdit.
        """
        self.findOptionsMenu = QMenu(self.findOptionsToolButton)
        self.caseSensitiveFindAction = QAction(self.findOptionsToolButton)
        self.caseSensitiveFindAction.setText('Match Case')
        self.caseSensitiveFindAction.setCheckable(True)
        self.caseSensitiveFindAction.setChecked(False)
        self.findOptionsMenu.addAction(self.caseSensitiveFindAction)
        self.findOptionsMenu.addSeparator()
        self.findOptionsToolButton.setMenu(self.findOptionsMenu)
        return

    def _addToolTipText(self):
        """
        What's Tool Tip text for widgets in this Property Manager.
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_ProteinSequenceEditor
        ToolTip_ProteinSequenceEditor(self)
        return

    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_ProteinSequenceEditor
        whatsThis_ProteinSequenceEditor(self)
        return
    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
Esempio n. 51
0
class BreakStrands_PropertyManager(BreakOrJoinStrands_PropertyManager):
    """
    The BreakStrands_PropertyManager class provides a Property Manager 
    for the B{Break Strands} 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 = "Break Strands"
    pmName = title
    iconPath = "ui/actions/Command Toolbar/BuildDna/BreakStrand.png"

    def __init__(self, command):
        """
        Constructor for the property manager.
        """
        self._previous_model_changed_params = None
        #see self.connect_or_disconnect_signals for comment about this flag
        self.isAlreadyConnected = False
        self.isAlreadyDisconnected = False

        _superclass.__init__(self, command)

        msg = "Click on a strand's backbone bond to break a strand."
        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
        """
        #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

        _superclass.connect_or_disconnect_signals(self, isConnect=isConnect)

        if DEBUG_BREAK_OPTIONS_FEATURE:

            self._dnaStrandChooserGroupBox.connect_or_disconnect_signals(
                isConnect=isConnect)

            change_connect(self.breakAllStrandsButton, SIGNAL("clicked()"),
                           self.command.breakStrandBonds)

            change_connect(self.basesBeforeNextBreakSpinBox,
                           SIGNAL("valueChanged(int)"),
                           self.valueChanged_basesBeforeNextBreak)

    def _update_UI_do_updates(self):
        """
        Overrides superclass method. 
        @see: Command_PropertyManager._update_UI_do_updates()
        @see: DnaSegment_EditCommand.hasResizableStructure()
        @see: self._current_model_changed_params()
        """
        if not DEBUG_BREAK_OPTIONS_FEATURE:
            return

        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

        basesBeforeNextBreak = currentParams

        #update the self._previous_model_changed_params with this new param set.
        self._previous_model_changed_params = currentParams
        self.command.updateBreakSites()

    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:
            params = (env.prefs[
                breakStrandsCommand_numberOfBasesBeforeNextBreak_prefs_key])

        return params

    def valueChanged_basesBeforeNextBreak(self, val):
        self.win.glpane.gl_update()

    def getNumberOfBasesBeforeNextBreak(self):
        return self.basesBeforeNextBreakSpinBox.value()

    def _addGroupBoxes(self):
        """
        Add the Property Manager group boxes.
        """
        self._breakOptionsGroupbox = PM_GroupBox(self, title="Break Options")
        self._loadBreakOptionsGroupbox(self._breakOptionsGroupbox)

        self._displayOptionsGroupBox = PM_GroupBox(self,
                                                   title="Display Options")
        self._loadDisplayOptionsGroupBox(self._displayOptionsGroupBox)

        self._baseNumberLabelGroupBox = PM_GroupBox(self,
                                                    title="Base Number Labels")
        self._loadBaseNumberLabelGroupBox(self._baseNumberLabelGroupBox)

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

        self.assignColorToBrokenDnaStrandsCheckBox = \
            PM_CheckBox(pmGroupBox ,
                        text         = 'Assign new color to broken strands',
                        widgetColumn = 0,
                        spanWidth = True)

        connect_checkbox_with_boolean_pref(
            self.assignColorToBrokenDnaStrandsCheckBox,
            assignColorToBrokenDnaStrands_prefs_key)



        self.basesBeforeNextBreakSpinBox = \
            PM_SpinBox( pmGroupBox,
                        label         =  "Break Every:",
                        value         =  3,
                        setAsDefault  =  False,
                        minimum       =  1,
                        maximum       =  10000,
                        suffix       = " bases"
                        )

        connect_spinBox_with_pref(
            self.basesBeforeNextBreakSpinBox,
            breakStrandsCommand_numberOfBasesBeforeNextBreak_prefs_key)

        self.breakAllStrandsButton = PM_PushButton(pmGroupBox,
                                                   label="",
                                                   text="do it")

        self._dnaStrandChooserGroupBox = PM_ObjectChooser(
            pmGroupBox,
            self.command,
            modelObjectType=self.win.assy.DnaStrand,
            title="Choose strands ")

        if not DEBUG_BREAK_OPTIONS_FEATURE:
            self._dnaStrandChooserGroupBox.hide()
            self.breakAllStrandsButton.hide()
            self.basesBeforeNextBreakSpinBox.hide()

    #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 breakStrandsCommand_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 breakStrandsCommand_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 breakStrandsCommand_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 breakStrandsCommand_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 breakStrandsCommand_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 breakStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key

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

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the DNA Property Manager.  
        """
        pass
class OrderDna_PropertyManager(Command_PropertyManager):
    """
    The OrderDna_PropertyManager class provides a Property Manager 
    for the B{Order Dna} 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 = "Order DNA"
    pmName = title
    iconPath = "ui/actions/Command Toolbar/BuildDna/OrderDna.png"

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

        _superclass.__init__(self, command)

        self.assy = self.win.assy

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        self.update_includeStrands()  # Updates the message box.
        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

        change_connect(self.viewDnaOrderFileButton, SIGNAL("clicked()"),
                       self.viewDnaOrderFile)

        change_connect(self.includeStrandsComboBox, SIGNAL("activated(int)"),
                       self.update_includeStrands)
        return

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

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

        includeStrandsChoices = [
            "All strands in model", "Selected strands only"
        ]

        self.includeStrandsComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Include strands:",
                         choices       =  includeStrandsChoices,
                         setAsDefault  =  True)

        self.numberOfBasesLineEdit  = \
            PM_LineEdit( pmGroupBox,
                         label  =  "Total nucleotides:",
                         text   = str(self.getNumberOfBases()))
        self.numberOfBasesLineEdit.setEnabled(False)

        self.numberOfXBasesLineEdit  = \
            PM_LineEdit( pmGroupBox,
                         label  =  "Unassigned:",
                         text   = str(self.getNumberOfBases(unassignedOnly = True)))
        self.numberOfXBasesLineEdit.setEnabled(False)

        self.viewDnaOrderFileButton = \
            PM_PushButton( pmGroupBox,
                           label     = "",
                           text      = "View DNA Order File...",
                           spanWidth = True)
        return

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

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

    # Ask Bruce where this should live (i.e. class Part?) --Mark
    def getAllDnaStrands(self, selectedOnly=False):
        """
        Returns a list of all the DNA strands in the current part, or only
        the selected strands if I{selectedOnly} is True.
        
        @param selectedOnly: If True, return only the selected DNA strands.
        @type  selectedOnly: bool
        """

        dnaStrandList = []

        def func(node):
            if isinstance(node, DnaStrand):
                if selectedOnly:
                    if node.picked:
                        dnaStrandList.append(node)
                else:
                    dnaStrandList.append(node)

        self.win.assy.part.topnode.apply2all(func)

        return dnaStrandList

    def getNumberOfBases(self, selectedOnly=False, unassignedOnly=False):
        """
        Returns the number of bases count for all the DNA strands in the 
        current part, or only the selected strand if I{selectedOnly} is True.
        
        @param selectedOnly: If True, return only the number of bases in the
                             selected DNA strands.
        @type  selectedOnly: bool
        
        @param unassignedOnly: If True, return only the number of unassigned
                               bases (i.e. base letters = X).
        @type  unassignedOnly: bool
        """
        dnaSequenceString = ''
        selectedOnly = self.includeStrandsComboBox.currentIndex()
        strandList = self.getAllDnaStrands(selectedOnly)

        for strand in strandList:
            strandSequenceString = str(strand.getStrandSequence())
            dnaSequenceString += strandSequenceString

        if unassignedOnly:
            return dnaSequenceString.count("X")

        return len(dnaSequenceString)

    def _update_UI_do_updates(self):
        """
        Overrides superclass method.
        """
        self.update_includeStrands()
        return

    def getDnaSequence(self, format='CSV'):
        """
        Return the complete Dna sequence information string (i.e. all strand 
        sequences) in the specified format. 
        
        @return: The Dna sequence string
        @rtype: string
        
        """
        if format == 'CSV':  #comma separated values.
            separator = ','

        dnaSequenceString = ''
        selectedOnly = self.includeStrandsComboBox.currentIndex()
        strandList = self.getAllDnaStrands(selectedOnly)

        for strand in strandList:
            dnaSequenceString = dnaSequenceString + strand.name + separator
            strandSequenceString = str(strand.getStrandSequence())
            if strandSequenceString:
                strandSequenceString = strandSequenceString.upper()
                strandLength = str(len(strandSequenceString)) + separator
                dnaSequenceString = dnaSequenceString + strandLength + strandSequenceString

            dnaSequenceString = dnaSequenceString + "\n"

        return dnaSequenceString

    def viewDnaOrderFile(self, openFileInEditor=True):
        """
        Writes a DNA Order file in comma-separated values (CSV) format 
        and opens it in a text editor.

        The user must save the file to a permanent location using the 
        text editor.

        @see: Ui_DnaFlyout.orderDnaCommand
        @see: writeDnaOrderFile()
        @TODO: assy.getAllDnaObjects(). 
        """
        dnaSequence = self.getDnaSequence(format='CSV')

        if dnaSequence:
            tmpdir = find_or_make_Nanorex_subdir('temp')
            fileBaseName = 'DnaOrder'
            temporaryFile = os.path.join(tmpdir, "%s.csv" % fileBaseName)
            writeDnaOrderFile(temporaryFile, self.assy,
                              self.getNumberOfBases(),
                              self.getNumberOfBases(unassignedOnly=True),
                              dnaSequence)

            if openFileInEditor:
                open_file_in_editor(temporaryFile)

        return

    def update_includeStrands(self, ignoreVal=0):
        """
        Slot method for "Include (strands)" combobox.
        """

        idx = self.includeStrandsComboBox.currentIndex()

        includeType = ["model", "selection"]

        _numberOfBases = self.getNumberOfBases()
        self.numberOfBasesLineEdit.setText(str(_numberOfBases) + " bases")

        _numberOfXBases = self.getNumberOfBases(unassignedOnly=True)
        self.numberOfXBasesLineEdit.setText(str(_numberOfXBases) + " bases")

        # Make the background color red if there are any unassigned bases.
        if _numberOfXBases:
            self.numberOfXBasesLineEdit.setStyleSheet(\
                "QLineEdit {"\
                "background-color: rgb(255, 0, 0)"\
                "}")
        else:
            self.numberOfXBasesLineEdit.setStyleSheet(\
                "QLineEdit {"\
                "background-color: rgb(255, 255, 255)"\
                "}")

        if _numberOfBases > 0:
            self.viewDnaOrderFileButton.setEnabled(True)
            msg = "Click on <b>View DNA Order File...</b> to preview a " \
                "DNA order for all DNA strands in the current %s." \
                % includeType[idx]
        else:
            self.viewDnaOrderFileButton.setEnabled(False)
            msg = "<font color=red>" \
                "There are no DNA strands in the current %s." \
                % includeType[idx]

        self.updateMessage(msg)
        return
    def _loadMenuWidgets(self):
        """
        Load the various menu widgets (e.g. Open, save sequence options, 
        Find and replace widgets etc. 
        """
        #Note: Find and replace widgets might be moved to their own class.

        self.loadSequenceButton = PM_ToolButton(
            self,
            iconPath = "ui/actions/Properties Manager/Open.png")  

        self.saveSequenceButton = PM_ToolButton(
            self, 
            iconPath = "ui/actions/Properties Manager/Save_Strand_Sequence.png") 

        self.loadSequenceButton.setAutoRaise(True)
        self.saveSequenceButton.setAutoRaise(True)

        
        #Find and replace widgets --
        self.findLineEdit = \
            PM_LineEdit( self, 
                         label        = "",
                         spanWidth    = False)
        self.findLineEdit.setMaximumWidth(60)


        self.replaceLineEdit = \
            PM_LineEdit( self, 
                         label        = "",
                         spanWidth    = False)
        self.replaceLineEdit.setMaximumWidth(60)

        self.findOptionsToolButton = PM_ToolButton(self)
        self.findOptionsToolButton.setMaximumWidth(12)
        self.findOptionsToolButton.setAutoRaise(True)

        self.findOptionsToolButton.setPopupMode(QToolButton.MenuButtonPopup)

        self._setFindOptionsToolButtonMenu()

        self.findNextToolButton = PM_ToolButton(
            self,
            iconPath = "ui/actions/Properties Manager/Find_Next.png")
        self.findNextToolButton.setAutoRaise(True)

        self.findPreviousToolButton = PM_ToolButton(
            self,
            iconPath = "ui/actions/Properties Manager/Find_Previous.png")
        self.findPreviousToolButton.setAutoRaise(True)

        self.replacePushButton = PM_PushButton(self, text = "Replace")

        self.warningSign = QLabel(self)
        self.warningSign.setPixmap(
            getpixmap('ui/actions/Properties Manager/Warning.png'))
        self.warningSign.hide()

        self.phraseNotFoundLabel = QLabel(self)
        self.phraseNotFoundLabel.setText("Sequence Not Found")
        self.phraseNotFoundLabel.hide()

        

        #Widgets to include in the widget row. 
        widgetList = [('PM_ToolButton', self.loadSequenceButton, 0),
                      ('PM_ToolButton', self.saveSequenceButton, 1),
                      ('QLabel', "     Find:", 4),
                      ('PM_LineEdit', self.findLineEdit, 5),
                      ('PM_ToolButton', self.findOptionsToolButton, 6),
                      ('PM_ToolButton', self.findPreviousToolButton, 7),
                      ('PM_ToolButton', self.findNextToolButton, 8), 
                      ('QLabel', "     Replace:", 9),
                      ('PM_TextEdit', self.replaceLineEdit, 10), 
                      ('PM_PushButton', self.replacePushButton, 11),
                      ('PM_Label', self.warningSign, 12),
                      ('PM_Label', self.phraseNotFoundLabel, 13),
                      ('QSpacerItem', 5, 5, 14) ]

        widgetRow = PM_WidgetRow(self,
                                 title     = '',
                                 widgetList = widgetList,
                                 label = "",
                                 spanWidth = True )