Esempio n. 1
0
class BreakOrJoinStrands_PropertyManager(Command_PropertyManager):

    _baseNumberLabelGroupBox = None

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

        return

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

        # DNA Strand arrowhead display options signal-slot connections.

        self._connect_checkboxes_to_global_prefs_keys(isConnect)

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

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

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

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

        self._baseNumberLabelGroupBox.connect_or_disconnect_signals(isConnect)

        return

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

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

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

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

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

        return

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

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

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

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

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

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

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

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

        return

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

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

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

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

        return

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    title         =  "Make Crossovers"
    pmName        =  title
    iconPath      =  "ui/actions/Command Toolbar/BuildDna/MakeCrossovers.png"


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

            

        self.isAlreadyConnected = False
        self.isAlreadyDisconnected = False

        self._previous_model_changed_params = None

        _superclass.__init__(self, command)

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

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

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

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

        self.isAlreadyConnected = isConnect
        self.isAlreadyDisconnected = not isConnect

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

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

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

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


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


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

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

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

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

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

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

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

        return params

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

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the DNA Property Manager.  
        """
        pass
Esempio n. 3
0
class MakeCrossovers_PropertyManager(Command_PropertyManager,
                                     ListWidgetItems_PM_Mixin):
    """
    The MakeCrossovers_PropertyManager class provides a Property Manager 
    for the B{Make Crossovers} command on the flyout toolbar in the 
    Build > Dna mode. 

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

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

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

    title = "Make Crossovers"
    pmName = title
    iconPath = "ui/actions/Command Toolbar/BuildDna/MakeCrossovers.png"

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

        self.isAlreadyConnected = False
        self.isAlreadyDisconnected = False

        self._previous_model_changed_params = None

        _superclass.__init__(self, command)


        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

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

        self.updateMessage(self.defaultLogMessage)

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

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

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

        self.isAlreadyConnected = isConnect
        self.isAlreadyDisconnected = not isConnect

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

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

        change_connect(self.makeCrossoverPushButton, SIGNAL("clicked()"),
                       self._makeAllCrossovers)

        connect_checkbox_with_boolean_pref(
            self.crossoversBetGivenSegmentsOnly_checkBox,
            makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key
        )

    def show(self):
        """
        Overrides the superclass method
        @see: self._deactivateAddRemoveSegmentsTool
        """
        _superclass.show(self)
        self._deactivateAddRemoveSegmentsTool()

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

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

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

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

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

        self.makeCrossoverPushButton = PM_PushButton(
            pmGroupBox, label="", text="Make All Crossovers", spanWidth=True)

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

        currentParams = self._current_model_changed_params()

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


        number_of_segments, \
                          crossover_search_pref_junk,\
                          bool_valid_segmentList_junk = currentParams

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

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

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

        return params

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

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

    _baseNumberLabelGroupBox = None

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


        return

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

        # DNA Strand arrowhead display options signal-slot connections.


        self._connect_checkboxes_to_global_prefs_keys(isConnect)

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

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

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

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

        self._baseNumberLabelGroupBox.connect_or_disconnect_signals(isConnect)

        return

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


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

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

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

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

        return

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

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

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

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

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

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

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

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

        return

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


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

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

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

        return

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    title         =  "Edit Protein Display Style"
    pmName        =  title
    iconPath      =  "ui/actions/Edit/EditProteinDisplayStyle.png"
    
    def __init__( self, command ):
        """
        Constructor for the property manager.
        """

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

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        
     
        msg = "Modify the protein display settings below."
        self.updateMessage(msg)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.updateProteinDisplayStyleWidgets()
        return

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


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

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

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

                #favorite file already exists!

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

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

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

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

        env.history.message(msg)

        return

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

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

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

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

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

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

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

    def _addToolTipText(self):
        """
        Add tool tip text to all widgets.
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager 
        ToolTip_EditProteinDisplayStyle_PropertyManager(self)
class ProteinDisplayStyle_PropertyManager(PM_Dialog, DebugMenuMixin):
    """
    The ProteinDisplayStyle_PropertyManager class provides a Property Manager 
    for the B{Display Style} command on the flyout toolbar in the 
    Build > Protein mode. 

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

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

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

    title = "Edit Protein Display Style"
    pmName = title
    iconPath = "ui/actions/Edit/EditProteinDisplayStyle.png"

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

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

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

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

        DebugMenuMixin._init1(self)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Modify the protein display settings below."
        self.updateMessage(msg)

    def connect_or_disconnect_signals(self, isConnect=True):

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

        # Favorite buttons signal-slot connections.
        change_connect(self.applyFavoriteButton, SIGNAL("clicked()"),
                       self.applyFavorite)

        change_connect(self.addFavoriteButton, SIGNAL("clicked()"),
                       self.addFavorite)

        change_connect(self.deleteFavoriteButton, SIGNAL("clicked()"),
                       self.deleteFavorite)

        change_connect(self.saveFavoriteButton, SIGNAL("clicked()"),
                       self.saveFavorite)

        change_connect(self.loadFavoriteButton, SIGNAL("clicked()"),
                       self.loadFavorite)

        #Display group box signal slot connections
        change_connect(self.proteinStyleComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.changeProteinDisplayStyle)

        change_connect(self.smoothingCheckBox, SIGNAL("stateChanged(int)"),
                       self.smoothProteinDisplay)
        change_connect(self.scaleComboBox, SIGNAL("currentIndexChanged(int)"),
                       self.changeProteinDisplayScale)
        change_connect(self.splineDoubleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.changeProteinSplineValue)
        change_connect(self.scaleFactorDoubleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.changeProteinScaleFactor)

        #color groupbox
        change_connect(self.proteinComponentComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.chooseProteinComponent)

        change_connect(self.proteinAuxComponentComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.chooseAuxilliaryProteinComponent)

        change_connect(self.customColorComboBox, SIGNAL("editingFinished()"),
                       self.chooseCustomColor)

        change_connect(self.auxColorComboBox, SIGNAL("editingFinished()"),
                       self.chooseAuxilliaryColor)

        change_connect(self.discColorCheckBox, SIGNAL("stateChanged(int)"),
                       self.setDiscreteColors)

        change_connect(self.helixColorComboBox, SIGNAL("editingFinished()"),
                       self.chooseHelixColor)

        change_connect(self.strandColorComboBox, SIGNAL("editingFinished()"),
                       self.chooseStrandColor)

        change_connect(self.coilColorComboBox, SIGNAL("editingFinished()"),
                       self.chooseCoilColor)

    #Protein Display methods

    def changeProteinDisplayStyle(self, idx):
        env.prefs[proteinStyle_prefs_key] = idx
        return

    def changeProteinDisplayQuality(self, idx):
        env.prefs[proteinStyleQuality_prefs_key] = idx
        return

    def smoothProteinDisplay(self, state):
        if state == Qt.Checked:
            env.prefs[proteinStyleSmooth_prefs_key] = True
        else:
            env.prefs[proteinStyleSmooth_prefs_key] = False
        return

    def changeProteinDisplayScale(self, idx):
        env.prefs[proteinStyleScaling_prefs_key] = idx
        return

    def changeProteinSplineValue(self, val):
        env.prefs[proteinStyleQuality_prefs_key] = val
        return

    def changeProteinScaleFactor(self, val):
        env.prefs[proteinStyleScaleFactor_prefs_key] = val
        return

    def chooseProteinComponent(self, idx):
        env.prefs[proteinStyleColors_prefs_key] = idx
        return

    def chooseAuxilliaryProteinComponent(self, idx):
        env.prefs[proteinStyleAuxColors_prefs_key] = idx - 1
        return

    def chooseCustomColor(self):
        color = self.customColorComboBox.getColor()
        env.prefs[proteinStyleCustomColor_prefs_key] = color
        return

    def chooseAuxilliaryColor(self):
        color = self.auxColorComboBox.getColor()
        env.prefs[proteinStyleAuxCustomColor_prefs_key] = color
        return

    def chooseHelixColor(self):
        color = self.helixColorComboBox.getColor()
        env.prefs[proteinStyleHelixColor_prefs_key] = color
        return

    def chooseStrandColor(self):
        color = self.strandColorComboBox.getColor()
        env.prefs[proteinStyleStrandColor_prefs_key] = color
        return

    def chooseCoilColor(self):
        color = self.coilColorComboBox.getColor()
        env.prefs[proteinStyleCoilColor_prefs_key] = color
        return

    def setDiscreteColors(self, state):
        if state == Qt.Checked:
            env.prefs[proteinStyleColorsDiscrete_prefs_key] = True
        else:
            env.prefs[proteinStyleColorsDiscrete_prefs_key] = False
        return

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

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

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

        #Not required for Proteins
        # Force the Global Display Style to "DNA Cylinder" so the user
        # can see the display style setting effects on any DNA in the current
        # model. The current global display style will be restored when leaving
        # this command (via self.close()).
        #self.originalDisplayStyle = self.o.getGlobalDisplayStyle()
        #self.o.setGlobalDisplayStyle(diDNACYLINDER)

        # Update all PM widgets, then establish their signal-slot connections.
        # note: It is important to update the widgets *first* since doing
        # it in the reverse order will generate signals when updating
        # the PM widgets (via updateDnaDisplayStyleWidgets()), causing
        # unneccessary repaints of the model view.
        self.updateProteinDisplayStyleWidgets()
        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)

        #Not required for proteins
        # Restore the original global display style.
        #self.o.setGlobalDisplayStyle(self.originalDisplayStyle)

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

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

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

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        # Other info
        # Not only loads the factory default settings but also all the favorite
        # files stored in the ~/Nanorex/Favorites/ProteinDisplayStyle directory

        favoriteChoices = ['Factory default settings']

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

        for file in os.listdir(_dir):
            fullname = os.path.join(_dir, file)
            if os.path.isfile(fullname):
                if fnmatch.fnmatch(file, "*.txt"):

                    # leave the extension out
                    favoriteChoices.append(file[0:len(file) - 4])

        self.favoritesComboBox  = \
            PM_ComboBox( pmGroupBox,
                         choices       =  favoriteChoices,
                         spanWidth  =  True)

        self.favoritesComboBox.setWhatsThis("""<b> List of Favorites </b>

            <p>
            Creates a list of favorite Protein display styles. Once favorite
            styles have been added to the list using the Add Favorite button,
            the list will display the chosen favorites.
            To change the current favorite, select a current favorite from
            the list, and push the Apply Favorite button.""")

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

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

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

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

        self.favsButtonGroup.buttonGroup.setExclusive(False)

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

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        proteinStyleChoices = [
            'CA trace (wire)', 'CA trace (cylinders)',
            'CA trace (ball and stick)', 'Tube', 'Ladder', 'Zigzag',
            'Flat ribbon', 'Solid ribbon', 'Cartoons', 'Fancy cartoons',
            'Peptide tiles'
        ]

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

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


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

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

        self.smoothingCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Smoothing",
                         setAsDefault = True)

    def _loadGroupBox3(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        colorChoices = [
            'Chunk', 'Chain', 'Order', 'Hydropathy', 'Polarity', 'Acidity',
            'Size', 'Character', 'Number of contacts',
            'Secondary structure type', 'Secondary structure order',
            'B-factor', 'Occupancy', 'Custom'
        ]

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

        colorList = [
            orange, yellow, red, magenta, cyan, blue, white, black, gray
        ]

        colorNames = [
            "Orange(default)", "Yellow", "Red", "Magenta", "Cyan", "Blue",
            "White", "Black", "Other color..."
        ]

        self.customColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                            colorList = colorList,
                            colorNames = colorNames,
                            label      = "Custom:",
                            color      = orange,
                            setAsDefault  =  True)

        colorChoices1 = [
            'Same as main color', 'Chunk', 'Chain', 'Order', 'Hydropathy',
            'Polarity', 'Acidity', 'Size', 'Character', 'Number of contacts',
            'Secondary structure type', 'Secondary structure order',
            'B-factor', 'Occupancy', 'Custom'
        ]

        self.proteinAuxComponentComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Aux:",
                         choices       =  colorChoices1,
                         setAsDefault  =  True)

        colorListAux = [
            orange, yellow, red, magenta, cyan, blue, white, black, gray
        ]

        colorNamesAux = [
            "Orange(default)", "Yellow", "Red", "Magenta", "Cyan", "Blue",
            "White", "Black", "Other color..."
        ]

        self.auxColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                             colorList = colorListAux,
                             colorNames = colorNamesAux,
                             label = "Custom aux:",
                             color = gray,
                             setAsDefault  =  True)

        self.discColorCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text = "Discretize colors",
                         setAsDefault = True
                         )

        colorListHelix = [
            red, yellow, gray, magenta, cyan, blue, white, black, orange
        ]

        colorNamesHelix = [
            "Red(default)", "Yellow", "Gray", "Magenta", "Cyan", "Blue",
            "White", "Black", "Other color..."
        ]

        self.helixColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                            colorList = colorListHelix,
                            colorNames = colorNamesHelix,
                            label      = "Helix:",
                            color      = red,
                            setAsDefault  =  True)

        colorListStrand = [
            cyan, yellow, gray, magenta, red, blue, white, black, orange
        ]

        colorNamesStrand = [
            "Cyan(default)", "Yellow", "Gray", "Magenta", "Red", "Blue",
            "White", "Black", "Other color..."
        ]

        self.strandColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                            colorList = colorListStrand,
                            colorNames = colorNamesStrand,
                            label      = "Strand:",
                            color      = cyan,
                            setAsDefault  =  True)

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

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

        return

    def applyFavorite(self):

        # Rules and other info:
        # The user has to press the button related to this method when he loads
        # a previously saved favorite file

        current_favorite = self.favoritesComboBox.currentText()
        if current_favorite == 'Factory default settings':
            env.prefs.restore_defaults(proteinDisplayStylePrefsList)
        else:
            favfilepath = getFavoritePathFromBasename(current_favorite)
            loadFavoriteFile(favfilepath)

        self.updateProteinDisplayStyleWidgets()
        return

    def addFavorite(self):

        # Rules and other info:

        # - The new favorite is defined by the current Protein display style

        #  settings.

        # - The user is prompted to type in a name for the new
        #    favorite.
        # - The DNA display style settings are written to a file in a special
        #    directory on the disk
        # (i.e. $HOME/Nanorex/Favorites/ProteinDisplayStyle/$FAV_NAME.txt).
        # - The name of the new favorite is added to the list of favorites in
        #    the combobox, which becomes the current option.

        # Existence of a favorite with the same name is checked in the above
        # mentioned location and if a duplicate exists, then the user can either
        # overwrite and provide a new name.

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

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

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

                #favorite file already exists!

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

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

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

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

        env.history.message(msg)

        return

    def deleteFavorite(self):

        currentIndex = self.favoritesComboBox.currentIndex()
        currentText = self.favoritesComboBox.currentText()
        if currentIndex == 0:
            msg = "Cannot delete '%s'." % currentText
        else:
            self.favoritesComboBox.removeItem(currentIndex)

            # delete file from the disk

            deleteFile = getFavoritePathFromBasename(currentText)
            os.remove(deleteFile)

            msg = "Deleted favorite named [%s].\n" \
                "and the favorite file [%s.txt]." \
                % (currentText, currentText)

        env.history.message(msg)
        return

    def saveFavorite(self):

        cmd = greenmsg("Save Favorite File: ")
        env.history.message(greenmsg("Save Favorite File:"))
        current_favorite = self.favoritesComboBox.currentText()
        favfilepath = getFavoritePathFromBasename(current_favorite)

        formats = \
                "Favorite (*.txt);;"\
                "All Files (*.*)"

        directory = self.currentWorkingDirectory
        saveLocation = directory + "/" + current_favorite + ".txt"

        fn = QFileDialog.getSaveFileName(
            self,
            "Save Favorite As",  # caption
            favfilepath,  #where to save
            formats,  # file format options
            QString("Favorite (*.txt)")  # selectedFilter
        )
        if not fn:
            env.history.message(cmd + "Cancelled")

        else:
            dir, fil = os.path.split(str(fn))
            self.setCurrentWorkingDirectory(dir)
            saveFavoriteFile(str(fn), favfilepath)
        return

    def setCurrentWorkingDirectory(self, dir=None):
        if os.path.isdir(dir):
            self.currentWorkingDirectory = dir
            self._setWorkingDirectoryInPrefsDB(dir)
        else:
            self.currentWorkingDirectory = getDefaultWorkingDirectory()

    def _setWorkingDirectoryInPrefsDB(self, workdir=None):

        if not workdir:
            return

        workdir = str(workdir)
        if os.path.isdir(workdir):
            workdir = os.path.normpath(workdir)
            env.prefs[
                workingDirectory_prefs_key] = workdir  # Change pref in prefs db.
        else:
            msg = "[" + workdir + "] is not a directory. Working directory was not changed."
            env.history.message(redmsg(msg))
        return

    def loadFavorite(self):

        # If the file already exists in the favorites folder then the user is
        # given the option of overwriting it or renaming it

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

        directory = self.currentWorkingDirectory
        if directory == '':
            directory = getDefaultWorkingDirectory()

        fname = QFileDialog.getOpenFileName(self, "Choose a file to load",
                                            directory, formats)

        if not fname:
            env.history.message("User cancelled loading file.")
            return

        else:
            dir, fil = os.path.split(str(fname))
            self.setCurrentWorkingDirectory(dir)
            canLoadFile = loadFavoriteFile(fname)

            if canLoadFile == 1:

                #get just the name of the file for loading into the combobox

                favName = os.path.basename(str(fname))
                name = favName[0:len(favName) - 4]
                indexOfDuplicateItem = self.favoritesComboBox.findText(name)

                #duplicate exists in combobox

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

                    if ret == 0:
                        self.favoritesComboBox.removeItem(indexOfDuplicateItem)
                        self.favoritesComboBox.addItem(name)
                        _lastItem = self.favoritesComboBox.count()
                        self.favoritesComboBox.setCurrentIndex(_lastItem - 1)
                        ok2, text = writeProteinDisplayStyleSettingsToFavoritesFile(
                            name)
                        msg = "Overwrote favorite [%s]." % (text)
                        env.history.message(msg)

                    elif ret == 1:
                        # add new item to favorites folder as well as combobox
                        self.addFavorite()

                    else:
                        #reset the display setting values to factory default

                        factoryIndex = self.favoritesComboBox.findText(
                            'Factory default settings')
                        self.favoritesComboBox.setCurrentIndex(factoryIndex)
                        env.prefs.restore_defaults(
                            proteinDisplayStylePrefsList)

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

                    env.history.message(msg)

                self.updateProteinDisplayStyleWidgets()

        return

    def _addWhatsThisText(self):

        from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditDnaDisplayStyle_PropertyManager
        WhatsThis_EditDnaDisplayStyle_PropertyManager(self)

    def _addToolTipText(self):

        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager
        ToolTip_EditProteinDisplayStyle_PropertyManager(self)
