class ProteinDisplayStyle_PropertyManager(Command_PropertyManager): """ The ProteinDisplayStyle_PropertyManager class provides a Property Manager for the B{Display Style} command on the flyout toolbar in the Build > Protein mode. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Edit Protein Display Style" pmName = title iconPath = "ui/actions/Edit/EditProteinDisplayStyle.png" def __init__( self, command ): """ Constructor for the property manager. """ self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key] _superclass.__init__(self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) msg = "Modify the protein display settings below." self.updateMessage(msg) def connect_or_disconnect_signals(self, isConnect = True): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect # Favorite buttons signal-slot connections. change_connect( self.applyFavoriteButton, SIGNAL("clicked()"), self.applyFavorite) change_connect( self.addFavoriteButton, SIGNAL("clicked()"), self.addFavorite) change_connect( self.deleteFavoriteButton, SIGNAL("clicked()"), self.deleteFavorite) change_connect( self.saveFavoriteButton, SIGNAL("clicked()"), self.saveFavorite) change_connect( self.loadFavoriteButton, SIGNAL("clicked()"), self.loadFavorite) #Display group box signal slot connections change_connect(self.proteinStyleComboBox, SIGNAL("currentIndexChanged(int)"), self.changeProteinDisplayStyle) change_connect(self.smoothingCheckBox, SIGNAL("stateChanged(int)"), self.smoothProteinDisplay) change_connect(self.scaleComboBox, SIGNAL("currentIndexChanged(int)"), self.changeProteinDisplayScale) change_connect(self.splineDoubleSpinBox, SIGNAL("valueChanged(double)"), self.changeProteinSplineValue) change_connect(self.scaleFactorDoubleSpinBox, SIGNAL("valueChanged(double)"), self.changeProteinScaleFactor) #color groupbox change_connect(self.proteinComponentComboBox, SIGNAL("currentIndexChanged(int)"), self.chooseProteinComponent) change_connect(self.proteinAuxComponentComboBox, SIGNAL("currentIndexChanged(int)"), self.chooseAuxilliaryProteinComponent) change_connect(self.customColorComboBox, SIGNAL("editingFinished()"), self.chooseCustomColor) change_connect(self.auxColorComboBox, SIGNAL("editingFinished()"), self.chooseAuxilliaryColor) #change_connect(self.discColorCheckBox, # SIGNAL("stateChanged(int)"), # self.setDiscreteColors) change_connect(self.helixColorComboBox, SIGNAL("editingFinished()"), self.chooseHelixColor) change_connect(self.strandColorComboBox, SIGNAL("editingFinished()"), self.chooseStrandColor) change_connect(self.coilColorComboBox, SIGNAL("editingFinished()"), self.chooseCoilColor) #Protein Display methods def changeProteinDisplayStyle(self, idx): """ Change protein display style @param idx: index of the protein display style combo box @type idx: int """ env.prefs[proteinStyle_prefs_key] = idx return def changeProteinDisplayQuality(self, idx): env.prefs[proteinStyleQuality_prefs_key] = idx return def smoothProteinDisplay(self, state): """ Smoooth protein display. @param state: state of the smooth protein display check box. @type state: int """ if state == Qt.Checked: env.prefs[proteinStyleSmooth_prefs_key] = True else: env.prefs[proteinStyleSmooth_prefs_key] = False return def changeProteinDisplayScale(self, idx): """ Change protein display scale @param idx: index of the protein display scaling choices combo box @type idx: int """ env.prefs[proteinStyleScaling_prefs_key] = idx return def changeProteinSplineValue(self, val): """ Change protein display resolution @param val: value in the protein display resolution double spinbox @type val: double """ env.prefs[proteinStyleQuality_prefs_key] = val return def changeProteinScaleFactor(self, val): """ Change protein display scale factor @param val: value in the protein display scale factor double spinbox @type val: double """ env.prefs[proteinStyleScaleFactor_prefs_key] = val return def chooseProteinComponent(self, idx): """ Choose protein component to set the color of @param idx: index of the protein component choices combo box @type idx: int """ env.prefs[proteinStyleColors_prefs_key] = idx return def chooseAuxilliaryProteinComponent(self, idx): """ Choose auxilliary protein component to set the color of @param idx: index of the auxilliary protein component choices combo box @type idx: int """ env.prefs[proteinStyleAuxColors_prefs_key] = idx - 1 return def chooseCustomColor(self): """ Choose custom color of the chosen protein component """ color = self.customColorComboBox.getColor() env.prefs[proteinStyleCustomColor_prefs_key] = color return def chooseAuxilliaryColor(self): """ Choose custom color of the chosen auxilliary protein component """ color = self.auxColorComboBox.getColor() env.prefs[proteinStyleAuxCustomColor_prefs_key] = color return def chooseHelixColor(self): """ Choose helix color """ color = self.helixColorComboBox.getColor() env.prefs[proteinStyleHelixColor_prefs_key] = color return def chooseStrandColor(self): """ Choose strand color """ color = self.strandColorComboBox.getColor() env.prefs[proteinStyleStrandColor_prefs_key] = color return def chooseCoilColor(self): """ Choose coil color """ color = self.coilColorComboBox.getColor() env.prefs[proteinStyleCoilColor_prefs_key] = color return def setDiscreteColors(self, state): """ Set discrete colors. @param state: state of the set discrete colors check box. @type state: int """ if state == Qt.Checked: env.prefs[proteinStyleColorsDiscrete_prefs_key] = True else: env.prefs[proteinStyleColorsDiscrete_prefs_key] = False return def show_OLD(self): """ Shows the Property Manager.Extends superclass method. """ #@REVIEW: See comment in CompareProteins_PropertyManager self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded() self.sequenceEditor.hide() self.updateProteinDisplayStyleWidgets() _superclass.show(self) def show(self): """ Shows the Property Manager. Extends superclass method """ _superclass.show(self) #@REVIEW: Is it safe to do the follwoing before calling superclass.show()? #-- Ninad 2008-10-02 # Force the Global Display Style to "DNA Cylinder" so the user # can see the display style setting effects on any DNA in the current # model. The current global display style will be restored when leaving # this command (via self.close()). self.originalDisplayStyle = self.o.displayMode # TODO: rename that public attr of GLPane (widely used) # from displayMode to displayStyle. [bruce 080910 comment] self.o.setGlobalDisplayStyle(diPROTEIN) # Update all PM widgets, . # note: It is important to update the widgets by blocking the # 'signals'. If done in the reverse order, it will generate signals #when updating the PM widgets (via updateDnaDisplayStyleWidgets()), #causing unneccessary repaints of the model view. self.updateProteinDisplayStyleWidgets()#@@@ blockSignals = True) return def close(self): """ Closes the Property Manager. Extends superclass method. """ _superclass.close(self) # Restore the original global display style. self.o.setGlobalDisplayStyle(self.originalDisplayStyle) return def _addGroupBoxes( self ): """ Add the Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Favorites") self._loadGroupBox1( self._pmGroupBox1 ) self._pmGroupBox2 = PM_GroupBox( self, title = "Display") self._loadGroupBox2( self._pmGroupBox2 ) self._pmGroupBox3 = PM_GroupBox( self, title = "Color") self._loadGroupBox3( self._pmGroupBox3 ) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box. @param pmGroupBox: group box that contains various favorite buttons @see: L{PM_GroupBox} """ # Other info # Not only loads the factory default settings but also all the favorite # files stored in the ~/Nanorex/Favorites/ProteinDisplayStyle directory favoriteChoices = ['Factory default settings'] #look for all the favorite files in the favorite folder and add them to # the list from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir _dir = find_or_make_Nanorex_subdir('Favorites/ProteinDisplayStyle') for file in os.listdir(_dir): fullname = os.path.join( _dir, file) if os.path.isfile(fullname): if fnmatch.fnmatch( file, "*.txt"): # leave the extension out favoriteChoices.append(file[0:len(file)-4]) self.favoritesComboBox = \ PM_ComboBox( pmGroupBox, choices = favoriteChoices, spanWidth = True) self.favoritesComboBox.setWhatsThis( """<b> List of Favorites </b> <p> Creates a list of favorite Protein display styles. Once favorite styles have been added to the list using the Add Favorite button, the list will display the chosen favorites. To change the current favorite, select a current favorite from the list, and push the Apply Favorite button.""") # PM_ToolButtonRow =============== # Button list to create a toolbutton row. # Format: # - QToolButton, buttonId, buttonText, # - iconPath, # - tooltip, shortcut, column BUTTON_LIST = [ ( "QToolButton", 1, "APPLY_FAVORITE","ui/actions/Properties Manager/ApplyPeptideDisplayStyleFavorite.png", "Apply Favorite", "", 0), ( "QToolButton", 2, "ADD_FAVORITE", "ui/actions/Properties Manager/AddFavorite.png","Add Favorite", "", 1), ( "QToolButton", 3, "DELETE_FAVORITE", "ui/actions/Properties Manager/DeleteFavorite.png", "Delete Favorite", "", 2), ( "QToolButton", 4, "SAVE_FAVORITE", "ui/actions/Properties Manager/SaveFavorite.png", "Save Favorite", "", 3), ( "QToolButton", 5, "LOAD_FAVORITE", "ui/actions/Properties Manager/LoadFavorite.png", "Load Favorite", \ "", 4) ] self.favsButtonGroup = \ PM_ToolButtonRow( pmGroupBox, title = "", buttonList = BUTTON_LIST, spanWidth = True, isAutoRaise = False, isCheckable = False, setAsDefault = True, ) self.favsButtonGroup.buttonGroup.setExclusive(False) self.applyFavoriteButton = self.favsButtonGroup.getButtonById(1) self.addFavoriteButton = self.favsButtonGroup.getButtonById(2) self.deleteFavoriteButton = self.favsButtonGroup.getButtonById(3) self.saveFavoriteButton = self.favsButtonGroup.getButtonById(4) self.loadFavoriteButton = self.favsButtonGroup.getButtonById(5) def _loadGroupBox2(self, pmGroupBox): """ Load widgets in group box. @param pmGroupBox: group box that contains protein display choices @see: L{PM_GroupBox} """ proteinStyleChoices = ['CA trace (wire)', 'CA trace (cylinders)', 'CA trace (ball and stick)', 'Tube', 'Ladder', 'Zigzag', 'Flat ribbon', 'Solid ribbon', 'Cartoons', 'Fancy cartoons', 'Peptide tiles' ] self.proteinStyleComboBox = \ PM_ComboBox( pmGroupBox, label = "Style:", choices = proteinStyleChoices, setAsDefault = True) scaleChoices = ['Constant', 'Secondary structure', 'B-factor'] self.scaleComboBox = \ PM_ComboBox( pmGroupBox, label = "Scaling:", choices = scaleChoices, setAsDefault = True) self.scaleFactorDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Scaling factor:", value = 1.00, setAsDefault = True, minimum = 0.1, maximum = 3.0, decimals = 1, singleStep = 0.1 ) self.splineDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Resolution:", value = 3, setAsDefault = True, minimum = 2, maximum = 8, decimals = 0, singleStep = 1 ) self.smoothingCheckBox = \ PM_CheckBox( pmGroupBox, text = "Smoothing", setAsDefault = True) def _loadGroupBox3(self, pmGroupBox): """ Load widgets in group box. @param pmGroupBox: group box that contains various color choices @see: L{PM_GroupBox} """ colorChoices = ['Chunk', 'Chain', 'Order', 'Hydropathy', 'Polarity', 'Acidity', 'Size', 'Character', 'Number of contacts', 'Secondary structure type', 'Secondary structure order', 'B-factor', 'Occupancy', 'Custom'] self.proteinComponentComboBox = \ PM_ComboBox( pmGroupBox, label = "Color by:", choices = colorChoices, setAsDefault = True) colorList = [orange, yellow, red, magenta, cyan, blue, white, black, gray] colorNames = ["Orange(default)", "Yellow", "Red", "Magenta", "Cyan", "Blue", "White", "Black", "Other color..."] self.customColorComboBox = \ PM_ColorComboBox(pmGroupBox, colorList = colorList, colorNames = colorNames, label = "Custom:", color = orange, setAsDefault = True) colorChoices1 = [ 'Same as main color', 'Lighter', 'Darker', 'Gray', 'Custom'] self.proteinAuxComponentComboBox = \ PM_ComboBox( pmGroupBox, label = "Aux:", choices = colorChoices1, setAsDefault = True) colorListAux = [orange, yellow, red, magenta,cyan, blue, white, black, gray] colorNamesAux = ["Orange(default)", "Yellow", "Red", "Magenta", "Cyan", "Blue", "White", "Black", "Other color..."] self.auxColorComboBox = \ PM_ColorComboBox(pmGroupBox, colorList = colorListAux, colorNames = colorNamesAux, label = "Custom aux:", color = gray, setAsDefault = True) #self.discColorCheckBox = \ # PM_CheckBox( pmGroupBox, # text = "Discretize colors", # setAsDefault = True # ) # colorListHelix = [red, yellow, gray, magenta, cyan, blue, white, black, orange] colorNamesHelix = ["Red(default)", "Yellow", "Gray", "Magenta", "Cyan", "Blue", "White", "Black", "Other color..."] self.helixColorComboBox = \ PM_ColorComboBox(pmGroupBox, colorList = colorListHelix, colorNames = colorNamesHelix, label = "Helix:", color = red, setAsDefault = True) colorListStrand = [cyan, yellow, gray, magenta, red, blue, white, black, orange] colorNamesStrand = ["Cyan(default)", "Yellow", "Gray", "Magenta", "Red", "Blue", "White", "Black", "Other color..."] self.strandColorComboBox = \ PM_ColorComboBox(pmGroupBox, colorList = colorListStrand, colorNames = colorNamesStrand, label = "Strand:", color = cyan, setAsDefault = True) self.coilColorComboBox = \ PM_ColorComboBox(pmGroupBox, colorList = colorListAux, colorNames = colorNamesAux, label = "Coil:", color = orange, setAsDefault = True) def updateProteinDisplayStyleWidgets( self ): """ Updates all the Protein Display style widgets based on the current pref keys values """ self.proteinStyleComboBox.setCurrentIndex(env.prefs[proteinStyle_prefs_key]) self.splineDoubleSpinBox.setValue(env.prefs[proteinStyleQuality_prefs_key]) if env.prefs[proteinStyleSmooth_prefs_key] == True: self.smoothingCheckBox.setCheckState(Qt.Checked) else: self.smoothingCheckBox.setCheckState(Qt.Unchecked) self.scaleComboBox.setCurrentIndex(env.prefs[proteinStyleScaling_prefs_key]) self.scaleFactorDoubleSpinBox.setValue(env.prefs[proteinStyleScaleFactor_prefs_key]) self.proteinComponentComboBox.setCurrentIndex(env.prefs[proteinStyleColors_prefs_key]) self.customColorComboBox.setColor(env.prefs[proteinStyleCustomColor_prefs_key]) self.proteinAuxComponentComboBox.setCurrentIndex(env.prefs[proteinStyleAuxColors_prefs_key]) self.auxColorComboBox.setColor(env.prefs[proteinStyleAuxCustomColor_prefs_key]) #if env.prefs[proteinStyleColorsDiscrete_prefs_key] == True: # self.discColorCheckBox.setCheckState(Qt.Checked) #else: # self.discColorCheckBox.setCheckState(Qt.Unchecked) self.helixColorComboBox.setColor(env.prefs[proteinStyleHelixColor_prefs_key]) self.strandColorComboBox.setColor(env.prefs[proteinStyleStrandColor_prefs_key]) self.coilColorComboBox.setColor(env.prefs[proteinStyleCoilColor_prefs_key]) return def applyFavorite(self): """ Apply a favorite to the current display chosen in the favorites combo box """ current_favorite = self.favoritesComboBox.currentText() if current_favorite == 'Factory default settings': env.prefs.restore_defaults(proteinDisplayStylePrefsList) else: favfilepath = getFavoritePathFromBasename(current_favorite) loadFavoriteFile(favfilepath) self.updateProteinDisplayStyleWidgets() return def addFavorite(self): """ create and add favorite to favorites directory and favorites combo box in PM @note: Rules and other info: - The new favorite is defined by the current Protein display style settings. - The user is prompted to type in a name for the new favorite. - The Protein display style settings are written to a file in a special directory on the disk (i.e. $HOME/Nanorex/Favorites/ProteinDisplayStyle/$FAV_NAME.txt). - The name of the new favorite is added to the list of favorites in the combobox, which becomes the current option. Existence of a favorite with the same name is checked in the above mentioned location and if a duplicate exists, then the user can either overwrite and provide a new name. """ # Prompt user for a favorite name to add. from widgets.simple_dialogs import grab_text_line_using_dialog ok1, name = \ grab_text_line_using_dialog( title = "Add new favorite", label = "favorite name:", iconPath = "ui/actions/Properties Manager/AddFavorite.png", default = "" ) if ok1: # check for duplicate files in the # $HOME/Nanorex/Favorites/DnaDisplayStyle/ directory fname = getFavoritePathFromBasename( name ) if os.path.exists(fname): #favorite file already exists! _ext= ".txt" ret = QMessageBox.warning( self, "Warning!", "The favorite file \"" + name + _ext + "\"already exists.\n" "Do you want to overwrite the existing file?", "&Overwrite", "&Cancel", "", 0, # Enter == button 0 1) # Escape == button 1 if ret == 0: #overwrite favorite file ok2, text = writeProteinDisplayStyleSettingsToFavoritesFile(name) indexOfDuplicateItem = self.favoritesComboBox.findText(name) self.favoritesComboBox.removeItem(indexOfDuplicateItem) print "Add Favorite: removed duplicate favorite item." else: env.history.message("Add Favorite: cancelled overwriting favorite item.") return else: ok2, text = writeProteinDisplayStyleSettingsToFavoritesFile(name) else: # User cancelled. return if ok2: self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) msg = "New favorite [%s] added." % (text) else: msg = "Can't add favorite [%s]: %s" % (name, text) # text is reason why not env.history.message(msg) return def deleteFavorite(self): """ Delete favorite file from the favorites directory """ currentIndex = self.favoritesComboBox.currentIndex() currentText = self.favoritesComboBox.currentText() if currentIndex == 0: msg = "Cannot delete '%s'." % currentText else: self.favoritesComboBox.removeItem(currentIndex) # delete file from the disk deleteFile= getFavoritePathFromBasename( currentText ) os.remove(deleteFile) msg = "Deleted favorite named [%s].\n" \ "and the favorite file [%s.txt]." \ % (currentText, currentText) env.history.message(msg) return def saveFavorite(self): """ Save favorite file in a user chosen location """ cmd = greenmsg("Save Favorite File: ") env.history.message(greenmsg("Save Favorite File:")) current_favorite = self.favoritesComboBox.currentText() favfilepath = getFavoritePathFromBasename(current_favorite) formats = \ "Favorite (*.txt);;"\ "All Files (*.*)" directory = self.currentWorkingDirectory saveLocation = directory + "/" + current_favorite + ".txt" fn = QFileDialog.getSaveFileName( self, "Save Favorite As", # caption favfilepath, #where to save formats, # file format options QString("Favorite (*.txt)") # selectedFilter ) if not fn: env.history.message(cmd + "Cancelled") else: dir, fil = os.path.split(str(fn)) self.setCurrentWorkingDirectory(dir) saveFavoriteFile(str(fn), favfilepath) return def setCurrentWorkingDirectory(self, dir = None): """ Set dir as current working diretcory @param dir: dirname @type dir: str """ if os.path.isdir(dir): self.currentWorkingDirectory = dir self._setWorkingDirectoryInPrefsDB(dir) else: self.currentWorkingDirectory = getDefaultWorkingDirectory() return def _setWorkingDirectoryInPrefsDB(self, workdir = None): """ Set workdir as current working diretcory in prefDB @param workdir: dirname @type workdir: str """ if not workdir: return workdir = str(workdir) if os.path.isdir(workdir): workdir = os.path.normpath(workdir) env.prefs[workingDirectory_prefs_key] = workdir # Change pref in prefs db. else: msg = "[" + workdir + "] is not a directory. Working directory was not changed." env.history.message( redmsg(msg)) return def loadFavorite(self): """ Load a favorite file """ # If the file already exists in the favorites folder then the user is # given the option of overwriting it or renaming it env.history.message(greenmsg("Load Favorite File:")) formats = \ "Favorite (*.txt);;"\ "All Files (*.*)" directory = self.currentWorkingDirectory if directory == '': directory= getDefaultWorkingDirectory() fname = QFileDialog.getOpenFileName(self, "Choose a file to load", directory, formats) if not fname: env.history.message("User cancelled loading file.") return else: dir, fil = os.path.split(str(fname)) self.setCurrentWorkingDirectory(dir) canLoadFile=loadFavoriteFile(fname) if canLoadFile == 1: #get just the name of the file for loading into the combobox favName = os.path.basename(str(fname)) name = favName[0:len(favName)-4] indexOfDuplicateItem = self.favoritesComboBox.findText(name) #duplicate exists in combobox if indexOfDuplicateItem != -1: ret = QMessageBox.warning( self, "Warning!", "The favorite file \"" + name + "\"already exists.\n" "Do you want to overwrite the existing file?", "&Overwrite", "&Rename", "&Cancel", 0, # Enter == button 0 1 # button 1 ) if ret == 0: self.favoritesComboBox.removeItem(indexOfDuplicateItem) self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) ok2, text = writeProteinDisplayStyleSettingsToFavoritesFile(name) msg = "Overwrote favorite [%s]." % (text) env.history.message(msg) elif ret == 1: # add new item to favorites folder as well as combobox self.addFavorite() else: #reset the display setting values to factory default factoryIndex = self.favoritesComboBox.findText( 'Factory default settings') self.favoritesComboBox.setCurrentIndex(factoryIndex) env.prefs.restore_defaults(proteinDisplayStylePrefsList) env.history.message("Cancelled overwriting favorite file.") return else: self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) msg = "Loaded favorite [%s]." % (name) env.history.message(msg) self.updateProteinDisplayStyleWidgets() return def _addWhatsThisText( self ): """ Add what's this text for this PM """ from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditDnaDisplayStyle_PropertyManager WhatsThis_EditDnaDisplayStyle_PropertyManager(self) def _addToolTipText(self): """ Add tool tip text to all widgets. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager ToolTip_EditProteinDisplayStyle_PropertyManager(self)
class 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
class InsertPeptide_PropertyManager(EditCommand_PM): """ The InsertPeptide_PropertyManager class provides a Property Manager for the "Insert > Peptide" command. """ # The title that appears in the property manager header. title = "Insert Peptide" # The name of this property manager. This will be set to # the name of the PropMgr (this) object via setObjectName(). pmName = title # The relative path to PNG file that appears in the header. iconPath = "ui/actions/Command Toolbar/BuildProtein/InsertPeptide.png" # phi psi angles will define the secondary structure of the peptide chain phi = -57.0 psi = -47.0 chirality = 1 secondary = SS_HELIX current_amino_acid = 7 # Glycine # DEPRECATED ATTRS #peptide_cache = [] #peptide_cache.append((0, 0, 0)) def __init__(self, command): """ Construct the Property Manager. """ _superclass.__init__(self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_WHATS_THIS_BUTTON) return def show(self): """ Extends superclass method. """ _superclass.show(self) self.updateMessage("Choose the peptide parameters below, then click "\ "two endpoints in the graphics area to insert a "\ "peptide chain.") return def getParameters(self): """ Return the parameters from this property manager to be used to create the peptide. @return: A tuple containing the parameters @rtype: tuple @see: L{InsertPeptide_EditCommand._gatherParameters()} where this is used """ return (self.secondary, self.phi, self.psi, self.current_amino_acid) def _addGroupBoxes(self): """ Add the group boxe to the Peptide Property Manager dialog. """ self.pmGroupBox1 = \ PM_GroupBox( self, title = "Peptide Parameters" ) # Add group box widgets. self._loadGroupBox1(self.pmGroupBox1) return def _loadGroupBox1(self, inPmGroupBox): """ Load widgets in the group box. """ memberChoices = [ "Custom", "Alpha helix", "Beta strand", "Pi helix", "3_10 helix", "Polyproline-II helix", "Fully extended" ] self.aaTypeComboBox= \ PM_ComboBox( inPmGroupBox, label = "Conformation:", choices = memberChoices, index = 1, setAsDefault = True, spanWidth = False ) self.connect(self.aaTypeComboBox, SIGNAL("currentIndexChanged(int)"), self._aaTypeChanged) self.phiAngleField = \ PM_DoubleSpinBox( inPmGroupBox, label = "Phi angle:", value = self.phi, setAsDefault = True, minimum = -180.0, maximum = 180.0, singleStep = 1.0, decimals = 1, suffix = " degrees") self.connect(self.phiAngleField, SIGNAL("valueChanged(double)"), self._aaPhiAngleChanged) self.phiAngleField.setEnabled(False) self.psiAngleField = \ PM_DoubleSpinBox( inPmGroupBox, label = "Psi angle:", value = self.psi, setAsDefault = True, minimum = -180.0, maximum = 180.0, singleStep = 1.0, decimals = 1, suffix = " degrees" ) self.connect(self.psiAngleField, SIGNAL("valueChanged(double)"), self._aaPsiAngleChanged) self.psiAngleField.setEnabled(False) self.aaTypesButtonGroup = \ PM_ToolButtonGrid( inPmGroupBox, buttonList = AA_BUTTON_LIST, label = "Amino acids", checkedId = self.current_amino_acid, # Glycine setAsDefault = True ) self.connect(self.aaTypesButtonGroup.buttonGroup, SIGNAL("buttonClicked(int)"), self._setAminoAcidType) return def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_InsertPeptide_PropertyManager whatsThis_InsertPeptide_PropertyManager(self) return def _addToolTipText(self): """ Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_InsertPeptide_PropertyManager ToolTip_InsertPeptide_PropertyManager(self) return def _aaChiralityChanged(self): """ Set chirality of the peptide chain. """ # This feature is currently disable as it was confusing to the users # who expected control over chirality of amino acids (D/L conformers) # rather than over polypeptide chain (left/right-handed structure). self.psi *= -1 self.phi *= -1 self.phiAngleField.setValue(self.phi) self.psiAngleField.setValue(self.psi) return def _aaTypeChanged(self, idx): """ Slot for Peptide Structure Type combo box. Changes phi/psi angles for secondary structure. @param idx: index of secondary structure combo box @type idx: int """ self.ss_idx = idx if idx == 0: self.phiAngleField.setEnabled(True) self.psiAngleField.setEnabled(True) else: self.phiAngleField.setEnabled(False) self.psiAngleField.setEnabled(False) if idx == 1: # alpha helix self.phi = -57.0 self.psi = -47.0 self.secondary = SS_HELIX elif idx == 2: # beta strand self.phi = -135.0 self.psi = 135.0 self.secondary = SS_STRAND elif idx == 3: # 3-10 helix self.phi = -55.0 self.psi = -70.0 self.secondary = SS_HELIX elif idx == 4: # pi helix self.phi = -49.0 self.psi = -26.0 self.secondary = SS_HELIX elif idx == 5: # polyprolin-II self.phi = -75.0 self.psi = 150.0 self.secondary = SS_COIL elif idx == 6: # fully extended self.phi = -180.0 self.psi = 180.0 self.secondary = SS_STRAND else: self.phi = self.phiAngleField.value() self.psi = self.psiAngleField.value() self.secondary = SS_COIL self.phi *= self.chirality self.psi *= self.chirality self.command.secondary = self.secondary self.phiAngleField.setValue(self.phi) self.psiAngleField.setValue(self.psi) return def _aaPhiAngleChanged(self, phi): """ Called when phi angle spin box has changed. @param phi: phi angle value @type phi: float """ self.phi = self.phiAngleField.value() return def _aaPsiAngleChanged(self, psi): """ Called when psi angle spin box has changed. @param psi: psi angle value @type psi: float """ self.psi = self.psiAngleField.value() return def _setAminoAcidType(self, index): """ Sets the current amino acid type to I{index}. """ self.current_amino_acid = index return # -------------------------------------------------------------------- # Deprecated methods to keep until we're certain this is working. # --Mark 2008-12-12. def addAminoAcid_DEPRECATED(self, index): """ Adds a new amino acid to the peptide molecule. """ # This commened out code is obsolete in interactive peptide builder. # The interactive peptide builder creates homopeptides. # add a new amino acid and chain conformation to the peptide cache #self.peptide_cache.append((index,self.phi,self.psi)) #self.peptide_cache[0] = (index,self.phi,self.psi) self.current_amino_acid = index return def _setAminoAcidType_DEPRECATED(self, aaTypeIndex): """ Adds a new amino acid to the peptide molecule. """ # piotr 080911: this method is obsolete as of 080911. It was used in # the old Peptide Generator. button, idx, short_name, dum, name, symbol, x, y = AA_BUTTON_LIST[ aaTypeIndex] if self.ss_idx == 1: aa_txt = "<font color=red>" elif self.ss_idx == 2: aa_txt = "<font color=blue>" elif self.ss_idx == 3: aa_txt = "<font color=green>" elif self.ss_idx == 4: aa_txt = "<font color=orange>" elif self.ss_idx == 5: aa_txt = "<font color=magenta>" elif self.ss_idx == 6: aa_txt = "<font color=darkblue>" else: aa_txt = "<font color=black>" aa_txt += symbol + "</font>" #self.sequenceEditor.insertHtml(aa_txt, False, 4, 10, False) 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 NanotubeGeneratorPropertyManager(PM_Dialog): """ The NanotubeGeneratorPropertyManager class provides a Property Manager for the "Build > Nanotube" command. """ # The title that appears in the property manager header. title = "Nanotube" # The name of this property manager. This will be set to # the name of the PropMgr (this) object via setObjectName(). pmName = title # The relative path to PNG file that appears in the header. iconPath = "ui/actions/Tools/Build Structures/Nanotube.png" def __init__(self): """Construct the Graphene Property Manager. """ PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title) #@self.addGroupBoxes() #@self.add_whats_this_text() self.updateMessageGroupBox() def updateMessageGroupBox(self): msg = "" # A (4, 4) tube is stable, but a (3, 3) has not been seen in # isolation. Circumference of a (4, 4) tube is about 6.93. xOffset = self.n + self.m * math.cos(math.pi/3.0) yOffset = self.m * math.sin(math.pi/3.0) circumference = math.sqrt(xOffset * xOffset + yOffset * yOffset) if (circumference < 6.5): msg = "Warning: Small diameter nanotubes may be unstable, \ and may give unexpected results when minimized.<p>" msg = msg + "Edit the Nanotube parameters and select <b>Preview</b> to \ preview the structure. Click <b>Done</b> to insert it into the model." # This causes the "Message" box to be displayed as well. # setAsDefault=True causes this message to be reset whenever # this PropMgr is (re)displayed via show(). Mark 2007-06-01. self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=True) def _addGroupBoxes(self): """ Add the 3 group boxes to the Nanotube Property Manager dialog. """ self.pmGroupBox1 = \ PM_GroupBox( self, title = "Nanotube Parameters" ) self.pmGroupBox2 = \ PM_GroupBox( self, title = "Nanotube Distortion" ) self.pmGroupBox3 = \ PM_GroupBox( self, title = "Multi-Walled Nanotubes" ) # Add group box widgets. self._loadGroupBox1(self.pmGroupBox1) self._loadGroupBox2(self.pmGroupBox2) self._loadGroupBox3(self.pmGroupBox3) def _loadGroupBox1(self, inPmGroupBox): """ Load widgets in group box 1. """ memberChoices = ["Carbon", "Boron Nitride"] self.typeComboBox= \ PM_ComboBox( inPmGroupBox, label = "Type :", choices = memberChoices, index = 0, setAsDefault = True, spanWidth = False ) self.connect( self.typeComboBox, SIGNAL("currentIndexChanged(int)"), self.nt_type_changed) self.lengthField = \ PM_DoubleSpinBox( inPmGroupBox, label = "Length :", value = 20.0, setAsDefault = True, minimum = 1.0, maximum = 1000.0, singleStep = 1.0, decimals = 3, suffix = " Angstroms" ) self.n = 5 self.chiralityNSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Chirality (n) :", value = self.n, setAsDefault = True ) self.connect(self.chiralityNSpinBox, SIGNAL("valueChanged(int)"), self.chirality_fixup) self.m = 5 self.chiralityMSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Chirality (m) :", value = self.m, setAsDefault = True ) self.connect(self.chiralityMSpinBox, SIGNAL("valueChanged(int)"), self.chirality_fixup) self.bondLengthField = \ PM_DoubleSpinBox( inPmGroupBox, label = "Bond Length :", value = CC_GRAPHITIC_BONDLENGTH, setAsDefault = True, minimum = 1.0, maximum = 3.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) endingChoices = ["None", "Hydrogen", "Nitrogen"] self.endingsComboBox= \ PM_ComboBox( inPmGroupBox, label = "Endings :", choices = endingChoices, index = 0, setAsDefault = True, spanWidth = False ) def _loadGroupBox2(self, inPmGroupBox): """ Load widgets in group box 2. """ self.zDistortionField = \ PM_DoubleSpinBox( inPmGroupBox, label = "Z-distortion :", value = 0.0, setAsDefault = True, minimum = 0.0, maximum = 10.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) self.xyDistortionField = \ PM_DoubleSpinBox( inPmGroupBox, label = "XY-distortion :", value = 0.0, setAsDefault = True, minimum = 0.0, maximum = 2.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) self.twistSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Twist :", value = 0, setAsDefault = True, minimum = 0, maximum = 100, # What should maximum be? suffix = " deg/A" ) self.bendSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Bend :", value = 0, setAsDefault = True, minimum = 0, maximum = 360, suffix = " deg" ) def _loadGroupBox3(self, inPmGroupBox): """ Load widgets in group box 3. """ # "Number of Nanotubes" SpinBox self.mwntCountSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Number :", value = 1, setAsDefault = True, minimum = 1, maximum = 10, suffix = " nanotubes" ) self.mwntCountSpinBox.setSpecialValueText("SWNT") # "Spacing" lineedit. self.mwntSpacingField = \ PM_DoubleSpinBox( inPmGroupBox, label = "Spacing :", value = 2.46, setAsDefault = True, minimum = 1.0, maximum = 10.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_NanotubeGeneratorPropertyManager whatsThis_NanotubeGeneratorPropertyManager(self) def _addToolTipText(self): """ Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_NanotubeGeneratorPropertyManager ToolTip_NanotubeGeneratorPropertyManager(self) def chirality_fixup(self, spinBoxValueJunk = None): """ Slot for several validators for different parameters. This gets called each time a user types anything into a widget or changes a spinbox. @param spinBoxValueJunk: This is the Spinbox value from the valueChanged signal. It is not used. We just want to know that the spinbox value has changed. @type spinBoxValueJunk: double or None """ if not hasattr(self, 'n'): print_compact_traceback("Bug: no attr 'n' ") # mark 2007-05-24 return n_previous = int(self.n) m_previous = int(self.m) n = self.chiralityNSpinBox.value() m = self.chiralityMSpinBox.value() # Two restrictions to maintain # n >= 2 # 0 <= m <= n if n < 2: n = 2 if m != self.m: # The user changed m. If m became larger than n, make n bigger. if m > n: n = m elif n != self.n: # The user changed n. If n became smaller than m, make m smaller. if m > n: m = n self.chiralityNSpinBox.setValue(n) self.chiralityMSpinBox.setValue(m) self.m, self.n = m, n self.updateMessageGroupBox() def nt_type_changed(self, idx): """ Slot for Nanotube Type combobox. Update the bond length field when the type changes. """ self.bondLengthField.setValue(ntBondLengths[idx])
class DnaStrand_PropertyManager( DnaOrCnt_PropertyManager): """ The DnaStrand_PropertyManager class provides a Property Manager for the DnaStrand_EditCommand. @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 = "DnaStrand Properties" pmName = title iconPath = "ui/actions/Properties Manager/Strand.png" def __init__( self, win, editCommand ): """ Constructor for the Build DNA property manager. """ #For model changed signal self.previousSelectionParams = None #see self.connect_or_disconnect_signals for comment about this flag self.isAlreadyConnected = False self.isAlreadyDisconnected = False self.sequenceEditor = None self._numberOfBases = 0 self._conformation = 'B-DNA' self.duplexRise = 3.18 self.basesPerTurn = 10 self.dnaModel = 'PAM3' _superclass.__init__( self, win, editCommand) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) self._loadSequenceEditor() msg = "Use resize handles to resize the strand. Use sequence editor"\ "to assign a new sequence or the current one to a file." self.updateMessage(msg) def _addGroupBoxes( self ): """ Add the DNA Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Parameters" ) self._loadGroupBox1( self._pmGroupBox1 ) self._displayOptionsGroupBox = PM_GroupBox( self, title = "Display Options" ) self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox ) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 4. """ self.nameLineEdit = PM_LineEdit( pmGroupBox, label = "Strand name:", text = "", setAsDefault = False) self.numberOfBasesSpinBox = \ PM_SpinBox( pmGroupBox, label = "Number of bases:", value = self._numberOfBases, setAsDefault = False, minimum = 2, maximum = 10000 ) self.basesPerTurnDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Bases per turn:", value = self.basesPerTurn, setAsDefault = True, minimum = 8.0, maximum = 20.0, decimals = 2, singleStep = 0.1 ) self.duplexRiseDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Rise:", value = self.duplexRise, setAsDefault = True, minimum = 2.0, maximum = 4.0, decimals = 3, singleStep = 0.01 ) self.disableStructHighlightingCheckbox = \ PM_CheckBox( pmGroupBox, text = "Don't highlight while editing DNA", widgetColumn = 0, state = Qt.Unchecked, setAsDefault = True, spanWidth = True ) #As of 2008-03-31, the properties such as number of bases will be #editable only by using the resize handles. post FNANO we will support #the self.numberOfBasesSpinBox.setEnabled(False) self.basesPerTurnDoubleSpinBox.setEnabled(False) self.duplexRiseDoubleSpinBox.setEnabled(False) def _loadSequenceEditor(self): """ Temporary code that shows the Sequence editor ..a doc widget docked at the bottom of the mainwindow. The implementation is going to change before 'rattleSnake' product release. As of 2007-11-20: This feature (sequence editor) is waiting for the ongoing dna model work to complete. """ self.sequenceEditor = self.win.createDnaSequenceEditorIfNeeded() self.sequenceEditor.hide() def _loadDisplayOptionsGroupBox(self, pmGroupBox): """ Overrides superclass method. Also loads the color chooser widget. """ self._loadColorChooser(pmGroupBox) _superclass._loadDisplayOptionsGroupBox(self, pmGroupBox) def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Overrides DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox """ connect_checkbox_with_boolean_pref( self.showCursorTextCheckBox , dnaStrandEditCommand_showCursorTextCheckBox_prefs_key) def _params_for_creating_cursorTextCheckBoxes(self): """ Returns params needed to create various cursor text checkboxes connected to prefs_keys that allow custom cursor texts. @return: A list containing tuples in the following format: ('checkBoxTextString' , preference_key). PM_PrefsCheckBoxes uses this data to create checkboxes with the the given names and connects them to the provided preference keys. (Note that PM_PrefsCheckBoxes puts thes within a GroupBox) @rtype: list @see: PM_PrefsCheckBoxes @see: self._loadDisplayOptionsGroupBox where this list is used. @see: Superclass method which is overridden here -- DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = \ [ #Format: (" checkbox text", prefs_key) ("Number of bases", dnaStrandEditCommand_cursorTextCheckBox_numberOfBases_prefs_key), ("Number of bases to be changed", dnaStrandEditCommand_cursorTextCheckBox_changedBases_prefs_key) ] return params def getParameters(self): numberOfBases = self.numberOfBasesSpinBox.value() dnaForm = self._conformation dnaModel = self.dnaModel basesPerTurn = self.basesPerTurn duplexRise = self.duplexRise color = self._colorChooser.getColor() return (numberOfBases, dnaForm, dnaModel, basesPerTurn, duplexRise, color ) def setParameters(self, params): """ This is usually called when you are editing an existing structure. Some property manager ui elements then display the information obtained from the object being edited. TODO: - Make this a EditCommand_PM API method? - See also the routines GraphicsMode.setParams or object.setProps ..better to name them all in one style? """ #Set the duplex rise and bases per turn spinbox values. numberOfBases, \ dnaForm, \ dnaModel, \ basesPerTurn, \ duplexRise, \ color = params if numberOfBases is not None: self.numberOfBasesSpinBox.setValue(numberOfBases) if dnaForm is not None: self._conformation = dnaForm if dnaModel is not None: self.dnaModel = dnaModel if duplexRise is not None: self.duplexRiseDoubleSpinBox.setValue(duplexRise) if basesPerTurn is not None: self.basesPerTurnDoubleSpinBox.setValue(basesPerTurn) if color is not None: self._colorChooser.setColor(color) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ #TODO: This is a temporary fix for a bug. When you invoke a temporary # mode Entering such a temporary mode keeps the signals of #PM from the previous mode connected ( #but while exiting that temporary mode and reentering the #previous mode, it atucally reconnects the signal! This gives rise to #lots of bugs. This needs more general fix in Temporary mode API. # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py if isConnect and self.isAlreadyConnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to connect widgets"\ "in this PM that are already connected." ) return if not isConnect and self.isAlreadyDisconnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to disconnect widgets"\ "in this PM that are already disconnected.") return self.isAlreadyConnected = isConnect self.isAlreadyDisconnected = not isConnect if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect if self.sequenceEditor: self.sequenceEditor.connect_or_disconnect_signals(isConnect) _superclass.connect_or_disconnect_signals(self, isConnect) change_connect(self.disableStructHighlightingCheckbox, SIGNAL('stateChanged(int)'), self.change_struct_highlightPolicy) change_connect(self.showCursorTextCheckBox, SIGNAL('stateChanged(int)'), self._update_state_of_cursorTextGroupBox) def model_changed(self): """ @see: DnaStrand_EditCommand.model_changed() @see: DnaStrand_EditCommand.hasResizableStructure() """ isStructResizable, why_not = self.editCommand.hasResizableStructure() if not isStructResizable: #disable all widgets if self._pmGroupBox1.isEnabled(): self._pmGroupBox1.setEnabled(False) msg1 = ("Viewing properties of %s <br>") %(self.editCommand.struct.name) msg2 = redmsg("DnaStrand is not resizable. Reason: %s"%(why_not)) self.updateMessage(msg1 + msg2) else: if not self._pmGroupBox1.isEnabled(): self._pmGroupBox1.setEnabled(True) msg1 = ("Viewing properties of %s <br>") %(self.editCommand.struct.name) msg2 = "Use resize handles to resize the strand. Use sequence editor"\ "to assign a new sequence or the current one to a file." self.updateMessage(msg1 + msg2) def show(self): """ Show this PM As of 2007-11-20, it also shows the Sequence Editor widget and hides the history widget. This implementation may change in the near future This method also retrives the name information from the editCommand's structure for its name line edit field. @see: DnaStrand_EditCommand.getStructureName() @see: self.close() """ _superclass.show(self) self._showSequenceEditor() if self.editCommand is not None: name = self.editCommand.getStructureName() if name is not None: self.nameLineEdit.setText(name) def close(self): """ Close this property manager. Also sets the name of the self.editCommand's structure to the one displayed in the line edit field. @see self.show() @see: DnaSegment_EditCommand.setStructureName """ if self.editCommand is not None: name = str(self.nameLineEdit.text()) self.editCommand.setStructureName(name) if self.sequenceEditor: self.sequenceEditor.close() _superclass.close(self) def _showSequenceEditor(self): if self.sequenceEditor: if not self.sequenceEditor.isVisible(): #Show the sequence editor #ATTENTION: the sequence editor also closes (temporarily) the #reports dockwidget (if visible) Its state is later restored when #the sequuence Editor is closed. self.sequenceEditor.show() self.updateSequence() def updateSequence(self): """ Update the sequence string in the sequence editor @see: DnaSequenceEditor.setSequence() @see DnaSequenceEditor._determine_complementSequence() @see: DnaSequenceEditor.setComplementSequence() @see: DnaStrand.getStrandSequenceAndItsComplement() """ #Read in the strand sequence of the selected strand and #show it in the text edit in the sequence editor. ##strand = self.strandListWidget.getPickedItem() if not self.editCommand.hasValidStructure(): return strand = self.editCommand.struct titleString = 'Sequence Editor for ' + strand.name self.sequenceEditor.setWindowTitle(titleString) sequenceString, complementSequenceString = strand.getStrandSequenceAndItsComplement() if sequenceString: sequenceString = QString(sequenceString) sequenceString = sequenceString.toUpper() #Set the initial sequence (read in from the file) self.sequenceEditor.setSequence(sequenceString) #Set the initial complement sequence for DnaSequence editor. #do this independently because 'complementSequenceString' may have #some characters (such as * ) that denote a missing base on the #complementary strand. this information is used by the sequence #editor. See DnaSequenceEditor._determine_complementSequence() #for more details. See also bug 2787 self.sequenceEditor.setComplementSequence(complementSequenceString) def change_struct_highlightPolicy(self,checkedState = False): """ Change the 'highlight policy' of the structure being edited (i.e. self.editCommand.struct) . @param checkedState: The checked state of the checkbox that says 'Don't highlight while editing DNA'. So, it its True, the structure being edited won't get highlighted. @see: DnaStrand.setHighlightPolicy for more comments """ if self.editCommand and self.editCommand.hasValidStructure(): highlight = not checkedState self.editCommand.struct.setHighlightPolicy(highlight = highlight) def _addWhatsThisText(self): """ Add what's this text. Abstract method. """ pass
class DnaDuplexPropertyManager( DnaOrCnt_PropertyManager ): """ The DnaDuplexPropertyManager class provides a Property Manager for the B{Build > DNA > Duplex} 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 = "Insert DNA" pmName = title iconPath = "ui/actions/Tools/Build Structures/InsertDsDna.png" def __init__( self, win, editCommand ): """ Constructor for the DNA Duplex property manager. """ self.endPoint1 = None self.endPoint2 = None self._conformation = "B-DNA" self._numberOfBases = 0 self._basesPerTurn = getDuplexBasesPerTurn(self._conformation) self._duplexRise = getDuplexRise(self._conformation) self._duplexLength = getDuplexLength(self._conformation, self._numberOfBases) _superclass.__init__( self, win, editCommand) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_WHATS_THIS_BUTTON) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect change_connect(self._placementOptions.buttonGroup, SIGNAL("buttonClicked(int)"), self.activateSpecifyReferencePlaneTool) change_connect( self.conformationComboBox, SIGNAL("currentIndexChanged(int)"), self.conformationComboBoxChanged ) change_connect( self.numberOfBasePairsSpinBox, SIGNAL("valueChanged(int)"), self.numberOfBasesChanged ) change_connect( self.basesPerTurnDoubleSpinBox, SIGNAL("valueChanged(double)"), self.basesPerTurnChanged ) change_connect( self.duplexRiseDoubleSpinBox, SIGNAL("valueChanged(double)"), self.duplexRiseChanged ) change_connect(self.showCursorTextCheckBox, SIGNAL('stateChanged(int)'), self._update_state_of_cursorTextGroupBox) self.duplexRiseDoubleSpinBox.connectWithState( Preferences_StateRef_double( bdnaRise_prefs_key, env.prefs[bdnaRise_prefs_key] ) ) self.basesPerTurnDoubleSpinBox.connectWithState( Preferences_StateRef_double( bdnaBasesPerTurn_prefs_key, env.prefs[bdnaBasesPerTurn_prefs_key] ) ) def ok_btn_clicked(self): """ Slot for the OK button """ if self.editCommand: self.editCommand.preview_or_finalize_structure(previewing = False) ##env.history.message(self.editCommand.logMessage) self.win.toolsDone() def cancel_btn_clicked(self): """ Slot for the Cancel button. """ if self.editCommand: self.editCommand.cancelStructure() self.win.toolsCancel() def _update_widgets_in_PM_before_show(self): """ Update various widgets in this Property manager. Overrides superclass method @see: MotorPropertyManager._update_widgets_in_PM_before_show @see: self.show where it is called. """ pass def getFlyoutActionList(self): """ returns custom actionlist that will be used in a specific mode or editing a feature etc Example: while in movie mode, the _createFlyoutToolBar method calls this """ #'allActionsList' returns all actions in the flyout toolbar #including the subcontrolArea actions allActionsList = [] #Action List for subcontrol Area buttons. #In this mode there is really no subcontrol area. #We will treat subcontrol area same as 'command area' #(subcontrol area buttons will have an empty list as their command area #list). We will set the Comamnd Area palette background color to the #subcontrol area. subControlAreaActionList =[] self.exitEditCommandAction.setChecked(True) subControlAreaActionList.append(self.exitEditCommandAction) separator = QAction(self.w) separator.setSeparator(True) subControlAreaActionList.append(separator) allActionsList.extend(subControlAreaActionList) #Empty actionlist for the 'Command Area' commandActionLists = [] #Append empty 'lists' in 'commandActionLists equal to the #number of actions in subControlArea for i in range(len(subControlAreaActionList)): lst = [] commandActionLists.append(lst) params = (subControlAreaActionList, commandActionLists, allActionsList) return params def _addGroupBoxes( self ): """ Add the DNA Property Manager group boxes. """ self._pmReferencePlaneGroupBox = PM_GroupBox( self, title = "Placement Options" ) self._loadReferencePlaneGroupBox( self._pmReferencePlaneGroupBox ) self._pmGroupBox1 = PM_GroupBox( self, title = "Endpoints" ) self._loadGroupBox1( self._pmGroupBox1 ) self._pmGroupBox1.hide() self._pmGroupBox2 = PM_GroupBox( self, title = "Parameters" ) self._loadGroupBox2( self._pmGroupBox2 ) self._displayOptionsGroupBox = PM_GroupBox( self, title = "Display Options" ) self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox ) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 3. """ #Folllowing toolbutton facilitates entering a temporary DnaLineMode #to create a DNA using endpoints of the specified line. self.specifyDnaLineButton = PM_ToolButton( pmGroupBox, text = "Specify Endpoints", iconPath = "ui/actions/Properties Manager/Pencil.png", spanWidth = True ) self.specifyDnaLineButton.setCheckable(True) self.specifyDnaLineButton.setAutoRaise(True) self.specifyDnaLineButton.setToolButtonStyle( Qt.ToolButtonTextBesideIcon) #EndPoint1 and endPoint2 coordinates. These widgets are hidden # as of 2007- 12 - 05 self._endPoint1SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox, label = "End Point 1") self.x1SpinBox = self._endPoint1SpinBoxes.xSpinBox self.y1SpinBox = self._endPoint1SpinBoxes.ySpinBox self.z1SpinBox = self._endPoint1SpinBoxes.zSpinBox self._endPoint2SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox, label = "End Point 2") self.x2SpinBox = self._endPoint2SpinBoxes.xSpinBox self.y2SpinBox = self._endPoint2SpinBoxes.ySpinBox self.z2SpinBox = self._endPoint2SpinBoxes.zSpinBox self._endPoint1SpinBoxes.hide() self._endPoint2SpinBoxes.hide() def _loadGroupBox2(self, pmGroupBox): """ Load widgets in group box 4. """ self.conformationComboBox = \ PM_ComboBox( pmGroupBox, label = "Conformation:", choices = ["B-DNA"], setAsDefault = True) dnaModelChoices = ['PAM3', 'PAM5'] self.dnaModelComboBox = \ PM_ComboBox( pmGroupBox, label = "Model:", choices = dnaModelChoices, setAsDefault = True) self.basesPerTurnDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Bases per turn:", value = env.prefs[bdnaBasesPerTurn_prefs_key], setAsDefault = True, minimum = 8.0, maximum = 20.0, decimals = 2, singleStep = 0.1 ) self.duplexRiseDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Rise:", value = env.prefs[bdnaRise_prefs_key], setAsDefault = True, minimum = 2.0, maximum = 4.0, decimals = 3, singleStep = 0.01 ) # Strand Length (i.e. the number of bases) self.numberOfBasePairsSpinBox = \ PM_SpinBox( pmGroupBox, label = "Base pairs:", value = self._numberOfBases, setAsDefault = False, minimum = 0, maximum = 10000 ) self.numberOfBasePairsSpinBox.setDisabled(True) # Duplex Length self.duplexLengthLineEdit = \ PM_LineEdit( pmGroupBox, label = "Duplex length: ", text = "0.0 Angstroms", setAsDefault = False) self.duplexLengthLineEdit.setDisabled(True) def _loadDisplayOptionsGroupBox(self, pmGroupBox): """ Load widgets in the Display Options GroupBox @see: DnaOrCnt_PropertyManager. _loadDisplayOptionsGroupBox """ #Call the superclass method that loads the cursor text checkboxes. #Note, as of 2008-05-19, the superclass, DnaOrCnt_PropertyManager #only loads the cursor text groupboxes. Subclasses like this can #call custom methods like self._loadCursorTextCheckBoxes etc if they #don't need all groupboxes that the superclass loads. _superclass._loadDisplayOptionsGroupBox(self, pmGroupBox) self._rubberbandLineGroupBox = PM_GroupBox( pmGroupBox, title = 'Rubber band line:') dnaLineChoices = ['Ribbons', 'Ladder'] self.dnaRubberBandLineDisplayComboBox = \ PM_ComboBox( self._rubberbandLineGroupBox , label = " Display as:", choices = dnaLineChoices, setAsDefault = True) self.lineSnapCheckBox = \ PM_CheckBox(self._rubberbandLineGroupBox , text = 'Enable line snap' , widgetColumn = 1, state = Qt.Checked ) def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Overrides DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox """ connect_checkbox_with_boolean_pref( self.showCursorTextCheckBox , dnaDuplexEditCommand_showCursorTextCheckBox_prefs_key) def _params_for_creating_cursorTextCheckBoxes(self): """ Returns params needed to create various cursor text checkboxes connected to prefs_keys that allow custom cursor texts. @return: A list containing tuples in the following format: ('checkBoxTextString' , preference_key). PM_PrefsCheckBoxes uses this data to create checkboxes with the the given names and connects them to the provided preference keys. (Note that PM_PrefsCheckBoxes puts thes within a GroupBox) @rtype: list @see: PM_PrefsCheckBoxes @see: self._loadDisplayOptionsGroupBox where this list is used. @see: Superclass method which is overridden here -- DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = \ [ #Format: (" checkbox text", prefs_key) ("Number of base pairs", dnaDuplexEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key), ("Number of turns", dnaDuplexEditCommand_cursorTextCheckBox_numberOfTurns_prefs_key), ("Duplex length", dnaDuplexEditCommand_cursorTextCheckBox_length_prefs_key), ("Angle", dnaDuplexEditCommand_cursorTextCheckBox_angle_prefs_key) ] return params def _addToolTipText(self): """ Tool Tip text for widgets in the DNA Property Manager. """ pass def conformationComboBoxChanged( self, inIndex ): """ Slot for the Conformation combobox. It is called whenever the Conformation choice is changed. @param inIndex: The new index. @type inIndex: int """ conformation = self.conformationComboBox.currentText() if conformation == "B-DNA": self.basesPerTurnDoubleSpinBox.setValue("10.0") elif conformation == "Z-DNA": self.basesPerTurnDoubleSpinBox.setValue("12.0") else: msg = redmsg("conformationComboBoxChanged(): \ Error - unknown DNA conformation. Index = "+ inIndex) env.history.message(msg) self.duplexLengthSpinBox.setSingleStep(getDuplexRise(conformation)) def numberOfBasesChanged( self, numberOfBases ): """ Slot for the B{Number of Bases} spinbox. """ # Update the Duplex Length lineEdit widget. text = str(getDuplexLength(self._conformation, numberOfBases, self._duplexRise)) \ + " Angstroms" self.duplexLengthLineEdit.setText(text) return def basesPerTurnChanged( self, basesPerTurn ): """ Slot for the B{Bases per turn} spinbox. """ self.editCommand.basesPerTurn = basesPerTurn self._basesPerTurn = basesPerTurn return def duplexRiseChanged( self, rise ): """ Slot for the B{Rise} spinbox. """ self.editCommand.duplexRise = rise self._duplexRise = rise return def getParameters(self): """ Return the parameters from this property manager to be used to create the DNA duplex. @return: A tuple containing the parameters @rtype: tuple @see: L{DnaDuplex_EditCommand._gatherParameters} where this is used """ numberOfBases = self.numberOfBasePairsSpinBox.value() dnaForm = str(self.conformationComboBox.currentText()) basesPerTurn = self.basesPerTurnDoubleSpinBox.value() duplexRise = self.duplexRiseDoubleSpinBox.value() dnaModel = str(self.dnaModelComboBox.currentText()) # First endpoint (origin) of DNA duplex x1 = self.x1SpinBox.value() y1 = self.y1SpinBox.value() z1 = self.z1SpinBox.value() # Second endpoint (direction vector/axis) of DNA duplex. x2 = self.x2SpinBox.value() y2 = self.y2SpinBox.value() z2 = self.z2SpinBox.value() if not self.endPoint1: self.endPoint1 = V(x1, y1, z1) if not self.endPoint2: self.endPoint2 = V(x2, y2, z2) return (numberOfBases, dnaForm, dnaModel, basesPerTurn, duplexRise, self.endPoint1, self.endPoint2) def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ whatsThis_DnaDuplexPropertyManager(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 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
class PeptideGeneratorPropertyManager(PM_Dialog): """ The PeptideGeneratorPropertyManager class provides a Property Manager for the "Build > Peptide" command. """ # The title that appears in the property manager header. title = "Peptide Generator" # The name of this property manager. This will be set to # the name of the PropMgr (this) object via setObjectName(). pmName = title # The relative path to PNG file that appears in the header. iconPath = "ui/actions/Tools/Build Structures/Peptide.png" def __init__(self): """Construct the Peptide Property Manager. """ PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title) # phi psi angles will define the secondary structure of the peptide chain self.phi = -57.0 self.psi = -47.0 self.chirality = 1 self.ss_idx = 1 self.peptide_cache = [] self.updateMessageGroupBox() def updateMessageGroupBox(self): msg = "" msg = msg + "Click on the Amino Acid buttons to add a new residuum to\ the polypeptide chain. Click <b>Done</b> to insert it into the project." # This causes the "Message" box to be displayed as well. # setAsDefault=True causes this message to be reset whenever # this PropMgr is (re)displayed via show(). Mark 2007-06-01. self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=True) def _addGroupBoxes(self): """ Add the group boxe to the Peptide Property Manager dialog. """ self.pmGroupBox1 = \ PM_GroupBox( self, title = "Peptide Parameters" ) # Add group box widgets. self._loadGroupBox1(self.pmGroupBox1) def _loadGroupBox1(self, inPmGroupBox): """ Load widgets in the group box. """ memberChoices = ["Custom", "Alpha helix", "Beta strand", "Pi helix", "3_10 helix", "Polyproline-II helix", "Fully extended"] self.aaTypeComboBox= \ PM_ComboBox( inPmGroupBox, label = "Conformation :", choices = memberChoices, index = 1, setAsDefault = True, spanWidth = False ) self.connect( self.aaTypeComboBox, SIGNAL("currentIndexChanged(int)"), self._aaTypeChanged) self.phiAngleField = \ PM_DoubleSpinBox( inPmGroupBox, label = "Phi angle :", value = -57.0, setAsDefault = True, minimum = -180.0, maximum = 180.0, singleStep = 1.0, decimals = 1, suffix = " degrees") self.connect( self.phiAngleField, SIGNAL("valueChanged(double)"), self._aaPhiAngleChanged) self.phiAngleField.setEnabled(False) self.psiAngleField = \ PM_DoubleSpinBox( inPmGroupBox, label = "Psi angle :", value = -47.0, setAsDefault = True, minimum = -180.0, maximum = 180.0, singleStep = 1.0, decimals = 1, suffix = " degrees" ) self.connect( self.psiAngleField, SIGNAL("valueChanged(double)"), self._aaPsiAngleChanged) self.psiAngleField.setEnabled(False) self.invertChiralityPushButton = \ PM_PushButton( inPmGroupBox, text = 'Invert chirality' , spanWidth = False ) self.connect(self.invertChiralityPushButton, SIGNAL("clicked()"), self._aaChiralityChanged) self.aaTypesButtonGroup = \ PM_ToolButtonGrid( inPmGroupBox, buttonList = AA_BUTTON_LIST, label = "Amino acids :", checkedId = 0, setAsDefault = True ) self.connect( self.aaTypesButtonGroup.buttonGroup, SIGNAL("buttonClicked(int)"), self._setAminoAcidType) self.sequenceEditor = \ PM_TextEdit( inPmGroupBox, label = "Sequence", spanWidth = True ) self.sequenceEditor.insertHtml("", False, 4, 10, True) self.sequenceEditor.setReadOnly(True) self.startOverButton = \ PM_PushButton( inPmGroupBox, label = "", text = "Start Over", spanWidth = True, setAsDefault = True ) self.connect( self.startOverButton, SIGNAL("clicked()"), self._startOverClicked) def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_PeptideGeneratorPropertyManager whatsThis_PeptideGeneratorPropertyManager(self) def _addToolTipText(self): """ Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_PeptideGeneratorPropertyManager ToolTip_PeptideGeneratorPropertyManager(self) def _aaChiralityChanged(self): """ Set chirality of the peptide chain. """ self.psi *= -1 self.phi *= -1 self.phiAngleField.setValue(self.phi) self.psiAngleField.setValue(self.psi) def _aaTypeChanged(self, idx): """ Slot for Peptide Structure Type combobox. Changes phi/psi angles for secondary structure. """ self.ss_idx = idx if idx == 0: self.phiAngleField.setEnabled(True) self.psiAngleField.setEnabled(True) else: self.phiAngleField.setEnabled(False) self.psiAngleField.setEnabled(False) if idx == 1: # alpha helix self.phi = -57.0 self.psi = -47.0 elif idx == 2: # beta strand self.phi = -135.0 self.psi = 135.0 elif idx == 3: # 3-10 helix self.phi = -55.0 self.psi = -70.0 elif idx == 4: # pi helix self.phi = -49.0 self.psi = -26.0 elif idx == 5: # polyprolin-II self.phi = -75.0 self.psi = 150.0 elif idx == 6: # fully extended self.phi = -180.0 self.psi = 180.0 else: self.phi = self.phiAngleField.value() self.psi = self.psiAngleField.value() self.phi *= self.chirality self.psi *= self.chirality self.phiAngleField.setValue(self.phi) self.psiAngleField.setValue(self.psi) pass def _aaPhiAngleChanged(self, phi): self.phi = self.phiAngleField.value() pass def _aaPsiAngleChanged(self, psi): self.psi = self.psiAngleField.value() pass def _setAminoAcidType(self, aaTypeIndex): """ Adds a new amino acid to the peptide molecule. """ button, idx, short_name, dum, name, symbol, x, y = AA_BUTTON_LIST[aaTypeIndex] if self.ss_idx==1: aa_txt = "<font color=red>" elif self.ss_idx==2: aa_txt = "<font color=blue>" elif self.ss_idx==3: aa_txt = "<font color=green>" elif self.ss_idx==4: aa_txt = "<font color=orange>" elif self.ss_idx==5: aa_txt = "<font color=magenta>" elif self.ss_idx==6: aa_txt = "<font color=darkblue>" else: aa_txt = "<font color=black>" aa_txt += symbol+"</font>" self.sequenceEditor.insertHtml(aa_txt, False, 4, 10, False) self.addAminoAcid(aaTypeIndex) pass def _startOverClicked(self): """ Resets a sequence in the sequence editor window. """ self.sequenceEditor.clear() self.peptide_cache = [] pass
class InsertNanotube_PropertyManager( DnaOrCnt_PropertyManager): """ The InsertNanotube_PropertyManager class provides a Property Manager for the B{Build > Nanotube > CNT} command. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Insert Nanotube" pmName = title iconPath = "ui/actions/Tools/Build Structures/InsertNanotube.png" def __init__( self, win, editCommand ): """ Constructor for the Nanotube property manager. """ self.endPoint1 = None self.endPoint2 = None self.nanotube = Nanotube() # A 5x5 CNT. _superclass.__init__( self, win, editCommand) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_WHATS_THIS_BUTTON) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect change_connect( self.ntTypeComboBox, SIGNAL("currentIndexChanged(const QString&)"), self._ntTypeComboBoxChanged ) change_connect(self.chiralityNSpinBox, SIGNAL("valueChanged(int)"), self._chiralityFixup) change_connect(self.chiralityMSpinBox, SIGNAL("valueChanged(int)"), self._chiralityFixup) change_connect(self.endingsComboBox, SIGNAL("currentIndexChanged(const QString&)"), self._endingsComboBoxChanged ) # This spin box is currently hidden. change_connect(self.bondLengthDoubleSpinBox, SIGNAL("valueChanged(double)"), self._bondLengthChanged) change_connect(self.showCursorTextCheckBox, SIGNAL('stateChanged(int)'), self._update_state_of_cursorTextGroupBox) def ok_btn_clicked(self): """ Slot for the OK button """ if self.editCommand: self.editCommand.preview_or_finalize_structure(previewing = False) ##env.history.message(self.editCommand.logMessage) self.win.toolsDone() def cancel_btn_clicked(self): """ Slot for the Cancel button. """ if self.editCommand: self.editCommand.cancelStructure() self.win.toolsCancel() def _update_widgets_in_PM_before_show(self): """ Update various widgets in this Property manager. Overrides MotorPropertyManager._update_widgets_in_PM_before_show. The various widgets , (e.g. spinboxes) will get values from the structure for which this propMgr is constructed for (self.editcCntroller.struct) @see: MotorPropertyManager._update_widgets_in_PM_before_show @see: self.show where it is called. """ pass def getFlyoutActionList(self): """ Returns custom actionlist that will be used in a specific mode or editing a feature etc Example: while in movie mode, the _createFlyoutToolBar method calls this. """ #'allActionsList' returns all actions in the flyout toolbar #including the subcontrolArea actions allActionsList = [] #Action List for subcontrol Area buttons. #In this mode there is really no subcontrol area. #We will treat subcontrol area same as 'command area' #(subcontrol area buttons will have an empty list as their command area #list). We will set the Comamnd Area palette background color to the #subcontrol area. subControlAreaActionList =[] self.exitEditCommandAction.setChecked(True) subControlAreaActionList.append(self.exitEditCommandAction) separator = QAction(self.w) separator.setSeparator(True) subControlAreaActionList.append(separator) allActionsList.extend(subControlAreaActionList) #Empty actionlist for the 'Command Area' commandActionLists = [] #Append empty 'lists' in 'commandActionLists equal to the #number of actions in subControlArea for i in range(len(subControlAreaActionList)): lst = [] commandActionLists.append(lst) params = (subControlAreaActionList, commandActionLists, allActionsList) return params def _addGroupBoxes( self ): """ Add the Insert Nanotube Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Endpoints" ) self._loadGroupBox1( self._pmGroupBox1 ) self._pmGroupBox1.hide() self._pmGroupBox2 = PM_GroupBox( self, title = "Parameters" ) self._loadGroupBox2( self._pmGroupBox2 ) self._displayOptionsGroupBox = PM_GroupBox( self, title = "Display Options" ) self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox ) self._pmGroupBox3 = PM_GroupBox( self, title = "Nanotube Distortion" ) self._loadGroupBox3( self._pmGroupBox3 ) self._pmGroupBox3.hide() #@ Temporary. self._pmGroupBox4 = PM_GroupBox( self, title = "Multi-Walled CNTs" ) self._loadGroupBox4( self._pmGroupBox4 ) self._pmGroupBox4.hide() #@ Temporary. self._pmGroupBox5 = PM_GroupBox( self, title = "Advanced Options" ) self._loadGroupBox5( self._pmGroupBox5 ) self._pmGroupBox5.hide() #@ Temporary. def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 1. """ #Following toolbutton facilitates entering a temporary NanotubeLineMode #to create a CNT using endpoints of the specified line. self.specifyCntLineButton = PM_ToolButton( pmGroupBox, text = "Specify Endpoints", iconPath = "ui/actions/Properties Manager/Pencil.png", spanWidth = True ) self.specifyCntLineButton.setCheckable(True) self.specifyCntLineButton.setAutoRaise(True) self.specifyCntLineButton.setToolButtonStyle( Qt.ToolButtonTextBesideIcon) #EndPoint1 and endPoint2 coordinates. These widgets are hidden # as of 2007- 12 - 05 self._endPoint1SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox, label = "End Point 1") self.x1SpinBox = self._endPoint1SpinBoxes.xSpinBox self.y1SpinBox = self._endPoint1SpinBoxes.ySpinBox self.z1SpinBox = self._endPoint1SpinBoxes.zSpinBox self._endPoint2SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox, label = "End Point 2") self.x2SpinBox = self._endPoint2SpinBoxes.xSpinBox self.y2SpinBox = self._endPoint2SpinBoxes.ySpinBox self.z2SpinBox = self._endPoint2SpinBoxes.zSpinBox self._endPoint1SpinBoxes.hide() self._endPoint2SpinBoxes.hide() def _loadGroupBox2(self, pmGroupBox): """ Load widgets in group box 2. """ _ntTypeChoices = ['Carbon', 'Boron Nitride'] self.ntTypeComboBox = \ PM_ComboBox( pmGroupBox, label = "Type:", choices = _ntTypeChoices, setAsDefault = True) self.ntRiseDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Rise:", value = self.nanotube.getRise(), setAsDefault = True, minimum = 2.0, maximum = 4.0, decimals = 3, singleStep = 0.01 ) self.ntRiseDoubleSpinBox.hide() # Nanotube Length self.ntLengthLineEdit = \ PM_LineEdit( pmGroupBox, label = "Nanotube Length: ", text = "0.0 Angstroms", setAsDefault = False) self.ntLengthLineEdit.setDisabled(True) self.ntLengthLineEdit.hide() # Nanotube diameter self.ntDiameterLineEdit = \ PM_LineEdit( pmGroupBox, label = "Diameter: ", setAsDefault = False) self.ntDiameterLineEdit.setDisabled(True) self.updateNanotubeDiameter() self.chiralityNSpinBox = \ PM_SpinBox( pmGroupBox, label = "Chirality (n):", value = self.nanotube.getChiralityN(), minimum = 2, maximum = 100, setAsDefault = True ) self.chiralityMSpinBox = \ PM_SpinBox( pmGroupBox, label = "Chirality (m):", value = self.nanotube.getChiralityM(), minimum = 0, maximum = 100, setAsDefault = True ) # How about having user prefs for CNT and BNNT bond lengths? # I'm guessing that if the user wants to set these values, they will # do it once and would like those bond length values persist forever. # Need to discuss with others to determine if this spinbox comes out. # --Mark 2008-03-29 self.bondLengthDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Bond length:", value = self.nanotube.getBondLength(), setAsDefault = True, minimum = 1.0, maximum = 3.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) #self.bondLengthDoubleSpinBox.hide() endingChoices = ["Hydrogen", "None"] # Removed:, "Nitrogen"] self.endingsComboBox= \ PM_ComboBox( pmGroupBox, label = "Endings:", choices = endingChoices, index = 0, setAsDefault = True, spanWidth = False ) def _loadGroupBox3(self, inPmGroupBox): """ Load widgets in group box 3. """ self.zDistortionDoubleSpinBox = \ PM_DoubleSpinBox( inPmGroupBox, label = "Z-distortion:", value = 0.0, setAsDefault = True, minimum = 0.0, maximum = 10.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) self.xyDistortionDoubleSpinBox = \ PM_DoubleSpinBox( inPmGroupBox, label = "XY-distortion:", value = 0.0, setAsDefault = True, minimum = 0.0, maximum = 2.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) self.twistSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Twist:", value = 0, setAsDefault = True, minimum = 0, maximum = 100, # What should maximum be? suffix = " deg/A" ) self.bendSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Bend:", value = 0, setAsDefault = True, minimum = 0, maximum = 360, suffix = " deg" ) def _loadGroupBox4(self, inPmGroupBox): """ Load widgets in group box 4. """ # "Number of Nanotubes" SpinBox self.mwntCountSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Number:", value = 1, setAsDefault = True, minimum = 1, maximum = 10, suffix = " nanotubes" ) self.mwntCountSpinBox.setSpecialValueText("SWNT") # "Spacing" lineedit. self.mwntSpacingDoubleSpinBox = \ PM_DoubleSpinBox( inPmGroupBox, label = "Spacing:", value = 2.46, setAsDefault = True, minimum = 1.0, maximum = 10.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) def _loadGroupBox5(self, pmGroupBox): """ Load widgets in group box 5. """ self._rubberbandLineGroupBox = PM_GroupBox( pmGroupBox, title = 'Rubber band Line:') ntLineChoices = ['Ladder'] self.ntRubberBandLineDisplayComboBox = \ PM_ComboBox( self._rubberbandLineGroupBox , label = " Display as:", choices = ntLineChoices, setAsDefault = True) self.lineSnapCheckBox = \ PM_CheckBox(self._rubberbandLineGroupBox , text = 'Enable line snap' , widgetColumn = 1, state = Qt.Checked ) def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Overrides DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox """ connect_checkbox_with_boolean_pref( self.showCursorTextCheckBox , insertNanotubeEditCommand_showCursorTextCheckBox_prefs_key ) def _params_for_creating_cursorTextCheckBoxes(self): """ Returns params needed to create various cursor text checkboxes connected to prefs_keys that allow custom cursor texts. @return: A list containing tuples in the following format: ('checkBoxTextString' , preference_key). PM_PrefsCheckBoxes uses this data to create checkboxes with the the given names and connects them to the provided preference keys. (Note that PM_PrefsCheckBoxes puts thes within a GroupBox) @rtype: list @see: PM_PrefsCheckBoxes @see: self._loadDisplayOptionsGroupBox where this list is used. @see: Superclass method which is overridden here -- DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = \ [ #Format: (" checkbox text", prefs_key) ("Nanotube length", insertNanotubeEditCommand_cursorTextCheckBox_length_prefs_key ), ("Angle", insertNanotubeEditCommand_cursorTextCheckBox_angle_prefs_key ) ] return params def _addToolTipText(self): """ Tool Tip text for widgets in the Insert Nanotube Property Manager. """ pass def _setEndPoints(self): """ Set the two endpoints of the nanotube using the values from the X, Y, Z coordinate spinboxes in the property manager. @note: The group box containing the 2 sets of XYZ spin boxes are currently hidden. """ # First endpoint (origin) of nanotube x1 = self.x1SpinBox.value() y1 = self.y1SpinBox.value() z1 = self.z1SpinBox.value() # Second endpoint (direction vector/axis) of nanotube. x2 = self.x2SpinBox.value() y2 = self.y2SpinBox.value() z2 = self.z2SpinBox.value() if not self.endPoint1: self.endPoint1 = V(x1, y1, z1) if not self.endPoint2: self.endPoint2 = V(x2, y2, z2) self.nanotube.setEndPoints(self.endPoint1, self.endPoint2) # Need arg "recompute=True", which will recompute the second # endpoint (endPoint2) using the nanotube rise. def getParameters(self): """ Return the parameters from this property manager to be used to create the nanotube. @return: A nanotube instance with its attrs set to the current parameters in the property manager. @rtype: L{Nanotube} @see: L{InsertNanotube_EditCommand._gatherParameters} where this is used """ self._setEndPoints() return (self.nanotube) def _ntTypeComboBoxChanged( self, type ): """ Slot for the Type combobox. It is called whenever the Type choice is changed. @param inIndex: The new index. @type inIndex: int """ self.nanotube.setType(str(type)) print "Bond Length =", self.nanotube.getBondLength() self.bondLengthDoubleSpinBox.setValue(self.nanotube.getBondLength()) #self.bondLengthDoubleSpinBox.setValue(ntBondLengths[inIndex]) def _bondLengthChanged(self, bondLength): """ Slot for the B{Bond Length} spinbox. """ self.nanotube.setBondLength(bondLength) self.updateNanotubeDiameter() return def _chiralityFixup(self, spinBoxValueJunk = None): """ Slot for several validators for different parameters. This gets called whenever the user changes the n, m chirality values. @param spinBoxValueJunk: This is the Spinbox value from the valueChanged signal. It is not used. We just want to know that the spinbox value has changed. @type spinBoxValueJunk: double or None """ _n, _m = self.nanotube.setChirality(self.chiralityNSpinBox.value(), self.chiralityMSpinBox.value()) #self.n, self.m = self.nanotube.getChirality() self.connect_or_disconnect_signals(isConnect = False) self.chiralityNSpinBox.setValue(_n) self.chiralityMSpinBox.setValue(_m) self.connect_or_disconnect_signals(isConnect = True) self.updateNanotubeDiameter() def updateNanotubeDiameter(self): """ Update the nanotube Diameter lineEdit widget. """ diameterText = "%-7.4f Angstroms" % (self.nanotube.getDiameter()) self.ntDiameterLineEdit.setText(diameterText) # ntRiseDoubleSpinBox is currently hidden. self.ntRiseDoubleSpinBox.setValue(self.nanotube.getRise()) def _endingsComboBoxChanged(self, endings): """ Slot for the B{Ending} combobox. @param endings: The option's text. @type endings: string """ self.nanotube.setEndings(str(endings)) return def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ whatsThis_InsertNanotube_PropertyManager(self) return
class DnaStrand_PropertyManager(DnaOrCnt_PropertyManager): """ The DnaStrand_PropertyManager class provides a Property Manager for the DnaStrand_EditCommand. @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 = "DnaStrand Properties" pmName = title iconPath = "ui/actions/Properties Manager/Strand.png" def __init__(self, win, editCommand): """ Constructor for the Build DNA property manager. """ #For model changed signal self.previousSelectionParams = None #see self.connect_or_disconnect_signals for comment about this flag self.isAlreadyConnected = False self.isAlreadyDisconnected = False self.sequenceEditor = None self._numberOfBases = 0 self._conformation = 'B-DNA' self.duplexRise = 3.18 self.basesPerTurn = 10 self.dnaModel = 'PAM3' _superclass.__init__(self, win, editCommand) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) self._loadSequenceEditor() msg = "Use resize handles to resize the strand. Use sequence editor"\ "to assign a new sequence or the current one to a file." self.updateMessage(msg) def _addGroupBoxes(self): """ Add the DNA Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox(self, title="Parameters") self._loadGroupBox1(self._pmGroupBox1) self._displayOptionsGroupBox = PM_GroupBox(self, title="Display Options") self._loadDisplayOptionsGroupBox(self._displayOptionsGroupBox) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 4. """ self.nameLineEdit = PM_LineEdit(pmGroupBox, label="Strand name:", text="", setAsDefault=False) self.numberOfBasesSpinBox = \ PM_SpinBox( pmGroupBox, label = "Number of bases:", value = self._numberOfBases, setAsDefault = False, minimum = 2, maximum = 10000 ) self.basesPerTurnDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Bases per turn:", value = self.basesPerTurn, setAsDefault = True, minimum = 8.0, maximum = 20.0, decimals = 2, singleStep = 0.1 ) self.duplexRiseDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Rise:", value = self.duplexRise, setAsDefault = True, minimum = 2.0, maximum = 4.0, decimals = 3, singleStep = 0.01 ) self.disableStructHighlightingCheckbox = \ PM_CheckBox( pmGroupBox, text = "Don't highlight while editing DNA", widgetColumn = 0, state = Qt.Unchecked, setAsDefault = True, spanWidth = True ) #As of 2008-03-31, the properties such as number of bases will be #editable only by using the resize handles. post FNANO we will support #the self.numberOfBasesSpinBox.setEnabled(False) self.basesPerTurnDoubleSpinBox.setEnabled(False) self.duplexRiseDoubleSpinBox.setEnabled(False) def _loadSequenceEditor(self): """ Temporary code that shows the Sequence editor ..a doc widget docked at the bottom of the mainwindow. The implementation is going to change before 'rattleSnake' product release. As of 2007-11-20: This feature (sequence editor) is waiting for the ongoing dna model work to complete. """ self.sequenceEditor = self.win.createDnaSequenceEditorIfNeeded() self.sequenceEditor.hide() def _loadDisplayOptionsGroupBox(self, pmGroupBox): """ Overrides superclass method. Also loads the color chooser widget. """ self._loadColorChooser(pmGroupBox) _superclass._loadDisplayOptionsGroupBox(self, pmGroupBox) def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Overrides DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox """ connect_checkbox_with_boolean_pref( self.showCursorTextCheckBox, dnaStrandEditCommand_showCursorTextCheckBox_prefs_key) def _params_for_creating_cursorTextCheckBoxes(self): """ Returns params needed to create various cursor text checkboxes connected to prefs_keys that allow custom cursor texts. @return: A list containing tuples in the following format: ('checkBoxTextString' , preference_key). PM_PrefsCheckBoxes uses this data to create checkboxes with the the given names and connects them to the provided preference keys. (Note that PM_PrefsCheckBoxes puts thes within a GroupBox) @rtype: list @see: PM_PrefsCheckBoxes @see: self._loadDisplayOptionsGroupBox where this list is used. @see: Superclass method which is overridden here -- DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = \ [ #Format: (" checkbox text", prefs_key) ("Number of bases", dnaStrandEditCommand_cursorTextCheckBox_numberOfBases_prefs_key), ("Number of bases to be changed", dnaStrandEditCommand_cursorTextCheckBox_changedBases_prefs_key) ] return params def getParameters(self): numberOfBases = self.numberOfBasesSpinBox.value() dnaForm = self._conformation dnaModel = self.dnaModel basesPerTurn = self.basesPerTurn duplexRise = self.duplexRise color = self._colorChooser.getColor() return (numberOfBases, dnaForm, dnaModel, basesPerTurn, duplexRise, color) def setParameters(self, params): """ This is usually called when you are editing an existing structure. Some property manager ui elements then display the information obtained from the object being edited. TODO: - Make this a EditCommand_PM API method? - See also the routines GraphicsMode.setParams or object.setProps ..better to name them all in one style? """ #Set the duplex rise and bases per turn spinbox values. numberOfBases, \ dnaForm, \ dnaModel, \ basesPerTurn, \ duplexRise, \ color = params if numberOfBases is not None: self.numberOfBasesSpinBox.setValue(numberOfBases) if dnaForm is not None: self._conformation = dnaForm if dnaModel is not None: self.dnaModel = dnaModel if duplexRise is not None: self.duplexRiseDoubleSpinBox.setValue(duplexRise) if basesPerTurn is not None: self.basesPerTurnDoubleSpinBox.setValue(basesPerTurn) if color is not None: self._colorChooser.setColor(color) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ #TODO: This is a temporary fix for a bug. When you invoke a temporary # mode Entering such a temporary mode keeps the signals of #PM from the previous mode connected ( #but while exiting that temporary mode and reentering the #previous mode, it atucally reconnects the signal! This gives rise to #lots of bugs. This needs more general fix in Temporary mode API. # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py if isConnect and self.isAlreadyConnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to connect widgets"\ "in this PM that are already connected." ) return if not isConnect and self.isAlreadyDisconnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to disconnect widgets"\ "in this PM that are already disconnected.") return self.isAlreadyConnected = isConnect self.isAlreadyDisconnected = not isConnect if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect if self.sequenceEditor: self.sequenceEditor.connect_or_disconnect_signals(isConnect) _superclass.connect_or_disconnect_signals(self, isConnect) change_connect(self.disableStructHighlightingCheckbox, SIGNAL('stateChanged(int)'), self.change_struct_highlightPolicy) change_connect(self.showCursorTextCheckBox, SIGNAL('stateChanged(int)'), self._update_state_of_cursorTextGroupBox) def model_changed(self): """ @see: DnaStrand_EditCommand.model_changed() @see: DnaStrand_EditCommand.hasResizableStructure() """ isStructResizable, why_not = self.editCommand.hasResizableStructure() if not isStructResizable: #disable all widgets if self._pmGroupBox1.isEnabled(): self._pmGroupBox1.setEnabled(False) msg1 = ("Viewing properties of %s <br>") % ( self.editCommand.struct.name) msg2 = redmsg("DnaStrand is not resizable. Reason: %s" % (why_not)) self.updateMessage(msg1 + msg2) else: if not self._pmGroupBox1.isEnabled(): self._pmGroupBox1.setEnabled(True) msg1 = ("Viewing properties of %s <br>") % ( self.editCommand.struct.name) msg2 = "Use resize handles to resize the strand. Use sequence editor"\ "to assign a new sequence or the current one to a file." self.updateMessage(msg1 + msg2) def show(self): """ Show this PM As of 2007-11-20, it also shows the Sequence Editor widget and hides the history widget. This implementation may change in the near future This method also retrives the name information from the editCommand's structure for its name line edit field. @see: DnaStrand_EditCommand.getStructureName() @see: self.close() """ _superclass.show(self) self._showSequenceEditor() if self.editCommand is not None: name = self.editCommand.getStructureName() if name is not None: self.nameLineEdit.setText(name) def close(self): """ Close this property manager. Also sets the name of the self.editCommand's structure to the one displayed in the line edit field. @see self.show() @see: DnaSegment_EditCommand.setStructureName """ if self.editCommand is not None: name = str(self.nameLineEdit.text()) self.editCommand.setStructureName(name) if self.sequenceEditor: self.sequenceEditor.close() _superclass.close(self) def _showSequenceEditor(self): if self.sequenceEditor: if not self.sequenceEditor.isVisible(): #Show the sequence editor #ATTENTION: the sequence editor also closes (temporarily) the #reports dockwidget (if visible) Its state is later restored when #the sequuence Editor is closed. self.sequenceEditor.show() self.updateSequence() def updateSequence(self): """ Update the sequence string in the sequence editor @see: DnaSequenceEditor.setSequence() @see DnaSequenceEditor._determine_complementSequence() @see: DnaSequenceEditor.setComplementSequence() @see: DnaStrand.getStrandSequenceAndItsComplement() """ #Read in the strand sequence of the selected strand and #show it in the text edit in the sequence editor. ##strand = self.strandListWidget.getPickedItem() if not self.editCommand.hasValidStructure(): return strand = self.editCommand.struct titleString = 'Sequence Editor for ' + strand.name self.sequenceEditor.setWindowTitle(titleString) sequenceString, complementSequenceString = strand.getStrandSequenceAndItsComplement( ) if sequenceString: sequenceString = QString(sequenceString) sequenceString = sequenceString.toUpper() #Set the initial sequence (read in from the file) self.sequenceEditor.setSequence(sequenceString) #Set the initial complement sequence for DnaSequence editor. #do this independently because 'complementSequenceString' may have #some characters (such as * ) that denote a missing base on the #complementary strand. this information is used by the sequence #editor. See DnaSequenceEditor._determine_complementSequence() #for more details. See also bug 2787 self.sequenceEditor.setComplementSequence(complementSequenceString) def change_struct_highlightPolicy(self, checkedState=False): """ Change the 'highlight policy' of the structure being edited (i.e. self.editCommand.struct) . @param checkedState: The checked state of the checkbox that says 'Don't highlight while editing DNA'. So, it its True, the structure being edited won't get highlighted. @see: DnaStrand.setHighlightPolicy for more comments """ if self.editCommand and self.editCommand.hasValidStructure(): highlight = not checkedState self.editCommand.struct.setHighlightPolicy(highlight=highlight) def _addWhatsThisText(self): """ Add what's this text. Abstract method. """ pass
class PeptideGeneratorPropertyManager(PM_Dialog): """ The PeptideGeneratorPropertyManager class provides a Property Manager for the "Build > Peptide" command. """ # The title that appears in the property manager header. title = "Peptide Generator" # The name of this property manager. This will be set to # the name of the PropMgr (this) object via setObjectName(). pmName = title # The relative path to PNG file that appears in the header. iconPath = "ui/actions/Tools/Build Structures/Peptide.png" def __init__(self): """Construct the Peptide Property Manager. """ PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title) # phi psi angles will define the secondary structure of the peptide chain self.phi = -57.0 self.psi = -47.0 self.chirality = 1 self.ss_idx = 1 self.peptide_cache = [] self.updateMessageGroupBox() def updateMessageGroupBox(self): msg = "" msg = msg + "Click on the Amino Acid buttons to add a new residuum to\ the polypeptide chain. Click <b>Done</b> to insert it into the project." # This causes the "Message" box to be displayed as well. # setAsDefault=True causes this message to be reset whenever # this PropMgr is (re)displayed via show(). Mark 2007-06-01. self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=True) def _addGroupBoxes(self): """ Add the group boxe to the Peptide Property Manager dialog. """ self.pmGroupBox1 = \ PM_GroupBox( self, title = "Peptide Parameters" ) # Add group box widgets. self._loadGroupBox1(self.pmGroupBox1) def _loadGroupBox1(self, inPmGroupBox): """ Load widgets in the group box. """ memberChoices = [ "Custom", "Alpha helix", "Beta strand", "Pi helix", "3_10 helix", "Polyproline-II helix", "Fully extended" ] self.aaTypeComboBox= \ PM_ComboBox( inPmGroupBox, label = "Conformation :", choices = memberChoices, index = 1, setAsDefault = True, spanWidth = False ) self.connect(self.aaTypeComboBox, SIGNAL("currentIndexChanged(int)"), self._aaTypeChanged) self.phiAngleField = \ PM_DoubleSpinBox( inPmGroupBox, label = "Phi angle :", value = -57.0, setAsDefault = True, minimum = -180.0, maximum = 180.0, singleStep = 1.0, decimals = 1, suffix = " degrees") self.connect(self.phiAngleField, SIGNAL("valueChanged(double)"), self._aaPhiAngleChanged) self.phiAngleField.setEnabled(False) self.psiAngleField = \ PM_DoubleSpinBox( inPmGroupBox, label = "Psi angle :", value = -47.0, setAsDefault = True, minimum = -180.0, maximum = 180.0, singleStep = 1.0, decimals = 1, suffix = " degrees" ) self.connect(self.psiAngleField, SIGNAL("valueChanged(double)"), self._aaPsiAngleChanged) self.psiAngleField.setEnabled(False) self.invertChiralityPushButton = \ PM_PushButton( inPmGroupBox, text = 'Invert chirality' , spanWidth = False ) self.connect(self.invertChiralityPushButton, SIGNAL("clicked()"), self._aaChiralityChanged) self.aaTypesButtonGroup = \ PM_ToolButtonGrid( inPmGroupBox, buttonList = AA_BUTTON_LIST, label = "Amino acids :", checkedId = 0, setAsDefault = True ) self.connect(self.aaTypesButtonGroup.buttonGroup, SIGNAL("buttonClicked(int)"), self._setAminoAcidType) self.sequenceEditor = \ PM_TextEdit( inPmGroupBox, label = "Sequence", spanWidth = True ) self.sequenceEditor.insertHtml("", False, 4, 10, True) self.sequenceEditor.setReadOnly(True) self.startOverButton = \ PM_PushButton( inPmGroupBox, label = "", text = "Start Over", spanWidth = True, setAsDefault = True ) self.connect(self.startOverButton, SIGNAL("clicked()"), self._startOverClicked) def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_PeptideGeneratorPropertyManager whatsThis_PeptideGeneratorPropertyManager(self) def _addToolTipText(self): """ Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_PeptideGeneratorPropertyManager ToolTip_PeptideGeneratorPropertyManager(self) def _aaChiralityChanged(self): """ Set chirality of the peptide chain. """ self.psi *= -1 self.phi *= -1 self.phiAngleField.setValue(self.phi) self.psiAngleField.setValue(self.psi) def _aaTypeChanged(self, idx): """ Slot for Peptide Structure Type combobox. Changes phi/psi angles for secondary structure. """ self.ss_idx = idx if idx == 0: self.phiAngleField.setEnabled(True) self.psiAngleField.setEnabled(True) else: self.phiAngleField.setEnabled(False) self.psiAngleField.setEnabled(False) if idx == 1: # alpha helix self.phi = -57.0 self.psi = -47.0 elif idx == 2: # beta strand self.phi = -135.0 self.psi = 135.0 elif idx == 3: # 3-10 helix self.phi = -55.0 self.psi = -70.0 elif idx == 4: # pi helix self.phi = -49.0 self.psi = -26.0 elif idx == 5: # polyprolin-II self.phi = -75.0 self.psi = 150.0 elif idx == 6: # fully extended self.phi = -180.0 self.psi = 180.0 else: self.phi = self.phiAngleField.value() self.psi = self.psiAngleField.value() self.phi *= self.chirality self.psi *= self.chirality self.phiAngleField.setValue(self.phi) self.psiAngleField.setValue(self.psi) pass def _aaPhiAngleChanged(self, phi): self.phi = self.phiAngleField.value() pass def _aaPsiAngleChanged(self, psi): self.psi = self.psiAngleField.value() pass def _setAminoAcidType(self, aaTypeIndex): """ Adds a new amino acid to the peptide molecule. """ button, idx, short_name, dum, name, symbol, x, y = AA_BUTTON_LIST[ aaTypeIndex] if self.ss_idx == 1: aa_txt = "<font color=red>" elif self.ss_idx == 2: aa_txt = "<font color=blue>" elif self.ss_idx == 3: aa_txt = "<font color=green>" elif self.ss_idx == 4: aa_txt = "<font color=orange>" elif self.ss_idx == 5: aa_txt = "<font color=magenta>" elif self.ss_idx == 6: aa_txt = "<font color=darkblue>" else: aa_txt = "<font color=black>" aa_txt += symbol + "</font>" self.sequenceEditor.insertHtml(aa_txt, False, 4, 10, False) self.addAminoAcid(aaTypeIndex) pass def _startOverClicked(self): """ Resets a sequence in the sequence editor window. """ self.sequenceEditor.clear() self.peptide_cache = [] pass
class InsertPeptide_PropertyManager(EditCommand_PM): """ The InsertPeptide_PropertyManager class provides a Property Manager for the "Insert > Peptide" command. """ # The title that appears in the property manager header. title = "Insert Peptide" # The name of this property manager. This will be set to # the name of the PropMgr (this) object via setObjectName(). pmName = title # The relative path to PNG file that appears in the header. iconPath = "ui/actions/Command Toolbar/BuildProtein/InsertPeptide.png" # phi psi angles will define the secondary structure of the peptide chain phi = -57.0 psi = -47.0 chirality = 1 secondary = SS_HELIX current_amino_acid = 7 # Glycine # DEPRECATED ATTRS #peptide_cache = [] #peptide_cache.append((0, 0, 0)) def __init__( self, command ): """ Construct the Property Manager. """ _superclass.__init__( self, command ) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_WHATS_THIS_BUTTON) return def show(self): """ Extends superclass method. """ _superclass.show(self) self.updateMessage("Choose the peptide parameters below, then click "\ "two endpoints in the graphics area to insert a "\ "peptide chain.") return def getParameters(self): """ Return the parameters from this property manager to be used to create the peptide. @return: A tuple containing the parameters @rtype: tuple @see: L{InsertPeptide_EditCommand._gatherParameters()} where this is used """ return (self.secondary, self.phi, self.psi, self.current_amino_acid) def _addGroupBoxes(self): """ Add the group boxe to the Peptide Property Manager dialog. """ self.pmGroupBox1 = \ PM_GroupBox( self, title = "Peptide Parameters" ) # Add group box widgets. self._loadGroupBox1(self.pmGroupBox1) return def _loadGroupBox1(self, inPmGroupBox): """ Load widgets in the group box. """ memberChoices = ["Custom", "Alpha helix", "Beta strand", "Pi helix", "3_10 helix", "Polyproline-II helix", "Fully extended"] self.aaTypeComboBox= \ PM_ComboBox( inPmGroupBox, label = "Conformation:", choices = memberChoices, index = 1, setAsDefault = True, spanWidth = False ) self.connect( self.aaTypeComboBox, SIGNAL("currentIndexChanged(int)"), self._aaTypeChanged) self.phiAngleField = \ PM_DoubleSpinBox( inPmGroupBox, label = "Phi angle:", value = self.phi, setAsDefault = True, minimum = -180.0, maximum = 180.0, singleStep = 1.0, decimals = 1, suffix = " degrees") self.connect( self.phiAngleField, SIGNAL("valueChanged(double)"), self._aaPhiAngleChanged) self.phiAngleField.setEnabled(False) self.psiAngleField = \ PM_DoubleSpinBox( inPmGroupBox, label = "Psi angle:", value = self.psi, setAsDefault = True, minimum = -180.0, maximum = 180.0, singleStep = 1.0, decimals = 1, suffix = " degrees" ) self.connect( self.psiAngleField, SIGNAL("valueChanged(double)"), self._aaPsiAngleChanged) self.psiAngleField.setEnabled(False) self.aaTypesButtonGroup = \ PM_ToolButtonGrid( inPmGroupBox, buttonList = AA_BUTTON_LIST, label = "Amino acids", checkedId = self.current_amino_acid, # Glycine setAsDefault = True ) self.connect( self.aaTypesButtonGroup.buttonGroup, SIGNAL("buttonClicked(int)"), self._setAminoAcidType) return def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_InsertPeptide_PropertyManager whatsThis_InsertPeptide_PropertyManager(self) return def _addToolTipText(self): """ Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_InsertPeptide_PropertyManager ToolTip_InsertPeptide_PropertyManager(self) return def _aaChiralityChanged(self): """ Set chirality of the peptide chain. """ # This feature is currently disable as it was confusing to the users # who expected control over chirality of amino acids (D/L conformers) # rather than over polypeptide chain (left/right-handed structure). self.psi *= -1 self.phi *= -1 self.phiAngleField.setValue(self.phi) self.psiAngleField.setValue(self.psi) return def _aaTypeChanged(self, idx): """ Slot for Peptide Structure Type combo box. Changes phi/psi angles for secondary structure. @param idx: index of secondary structure combo box @type idx: int """ self.ss_idx = idx if idx == 0: self.phiAngleField.setEnabled(True) self.psiAngleField.setEnabled(True) else: self.phiAngleField.setEnabled(False) self.psiAngleField.setEnabled(False) if idx == 1: # alpha helix self.phi = -57.0 self.psi = -47.0 self.secondary = SS_HELIX elif idx == 2: # beta strand self.phi = -135.0 self.psi = 135.0 self.secondary = SS_STRAND elif idx == 3: # 3-10 helix self.phi = -55.0 self.psi = -70.0 self.secondary = SS_HELIX elif idx == 4: # pi helix self.phi = -49.0 self.psi = -26.0 self.secondary = SS_HELIX elif idx == 5: # polyprolin-II self.phi = -75.0 self.psi = 150.0 self.secondary = SS_COIL elif idx == 6: # fully extended self.phi = -180.0 self.psi = 180.0 self.secondary = SS_STRAND else: self.phi = self.phiAngleField.value() self.psi = self.psiAngleField.value() self.secondary = SS_COIL self.phi *= self.chirality self.psi *= self.chirality self.command.secondary = self.secondary self.phiAngleField.setValue(self.phi) self.psiAngleField.setValue(self.psi) return def _aaPhiAngleChanged(self, phi): """ Called when phi angle spin box has changed. @param phi: phi angle value @type phi: float """ self.phi = self.phiAngleField.value() return def _aaPsiAngleChanged(self, psi): """ Called when psi angle spin box has changed. @param psi: psi angle value @type psi: float """ self.psi = self.psiAngleField.value() return def _setAminoAcidType(self, index): """ Sets the current amino acid type to I{index}. """ self.current_amino_acid = index return # -------------------------------------------------------------------- # Deprecated methods to keep until we're certain this is working. # --Mark 2008-12-12. def addAminoAcid_DEPRECATED(self, index): """ Adds a new amino acid to the peptide molecule. """ # This commened out code is obsolete in interactive peptide builder. # The interactive peptide builder creates homopeptides. # add a new amino acid and chain conformation to the peptide cache #self.peptide_cache.append((index,self.phi,self.psi)) #self.peptide_cache[0] = (index,self.phi,self.psi) self.current_amino_acid = index return def _setAminoAcidType_DEPRECATED(self, aaTypeIndex): """ Adds a new amino acid to the peptide molecule. """ # piotr 080911: this method is obsolete as of 080911. It was used in # the old Peptide Generator. button, idx, short_name, dum, name, symbol, x, y = AA_BUTTON_LIST[aaTypeIndex] if self.ss_idx==1: aa_txt = "<font color=red>" elif self.ss_idx==2: aa_txt = "<font color=blue>" elif self.ss_idx==3: aa_txt = "<font color=green>" elif self.ss_idx==4: aa_txt = "<font color=orange>" elif self.ss_idx==5: aa_txt = "<font color=magenta>" elif self.ss_idx==6: aa_txt = "<font color=darkblue>" else: aa_txt = "<font color=black>" aa_txt += symbol+"</font>" #self.sequenceEditor.insertHtml(aa_txt, False, 4, 10, False) return
class InsertDna_PropertyManager(DnaOrCnt_PropertyManager): """ The InsertDna_PropertyManager class provides a Property Manager for the B{Insert Dna} command. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Insert DNA" pmName = title iconPath = "ui/actions/Command Toolbar/BuildDna/InsertDna.png" def __init__(self, command): """ Constructor for the DNA Duplex property manager. """ self.endPoint1 = None self.endPoint2 = None self._conformation = "B-DNA" self._numberOfBases = 0 self._basesPerTurn = getDuplexBasesPerTurn(self._conformation) self._duplexRise = getDuplexRise(self._conformation) self._duplexLength = getDuplexLength(self._conformation, self._numberOfBases) _superclass.__init__(self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_WHATS_THIS_BUTTON) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect change_connect(self._placementOptions.buttonGroup, SIGNAL("buttonClicked(int)"), self.activateSpecifyReferencePlaneTool) change_connect(self.conformationComboBox, SIGNAL("currentIndexChanged(int)"), self.conformationComboBoxChanged) change_connect(self.numberOfBasePairsSpinBox, SIGNAL("valueChanged(int)"), self.numberOfBasesChanged) change_connect(self.basesPerTurnDoubleSpinBox, SIGNAL("valueChanged(double)"), self.basesPerTurnChanged) change_connect(self.duplexRiseDoubleSpinBox, SIGNAL("valueChanged(double)"), self.duplexRiseChanged) change_connect(self.showCursorTextCheckBox, SIGNAL('stateChanged(int)'), self._update_state_of_cursorTextGroupBox) self.duplexRiseDoubleSpinBox.connectWithState( Preferences_StateRef_double(bdnaRise_prefs_key, env.prefs[bdnaRise_prefs_key])) self.basesPerTurnDoubleSpinBox.connectWithState( Preferences_StateRef_double(bdnaBasesPerTurn_prefs_key, env.prefs[bdnaBasesPerTurn_prefs_key])) def show(self): _superclass.show(self) self.updateMessage("Specify the DNA parameters below, then click "\ "two endpoints in the graphics area to insert a DNA duplex.") def _addGroupBoxes(self): """ Add the DNA Property Manager group boxes. """ self._pmReferencePlaneGroupBox = PM_GroupBox(self, title="Placement Options") self._loadReferencePlaneGroupBox(self._pmReferencePlaneGroupBox) self._pmGroupBox1 = PM_GroupBox(self, title="Endpoints") self._loadGroupBox1(self._pmGroupBox1) self._pmGroupBox1.hide() self._pmGroupBox2 = PM_GroupBox(self, title="Parameters") self._loadGroupBox2(self._pmGroupBox2) self._displayOptionsGroupBox = PM_GroupBox(self, title="Display Options") self._loadDisplayOptionsGroupBox(self._displayOptionsGroupBox) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 3. """ #Folllowing toolbutton facilitates entering a temporary DnaLineMode #to create a DNA using endpoints of the specified line. self.specifyDnaLineButton = PM_ToolButton( pmGroupBox, text="Specify Endpoints", iconPath="ui/actions/Properties Manager/Pencil.png", spanWidth=True) self.specifyDnaLineButton.setCheckable(True) self.specifyDnaLineButton.setAutoRaise(True) self.specifyDnaLineButton.setToolButtonStyle( Qt.ToolButtonTextBesideIcon) #EndPoint1 and endPoint2 coordinates. These widgets are hidden # as of 2007- 12 - 05 self._endPoint1SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox, label="End Point 1") self.x1SpinBox = self._endPoint1SpinBoxes.xSpinBox self.y1SpinBox = self._endPoint1SpinBoxes.ySpinBox self.z1SpinBox = self._endPoint1SpinBoxes.zSpinBox self._endPoint2SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox, label="End Point 2") self.x2SpinBox = self._endPoint2SpinBoxes.xSpinBox self.y2SpinBox = self._endPoint2SpinBoxes.ySpinBox self.z2SpinBox = self._endPoint2SpinBoxes.zSpinBox self._endPoint1SpinBoxes.hide() self._endPoint2SpinBoxes.hide() def _loadGroupBox2(self, pmGroupBox): """ Load widgets in group box 4. """ self.conformationComboBox = \ PM_ComboBox( pmGroupBox, label = "Conformation:", choices = ["B-DNA"], setAsDefault = True) dnaModelChoices = ['PAM3', 'PAM5'] self.dnaModelComboBox = \ PM_ComboBox( pmGroupBox, label = "Model:", choices = dnaModelChoices, setAsDefault = True) self.basesPerTurnDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Bases per turn:", value = env.prefs[bdnaBasesPerTurn_prefs_key], setAsDefault = True, minimum = 8.0, maximum = 20.0, decimals = 2, singleStep = 0.1 ) self.duplexRiseDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Rise:", value = env.prefs[bdnaRise_prefs_key], setAsDefault = True, minimum = 2.0, maximum = 4.0, decimals = 3, singleStep = 0.01 ) # Strand Length (i.e. the number of bases) self.numberOfBasePairsSpinBox = \ PM_SpinBox( pmGroupBox, label = "Base pairs:", value = self._numberOfBases, setAsDefault = False, minimum = 0, maximum = 10000 ) self.numberOfBasePairsSpinBox.setDisabled(True) # Duplex Length self.duplexLengthLineEdit = \ PM_LineEdit( pmGroupBox, label = "Duplex length: ", text = "0.0 Angstroms", setAsDefault = False) self.duplexLengthLineEdit.setDisabled(True) def _loadDisplayOptionsGroupBox(self, pmGroupBox): """ Load widgets in the Display Options GroupBox @see: DnaOrCnt_PropertyManager. _loadDisplayOptionsGroupBox """ #Call the superclass method that loads the cursor text checkboxes. #Note, as of 2008-05-19, the superclass, DnaOrCnt_PropertyManager #only loads the cursor text groupboxes. Subclasses like this can #call custom methods like self._loadCursorTextCheckBoxes etc if they #don't need all groupboxes that the superclass loads. _superclass._loadDisplayOptionsGroupBox(self, pmGroupBox) self._rubberbandLineGroupBox = PM_GroupBox(pmGroupBox, title='Rubber band line:') dnaLineChoices = ['Ribbons', 'Ladder'] self.dnaRubberBandLineDisplayComboBox = \ PM_ComboBox( self._rubberbandLineGroupBox , label = " Display as:", choices = dnaLineChoices, setAsDefault = True) self.lineSnapCheckBox = \ PM_CheckBox(self._rubberbandLineGroupBox , text = 'Enable line snap' , widgetColumn = 1, state = Qt.Checked ) def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Overrides DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox """ connect_checkbox_with_boolean_pref( self.showCursorTextCheckBox, dnaDuplexEditCommand_showCursorTextCheckBox_prefs_key) def _params_for_creating_cursorTextCheckBoxes(self): """ Returns params needed to create various cursor text checkboxes connected to prefs_keys that allow custom cursor texts. @return: A list containing tuples in the following format: ('checkBoxTextString' , preference_key). PM_PrefsCheckBoxes uses this data to create checkboxes with the the given names and connects them to the provided preference keys. (Note that PM_PrefsCheckBoxes puts thes within a GroupBox) @rtype: list @see: PM_PrefsCheckBoxes @see: self._loadDisplayOptionsGroupBox where this list is used. @see: Superclass method which is overridden here -- DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = \ [ #Format: (" checkbox text", prefs_key) ("Number of base pairs", dnaDuplexEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key), ("Number of turns", dnaDuplexEditCommand_cursorTextCheckBox_numberOfTurns_prefs_key), ("Duplex length", dnaDuplexEditCommand_cursorTextCheckBox_length_prefs_key), ("Angle", dnaDuplexEditCommand_cursorTextCheckBox_angle_prefs_key) ] return params def _addToolTipText(self): """ Tool Tip text for widgets in the DNA Property Manager. """ pass def conformationComboBoxChanged(self, inIndex): """ Slot for the Conformation combobox. It is called whenever the Conformation choice is changed. @param inIndex: The new index. @type inIndex: int """ conformation = self.conformationComboBox.currentText() if conformation == "B-DNA": self.basesPerTurnDoubleSpinBox.setValue("10.0") elif conformation == "Z-DNA": self.basesPerTurnDoubleSpinBox.setValue("12.0") else: msg = redmsg("conformationComboBoxChanged(): \ Error - unknown DNA conformation. Index = " + inIndex) env.history.message(msg) self.duplexLengthSpinBox.setSingleStep(getDuplexRise(conformation)) def numberOfBasesChanged(self, numberOfBases): """ Slot for the B{Number of Bases} spinbox. """ # Update the Duplex Length lineEdit widget. text = str(getDuplexLength(self._conformation, numberOfBases, self._duplexRise)) \ + " Angstroms" self.duplexLengthLineEdit.setText(text) return def basesPerTurnChanged(self, basesPerTurn): """ Slot for the B{Bases per turn} spinbox. """ self.command.basesPerTurn = basesPerTurn self._basesPerTurn = basesPerTurn return def duplexRiseChanged(self, rise): """ Slot for the B{Rise} spinbox. """ self.command.duplexRise = rise self._duplexRise = rise return def getParameters(self): """ Return the parameters from this property manager to be used to create the DNA duplex. @return: A tuple containing the parameters @rtype: tuple @see: L{InsertDna_EditCommand._gatherParameters} where this is used """ numberOfBases = self.numberOfBasePairsSpinBox.value() dnaForm = str(self.conformationComboBox.currentText()) basesPerTurn = self.basesPerTurnDoubleSpinBox.value() duplexRise = self.duplexRiseDoubleSpinBox.value() dnaModel = str(self.dnaModelComboBox.currentText()) # First endpoint (origin) of DNA duplex x1 = self.x1SpinBox.value() y1 = self.y1SpinBox.value() z1 = self.z1SpinBox.value() # Second endpoint (direction vector/axis) of DNA duplex. x2 = self.x2SpinBox.value() y2 = self.y2SpinBox.value() z2 = self.z2SpinBox.value() if not self.endPoint1: self.endPoint1 = V(x1, y1, z1) if not self.endPoint2: self.endPoint2 = V(x2, y2, z2) return (numberOfBases, dnaForm, dnaModel, basesPerTurn, duplexRise, self.endPoint1, self.endPoint2) def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ whatsThis_InsertDna_PropertyManager(self)
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 DnaGeneratorPropertyManager(PM_Dialog, DebugMenuMixin): """ The DnaGeneratorPropertyManager class provides a Property Manager for the "Build > Atoms" 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 @ivar validSymbols: Miscellaneous symbols that may appear in the sequence (but are ignored). The hyphen '-' is a special case that must be dealt with individually; it is not included because it can confuse regular expressions. @type validSymbols: QString """ title = "DNA" pmName = title iconPath = "ui/actions/Tools/Build Structures/DNA.png" validSymbols = QString(' <>~!@#%&_+`=$*()[]{}|^\'"\\.;:,/?') # The following class variables guarantee the UI's menu items # are synchronized with their action code. The arrays should # not be changed, unless an item is removed or inserted. # Changes should be made via only the _action... variables. # e.g., Change _action_Complement from "Complement" # to "Complement Sequences". The menu item will # change and its related code will need no update. _action_Complement = "Complement" _action_Reverse = "Reverse" _action_RemoveUnrecognized = 'Remove unrecognized letters' _action_ConvertUnrecognized = 'Convert unrecognized letters to "N"' _actionChoices = [ "Action", "---", _action_Complement, _action_Reverse, _action_RemoveUnrecognized, _action_ConvertUnrecognized ] _modeltype_PAM3 = "PAM3" _modeltype_PAM5 = "PAM5" _modeltype_Atomistic = "Atomistic" # deprecated _modelChoices = [_modeltype_PAM3, _modeltype_PAM5] def __init__(self): """ Constructor for the DNA Generator property manager. """ PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title) DebugMenuMixin._init1(self) msg = "Edit the DNA parameters and select <b>Preview</b> to \ preview the structure. Click <b>Done</b> to insert it into \ the model." # This causes the "Message" box to be displayed as well. # setAsDefault=True causes this message to be reset whenever # this PM is (re)displayed via show(). Mark 2007-06-01. self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=True) def _addGroupBoxes(self): """ Add the DNA Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox(self, title="Strand Sequence") self._loadGroupBox1(self._pmGroupBox1) self._pmGroupBox2 = PM_GroupBox(self, title="DNA Parameters") self._loadGroupBox2(self._pmGroupBox2) self._pmGroupBox3 = PM_GroupBox(self, title="Endpoints") self._loadGroupBox3(self._pmGroupBox3) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 1. """ # Duplex Length self.duplexLengthSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Duplex Length: ", value = 0, setAsDefault = False, minimum = 0, maximum = 34000, singleStep = self.getDuplexRise("B-DNA"), decimals = 3, suffix = ' Angstroms') self.connect(self.duplexLengthSpinBox, SIGNAL("valueChanged(double)"), self.duplexLengthChanged) # Strand Length self.strandLengthSpinBox = \ PM_SpinBox( pmGroupBox, label = "Strand Length :", value = 0, setAsDefault = False, minimum = 0, maximum = 10000, suffix = ' bases' ) self.connect(self.strandLengthSpinBox, SIGNAL("valueChanged(int)"), self.strandLengthChanged) # New Base choices newBaseChoices = [] for theBase in basesDict.keys(): newBaseChoices = newBaseChoices \ + [ theBase + ' (' \ + basesDict[theBase]['Name'] + ')' ] try: defaultBaseChoice = basesDict.keys().index('N') except: defaultBaseChoice = 0 # Strand Sequence self.sequenceTextEdit = \ PM_TextEdit( pmGroupBox, label = "", spanWidth = True ) self.sequenceTextEdit.setCursorWidth(2) self.sequenceTextEdit.setWordWrapMode(QTextOption.WrapAnywhere) self.connect(self.sequenceTextEdit, SIGNAL("textChanged()"), self.sequenceChanged) self.connect(self.sequenceTextEdit, SIGNAL("cursorPositionChanged()"), self.cursorPosChanged) # Actions self.actionsComboBox = \ PM_ComboBox( pmGroupBox, label = '', choices = self._actionChoices, index = 0, setAsDefault = True, spanWidth = True ) # If SIGNAL("activate(const QString&)") is used, we get a TypeError. # This is a bug that needs Bruce. Using currentIndexChanged(int) as # a workaround, but there is still a bug when the "Reverse" action # is selected. Mark 2007-08-15 self.connect(self.actionsComboBox, SIGNAL("currentIndexChanged(int)"), self.actionsComboBoxChanged) def _loadGroupBox2(self, pmGroupBox): """ Load widgets in group box 2. """ self.modelComboBox = \ PM_ComboBox( pmGroupBox, label = "Model :", choices = self._modelChoices, setAsDefault = True) self.conformationComboBox = \ PM_ComboBox( pmGroupBox, label = "Conformation :", choices = ["B-DNA"], setAsDefault = True) self.connect(self.conformationComboBox, SIGNAL("currentIndexChanged(int)"), self.conformationComboBoxChanged) self.basesPerTurnComboBox= \ PM_ComboBox( pmGroupBox, label = "Bases Per Turn :", choices = ["10.0", "10.5", "10.67"], setAsDefault = True) # I may decide to reintroduce "base-pair chunks" at a later time. # Please talk to me if you have a strong feeling about including # this. Mark 2007-08-19. createChoices = ["Strand chunks", \ "Single chunk" ] #@ "Base-pair chunks"] self.createComboBox = \ PM_ComboBox( pmGroupBox, label = "Create :", choices = createChoices, index = 0, setAsDefault = True, spanWidth = False ) def _loadGroupBox3(self, pmGroupBox): """ Load widgets in group box 3. """ self._endPoint1GroupBox = PM_GroupBox(pmGroupBox, title="Endpoint1") self._endPoint2GroupBox = PM_GroupBox(pmGroupBox, title="Endpoint2") # Point 1 self.x1SpinBox = \ PM_DoubleSpinBox( self._endPoint1GroupBox, label = \ "ui/actions/Properties Manager/X_Coordinate.png", value = 0, setAsDefault = True, minimum = -100.0, maximum = 100.0, decimals = 3, suffix = ' Angstroms') self.y1SpinBox = \ PM_DoubleSpinBox( self._endPoint1GroupBox, label = \ "ui/actions/Properties Manager/Y_Coordinate.png", value = 0, setAsDefault = True, minimum = -100.0, maximum = 100.0, decimals = 3, suffix = ' Angstroms') self.z1SpinBox = \ PM_DoubleSpinBox( self._endPoint1GroupBox, label = \ "ui/actions/Properties Manager/Z_Coordinate.png", value = 0, setAsDefault = True, minimum = -100.0, maximum = 100.0, decimals = 3, suffix = ' Angstroms') # Point 2 self.x2SpinBox = \ PM_DoubleSpinBox( self._endPoint2GroupBox, label = \ "ui/actions/Properties Manager/X_Coordinate.png", value = 10.0, setAsDefault = True, minimum = -100.0, maximum = 100.0, decimals = 3, suffix = ' Angstroms') self.y2SpinBox = \ PM_DoubleSpinBox( self._endPoint2GroupBox, label = \ "ui/actions/Properties Manager/Y_Coordinate.png", value = 0, setAsDefault = True, minimum = -100.0, maximum = 100.0, decimals = 3, suffix = ' Angstroms') self.z2SpinBox = \ PM_DoubleSpinBox( self._endPoint2GroupBox, label = \ "ui/actions/Properties Manager/Z_Coordinate.png", value = 0, setAsDefault = True, minimum = -100.0, maximum = 100.0, decimals = 3, suffix = ' Angstroms') def _addWhatsThisText(self): """ What's This text for some of the widgets in the DNA Property Manager. @note: Many PM widgets are still missing their "What's This" text. """ self.conformationComboBox.setWhatsThis("""<b>Conformation</b> <p>There are three DNA geometries, A-DNA, B-DNA, and Z-DNA. Only B-DNA and Z-DNA are currently supported.</p>""") self.sequenceTextEdit.setWhatsThis("""<b>Strand Sequence</b> <p>Type in the strand sequence you want to generate here (5' => 3')<br> <br> Recognized base letters:<br> <br> A = Adenosine<br> C = Cytosine<br> G = Guanosine<br> T = Thymidine<br> N = aNy base<br> X = Unassigned<br> <br> Other base letters currently recognized:<br> <br> B = C,G, or T<br> D = A,G, or T<br> H = A,C, or T<br> V = A,C, or G<br> R = A or G (puRine)<br> Y = C or T (pYrimidine)<br> K = G or T (Keto)<br> M = A or C (aMino)<br> S = G or C (Strong -3H bonds)<br> W = A or T (Weak - 2H bonds)<br> </p>""") self.actionsComboBox.setWhatsThis("""<b>Action</b> <p>Select an action to perform on the sequence.</p>""") def conformationComboBoxChanged(self, inIndex): """ Slot for the Conformation combobox. It is called whenever the Conformation choice is changed. @param inIndex: The new index. @type inIndex: int """ self.basesPerTurnComboBox.clear() conformation = self.conformationComboBox.currentText() if conformation == "B-DNA": self.basesPerTurnComboBox.insertItem(0, "10.0") self.basesPerTurnComboBox.insertItem(1, "10.5") self.basesPerTurnComboBox.insertItem(2, "10.67") #10.5 is the default value for Bases per turn. #So set the current index to 1 self.basesPerTurnComboBox.setCurrentIndex(1) elif conformation == "Z-DNA": self.basesPerTurnComboBox.insertItem(0, "12.0") elif inIndex == -1: # Caused by clear(). This is tolerable for now. Mark 2007-05-24. conformation = "B-DNA" # Workaround for "Restore Defaults". pass else: msg = redmsg("conformationComboBoxChanged(): \ Error - unknown DNA conformation. Index = " + inIndex) env.history.message(msg) self.duplexLengthSpinBox.setSingleStep( self.getDuplexRise(conformation)) def modelComboBoxChanged(self, inIndex): """ Slot for the Model combobox. It is called whenever the Model choice is changed. @param inIndex: The new index. @type inIndex: int """ conformation = self._modelChoices[inIndex] self.disconnect(self.conformationComboBox, SIGNAL("currentIndexChanged(int)"), self.conformationComboBoxChanged) self.conformationComboBox.clear() # Generates signal! if conformation == self._modeltype_PAM3: self.conformationComboBox.addItem("B-DNA") elif conformation == self._modeltype_PAM5: self.conformationComboBox.addItem("B-DNA") elif conformation == self._modeltype_Atomistic: self.conformationComboBox.addItem("B-DNA") self.conformationComboBox.addItem("Z-DNA") elif inIndex == -1: # Caused by clear(). This is tolerable for now. Mark 2007-05-24. pass else: msg = "Error - unknown model representation. Index = " + inIndex env.history.message(redmsg(msg)) self.connect(self.conformationComboBox, SIGNAL("currentIndexChanged(int)"), self.conformationComboBoxChanged) # GroupBox3 slots (and other methods) supporting the Strand Sequence groupbox. def getDuplexRise(self, inConformation): """ Return the 'rise' between base pairs of the specified DNA type (conformation). @param inConformation: The current conformation. @type inConformation: int """ return dnaDict[str(inConformation)]['DuplexRise'] def synchronizeLengths(self): """ Guarantees the values of the duplex length and strand length spinboxes agree with the strand sequence (textedit). """ self.updateStrandLength() self.updateDuplexLength() return # Added :jbirac 20070613: def duplexLengthChanged(self, inDuplexLength): """ Slot for the duplex length spinbox, called whenever the value of the Duplex Length spinbox changes. @param inDuplexLength: The duplex length. @type inDuplexLength: float """ conformation = self.conformationComboBox.currentText() duplexRise = self.getDuplexRise(conformation) newStrandLength = inDuplexLength / duplexRise + 0.5 newStrandLength = int(newStrandLength) self.strandLengthChanged(newStrandLength) def updateDuplexLength(self): # Added :jbirac 20070615: """ Update the Duplex Length spinbox; always the length of the strand sequence multiplied by the 'rise' of the duplex. This method is called by slots of other controls (i.e., this itself is not a slot.) """ conformation = self.conformationComboBox.currentText() newDuplexLength = self.getDuplexRise( conformation ) \ * self.getSequenceLength() self.disconnect(self.duplexLengthSpinBox, SIGNAL("valueChanged(double)"), self.duplexLengthChanged) self.duplexLengthSpinBox.setValue(newDuplexLength) self.connect(self.duplexLengthSpinBox, SIGNAL("valueChanged(double)"), self.duplexLengthChanged) # Renamed from length_changed :jbirac 20070613: def strandLengthChanged(self, inStrandLength): """ Slot for the Strand Length spin box, called whenever the value of the Strand Length spin box changes. @param inStrandLength: The number of bases in the strand sequence. @type inStrandLength: int """ theSequence = self.getPlainSequence() sequenceLen = len(theSequence) lengthChange = inStrandLength - self.getSequenceLength() # Preserve the cursor's position/selection cursor = self.sequenceTextEdit.textCursor() #cursorPosition = cursor.position() selectionStart = cursor.selectionStart() selectionEnd = cursor.selectionEnd() if inStrandLength < 0: return # Should never happen. if lengthChange < 0: # If length is less than the previous length, # simply truncate the current sequence. theSequence.chop(-lengthChange) elif lengthChange > 0: # If length has increased, add the correct number of base # letters to the current strand sequence. numNewBases = lengthChange # Get current base selected in combobox. chosenBase = 'X' # Unassigned. basesToAdd = chosenBase * numNewBases theSequence.append(basesToAdd) else: env.history.message( orangemsg("strandLengthChanged(): Length has not changed.")) self.setSequence(theSequence) return # Renamed from updateLength :jbirac 20070613: def updateStrandLength(self): """ Update the Strand Length spinbox; always the length of the strand sequence. """ self.disconnect(self.strandLengthSpinBox, SIGNAL("valueChanged(int)"), self.strandLengthChanged) self.strandLengthSpinBox.setValue(self.getSequenceLength()) self.connect(self.strandLengthSpinBox, SIGNAL("valueChanged(int)"), self.strandLengthChanged) return def sequenceChanged(self): """ Slot for the Strand Sequence textedit widget. Assumes the sequence changed directly by user's keystroke in the textedit. Other methods... """ cursorPosition = self.getCursorPosition() theSequence = self.getPlainSequence() # Disconnect while we edit the sequence. self.disconnect(self.sequenceTextEdit, SIGNAL("textChanged()"), self.sequenceChanged) # How has the text changed? if theSequence.length() == 0: # There is no sequence. self.updateStrandLength() self.updateDuplexLength() else: # Insert the sequence; it will be "stylized" by setSequence(). self.setSequence(theSequence) # Reconnect to respond when the sequence is changed. self.connect(self.sequenceTextEdit, SIGNAL("textChanged()"), self.sequenceChanged) self.synchronizeLengths() return def getPlainSequence(self, inOmitSymbols=False): """ Returns a plain text QString (without HTML stylization) of the current sequence. All characters are preserved (unless specified explicitly), including valid base letters, punctuation symbols, whitespace and invalid letters. @param inOmitSymbols: Omits characters listed in self.validSymbols. @type inOmitSymbols: bool @return: The current DNA sequence in the PM. @rtype: QString """ outSequence = self.sequenceTextEdit.toPlainText() if inOmitSymbols: # This may look like a sloppy piece of code, but Qt's QRegExp # class makes it pretty tricky to remove all punctuation. theString = '[<>' \ + str( QRegExp.escape(self.validSymbols) ) \ + ']|-' outSequence.remove(QRegExp(theString)) return outSequence def stylizeSequence(self, inSequence): """ Converts a plain text string of a sequence (including optional symbols) to an HTML rich text string. @param inSequence: A DNA sequence. @type inSequence: QString @return: The sequence. @rtype: QString """ outSequence = str(inSequence) # Verify that all characters (bases) in the sequence are "valid". invalidSequence = False basePosition = 0 sequencePosition = 0 invalidStartTag = "<b><font color=black>" invalidEndTag = "</b>" previousChar = chr(1) # Null character; may be revised. # Some characters must be substituted to preserve # whitespace and tags in HTML code. substituteDict = {' ': ' ', '<': '<', '>': '>'} while basePosition < len(outSequence): theSeqChar = outSequence[basePosition] if (theSeqChar in basesDict or theSeqChar in self.validSymbols): # Close any preceding invalid sequence segment. if invalidSequence == True: outSequence = outSequence[:basePosition] \ + invalidEndTag \ + outSequence[basePosition:] basePosition += len(invalidEndTag) invalidSequence = False # Color the valid characters. if theSeqChar != previousChar: # We only need to insert 'color' tags in places where # the adjacent characters are different. if theSeqChar in basesDict: theTag = '<font color=' \ + basesDict[ theSeqChar ]['Color'] \ + '>' elif not previousChar in self.validSymbols: # The character is a 'valid' symbol to be greyed # out. Only one 'color' tag is needed for a # group of adjacent symbols. theTag = '<font color=dimgrey>' else: theTag = '' outSequence = outSequence[:basePosition] \ + theTag + outSequence[basePosition:] basePosition += len(theTag) # Any <space> character must be substituted with an # ASCII code tag because the HTML engine will collapse # whitespace to a single <space> character; whitespace # is truncated from the end of HTML by default. # Also, many symbol characters must be substituted # because they confuse the HTML syntax. #if str( outSequence[basePosition] ) in substituteDict: if outSequence[basePosition] in substituteDict: #theTag = substituteDict[theSeqChar] theTag = substituteDict[outSequence[basePosition]] outSequence = outSequence[:basePosition] \ + theTag \ + outSequence[basePosition + 1:] basePosition += len(theTag) - 1 else: # The sequence character is invalid (but permissible). # Tags (e.g., <b> and </b>) must be inserted at both the # beginning and end of a segment of invalid characters. if invalidSequence == False: outSequence = outSequence[:basePosition] \ + invalidStartTag \ + outSequence[basePosition:] basePosition += len(invalidStartTag) invalidSequence = True basePosition += 1 previousChar = theSeqChar #basePosition += 1 # Specify that theSequence is definitely HTML format, because # Qt can get confused between HTML and Plain Text. outSequence = "<html>" + outSequence outSequence += "</html>" return outSequence def setSequence(self, inSequence, inStylize=True, inRestoreCursor=True): """ Replace the current strand sequence with the new sequence text. @param inSequence: The new sequence. @type inSequence: QString @param inStylize: If True, inSequence will be converted from a plain text string (including optional symbols) to an HTML rich text string. @type inStylize: bool @param inRestoreCursor: Not implemented yet. @type inRestoreCursor: bool @attention: Signals/slots must be managed before calling this method. The textChanged() signal will be sent to any connected widgets. """ cursor = self.sequenceTextEdit.textCursor() selectionStart = cursor.selectionStart() selectionEnd = cursor.selectionEnd() if inStylize: inSequence = self.stylizeSequence(inSequence) self.sequenceTextEdit.insertHtml(inSequence) if inRestoreCursor: cursor.setPosition(min(selectionStart, self.getSequenceLength()), QTextCursor.MoveAnchor) cursor.setPosition(min(selectionEnd, self.getSequenceLength()), QTextCursor.KeepAnchor) self.sequenceTextEdit.setTextCursor(cursor) return def getSequenceLength(self): """ Returns the number of characters in the strand sequence textedit widget. """ theSequence = self.getPlainSequence(inOmitSymbols=True) outLength = theSequence.length() return outLength def getCursorPosition(self): """ Returns the cursor position in the strand sequence textedit widget. """ cursor = self.sequenceTextEdit.textCursor() return cursor.position() def cursorPosChanged(self): """ Slot called when the cursor position changes. """ cursor = self.sequenceTextEdit.textCursor() if 0: env.history.message( greenmsg("cursorPosChanged: Selection (" + str(cursor.selectionStart()) + " thru " + str(cursor.selectionEnd()) + ')')) return def actionsComboBoxChanged(self, inIndex): """ Slot for the Actions combobox. It is called whenever the Action choice is changed. @param inIndex: The index of the selected action choice. @type inIndex: int """ if inIndex == 0: # Very important. return actionName = str(self.actionsComboBox.currentText()) self.actionsComboBox.setCurrentIndex(0) # Generates signal! self.invokeAction(actionName) return def invokeAction(self, inActionName): """ Applies an action on the current sequence displayed in the PM. @param inActionName: The action name. @type inActionName: str @return: The sequence after the action has been applied. @rtype: str """ sequence, allKnown = self._getSequence() outResult = "" if inActionName == self._action_Complement: outResult = getComplementSequence(sequence) elif inActionName == self._action_Reverse: outResult = getReverseSequence(sequence) elif inActionName == self._action_ConvertUnrecognized: outResult = replaceUnrecognized(sequence, replaceBase='N') self.setSequence(outResult) elif inActionName == self._action_RemoveUnrecognized: outResult = replaceUnrecognized(sequence, replaceBase='') self.setSequence(outResult) return
class DnaGeneratorPropertyManager( PM_Dialog, DebugMenuMixin ): """ The DnaGeneratorPropertyManager class provides a Property Manager for the "Build > Atoms" 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 @ivar validSymbols: Miscellaneous symbols that may appear in the sequence (but are ignored). The hyphen '-' is a special case that must be dealt with individually; it is not included because it can confuse regular expressions. @type validSymbols: QString """ title = "DNA" pmName = title iconPath = "ui/actions/Tools/Build Structures/DNA.png" validSymbols = QString(' <>~!@#%&_+`=$*()[]{}|^\'"\\.;:,/?') # The following class variables guarantee the UI's menu items # are synchronized with their action code. The arrays should # not be changed, unless an item is removed or inserted. # Changes should be made via only the _action... variables. # e.g., Change _action_Complement from "Complement" # to "Complement Sequences". The menu item will # change and its related code will need no update. _action_Complement = "Complement" _action_Reverse = "Reverse" _action_RemoveUnrecognized = 'Remove unrecognized letters' _action_ConvertUnrecognized = 'Convert unrecognized letters to "N"' _actionChoices = [ "Action", "---", _action_Complement, _action_Reverse, _action_RemoveUnrecognized, _action_ConvertUnrecognized ] _modeltype_PAM3 = "PAM3" _modeltype_PAM5 = "PAM5" _modeltype_Atomistic = "Atomistic" # deprecated _modelChoices = [ _modeltype_PAM3, _modeltype_PAM5 ] def __init__( self ): """ Constructor for the DNA Generator property manager. """ PM_Dialog.__init__( self, self.pmName, self.iconPath, self.title ) DebugMenuMixin._init1( self ) msg = "Edit the DNA parameters and select <b>Preview</b> to \ preview the structure. Click <b>Done</b> to insert it into \ the model." # This causes the "Message" box to be displayed as well. # setAsDefault=True causes this message to be reset whenever # this PM is (re)displayed via show(). Mark 2007-06-01. self.MessageGroupBox.insertHtmlMessage( msg, setAsDefault = True ) def _addGroupBoxes( self ): """ Add the DNA Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Strand Sequence" ) self._loadGroupBox1( self._pmGroupBox1 ) self._pmGroupBox2 = PM_GroupBox( self, title = "DNA Parameters" ) self._loadGroupBox2( self._pmGroupBox2 ) self._pmGroupBox3 = PM_GroupBox( self, title = "Endpoints" ) self._loadGroupBox3( self._pmGroupBox3 ) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 1. """ # Duplex Length self.duplexLengthSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Duplex Length: ", value = 0, setAsDefault = False, minimum = 0, maximum = 34000, singleStep = self.getDuplexRise("B-DNA"), decimals = 3, suffix = ' Angstroms') self.connect( self.duplexLengthSpinBox, SIGNAL("valueChanged(double)"), self.duplexLengthChanged ) # Strand Length self.strandLengthSpinBox = \ PM_SpinBox( pmGroupBox, label = "Strand Length :", value = 0, setAsDefault = False, minimum = 0, maximum = 10000, suffix = ' bases' ) self.connect( self.strandLengthSpinBox, SIGNAL("valueChanged(int)"), self.strandLengthChanged ) # New Base choices newBaseChoices = [] for theBase in basesDict.keys(): newBaseChoices = newBaseChoices \ + [ theBase + ' (' \ + basesDict[theBase]['Name'] + ')' ] try: defaultBaseChoice = basesDict.keys().index('N') except: defaultBaseChoice = 0 # Strand Sequence self.sequenceTextEdit = \ PM_TextEdit( pmGroupBox, label = "", spanWidth = True ) self.sequenceTextEdit.setCursorWidth(2) self.sequenceTextEdit.setWordWrapMode( QTextOption.WrapAnywhere ) self.connect( self.sequenceTextEdit, SIGNAL("textChanged()"), self.sequenceChanged ) self.connect( self.sequenceTextEdit, SIGNAL("cursorPositionChanged()"), self.cursorPosChanged ) # Actions self.actionsComboBox = \ PM_ComboBox( pmGroupBox, label = '', choices = self._actionChoices, index = 0, setAsDefault = True, spanWidth = True ) # If SIGNAL("activate(const QString&)") is used, we get a TypeError. # This is a bug that needs Bruce. Using currentIndexChanged(int) as # a workaround, but there is still a bug when the "Reverse" action # is selected. Mark 2007-08-15 self.connect( self.actionsComboBox, SIGNAL("currentIndexChanged(int)"), self.actionsComboBoxChanged ) def _loadGroupBox2( self, pmGroupBox ): """ Load widgets in group box 2. """ self.modelComboBox = \ PM_ComboBox( pmGroupBox, label = "Model :", choices = self._modelChoices, setAsDefault = True) self.conformationComboBox = \ PM_ComboBox( pmGroupBox, label = "Conformation :", choices = ["B-DNA"], setAsDefault = True) self.connect( self.conformationComboBox, SIGNAL("currentIndexChanged(int)"), self.conformationComboBoxChanged ) self.basesPerTurnComboBox= \ PM_ComboBox( pmGroupBox, label = "Bases Per Turn :", choices = ["10.0", "10.5", "10.67"], setAsDefault = True) # I may decide to reintroduce "base-pair chunks" at a later time. # Please talk to me if you have a strong feeling about including # this. Mark 2007-08-19. createChoices = ["Strand chunks", \ "Single chunk" ] #@ "Base-pair chunks"] self.createComboBox = \ PM_ComboBox( pmGroupBox, label = "Create :", choices = createChoices, index = 0, setAsDefault = True, spanWidth = False ) def _loadGroupBox3(self, pmGroupBox): """ Load widgets in group box 3. """ self._endPoint1GroupBox = PM_GroupBox( pmGroupBox, title = "Endpoint1" ) self._endPoint2GroupBox = PM_GroupBox( pmGroupBox, title = "Endpoint2" ) # Point 1 self.x1SpinBox = \ PM_DoubleSpinBox( self._endPoint1GroupBox, label = \ "ui/actions/Properties Manager/X_Coordinate.png", value = 0, setAsDefault = True, minimum = -100.0, maximum = 100.0, decimals = 3, suffix = ' Angstroms') self.y1SpinBox = \ PM_DoubleSpinBox( self._endPoint1GroupBox, label = \ "ui/actions/Properties Manager/Y_Coordinate.png", value = 0, setAsDefault = True, minimum = -100.0, maximum = 100.0, decimals = 3, suffix = ' Angstroms') self.z1SpinBox = \ PM_DoubleSpinBox( self._endPoint1GroupBox, label = \ "ui/actions/Properties Manager/Z_Coordinate.png", value = 0, setAsDefault = True, minimum = -100.0, maximum = 100.0, decimals = 3, suffix = ' Angstroms') # Point 2 self.x2SpinBox = \ PM_DoubleSpinBox( self._endPoint2GroupBox, label = \ "ui/actions/Properties Manager/X_Coordinate.png", value = 10.0, setAsDefault = True, minimum = -100.0, maximum = 100.0, decimals = 3, suffix = ' Angstroms') self.y2SpinBox = \ PM_DoubleSpinBox( self._endPoint2GroupBox, label = \ "ui/actions/Properties Manager/Y_Coordinate.png", value = 0, setAsDefault = True, minimum = -100.0, maximum = 100.0, decimals = 3, suffix = ' Angstroms') self.z2SpinBox = \ PM_DoubleSpinBox( self._endPoint2GroupBox, label = \ "ui/actions/Properties Manager/Z_Coordinate.png", value = 0, setAsDefault = True, minimum = -100.0, maximum = 100.0, decimals = 3, suffix = ' Angstroms') def _addWhatsThisText( self ): """ What's This text for some of the widgets in the DNA Property Manager. @note: Many PM widgets are still missing their "What's This" text. """ self.conformationComboBox.setWhatsThis("""<b>Conformation</b> <p>There are three DNA geometries, A-DNA, B-DNA, and Z-DNA. Only B-DNA and Z-DNA are currently supported.</p>""") self.sequenceTextEdit.setWhatsThis("""<b>Strand Sequence</b> <p>Type in the strand sequence you want to generate here (5' => 3')<br> <br> Recognized base letters:<br> <br> A = Adenosine<br> C = Cytosine<br> G = Guanosine<br> T = Thymidine<br> N = aNy base<br> X = Unassigned<br> <br> Other base letters currently recognized:<br> <br> B = C,G, or T<br> D = A,G, or T<br> H = A,C, or T<br> V = A,C, or G<br> R = A or G (puRine)<br> Y = C or T (pYrimidine)<br> K = G or T (Keto)<br> M = A or C (aMino)<br> S = G or C (Strong -3H bonds)<br> W = A or T (Weak - 2H bonds)<br> </p>""") self.actionsComboBox.setWhatsThis("""<b>Action</b> <p>Select an action to perform on the sequence.</p>""") def conformationComboBoxChanged( self, inIndex ): """ Slot for the Conformation combobox. It is called whenever the Conformation choice is changed. @param inIndex: The new index. @type inIndex: int """ self.basesPerTurnComboBox.clear() conformation = self.conformationComboBox.currentText() if conformation == "B-DNA": self.basesPerTurnComboBox.insertItem(0, "10.0") self.basesPerTurnComboBox.insertItem(1, "10.5") self.basesPerTurnComboBox.insertItem(2, "10.67") #10.5 is the default value for Bases per turn. #So set the current index to 1 self.basesPerTurnComboBox.setCurrentIndex(1) elif conformation == "Z-DNA": self.basesPerTurnComboBox.insertItem(0, "12.0") elif inIndex == -1: # Caused by clear(). This is tolerable for now. Mark 2007-05-24. conformation = "B-DNA" # Workaround for "Restore Defaults". pass else: msg = redmsg("conformationComboBoxChanged(): \ Error - unknown DNA conformation. Index = "+ inIndex) env.history.message(msg) self.duplexLengthSpinBox.setSingleStep( self.getDuplexRise(conformation) ) def modelComboBoxChanged( self, inIndex ): """ Slot for the Model combobox. It is called whenever the Model choice is changed. @param inIndex: The new index. @type inIndex: int """ conformation = self._modelChoices[ inIndex ] self.disconnect( self.conformationComboBox, SIGNAL("currentIndexChanged(int)"), self.conformationComboBoxChanged ) self.conformationComboBox.clear() # Generates signal! if conformation == self._modeltype_PAM3: self.conformationComboBox.addItem("B-DNA") elif conformation == self._modeltype_PAM5: self.conformationComboBox.addItem("B-DNA") elif conformation == self._modeltype_Atomistic: self.conformationComboBox.addItem("B-DNA") self.conformationComboBox.addItem("Z-DNA") elif inIndex == -1: # Caused by clear(). This is tolerable for now. Mark 2007-05-24. pass else: msg = "Error - unknown model representation. Index = " + inIndex env.history.message(redmsg(msg)) self.connect( self.conformationComboBox, SIGNAL("currentIndexChanged(int)"), self.conformationComboBoxChanged) # GroupBox3 slots (and other methods) supporting the Strand Sequence groupbox. def getDuplexRise( self, inConformation ): """ Return the 'rise' between base pairs of the specified DNA type (conformation). @param inConformation: The current conformation. @type inConformation: int """ return dnaDict[str(inConformation)]['DuplexRise'] def synchronizeLengths( self ): """ Guarantees the values of the duplex length and strand length spinboxes agree with the strand sequence (textedit). """ self.updateStrandLength() self.updateDuplexLength() return # Added :jbirac 20070613: def duplexLengthChanged( self, inDuplexLength ): """ Slot for the duplex length spinbox, called whenever the value of the Duplex Length spinbox changes. @param inDuplexLength: The duplex length. @type inDuplexLength: float """ conformation = self.conformationComboBox.currentText() duplexRise = self.getDuplexRise( conformation ) newStrandLength = inDuplexLength / duplexRise + 0.5 newStrandLength = int( newStrandLength ) self.strandLengthChanged( newStrandLength ) def updateDuplexLength( self ): # Added :jbirac 20070615: """ Update the Duplex Length spinbox; always the length of the strand sequence multiplied by the 'rise' of the duplex. This method is called by slots of other controls (i.e., this itself is not a slot.) """ conformation = self.conformationComboBox.currentText() newDuplexLength = self.getDuplexRise( conformation ) \ * self.getSequenceLength() self.disconnect( self.duplexLengthSpinBox, SIGNAL("valueChanged(double)"), self.duplexLengthChanged) self.duplexLengthSpinBox.setValue( newDuplexLength ) self.connect( self.duplexLengthSpinBox, SIGNAL("valueChanged(double)"), self.duplexLengthChanged) # Renamed from length_changed :jbirac 20070613: def strandLengthChanged( self, inStrandLength ): """ Slot for the Strand Length spin box, called whenever the value of the Strand Length spin box changes. @param inStrandLength: The number of bases in the strand sequence. @type inStrandLength: int """ theSequence = self.getPlainSequence() sequenceLen = len( theSequence ) lengthChange = inStrandLength - self.getSequenceLength() # Preserve the cursor's position/selection cursor = self.sequenceTextEdit.textCursor() #cursorPosition = cursor.position() selectionStart = cursor.selectionStart() selectionEnd = cursor.selectionEnd() if inStrandLength < 0: return # Should never happen. if lengthChange < 0: # If length is less than the previous length, # simply truncate the current sequence. theSequence.chop( -lengthChange ) elif lengthChange > 0: # If length has increased, add the correct number of base # letters to the current strand sequence. numNewBases = lengthChange # Get current base selected in combobox. chosenBase = 'X' # Unassigned. basesToAdd = chosenBase * numNewBases theSequence.append( basesToAdd ) else: env.history.message( orangemsg( "strandLengthChanged(): Length has not changed." )) self.setSequence( theSequence ) return # Renamed from updateLength :jbirac 20070613: def updateStrandLength( self ): """ Update the Strand Length spinbox; always the length of the strand sequence. """ self.disconnect( self.strandLengthSpinBox, SIGNAL("valueChanged(int)"), self.strandLengthChanged ) self.strandLengthSpinBox.setValue( self.getSequenceLength() ) self.connect( self.strandLengthSpinBox, SIGNAL("valueChanged(int)"), self.strandLengthChanged ) return def sequenceChanged( self ): """ Slot for the Strand Sequence textedit widget. Assumes the sequence changed directly by user's keystroke in the textedit. Other methods... """ cursorPosition = self.getCursorPosition() theSequence = self.getPlainSequence() # Disconnect while we edit the sequence. self.disconnect( self.sequenceTextEdit, SIGNAL("textChanged()"), self.sequenceChanged ) # How has the text changed? if theSequence.length() == 0: # There is no sequence. self.updateStrandLength() self.updateDuplexLength() else: # Insert the sequence; it will be "stylized" by setSequence(). self.setSequence( theSequence ) # Reconnect to respond when the sequence is changed. self.connect( self.sequenceTextEdit, SIGNAL("textChanged()"), self.sequenceChanged ) self.synchronizeLengths() return def getPlainSequence( self, inOmitSymbols = False ): """ Returns a plain text QString (without HTML stylization) of the current sequence. All characters are preserved (unless specified explicitly), including valid base letters, punctuation symbols, whitespace and invalid letters. @param inOmitSymbols: Omits characters listed in self.validSymbols. @type inOmitSymbols: bool @return: The current DNA sequence in the PM. @rtype: QString """ outSequence = self.sequenceTextEdit.toPlainText() if inOmitSymbols: # This may look like a sloppy piece of code, but Qt's QRegExp # class makes it pretty tricky to remove all punctuation. theString = '[<>' \ + str( QRegExp.escape(self.validSymbols) ) \ + ']|-' outSequence.remove(QRegExp( theString )) return outSequence def stylizeSequence( self, inSequence ): """ Converts a plain text string of a sequence (including optional symbols) to an HTML rich text string. @param inSequence: A DNA sequence. @type inSequence: QString @return: The sequence. @rtype: QString """ outSequence = str(inSequence) # Verify that all characters (bases) in the sequence are "valid". invalidSequence = False basePosition = 0 sequencePosition = 0 invalidStartTag = "<b><font color=black>" invalidEndTag = "</b>" previousChar = chr(1) # Null character; may be revised. # Some characters must be substituted to preserve # whitespace and tags in HTML code. substituteDict = { ' ':' ', '<':'<', '>':'>' } while basePosition < len(outSequence): theSeqChar = outSequence[basePosition] if ( theSeqChar in basesDict or theSeqChar in self.validSymbols ): # Close any preceding invalid sequence segment. if invalidSequence == True: outSequence = outSequence[:basePosition] \ + invalidEndTag \ + outSequence[basePosition:] basePosition += len(invalidEndTag) invalidSequence = False # Color the valid characters. if theSeqChar != previousChar: # We only need to insert 'color' tags in places where # the adjacent characters are different. if theSeqChar in basesDict: theTag = '<font color=' \ + basesDict[ theSeqChar ]['Color'] \ + '>' elif not previousChar in self.validSymbols: # The character is a 'valid' symbol to be greyed # out. Only one 'color' tag is needed for a # group of adjacent symbols. theTag = '<font color=dimgrey>' else: theTag = '' outSequence = outSequence[:basePosition] \ + theTag + outSequence[basePosition:] basePosition += len(theTag) # Any <space> character must be substituted with an # ASCII code tag because the HTML engine will collapse # whitespace to a single <space> character; whitespace # is truncated from the end of HTML by default. # Also, many symbol characters must be substituted # because they confuse the HTML syntax. #if str( outSequence[basePosition] ) in substituteDict: if outSequence[basePosition] in substituteDict: #theTag = substituteDict[theSeqChar] theTag = substituteDict[ outSequence[basePosition] ] outSequence = outSequence[:basePosition] \ + theTag \ + outSequence[basePosition + 1:] basePosition += len(theTag) - 1 else: # The sequence character is invalid (but permissible). # Tags (e.g., <b> and </b>) must be inserted at both the # beginning and end of a segment of invalid characters. if invalidSequence == False: outSequence = outSequence[:basePosition] \ + invalidStartTag \ + outSequence[basePosition:] basePosition += len(invalidStartTag) invalidSequence = True basePosition += 1 previousChar = theSeqChar #basePosition += 1 # Specify that theSequence is definitely HTML format, because # Qt can get confused between HTML and Plain Text. outSequence = "<html>" + outSequence outSequence += "</html>" return outSequence def setSequence( self, inSequence, inStylize = True, inRestoreCursor = True ): """ Replace the current strand sequence with the new sequence text. @param inSequence: The new sequence. @type inSequence: QString @param inStylize: If True, inSequence will be converted from a plain text string (including optional symbols) to an HTML rich text string. @type inStylize: bool @param inRestoreCursor: Not implemented yet. @type inRestoreCursor: bool @attention: Signals/slots must be managed before calling this method. The textChanged() signal will be sent to any connected widgets. """ cursor = self.sequenceTextEdit.textCursor() selectionStart = cursor.selectionStart() selectionEnd = cursor.selectionEnd() if inStylize: inSequence = self.stylizeSequence( inSequence ) self.sequenceTextEdit.insertHtml( inSequence ) if inRestoreCursor: cursor.setPosition( min(selectionStart, self.getSequenceLength()), QTextCursor.MoveAnchor ) cursor.setPosition( min(selectionEnd, self.getSequenceLength()), QTextCursor.KeepAnchor ) self.sequenceTextEdit.setTextCursor( cursor ) return def getSequenceLength( self ): """ Returns the number of characters in the strand sequence textedit widget. """ theSequence = self.getPlainSequence( inOmitSymbols = True ) outLength = theSequence.length() return outLength def getCursorPosition( self ): """ Returns the cursor position in the strand sequence textedit widget. """ cursor = self.sequenceTextEdit.textCursor() return cursor.position() def cursorPosChanged( self ): """ Slot called when the cursor position changes. """ cursor = self.sequenceTextEdit.textCursor() if 0: env.history.message( greenmsg( "cursorPosChanged: Selection (" + str(cursor.selectionStart()) + " thru " + str(cursor.selectionEnd())+')' ) ) return def actionsComboBoxChanged( self, inIndex ): """ Slot for the Actions combobox. It is called whenever the Action choice is changed. @param inIndex: The index of the selected action choice. @type inIndex: int """ if inIndex == 0: # Very important. return actionName = str(self.actionsComboBox.currentText()) self.actionsComboBox.setCurrentIndex( 0 ) # Generates signal! self.invokeAction( actionName ) return def invokeAction( self, inActionName ): """ Applies an action on the current sequence displayed in the PM. @param inActionName: The action name. @type inActionName: str @return: The sequence after the action has been applied. @rtype: str """ sequence, allKnown = self._getSequence() outResult = "" if inActionName == self._action_Complement: outResult = getComplementSequence(sequence) elif inActionName == self._action_Reverse: outResult = getReverseSequence(sequence) elif inActionName == self._action_ConvertUnrecognized: outResult = replaceUnrecognized(sequence, replaceBase = 'N') self.setSequence( outResult ) elif inActionName == self._action_RemoveUnrecognized: outResult = replaceUnrecognized(sequence, replaceBase = '') self.setSequence( outResult ) return
class InsertNanotube_PropertyManager(DnaOrCnt_PropertyManager): """ The InsertNanotube_PropertyManager class provides a Property Manager for the B{Build > Nanotube > CNT} command. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Insert Nanotube" pmName = title iconPath = "ui/actions/Tools/Build Structures/InsertNanotube.png" def __init__(self, win, editCommand): """ Constructor for the Nanotube property manager. """ self.endPoint1 = None self.endPoint2 = None self.nanotube = Nanotube() # A 5x5 CNT. _superclass.__init__(self, win, editCommand) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_WHATS_THIS_BUTTON) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect change_connect(self.ntTypeComboBox, SIGNAL("currentIndexChanged(const QString&)"), self._ntTypeComboBoxChanged) change_connect(self.chiralityNSpinBox, SIGNAL("valueChanged(int)"), self._chiralityFixup) change_connect(self.chiralityMSpinBox, SIGNAL("valueChanged(int)"), self._chiralityFixup) change_connect(self.endingsComboBox, SIGNAL("currentIndexChanged(const QString&)"), self._endingsComboBoxChanged) # This spin box is currently hidden. change_connect(self.bondLengthDoubleSpinBox, SIGNAL("valueChanged(double)"), self._bondLengthChanged) change_connect(self.showCursorTextCheckBox, SIGNAL('stateChanged(int)'), self._update_state_of_cursorTextGroupBox) def ok_btn_clicked(self): """ Slot for the OK button """ if self.editCommand: self.editCommand.preview_or_finalize_structure(previewing=False) ##env.history.message(self.editCommand.logMessage) self.win.toolsDone() def cancel_btn_clicked(self): """ Slot for the Cancel button. """ if self.editCommand: self.editCommand.cancelStructure() self.win.toolsCancel() def _update_widgets_in_PM_before_show(self): """ Update various widgets in this Property manager. Overrides MotorPropertyManager._update_widgets_in_PM_before_show. The various widgets , (e.g. spinboxes) will get values from the structure for which this propMgr is constructed for (self.editcCntroller.struct) @see: MotorPropertyManager._update_widgets_in_PM_before_show @see: self.show where it is called. """ pass def getFlyoutActionList(self): """ Returns custom actionlist that will be used in a specific mode or editing a feature etc Example: while in movie mode, the _createFlyoutToolBar method calls this. """ #'allActionsList' returns all actions in the flyout toolbar #including the subcontrolArea actions allActionsList = [] #Action List for subcontrol Area buttons. #In this mode there is really no subcontrol area. #We will treat subcontrol area same as 'command area' #(subcontrol area buttons will have an empty list as their command area #list). We will set the Comamnd Area palette background color to the #subcontrol area. subControlAreaActionList = [] self.exitEditCommandAction.setChecked(True) subControlAreaActionList.append(self.exitEditCommandAction) separator = QAction(self.w) separator.setSeparator(True) subControlAreaActionList.append(separator) allActionsList.extend(subControlAreaActionList) #Empty actionlist for the 'Command Area' commandActionLists = [] #Append empty 'lists' in 'commandActionLists equal to the #number of actions in subControlArea for i in range(len(subControlAreaActionList)): lst = [] commandActionLists.append(lst) params = (subControlAreaActionList, commandActionLists, allActionsList) return params def _addGroupBoxes(self): """ Add the Insert Nanotube Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox(self, title="Endpoints") self._loadGroupBox1(self._pmGroupBox1) self._pmGroupBox1.hide() self._pmGroupBox2 = PM_GroupBox(self, title="Parameters") self._loadGroupBox2(self._pmGroupBox2) self._displayOptionsGroupBox = PM_GroupBox(self, title="Display Options") self._loadDisplayOptionsGroupBox(self._displayOptionsGroupBox) self._pmGroupBox3 = PM_GroupBox(self, title="Nanotube Distortion") self._loadGroupBox3(self._pmGroupBox3) self._pmGroupBox3.hide() #@ Temporary. self._pmGroupBox4 = PM_GroupBox(self, title="Multi-Walled CNTs") self._loadGroupBox4(self._pmGroupBox4) self._pmGroupBox4.hide() #@ Temporary. self._pmGroupBox5 = PM_GroupBox(self, title="Advanced Options") self._loadGroupBox5(self._pmGroupBox5) self._pmGroupBox5.hide() #@ Temporary. def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 1. """ #Following toolbutton facilitates entering a temporary NanotubeLineMode #to create a CNT using endpoints of the specified line. self.specifyCntLineButton = PM_ToolButton( pmGroupBox, text="Specify Endpoints", iconPath="ui/actions/Properties Manager/Pencil.png", spanWidth=True) self.specifyCntLineButton.setCheckable(True) self.specifyCntLineButton.setAutoRaise(True) self.specifyCntLineButton.setToolButtonStyle( Qt.ToolButtonTextBesideIcon) #EndPoint1 and endPoint2 coordinates. These widgets are hidden # as of 2007- 12 - 05 self._endPoint1SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox, label="End Point 1") self.x1SpinBox = self._endPoint1SpinBoxes.xSpinBox self.y1SpinBox = self._endPoint1SpinBoxes.ySpinBox self.z1SpinBox = self._endPoint1SpinBoxes.zSpinBox self._endPoint2SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox, label="End Point 2") self.x2SpinBox = self._endPoint2SpinBoxes.xSpinBox self.y2SpinBox = self._endPoint2SpinBoxes.ySpinBox self.z2SpinBox = self._endPoint2SpinBoxes.zSpinBox self._endPoint1SpinBoxes.hide() self._endPoint2SpinBoxes.hide() def _loadGroupBox2(self, pmGroupBox): """ Load widgets in group box 2. """ _ntTypeChoices = ['Carbon', 'Boron Nitride'] self.ntTypeComboBox = \ PM_ComboBox( pmGroupBox, label = "Type:", choices = _ntTypeChoices, setAsDefault = True) self.ntRiseDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Rise:", value = self.nanotube.getRise(), setAsDefault = True, minimum = 2.0, maximum = 4.0, decimals = 3, singleStep = 0.01 ) self.ntRiseDoubleSpinBox.hide() # Nanotube Length self.ntLengthLineEdit = \ PM_LineEdit( pmGroupBox, label = "Nanotube Length: ", text = "0.0 Angstroms", setAsDefault = False) self.ntLengthLineEdit.setDisabled(True) self.ntLengthLineEdit.hide() # Nanotube diameter self.ntDiameterLineEdit = \ PM_LineEdit( pmGroupBox, label = "Diameter: ", setAsDefault = False) self.ntDiameterLineEdit.setDisabled(True) self.updateNanotubeDiameter() self.chiralityNSpinBox = \ PM_SpinBox( pmGroupBox, label = "Chirality (n):", value = self.nanotube.getChiralityN(), minimum = 2, maximum = 100, setAsDefault = True ) self.chiralityMSpinBox = \ PM_SpinBox( pmGroupBox, label = "Chirality (m):", value = self.nanotube.getChiralityM(), minimum = 0, maximum = 100, setAsDefault = True ) # How about having user prefs for CNT and BNNT bond lengths? # I'm guessing that if the user wants to set these values, they will # do it once and would like those bond length values persist forever. # Need to discuss with others to determine if this spinbox comes out. # --Mark 2008-03-29 self.bondLengthDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Bond length:", value = self.nanotube.getBondLength(), setAsDefault = True, minimum = 1.0, maximum = 3.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) #self.bondLengthDoubleSpinBox.hide() endingChoices = ["Hydrogen", "None"] # Removed:, "Nitrogen"] self.endingsComboBox= \ PM_ComboBox( pmGroupBox, label = "Endings:", choices = endingChoices, index = 0, setAsDefault = True, spanWidth = False ) def _loadGroupBox3(self, inPmGroupBox): """ Load widgets in group box 3. """ self.zDistortionDoubleSpinBox = \ PM_DoubleSpinBox( inPmGroupBox, label = "Z-distortion:", value = 0.0, setAsDefault = True, minimum = 0.0, maximum = 10.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) self.xyDistortionDoubleSpinBox = \ PM_DoubleSpinBox( inPmGroupBox, label = "XY-distortion:", value = 0.0, setAsDefault = True, minimum = 0.0, maximum = 2.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) self.twistSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Twist:", value = 0, setAsDefault = True, minimum = 0, maximum = 100, # What should maximum be? suffix = " deg/A" ) self.bendSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Bend:", value = 0, setAsDefault = True, minimum = 0, maximum = 360, suffix = " deg" ) def _loadGroupBox4(self, inPmGroupBox): """ Load widgets in group box 4. """ # "Number of Nanotubes" SpinBox self.mwntCountSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Number:", value = 1, setAsDefault = True, minimum = 1, maximum = 10, suffix = " nanotubes" ) self.mwntCountSpinBox.setSpecialValueText("SWNT") # "Spacing" lineedit. self.mwntSpacingDoubleSpinBox = \ PM_DoubleSpinBox( inPmGroupBox, label = "Spacing:", value = 2.46, setAsDefault = True, minimum = 1.0, maximum = 10.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) def _loadGroupBox5(self, pmGroupBox): """ Load widgets in group box 5. """ self._rubberbandLineGroupBox = PM_GroupBox(pmGroupBox, title='Rubber band Line:') ntLineChoices = ['Ladder'] self.ntRubberBandLineDisplayComboBox = \ PM_ComboBox( self._rubberbandLineGroupBox , label = " Display as:", choices = ntLineChoices, setAsDefault = True) self.lineSnapCheckBox = \ PM_CheckBox(self._rubberbandLineGroupBox , text = 'Enable line snap' , widgetColumn = 1, state = Qt.Checked ) def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Overrides DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox """ connect_checkbox_with_boolean_pref( self.showCursorTextCheckBox, insertNanotubeEditCommand_showCursorTextCheckBox_prefs_key) def _params_for_creating_cursorTextCheckBoxes(self): """ Returns params needed to create various cursor text checkboxes connected to prefs_keys that allow custom cursor texts. @return: A list containing tuples in the following format: ('checkBoxTextString' , preference_key). PM_PrefsCheckBoxes uses this data to create checkboxes with the the given names and connects them to the provided preference keys. (Note that PM_PrefsCheckBoxes puts thes within a GroupBox) @rtype: list @see: PM_PrefsCheckBoxes @see: self._loadDisplayOptionsGroupBox where this list is used. @see: Superclass method which is overridden here -- DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = \ [ #Format: (" checkbox text", prefs_key) ("Nanotube length", insertNanotubeEditCommand_cursorTextCheckBox_length_prefs_key ), ("Angle", insertNanotubeEditCommand_cursorTextCheckBox_angle_prefs_key ) ] return params def _addToolTipText(self): """ Tool Tip text for widgets in the Insert Nanotube Property Manager. """ pass def _setEndPoints(self): """ Set the two endpoints of the nanotube using the values from the X, Y, Z coordinate spinboxes in the property manager. @note: The group box containing the 2 sets of XYZ spin boxes are currently hidden. """ # First endpoint (origin) of nanotube x1 = self.x1SpinBox.value() y1 = self.y1SpinBox.value() z1 = self.z1SpinBox.value() # Second endpoint (direction vector/axis) of nanotube. x2 = self.x2SpinBox.value() y2 = self.y2SpinBox.value() z2 = self.z2SpinBox.value() if not self.endPoint1: self.endPoint1 = V(x1, y1, z1) if not self.endPoint2: self.endPoint2 = V(x2, y2, z2) self.nanotube.setEndPoints(self.endPoint1, self.endPoint2) # Need arg "recompute=True", which will recompute the second # endpoint (endPoint2) using the nanotube rise. def getParameters(self): """ Return the parameters from this property manager to be used to create the nanotube. @return: A nanotube instance with its attrs set to the current parameters in the property manager. @rtype: L{Nanotube} @see: L{InsertNanotube_EditCommand._gatherParameters} where this is used """ self._setEndPoints() return (self.nanotube) def _ntTypeComboBoxChanged(self, type): """ Slot for the Type combobox. It is called whenever the Type choice is changed. @param inIndex: The new index. @type inIndex: int """ self.nanotube.setType(str(type)) print "Bond Length =", self.nanotube.getBondLength() self.bondLengthDoubleSpinBox.setValue(self.nanotube.getBondLength()) #self.bondLengthDoubleSpinBox.setValue(ntBondLengths[inIndex]) def _bondLengthChanged(self, bondLength): """ Slot for the B{Bond Length} spinbox. """ self.nanotube.setBondLength(bondLength) self.updateNanotubeDiameter() return def _chiralityFixup(self, spinBoxValueJunk=None): """ Slot for several validators for different parameters. This gets called whenever the user changes the n, m chirality values. @param spinBoxValueJunk: This is the Spinbox value from the valueChanged signal. It is not used. We just want to know that the spinbox value has changed. @type spinBoxValueJunk: double or None """ _n, _m = self.nanotube.setChirality(self.chiralityNSpinBox.value(), self.chiralityMSpinBox.value()) #self.n, self.m = self.nanotube.getChirality() self.connect_or_disconnect_signals(isConnect=False) self.chiralityNSpinBox.setValue(_n) self.chiralityMSpinBox.setValue(_m) self.connect_or_disconnect_signals(isConnect=True) self.updateNanotubeDiameter() def updateNanotubeDiameter(self): """ Update the nanotube Diameter lineEdit widget. """ diameterText = "%-7.4f Angstroms" % (self.nanotube.getDiameter()) self.ntDiameterLineEdit.setText(diameterText) # ntRiseDoubleSpinBox is currently hidden. self.ntRiseDoubleSpinBox.setValue(self.nanotube.getRise()) def _endingsComboBoxChanged(self, endings): """ Slot for the B{Ending} combobox. @param endings: The option's text. @type endings: string """ self.nanotube.setEndings(str(endings)) return def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ whatsThis_InsertNanotube_PropertyManager(self) return
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)