class Ui_MovePropertyManager(Command_PropertyManager):
    
       
    # The title that appears in the Property Manager header        
    title = "Move"
    # The name of this Property Manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    # The relative path to the PNG file that appears in the header
    iconPath = "ui/actions/Properties Manager/Translate_Components.png"
    
    # The title(s) that appear in the property manager header.
    # (these are changed depending on the active group box) 
    translateTitle = "Translate"
    rotateTitle = "Rotate"

    # The full path to PNG file(s) that appears in the header.
    translateIconPath = "ui/actions/Properties Manager/Translate_Components.png"
    rotateIconPath = "ui/actions/Properties Manager/Rotate_Components.png"
    
    def __init__(self, command):  
        _superclass.__init__(self, command)       
        self.showTopRowButtons(PM_DONE_BUTTON | PM_WHATS_THIS_BUTTON)
    
    def _addGroupBoxes(self):
        """
        Add groupboxes to the Property Manager dialog. 
        """
        
        self.translateGroupBox = PM_GroupBox( self, 
                                              title = "Translate",
                                              connectTitleButton = False)
        self.translateGroupBox.titleButton.setShortcut('T')
        self._loadTranslateGroupBox(self.translateGroupBox)
        
        self.rotateGroupBox = PM_GroupBox( self, 
                                           title = "Rotate",
                                           connectTitleButton = False)
        self.rotateGroupBox.titleButton.setShortcut('R')
        self._loadRotateGroupBox(self.rotateGroupBox)
        
        self.translateGroupBox.collapse()
        self.rotateGroupBox.collapse()
            
    # == Begin Translate Group Box =====================
    
    def _loadTranslateGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Translate group box.
        @param inPmGroupBox: The Translate group box in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        
        translateChoices = [ "Free Drag", 
                             "By Delta XYZ", 
                             "To XYZ Position" ]
        
        self.translateComboBox = \
            PM_ComboBox( inPmGroupBox,
                         label        = '', 
                         choices      = translateChoices, 
                         index        = 0, 
                         setAsDefault = False,
                         spanWidth    = True )
        
        self.freeDragTranslateGroupBox = PM_GroupBox( inPmGroupBox )
        self._loadFreeDragTranslateGroupBox(self.freeDragTranslateGroupBox)
                
        self.byDeltaGroupBox = PM_GroupBox( inPmGroupBox )
        self._loadByDeltaGroupBox(self.byDeltaGroupBox)
        
        self.toPositionGroupBox = PM_GroupBox( inPmGroupBox )
        self._loadToPositionGroupBox(self.toPositionGroupBox)
        
        self.updateTranslateGroupBoxes(0)
    
    def _loadFreeDragTranslateGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Free Drag Translate group box, which is present 
        within the Translate groupbox.
        @param inPmGroupBox: The Free Drag Translate group box in the Translate 
                             group box. 
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        # Button list to create a toolbutton row.
        # Format: 
        # - buttonId, 
        # - buttonText , 
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        
         
        BUTTON_LIST = [ 
            ( "QToolButton", 1,  "MOVEDEFAULT", 
              "ui/actions/Properties Manager/Move_Free.png", "", "F", 0),
            ( "QToolButton", 2,  "TRANSX", 
              "ui/actions/Properties Manager/TranslateX.png", "", "X", 1),
            ( "QToolButton", 3,  "TRANSY",  
              "ui/actions/Properties Manager/TranslateY.png", "", "Y", 2),
            ( "QToolButton", 4,  "TRANSZ",  
              "ui/actions/Properties Manager/TranslateZ.png", "", "Z", 3),
            ( "QToolButton", 5,  "ROT_TRANS_ALONG_AXIS",  
              "ui/actions/Properties Manager/translate+rotate-A.png", "", \
              "A", 4)
                        
            ]
            
        self.freeDragTranslateButtonGroup = \
            PM_ToolButtonRow( inPmGroupBox, 
                               title        = "",
                               buttonList   = BUTTON_LIST,
                               checkedId    = 1,
                               setAsDefault = True,
                               )
        self.transFreeButton =self.freeDragTranslateButtonGroup.getButtonById(1)
        self.transXButton = self.freeDragTranslateButtonGroup.getButtonById(2)
        self.transYButton = self.freeDragTranslateButtonGroup.getButtonById(3)
        self.transZButton = self.freeDragTranslateButtonGroup.getButtonById(4)
        self.transAlongAxisButton = \
            self.freeDragTranslateButtonGroup.getButtonById(5)
        
        self.moveFromToButton = PM_ToolButton(
                    inPmGroupBox, 
                    text = "Translate from/to",
                    iconPath  = "ui/actions/Properties Manager"\
                    "/Translate_Components.png",
                    spanWidth = True
                    
                    )
        self.moveFromToButton.setCheckable(True)
        self.moveFromToButton.setAutoRaise(True)
        self.moveFromToButton.setToolButtonStyle(
            Qt.ToolButtonTextBesideIcon)
        
        
        self.startCoordLineEdit = PM_LineEdit( 
            inPmGroupBox, 
            label        = "ui/actions/Properties Manager"\
                    "/Move_Start_Point.png",
            text         = "Define 'from' and 'to' points",
            setAsDefault = False,
            )
        self.startCoordLineEdit.setReadOnly(True)
        self.startCoordLineEdit.setEnabled(False)
        
    def _loadByDeltaGroupBox(self, inPmGroupBox):
        """
        Load widgets in the translate By Delta group box, which is present 
        within the Translate groupbox.
        @param inPmGroupBox: The Translate By Delta group box in the translate 
                             group box. 
        @type  inPmGroupBox: L{PM_GroupBox}
        """

        self.moveDeltaXSpinBox = \
            PM_DoubleSpinBox( 
                inPmGroupBox, 
                label        = "ui/actions/Properties Manager/Delta_X.png",
                value        = 0.0, 
                setAsDefault = True,
                minimum      = -100.0, 
                maximum      =  100.0, 
                singleStep   = 1.0, 
                decimals     = 3, 
                suffix       = ' Angstroms',
                spanWidth    = False )
        
        self.moveDeltaYSpinBox = \
            PM_DoubleSpinBox( 
                inPmGroupBox, 
                label        = "ui/actions/Properties Manager/Delta_Y.png",
                value        = 0.0, 
                setAsDefault = True,
                minimum      = -100.0, 
                maximum      =  100.0, 
                singleStep   = 1.0, 
                decimals     = 3, 
                suffix       = ' Angstroms',
                spanWidth    = False )
        
        self.moveDeltaZSpinBox = \
            PM_DoubleSpinBox( 
                inPmGroupBox, 
                label        = "ui/actions/Properties Manager/Delta_Z.png",
                value        = 0.0, 
                setAsDefault = True,
                minimum      = -100.0, 
                maximum      =  100.0, 
                singleStep   = 1.0, 
                decimals     = 3, 
                suffix       = ' Angstroms',
                spanWidth    = False )
        
        DELTA_BUTTONS = [
                        ("QToolButton",1,  "Delta Plus", 
                         "ui/actions/Properties Manager/Move_Delta_Plus.png", 
                         "", "+", 0 ),
            
                        ( "QToolButton", 2,  "Delta Minus",  
                          "ui/actions/Properties Manager/Move_Delta_Minus.png", 
                          "", "-", 1 )
                        ]
        
        self.translateDeltaButtonRow = \
            PM_ToolButtonRow( inPmGroupBox, 
                              title        = "",
                              buttonList   = DELTA_BUTTONS,
                              label        = 'Translate:',
                              isAutoRaise  =  True,
                              isCheckable  =  False                           
                            )
        self.transDeltaPlusButton = \
            self.translateDeltaButtonRow.getButtonById(1)
        self.transDeltaMinusButton = \
            self.translateDeltaButtonRow.getButtonById(2)
        
            
    def _loadToPositionGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Translate To a given Position group box, which is 
        present within the Translate groupbox.
        @param inPmGroupBox: Translate To Position group box in the Translate 
                             group box.
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        
        self.toPositionspinboxes = PM_CoordinateSpinBoxes(inPmGroupBox)
        
        self.moveXSpinBox = self.toPositionspinboxes.xSpinBox
        self.moveYSpinBox = self.toPositionspinboxes.ySpinBox
        self.moveZSpinBox = self.toPositionspinboxes.zSpinBox
        
        
        self.moveAbsoluteButton = \
            PM_PushButton( inPmGroupBox,
                           label     = "",
                           text      = "Move Selection",
                           spanWidth = True )
            
    # == Begin Rotate Group Box =====================
    def _loadRotateGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Rotate group box, 
        @param inPmGroupBox: The Rotate GroupBox in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        
        rotateChoices = [ "Free Drag", "By Specified Angle"]
        
        self.rotateComboBox = \
            PM_ComboBox( inPmGroupBox,
                         label        = '', 
                         choices      = rotateChoices, 
                         index        = 0, 
                         setAsDefault = False,
                         spanWidth    = True )
        
        self.rotateAsUnitCB = \
            PM_CheckBox( inPmGroupBox,
                         text         = 'Rotate as a unit' ,
                         widgetColumn = 0,
                         state        = Qt.Checked )
        
               
        self.freeDragRotateGroupBox = PM_GroupBox( inPmGroupBox )
        self._loadFreeDragRotateGroupBox(self.freeDragRotateGroupBox)
        
        self.bySpecifiedAngleGroupBox = PM_GroupBox( inPmGroupBox )
        self._loadBySpecifiedAngleGroupBox(self.bySpecifiedAngleGroupBox)
        
        self.updateRotateGroupBoxes(0)    
        
    def _loadFreeDragRotateGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Free Drag Rotate group box, which is 
        present within the Rotate groupbox.
        @param inPmGroupBox: The Free Drag Rotate group box in the Rotate 
                             group box.
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        # Button list to create a toolbutton row.
        # Format: 
        # - buttonId, 
        # - buttonText , 
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        
        BUTTON_LIST = [ 
            ( "QToolButton", 1,  "ROTATEDEFAULT", 
              "ui/actions/Properties Manager/Rotate_Free.png", "", "F", 0 ),
            
            ( "QToolButton", 2,  "ROTATEX", 
              "ui/actions/Properties Manager/RotateX.png", "", "X", 1 ),
            
            ( "QToolButton", 3,  "ROTATEY",  
              "ui/actions/Properties Manager/RotateY.png", "", "Y", 2 ),
            
            ( "QToolButton", 4,  "ROTATEZ",  
              "ui/actions/Properties Manager/RotateZ.png", "", "Z", 3 ),
            
            ( "QToolButton", 5,  "ROT_TRANS_ALONG_AXIS",  
              "ui/actions/Properties Manager/translate+rotate-A.png", "", \
              "A", 4 )
                        
            ]
            
        self.freeDragRotateButtonGroup = \
            PM_ToolButtonRow( inPmGroupBox, 
                               title        = "",
                               buttonList   = BUTTON_LIST,
                               spanWidth = True,
                               checkedId    = 1,
                               setAsDefault = True,
                            )
                
        self.rotateFreeButton = self.freeDragRotateButtonGroup.getButtonById(1)
        self.rotateXButton    = self.freeDragRotateButtonGroup.getButtonById(2)
        self.rotateYButton    = self.freeDragRotateButtonGroup.getButtonById(3)
        self.rotateZButton    = self.freeDragRotateButtonGroup.getButtonById(4)
        self.rotAlongAxisButton = \
            self.freeDragRotateButtonGroup.getButtonById(5)
        
        inPmGroupBox.setStyleSheet(
            self.freeDragRotateButtonGroup._getStyleSheet())
                
        X_ROW_LABELS = [("QLabel", "Delta Theta X:", 0),
                        ("QLabel", "", 1),
                        ("QLabel", "0.00", 2),
                        ("QLabel", "Degrees", 3)]
        
        Y_ROW_LABELS = [("QLabel", "Delta Theta Y:", 0),
                        ("QLabel", "", 1),
                        ("QLabel", "0.00", 2),
                        ("QLabel", "Degrees", 3)]
        
        Z_ROW_LABELS = [("QLabel", "Delta Theta Z:", 0),
                        ("QLabel", "", 1),
                        ("QLabel", "0.00", 2),
                        ("QLabel", "Degrees", 3)]
        
        self.rotateXLabelRow = PM_LabelRow( inPmGroupBox,
                                            title = "",
                                            labelList = X_ROW_LABELS )  
        self.deltaThetaX_lbl = self.rotateXLabelRow.labels[2]
                                           
        self.rotateYLabelRow = PM_LabelRow( inPmGroupBox,
                                            title = "",
                                            labelList = Y_ROW_LABELS )
        self.deltaThetaY_lbl = self.rotateYLabelRow.labels[2]
                                          
        self.rotateZLabelRow = PM_LabelRow( inPmGroupBox,
                                            title = "",
                                            labelList = Z_ROW_LABELS )  
        self.deltaThetaZ_lbl = self.rotateZLabelRow.labels[2]    
        
        self.rotateAboutPointButton = PM_ToolButton(
                    inPmGroupBox, 
                    text = "Rotate selection about a point",
                    iconPath  = "ui/actions/Properties Manager"\
                    "/Rotate_Components.png",
                    spanWidth = True                    
                    )
        self.rotateAboutPointButton.setCheckable(True)
        self.rotateAboutPointButton.setAutoRaise(True)
        self.rotateAboutPointButton.setToolButtonStyle(
            Qt.ToolButtonTextBesideIcon)
        
        
        self.rotateStartCoordLineEdit = PM_LineEdit( 
            inPmGroupBox, 
            label        = "ui/actions/Properties Manager"\
                    "/Move_Start_Point.png",
            text         = "Define 3 points",
            setAsDefault = False,
            )
        self.rotateStartCoordLineEdit.setReadOnly(True)
        self.rotateStartCoordLineEdit.setEnabled(False)
            
            
    def _loadBySpecifiedAngleGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Rotate By Specified Angle group box, which is 
        present within the Rotate groupbox.
        @param inPmGroupBox: Rotate By Specified Angle group box in the Rotate 
                             group box.
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        # Button list to create a toolbutton row.
        # Format: 
        # - buttonId, 
        # - buttonText , 
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        
        BUTTON_LIST = [ 
            ( "QToolButton", 1,  "ROTATEX", 
              "ui/actions/Properties Manager/RotateX.png", 
              "Rotate about X axis", "X", 0 ),
            
            ( "QToolButton", 2,  "ROTATEY",  
              "ui/actions/Properties Manager/RotateY.png", 
              "Rotate about Y axis", "Y", 1 ),
            
            ( "QToolButton", 3,  "ROTATEZ",  
              "ui/actions/Properties Manager/RotateZ.png", 
              "Rotate about Z axis","Z", 2 ),
            ]
        
        
        
        self.rotateAroundAxisButtonRow = \
            PM_ToolButtonRow( inPmGroupBox, 
                              title        = "",
                              buttonList   = BUTTON_LIST,
                              alignment    = 'Right',
                              label        = 'Rotate Around:'
                            )
        self.rotXaxisButton = \
            self.rotateAroundAxisButtonRow.getButtonById(1)
        
        self.rotYaxisButton = \
            self.rotateAroundAxisButtonRow.getButtonById(2)
        
        self.rotZaxisButton = \
            self.rotateAroundAxisButtonRow.getButtonById(3)
        
        

        self.rotateThetaSpinBox = \
            PM_DoubleSpinBox(inPmGroupBox,
                             label        = "Rotate By:",
                             value        = 0.0, 
                             setAsDefault = True,
                             minimum      = 0, 
                             maximum      = 360.0,
                             singleStep   = 1.0, 
                             decimals     = 2, 
                             suffix       = ' Degrees')
        
        
        THETA_BUTTONS = [ 
            ( "QToolButton", 1,  "Theta Plus", 
              "ui/actions/Properties Manager/Move_Theta_Plus.png", "", "+", 0 ),
            
            ( "QToolButton", 2,  "Theta Minus",  
              "ui/actions/Properties Manager/Move_Theta_Minus.png", "", "-", 1 )
            ]
        
        self.rotateThetaButtonRow = \
            PM_ToolButtonRow( inPmGroupBox, 
                              title        = "",
                              buttonList   = THETA_BUTTONS,
                              label        = 'Direction:',
                              isAutoRaise  =  True,
                              isCheckable  =  False                           
                            )
        self.rotateThetaPlusButton =  self.rotateThetaButtonRow.getButtonById(1)
        self.rotateThetaMinusButton = self.rotateThetaButtonRow.getButtonById(2)
    
    # == End Rotate Group Box =====================
        
    # == Slots for Translate group box
    def _hideAllTranslateGroupBoxes(self):
        """
        Hides all Translate group boxes.
        """
        self.toPositionGroupBox.hide()
        self.byDeltaGroupBox.hide()
        self.freeDragTranslateGroupBox.hide()
            
    def updateTranslateGroupBoxes(self, id):
        """
        Update the translate group boxes displayed based on the translate
        option selected.
        @param id: Integer value corresponding to the combobox item in the 
                   Translate group box. 
        @type  id: int
        """
        self._hideAllTranslateGroupBoxes()
        
        if id is 0:
            self.freeDragTranslateGroupBox.show()
                               
        if id is 1:
            self.byDeltaGroupBox.show()                    
        if id is 2:
            self.toPositionGroupBox.show()
           
        self.updateMessage()
    
    def changeMoveOption(self, button):
        """
        Subclasses should reimplement this method.
        
        @param button: QToolButton that decides the type of translate operation 
        to be set.
        @type  button: QToolButton 
                       L{http://doc.trolltech.com/4.2/qtoolbutton.html}
        @see: B{MovePropertyManager.changeMoveOption} which overrides this
              method
        """
        pass
    
    # == Slots for Rotate group box
    def updateRotateGroupBoxes(self, id):
        """
        Update the translate group boxes displayed based on the translate
        option selected.
        @param id: Integer value corresponding to the combobox item in the 
                   Rotate group box. 
        @type  id: int
        """
        if id is 0:
            self.bySpecifiedAngleGroupBox.hide()
            self.freeDragRotateGroupBox.show()   
        if id is 1:
            self.freeDragRotateGroupBox.hide()
            self.bySpecifiedAngleGroupBox.show()
            
        self.updateMessage()
            
    def changeRotateOption(self, button):
        """
        Subclasses should reimplement this method. 
        
        @param button: QToolButton that decides the type of rotate operation 
        to be set.
        @type  button: QToolButton 
                       L{http://doc.trolltech.com/4.2/qtoolbutton.html}
        @see: B{MovePropertyManage.changeRotateOption} which overrides this 
             method
        """
        pass
    
    def _addWhatsThisText(self):
        """
        What's This text for some of the widgets in this Property Manager.  

        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_MovePropertyManager
        whatsThis_MovePropertyManager(self)
        
    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.  
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_MovePropertyManager
        ToolTip_MovePropertyManager(self)
class Ui_BuildCrystal_PropertyManager(Command_PropertyManager):
    """
    The Ui_BuildCrystal_PropertyManager class defines UI elements for the Property
    Manager of the B{Crystal mode}.

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

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

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

    # <title> - the title that appears in the property manager header.
    title = "Build Crystal"
    # <iconPath> - full path to PNG file that appears in the header.
    # The name of this Property Manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    iconPath = "ui/actions/Tools/Build Structures/Build Crystal.png"

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

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


        _superclass.__init__(self, command)

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


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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


    def _loadAdvancedOptionsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Advanced Options group box.
        @param inPmGroupBox: The Advanced Options box in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        self.snapGridCheckBox = \
            PM_CheckBox(inPmGroupBox,
                        text = "Snap to grid",
                        state = Qt.Checked
                        )
        tooltip = "Snap selection point to a nearest cell grid point."
        self.snapGridCheckBox.setToolTip(tooltip)

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

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

        displayChoices = ['Tubes', 'Spheres']

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


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


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

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

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

    def _addToolTipText(self):
        """
        What's Tool Tip text for widgets in this Property Manager.
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_CookiePropertyManager
        ToolTip_CookiePropertyManager(self)
    def _loadByDeltaGroupBox(self, inPmGroupBox):
        """
        Load widgets in the translate By Delta group box, which is present 
        within the Translate groupbox.
        @param inPmGroupBox: The Translate By Delta group box in the translate 
                             group box. 
        @type  inPmGroupBox: L{PM_GroupBox}
        """

        self.moveDeltaXSpinBox = \
            PM_DoubleSpinBox( 
                inPmGroupBox, 
                label        = "ui/actions/Properties Manager/Delta_X.png",
                value        = 0.0, 
                setAsDefault = True,
                minimum      = -100.0, 
                maximum      =  100.0, 
                singleStep   = 1.0, 
                decimals     = 3, 
                suffix       = ' Angstroms',
                spanWidth    = False )
        
        self.moveDeltaYSpinBox = \
            PM_DoubleSpinBox( 
                inPmGroupBox, 
                label        = "ui/actions/Properties Manager/Delta_Y.png",
                value        = 0.0, 
                setAsDefault = True,
                minimum      = -100.0, 
                maximum      =  100.0, 
                singleStep   = 1.0, 
                decimals     = 3, 
                suffix       = ' Angstroms',
                spanWidth    = False )
        
        self.moveDeltaZSpinBox = \
            PM_DoubleSpinBox( 
                inPmGroupBox, 
                label        = "ui/actions/Properties Manager/Delta_Z.png",
                value        = 0.0, 
                setAsDefault = True,
                minimum      = -100.0, 
                maximum      =  100.0, 
                singleStep   = 1.0, 
                decimals     = 3, 
                suffix       = ' Angstroms',
                spanWidth    = False )
        
        DELTA_BUTTONS = [
                        ("QToolButton",1,  "Delta Plus", 
                         "ui/actions/Properties Manager/Move_Delta_Plus.png", 
                         "", "+", 0 ),
            
                        ( "QToolButton", 2,  "Delta Minus",  
                          "ui/actions/Properties Manager/Move_Delta_Minus.png", 
                          "", "-", 1 )
                        ]
        
        self.translateDeltaButtonRow = \
            PM_ToolButtonRow( inPmGroupBox, 
                              title        = "",
                              buttonList   = DELTA_BUTTONS,
                              label        = 'Translate:',
                              isAutoRaise  =  True,
                              isCheckable  =  False                           
                            )
        self.transDeltaPlusButton = \
            self.translateDeltaButtonRow.getButtonById(1)
        self.transDeltaMinusButton = \
            self.translateDeltaButtonRow.getButtonById(2)
    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/DnaDisplayStyle 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/ColorScheme')


        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)

        # 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/ApplyColorSchemeFavorite.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)
Example #5
0
    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 the image group box.

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

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

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

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

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

        self.imageChangeButtonGroup.buttonGroup.setExclusive(False)

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

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

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

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

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

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

        self.heightfieldDisplayCheckBox.setEnabled(False)
        self.heightfieldHQDisplayCheckBox.setEnabled(False)
        self.heightfieldTextureCheckBox.setEnabled(False)
        self.vScaleSpinBox.setEnabled(False)
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        # Other info
        # Not only loads the factory default settings but also all the favorite
        # files stored in the ~/Nanorex/Favorites/DnaDisplayStyle 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/DnaDisplayStyle')


        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 DNA 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/ApplyFavorite.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)
Example #8
0
 def _loadFreeDragRotateGroupBox(self, inPmGroupBox):
     """
     Load widgets in the Free Drag Rotate group box, which is 
     present within the Rotate groupbox.
     @param inPmGroupBox: The Free Drag Rotate group box in the Rotate 
                          group box.
     @type  inPmGroupBox: L{PM_GroupBox}
     """
     # Button list to create a toolbutton row.
     # Format: 
     # - buttonId, 
     # - buttonText , 
     # - iconPath
     # - tooltip
     # - shortcut
     # - column
     
     BUTTON_LIST = [ 
         ( "QToolButton", 1,  "ROTATEDEFAULT", 
           "ui/actions/Properties Manager/Rotate_Free.png", "", "F", 0 ),
         
         ( "QToolButton", 2,  "ROTATEX", 
           "ui/actions/Properties Manager/RotateX.png", "", "X", 1 ),
         
         ( "QToolButton", 3,  "ROTATEY",  
           "ui/actions/Properties Manager/RotateY.png", "", "Y", 2 ),
         
         ( "QToolButton", 4,  "ROTATEZ",  
           "ui/actions/Properties Manager/RotateZ.png", "", "Z", 3 ),
         
         ( "QToolButton", 5,  "ROT_TRANS_ALONG_AXIS",  
           "ui/actions/Properties Manager/translate+rotate-A.png", "", \
           "A", 4 )
                     
         ]
         
     self.freeDragRotateButtonGroup = \
         PM_ToolButtonRow( inPmGroupBox, 
                            title        = "",
                            buttonList   = BUTTON_LIST,
                            spanWidth = True,
                            checkedId    = 1,
                            setAsDefault = True,
                         )
             
     self.rotateFreeButton = self.freeDragRotateButtonGroup.getButtonById(1)
     self.rotateXButton    = self.freeDragRotateButtonGroup.getButtonById(2)
     self.rotateYButton    = self.freeDragRotateButtonGroup.getButtonById(3)
     self.rotateZButton    = self.freeDragRotateButtonGroup.getButtonById(4)
     self.rotAlongAxisButton = \
         self.freeDragRotateButtonGroup.getButtonById(5)
     
     inPmGroupBox.setStyleSheet(
         self.freeDragRotateButtonGroup._getStyleSheet())
             
     X_ROW_LABELS = [("QLabel", "Delta Theta X:", 0),
                     ("QLabel", "", 1),
                     ("QLabel", "0.00", 2),
                     ("QLabel", "Degrees", 3)]
     
     Y_ROW_LABELS = [("QLabel", "Delta Theta Y:", 0),
                     ("QLabel", "", 1),
                     ("QLabel", "0.00", 2),
                     ("QLabel", "Degrees", 3)]
     
     Z_ROW_LABELS = [("QLabel", "Delta Theta Z:", 0),
                     ("QLabel", "", 1),
                     ("QLabel", "0.00", 2),
                     ("QLabel", "Degrees", 3)]
     
     self.rotateXLabelRow = PM_LabelRow( inPmGroupBox,
                                         title = "",
                                         labelList = X_ROW_LABELS )  
     self.deltaThetaX_lbl = self.rotateXLabelRow.labels[2]
                                        
     self.rotateYLabelRow = PM_LabelRow( inPmGroupBox,
                                         title = "",
                                         labelList = Y_ROW_LABELS )
     self.deltaThetaY_lbl = self.rotateYLabelRow.labels[2]
                                       
     self.rotateZLabelRow = PM_LabelRow( inPmGroupBox,
                                         title = "",
                                         labelList = Z_ROW_LABELS )  
     self.deltaThetaZ_lbl = self.rotateZLabelRow.labels[2]    
     
     self.rotateAboutPointButton = PM_ToolButton(
                 inPmGroupBox, 
                 text = "Rotate selection about a point",
                 iconPath  = "ui/actions/Properties Manager"\
                 "/Rotate_Components.png",
                 spanWidth = True                    
                 )
     self.rotateAboutPointButton.setCheckable(True)
     self.rotateAboutPointButton.setAutoRaise(True)
     self.rotateAboutPointButton.setToolButtonStyle(
         Qt.ToolButtonTextBesideIcon)
     
     
     self.rotateStartCoordLineEdit = PM_LineEdit( 
         inPmGroupBox, 
         label        = "ui/actions/Properties Manager"\
                 "/Move_Start_Point.png",
         text         = "Define start point from 3D workspace",
         setAsDefault = False,
         )
     self.rotateStartCoordLineEdit.setReadOnly(True)
     self.rotateStartCoordLineEdit.setEnabled(False)
Example #9
0
    def _loadBySpecifiedAngleGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Rotate By Specified Angle group box, which is 
        present within the Rotate groupbox.
        @param inPmGroupBox: Rotate By Specified Angle group box in the Rotate 
                             group box.
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        # Button list to create a toolbutton row.
        # Format: 
        # - buttonId, 
        # - buttonText , 
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        
        BUTTON_LIST = [ 
            ( "QToolButton", 1,  "ROTATEX", 
              "ui/actions/Properties Manager/RotateX.png", 
              "Rotate about X axis", "X", 0 ),
            
            ( "QToolButton", 2,  "ROTATEY",  
              "ui/actions/Properties Manager/RotateY.png", 
              "Rotate about Y axis", "Y", 1 ),
            
            ( "QToolButton", 3,  "ROTATEZ",  
              "ui/actions/Properties Manager/RotateZ.png", 
              "Rotate about Z axis","Z", 2 ),
            ]
        
        
        
        self.rotateAroundAxisButtonRow = \
            PM_ToolButtonRow( inPmGroupBox, 
                              title        = "",
                              buttonList   = BUTTON_LIST,
                              alignment    = 'Right',
                              label        = 'Rotate Around:'
                            )
        self.rotXaxisButton = \
            self.rotateAroundAxisButtonRow.getButtonById(1)
        
        self.rotYaxisButton = \
            self.rotateAroundAxisButtonRow.getButtonById(2)
        
        self.rotZaxisButton = \
            self.rotateAroundAxisButtonRow.getButtonById(3)
        
        

        self.rotateThetaSpinBox = \
            PM_DoubleSpinBox(inPmGroupBox,
                             label        = "Rotate By:",
                             value        = 0.0, 
                             setAsDefault = True,
                             minimum      = 0, 
                             maximum      = 360.0,
                             singleStep   = 1.0, 
                             decimals     = 2, 
                             suffix       = ' Degrees')
        
        
        THETA_BUTTONS = [ 
            ( "QToolButton", 1,  "Theta Plus", 
              "ui/actions/Properties Manager/Move_Theta_Plus.png", "", "+", 0 ),
            
            ( "QToolButton", 2,  "Theta Minus",  
              "ui/actions/Properties Manager/Move_Theta_Minus.png", "", "-", 1 )
            ]
        
        self.rotateThetaButtonRow = \
            PM_ToolButtonRow( inPmGroupBox, 
                              title        = "",
                              buttonList   = THETA_BUTTONS,
                              label        = 'Direction:',
                              isAutoRaise  =  True,
                              isCheckable  =  False                           
                            )
        self.rotateThetaPlusButton =  self.rotateThetaButtonRow.getButtonById(1)
        self.rotateThetaMinusButton = self.rotateThetaButtonRow.getButtonById(2)
Example #10
0
    def _loadByDeltaGroupBox(self, inPmGroupBox):
        """
        Load widgets in the translate By Delta group box, which is present 
        within the Translate groupbox.
        @param inPmGroupBox: The Translate By Delta group box in the translate 
                             group box. 
        @type  inPmGroupBox: L{PM_GroupBox}
        """

        self.moveDeltaXSpinBox = \
            PM_DoubleSpinBox( 
                inPmGroupBox, 
                label        = "ui/actions/Properties Manager/Delta_X.png",
                value        = 0.0, 
                setAsDefault = True,
                minimum      = -100.0, 
                maximum      =  100.0, 
                singleStep   = 1.0, 
                decimals     = 3, 
                suffix       = ' Angstroms',
                spanWidth    = False )
        
        self.moveDeltaYSpinBox = \
            PM_DoubleSpinBox( 
                inPmGroupBox, 
                label        = "ui/actions/Properties Manager/Delta_Y.png",
                value        = 0.0, 
                setAsDefault = True,
                minimum      = -100.0, 
                maximum      =  100.0, 
                singleStep   = 1.0, 
                decimals     = 3, 
                suffix       = ' Angstroms',
                spanWidth    = False )
        
        self.moveDeltaZSpinBox = \
            PM_DoubleSpinBox( 
                inPmGroupBox, 
                label        = "ui/actions/Properties Manager/Delta_Z.png",
                value        = 0.0, 
                setAsDefault = True,
                minimum      = -100.0, 
                maximum      =  100.0, 
                singleStep   = 1.0, 
                decimals     = 3, 
                suffix       = ' Angstroms',
                spanWidth    = False )
        
        DELTA_BUTTONS = [
                        ("QToolButton",1,  "Delta Plus", 
                         "ui/actions/Properties Manager/Move_Delta_Plus.png", 
                         "", "+", 0 ),
            
                        ( "QToolButton", 2,  "Delta Minus",  
                          "ui/actions/Properties Manager/Move_Delta_Minus.png", 
                          "", "-", 1 )
                        ]
        
        self.translateDeltaButtonRow = \
            PM_ToolButtonRow( inPmGroupBox, 
                              title        = "",
                              buttonList   = DELTA_BUTTONS,
                              label        = 'Translate:',
                              isAutoRaise  =  True,
                              isCheckable  =  False                           
                            )
        self.transDeltaPlusButton = \
            self.translateDeltaButtonRow.getButtonById(1)
        self.transDeltaMinusButton = \
            self.translateDeltaButtonRow.getButtonById(2)
Example #11
0
class Ui_MovePropertyManager( PM_Dialog ):
    
       
    # The title that appears in the Property Manager header        
    title = "Move"
    # The name of this Property Manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    # The relative path to the PNG file that appears in the header
    iconPath = "ui/actions/Properties Manager/Translate_Components.png"
    
    # The title(s) that appear in the property manager header.
    # (these are changed depending on the active group box) 
    translateTitle = "Translate"
    rotateTitle = "Rotate"

    # The full path to PNG file(s) that appears in the header.
    translateIconPath = "ui/actions/Properties Manager/Translate_Components.png"
    rotateIconPath = "ui/actions/Properties Manager/Rotate_Components.png"
    
    def __init__(self, parentMode):        
        self.parentMode = parentMode
        self.w = self.parentMode.w
        self.win = self.parentMode.w
        self.o = self.parentMode.o
        self.pw = self.parentMode.pw

        
        PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title)        
        self.showTopRowButtons(PM_DONE_BUTTON | PM_WHATS_THIS_BUTTON)
    
    def _addGroupBoxes(self):
        """
        Add groupboxes to the Property Manager dialog. 
        """
        
        self.translateGroupBox = PM_GroupBox( self, 
                                              title = "Translate",
                                              connectTitleButton = False)
        self.translateGroupBox.titleButton.setShortcut('T')
        self._loadTranslateGroupBox(self.translateGroupBox)
        
        self.rotateGroupBox = PM_GroupBox( self, 
                                           title = "Rotate",
                                           connectTitleButton = False)
        self.rotateGroupBox.titleButton.setShortcut('R')
        self._loadRotateGroupBox(self.rotateGroupBox)
        
        self.translateGroupBox.collapse()
        self.rotateGroupBox.collapse()
            
    # == Begin Translate Group Box =====================
    
    def _loadTranslateGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Translate group box.
        @param inPmGroupBox: The Translate group box in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        
        translateChoices = [ "Free Drag", 
                             "By Delta XYZ", 
                             "To XYZ Position" ]
        
        self.translateComboBox = \
            PM_ComboBox( inPmGroupBox,
                         label        = '', 
                         choices      = translateChoices, 
                         index        = 0, 
                         setAsDefault = False,
                         spanWidth    = True )
        
        self.freeDragTranslateGroupBox = PM_GroupBox( inPmGroupBox )
        self._loadFreeDragTranslateGroupBox(self.freeDragTranslateGroupBox)
                
        self.byDeltaGroupBox = PM_GroupBox( inPmGroupBox )
        self._loadByDeltaGroupBox(self.byDeltaGroupBox)
        
        self.toPositionGroupBox = PM_GroupBox( inPmGroupBox )
        self._loadToPositionGroupBox(self.toPositionGroupBox)
        
        self.updateTranslateGroupBoxes(0)
    
    def _loadFreeDragTranslateGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Free Drag Translate group box, which is present 
        within the Translate groupbox.
        @param inPmGroupBox: The Free Drag Translate group box in the Translate 
                             group box. 
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        # Button list to create a toolbutton row.
        # Format: 
        # - buttonId, 
        # - buttonText , 
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        
         
        BUTTON_LIST = [ 
            ( "QToolButton", 1,  "MOVEDEFAULT", 
              "ui/actions/Properties Manager/Move_Free.png", "", "F", 0),
            ( "QToolButton", 2,  "TRANSX", 
              "ui/actions/Properties Manager/TranslateX.png", "", "X", 1),
            ( "QToolButton", 3,  "TRANSY",  
              "ui/actions/Properties Manager/TranslateY.png", "", "Y", 2),
            ( "QToolButton", 4,  "TRANSZ",  
              "ui/actions/Properties Manager/TranslateZ.png", "", "Z", 3),
            ( "QToolButton", 5,  "ROT_TRANS_ALONG_AXIS",  
              "ui/actions/Properties Manager/translate+rotate-A.png", "", \
              "A", 4)
                        
            ]
            
        self.freeDragTranslateButtonGroup = \
            PM_ToolButtonRow( inPmGroupBox, 
                               title        = "",
                               buttonList   = BUTTON_LIST,
                               checkedId    = 1,
                               setAsDefault = True,
                               )
        self.transFreeButton =self.freeDragTranslateButtonGroup.getButtonById(1)
        self.transXButton = self.freeDragTranslateButtonGroup.getButtonById(2)
        self.transYButton = self.freeDragTranslateButtonGroup.getButtonById(3)
        self.transZButton = self.freeDragTranslateButtonGroup.getButtonById(4)
        self.transAlongAxisButton = \
            self.freeDragTranslateButtonGroup.getButtonById(5)
        
        self.moveFromToButton = PM_ToolButton(
                    inPmGroupBox, 
                    text = "Translate from/to",
                    iconPath  = "ui/actions/Properties Manager"\
                    "/Translate_Components.png",
                    spanWidth = True
                    
                    )
        self.moveFromToButton.setCheckable(True)
        self.moveFromToButton.setAutoRaise(True)
        self.moveFromToButton.setToolButtonStyle(
            Qt.ToolButtonTextBesideIcon)
        
        
        self.startCoordLineEdit = PM_LineEdit( 
            inPmGroupBox, 
            label        = "ui/actions/Properties Manager"\
                    "/Move_Start_Point.png",
            text         = "Define start point from 3D workspace",
            setAsDefault = False,
            )
        self.startCoordLineEdit.setReadOnly(True)
        self.startCoordLineEdit.setEnabled(False)
        
    def _loadByDeltaGroupBox(self, inPmGroupBox):
        """
        Load widgets in the translate By Delta group box, which is present 
        within the Translate groupbox.
        @param inPmGroupBox: The Translate By Delta group box in the translate 
                             group box. 
        @type  inPmGroupBox: L{PM_GroupBox}
        """

        self.moveDeltaXSpinBox = \
            PM_DoubleSpinBox( 
                inPmGroupBox, 
                label        = "ui/actions/Properties Manager/Delta_X.png",
                value        = 0.0, 
                setAsDefault = True,
                minimum      = -100.0, 
                maximum      =  100.0, 
                singleStep   = 1.0, 
                decimals     = 3, 
                suffix       = ' Angstroms',
                spanWidth    = False )
        
        self.moveDeltaYSpinBox = \
            PM_DoubleSpinBox( 
                inPmGroupBox, 
                label        = "ui/actions/Properties Manager/Delta_Y.png",
                value        = 0.0, 
                setAsDefault = True,
                minimum      = -100.0, 
                maximum      =  100.0, 
                singleStep   = 1.0, 
                decimals     = 3, 
                suffix       = ' Angstroms',
                spanWidth    = False )
        
        self.moveDeltaZSpinBox = \
            PM_DoubleSpinBox( 
                inPmGroupBox, 
                label        = "ui/actions/Properties Manager/Delta_Z.png",
                value        = 0.0, 
                setAsDefault = True,
                minimum      = -100.0, 
                maximum      =  100.0, 
                singleStep   = 1.0, 
                decimals     = 3, 
                suffix       = ' Angstroms',
                spanWidth    = False )
        
        DELTA_BUTTONS = [
                        ("QToolButton",1,  "Delta Plus", 
                         "ui/actions/Properties Manager/Move_Delta_Plus.png", 
                         "", "+", 0 ),
            
                        ( "QToolButton", 2,  "Delta Minus",  
                          "ui/actions/Properties Manager/Move_Delta_Minus.png", 
                          "", "-", 1 )
                        ]
        
        self.translateDeltaButtonRow = \
            PM_ToolButtonRow( inPmGroupBox, 
                              title        = "",
                              buttonList   = DELTA_BUTTONS,
                              label        = 'Translate:',
                              isAutoRaise  =  True,
                              isCheckable  =  False                           
                            )
        self.transDeltaPlusButton = \
            self.translateDeltaButtonRow.getButtonById(1)
        self.transDeltaMinusButton = \
            self.translateDeltaButtonRow.getButtonById(2)
        
            
    def _loadToPositionGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Translate To a given Position group box, which is 
        present within the Translate groupbox.
        @param inPmGroupBox: Translate To Position group box in the Translate 
                             group box.
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        
        self.toPositionspinboxes = PM_CoordinateSpinBoxes(inPmGroupBox)
        
        self.moveXSpinBox = self.toPositionspinboxes.xSpinBox
        self.moveYSpinBox = self.toPositionspinboxes.ySpinBox
        self.moveZSpinBox = self.toPositionspinboxes.zSpinBox
        
        
        self.moveAbsoluteButton = \
            PM_PushButton( inPmGroupBox,
                           label     = "",
                           text      = "Move Selection",
                           spanWidth = True )
            
    # == Begin Rotate Group Box =====================
    def _loadRotateGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Rotate group box, 
        @param inPmGroupBox: The Rotate GroupBox in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        
        rotateChoices = [ "Free Drag", "By Specified Angle"]
        
        self.rotateComboBox = \
            PM_ComboBox( inPmGroupBox,
                         label        = '', 
                         choices      = rotateChoices, 
                         index        = 0, 
                         setAsDefault = False,
                         spanWidth    = True )
        
        self.rotateAsUnitCB = \
            PM_CheckBox( inPmGroupBox,
                         text         = 'Rotate as a unit' ,
                         widgetColumn = 0,
                         state        = Qt.Checked )
        
               
        self.freeDragRotateGroupBox = PM_GroupBox( inPmGroupBox )
        self._loadFreeDragRotateGroupBox(self.freeDragRotateGroupBox)
        
        self.bySpecifiedAngleGroupBox = PM_GroupBox( inPmGroupBox )
        self._loadBySpecifiedAngleGroupBox(self.bySpecifiedAngleGroupBox)
        
        self.updateRotateGroupBoxes(0)    
        
    def _loadFreeDragRotateGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Free Drag Rotate group box, which is 
        present within the Rotate groupbox.
        @param inPmGroupBox: The Free Drag Rotate group box in the Rotate 
                             group box.
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        # Button list to create a toolbutton row.
        # Format: 
        # - buttonId, 
        # - buttonText , 
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        
        BUTTON_LIST = [ 
            ( "QToolButton", 1,  "ROTATEDEFAULT", 
              "ui/actions/Properties Manager/Rotate_Free.png", "", "F", 0 ),
            
            ( "QToolButton", 2,  "ROTATEX", 
              "ui/actions/Properties Manager/RotateX.png", "", "X", 1 ),
            
            ( "QToolButton", 3,  "ROTATEY",  
              "ui/actions/Properties Manager/RotateY.png", "", "Y", 2 ),
            
            ( "QToolButton", 4,  "ROTATEZ",  
              "ui/actions/Properties Manager/RotateZ.png", "", "Z", 3 ),
            
            ( "QToolButton", 5,  "ROT_TRANS_ALONG_AXIS",  
              "ui/actions/Properties Manager/translate+rotate-A.png", "", \
              "A", 4 )
                        
            ]
            
        self.freeDragRotateButtonGroup = \
            PM_ToolButtonRow( inPmGroupBox, 
                               title        = "",
                               buttonList   = BUTTON_LIST,
                               spanWidth = True,
                               checkedId    = 1,
                               setAsDefault = True,
                            )
                
        self.rotateFreeButton = self.freeDragRotateButtonGroup.getButtonById(1)
        self.rotateXButton    = self.freeDragRotateButtonGroup.getButtonById(2)
        self.rotateYButton    = self.freeDragRotateButtonGroup.getButtonById(3)
        self.rotateZButton    = self.freeDragRotateButtonGroup.getButtonById(4)
        self.rotAlongAxisButton = \
            self.freeDragRotateButtonGroup.getButtonById(5)
        
        inPmGroupBox.setStyleSheet(
            self.freeDragRotateButtonGroup._getStyleSheet())
                
        X_ROW_LABELS = [("QLabel", "Delta Theta X:", 0),
                        ("QLabel", "", 1),
                        ("QLabel", "0.00", 2),
                        ("QLabel", "Degrees", 3)]
        
        Y_ROW_LABELS = [("QLabel", "Delta Theta Y:", 0),
                        ("QLabel", "", 1),
                        ("QLabel", "0.00", 2),
                        ("QLabel", "Degrees", 3)]
        
        Z_ROW_LABELS = [("QLabel", "Delta Theta Z:", 0),
                        ("QLabel", "", 1),
                        ("QLabel", "0.00", 2),
                        ("QLabel", "Degrees", 3)]
        
        self.rotateXLabelRow = PM_LabelRow( inPmGroupBox,
                                            title = "",
                                            labelList = X_ROW_LABELS )  
        self.deltaThetaX_lbl = self.rotateXLabelRow.labels[2]
                                           
        self.rotateYLabelRow = PM_LabelRow( inPmGroupBox,
                                            title = "",
                                            labelList = Y_ROW_LABELS )
        self.deltaThetaY_lbl = self.rotateYLabelRow.labels[2]
                                          
        self.rotateZLabelRow = PM_LabelRow( inPmGroupBox,
                                            title = "",
                                            labelList = Z_ROW_LABELS )  
        self.deltaThetaZ_lbl = self.rotateZLabelRow.labels[2]    
        
        self.rotateAboutPointButton = PM_ToolButton(
                    inPmGroupBox, 
                    text = "Rotate selection about a point",
                    iconPath  = "ui/actions/Properties Manager"\
                    "/Rotate_Components.png",
                    spanWidth = True                    
                    )
        self.rotateAboutPointButton.setCheckable(True)
        self.rotateAboutPointButton.setAutoRaise(True)
        self.rotateAboutPointButton.setToolButtonStyle(
            Qt.ToolButtonTextBesideIcon)
        
        
        self.rotateStartCoordLineEdit = PM_LineEdit( 
            inPmGroupBox, 
            label        = "ui/actions/Properties Manager"\
                    "/Move_Start_Point.png",
            text         = "Define start point from 3D workspace",
            setAsDefault = False,
            )
        self.rotateStartCoordLineEdit.setReadOnly(True)
        self.rotateStartCoordLineEdit.setEnabled(False)
            
            
    def _loadBySpecifiedAngleGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Rotate By Specified Angle group box, which is 
        present within the Rotate groupbox.
        @param inPmGroupBox: Rotate By Specified Angle group box in the Rotate 
                             group box.
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        # Button list to create a toolbutton row.
        # Format: 
        # - buttonId, 
        # - buttonText , 
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        
        BUTTON_LIST = [ 
            ( "QToolButton", 1,  "ROTATEX", 
              "ui/actions/Properties Manager/RotateX.png", 
              "Rotate about X axis", "X", 0 ),
            
            ( "QToolButton", 2,  "ROTATEY",  
              "ui/actions/Properties Manager/RotateY.png", 
              "Rotate about Y axis", "Y", 1 ),
            
            ( "QToolButton", 3,  "ROTATEZ",  
              "ui/actions/Properties Manager/RotateZ.png", 
              "Rotate about Z axis","Z", 2 ),
            ]
        
        
        
        self.rotateAroundAxisButtonRow = \
            PM_ToolButtonRow( inPmGroupBox, 
                              title        = "",
                              buttonList   = BUTTON_LIST,
                              alignment    = 'Right',
                              label        = 'Rotate Around:'
                            )
        self.rotXaxisButton = \
            self.rotateAroundAxisButtonRow.getButtonById(1)
        
        self.rotYaxisButton = \
            self.rotateAroundAxisButtonRow.getButtonById(2)
        
        self.rotZaxisButton = \
            self.rotateAroundAxisButtonRow.getButtonById(3)
        
        

        self.rotateThetaSpinBox = \
            PM_DoubleSpinBox(inPmGroupBox,
                             label        = "Rotate By:",
                             value        = 0.0, 
                             setAsDefault = True,
                             minimum      = 0, 
                             maximum      = 360.0,
                             singleStep   = 1.0, 
                             decimals     = 2, 
                             suffix       = ' Degrees')
        
        
        THETA_BUTTONS = [ 
            ( "QToolButton", 1,  "Theta Plus", 
              "ui/actions/Properties Manager/Move_Theta_Plus.png", "", "+", 0 ),
            
            ( "QToolButton", 2,  "Theta Minus",  
              "ui/actions/Properties Manager/Move_Theta_Minus.png", "", "-", 1 )
            ]
        
        self.rotateThetaButtonRow = \
            PM_ToolButtonRow( inPmGroupBox, 
                              title        = "",
                              buttonList   = THETA_BUTTONS,
                              label        = 'Direction:',
                              isAutoRaise  =  True,
                              isCheckable  =  False                           
                            )
        self.rotateThetaPlusButton =  self.rotateThetaButtonRow.getButtonById(1)
        self.rotateThetaMinusButton = self.rotateThetaButtonRow.getButtonById(2)
    
    # == End Rotate Group Box =====================
        
    # == Slots for Translate group box
    def _hideAllTranslateGroupBoxes(self):
        """
        Hides all Translate group boxes.
        """
        self.toPositionGroupBox.hide()
        self.byDeltaGroupBox.hide()
        self.freeDragTranslateGroupBox.hide()
            
    def updateTranslateGroupBoxes(self, id):
        """
        Update the translate group boxes displayed based on the translate
        option selected.
        @param id: Integer value corresponding to the combobox item in the 
                   Translate group box. 
        @type  id: int
        """
        self._hideAllTranslateGroupBoxes()
        
        if id is 0:
            self.freeDragTranslateGroupBox.show()
                               
        if id is 1:
            self.byDeltaGroupBox.show()                    
        if id is 2:
            self.toPositionGroupBox.show()
           
        self.updateMessage()
    
    def changeMoveOption(self, button):
        """
        Subclasses should reimplement this method.
        
        @param button: QToolButton that decides the type of translate operation 
        to be set.
        @type  button: QToolButton 
                       L{http://doc.trolltech.com/4.2/qtoolbutton.html}
        @see: B{MovePropertyManager.changeMoveOption} which overrides this
              method
        """
        pass
    
    # == Slots for Rotate group box
    def updateRotateGroupBoxes(self, id):
        """
        Update the translate group boxes displayed based on the translate
        option selected.
        @param id: Integer value corresponding to the combobox item in the 
                   Rotate group box. 
        @type  id: int
        """
        if id is 0:
            self.bySpecifiedAngleGroupBox.hide()
            self.freeDragRotateGroupBox.show()   
        if id is 1:
            self.freeDragRotateGroupBox.hide()
            self.bySpecifiedAngleGroupBox.show()
            
        self.updateMessage()
            
    def changeRotateOption(self, button):
        """
        Subclasses should reimplement this method. 
        
        @param button: QToolButton that decides the type of rotate operation 
        to be set.
        @type  button: QToolButton 
                       L{http://doc.trolltech.com/4.2/qtoolbutton.html}
        @see: B{MovePropertyManage.changeRotateOption} which overrides this 
             method
        """
        pass
    
    def _addWhatsThisText(self):
        """
        What's This text for some of the widgets in this Property Manager.  

        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_MovePropertyManager
        whatsThis_MovePropertyManager(self)
        
    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.  
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_MovePropertyManager
        ToolTip_MovePropertyManager(self)
            
Example #12
0
 def _loadFreeDragTranslateGroupBox(self, inPmGroupBox):
     """
     Load widgets in the Free Drag Translate group box, which is present 
     within the Translate groupbox.
     @param inPmGroupBox: The Free Drag Translate group box in the Translate 
                          group box. 
     @type  inPmGroupBox: L{PM_GroupBox}
     """
     # Button list to create a toolbutton row.
     # Format: 
     # - buttonId, 
     # - buttonText , 
     # - iconPath
     # - tooltip
     # - shortcut
     # - column
     
      
     BUTTON_LIST = [ 
         ( "QToolButton", 1,  "MOVEDEFAULT", 
           "ui/actions/Properties Manager/Move_Free.png", "", "F", 0),
         ( "QToolButton", 2,  "TRANSX", 
           "ui/actions/Properties Manager/TranslateX.png", "", "X", 1),
         ( "QToolButton", 3,  "TRANSY",  
           "ui/actions/Properties Manager/TranslateY.png", "", "Y", 2),
         ( "QToolButton", 4,  "TRANSZ",  
           "ui/actions/Properties Manager/TranslateZ.png", "", "Z", 3),
         ( "QToolButton", 5,  "ROT_TRANS_ALONG_AXIS",  
           "ui/actions/Properties Manager/translate+rotate-A.png", "", \
           "A", 4)
                     
         ]
         
     self.freeDragTranslateButtonGroup = \
         PM_ToolButtonRow( inPmGroupBox, 
                            title        = "",
                            buttonList   = BUTTON_LIST,
                            checkedId    = 1,
                            setAsDefault = True,
                            )
     self.transFreeButton =self.freeDragTranslateButtonGroup.getButtonById(1)
     self.transXButton = self.freeDragTranslateButtonGroup.getButtonById(2)
     self.transYButton = self.freeDragTranslateButtonGroup.getButtonById(3)
     self.transZButton = self.freeDragTranslateButtonGroup.getButtonById(4)
     self.transAlongAxisButton = \
         self.freeDragTranslateButtonGroup.getButtonById(5)
     
     self.moveFromToButton = PM_ToolButton(
                 inPmGroupBox, 
                 text = "Translate from/to",
                 iconPath  = "ui/actions/Properties Manager"\
                 "/Translate_Components.png",
                 spanWidth = True
                 
                 )
     self.moveFromToButton.setCheckable(True)
     self.moveFromToButton.setAutoRaise(True)
     self.moveFromToButton.setToolButtonStyle(
         Qt.ToolButtonTextBesideIcon)
     
     
     self.startCoordLineEdit = PM_LineEdit( 
         inPmGroupBox, 
         label        = "ui/actions/Properties Manager"\
                 "/Move_Start_Point.png",
         text         = "Define start point from 3D workspace",
         setAsDefault = False,
         )
     self.startCoordLineEdit.setReadOnly(True)
     self.startCoordLineEdit.setEnabled(False)
Example #13
0
class ColorScheme_PropertyManager(PM_Dialog, DebugMenuMixin):
    """
    The ColorScheme_PropertyManager class provides a Property Manager
    for choosing background and other colors for the Choose Color toolbar command
    as well as the View/Color Scheme command

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

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

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

    title = "Color Scheme"
    pmName = title
    iconPath = "ui/actions/View/ColorScheme.png"

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

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

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

        DebugMenuMixin._init1(self)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Edit the color scheme for NE1, including the background color, "\
            "hover highlighting and selection colors, etc."
        self.updateMessage(msg)

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

        # 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)

        # background color setting combo box.
        change_connect(self.backgroundColorComboBox, SIGNAL("activated(int)"),
                       self.changeBackgroundColor)

        #hover highlighting style combo box
        change_connect(self.hoverHighlightingStyleComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.changeHoverHighlightingStyle)
        change_connect(self.hoverHighlightingColorComboBox,
                       SIGNAL("editingFinished()"),
                       self.changeHoverHighlightingColor)

        #selection style combo box
        change_connect(self.selectionStyleComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.changeSelectionStyle)
        change_connect(self.selectionColorComboBox,
                       SIGNAL("editingFinished()"), self.changeSelectionColor)

    def changeHoverHighlightingColor(self):
        """
        Slot method for Hover Highlighting color chooser.
        Change the (3D) hover highlighting color.
        """
        color = self.hoverHighlightingColorComboBox.getColor()
        env.prefs[hoverHighlightingColor_prefs_key] = color
        return

    def changeHoverHighlightingStyle(self, idx):
        """
        Slot method for Hover Highlighting combobox.
        Change the (3D) hover highlighting style.
        """
        env.prefs[hoverHighlightingColorStyle_prefs_key] = HHS_INDEXES[idx]

    def changeSelectionStyle(self, idx):
        """
        Slot method for Selection color style combobox.
        Change the (3D) Selection color style.
        """
        env.prefs[selectionColorStyle_prefs_key] = SS_INDEXES[idx]

    def changeSelectionColor(self):
        """
        Slot method for Selection color chooser.
        Change the (3D) Selection color.
        """
        color = self.selectionColorComboBox.getColor()
        env.prefs[selectionColor_prefs_key] = color
        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._updateAllWidgets()
        PM_Dialog.show(self)
        self.connect_or_disconnect_signals(isConnect=True)

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

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

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

        self._pmGroupBox3 = PM_GroupBox(self,
                                        title="Highlighting and Selection")
        self._loadGroupBox3(self._pmGroupBox3)

        self._updateAllWidgets()

    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/DnaDisplayStyle 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/ColorScheme')

        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)

        # 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/ApplyColorSchemeFavorite.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.
        """
        #background color combo box
        self.backgroundColorComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label     =  "Color:",
                         spanWidth = False)

        self._loadBackgroundColorItems()

        self.enableFogCheckBox = \
            PM_CheckBox( pmGroupBox, text = "Enable fog" )

        connect_checkbox_with_boolean_pref(self.enableFogCheckBox,
                                           fogEnabled_prefs_key)
        return

    def _loadGroupBox3(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        # hover highlighting style and color
        self.hoverHighlightingStyleComboBox = \
            PM_ComboBox( pmGroupBox,
                         label     =  "Highlighting:",
                         )

        self._loadHoverHighlightingStyleItems()

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

        self.hoverHighlightingColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                             colorList = hhColorList,
                             colorNames = hhColorNames,
                             color = env.prefs[hoverHighlightingColor_prefs_key]
                             )

        # selection style and color
        self.selectionStyleComboBox = \
            PM_ComboBox( pmGroupBox,
                         label     =  "Selection:",
                         )

        self._loadSelectionStyleItems()

        selColorList = [
            darkgreen, green, orange, red, magenta, cyan, blue, white, black,
            gray
        ]
        selColorNames = [
            "Dark green (default)", "Green", "Orange", "Red", "Magenta",
            "Cyan", "Blue", "White", "Black", "Other color..."
        ]

        self.selectionColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                             colorList = selColorList,
                             colorNames = selColorNames,
                             color = env.prefs[selectionColor_prefs_key]
                             )
        return

    def _updateAllWidgets(self):
        """
        Update all the PM widgets. This is typically called after applying
        a favorite.
        """
        self._updateBackgroundColorComboBoxIndex()
        self.updateCustomColorItemIcon(
            RGBf_to_QColor(env.prefs[backgroundColor_prefs_key]))
        self.hoverHighlightingStyleComboBox.setCurrentIndex(
            HHS_INDEXES.index(
                env.prefs[hoverHighlightingColorStyle_prefs_key]))
        self.hoverHighlightingColorComboBox.setColor(
            env.prefs[hoverHighlightingColor_prefs_key])
        self.selectionStyleComboBox.setCurrentIndex(
            SS_INDEXES.index(env.prefs[selectionColorStyle_prefs_key]))
        self.selectionColorComboBox.setColor(
            env.prefs[selectionColor_prefs_key])
        return

    def _loadSelectionStyleItems(self):
        """
        Load the selection color style combobox with items.
        """
        for selectionStyle in SS_OPTIONS:
            self.selectionStyleComboBox.addItem(selectionStyle)
        return

    def _loadHoverHighlightingStyleItems(self):
        """
        Load the hover highlighting style combobox with items.
        """
        for hoverHighlightingStyle in HHS_OPTIONS:
            self.hoverHighlightingStyleComboBox.addItem(hoverHighlightingStyle)
        return

    def _loadBackgroundColorItems(self):
        """
        Load the background color combobox with all the color options and sets
        the current background color
        """
        backgroundIndexes = [
            bg_EVENING_SKY, bg_BLUE_SKY, bg_SEAGREEN, bg_BLACK, bg_WHITE,
            bg_GRAY, bg_CUSTOM
        ]

        backgroundNames = [
            "Evening Sky (default)", "Blue Sky", "Sea Green", "Black", "White",
            "Gray", "Custom..."
        ]

        backgroundIcons = [
            "Background_EveningSky", "Background_BlueSky",
            "Background_SeaGreen", "Background_Black", "Background_White",
            "Background_Gray", "Background_Custom"
        ]

        backgroundIconsDict = dict(zip(backgroundNames, backgroundIcons))
        backgroundNamesDict = dict(zip(backgroundIndexes, backgroundNames))

        for backgroundName in backgroundNames:

            basename = backgroundIconsDict[backgroundName] + ".png"
            iconPath = os.path.join("ui/dialogs/Preferences/", basename)
            self.backgroundColorComboBox.addItem(geticon(iconPath),
                                                 backgroundName)

        self._updateBackgroundColorComboBoxIndex()  # Not needed, but OK.
        return

    def _updateBackgroundColorComboBoxIndex(self):
        """
        Set current index in the background color combobox.
        """
        if self.win.glpane.backgroundGradient:
            self.backgroundColorComboBox.setCurrentIndex(
                self.win.glpane.backgroundGradient - 1)
        else:
            if (env.prefs[backgroundColor_prefs_key] == black):
                self.backgroundColorComboBox.setCurrentIndex(bg_BLACK)
            elif (env.prefs[backgroundColor_prefs_key] == white):
                self.backgroundColorComboBox.setCurrentIndex(bg_WHITE)
            elif (env.prefs[backgroundColor_prefs_key] == gray):
                self.backgroundColorComboBox.setCurrentIndex(bg_GRAY)
            else:
                self.backgroundColorComboBox.setCurrentIndex(bg_CUSTOM)
        return

    def changeBackgroundColor(self, idx):
        """
        Slot method for the background color combobox.
        """
        #print "changeBackgroundColor(): Slot method called. Idx =", idx

        if idx == bg_EVENING_SKY:
            self.win.glpane.setBackgroundGradient(idx + 1)
        elif idx == bg_BLUE_SKY:
            self.win.glpane.setBackgroundGradient(idx + 1)
        elif idx == bg_SEAGREEN:
            self.win.glpane.setBackgroundGradient(idx + 1)
        elif idx == bg_BLACK:
            self.win.glpane.setBackgroundColor(black)
        elif idx == bg_WHITE:
            self.win.glpane.setBackgroundColor(white)
        elif idx == bg_GRAY:
            self.win.glpane.setBackgroundColor(gray)
        elif idx == bg_CUSTOM:
            #change background color to Custom Color
            self.chooseCustomBackgroundColor()
        else:
            msg = "Unknown color idx=", idx
            print_compact_traceback(msg)

        self.win.glpane.gl_update()  # Needed!
        return

    def chooseCustomBackgroundColor(self):
        """
        Choose a custom background color.
        """
        c = QColorDialog.getColor(
            RGBf_to_QColor(self.win.glpane.getBackgroundColor()), self)
        if c.isValid():
            self.win.glpane.setBackgroundColor(QColor_to_RGBf(c))
            self.updateCustomColorItemIcon(c)
        else:
            # User cancelled. Need to reset combobox to correct index.
            self._updateBackgroundColorComboBoxIndex()
        return

    def updateCustomColorItemIcon(self, qcolor):
        """
        Update the custom color item icon in the background color combobox
        with I{qcolor}.
        """
        pixmap = QPixmap(16, 16)
        pixmap.fill(qcolor)
        self.backgroundColorComboBox.setItemIcon(bg_CUSTOM, QIcon(pixmap))
        return

    def applyFavorite(self):
        """
        Apply the color scheme settings stored in the current favorite
        (selected in the combobox) to the current color scheme settings.
        """
        # 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(colorSchemePrefsList)
            # set it back to blue sky
            self.win.glpane.setBackgroundGradient(1)
        else:
            favfilepath = getFavoritePathFromBasename(current_favorite)
            loadFavoriteFile(favfilepath)
            if env.prefs[backgroundGradient_prefs_key]:
                self.win.glpane.setBackgroundGradient(
                    env.prefs[backgroundGradient_prefs_key])
            else:
                self.win.glpane.setBackgroundColor(
                    env.prefs[backgroundColor_prefs_key])
        #self.hoverHighlightingColorComboBox.setColor(env.prefs[hoverHighlightingColor_prefs_key])
        #self.selectionColorComboBox.setColor(env.prefs[selectionColor_prefs_key])
        self._updateAllWidgets()
        self.win.glpane.gl_update()
        return

    def addFavorite(self):
        """
        Adds a new favorite to the user's list of favorites.
        """
        # Rules and other info:
        # - The new favorite is defined by the current color scheme
        #    settings.

        # - The user is prompted to type in a name for the new
        #    favorite.
        # - The color scheme settings are written to a file in a special
        #    directory on the disk
        # (i.e. $HOME/Nanorex/Favorites/ColorScheme/$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/ColorScheme/ 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 = writeColorSchemeToFavoritesFile(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 = writeColorSchemeToFavoritesFile(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):
        """
        Deletes the current favorite from the user's personal list of favorites
        (and from disk, only in the favorites folder though).

        @note: Cannot delete "Factory default settings".
        """
        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):
        """
        Writes the current favorite (selected in the combobox) to a file, any
        where in the disk that
        can be given to another NE1 user (i.e. as an email attachment).
        """

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

        #Check to see if favfilepath exists first
        if not os.path.exists(favfilepath):
            msg = "%s does not exist" % favfilepath
            env.history.message(cmd + msg)
            return
        formats = \
                    "Favorite (*.txt);;"\
                    "All Files (*.*)"

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

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

        else:
            #remember this directory

            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):
        """
        [private method]
        Set the working directory in the user preferences database.

        @param workdir: The fullpath directory to write to the user pref db.
        If I{workdir} is None (default), there is no change.
        @type  workdir: string
        """
        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):
        """
        Prompts the user to choose a "favorite file" (i.e. *.txt) from disk to
        be added to the personal favorites list.
        """
        # 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 = writeColorSchemeToFavoritesFile(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(colorSchemePrefsList)

                        # set it back to blue sky
                        self.win.glpane.setBackgroundGradient(1)
                        self.win.glpane.gl_update()
                        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)

                if env.prefs[backgroundGradient_prefs_key]:
                    self.win.glpane.setBackgroundGradient(
                        env.prefs[backgroundGradient_prefs_key])
                else:
                    self.win.glpane.setBackgroundColor(
                        env.prefs[backgroundColor_prefs_key])
                self.win.glpane.gl_update()
        return

    def _addWhatsThisText(self):
        """
        What's This text for widgets in the Color Scheme Property Manager.
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_ColorScheme_PropertyManager
        WhatsThis_ColorScheme_PropertyManager(self)

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the Color Scheme Property Manager.
        """
        #modify this for color schemes
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_ColorScheme_PropertyManager
        ToolTip_ColorScheme_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 Ui_BuildCrystal_PropertyManager(Command_PropertyManager):
    """
    The Ui_BuildCrystal_PropertyManager class defines UI elements for the Property
    Manager of the B{Crystal mode}.

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

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

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

    # <title> - the title that appears in the property manager header.
    title = "Build Crystal"
    # <iconPath> - full path to PNG file that appears in the header.
    # The name of this Property Manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    iconPath = "ui/actions/Tools/Build Structures/Build Crystal.png"

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

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

        _superclass.__init__(self, command)

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

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

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

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

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

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

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

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

        # Button list to create a toolbutton row.
        # Format:
        # - buttonType,
        # - buttonId,
        # - buttonText ,
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        BUTTON_LIST = [("QToolButton", 0, "Surface 100",
                        "ui/actions/Properties Manager/Surface100.png",
                        "Surface 100", "", 0),
                       ("QToolButton", 1, "Surface 110",
                        "ui/actions/Properties Manager/Surface110.png",
                        "Surface 110", "", 1),
                       ("QToolButton", 2, "Surface 111",
                        "ui/actions/Properties Manager/Surface111.png",
                        "Surface 110", "", 2)]
        self.gridOrientationButtonRow = \
            PM_ToolButtonRow(inPmGroupBox,
                               title        = "",
                               label        = "Orientation:",
                               buttonList   = BUTTON_LIST,
                               checkedId    = 0,
                               setAsDefault = True,
                               spanWidth   = False
                               )

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

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

        GRID_ANGLE_BUTTONS = [
            ("QToolButton", 0, "Anticlockwise",
             "ui/actions/Properties Manager/rotate_minus.png", "", "+", 0),
            ("QToolButton", 1, "Clockwise",
             "ui/actions/Properties Manager/rotate_plus.png", "", "-", 1)
        ]

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

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

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

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

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

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

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

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

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

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

    def _loadAdvancedOptionsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Advanced Options group box.
        @param inPmGroupBox: The Advanced Options box in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        self.snapGridCheckBox = \
            PM_CheckBox(inPmGroupBox,
                        text = "Snap to grid",
                        state = Qt.Checked
                        )
        tooltip = "Snap selection point to a nearest cell grid point."
        self.snapGridCheckBox.setToolTip(tooltip)

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

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

        displayChoices = ['Tubes', 'Spheres']

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

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

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

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

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

    def _addToolTipText(self):
        """
        What's Tool Tip text for widgets in this Property Manager.
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_CookiePropertyManager
        ToolTip_CookiePropertyManager(self)