class BreakOrJoinStrands_PropertyManager(PM_Dialog, DebugMenuMixin):
    def __init__(self, parentCommand):
        """
        Constructor for the property manager.
        """

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

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

        DebugMenuMixin._init1(self)

        self.showTopRowButtons(PM_DONE_BUTTON | PM_WHATS_THIS_BUTTON)
        return

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

        # DNA Strand arrowhead display options signal-slot connections.

        self._connect_checkboxes_to_global_prefs_keys(isConnect)

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

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

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

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

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

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

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

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

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

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

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

        return

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

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

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

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

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

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

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

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

        return

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

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

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

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

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

        return

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    title = "Edit Protein Display Style"
    pmName = title
    iconPath = "ui/actions/Edit/EditProteinDisplayStyle.png"

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

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

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

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

        DebugMenuMixin._init1(self)

        self.showTopRowButtons(PM_DONE_BUTTON | PM_WHATS_THIS_BUTTON)

        msg = "Modify the protein display settings below."
        self.updateMessage(msg)

    def connect_or_disconnect_signals(self, isConnect=True):

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

        # Favorite buttons signal-slot connections.
        change_connect(self.applyFavoriteButton, SIGNAL("clicked()"), self.applyFavorite)

        change_connect(self.addFavoriteButton, SIGNAL("clicked()"), self.addFavorite)

        change_connect(self.deleteFavoriteButton, SIGNAL("clicked()"), self.deleteFavorite)

        change_connect(self.saveFavoriteButton, SIGNAL("clicked()"), self.saveFavorite)

        change_connect(self.loadFavoriteButton, SIGNAL("clicked()"), self.loadFavorite)

        # Display group box signal slot connections
        change_connect(self.proteinStyleComboBox, SIGNAL("currentIndexChanged(int)"), self.changeProteinDisplayStyle)

        change_connect(self.smoothingCheckBox, SIGNAL("stateChanged(int)"), self.smoothProteinDisplay)
        change_connect(self.scaleComboBox, SIGNAL("currentIndexChanged(int)"), self.changeProteinDisplayScale)
        change_connect(self.splineDoubleSpinBox, SIGNAL("valueChanged(double)"), self.changeProteinSplineValue)
        change_connect(self.scaleFactorDoubleSpinBox, SIGNAL("valueChanged(double)"), self.changeProteinScaleFactor)

        # color groupbox
        change_connect(self.proteinComponentComboBox, SIGNAL("currentIndexChanged(int)"), self.chooseProteinComponent)

        change_connect(
            self.proteinAuxComponentComboBox, SIGNAL("currentIndexChanged(int)"), self.chooseAuxilliaryProteinComponent
        )

        change_connect(self.customColorComboBox, SIGNAL("editingFinished()"), self.chooseCustomColor)

        change_connect(self.auxColorComboBox, SIGNAL("editingFinished()"), self.chooseAuxilliaryColor)

        change_connect(self.discColorCheckBox, SIGNAL("stateChanged(int)"), self.setDiscreteColors)

        change_connect(self.helixColorComboBox, SIGNAL("editingFinished()"), self.chooseHelixColor)

        change_connect(self.strandColorComboBox, SIGNAL("editingFinished()"), self.chooseStrandColor)

        change_connect(self.coilColorComboBox, SIGNAL("editingFinished()"), self.chooseCoilColor)

    # Protein Display methods

    def changeProteinDisplayStyle(self, idx):
        env.prefs[proteinStyle_prefs_key] = idx
        return

    def changeProteinDisplayQuality(self, idx):
        env.prefs[proteinStyleQuality_prefs_key] = idx
        return

    def smoothProteinDisplay(self, state):
        if state == Qt.Checked:
            env.prefs[proteinStyleSmooth_prefs_key] = True
        else:
            env.prefs[proteinStyleSmooth_prefs_key] = False
        return

    def changeProteinDisplayScale(self, idx):
        env.prefs[proteinStyleScaling_prefs_key] = idx
        return

    def changeProteinSplineValue(self, val):
        env.prefs[proteinStyleQuality_prefs_key] = val
        return

    def changeProteinScaleFactor(self, val):
        env.prefs[proteinStyleScaleFactor_prefs_key] = val
        return

    def chooseProteinComponent(self, idx):
        env.prefs[proteinStyleColors_prefs_key] = idx
        return

    def chooseAuxilliaryProteinComponent(self, idx):
        env.prefs[proteinStyleAuxColors_prefs_key] = idx - 1
        return

    def chooseCustomColor(self):
        color = self.customColorComboBox.getColor()
        env.prefs[proteinStyleCustomColor_prefs_key] = color
        return

    def chooseAuxilliaryColor(self):
        color = self.auxColorComboBox.getColor()
        env.prefs[proteinStyleAuxCustomColor_prefs_key] = color
        return

    def chooseHelixColor(self):
        color = self.helixColorComboBox.getColor()
        env.prefs[proteinStyleHelixColor_prefs_key] = color
        return

    def chooseStrandColor(self):
        color = self.strandColorComboBox.getColor()
        env.prefs[proteinStyleStrandColor_prefs_key] = color
        return

    def chooseCoilColor(self):
        color = self.coilColorComboBox.getColor()
        env.prefs[proteinStyleCoilColor_prefs_key] = color
        return

    def setDiscreteColors(self, state):
        if state == Qt.Checked:
            env.prefs[proteinStyleColorsDiscrete_prefs_key] = True
        else:
            env.prefs[proteinStyleColorsDiscrete_prefs_key] = False
        return

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

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

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

        # Not required for Proteins
        # Force the Global Display Style to "DNA Cylinder" so the user
        # can see the display style setting effects on any DNA in the current
        # model. The current global display style will be restored when leaving
        # this command (via self.close()).
        # self.originalDisplayStyle = self.o.getGlobalDisplayStyle()
        # self.o.setGlobalDisplayStyle(diDNACYLINDER)

        # Update all PM widgets, then establish their signal-slot connections.
        # note: It is important to update the widgets *first* since doing
        # it in the reverse order will generate signals when updating
        # the PM widgets (via updateDnaDisplayStyleWidgets()), causing
        # unneccessary repaints of the model view.
        self.updateProteinDisplayStyleWidgets()
        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)

        # Not required for proteins
        # Restore the original global display style.
        # self.o.setGlobalDisplayStyle(self.originalDisplayStyle)

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

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

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

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        # Other info
        # Not only loads the factory default settings but also all the favorite
        # files stored in the ~/Nanorex/Favorites/ProteinDisplayStyle directory

        favoriteChoices = ["Factory default settings"]

        # look for all the favorite files in the favorite folder and add them to
        # the list
        from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir

        _dir = find_or_make_Nanorex_subdir("Favorites/ProteinDisplayStyle")

        for file in os.listdir(_dir):
            fullname = os.path.join(_dir, file)
            if os.path.isfile(fullname):
                if fnmatch.fnmatch(file, "*.txt"):

                    # leave the extension out
                    favoriteChoices.append(file[0 : len(file) - 4])

        self.favoritesComboBox = PM_ComboBox(pmGroupBox, choices=favoriteChoices, spanWidth=True)

        self.favoritesComboBox.setWhatsThis(
            """<b> List of Favorites </b>

            <p>
            Creates a list of favorite Protein display styles. Once favorite
            styles have been added to the list using the Add Favorite button,
            the list will display the chosen favorites.
            To change the current favorite, select a current favorite from
            the list, and push the Apply Favorite button."""
        )

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

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

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

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

        self.favsButtonGroup.buttonGroup.setExclusive(False)

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

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        proteinStyleChoices = [
            "CA trace (wire)",
            "CA trace (cylinders)",
            "CA trace (ball and stick)",
            "Tube",
            "Ladder",
            "Zigzag",
            "Flat ribbon",
            "Solid ribbon",
            "Cartoons",
            "Fancy cartoons",
            "Peptide tiles",
        ]

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

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

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

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

        self.smoothingCheckBox = PM_CheckBox(pmGroupBox, text="Smoothing", setAsDefault=True)

    def _loadGroupBox3(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        colorChoices = [
            "Chunk",
            "Chain",
            "Order",
            "Hydropathy",
            "Polarity",
            "Acidity",
            "Size",
            "Character",
            "Number of contacts",
            "Secondary structure type",
            "Secondary structure order",
            "B-factor",
            "Occupancy",
            "Custom",
        ]

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

        colorList = [orange, yellow, red, magenta, cyan, blue, white, black, gray]

        colorNames = ["Orange(default)", "Yellow", "Red", "Magenta", "Cyan", "Blue", "White", "Black", "Other color..."]

        self.customColorComboBox = PM_ColorComboBox(
            pmGroupBox, colorList=colorList, colorNames=colorNames, label="Custom:", color=orange, setAsDefault=True
        )

        colorChoices1 = [
            "Same as main color",
            "Chunk",
            "Chain",
            "Order",
            "Hydropathy",
            "Polarity",
            "Acidity",
            "Size",
            "Character",
            "Number of contacts",
            "Secondary structure type",
            "Secondary structure order",
            "B-factor",
            "Occupancy",
            "Custom",
        ]

        self.proteinAuxComponentComboBox = PM_ComboBox(
            pmGroupBox, label="Aux:", choices=colorChoices1, setAsDefault=True
        )

        colorListAux = [orange, yellow, red, magenta, cyan, blue, white, black, gray]

        colorNamesAux = [
            "Orange(default)",
            "Yellow",
            "Red",
            "Magenta",
            "Cyan",
            "Blue",
            "White",
            "Black",
            "Other color...",
        ]

        self.auxColorComboBox = PM_ColorComboBox(
            pmGroupBox,
            colorList=colorListAux,
            colorNames=colorNamesAux,
            label="Custom aux:",
            color=gray,
            setAsDefault=True,
        )

        self.discColorCheckBox = PM_CheckBox(pmGroupBox, text="Discretize colors", setAsDefault=True)

        colorListHelix = [red, yellow, gray, magenta, cyan, blue, white, black, orange]

        colorNamesHelix = [
            "Red(default)",
            "Yellow",
            "Gray",
            "Magenta",
            "Cyan",
            "Blue",
            "White",
            "Black",
            "Other color...",
        ]

        self.helixColorComboBox = PM_ColorComboBox(
            pmGroupBox,
            colorList=colorListHelix,
            colorNames=colorNamesHelix,
            label="Helix:",
            color=red,
            setAsDefault=True,
        )

        colorListStrand = [cyan, yellow, gray, magenta, red, blue, white, black, orange]

        colorNamesStrand = [
            "Cyan(default)",
            "Yellow",
            "Gray",
            "Magenta",
            "Red",
            "Blue",
            "White",
            "Black",
            "Other color...",
        ]

        self.strandColorComboBox = PM_ColorComboBox(
            pmGroupBox,
            colorList=colorListStrand,
            colorNames=colorNamesStrand,
            label="Strand:",
            color=cyan,
            setAsDefault=True,
        )

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

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

        return

    def applyFavorite(self):

        # Rules and other info:
        # The user has to press the button related to this method when he loads
        # a previously saved favorite file

        current_favorite = self.favoritesComboBox.currentText()
        if current_favorite == "Factory default settings":
            env.prefs.restore_defaults(proteinDisplayStylePrefsList)
        else:
            favfilepath = getFavoritePathFromBasename(current_favorite)
            loadFavoriteFile(favfilepath)

        self.updateProteinDisplayStyleWidgets()
        return

    def addFavorite(self):

        # Rules and other info:

        # - The new favorite is defined by the current Protein display style

        #  settings.

        # - The user is prompted to type in a name for the new
        #    favorite.
        # - The DNA display style settings are written to a file in a special
        #    directory on the disk
        # (i.e. $HOME/Nanorex/Favorites/ProteinDisplayStyle/$FAV_NAME.txt).
        # - The name of the new favorite is added to the list of favorites in
        #    the combobox, which becomes the current option.

        # Existence of a favorite with the same name is checked in the above
        # mentioned location and if a duplicate exists, then the user can either
        # overwrite and provide a new name.

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

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

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

                # favorite file already exists!

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

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

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

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

        env.history.message(msg)

        return

    def deleteFavorite(self):

        currentIndex = self.favoritesComboBox.currentIndex()
        currentText = self.favoritesComboBox.currentText()
        if currentIndex == 0:
            msg = "Cannot delete '%s'." % currentText
        else:
            self.favoritesComboBox.removeItem(currentIndex)

            # delete file from the disk

            deleteFile = getFavoritePathFromBasename(currentText)
            os.remove(deleteFile)

            msg = "Deleted favorite named [%s].\n" "and the favorite file [%s.txt]." % (currentText, currentText)

        env.history.message(msg)
        return

    def saveFavorite(self):

        cmd = greenmsg("Save Favorite File: ")
        env.history.message(greenmsg("Save Favorite File:"))
        current_favorite = self.favoritesComboBox.currentText()
        favfilepath = getFavoritePathFromBasename(current_favorite)

        formats = "Favorite (*.txt);;" "All Files (*.*)"

        directory = self.currentWorkingDirectory
        saveLocation = directory + "/" + current_favorite + ".txt"

        fn = QFileDialog.getSaveFileName(
            self,
            "Save Favorite As",  # caption
            favfilepath,  # where to save
            formats,  # file format options
            QString("Favorite (*.txt)"),  # selectedFilter
        )
        if not fn:
            env.history.message(cmd + "Cancelled")

        else:
            dir, fil = os.path.split(str(fn))
            self.setCurrentWorkingDirectory(dir)
            saveFavoriteFile(str(fn), favfilepath)
        return

    def setCurrentWorkingDirectory(self, dir=None):
        if os.path.isdir(dir):
            self.currentWorkingDirectory = dir
            self._setWorkingDirectoryInPrefsDB(dir)
        else:
            self.currentWorkingDirectory = getDefaultWorkingDirectory()

    def _setWorkingDirectoryInPrefsDB(self, workdir=None):

        if not workdir:
            return

        workdir = str(workdir)
        if os.path.isdir(workdir):
            workdir = os.path.normpath(workdir)
            env.prefs[workingDirectory_prefs_key] = workdir  # Change pref in prefs db.
        else:
            msg = "[" + workdir + "] is not a directory. Working directory was not changed."
            env.history.message(redmsg(msg))
        return

    def loadFavorite(self):

        # If the file already exists in the favorites folder then the user is
        # given the option of overwriting it or renaming it

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

        directory = self.currentWorkingDirectory
        if directory == "":
            directory = getDefaultWorkingDirectory()

        fname = QFileDialog.getOpenFileName(self, "Choose a file to load", directory, formats)

        if not fname:
            env.history.message("User cancelled loading file.")
            return

        else:
            dir, fil = os.path.split(str(fname))
            self.setCurrentWorkingDirectory(dir)
            canLoadFile = loadFavoriteFile(fname)

            if canLoadFile == 1:

                # get just the name of the file for loading into the combobox

                favName = os.path.basename(str(fname))
                name = favName[0 : len(favName) - 4]
                indexOfDuplicateItem = self.favoritesComboBox.findText(name)

                # duplicate exists in combobox

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

                    if ret == 0:
                        self.favoritesComboBox.removeItem(indexOfDuplicateItem)
                        self.favoritesComboBox.addItem(name)
                        _lastItem = self.favoritesComboBox.count()
                        self.favoritesComboBox.setCurrentIndex(_lastItem - 1)
                        ok2, text = writeProteinDisplayStyleSettingsToFavoritesFile(name)
                        msg = "Overwrote favorite [%s]." % (text)
                        env.history.message(msg)

                    elif ret == 1:
                        # add new item to favorites folder as well as combobox
                        self.addFavorite()

                    else:
                        # reset the display setting values to factory default

                        factoryIndex = self.favoritesComboBox.findText("Factory default settings")
                        self.favoritesComboBox.setCurrentIndex(factoryIndex)
                        env.prefs.restore_defaults(proteinDisplayStylePrefsList)

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

                    env.history.message(msg)

                self.updateProteinDisplayStyleWidgets()

        return

    def _addWhatsThisText(self):

        from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditDnaDisplayStyle_PropertyManager

        WhatsThis_EditDnaDisplayStyle_PropertyManager(self)

    def _addToolTipText(self):

        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager

        ToolTip_EditProteinDisplayStyle_PropertyManager(self)