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 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
示例#3
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 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
示例#5
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 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
示例#7
0
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 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
示例#9
0
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
示例#10
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 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 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