class LightingScheme_PropertyManager( PM_Dialog, DebugMenuMixin ):
    """
    The LightingScheme_PropertyManager class provides a Property Manager 
    for changing light properties as well as material properties.

    @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         =  "Lighting Scheme"
    pmName        =  title
    iconPath      =  "ui/actions/View/LightingScheme.png"
    
    
    def __init__( self, parentCommand ):
        """
        Constructor for the property manager.
        """

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

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        
        msg = "Edit the lighting scheme for NE1. Includes turning lights on and off, "\
            "changing light colors, changing the position of lights as well as,"\
            "changing the ambient, diffuse, and specular properites."
        self.updateMessage(msg)
        
    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot 
                          method. 
        @type  isConnect: boolean
        """
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect 
        
        # 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)
        
        # Directional Lighting Properties
        change_connect(self.ambientDoubleSpinBox, SIGNAL("valueChanged(double)"), self.change_lighting)
        change_connect(self.lightColorComboBox, SIGNAL("editingFinished()"), self.changeLightColor) 
        change_connect(self.enableLightCheckBox, SIGNAL("toggled(bool)"), self.toggle_light)
        change_connect(self.lightComboBox, SIGNAL("activated(int)"), self.change_active_light)
        change_connect(self.diffuseDoubleSpinBox, SIGNAL("valueChanged(double)"), self.change_lighting)
        change_connect(self.specularDoubleSpinBox, SIGNAL("valueChanged(double)"), self.change_lighting)
        change_connect(self.xDoubleSpinBox, SIGNAL("editingFinished()"), self.save_lighting)
        change_connect(self.yDoubleSpinBox, SIGNAL("editingFinished()"), self.save_lighting)
        change_connect(self.zDoubleSpinBox, SIGNAL("editingFinished()"), self.save_lighting)
        # Material Specular Properties
        change_connect(self.brightnessDoubleSpinBox, SIGNAL("valueChanged(double)"), self.change_material_brightness)
        change_connect(self.finishDoubleSpinBox, SIGNAL("valueChanged(double)"), self.change_material_finish)
        change_connect(self.enableMaterialPropertiesComboBox, SIGNAL("toggled(bool)"), self.toggle_material_specularity)
        change_connect(self.shininessDoubleSpinBox, SIGNAL("valueChanged(double)"), self.change_material_shininess)
        self._setup_material_group()
        return
    
    def _updatePage_Lighting(self, lights = None): #mark 051124
        """
        Setup widgets to initial (default or defined) values on the Lighting page.
        """
        if not lights:
            self.lights = self.original_lights = self.win.glpane.getLighting()
        else:
            self.lights = lights

        light_num = self.lightComboBox.currentIndex()


        # Move lc_prefs_keys upstairs.  Mark.
        lc_prefs_keys = [light1Color_prefs_key, light2Color_prefs_key, light3Color_prefs_key]
        self.current_light_key = lc_prefs_keys[light_num] # Get prefs key for current light color.
        self.lightColorComboBox.setColor(env.prefs[self.current_light_key])
        self.light_color = env.prefs[self.current_light_key]

        # These sliders generate signals whenever their 'setValue()' slot is called (below).
        # This creates problems (bugs) for us, so we disconnect them temporarily.
        self.disconnect(self.ambientDoubleSpinBox, SIGNAL("valueChanged(double)"), self.change_lighting)
        self.disconnect(self.diffuseDoubleSpinBox, SIGNAL("valueChanged(double)"), self.change_lighting)
        self.disconnect(self.specularDoubleSpinBox, SIGNAL("valueChanged(double)"), self.change_lighting)

        # self.lights[light_num][0] contains 'color' attribute.  
        # We already have it (self.light_color) from the prefs key (above).
        a = self.lights[light_num][1] # ambient intensity
        d = self.lights[light_num][2] # diffuse intensity
        s = self.lights[light_num][3] # specular intensity
        g = self.lights[light_num][4] # xpos
        h = self.lights[light_num][5] # ypos
        k = self.lights[light_num][6] # zpos
        

        self.ambientDoubleSpinBox.setValue(a)# generates signal
        self.diffuseDoubleSpinBox.setValue(d) # generates signal
        self.specularDoubleSpinBox.setValue(s) # generates signal
        self.xDoubleSpinBox.setValue(g) # generates signal
        self.yDoubleSpinBox.setValue(h) # generates signal
        self.zDoubleSpinBox.setValue(k) # generates signal

        self.enableLightCheckBox.setChecked(self.lights[light_num][7])

        # Reconnect the slots to the light sliders.
        self.connect(self.ambientDoubleSpinBox, SIGNAL("valueChanged(double)"), self.change_lighting)
        self.connect(self.diffuseDoubleSpinBox, SIGNAL("valueChanged(double)"), self.change_lighting)
        self.connect(self.specularDoubleSpinBox, SIGNAL("valueChanged(double)"), self.change_lighting)
        
        self.update_light_combobox_items()
        self.save_lighting()
        self._setup_material_group()
        return
        
    def _setup_material_group(self, reset = False):
        """
        Setup Material Specularity widgets to initial (default or defined) values on the Lighting page.
        If reset = False, widgets are reset from the prefs db.
        If reset = True, widgets are reset from their previous values.
        """

        if reset:
            self.material_specularity = self.original_material_specularity
            self.whiteness = self.original_whiteness
            self.shininess = self.original_shininess
            self.brightness = self.original_brightness
        else:
            self.material_specularity = self.original_material_specularity = \
                env.prefs[material_specular_highlights_prefs_key]
            self.whiteness = self.original_whiteness = \
                env.prefs[material_specular_finish_prefs_key]
            self.shininess = self.original_shininess = \
                env.prefs[material_specular_shininess_prefs_key]
            self.brightness = self.original_brightness= \
                env.prefs[material_specular_brightness_prefs_key]

        # Enable/disable material specularity properites.
        self.enableMaterialPropertiesComboBox.setChecked(self.material_specularity)

        # For whiteness, the stored range is 0.0 (Plastic) to 1.0 (Metal).
        self.finishDoubleSpinBox.setValue(self.whiteness) # generates signal

        # For shininess, the range is 15 (low) to 60 (high).  Mark. 051129.
        self.shininessDoubleSpinBox.setValue(self.shininess) # generates signal

        # For brightness, the range is 0.0 (low) to 1.0 (high).  Mark. 051203.
        self.brightnessDoubleSpinBox.setValue(self.brightness) # generates signal
        return
    
    def toggle_material_specularity(self, val):
        """
        This is the slot for the Material Specularity Enabled checkbox.
        """
        env.prefs[material_specular_highlights_prefs_key] = val

    def change_material_finish(self, finish):
        """
        This is the slot for the Material Finish spin box.
        'finish' is between 0.0 and 1.0. 
        Saves finish parameter to pref db.
        """
        # For whiteness, the stored range is 0.0 (Metal) to 1.0 (Plastic).
        env.prefs[material_specular_finish_prefs_key] = finish
       
    def change_material_shininess(self, shininess):
        """
        This is the slot for the Material Shininess spin box.
        'shininess' is between 15 (low) and 60 (high).
        """
        env.prefs[material_specular_shininess_prefs_key] = shininess

    def change_material_brightness(self, brightness):
        """
        This is the slot for the Material Brightness sping box.
        'brightness' is between 0.0 (low) and 1.0 (high).
        """
        env.prefs[material_specular_brightness_prefs_key] = brightness
    
    def toggle_light(self, on):
        """
        Slot for light 'On' checkbox.  
        It updates the current item in the light combobox with '(On)' or 
        '(Off)' label.
        """
        if on:
            txt = "%d (On)" % (self.lightComboBox.currentIndex()+1)
        else:
            txt = "%d (Off)" % (self.lightComboBox.currentIndex()+1)
        self.lightComboBox.setItemText(self.lightComboBox.currentIndex(),txt)

        self.save_lighting()
    
    def change_lighting(self, specularityValueJunk = None):
        """
	Updates win.glpane lighting using the current lighting parameters from 
	the light checkboxes and sliders. This is also the slot for the light 
	spin boxes.
	@param specularityValueJunk: This value from the spin box is not used
				     We are interested in valueChanged signal 
				     only
        @type specularityValueJunk = int or None

        """

        light_num = self.lightComboBox.currentIndex()

        light1, light2, light3 = self.win.glpane.getLighting()

        a = self.ambientDoubleSpinBox.value()
        d = self.diffuseDoubleSpinBox.value()
        s = self.specularDoubleSpinBox.value()
        g = self.xDoubleSpinBox.value()
        h = self.yDoubleSpinBox.value()
        k = self.zDoubleSpinBox.value()

        new_light = [  self.light_color, a, d, s, g, h, k,\
                       self.enableLightCheckBox.isChecked()]

        # This is a kludge.  I'm certain there is a more elegant way.  Mark 051204.
        if light_num == 0:
            self.win.glpane.setLighting([new_light, light2, light3])
        elif light_num == 1:
            self.win.glpane.setLighting([light1, new_light, light3])
        elif light_num == 2:
            self.win.glpane.setLighting([light1, light2, new_light])
        else:
            print "Unsupported light # ", light_num,". No lighting change made."

    def change_active_light(self, currentIndexJunk = None):
        """
	Slot for the Light number combobox.  This changes the current light.
	@param currentIndexJunk: This index value from the combobox is not used
				 We are interested in 'activated' signal only
        @type currentIndexJunk = int or None
        """
        self._updatePage_Lighting()
        
    def reset_lighting(self):
        """
        Slot for Reset button.
        """
        # This has issues.  
        # I intend to remove the Reset button for A7.  Confirm with Bruce.  Mark 051204.
        self._setup_material_group(reset = True)
        self._updatePage_Lighting(self.original_lights)
        self.win.glpane.saveLighting()
    
    def save_lighting(self):
        """
        Saves lighting parameters (but not material specularity parameters) 
        to pref db. This is also the slot for light sliders (only when 
        released).
        """
        self.change_lighting()
        self.win.glpane.saveLighting()
        
    def restore_default_lighting(self):
        """
        Slot for Restore Defaults button.
        """

        self.win.glpane.restoreDefaultLighting()

        # Restore defaults for the Material Specularity properties
        env.prefs.restore_defaults([
            material_specular_highlights_prefs_key,
            material_specular_shininess_prefs_key,
            material_specular_finish_prefs_key,
            material_specular_brightness_prefs_key, #bruce 051203 bugfix
        ])

        self._updatePage_Lighting()
        self.save_lighting()
    
    def ok_btn_clicked(self):
        """
        Slot for the OK button
        """      
        self.win.toolsDone()
    
    def cancel_btn_clicked(self):
        """
        Slot for the Cancel button.
        """  
        #TODO: Cancel button needs to be removed. See comment at the top
        self.win.toolsDone()
        
    def show(self):
        """
        Shows the Property Manager. Overrides PM_Dialog.show.
        """
        PM_Dialog.show(self)
        self.connect_or_disconnect_signals(isConnect = True)
        self._updateAllWidgets()

    def close(self):
        """
        Closes the Property Manager. Overrides PM_Dialog.close.
        """
        self.connect_or_disconnect_signals(False)
        PM_Dialog.close(self)
        
    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox1 = PM_GroupBox( self, 
                                         title = "Favorites")
        self._loadGroupBox1( self._pmGroupBox1 )
        
        self._pmGroupBox2 = PM_GroupBox( self, 
                                         title = "Directional Lights")
        self._loadGroupBox2( self._pmGroupBox2 )
        
        self._pmGroupBox3 = PM_GroupBox( self, 
                                         title = "Material Properties")
        self._loadGroupBox3( self._pmGroupBox3 )
        
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """        
        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/LightingScheme')
        
        
        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)
        
        # 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/ApplyLightingSchemeFavorite.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.
        """
        
        self.lightComboBox  = \
            PM_ComboBox( pmGroupBox,
                         choices = ["1", "2", "3"],
                         label     =  "Light:")
        
        self.enableLightCheckBox = \
            PM_CheckBox( pmGroupBox, text = "On" )
        
        self.lightColorComboBox = \
            PM_ColorComboBox(pmGroupBox)
        self.ambientDoubleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox, 
                             maximum = 1.0,
                             minimum = 0.0,
                             decimals = 2,
                             singleStep = .1,
                             label = "Ambient:")
        self.diffuseDoubleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             maximum = 1.0,
                             minimum = 0.0,
                             decimals = 2,
                             singleStep = .1,
                             label = "Diffuse:")
        self.specularDoubleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             maximum = 1.0,
                             minimum = 0.0,
                             decimals = 2,
                             singleStep = .1,
                             label = "Specular:")
        
        self.positionGroupBox = \
            PM_GroupBox( pmGroupBox,
                         title = "Position:")
        
        self.xDoubleSpinBox = \
            PM_DoubleSpinBox(self.positionGroupBox,
                             maximum = 1000,
                             minimum = -1000,
                             decimals = 1,
                             singleStep = 10,
                             label = "X:")
        self.yDoubleSpinBox = \
            PM_DoubleSpinBox(self.positionGroupBox,
                             maximum = 1000,
                             minimum = -1000,
                             decimals = 1,
                             singleStep = 10,
                             label = "Y:")
        self.zDoubleSpinBox = \
            PM_DoubleSpinBox(self.positionGroupBox,
                             maximum = 1000,
                             minimum = -1000,
                             decimals = 1,
                             singleStep = 10,
                             label = "Z:")
        return
    
    def _loadGroupBox3(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        
        self.enableMaterialPropertiesComboBox = \
            PM_CheckBox( pmGroupBox, text = "On")
        self.finishDoubleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             maximum = 1.0,
                             minimum = 0.0,
                             decimals = 2,
                             singleStep = .1,
                             label = "Finish:")
        self.shininessDoubleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             maximum = 60,
                             minimum = 15,
                             decimals = 2,
                             label = "Shininess:")
        self.brightnessDoubleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             maximum = 1.0,
                             minimum = 0.0,
                             decimals = 2,
                             singleStep = .1,
                             label = "Brightness:")
        return
    
    def _updateAllWidgets(self):
        """
        Update all the PM widgets. This is typically called after applying
        a favorite.
        """
        self._updatePage_Lighting()
        return
    
    def update_light_combobox_items(self):
        """
        Updates all light combobox items with '(On)' or '(Off)' label.
        """
        for i in range(3):
            if self.lights[i][7]:
                txt = "%d (On)" % (i+1)
            else:
                txt = "%d (Off)" % (i+1)
            self.lightComboBox.setItemText(i, txt)
        return
        
    def changeLightColor(self):
        """
        Slot method for the ColorComboBox
        """
        color = self.lightColorComboBox.getColor()
        env.prefs[self.current_light_key] = color
        self.light_color = env.prefs[self.current_light_key]
        self.save_lighting()
        return
    
    def applyFavorite(self):
        """
        Apply the lighting scheme settings stored in the current favorite 
        (selected in the combobox) to the current lighting scheme settings.
        """
        # 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(lightingSchemePrefsList)
            self.restore_default_lighting()
        else:
            favfilepath = getFavoritePathFromBasename(current_favorite)
            loadFavoriteFile(favfilepath)
        self._updateAllWidgets()
        self.win.glpane.gl_update()
        return
    
    def addFavorite(self):
        """
        Adds a new favorite to the user's list of favorites.
        """
        # Rules and other info:
        # - The new favorite is defined by the current lighting scheme
        #    settings.
    
        # - The user is prompted to type in a name for the new 
        #    favorite.
        # - The lighting scheme settings are written to a file in a special 
        #    directory on the disk 
        # (i.e. $HOME/Nanorex/Favorites/LightingScheme/$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/LightingScheme/ 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 = writeLightingSchemeToFavoritesFile(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 = writeLightingSchemeToFavoritesFile(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):
        """
        Deletes the current favorite from the user's personal list of favorites
        (and from disk, only in the favorites folder though).
        
        @note: Cannot delete "Factory default settings".
        """
        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):
        """
        Writes the current favorite (selected in the combobox) to a file, any 
        where in the disk that 
        can be given to another NE1 user (i.e. as an email attachment).
        """
        
        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 (*.*)"
         
        
        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:
            saveFavoriteFile(str(fn), favfilepath)
        return
        
    def loadFavorite(self):
        """
        Prompts the user to choose a "favorite file" (i.e. *.txt) from disk to
        be added to the personal favorites list.
        """
        # 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= getDefaultWorkingDirectory()
        
        fname = QFileDialog.getOpenFileName(self,
                                         "Choose a file to load",
                                         directory,
                                         formats)
                    
        if not fname:
            env.history.message("User cancelled loading file.")
            return

        else:
            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 = writeLightingSchemeToFavoritesFile(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(lightingSchemePrefsList)
                        self.win.glpane.gl_update() 
                        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.win.glpane.gl_update()             
        return
    
    #def _addWhatsThisText( self ):
        #"""
        #What's This text for widgets in the Lighting Scheme Property Manager.  
        #"""
        #from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_LightingScheme_PropertyManager
        #WhatsThis_LightingScheme_PropertyManager(self)
                
    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the Lighting Scheme Property Manager.  
        """
        #modify this for lighting schemes
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_LightingScheme_PropertyManager 
        ToolTip_LightingScheme_PropertyManager(self)
class PlanePropertyManager(EditCommand_PM):
    """
    The PlanePropertyManager class provides a Property Manager for a
    (reference) Plane.

    """

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

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

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

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

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

        EditCommand_PM.__init__( self, command)

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


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

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

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

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

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

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

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

        connect_checkbox_with_boolean_pref(
            self.gridPlaneCheckBox ,
            PlanePM_showGrid_prefs_key)


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

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

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

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

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

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

        self.pmGroupBox5 = PM_GroupBox( pmGroupBox )

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

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

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

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

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

        self._showHideGPWidgets()

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

        return

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

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

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

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

        self.isAlreadyConnected = isConnect
        self.isAlreadyDisconnected = not isConnect

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self._connect_checkboxes_to_global_prefs_keys()

        return

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

        connect_checkbox_with_boolean_pref(
            self.gpDisplayLabels,
            PlanePM_showGridLabels_prefs_key)


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

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

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

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

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

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

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

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

        return

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

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

        return


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

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

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

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

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

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

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

        self.imageChangeButtonGroup.buttonGroup.setExclusive(False)

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

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

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

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

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

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

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




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

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

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



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



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


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

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

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

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


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

        self.command.struct.glpane.gl_update()


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

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

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

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

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


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

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

        plane = self.command.struct

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

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

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

            if validPath:
                from PIL import Image

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

                # Compute the relief image
                plane.computeHeightfield()

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


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

        if self.command.struct:

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

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

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

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


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

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

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


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

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

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

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

        return params


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

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

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

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

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

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

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

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

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

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


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

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

        self.aspectRatioSpinBox.setEnabled(enable)

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

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

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


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

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

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

        EditCommand_PM.update_props_if_needed_before_closing(self)

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

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

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

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

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

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

    def mirror_image(self):
        """
        Flip the image vertically.
        """
        if self.command.hasValidStructure():
            self.command.struct.mirrorImage(0)
        return
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        
        self.nameLineEdit = PM_LineEdit( pmGroupBox,
                                                label = "Name:")
        
        self.lengthLineEdit = PM_LineEdit( pmGroupBox,
                                           label = "Length:")
        self.lengthLineEdit.setEnabled(False)
        
        self.currentResidueComboBox = PM_ComboBox( pmGroupBox,
                                 label         =  "Current residue:",
                                 setAsDefault  =  False)
        
        BUTTON_LIST = [
            ("QToolButton", 1, "Previous residue", 
             "ui/actions/Properties Manager/Previous.png", 
             "", "Previous residue", 0 ),

            ( "QToolButton", 2, "Next residue",  
              "ui/actions/Properties Manager/Next.png", 
              "", "Next residue", 1 )
            ]
        
        self.prevNextButtonRow = \
            PM_ToolButtonRow( pmGroupBox, 
                              title        =  "",
                              buttonList   =  BUTTON_LIST,
                              label        =  'Previous / Next:',
                              isAutoRaise  =  True,
                              isCheckable  =  False
                            )
        self.prevButton = self.prevNextButtonRow.getButtonById(1)
        self.nextButton = self.prevNextButtonRow.getButtonById(2)
        
        self.recenterViewCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Center view on current residue",
                         setAsDefault  =  True,
                         state         =  Qt.Unchecked,
                         widgetColumn  =  0,
                         spanWidth     =  True)
        
        self.lockEditedCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Lock edited rotamers",
                         setAsDefault  =  True,
                         state         =  Qt.Checked,
                         widgetColumn  =  0,
                         spanWidth     =  True)
        
        self.showAllResiduesCheckBox  = \
            PM_CheckBox( pmGroupBox,
                         text          =  "Show all residues",
                         setAsDefault  =  False,
                         state         =  Qt.Unchecked,
                         widgetColumn  =  0,
                         spanWidth     =  True)
        return
class DnaDisplayStyle_PropertyManager( Command_PropertyManager):
    """
    The DnaDisplayStyle_PropertyManager class provides a Property Manager
    for the B{Display Style} 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         =  "Edit DNA Display Style"
    pmName        =  title
    iconPath      =  "ui/actions/Command Toolbar/BuildDna/EditDnaDisplayStyle.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 DNA display settings below."
        self.updateMessage(msg)

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

        # 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)

        # Current display settings groupbox.
        change_connect( self.dnaRenditionComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.change_dnaRendition )

        # Axis options.
        change_connect( self.axisShapeComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.win.userPrefs.change_dnaStyleAxisShape )

        change_connect( self.axisScaleDoubleSpinBox,
                      SIGNAL("valueChanged(double)"),
                      self.win.userPrefs.change_dnaStyleAxisScale )

        change_connect( self.axisColorComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.win.userPrefs.change_dnaStyleAxisColor )

        change_connect( self.axisEndingStyleComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.win.userPrefs.change_dnaStyleAxisEndingStyle )

        # Strands options.
        change_connect( self.strandsShapeComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.win.userPrefs.change_dnaStyleStrandsShape )

        change_connect( self.strandsScaleDoubleSpinBox,
                      SIGNAL("valueChanged(double)"),
                      self.win.userPrefs.change_dnaStyleStrandsScale )

        change_connect( self.strandsColorComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.win.userPrefs.change_dnaStyleStrandsColor )

        change_connect( self.strandsArrowsComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.win.userPrefs.change_dnaStyleStrandsArrows )

        # Structs options.
        change_connect( self.strutsShapeComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.win.userPrefs.change_dnaStyleStrutsShape )

        change_connect( self.strutsScaleDoubleSpinBox,
                      SIGNAL("valueChanged(double)"),
                      self.win.userPrefs.change_dnaStyleStrutsScale )

        change_connect( self.strutsColorComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.win.userPrefs.change_dnaStyleStrutsColor )

        # Nucleotides options.
        change_connect( self.nucleotidesShapeComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.win.userPrefs.change_dnaStyleBasesShape )

        change_connect( self.nucleotidesScaleDoubleSpinBox,
                      SIGNAL("valueChanged(double)"),
                      self.win.userPrefs.change_dnaStyleBasesScale )

        change_connect( self.nucleotidesColorComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.win.userPrefs.change_dnaStyleBasesColor )

        connect_checkbox_with_boolean_pref(
            self.dnaStyleBasesDisplayLettersCheckBox,
            dnaStyleBasesDisplayLetters_prefs_key)

        # Dna Strand labels option.

        change_connect( self.standLabelColorComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.change_dnaStrandLabelsDisplay )


    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(diDNACYLINDER)

        # 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.updateDnaDisplayStyleWidgets(blockSignals = True)


    def close(self):
        """
        Closes the Property Manager. Extends superclass method.
        """
        _superclass.close(self)

        # 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 = "Current Display Settings")
        self._loadGroupBox2( self._pmGroupBox2 )

    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/DnaDisplayStyle 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/DnaDisplayStyle')


        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 DNA 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/ApplyFavorite.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.
        """
        dnaRenditionChoices = ['3D (default)',
                               '2D with base letters',
                               '2D ball and stick',
                               '2D ladder']

        self.dnaRenditionComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Rendition:",
                         choices       =  dnaRenditionChoices,
                         setAsDefault  =  True)

        dnaComponentChoices = ['Axis',
                                'Strands',
                                'Struts',
                                'Nucleotides']

        self.dnaComponentComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Component:",
                         choices       =  dnaComponentChoices,
                         setAsDefault  =  True)

        self._loadAxisGroupBox()
        self._loadStrandsGroupBox()
        self._loadStrutsGroupBox()
        self._loadNucleotidesGroupBox()

        widgetList = [self.axisGroupBox,
                      self.strandsGroupBox,
                      self.strutsGroupBox,
                      self.nucleotidesGroupBox]

        self.dnaComponentStackedWidget = \
            PM_StackedWidget( pmGroupBox,
                              self.dnaComponentComboBox,
                              widgetList )

        standLabelColorChoices = ['Hide',
                                  'Show (in strand color)',
                                  'Black',
                                  'White',
                                  'Custom color...']

        self.standLabelColorComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Strand labels:",
                         choices       =  standLabelColorChoices,
                         setAsDefault  =  True)

        # This disables "Component" widgets if rendition style is 2D.
        self.change_dnaRendition(env.prefs[dnaRendition_prefs_key])

    def _loadAxisGroupBox(self):
        """
        Load the Axis group box.
        """

        axisGroupBox = PM_GroupBox( None )
        self.axisGroupBox = axisGroupBox

        axisShapeChoices = ['None', 'Wide tube', 'Narrow tube']

        self.axisShapeComboBox = \
            PM_ComboBox( axisGroupBox ,
                         label         =  "Shape:",
                         choices       =  axisShapeChoices,
                         setAsDefault  =  True)

        self.axisScaleDoubleSpinBox  =  \
            PM_DoubleSpinBox( axisGroupBox,
                              label         =  "Scale:",
                              value         =  1.00,
                              setAsDefault  =  True,
                              minimum       =  0.1,
                              maximum       =  2.0,
                              decimals      =  2,
                              singleStep    =  0.1 )

        axisColorChoices = ['Same as chunk',
                            'Base order',
                            'Base order (discrete)',
                            'Base type',
                            'Strand order']

        self.axisColorComboBox = \
            PM_ComboBox( axisGroupBox ,
                         label         =  "Color:",
                         choices       =  axisColorChoices,
                         setAsDefault  =  True)

        endingTypeChoices = ['Flat',
                             'Taper start',
                             'Taper end',
                             'Taper both',
                             'Spherical']

        self.axisEndingStyleComboBox = \
            PM_ComboBox( axisGroupBox ,
                         label         =  "Ending style:",
                         choices       =  endingTypeChoices,
                         setAsDefault  =  True)

    def _loadStrandsGroupBox(self):
        """
        Load the Strands group box.
        """

        strandsGroupBox = PM_GroupBox( None )
        self.strandsGroupBox = strandsGroupBox

        strandsShapeChoices = ['None', 'Cylinders', 'Tube']

        self.strandsShapeComboBox = \
            PM_ComboBox( strandsGroupBox ,
                         label         =  "Shape:",
                         choices       =  strandsShapeChoices,
                         setAsDefault  =  True)

        self.strandsScaleDoubleSpinBox  =  \
            PM_DoubleSpinBox( strandsGroupBox,
                              label         =  "Scale:",
                              value         =  1.00,
                              setAsDefault  =  True,
                              minimum       =  0.1,
                              maximum       =  5.0,
                              decimals      =  2,
                              singleStep    =  0.1 )

        strandsColorChoices = ['Same as chunk',
                               'Base order',
                               'Strand order']

        self.strandsColorComboBox = \
            PM_ComboBox( strandsGroupBox ,
                         label         =  "Color:",
                         choices       =  strandsColorChoices,
                         setAsDefault  =  True)

        strandsArrowsChoices = ['None',
                                '5\'',
                                '3\'',
                                '5\' and 3\'']

        self.strandsArrowsComboBox = \
            PM_ComboBox( strandsGroupBox ,
                         label         =  "Arrows:",
                         choices       =  strandsArrowsChoices,
                         setAsDefault  =  True)

    def _loadStrutsGroupBox(self):
        """
        Load the Struts group box.
        """

        strutsGroupBox = PM_GroupBox( None )
        self.strutsGroupBox = strutsGroupBox

        strutsShapeChoices = ['None',
                              'Base-axis-base cylinders',
                              'Straight cylinders']

        self.strutsShapeComboBox = \
            PM_ComboBox( strutsGroupBox ,
                         label         =  "Shape:",
                         choices       =  strutsShapeChoices,
                         setAsDefault  =  True)

        self.strutsScaleDoubleSpinBox  =  \
            PM_DoubleSpinBox( strutsGroupBox,

                              label         =  "Scale:",
                              value         =  1.00,
                              setAsDefault  =  True,
                              minimum       =  0.1,
                              maximum       =  3.0,
                              decimals      =  2,
                              singleStep    =  0.1 )

        strutsColorChoices = ['Same as strand',
                              'Base order',
                              'Strand order',
                              'Base type']

        self.strutsColorComboBox = \
            PM_ComboBox( strutsGroupBox ,
                         label         =  "Color:",
                         choices       =  strutsColorChoices,
                         setAsDefault  =  True)

    def _loadNucleotidesGroupBox(self):
        """
        Load the Nucleotides group box.
        """
        nucleotidesGroupBox = PM_GroupBox( None )
        self.nucleotidesGroupBox = nucleotidesGroupBox

        nucleotidesShapeChoices = ['None',
                                   'Sugar spheres',
                                   'Base cartoons']

        self.nucleotidesShapeComboBox = \
            PM_ComboBox( nucleotidesGroupBox ,
                         label         =  "Shape:",
                         choices       =  nucleotidesShapeChoices,
                         setAsDefault  =  True)

        self.nucleotidesScaleDoubleSpinBox  =  \
            PM_DoubleSpinBox( nucleotidesGroupBox,
                              label         =  "Scale:",
                              value         =  1.00,
                              setAsDefault  =  True,
                              minimum       =  0.1,
                              maximum       =  3.0,
                              decimals      =  2,
                              singleStep    =  0.1 )

        nucleotidesColorChoices = ['Same as strand',
                                   'Base order',
                                   'Strand order',
                                   'Base type']

        self.nucleotidesColorComboBox = \
            PM_ComboBox( nucleotidesGroupBox ,
                         label         =  "Color:",
                         choices       =  nucleotidesColorChoices,
                         setAsDefault  =  True)

        self.dnaStyleBasesDisplayLettersCheckBox = \
            PM_CheckBox(nucleotidesGroupBox ,
                        text         = 'Display base letters',
                        widgetColumn = 1
                        )

    def updateDnaDisplayStyleWidgets( self , blockSignals = False):
        """
        Updates all the DNA Display style widgets based on the current pref keys
        values.

        @param blockSignals: If its set to True, the set* methods of the
                             the widgets (currently only PM_ Spinboxes and
                             ComboBoxes) won't emit a signal.
        @type blockSignals: bool

        @see: self.show() where this method is called.
        @see: PM_Spinbox.setValue()
        @see: PM_ComboBox.setCurrentIndex()

        @note: This should be called each time the PM is displayed (see show()).
        """

        self.dnaRenditionComboBox.setCurrentIndex(
            env.prefs[dnaRendition_prefs_key],
            blockSignals = blockSignals )

        self.axisShapeComboBox.setCurrentIndex(
            env.prefs[dnaStyleAxisShape_prefs_key], blockSignals = blockSignals)

        self.axisScaleDoubleSpinBox.setValue(
            env.prefs[dnaStyleAxisScale_prefs_key], blockSignals = blockSignals)

        self.axisColorComboBox.setCurrentIndex(
            env.prefs[dnaStyleAxisColor_prefs_key], blockSignals = blockSignals)

        self.axisEndingStyleComboBox.setCurrentIndex(
            env.prefs[dnaStyleAxisEndingStyle_prefs_key], blockSignals = blockSignals)

        self.strandsShapeComboBox.setCurrentIndex(
            env.prefs[dnaStyleStrandsShape_prefs_key], blockSignals = blockSignals)

        self.strandsScaleDoubleSpinBox.setValue(
            env.prefs[dnaStyleStrandsScale_prefs_key], blockSignals = blockSignals)

        self.strandsColorComboBox.setCurrentIndex(
            env.prefs[dnaStyleStrandsColor_prefs_key], blockSignals = blockSignals)

        self.strandsArrowsComboBox.setCurrentIndex(
            env.prefs[dnaStyleStrandsArrows_prefs_key], blockSignals = blockSignals)


        self.strutsShapeComboBox.setCurrentIndex(
            env.prefs[dnaStyleStrutsShape_prefs_key], blockSignals = blockSignals)

        self.strutsScaleDoubleSpinBox.setValue(
            env.prefs[dnaStyleStrutsScale_prefs_key], blockSignals = blockSignals)

        self.strutsColorComboBox.setCurrentIndex(
            env.prefs[dnaStyleStrutsColor_prefs_key], blockSignals = blockSignals)

        self.nucleotidesShapeComboBox.setCurrentIndex(
            env.prefs[dnaStyleBasesShape_prefs_key], blockSignals = blockSignals)

        self.nucleotidesScaleDoubleSpinBox.setValue(
            env.prefs[dnaStyleBasesScale_prefs_key], blockSignals = blockSignals)

        self.nucleotidesColorComboBox.setCurrentIndex(
            env.prefs[dnaStyleBasesColor_prefs_key], blockSignals = blockSignals)

        # DNA Strand label combobox.
        if env.prefs[dnaStrandLabelsEnabled_prefs_key]:
            _dnaStrandColorItem = env.prefs[dnaStrandLabelsColorMode_prefs_key] + 1
        else:
            _dnaStrandColorItem = 0
        self.standLabelColorComboBox.setCurrentIndex(
            _dnaStrandColorItem, blockSignals = blockSignals)

    def change_dnaStrandLabelsDisplay(self, mode):
        """
        Changes DNA Strand labels display (and color) mode.

        @param mode: The display mode:
                    - 0 = hide all labels
                    - 1 = show (same color as chunk)
                    - 2 = show (black)
                    - 3 = show (white)
                    - 4 = show (custom color...)

        @type mode: int
        """
        if mode == 4:
            self.win.userPrefs.change_dnaStrandLabelsColor()

        if mode == 0:
            #@ Fix this at the same time I (we) remove the DNA display style
            #  prefs options from the Preferences dialog. --Mark 2008-05-13
            self.win.userPrefs.toggle_dnaDisplayStrandLabelsGroupBox(False)
        else:
            self.win.userPrefs.toggle_dnaDisplayStrandLabelsGroupBox(True)
            self.win.userPrefs.change_dnaStrandLabelsColorMode(mode - 1)

    def applyFavorite(self):
        """
        Apply the DNA display style settings stored in the current favorite
        (selected in the combobox) to the current DNA display style settings.
        """
        # 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(dnaDisplayStylePrefsList)
        else:
            favfilepath = getFavoritePathFromBasename(current_favorite)
            loadFavoriteFile(favfilepath)

        self.updateDnaDisplayStyleWidgets()
        return

    def addFavorite(self):
        """
        Adds a new favorite to the user's list of favorites.
        """
        # Rules and other info:
        # - The new favorite is defined by the current DNA 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/DnaDisplayStyle/$FAV_NAME.fav).
        # - 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 = writeDnaDisplayStyleSettingsToFavoritesFile(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 = writeDnaDisplayStyleSettingsToFavoritesFile(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):
        """
        Deletes the current favorite from the user's personal list of favorites
        (and from disk, only in the favorites folder though).

        @note: Cannot delete "Factory default settings".
        """
        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):
        """
        Writes the current favorite (selected in the combobox) to a file, any
        where in the disk that
        can be given to another NE1 user (i.e. as an email attachment).
        """

        cmd = greenmsg("Save Favorite File: ")
        env.history.message(greenmsg("Save Favorite File:"))
        current_favorite = self.favoritesComboBox.currentText()
        favfilepath = getFavoritePathFromBasename(current_favorite)
        #Check to see if favfilepath exists first
        if not os.path.exists(favfilepath):
            msg = "%s does not exist" % favfilepath
            env.history.message(cmd + msg)
            return
        formats = \
                    "Favorite (*.txt);;"\
                    "All Files (*.*)"

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

        fn = QFileDialog.getSaveFileName(
            self,
            "Save Favorite As", # caption
            saveLocation, #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):
        """
        [private method]
        Set the working directory in the user preferences database.

        @param workdir: The fullpath directory to write to the user pref db.
        If I{workdir} is None (default), there is no change.
        @type  workdir: string
        """
        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):
        """
        Prompts the user to choose a "favorite file" (i.e. *.txt) from disk to
        be added to the personal favorites list.
        """
        # 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 = writeDnaDisplayStyleSettingsToFavoritesFile(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(dnaDisplayStylePrefsList)

                        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.updateDnaDisplayStyleWidgets()


        return

    def change_dnaRendition(self, rendition):
        """
        Sets the DNA rendition to 3D or one of the optional 2D styles.

        @param rendition: The rendition mode, where:
                          - 0 = 3D (default)
                          - 1 = 2D with base letters
                          - 2 = 2D ball and stick
                          - 3 = 2D ladder
        @type  rendition: int
        """
        if rendition == 0:
            _enabled_flag = True
        else:
            _enabled_flag = False

        self.dnaComponentComboBox.setEnabled(_enabled_flag)
        self.dnaComponentStackedWidget.setEnabled(_enabled_flag)
        self.standLabelColorComboBox.setEnabled(_enabled_flag)

        env.prefs[dnaRendition_prefs_key] = rendition

        self.o.gl_update() # Force redraw

        return

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

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the DNA Property Manager.
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditDnaDisplayStyle_PropertyManager
        ToolTip_EditDnaDisplayStyle_PropertyManager(self)
class EditProtein_PropertyManager(Command_PropertyManager):
    """
    The ProteinDisplayStyle_PropertyManager class provides a Property Manager 
    for the B{Edit Protein} command on the Build Protein command toolbar. 
    
    The selected peptide/protein is displayed in the protein reduced display
    style. The user can select individual rotamers and edit their chi angles.
    This is useful for certain types of protein design protocols using a
    3rd party program like Rosetta.

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

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

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

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

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

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


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

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

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

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

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

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

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

    title         =  "Color Scheme"
    pmName        =  title
    iconPath      =  "ui/actions/View/ColorScheme.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 = "Edit the color scheme for NE1, including the background color, "\
            "hover highlighting and selection colors, etc."
        self.updateMessage(msg)

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

        # 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)

        # background color setting combo box.
        change_connect( self.backgroundColorComboBox,
                      SIGNAL("activated(int)"),
                      self.changeBackgroundColor )

        #hover highlighting style combo box
        change_connect(self.hoverHighlightingStyleComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.changeHoverHighlightingStyle)
        change_connect(self.hoverHighlightingColorComboBox,
                       SIGNAL("editingFinished()"),
                       self.changeHoverHighlightingColor)

        #selection style combo box
        change_connect(self.selectionStyleComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self.changeSelectionStyle)
        change_connect(self.selectionColorComboBox,
                       SIGNAL("editingFinished()"),
                       self.changeSelectionColor)

    def changeHoverHighlightingColor(self):
        """
        Slot method for Hover Highlighting color chooser.
        Change the (3D) hover highlighting color.
        """
        color = self.hoverHighlightingColorComboBox.getColor()
        env.prefs[hoverHighlightingColor_prefs_key] = color
        return

    def changeHoverHighlightingStyle(self, idx):

        """
        Slot method for Hover Highlighting combobox.
        Change the (3D) hover highlighting style.
        """
        env.prefs[hoverHighlightingColorStyle_prefs_key] = HHS_INDEXES[idx]

    def changeSelectionStyle(self, idx):

        """
        Slot method for Selection color style combobox.
        Change the (3D) Selection color style.
        """
        env.prefs[selectionColorStyle_prefs_key] = SS_INDEXES[idx]

    def changeSelectionColor(self):
        """
        Slot method for Selection color chooser.
        Change the (3D) Selection color.
        """
        color = self.selectionColorComboBox.getColor()
        env.prefs[selectionColor_prefs_key] = color
        return

    def show(self):
        """
        Shows the Property Manager. Extends superclass method.
        """
        self._updateAllWidgets()
        _superclass.show(self)

    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 = "Background")
        self._loadGroupBox2( self._pmGroupBox2 )

        self._pmGroupBox3 = PM_GroupBox( self,
                                         title = "Highlighting and Selection")
        self._loadGroupBox3( self._pmGroupBox3 )

        self._updateAllWidgets()

    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/DnaDisplayStyle 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/ColorScheme')


        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)

        # 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/ApplyColorSchemeFavorite.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.
        """
        #background color combo box
        self.backgroundColorComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label     =  "Color:",
                         spanWidth = False)

        self._loadBackgroundColorItems()

        self.enableFogCheckBox = \
            PM_CheckBox( pmGroupBox, text = "Enable fog" )

        connect_checkbox_with_boolean_pref( self.enableFogCheckBox, fogEnabled_prefs_key )
        return

    def _loadGroupBox3(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        # hover highlighting style and color
        self.hoverHighlightingStyleComboBox = \
            PM_ComboBox( pmGroupBox,
                         label     =  "Highlighting:",
                         )

        self._loadHoverHighlightingStyleItems()

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

        self.hoverHighlightingColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                             colorList = hhColorList,
                             colorNames = hhColorNames,
                             color = env.prefs[hoverHighlightingColor_prefs_key]
                             )

        # selection style and color
        self.selectionStyleComboBox = \
            PM_ComboBox( pmGroupBox,
                         label     =  "Selection:",
                         )

        self._loadSelectionStyleItems()

        selColorList = [darkgreen, green, orange, red,
                        magenta, cyan, blue, white, black,
                        gray]
        selColorNames = ["Dark green (default)", "Green", "Orange", "Red",
                         "Magenta", "Cyan", "Blue", "White", "Black",
                         "Other color..."]

        self.selectionColorComboBox = \
            PM_ColorComboBox(pmGroupBox,
                             colorList = selColorList,
                             colorNames = selColorNames,
                             color = env.prefs[selectionColor_prefs_key]
                             )
        return

    def _updateAllWidgets(self):
        """
        Update all the PM widgets. This is typically called after applying
        a favorite.
        """
        self._updateBackgroundColorComboBoxIndex()
        self.updateCustomColorItemIcon(RGBf_to_QColor(env.prefs[backgroundColor_prefs_key]))
        self.hoverHighlightingStyleComboBox.setCurrentIndex(HHS_INDEXES.index(env.prefs[hoverHighlightingColorStyle_prefs_key]))
        self.hoverHighlightingColorComboBox.setColor(env.prefs[hoverHighlightingColor_prefs_key])
        self.selectionStyleComboBox.setCurrentIndex(SS_INDEXES.index(env.prefs[selectionColorStyle_prefs_key]))
        self.selectionColorComboBox.setColor(env.prefs[selectionColor_prefs_key])
        return

    def _loadSelectionStyleItems(self):
        """
        Load the selection color style combobox with items.
        """
        for selectionStyle in SS_OPTIONS:
            self.selectionStyleComboBox.addItem(selectionStyle)
        return

    def _loadHoverHighlightingStyleItems(self):
        """
        Load the hover highlighting style combobox with items.
        """
        for hoverHighlightingStyle in HHS_OPTIONS:
            self.hoverHighlightingStyleComboBox.addItem(hoverHighlightingStyle)
        return

    def _loadBackgroundColorItems(self):
        """
        Load the background color combobox with all the color options and sets
        the current background color
        """
        backgroundIndexes = [bg_BLUE_SKY, bg_EVENING_SKY, bg_SEAGREEN,
                             bg_BLACK, bg_WHITE, bg_GRAY, bg_CUSTOM]

        backgroundNames   = ["Blue Sky (default)", "Evening Sky", "Sea Green",
                             "Black", "White", "Gray", "Custom..."]

        backgroundIcons   = ["Background_BlueSky", "Background_EveningSky",
                             "Background_SeaGreen",
                             "Background_Black",   "Background_White",
                             "Background_Gray",    "Background_Custom"]

        backgroundIconsDict = dict(zip(backgroundNames, backgroundIcons))
        backgroundNamesDict = dict(zip(backgroundIndexes, backgroundNames))

        for backgroundName in backgroundNames:

            basename = backgroundIconsDict[backgroundName] + ".png"
            iconPath = os.path.join("ui/dialogs/Preferences/",
                                    basename)
            self.backgroundColorComboBox.addItem(geticon(iconPath),
                                                 backgroundName)

        self._updateBackgroundColorComboBoxIndex() # Not needed, but OK.
        return

    def _updateBackgroundColorComboBoxIndex(self):
        """
        Set current index in the background color combobox.
        """
        if self.win.glpane.backgroundGradient:
            self.backgroundColorComboBox.setCurrentIndex(self.win.glpane.backgroundGradient - 1)
        else:
            if (env.prefs[ backgroundColor_prefs_key ] == black):
                self.backgroundColorComboBox.setCurrentIndex(bg_BLACK)
            elif (env.prefs[ backgroundColor_prefs_key ] == white):
                self.backgroundColorComboBox.setCurrentIndex(bg_WHITE)
            elif (env.prefs[ backgroundColor_prefs_key ] == gray):
                self.backgroundColorComboBox.setCurrentIndex(bg_GRAY)
            else:
                self.backgroundColorComboBox.setCurrentIndex(bg_CUSTOM)
        return

    def changeBackgroundColor(self, idx):
        """
        Slot method for the background color combobox.
        """
        #print "changeBackgroundColor(): Slot method called. Idx =", idx

        if idx == bg_BLUE_SKY:
            self.win.glpane.setBackgroundGradient(idx + 1)
        elif idx == bg_EVENING_SKY:
            self.win.glpane.setBackgroundGradient(idx + 1)
        elif idx == bg_SEAGREEN:
            self.win.glpane.setBackgroundGradient(idx + 1)
        elif idx == bg_BLACK:
            self.win.glpane.setBackgroundColor(black)
        elif idx == bg_WHITE:
            self.win.glpane.setBackgroundColor(white)
        elif idx == bg_GRAY:
            self.win.glpane.setBackgroundColor(gray)
        elif idx == bg_CUSTOM:
            #change background color to Custom Color
            self.chooseCustomBackgroundColor()
        else:
            msg = "Unknown color idx=", idx
            print_compact_traceback(msg)

        self.win.glpane.gl_update() # Needed!
        return

    def chooseCustomBackgroundColor(self):
        """
        Choose a custom background color.
        """
        c = QColorDialog.getColor(RGBf_to_QColor(self.win.glpane.getBackgroundColor()), self)
        if c.isValid():
            self.win.glpane.setBackgroundColor(QColor_to_RGBf(c))
            self.updateCustomColorItemIcon(c)
        else:
            # User cancelled. Need to reset combobox to correct index.
            self._updateBackgroundColorComboBoxIndex()
        return

    def updateCustomColorItemIcon(self, qcolor):
        """
        Update the custom color item icon in the background color combobox
        with I{qcolor}.
        """
        pixmap = QPixmap(16, 16)
        pixmap.fill(qcolor)
        self.backgroundColorComboBox.setItemIcon(bg_CUSTOM, QIcon(pixmap))
        return

    def applyFavorite(self):
        """
        Apply the color scheme settings stored in the current favorite
        (selected in the combobox) to the current color scheme settings.
        """
        # 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(colorSchemePrefsList)
            # set it back to blue sky
            self.win.glpane.setBackgroundGradient(1)
        else:
            favfilepath = getFavoritePathFromBasename(current_favorite)
            loadFavoriteFile(favfilepath)
            if env.prefs[backgroundGradient_prefs_key]:
                self.win.glpane.setBackgroundGradient(env.prefs[backgroundGradient_prefs_key])
            else:
                self.win.glpane.setBackgroundColor(env.prefs[backgroundColor_prefs_key])
        #self.hoverHighlightingColorComboBox.setColor(env.prefs[hoverHighlightingColor_prefs_key])
        #self.selectionColorComboBox.setColor(env.prefs[selectionColor_prefs_key])
        self._updateAllWidgets()
        self.win.glpane.gl_update()
        return

    def addFavorite(self):
        """
        Adds a new favorite to the user's list of favorites.
        """
        # Rules and other info:
        # - The new favorite is defined by the current color scheme
        #    settings.

        # - The user is prompted to type in a name for the new
        #    favorite.
        # - The color scheme settings are written to a file in a special
        #    directory on the disk
        # (i.e. $HOME/Nanorex/Favorites/ColorScheme/$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/ColorScheme/ 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 = writeColorSchemeToFavoritesFile(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 = writeColorSchemeToFavoritesFile(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):
        """
        Deletes the current favorite from the user's personal list of favorites
        (and from disk, only in the favorites folder though).

        @note: Cannot delete "Factory default settings".
        """
        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):
        """
        Writes the current favorite (selected in the combobox) to a file, any
        where in the disk that
        can be given to another NE1 user (i.e. as an email attachment).
        """

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

        #Check to see if favfilepath exists first
        if not os.path.exists(favfilepath):
            msg = "%s does not exist" % favfilepath
            env.history.message(cmd + msg)
            return
        formats = \
                    "Favorite (*.txt);;"\
                    "All Files (*.*)"

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

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

        else:
            #remember this directory

            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):
        """
        [private method]
        Set the working directory in the user preferences database.

        @param workdir: The fullpath directory to write to the user pref db.
        If I{workdir} is None (default), there is no change.
        @type  workdir: string
        """
        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):
        """
        Prompts the user to choose a "favorite file" (i.e. *.txt) from disk to
        be added to the personal favorites list.
        """
        # 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 = writeColorSchemeToFavoritesFile(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(colorSchemePrefsList)

                        # set it back to blue sky
                        self.win.glpane.setBackgroundGradient(1)
                        self.win.glpane.gl_update()
                        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)

                if env.prefs[backgroundGradient_prefs_key]:
                    self.win.glpane.setBackgroundGradient(env.prefs[backgroundGradient_prefs_key])
                else:
                    self.win.glpane.setBackgroundColor(env.prefs[backgroundColor_prefs_key])
                self.win.glpane.gl_update()
        return

    def _addWhatsThisText( self ):
        """
        What's This text for widgets in the Color Scheme Property Manager.
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_ColorScheme_PropertyManager
        WhatsThis_ColorScheme_PropertyManager(self)

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the Color Scheme Property Manager.
        """
        #modify this for color schemes
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_ColorScheme_PropertyManager
        ToolTip_ColorScheme_PropertyManager(self)
class LightingScheme_PropertyManager(PM_Dialog, DebugMenuMixin):
    """
    The LightingScheme_PropertyManager class provides a Property Manager 
    for changing light properties as well as material properties.

    @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 = "Lighting Scheme"
    pmName = title
    iconPath = "ui/actions/View/LightingScheme.png"

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

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

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

        DebugMenuMixin._init1(self)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

        msg = "Edit the lighting scheme for NE1. Includes turning lights on and off, "\
            "changing light colors, changing the position of lights as well as,"\
            "changing the ambient, diffuse, and specular properites."
        self.updateMessage(msg)

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

        # 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)

        # Directional Lighting Properties
        change_connect(self.ambientDoubleSpinBox,
                       SIGNAL("valueChanged(double)"), self.change_lighting)
        change_connect(self.lightColorComboBox, SIGNAL("editingFinished()"),
                       self.changeLightColor)
        change_connect(self.enableLightCheckBox, SIGNAL("toggled(bool)"),
                       self.toggle_light)
        change_connect(self.lightComboBox, SIGNAL("activated(int)"),
                       self.change_active_light)
        change_connect(self.diffuseDoubleSpinBox,
                       SIGNAL("valueChanged(double)"), self.change_lighting)
        change_connect(self.specularDoubleSpinBox,
                       SIGNAL("valueChanged(double)"), self.change_lighting)
        change_connect(self.xDoubleSpinBox, SIGNAL("editingFinished()"),
                       self.save_lighting)
        change_connect(self.yDoubleSpinBox, SIGNAL("editingFinished()"),
                       self.save_lighting)
        change_connect(self.zDoubleSpinBox, SIGNAL("editingFinished()"),
                       self.save_lighting)
        # Material Specular Properties
        change_connect(self.brightnessDoubleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.change_material_brightness)
        change_connect(self.finishDoubleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.change_material_finish)
        change_connect(self.enableMaterialPropertiesComboBox,
                       SIGNAL("toggled(bool)"),
                       self.toggle_material_specularity)
        change_connect(self.shininessDoubleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.change_material_shininess)
        self._setup_material_group()
        return

    def _updatePage_Lighting(self, lights=None):  #mark 051124
        """
        Setup widgets to initial (default or defined) values on the Lighting page.
        """
        if not lights:
            self.lights = self.original_lights = self.win.glpane.getLighting()
        else:
            self.lights = lights

        light_num = self.lightComboBox.currentIndex()

        # Move lc_prefs_keys upstairs.  Mark.
        lc_prefs_keys = [
            light1Color_prefs_key, light2Color_prefs_key, light3Color_prefs_key
        ]
        self.current_light_key = lc_prefs_keys[
            light_num]  # Get prefs key for current light color.
        self.lightColorComboBox.setColor(env.prefs[self.current_light_key])
        self.light_color = env.prefs[self.current_light_key]

        # These sliders generate signals whenever their 'setValue()' slot is called (below).
        # This creates problems (bugs) for us, so we disconnect them temporarily.
        self.disconnect(self.ambientDoubleSpinBox,
                        SIGNAL("valueChanged(double)"), self.change_lighting)
        self.disconnect(self.diffuseDoubleSpinBox,
                        SIGNAL("valueChanged(double)"), self.change_lighting)
        self.disconnect(self.specularDoubleSpinBox,
                        SIGNAL("valueChanged(double)"), self.change_lighting)

        # self.lights[light_num][0] contains 'color' attribute.
        # We already have it (self.light_color) from the prefs key (above).
        a = self.lights[light_num][1]  # ambient intensity
        d = self.lights[light_num][2]  # diffuse intensity
        s = self.lights[light_num][3]  # specular intensity
        g = self.lights[light_num][4]  # xpos
        h = self.lights[light_num][5]  # ypos
        k = self.lights[light_num][6]  # zpos

        self.ambientDoubleSpinBox.setValue(a)  # generates signal
        self.diffuseDoubleSpinBox.setValue(d)  # generates signal
        self.specularDoubleSpinBox.setValue(s)  # generates signal
        self.xDoubleSpinBox.setValue(g)  # generates signal
        self.yDoubleSpinBox.setValue(h)  # generates signal
        self.zDoubleSpinBox.setValue(k)  # generates signal

        self.enableLightCheckBox.setChecked(self.lights[light_num][7])

        # Reconnect the slots to the light sliders.
        self.connect(self.ambientDoubleSpinBox, SIGNAL("valueChanged(double)"),
                     self.change_lighting)
        self.connect(self.diffuseDoubleSpinBox, SIGNAL("valueChanged(double)"),
                     self.change_lighting)
        self.connect(self.specularDoubleSpinBox,
                     SIGNAL("valueChanged(double)"), self.change_lighting)

        self.update_light_combobox_items()
        self.save_lighting()
        self._setup_material_group()
        return

    def _setup_material_group(self, reset=False):
        """
        Setup Material Specularity widgets to initial (default or defined) values on the Lighting page.
        If reset = False, widgets are reset from the prefs db.
        If reset = True, widgets are reset from their previous values.
        """

        if reset:
            self.material_specularity = self.original_material_specularity
            self.whiteness = self.original_whiteness
            self.shininess = self.original_shininess
            self.brightness = self.original_brightness
        else:
            self.material_specularity = self.original_material_specularity = \
                env.prefs[material_specular_highlights_prefs_key]
            self.whiteness = self.original_whiteness = \
                env.prefs[material_specular_finish_prefs_key]
            self.shininess = self.original_shininess = \
                env.prefs[material_specular_shininess_prefs_key]
            self.brightness = self.original_brightness= \
                env.prefs[material_specular_brightness_prefs_key]

        # Enable/disable material specularity properites.
        self.enableMaterialPropertiesComboBox.setChecked(
            self.material_specularity)

        # For whiteness, the stored range is 0.0 (Plastic) to 1.0 (Metal).
        self.finishDoubleSpinBox.setValue(self.whiteness)  # generates signal

        # For shininess, the range is 15 (low) to 60 (high).  Mark. 051129.
        self.shininessDoubleSpinBox.setValue(
            self.shininess)  # generates signal

        # For brightness, the range is 0.0 (low) to 1.0 (high).  Mark. 051203.
        self.brightnessDoubleSpinBox.setValue(
            self.brightness)  # generates signal
        return

    def toggle_material_specularity(self, val):
        """
        This is the slot for the Material Specularity Enabled checkbox.
        """
        env.prefs[material_specular_highlights_prefs_key] = val

    def change_material_finish(self, finish):
        """
        This is the slot for the Material Finish spin box.
        'finish' is between 0.0 and 1.0. 
        Saves finish parameter to pref db.
        """
        # For whiteness, the stored range is 0.0 (Metal) to 1.0 (Plastic).
        env.prefs[material_specular_finish_prefs_key] = finish

    def change_material_shininess(self, shininess):
        """
        This is the slot for the Material Shininess spin box.
        'shininess' is between 15 (low) and 60 (high).
        """
        env.prefs[material_specular_shininess_prefs_key] = shininess

    def change_material_brightness(self, brightness):
        """
        This is the slot for the Material Brightness sping box.
        'brightness' is between 0.0 (low) and 1.0 (high).
        """
        env.prefs[material_specular_brightness_prefs_key] = brightness

    def toggle_light(self, on):
        """
        Slot for light 'On' checkbox.  
        It updates the current item in the light combobox with '(On)' or 
        '(Off)' label.
        """
        if on:
            txt = "%d (On)" % (self.lightComboBox.currentIndex() + 1)
        else:
            txt = "%d (Off)" % (self.lightComboBox.currentIndex() + 1)
        self.lightComboBox.setItemText(self.lightComboBox.currentIndex(), txt)

        self.save_lighting()

    def change_lighting(self, specularityValueJunk=None):
        """
	Updates win.glpane lighting using the current lighting parameters from 
	the light checkboxes and sliders. This is also the slot for the light 
	spin boxes.
	@param specularityValueJunk: This value from the spin box is not used
				     We are interested in valueChanged signal 
				     only
        @type specularityValueJunk = int or None

        """

        light_num = self.lightComboBox.currentIndex()

        light1, light2, light3 = self.win.glpane.getLighting()

        a = self.ambientDoubleSpinBox.value()
        d = self.diffuseDoubleSpinBox.value()
        s = self.specularDoubleSpinBox.value()
        g = self.xDoubleSpinBox.value()
        h = self.yDoubleSpinBox.value()
        k = self.zDoubleSpinBox.value()

        new_light = [  self.light_color, a, d, s, g, h, k,\
                       self.enableLightCheckBox.isChecked()]

        # This is a kludge.  I'm certain there is a more elegant way.  Mark 051204.
        if light_num == 0:
            self.win.glpane.setLighting([new_light, light2, light3])
        elif light_num == 1:
            self.win.glpane.setLighting([light1, new_light, light3])
        elif light_num == 2:
            self.win.glpane.setLighting([light1, light2, new_light])
        else:
            print "Unsupported light # ", light_num, ". No lighting change made."

    def change_active_light(self, currentIndexJunk=None):
        """
	Slot for the Light number combobox.  This changes the current light.
	@param currentIndexJunk: This index value from the combobox is not used
				 We are interested in 'activated' signal only
        @type currentIndexJunk = int or None
        """
        self._updatePage_Lighting()

    def reset_lighting(self):
        """
        Slot for Reset button.
        """
        # This has issues.
        # I intend to remove the Reset button for A7.  Confirm with Bruce.  Mark 051204.
        self._setup_material_group(reset=True)
        self._updatePage_Lighting(self.original_lights)
        self.win.glpane.saveLighting()

    def save_lighting(self):
        """
        Saves lighting parameters (but not material specularity parameters) 
        to pref db. This is also the slot for light sliders (only when 
        released).
        """
        self.change_lighting()
        self.win.glpane.saveLighting()

    def restore_default_lighting(self):
        """
        Slot for Restore Defaults button.
        """

        self.win.glpane.restoreDefaultLighting()

        # Restore defaults for the Material Specularity properties
        env.prefs.restore_defaults([
            material_specular_highlights_prefs_key,
            material_specular_shininess_prefs_key,
            material_specular_finish_prefs_key,
            material_specular_brightness_prefs_key,  #bruce 051203 bugfix
        ])

        self._updatePage_Lighting()
        self.save_lighting()

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

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

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

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

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

        self._pmGroupBox2 = PM_GroupBox(self, title="Directional Lights")
        self._loadGroupBox2(self._pmGroupBox2)

        self._pmGroupBox3 = PM_GroupBox(self, title="Material Properties")
        self._loadGroupBox3(self._pmGroupBox3)

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        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/LightingScheme')

        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)

        # 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/ApplyLightingSchemeFavorite.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.
        """

        self.lightComboBox  = \
            PM_ComboBox( pmGroupBox,
                         choices = ["1", "2", "3"],
                         label     =  "Light:")

        self.enableLightCheckBox = \
            PM_CheckBox( pmGroupBox, text = "On" )

        self.lightColorComboBox = \
            PM_ColorComboBox(pmGroupBox)
        self.ambientDoubleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             maximum = 1.0,
                             minimum = 0.0,
                             decimals = 2,
                             singleStep = .1,
                             label = "Ambient:")
        self.diffuseDoubleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             maximum = 1.0,
                             minimum = 0.0,
                             decimals = 2,
                             singleStep = .1,
                             label = "Diffuse:")
        self.specularDoubleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             maximum = 1.0,
                             minimum = 0.0,
                             decimals = 2,
                             singleStep = .1,
                             label = "Specular:")

        self.positionGroupBox = \
            PM_GroupBox( pmGroupBox,
                         title = "Position:")

        self.xDoubleSpinBox = \
            PM_DoubleSpinBox(self.positionGroupBox,
                             maximum = 1000,
                             minimum = -1000,
                             decimals = 1,
                             singleStep = 10,
                             label = "X:")
        self.yDoubleSpinBox = \
            PM_DoubleSpinBox(self.positionGroupBox,
                             maximum = 1000,
                             minimum = -1000,
                             decimals = 1,
                             singleStep = 10,
                             label = "Y:")
        self.zDoubleSpinBox = \
            PM_DoubleSpinBox(self.positionGroupBox,
                             maximum = 1000,
                             minimum = -1000,
                             decimals = 1,
                             singleStep = 10,
                             label = "Z:")
        return

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

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

    def _updateAllWidgets(self):
        """
        Update all the PM widgets. This is typically called after applying
        a favorite.
        """
        self._updatePage_Lighting()
        return

    def update_light_combobox_items(self):
        """
        Updates all light combobox items with '(On)' or '(Off)' label.
        """
        for i in range(3):
            if self.lights[i][7]:
                txt = "%d (On)" % (i + 1)
            else:
                txt = "%d (Off)" % (i + 1)
            self.lightComboBox.setItemText(i, txt)
        return

    def changeLightColor(self):
        """
        Slot method for the ColorComboBox
        """
        color = self.lightColorComboBox.getColor()
        env.prefs[self.current_light_key] = color
        self.light_color = env.prefs[self.current_light_key]
        self.save_lighting()
        return

    def applyFavorite(self):
        """
        Apply the lighting scheme settings stored in the current favorite 
        (selected in the combobox) to the current lighting scheme settings.
        """
        # 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(lightingSchemePrefsList)
            self.restore_default_lighting()
        else:
            favfilepath = getFavoritePathFromBasename(current_favorite)
            loadFavoriteFile(favfilepath)
        self._updateAllWidgets()
        self.win.glpane.gl_update()
        return

    def addFavorite(self):
        """
        Adds a new favorite to the user's list of favorites.
        """
        # Rules and other info:
        # - The new favorite is defined by the current lighting scheme
        #    settings.

        # - The user is prompted to type in a name for the new
        #    favorite.
        # - The lighting scheme settings are written to a file in a special
        #    directory on the disk
        # (i.e. $HOME/Nanorex/Favorites/LightingScheme/$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/LightingScheme/ 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 = writeLightingSchemeToFavoritesFile(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 = writeLightingSchemeToFavoritesFile(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):
        """
        Deletes the current favorite from the user's personal list of favorites
        (and from disk, only in the favorites folder though).
        
        @note: Cannot delete "Factory default settings".
        """
        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):
        """
        Writes the current favorite (selected in the combobox) to a file, any 
        where in the disk that 
        can be given to another NE1 user (i.e. as an email attachment).
        """

        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 (*.*)"

        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:
            saveFavoriteFile(str(fn), favfilepath)
        return

    def loadFavorite(self):
        """
        Prompts the user to choose a "favorite file" (i.e. *.txt) from disk to
        be added to the personal favorites list.
        """
        # 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 = getDefaultWorkingDirectory()

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

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

        else:
            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 = writeLightingSchemeToFavoritesFile(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(lightingSchemePrefsList)
                        self.win.glpane.gl_update()
                        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.win.glpane.gl_update()
        return

    #def _addWhatsThisText( self ):
    #"""
    #What's This text for widgets in the Lighting Scheme Property Manager.
    #"""
    #from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_LightingScheme_PropertyManager
    #WhatsThis_LightingScheme_PropertyManager(self)

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the Lighting Scheme Property Manager.  
        """
        #modify this for lighting schemes
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_LightingScheme_PropertyManager
        ToolTip_LightingScheme_PropertyManager(self)
Example #23
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)
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        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/LightingScheme')

        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)

        # 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/ApplyLightingSchemeFavorite.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 _loadCrystalSpecsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Crystal Specifications group box.
        @param inPmGroupBox: The Crystal Specifications groupbox in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        latticeChoices = ["Diamond", "Lonsdaleite"]

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

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

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

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

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

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

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

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

        self.gridRotateButtonRow = \
            PM_ToolButtonRow( inPmGroupBox,
                              title        = "",
                              buttonList   = GRID_ANGLE_BUTTONS,
                              label        = 'Rotate grid:',
                              isAutoRaise  =  False,
                              isCheckable  =  False
                            )
        self.rotGridAntiClockwiseButton = \
            self.gridRotateButtonRow.getButtonById(0)
        self.rotGridClockwiseButton = \
            self.gridRotateButtonRow.getButtonById(1)
Example #26
0
class PlanePropertyManager(EditCommand_PM):
    """
    The PlanePropertyManager class provides a Property Manager for a 
    (reference) Plane.

    """

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

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

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

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

        EditCommand_PM.__init__(self, win, planeEditCommand)



        msg = "Insert a Plane parallel to the screen. Note: This feature is "\
            "experimental for Alpha9 and has known bugs."

        # This causes the "Message" box to be displayed as well.
        self.updateMessage(msg)

        # self.resized_from_glpane flag makes sure that the
        #spinbox.valueChanged()
        # signal is not emitted after calling spinbox.setValue.
        self.resized_from_glpane = False

        # Hide Preview and Restore defaults button for Alpha9.
        self.hideTopRowButtons(PM_RESTORE_DEFAULTS_BUTTON)
        # needed to figure out if the model has changed or not
        self.previousPMParams = None
        self.gridColor = black
        self.gridXSpacing = 4.0
        self.gridYSpacing = 4.0
        self.gridLineType = 3
        self.displayLabels = False
        self.originLocation = LOWER_LEFT
        self.displayLabelStyle = LABELS_ALONG_ORIGIN

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

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

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

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

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

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

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

        connect_checkbox_with_boolean_pref(self.gridPlaneCheckBox,
                                           PlanePM_showGrid_prefs_key)


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

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

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

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

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

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

        self.pmGroupBox5 = PM_GroupBox(pmGroupBox)

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

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

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

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

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

        self._showHideGPWidgets()

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

        return

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

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

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

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

        self.isAlreadyConnected = isConnect
        self.isAlreadyDisconnected = not isConnect

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self._connect_checkboxes_to_global_prefs_keys()

        return

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

        connect_checkbox_with_boolean_pref(self.gpDisplayLabels,
                                           PlanePM_showGridLabels_prefs_key)

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

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

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

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

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

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

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

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

        return

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

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

        return

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

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

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

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

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

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

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

        self.imageChangeButtonGroup.buttonGroup.setExclusive(False)

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

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

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

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

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

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

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

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

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

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



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



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


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

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

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

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

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

        self.editCommand.struct.glpane.gl_update()

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

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

    def toggleTexture(self, checked):
        """
        Enables texturing in 3D relief mode.
        """
        if self.editCommand and self.editCommand.struct:
            plane = self.editCommand.struct
            plane.heightfield_use_texture = checked
            #if plane.display_heightfield and plane.image:
            #    plane.computeHeightfield()
            plane.glpane.gl_update()

    def update_spinboxes(self):
        """ 	 
	Update the width and height spinboxes. 	 
        @see: Plane.resizeGeometry()
	"""
        # self.resized_from_glpane flag makes sure that the
        # spinbox.valueChanged()
        # signal is not emitted after calling spinbox.setValue().
        # This flag is used in change_plane_size method.-- Ninad 20070601
        if self.editCommand and self.editCommand.hasValidStructure():
            self.resized_from_glpane = True
            self.heightDblSpinBox.setValue(self.editCommand.struct.height)
            self.widthDblSpinBox.setValue(self.editCommand.struct.width)
            self.win.glpane.gl_update()
            self.resized_from_glpane = False

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

        self.mirrorButton.setEnabled(False)
        self.plusNinetyButton.setEnabled(False)
        self.minusNinetyButton.setEnabled(False)
        self.flipButton.setEnabled(False)
        self.heightfieldDisplayCheckBox.setEnabled(False)
        self.heightfieldHQDisplayCheckBox.setEnabled(False)
        self.heightfieldTextureCheckBox.setEnabled(False)
        self.vScaleSpinBox.setEnabled(False)

        plane = self.editCommand.struct
        plane.deleteImage()
        plane.heightfield = None
        plane.display_image = self.imageDisplayCheckBox.isChecked()

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

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

            if validPath:
                from PIL import Image

                plane.image = Image.open(imageFile)
                plane.loadImage(imageFile)

                plane.computeHeightfield()

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

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

        if self.editCommand.struct:

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

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

        # self.resized_from_glpane flag makes sure that the
        # spinbox.valueChanged()
        # signal is not emitted after calling spinbox.setValue().
        # This flag is used in change_plane_size method.-- Ninad 20070601
        self.resized_from_glpane = True
        self.widthDblSpinBox.setValue(width)
        self.heightDblSpinBox.setValue(height)
        self.win.glpane.gl_update()
        self.resized_from_glpane = False

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

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

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

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

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

        return params

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

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

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

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

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

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

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

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

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

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

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

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

        self.aspectRatioSpinBox.setEnabled(enable)

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

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

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

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

        EditCommand_PM.update_props_if_needed_before_closing(self)

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

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

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

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

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

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

    def mirror_image(self):
        """
        Flip the image vertically.
        """
        if self.editCommand.hasValidStructure():
            self.editCommand.struct.mirrorImage(0)
        return
 def _loadFreeDragTranslateGroupBox(self, inPmGroupBox):
     """
     Load widgets in the Free Drag Translate group box, which is present 
     within the Translate groupbox.
     @param inPmGroupBox: The Free Drag Translate group box in the Translate 
                          group box. 
     @type  inPmGroupBox: L{PM_GroupBox}
     """
     # Button list to create a toolbutton row.
     # Format: 
     # - buttonId, 
     # - buttonText , 
     # - iconPath
     # - tooltip
     # - shortcut
     # - column
     
      
     BUTTON_LIST = [ 
         ( "QToolButton", 1,  "MOVEDEFAULT", 
           "ui/actions/Properties Manager/Move_Free.png", "", "F", 0),
         ( "QToolButton", 2,  "TRANSX", 
           "ui/actions/Properties Manager/TranslateX.png", "", "X", 1),
         ( "QToolButton", 3,  "TRANSY",  
           "ui/actions/Properties Manager/TranslateY.png", "", "Y", 2),
         ( "QToolButton", 4,  "TRANSZ",  
           "ui/actions/Properties Manager/TranslateZ.png", "", "Z", 3),
         ( "QToolButton", 5,  "ROT_TRANS_ALONG_AXIS",  
           "ui/actions/Properties Manager/translate+rotate-A.png", "", \
           "A", 4)
                     
         ]
         
     self.freeDragTranslateButtonGroup = \
         PM_ToolButtonRow( inPmGroupBox, 
                            title        = "",
                            buttonList   = BUTTON_LIST,
                            checkedId    = 1,
                            setAsDefault = True,
                            )
     self.transFreeButton =self.freeDragTranslateButtonGroup.getButtonById(1)
     self.transXButton = self.freeDragTranslateButtonGroup.getButtonById(2)
     self.transYButton = self.freeDragTranslateButtonGroup.getButtonById(3)
     self.transZButton = self.freeDragTranslateButtonGroup.getButtonById(4)
     self.transAlongAxisButton = \
         self.freeDragTranslateButtonGroup.getButtonById(5)
     
     self.moveFromToButton = PM_ToolButton(
                 inPmGroupBox, 
                 text = "Translate from/to",
                 iconPath  = "ui/actions/Properties Manager"\
                 "/Translate_Components.png",
                 spanWidth = True
                 
                 )
     self.moveFromToButton.setCheckable(True)
     self.moveFromToButton.setAutoRaise(True)
     self.moveFromToButton.setToolButtonStyle(
         Qt.ToolButtonTextBesideIcon)
     
     
     self.startCoordLineEdit = PM_LineEdit( 
         inPmGroupBox, 
         label        = "ui/actions/Properties Manager"\
                 "/Move_Start_Point.png",
         text         = "Define 'from' and 'to' points",
         setAsDefault = False,
         )
     self.startCoordLineEdit.setReadOnly(True)
     self.startCoordLineEdit.setEnabled(False)
Example #28
0
    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in the image group box.

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

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

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

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

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

        self.imageChangeButtonGroup.buttonGroup.setExclusive(False)

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

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

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

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

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

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

        self.heightfieldDisplayCheckBox.setEnabled(False)
        self.heightfieldHQDisplayCheckBox.setEnabled(False)
        self.heightfieldTextureCheckBox.setEnabled(False)
        self.vScaleSpinBox.setEnabled(False)
 def _loadFreeDragRotateGroupBox(self, inPmGroupBox):
     """
     Load widgets in the Free Drag Rotate group box, which is 
     present within the Rotate groupbox.
     @param inPmGroupBox: The Free Drag Rotate group box in the Rotate 
                          group box.
     @type  inPmGroupBox: L{PM_GroupBox}
     """
     # Button list to create a toolbutton row.
     # Format: 
     # - buttonId, 
     # - buttonText , 
     # - iconPath
     # - tooltip
     # - shortcut
     # - column
     
     BUTTON_LIST = [ 
         ( "QToolButton", 1,  "ROTATEDEFAULT", 
           "ui/actions/Properties Manager/Rotate_Free.png", "", "F", 0 ),
         
         ( "QToolButton", 2,  "ROTATEX", 
           "ui/actions/Properties Manager/RotateX.png", "", "X", 1 ),
         
         ( "QToolButton", 3,  "ROTATEY",  
           "ui/actions/Properties Manager/RotateY.png", "", "Y", 2 ),
         
         ( "QToolButton", 4,  "ROTATEZ",  
           "ui/actions/Properties Manager/RotateZ.png", "", "Z", 3 ),
         
         ( "QToolButton", 5,  "ROT_TRANS_ALONG_AXIS",  
           "ui/actions/Properties Manager/translate+rotate-A.png", "", \
           "A", 4 )
                     
         ]
         
     self.freeDragRotateButtonGroup = \
         PM_ToolButtonRow( inPmGroupBox, 
                            title        = "",
                            buttonList   = BUTTON_LIST,
                            spanWidth = True,
                            checkedId    = 1,
                            setAsDefault = True,
                         )
             
     self.rotateFreeButton = self.freeDragRotateButtonGroup.getButtonById(1)
     self.rotateXButton    = self.freeDragRotateButtonGroup.getButtonById(2)
     self.rotateYButton    = self.freeDragRotateButtonGroup.getButtonById(3)
     self.rotateZButton    = self.freeDragRotateButtonGroup.getButtonById(4)
     self.rotAlongAxisButton = \
         self.freeDragRotateButtonGroup.getButtonById(5)
     
     inPmGroupBox.setStyleSheet(
         self.freeDragRotateButtonGroup._getStyleSheet())
             
     X_ROW_LABELS = [("QLabel", "Delta Theta X:", 0),
                     ("QLabel", "", 1),
                     ("QLabel", "0.00", 2),
                     ("QLabel", "Degrees", 3)]
     
     Y_ROW_LABELS = [("QLabel", "Delta Theta Y:", 0),
                     ("QLabel", "", 1),
                     ("QLabel", "0.00", 2),
                     ("QLabel", "Degrees", 3)]
     
     Z_ROW_LABELS = [("QLabel", "Delta Theta Z:", 0),
                     ("QLabel", "", 1),
                     ("QLabel", "0.00", 2),
                     ("QLabel", "Degrees", 3)]
     
     self.rotateXLabelRow = PM_LabelRow( inPmGroupBox,
                                         title = "",
                                         labelList = X_ROW_LABELS )  
     self.deltaThetaX_lbl = self.rotateXLabelRow.labels[2]
                                        
     self.rotateYLabelRow = PM_LabelRow( inPmGroupBox,
                                         title = "",
                                         labelList = Y_ROW_LABELS )
     self.deltaThetaY_lbl = self.rotateYLabelRow.labels[2]
                                       
     self.rotateZLabelRow = PM_LabelRow( inPmGroupBox,
                                         title = "",
                                         labelList = Z_ROW_LABELS )  
     self.deltaThetaZ_lbl = self.rotateZLabelRow.labels[2]    
     
     self.rotateAboutPointButton = PM_ToolButton(
                 inPmGroupBox, 
                 text = "Rotate selection about a point",
                 iconPath  = "ui/actions/Properties Manager"\
                 "/Rotate_Components.png",
                 spanWidth = True                    
                 )
     self.rotateAboutPointButton.setCheckable(True)
     self.rotateAboutPointButton.setAutoRaise(True)
     self.rotateAboutPointButton.setToolButtonStyle(
         Qt.ToolButtonTextBesideIcon)
     
     
     self.rotateStartCoordLineEdit = PM_LineEdit( 
         inPmGroupBox, 
         label        = "ui/actions/Properties Manager"\
                 "/Move_Start_Point.png",
         text         = "Define 3 points",
         setAsDefault = False,
         )
     self.rotateStartCoordLineEdit.setReadOnly(True)
     self.rotateStartCoordLineEdit.setEnabled(False)
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)
    def _loadBySpecifiedAngleGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Rotate By Specified Angle group box, which is 
        present within the Rotate groupbox.
        @param inPmGroupBox: Rotate By Specified Angle group box in the Rotate 
                             group box.
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        # Button list to create a toolbutton row.
        # Format: 
        # - buttonId, 
        # - buttonText , 
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        
        BUTTON_LIST = [ 
            ( "QToolButton", 1,  "ROTATEX", 
              "ui/actions/Properties Manager/RotateX.png", 
              "Rotate about X axis", "X", 0 ),
            
            ( "QToolButton", 2,  "ROTATEY",  
              "ui/actions/Properties Manager/RotateY.png", 
              "Rotate about Y axis", "Y", 1 ),
            
            ( "QToolButton", 3,  "ROTATEZ",  
              "ui/actions/Properties Manager/RotateZ.png", 
              "Rotate about Z axis","Z", 2 ),
            ]
        
        
        
        self.rotateAroundAxisButtonRow = \
            PM_ToolButtonRow( inPmGroupBox, 
                              title        = "",
                              buttonList   = BUTTON_LIST,
                              alignment    = 'Right',
                              label        = 'Rotate Around:'
                            )
        self.rotXaxisButton = \
            self.rotateAroundAxisButtonRow.getButtonById(1)
        
        self.rotYaxisButton = \
            self.rotateAroundAxisButtonRow.getButtonById(2)
        
        self.rotZaxisButton = \
            self.rotateAroundAxisButtonRow.getButtonById(3)
        
        

        self.rotateThetaSpinBox = \
            PM_DoubleSpinBox(inPmGroupBox,
                             label        = "Rotate By:",
                             value        = 0.0, 
                             setAsDefault = True,
                             minimum      = 0, 
                             maximum      = 360.0,
                             singleStep   = 1.0, 
                             decimals     = 2, 
                             suffix       = ' Degrees')
        
        
        THETA_BUTTONS = [ 
            ( "QToolButton", 1,  "Theta Plus", 
              "ui/actions/Properties Manager/Move_Theta_Plus.png", "", "+", 0 ),
            
            ( "QToolButton", 2,  "Theta Minus",  
              "ui/actions/Properties Manager/Move_Theta_Minus.png", "", "-", 1 )
            ]
        
        self.rotateThetaButtonRow = \
            PM_ToolButtonRow( inPmGroupBox, 
                              title        = "",
                              buttonList   = THETA_BUTTONS,
                              label        = 'Direction:',
                              isAutoRaise  =  True,
                              isCheckable  =  False                           
                            )
        self.rotateThetaPlusButton =  self.rotateThetaButtonRow.getButtonById(1)
        self.rotateThetaMinusButton = self.rotateThetaButtonRow.getButtonById(2)
    def _loadCrystalSpecsGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Crystal Specifications group box.
        @param inPmGroupBox: The Crystal Specifications groupbox in the PM
        @type  inPmGroupBox: L{PM_GroupBox}
        """
        latticeChoices = ["Diamond", "Lonsdaleite"]

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

        # Button list to create a toolbutton row.
        # Format:
        # - buttonType,
        # - buttonId,
        # - buttonText ,
        # - iconPath
        # - tooltip
        # - shortcut
        # - column
        BUTTON_LIST = [("QToolButton", 0, "Surface 100",
                        "ui/actions/Properties Manager/Surface100.png",
                        "Surface 100", "", 0),
                       ("QToolButton", 1, "Surface 110",
                        "ui/actions/Properties Manager/Surface110.png",
                        "Surface 110", "", 1),
                       ("QToolButton", 2, "Surface 111",
                        "ui/actions/Properties Manager/Surface111.png",
                        "Surface 110", "", 2)]
        self.gridOrientationButtonRow = \
            PM_ToolButtonRow(inPmGroupBox,
                               title        = "",
                               label        = "Orientation:",
                               buttonList   = BUTTON_LIST,
                               checkedId    = 0,
                               setAsDefault = True,
                               spanWidth   = False
                               )

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

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

        GRID_ANGLE_BUTTONS = [
            ("QToolButton", 0, "Anticlockwise",
             "ui/actions/Properties Manager/rotate_minus.png", "", "+", 0),
            ("QToolButton", 1, "Clockwise",
             "ui/actions/Properties Manager/rotate_plus.png", "", "-", 1)
        ]

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