python_code
stringlengths
0
992k
repo_name
stringlengths
8
46
file_path
stringlengths
5
162
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Ninad 2008-01-25: Split modifyMode into Commmand and GraphicsMode classes and also refactored the GraphicsMode to create indiviudal classes rotating and tranlating selected entities. (called RotateChunks_GraphicsMode and TranslateChunks_GraphicsMode) TODO: [as of 2008-01-25] The class TranslateChunks_GraphicsMode may be renamed to Translate_GraphicsMode or TranslateComponents_GraphicsMode. """ from utilities import debug_flags import math from Numeric import dot import foundation.env as env from utilities.debug import print_compact_traceback from geometry.VQT import V, A, vlen, norm from commands.Move.Move_GraphicsMode import Move_GraphicsMode _superclass = Move_GraphicsMode class TranslateChunks_GraphicsMode(Move_GraphicsMode): """ Provides Graphics Mode for translating objects such as chunks. """ # class variables moveOption = 'MOVEDEFAULT' def update_cursor_for_no_MB(self): """ Update the cursor for 'Rotate Chunks' Graphics Mode """ if self.o.modkeys is None: if self.isConstrainedDragAlongAxis: self.o.setCursor(self.w.AxisTranslateRotateSelectionCursor) else: self.o.setCursor(self.w.TranslateSelectionCursor) elif self.o.modkeys == 'Shift': self.o.setCursor(self.w.TranslateSelectionAddCursor) elif self.o.modkeys == 'Control': self.o.setCursor(self.w.TranslateSelectionSubtractCursor) elif self.o.modkeys == 'Shift+Control': self.o.setCursor(self.w.DeleteCursor) else: print "Error in update_cursor_for_no_MB(): Invalid modkey=", self.o.modkeys return def _leftDown_preparation_for_dragging(self, objectUnderMouse, event): """ Handle left down event. Preparation for translation and/or selection This method is called inside of self.leftDown. @param event: The mouse left down event. @type event: QMouseEvent instance @see: self.leftDown @see: self.leftDragTranslation Overrides _superclass._leftDown_preparation_for_dragging """ _superclass._leftDown_preparation_for_dragging(self, objectUnderMouse, event) self.o.SaveMouse(event) self.picking = True self.dragdist = 0.0 self.transDelta = 0 # X, Y or Z deltas for translate. self.moveOffset = [0.0, 0.0, 0.0] # X, Y and Z offset for move. farQ_junk, self.movingPoint = self.dragstart_using_GL_DEPTH( event) # Following is in leftDrag() to compute move offset during drag op. self.startpt = self.movingPoint # Translate section if self.moveOption != 'MOVEDEFAULT': if self.moveOption == 'TRANSX': ma = V(1,0,0) # X Axis self.axis = 'X' elif self.moveOption == 'TRANSY': ma = V(0,1,0) # Y Axis self.axis = 'Y' elif self.moveOption == 'TRANSZ': ma = V(0,0,1) # Z Axis self.axis = 'Z' elif self.moveOption == 'ROT_TRANS_ALONG_AXIS': #The method 'self._leftDown_preparation_for_dragging should #never be reached if self.moveOption is 'ROT_TRANS_ALONG_AXIS' #If this code is reached, it indicates a bug. So fail gracefully #by calling self.leftADown() if debug_flags.atom_debug: print_compact_stack("bug: _leftDown_preparation_for_dragging"\ " called for translate option"\ "'ROT_TRANS_ALONG_AXIS'") self.leftADown(objectUnderMouse, event) return else: print "TranslateChunks_GraphicsMode Error - "\ "unknown moveOption value =", self.moveOption ma = norm(V(dot(ma,self.o.right),dot(ma,self.o.up))) # When in the front view, right = 1,0,0 and up = 0,1,0, so ma will #be computed as 0,0. # This creates a special case problem when the user wants to #constrain rotation around # the Z axis because Zmat will be zero. So we have to test for #this case (ma = 0,0) and # fix ma to -1,0. This was needed to fix bug 537. Mark 050420 if ma[0] == 0.0 and ma[1] == 0.0: ma = [-1.0, 0.0] self.Zmat = A([ma,[-ma[1],ma[0]]]) # end of Translate section self.leftDownType = 'TRANSLATE' return def leftDrag(self, event): """ Translate the selected object(s): - in the plane of the screen following the mouse, - or slide and rotate along the an axis @param event: The mouse left drag event. @type event: QMouseEvent instance """ _superclass.leftDrag(self, event) if self.cursor_over_when_LMB_pressed == 'Empty Space': #The _superclass.leftDrag considers this condition. #So simply return and don't go further. Fixes bug 2607 return if self.leftDownType in ['TRANSLATE', 'A_TRANSLATE']: try: self.leftDragTranslation(event) return except: msg1 = "Controlled translation not allowed. " msg2 = "Key must be pressed before starting the drag" env.history.statusbar_msg(msg1 + msg2) if debug_flags.atom_debug: msg3 = "Error occured in "\ "TranslateChunks_GraphicsMode.leftDragTranslation." msg4 = "Possibly due to a key press that activated. " msg5 = "Rotate groupbox. Aborting drag operation" print_compact_traceback(msg3 + msg4 + msg5) def leftADown(self, objectUnderMouse, event): """ """ _superclass.leftADown(self, objectUnderMouse, event) self.leftDownType = 'A_TRANSLATE' def leftDragTranslation(self, event): """ Translate the selected object(s): - in the plane of the screen following the mouse, - or slide and rotate along the an axis @param event: The mouse left drag event. @see: self.leftDrag() @see: self._leftDragFreeTranslation() @see: self._leftDragConstrainedTranslation() """ #TODO: Further cleanup of this method and also for # _superclass.leftDragTranslation. Need to move some common code #in this method to self.leftDrag. Lower priority -- ninad 20070727 if self.command and self.command.propMgr and \ hasattr(self.command.propMgr, "translateComboBox"): if self.command.propMgr.translateComboBox.currentText() != "Free Drag": return # Fixes bugs 583 and 674 along with change in keyRelease. Mark 050623 # Fix per Bruce's email. Mark 050704 if self.movingPoint is None: self.leftDown(event) if self.moveOption == 'ROT_TRANS_ALONG_AXIS': try: self.leftADrag(event) except: print_compact_traceback(" error doing leftADrag") return # Move section if self.moveOption == 'MOVEDEFAULT': self._leftDragFreeTranslation(event) return # end of Move section self._leftDragConstrainedTranslation(event) return def _leftDragConstrainedTranslation(self, event): """ Constrained translation during the left drag. @see: self.leftDragTranslation() @see: self._leftDragFreeTranslation() """ # Constrained translation w=self.o.width+0.0 h=self.o.height+0.0 deltaMouse = V(event.pos().x() - self.o.MousePos[0], self.o.MousePos[1] - event.pos().y()) a = dot(self.Zmat, deltaMouse) dx,dy = a * V(self.o.scale/(h*0.5), 2*math.pi/w) if self.moveOption == 'TRANSX': ma = V(1,0,0) # X Axis elif self.moveOption == 'TRANSY': ma = V(0,1,0) # Y Axis elif self.moveOption == 'TRANSZ': ma = V(0,0,1) # Z Axis else: print "_leftDragConstrainedTranslation Error: unknown moveOption value:", \ self.moveOption return self.transDelta += dx # Increment translation delta self.win.assy.translateSpecifiedMovables(dx*ma, movables = self._leftDrag_movables) # Print status bar msg indicating the current translation delta if self.o.assy.selmols: msg = "%s delta: [%.2f Angstroms] [0 Degrees]" % (self.axis, self.transDelta) env.history.statusbar_msg(msg) # common finished code self.dragdist += vlen(deltaMouse) self.o.SaveMouse(event) self.o.gl_update() return
NanoCAD-master
cad/src/commands/Translate/TranslateChunks_GraphicsMode.py
NanoCAD-master
cad/src/commands/Translate/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ TranslateChunks_Command.py @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version: $Id$ History: NOTE: As of 2008-01-25, this command is not yet used, however its graphics mode class (TranslateChunks_GraphicsMode) is used as an alternative graphics mode in Move_Command. """ from commands.Move.Move_Command import Move_Command from commands.Translate.TranslateChunks_GraphicsMode import TranslateChunks_GraphicsMode _superclass = Move_Command class TranslateChunks_Command(Move_Command): """ Translate Chunks command """ commandName = 'TRANSLATE_CHUNKS' featurename = "Translate Chunks" from utilities.constants import CL_EDIT_GENERIC command_level = CL_EDIT_GENERIC command_should_resume_prevMode = True command_has_its_own_PM = False GraphicsMode_class = TranslateChunks_GraphicsMode def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean As of 2008-01-25, this method does nothing. """ pass
NanoCAD-master
cad/src/commands/Translate/TranslateChunks_Command.py
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details. """ $Id$ """ from PyQt4 import QtCore, QtGui class Ui_ChunkPropDialog(object): def setupUi(self, ChunkPropDialog): ChunkPropDialog.setObjectName("ChunkPropDialog") ChunkPropDialog.resize(QtCore.QSize(QtCore.QRect(0,0,243,354).size()).expandedTo(ChunkPropDialog.minimumSizeHint())) self.vboxlayout = QtGui.QVBoxLayout(ChunkPropDialog) self.vboxlayout.setMargin(11) self.vboxlayout.setSpacing(6) self.vboxlayout.setObjectName("vboxlayout") self.gridlayout = QtGui.QGridLayout() self.gridlayout.setMargin(0) self.gridlayout.setSpacing(6) self.gridlayout.setObjectName("gridlayout") self.atomsTextBrowser = QtGui.QTextBrowser(ChunkPropDialog) self.atomsTextBrowser.setObjectName("atomsTextBrowser") self.gridlayout.addWidget(self.atomsTextBrowser,1,1,1,1) self.vboxlayout1 = QtGui.QVBoxLayout() self.vboxlayout1.setMargin(0) self.vboxlayout1.setSpacing(6) self.vboxlayout1.setObjectName("vboxlayout1") self.textLabel2 = QtGui.QLabel(ChunkPropDialog) self.textLabel2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.textLabel2.setObjectName("textLabel2") self.vboxlayout1.addWidget(self.textLabel2) spacerItem = QtGui.QSpacerItem(20,113,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Expanding) self.vboxlayout1.addItem(spacerItem) self.gridlayout.addLayout(self.vboxlayout1,1,0,1,1) self.nameLineEdit = QtGui.QLineEdit(ChunkPropDialog) self.nameLineEdit.setAlignment(QtCore.Qt.AlignLeading) self.nameLineEdit.setObjectName("nameLineEdit") self.gridlayout.addWidget(self.nameLineEdit,0,1,1,1) self.textLabel1 = QtGui.QLabel(ChunkPropDialog) self.textLabel1.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.textLabel1.setObjectName("textLabel1") self.gridlayout.addWidget(self.textLabel1,0,0,1,1) self.vboxlayout.addLayout(self.gridlayout) self.hboxlayout = QtGui.QHBoxLayout() self.hboxlayout.setMargin(0) self.hboxlayout.setSpacing(6) self.hboxlayout.setObjectName("hboxlayout") self.colorTextLabel = QtGui.QLabel(ChunkPropDialog) self.colorTextLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.colorTextLabel.setObjectName("colorTextLabel") self.hboxlayout.addWidget(self.colorTextLabel) self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setMargin(0) self.hboxlayout1.setSpacing(6) self.hboxlayout1.setObjectName("hboxlayout1") self.chunk_color_frame = QtGui.QLabel(ChunkPropDialog) self.chunk_color_frame.setAutoFillBackground(True) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(5)) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.chunk_color_frame.sizePolicy().hasHeightForWidth()) self.chunk_color_frame.setSizePolicy(sizePolicy) self.chunk_color_frame.setMinimumSize(QtCore.QSize(40,0)) self.chunk_color_frame.setFrameShape(QtGui.QFrame.Box) self.chunk_color_frame.setFrameShadow(QtGui.QFrame.Plain) self.chunk_color_frame.setScaledContents(True) self.chunk_color_frame.setObjectName("chunk_color_frame") self.hboxlayout1.addWidget(self.chunk_color_frame) self.choose_color_btn = QtGui.QPushButton(ChunkPropDialog) self.choose_color_btn.setEnabled(True) self.choose_color_btn.setAutoDefault(False) self.choose_color_btn.setObjectName("choose_color_btn") self.hboxlayout1.addWidget(self.choose_color_btn) spacerItem1 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout1.addItem(spacerItem1) self.hboxlayout.addLayout(self.hboxlayout1) self.vboxlayout.addLayout(self.hboxlayout) self.reset_color_btn = QtGui.QPushButton(ChunkPropDialog) self.reset_color_btn.setEnabled(True) self.reset_color_btn.setAutoDefault(False) self.reset_color_btn.setObjectName("reset_color_btn") self.vboxlayout.addWidget(self.reset_color_btn) self.make_atoms_visible_btn = QtGui.QPushButton(ChunkPropDialog) self.make_atoms_visible_btn.setEnabled(True) self.make_atoms_visible_btn.setAutoDefault(False) self.make_atoms_visible_btn.setObjectName("make_atoms_visible_btn") self.vboxlayout.addWidget(self.make_atoms_visible_btn) spacerItem2 = QtGui.QSpacerItem(20,20,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Expanding) self.vboxlayout.addItem(spacerItem2) self.hboxlayout2 = QtGui.QHBoxLayout() self.hboxlayout2.setMargin(0) self.hboxlayout2.setSpacing(6) self.hboxlayout2.setObjectName("hboxlayout2") spacerItem3 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout2.addItem(spacerItem3) self.ok_btn = QtGui.QPushButton(ChunkPropDialog) self.ok_btn.setMinimumSize(QtCore.QSize(0,0)) self.ok_btn.setDefault(True) self.ok_btn.setObjectName("ok_btn") self.hboxlayout2.addWidget(self.ok_btn) self.cancel_btn = QtGui.QPushButton(ChunkPropDialog) self.cancel_btn.setMinimumSize(QtCore.QSize(0,0)) self.cancel_btn.setDefault(False) self.cancel_btn.setObjectName("cancel_btn") self.hboxlayout2.addWidget(self.cancel_btn) self.vboxlayout.addLayout(self.hboxlayout2) self.retranslateUi(ChunkPropDialog) ChunkPropDialog.setTabOrder(self.nameLineEdit,self.atomsTextBrowser) ChunkPropDialog.setTabOrder(self.atomsTextBrowser,self.choose_color_btn) ChunkPropDialog.setTabOrder(self.choose_color_btn,self.reset_color_btn) ChunkPropDialog.setTabOrder(self.reset_color_btn,self.make_atoms_visible_btn) ChunkPropDialog.setTabOrder(self.make_atoms_visible_btn,self.ok_btn) ChunkPropDialog.setTabOrder(self.ok_btn,self.cancel_btn) def retranslateUi(self, ChunkPropDialog): ChunkPropDialog.setWindowTitle(QtGui.QApplication.translate("ChunkPropDialog", "Chunk Properties", None, QtGui.QApplication.UnicodeUTF8)) ChunkPropDialog.setWindowIcon(QtGui.QIcon("ui/border/Chunk")) self.textLabel2.setText(QtGui.QApplication.translate("ChunkPropDialog", "Atoms:", None, QtGui.QApplication.UnicodeUTF8)) self.textLabel1.setText(QtGui.QApplication.translate("ChunkPropDialog", "Name:", None, QtGui.QApplication.UnicodeUTF8)) self.colorTextLabel.setText(QtGui.QApplication.translate("ChunkPropDialog", "Chunk Color:", None, QtGui.QApplication.UnicodeUTF8)) self.choose_color_btn.setToolTip(QtGui.QApplication.translate("ChunkPropDialog", "Change chunk color", None, QtGui.QApplication.UnicodeUTF8)) self.choose_color_btn.setText(QtGui.QApplication.translate("ChunkPropDialog", "Choose...", None, QtGui.QApplication.UnicodeUTF8)) self.reset_color_btn.setText(QtGui.QApplication.translate("ChunkPropDialog", "Reset Chunk Color to Default", None, QtGui.QApplication.UnicodeUTF8)) self.make_atoms_visible_btn.setText(QtGui.QApplication.translate("ChunkPropDialog", "Make Invisible Atoms Visible", None, QtGui.QApplication.UnicodeUTF8)) self.ok_btn.setText(QtGui.QApplication.translate("ChunkPropDialog", "&OK", None, QtGui.QApplication.UnicodeUTF8)) self.ok_btn.setShortcut(QtGui.QApplication.translate("ChunkPropDialog", "Alt+O", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setText(QtGui.QApplication.translate("ChunkPropDialog", "&Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setShortcut(QtGui.QApplication.translate("ChunkPropDialog", "Alt+C", None, QtGui.QApplication.UnicodeUTF8))
NanoCAD-master
cad/src/commands/ChunkProperties/ChunkPropDialog.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ ChunkProp.py @author: Mark @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Original code from MoleculeProps.py and cleaned up by Mark. """ from PyQt4 import QtGui from PyQt4.Qt import QDialog, SIGNAL, QColorDialog from commands.ChunkProperties.ChunkPropDialog import Ui_ChunkPropDialog from widgets.widget_helpers import RGBf_to_QColor, QColor_to_RGBf class ChunkProp(QDialog, Ui_ChunkPropDialog): def __init__(self, chunk): QDialog.__init__(self) self.setupUi(self) self.chunk = chunk self.glpane = chunk.glpane self.connect(self.ok_btn,SIGNAL("clicked()"),self.accept) self.connect(self.cancel_btn,SIGNAL("clicked()"),self.reject) self.connect(self.reset_color_btn,SIGNAL("clicked()"),self.reset_chunk_color) self.connect(self.choose_color_btn,SIGNAL("clicked()"),self.change_chunk_color) self.connect(self.make_atoms_visible_btn,SIGNAL("clicked()"),self.make_atoms_visible) self.setup() def setup(self): # Chunk color self.original_color = self.chunk.color # Save original Chunk color in case of Cancel if self.chunk.color: # Set colortile to chunk color (without border) self.chunk_QColor = RGBf_to_QColor(self.chunk.color) # Used as default color by Color Chooser else: # Set the colortile to the dialog's bg color (no color) self.chunk_QColor =self.palette().color(QtGui.QPalette.Window) plt = QtGui.QPalette() plt.setColor(QtGui.QPalette.Active,QtGui.QPalette.Window,self.chunk_QColor) plt.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.Window,self.chunk_QColor) plt.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.Window,self.chunk_QColor) self.chunk_color_frame.setPalette(plt) self.nameLineEdit.setText(self.chunk.name) self.atomsTextBrowser.setPlainText(self.get_chunk_props_info()) def get_chunk_props_info(self): """ Return chunk properties information. """ self.atomsTextBrowser.setReadOnly(True) chunkInfoText = "" natoms = len(self.chunk.atoms) # number of atoms in the chunk # Determining the number of element types in this Chunk. ele2Num = {} for a in self.chunk.atoms.itervalues(): if not ele2Num.has_key(a.element.symbol): ele2Num[a.element.symbol] = 1 # New element found else: ele2Num[a.element.symbol] += 1 # Increment element # String construction for each element to be displayed. nsinglets = 0 for item in ele2Num.iteritems(): if item[0] == "X": # It is a Singlet nsinglets = int(item[1]) continue else: eleStr = item[0] + ": " + str(item[1]) + "\n" chunkInfoText += eleStr if nsinglets: eleStr = "\nBondpoints: " + str(nsinglets) + "\n" chunkInfoText += eleStr natoms -= nsinglets header = "Total Atoms: " + str(natoms) + "\n" return header + chunkInfoText def change_chunk_color(self): """ Slot method to change the chunk's color. """ color = QColorDialog.getColor(self.chunk_QColor, self) if color.isValid(): plt = QtGui.QPalette() plt.setColor(QtGui.QPalette.Active,QtGui.QPalette.Window,color) plt.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.Window,color) plt.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.Window,color) self.chunk_color_frame.setPalette(plt) self.chunk_QColor = color self.chunk.color = QColor_to_RGBf(color) self.chunk.setcolor(self.chunk.color) if self.chunk.hidden: # A hidden chunk has no glpane attr. return #Ninad 070321: #Note: #The chunk is NOT unpicked immediately after changing the color via #chunk property dialog, This is intentional. #BTW I don't know why it deselects the chunk after hitting OK or Cancel! #(looks like an old Qt4 transition bug) self.glpane.gl_update() def reset_chunk_color(self): """ Slot method to reset the chunk's color. """ if not self.chunk.color: return self.chunk_QColor = self.palette().color(QtGui.QPalette.Window) plt = QtGui.QPalette() plt.setColor(QtGui.QPalette.Active,QtGui.QPalette.Window,self.chunk_QColor) plt.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.Window,self.chunk_QColor) plt.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.Window,self.chunk_QColor) self.chunk_color_frame.setPalette(plt) self.chunk.color = None self.chunk.setcolor(self.chunk.color) if self.chunk.hidden: # A hidden chunk has no glpane attr. return self.glpane.gl_update() def make_atoms_visible(self): """ Makes any atoms in this chunk visible. """ self.chunk.show_invisible_atoms() if self.chunk.hidden: # A hidden chunk has no glpane attr. return self.glpane.gl_update() def accept(self): """ Slot for the 'OK' button """ self.chunk.try_rename(self.nameLineEdit.text()) self.chunk.assy.w.win_update() # Update model tree self.chunk.assy.changed() QDialog.accept(self) def reject(self): """ Slot for the 'Cancel' button """ self.chunk.color = self.original_color self.chunk.setcolor(self.chunk.color) QDialog.reject(self) # A hidden chunk has no glpane attr. This fixes bug 1137. Mark 051126. if self.chunk.hidden: return self.glpane.gl_update()
NanoCAD-master
cad/src/commands/ChunkProperties/ChunkProp.py
NanoCAD-master
cad/src/commands/ChunkProperties/__init__.py
NanoCAD-master
cad/src/commands/PlaneProperties/__init__.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ Plane_EditCommand.py @author: Ninad @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. @version: $Id$ History: ninad 20070606: Created. ninad 2007-10-05: Refactored, Also renamed PlaneGenerator to Plane_EditCommand while refactoring the old GeometryGeneratorBaseClass ninad 2007-12-26: Changes to make Plane_EditCommand a command on command stack Summer 2008: Urmi and Piotr added code to support image display and grid display within Plane objects. @TODO 2008-04-15: Note that Plane_EditCommand was originally implemented before the command sequencer was operational. This class and its Property Manager has some methods that need cleanup to matchup with the command/commandsequencer API. e.g. in its PM, the method update_props_if_needed_before_closing need to be revised because there is any easy way now, to know which command is currently active.Also a general clanup is due -- Ninad TODO 2008-09-09 Refactor update ui related code. e.g. see self.command_will_exit() -- self.struct.updatecosmeticProps() should go inside a command_update method. [-- Ninad] """ from utilities.Log import greenmsg from command_support.EditCommand import EditCommand from commands.PlaneProperties.PlanePropertyManager import PlanePropertyManager from model.Plane import Plane from commands.SelectAtoms.SelectAtoms_GraphicsMode import SelectAtoms_GraphicsMode from utilities.Comparison import same_vals from utilities.debug import print_compact_stack _superclass = EditCommand class Plane_EditCommand(EditCommand): """ The Plane_EditCommand class provides an editCommand Object. The editCommand, depending on what client code needs it to do, may create a new plane or it may be used for an existing plane. """ #@NOTE: self.struct is the Plane object PM_class = PlanePropertyManager GraphicsMode_class = SelectAtoms_GraphicsMode cmd = greenmsg("Plane: ") # prefix = '' # Not used by jigs. # All jigs like rotary and linear motors already created their # name, so do not (re)create it (in GeneratorBaseClass) from the prefix. create_name_from_prefix = False #See Command.anyCommand for details about the following flags command_should_resume_prevMode = True command_has_its_own_PM = True # When <command_should_resume_prevMode> and <command_has_its_own_PM> # are both set to True (like here), want_confirmation_corner_type() # will determine that the confirmation corner should include the # Transient-Done image, which is sometimes OK and sometimes not OK. # This is what bug 2701 is about (assigned to me). I will talk to Ninad # and Bruce about fixing this (after Rattlesnake). # --Mark 2008-03-24 commandName = 'REFERENCE_PLANE' featurename = "Reference Plane" from utilities.constants import CL_EDIT_GENERIC command_level = CL_EDIT_GENERIC #see self.command_update_internal_state() _previous_display_params = None def command_will_exit(self): #Following call doesn't update the struct with steps similar to #ones in bug 2699. Instead calling struct.updateCosmeticProps directly #Note 2008-09-09: this code was copied from the former self.restore_gui. #This needs to do inside an update method. if self.hasValidStructure(): self.struct.updateCosmeticProps() _superclass.command_will_exit(self) def _getStructureType(self): """ Subclasses override this method to define their own structure type. Returns the type of the structure this command supports. This is used in isinstance test. @see: EditCommand._getStructureType() (overridden here) """ return Plane def placePlaneParallelToScreen(self): """ Orient this plane such that it is placed parallel to the screen """ self.struct.placePlaneParallelToScreen() def placePlaneThroughAtoms(self): """ Orient this plane such that its center is same as the common center of three or more selected atoms. """ self.struct.placePlaneThroughAtoms() #NOTE: This log message can be used to either display a history message #if using NE1 UI or for consol print when command is executed via #command prompt. Its upto the client to use this message. This, #however needs a global updater that will clear previous log message #from this object, in order to avoid errors. (if in some cases, the #logMessage is not there, client could accidentaly use garbage #logMessage hanging out from some previous execution) #This is subject to revision. May not be needed after once Logging #facility (see Log.py) is fully implemented -- Ninad 20070921 self.logMessage = self.cmd + self.struct.logMessage def placePlaneOffsetToAnother(self): """ Orient the plane such that it is parallel to a selected plane , with an offset. """ self.struct.placePlaneOffsetToAnother() self.logMessage = self.cmd + self.struct.logMessage ##=========== Structure Generator like interface ======## def _gatherParameters(self): """ Return all the parameters from the Plane Property Manager. """ width, height, gridColor, gridLineType, gridXSpacing, gridYSpacing, \ originLocation, displayLabelStyle = self.propMgr.getParameters() atmList = self.win.assy.selatoms_list() #Do not change the plane placement here. ONLY do it when user explicitely #selects an option from the radio button list. This avoids bug 2949 #but a side effect of this fix is that if user has already changed a #radio button option , then makes some changes -- then the current placement #option won't have any effect. ##self.propMgr.changePlanePlacement( ##self.propMgr.pmPlacementOptions.checkedId()) if self.struct: ctr = self.struct.center imagePath = self.struct.imagePath else: ctr = None imagePath = '' return (width, height, ctr, atmList, imagePath, gridColor, gridLineType, gridXSpacing, gridYSpacing, originLocation, displayLabelStyle) def _createStructure(self): """ Create a Plane object. (The model object which this edit controller creates) """ assert not self.struct self.win.assy.part.ensure_toplevel_group() struct = Plane(self.win, self) self.win.assy.place_new_geometry(struct) return struct def _modifyStructure(self, params): """ Modifies the structure (Plane) using the provided params. @param params: The parameters used as an input to modify the structure (Plane created using this Plane_EditCommand) @type params: tuple """ assert self.struct assert params assert len(params) == 11 width, height, center_junk, atmList_junk, imagePath, \ gridColor, gridLineType, gridXSpacing, \ gridYSpacing, originLocation, displayLabelStyle = params self.struct.width = width self.struct.height = height self.struct.imagePath = imagePath self.struct.gridColor = gridColor self.struct.gridLineType = gridLineType self.struct.gridXSpacing = gridXSpacing self.struct.gridYSpacing = gridYSpacing self.struct.originLocation = originLocation self.struct.displayLabelStyle = displayLabelStyle self.win.win_update() # Update model tree self.win.assy.changed() ##=====================================## def command_update_internal_state(self): """ Extends the superclass method. This method should replace model_changed() eventually. This method calss self.model_changed at the moment. @see:baseCommand.command_update_internal_state() for documentation @see: PlanePropertyManager._update_UI_do_updates() @see: PlanePropertyManager.update_spinboxes() @see: Plane.resizeGeometry() """ if not self.propMgr: print_compact_stack("bug: self.propMgr not defined when"\ "Plane_EditCommand.command_update_internal_state called."\ "Returning.") return #check first if the plane object exists first if not self.hasValidStructure(): return #NOTE: The following ensures that the image path and other display #prams are properly updated in the plane. Perhaps its better done using #env.prefs? Revising this code to fix bugs in resizing because #of the self._modifyStructure call. See also original code in #Revision 12982 -- Ninad 2008-09-19 currentDisplayParams = self.propMgr.getCurrrentDisplayParams() if same_vals(currentDisplayParams, self._previous_display_params): return self._previous_display_params = currentDisplayParams params = self._gatherParameters() self._modifyStructure(params) def runCommand(self): """ Overrides superclass method. Run this edit command. This method is called when user invokes Insert > Plane command (to create a new plane object) . In addition to creating the Plane object and Property manager, this also updates the property manager values with the ones for the new Plane object. @see: MWSemantics.createPlane() which calls this while inserting a new Plane @see: self.editStructure() @see: PlanePropertyManager.setParameters() @see: self._updatePropMgrParams() @TODO: The code that updates the PropMgr params etc needs to be in the EditCommand API method/ """ _superclass.runCommand(self) if self.hasValidStructure(): self._updatePropMgrParams() #Store the previous parameters. Important to set it after you #set attrs in the propMgr. #self.previousParams is used in self._previewStructure and #self._finalizeStructure to check if self.struct changed. self.previousParams = self._gatherParameters() def editStructure(self, struct = None): """ """ _superclass.editStructure(self, struct) if self.hasValidStructure(): self._updatePropMgrParams() #Store the previous parameters. Important to set it after you #set attrs in the propMgr. #self.previousParams is used in self._previewStructure and #self._finalizeStructure to check if self.struct changed. self.previousParams = self._gatherParameters() def _updatePropMgrParams(self): """ Subclasses may override this method. Update some property manager parameters with the parameters of self.struct (which is being edited) @see: self.editStructure() """ params_for_propMgr = (self.struct.width, self.struct.height, self.struct.gridColor, self.struct.gridLineType, self.struct.gridXSpacing, self.struct.gridYSpacing, self.struct.originLocation, self.struct.displayLabelStyle ) #TODO 2008-03-25: better to get all parameters from self.struct and #set it in propMgr? This will mostly work but some params used in #PM are not required by structy and vice versa. (e.g. struct.name) self.propMgr.setParameters(params_for_propMgr)
NanoCAD-master
cad/src/commands/PlaneProperties/Plane_EditCommand.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: ninad 20070602: Created. Summer 2008: Urmi and Piotr added code to support image display and grid display within Plane objects. TODO 2008-09-19: See Plane_EditCommand.py """ from PyQt4.Qt import SIGNAL from PyQt4.Qt import Qt from PM.PM_GroupBox import PM_GroupBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_CheckBox import PM_CheckBox from PM.PM_LineEdit import PM_LineEdit from PM.PM_RadioButtonList import PM_RadioButtonList from PM.PM_ToolButtonRow import PM_ToolButtonRow from PM.PM_Constants import PM_RESTORE_DEFAULTS_BUTTON from PM.PM_FileChooser import PM_FileChooser from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_ComboBox import PM_ComboBox from PM.PM_ColorComboBox import PM_ColorComboBox from command_support.EditCommand_PM import EditCommand_PM import foundation.env as env from utilities.constants import yellow, orange, red, magenta from utilities.constants import cyan, blue, white, black, gray from utilities.constants import PLANE_ORIGIN_LOWER_LEFT from utilities.constants import PLANE_ORIGIN_LOWER_RIGHT from utilities.constants import PLANE_ORIGIN_UPPER_LEFT from utilities.constants import PLANE_ORIGIN_UPPER_RIGHT from utilities.constants import LABELS_ALONG_ORIGIN, LABELS_ALONG_PLANE_EDGES from utilities.prefs_constants import PlanePM_showGridLabels_prefs_key, PlanePM_showGrid_prefs_key from utilities import debug_flags from widgets.prefs_widgets import connect_checkbox_with_boolean_pref _superclass = EditCommand_PM 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
NanoCAD-master
cad/src/commands/PlaneProperties/PlanePropertyManager.py
NanoCAD-master
cad/src/commands/PovraySceneProperties/__init__.py
# -*- coding: utf-8 -*- # Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ PovrayScenePropDialog.py Note: this file is not presently used in NE1 (as of before 080515). @author: Mark @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. History: This used to be made by pyuic from a .ui file, but since then it has been hand-modified in ways that are not possible to do using the .ui file (though they might be doable in the subclass instead), and the .ui file has been moved to a non-active name. If this command is revived, either those changes need abandoning or to be done in the subclass (if the .ui file is also revived), or (preferably) the .ui file should be removed and the UI rewritten to use the PM module. The comment from pyuic claims that it was last created from the .ui file on this date: # Created: Wed Sep 27 14:24:15 2006 # by: PyQt4 UI code generator 4.0.1 """ from PyQt4 import QtCore, QtGui from utilities.icon_utilities import geticon #@from PM.PM_Constants import getHeaderFont #@from PM.PM_Constants import pmLabelLeftAlignment class Ui_PovrayScenePropDialog(object): def setupUi(self, PovrayScenePropDialog): PovrayScenePropDialog.setObjectName("PovrayScenePropDialog") PovrayScenePropDialog.resize(QtCore.QSize(QtCore.QRect(0,0,207,368).size()).expandedTo(PovrayScenePropDialog.minimumSizeHint())) self.vboxlayout = QtGui.QVBoxLayout(PovrayScenePropDialog) self.vboxlayout.setMargin(0) self.vboxlayout.setSpacing(0) self.vboxlayout.setObjectName("vboxlayout") self.heading_frame = QtGui.QFrame(PovrayScenePropDialog) self.heading_frame.setFrameShape(QtGui.QFrame.NoFrame) self.heading_frame.setFrameShadow(QtGui.QFrame.Plain) self.heading_frame.setObjectName("heading_frame") self.hboxlayout = QtGui.QHBoxLayout(self.heading_frame) self.hboxlayout.setMargin(0) self.hboxlayout.setSpacing(3) self.hboxlayout.setObjectName("hboxlayout") self.heading_pixmap = QtGui.QLabel(self.heading_frame) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(0),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.heading_pixmap.sizePolicy().hasHeightForWidth()) self.heading_pixmap.setSizePolicy(sizePolicy) self.heading_pixmap.setScaledContents(True) self.heading_pixmap.setAlignment(QtCore.Qt.AlignVCenter) self.heading_pixmap.setObjectName("heading_pixmap") self.hboxlayout.addWidget(self.heading_pixmap) self.heading_label = QtGui.QLabel(self.heading_frame) #@self.heading_label.setFont(getHeaderFont()) #@self.heading_label.setAlignment(pmLabelLeftAlignment) self.hboxlayout.addWidget(self.heading_label) self.vboxlayout.addWidget(self.heading_frame) self.body_frame = QtGui.QFrame(PovrayScenePropDialog) self.body_frame.setFrameShape(QtGui.QFrame.StyledPanel) self.body_frame.setFrameShadow(QtGui.QFrame.Raised) self.body_frame.setObjectName("body_frame") self.vboxlayout1 = QtGui.QVBoxLayout(self.body_frame) self.vboxlayout1.setMargin(3) self.vboxlayout1.setSpacing(3) self.vboxlayout1.setObjectName("vboxlayout1") self.sponsor_btn = QtGui.QPushButton(self.body_frame) self.sponsor_btn.setAutoDefault(False) self.sponsor_btn.setFlat(True) self.sponsor_btn.setObjectName("sponsor_btn") self.vboxlayout1.addWidget(self.sponsor_btn) self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setMargin(0) self.hboxlayout1.setSpacing(6) self.hboxlayout1.setObjectName("hboxlayout1") spacerItem = QtGui.QSpacerItem(35,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout1.addItem(spacerItem) self.done_btn = QtGui.QToolButton(self.body_frame) self.done_btn.setIcon( geticon("ui/actions/Properties Manager/Done.png")) self.done_btn.setObjectName("done_btn") self.hboxlayout1.addWidget(self.done_btn) self.abort_btn = QtGui.QToolButton(self.body_frame) self.abort_btn.setIcon( geticon("ui/actions/Properties Manager/Abort.png")) self.abort_btn.setObjectName("abort_btn") self.hboxlayout1.addWidget(self.abort_btn) self.restore_btn = QtGui.QToolButton(self.body_frame) self.restore_btn.setIcon( geticon("ui/actions/Properties Manager/Restore.png")) self.restore_btn.setObjectName("restore_btn") self.hboxlayout1.addWidget(self.restore_btn) self.preview_btn = QtGui.QToolButton(self.body_frame) self.preview_btn.setIcon( geticon("ui/actions/Properties Manager/Preview.png")) self.preview_btn.setObjectName("preview_btn") self.hboxlayout1.addWidget(self.preview_btn) self.whatsthis_btn = QtGui.QToolButton(self.body_frame) self.whatsthis_btn.setIcon( geticon("ui/actions/Properties Manager/WhatsThis.png")) self.whatsthis_btn.setObjectName("whatsthis_btn") self.hboxlayout1.addWidget(self.whatsthis_btn) spacerItem1 = QtGui.QSpacerItem(35,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout1.addItem(spacerItem1) self.vboxlayout1.addLayout(self.hboxlayout1) self.name_grpbox = QtGui.QGroupBox(self.body_frame) self.name_grpbox.setObjectName("name_grpbox") self.vboxlayout2 = QtGui.QVBoxLayout(self.name_grpbox) self.vboxlayout2.setMargin(4) self.vboxlayout2.setSpacing(1) self.vboxlayout2.setObjectName("vboxlayout2") self.hboxlayout2 = QtGui.QHBoxLayout() self.hboxlayout2.setMargin(0) self.hboxlayout2.setSpacing(6) self.hboxlayout2.setObjectName("hboxlayout2") self.name_grpbox_label = QtGui.QLabel(self.name_grpbox) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(1)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.name_grpbox_label.sizePolicy().hasHeightForWidth()) self.name_grpbox_label.setSizePolicy(sizePolicy) self.name_grpbox_label.setAlignment(QtCore.Qt.AlignVCenter) self.name_grpbox_label.setObjectName("name_grpbox_label") self.hboxlayout2.addWidget(self.name_grpbox_label) spacerItem2 = QtGui.QSpacerItem(67,16,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout2.addItem(spacerItem2) self.grpbtn_1 = QtGui.QPushButton(self.name_grpbox) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(0),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.grpbtn_1.sizePolicy().hasHeightForWidth()) self.grpbtn_1.setSizePolicy(sizePolicy) self.grpbtn_1.setMaximumSize(QtCore.QSize(16,16)) self.grpbtn_1.setIcon( geticon("ui/actions/Properties Manager/Group_Button.png")) self.grpbtn_1.setAutoDefault(False) self.grpbtn_1.setFlat(True) self.grpbtn_1.setObjectName("grpbtn_1") self.hboxlayout2.addWidget(self.grpbtn_1) self.vboxlayout2.addLayout(self.hboxlayout2) self.line2 = QtGui.QFrame(self.name_grpbox) self.line2.setFrameShape(QtGui.QFrame.HLine) self.line2.setFrameShadow(QtGui.QFrame.Sunken) self.line2.setMidLineWidth(0) self.line2.setFrameShape(QtGui.QFrame.HLine) self.line2.setFrameShadow(QtGui.QFrame.Sunken) self.line2.setObjectName("line2") self.vboxlayout2.addWidget(self.line2) self.name_linedit = QtGui.QLineEdit(self.name_grpbox) self.name_linedit.setObjectName("name_linedit") self.vboxlayout2.addWidget(self.name_linedit) self.vboxlayout1.addWidget(self.name_grpbox) self.output_image_grpbox = QtGui.QGroupBox(self.body_frame) self.output_image_grpbox.setCheckable(False) self.output_image_grpbox.setChecked(False) self.output_image_grpbox.setObjectName("output_image_grpbox") self.vboxlayout3 = QtGui.QVBoxLayout(self.output_image_grpbox) self.vboxlayout3.setMargin(4) self.vboxlayout3.setSpacing(1) self.vboxlayout3.setObjectName("vboxlayout3") self.hboxlayout3 = QtGui.QHBoxLayout() self.hboxlayout3.setMargin(0) self.hboxlayout3.setSpacing(6) self.hboxlayout3.setObjectName("hboxlayout3") self.image_size_grpbox_label = QtGui.QLabel(self.output_image_grpbox) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(1)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.image_size_grpbox_label.sizePolicy().hasHeightForWidth()) self.image_size_grpbox_label.setSizePolicy(sizePolicy) self.image_size_grpbox_label.setAlignment(QtCore.Qt.AlignVCenter) self.image_size_grpbox_label.setObjectName("image_size_grpbox_label") self.hboxlayout3.addWidget(self.image_size_grpbox_label) spacerItem3 = QtGui.QSpacerItem(40,16,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout3.addItem(spacerItem3) self.grpbtn_2 = QtGui.QPushButton(self.output_image_grpbox) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(0),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.grpbtn_2.sizePolicy().hasHeightForWidth()) self.grpbtn_2.setSizePolicy(sizePolicy) self.grpbtn_2.setMaximumSize(QtCore.QSize(16,16)) self.grpbtn_2.setIcon( geticon("ui/actions/Properties Manager/Group_Button.png")) self.grpbtn_2.setAutoDefault(False) self.grpbtn_2.setFlat(True) self.grpbtn_2.setObjectName("grpbtn_2") self.hboxlayout3.addWidget(self.grpbtn_2) self.vboxlayout3.addLayout(self.hboxlayout3) self.line3 = QtGui.QFrame(self.output_image_grpbox) self.line3.setFrameShape(QtGui.QFrame.HLine) self.line3.setFrameShadow(QtGui.QFrame.Sunken) self.line3.setMidLineWidth(0) self.line3.setFrameShape(QtGui.QFrame.HLine) self.line3.setFrameShadow(QtGui.QFrame.Sunken) self.line3.setObjectName("line3") self.vboxlayout3.addWidget(self.line3) self.hboxlayout4 = QtGui.QHBoxLayout() self.hboxlayout4.setMargin(0) self.hboxlayout4.setSpacing(6) self.hboxlayout4.setObjectName("hboxlayout4") self.vboxlayout4 = QtGui.QVBoxLayout() self.vboxlayout4.setMargin(0) self.vboxlayout4.setSpacing(6) self.vboxlayout4.setObjectName("vboxlayout4") self.output_type_label = QtGui.QLabel(self.output_image_grpbox) self.output_type_label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.output_type_label.setObjectName("output_type_label") self.vboxlayout4.addWidget(self.output_type_label) self.width_label = QtGui.QLabel(self.output_image_grpbox) self.width_label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.width_label.setObjectName("width_label") self.vboxlayout4.addWidget(self.width_label) self.height_label = QtGui.QLabel(self.output_image_grpbox) self.height_label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.height_label.setObjectName("height_label") self.vboxlayout4.addWidget(self.height_label) self.aspect_ratio_label = QtGui.QLabel(self.output_image_grpbox) self.aspect_ratio_label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.aspect_ratio_label.setObjectName("aspect_ratio_label") self.vboxlayout4.addWidget(self.aspect_ratio_label) self.hboxlayout4.addLayout(self.vboxlayout4) self.vboxlayout5 = QtGui.QVBoxLayout() self.vboxlayout5.setMargin(0) self.vboxlayout5.setSpacing(6) self.vboxlayout5.setObjectName("vboxlayout5") self.output_type_combox = QtGui.QComboBox(self.output_image_grpbox) self.output_type_combox.setObjectName("output_type_combox") self.vboxlayout5.addWidget(self.output_type_combox) self.width_spinbox = QtGui.QSpinBox(self.output_image_grpbox) self.width_spinbox.setMaximum(5000) self.width_spinbox.setMinimum(20) self.width_spinbox.setProperty("value",QtCore.QVariant(1024)) self.width_spinbox.setObjectName("width_spinbox") self.vboxlayout5.addWidget(self.width_spinbox) self.height_spinbox = QtGui.QSpinBox(self.output_image_grpbox) self.height_spinbox.setMaximum(5000) self.height_spinbox.setMinimum(20) self.height_spinbox.setProperty("value",QtCore.QVariant(768)) self.height_spinbox.setObjectName("height_spinbox") self.vboxlayout5.addWidget(self.height_spinbox) self.aspect_ratio_value_label = QtGui.QLabel(self.output_image_grpbox) self.aspect_ratio_value_label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.aspect_ratio_value_label.setObjectName("aspect_ratio_value_label") self.vboxlayout5.addWidget(self.aspect_ratio_value_label) self.hboxlayout4.addLayout(self.vboxlayout5) self.vboxlayout3.addLayout(self.hboxlayout4) self.vboxlayout1.addWidget(self.output_image_grpbox) self.vboxlayout.addWidget(self.body_frame) spacerItem4 = QtGui.QSpacerItem(20,16,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Expanding) self.vboxlayout.addItem(spacerItem4) self.hboxlayout5 = QtGui.QHBoxLayout() self.hboxlayout5.setMargin(4) self.hboxlayout5.setSpacing(6) self.hboxlayout5.setObjectName("hboxlayout5") spacerItem5 = QtGui.QSpacerItem(59,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout5.addItem(spacerItem5) self.cancel_btn = QtGui.QPushButton(PovrayScenePropDialog) self.cancel_btn.setAutoDefault(False) self.cancel_btn.setObjectName("cancel_btn") self.hboxlayout5.addWidget(self.cancel_btn) self.ok_btn = QtGui.QPushButton(PovrayScenePropDialog) self.ok_btn.setAutoDefault(False) self.ok_btn.setObjectName("ok_btn") self.hboxlayout5.addWidget(self.ok_btn) self.vboxlayout.addLayout(self.hboxlayout5) self.retranslateUi(PovrayScenePropDialog) QtCore.QMetaObject.connectSlotsByName(PovrayScenePropDialog) def retranslateUi(self, PovrayScenePropDialog): PovrayScenePropDialog.setWindowTitle(QtGui.QApplication.translate("PovrayScenePropDialog", "POV-Ray Scene", None, QtGui.QApplication.UnicodeUTF8)) PovrayScenePropDialog.setWindowIcon(QtGui.QIcon("ui/border/PovrayScene")) self.heading_label.setText(QtGui.QApplication.translate("PovrayScenePropDialog", "POV-Ray Scene", None, QtGui.QApplication.UnicodeUTF8)) self.done_btn.setToolTip(QtGui.QApplication.translate("PovrayScenePropDialog", "OK", None, QtGui.QApplication.UnicodeUTF8)) self.abort_btn.setToolTip(QtGui.QApplication.translate("PovrayScenePropDialog", "Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.restore_btn.setToolTip(QtGui.QApplication.translate("PovrayScenePropDialog", "Restore Defaults", None, QtGui.QApplication.UnicodeUTF8)) self.preview_btn.setToolTip(QtGui.QApplication.translate("PovrayScenePropDialog", "Preview", None, QtGui.QApplication.UnicodeUTF8)) self.whatsthis_btn.setToolTip(QtGui.QApplication.translate("PovrayScenePropDialog", "What\'s This Help", None, QtGui.QApplication.UnicodeUTF8)) self.name_grpbox_label.setText(QtGui.QApplication.translate("PovrayScenePropDialog", "POV-Ray Scene Name", None, QtGui.QApplication.UnicodeUTF8)) self.name_linedit.setToolTip(QtGui.QApplication.translate("PovrayScenePropDialog", "Name of POV-Ray Scene node in Model Tree", None, QtGui.QApplication.UnicodeUTF8)) self.name_linedit.setText(QtGui.QApplication.translate("PovrayScenePropDialog", "POV-Ray Scene-1.pov", None, QtGui.QApplication.UnicodeUTF8)) self.image_size_grpbox_label.setText(QtGui.QApplication.translate("PovrayScenePropDialog", "Render Image Parameters", None, QtGui.QApplication.UnicodeUTF8)) self.output_type_label.setText(QtGui.QApplication.translate("PovrayScenePropDialog", "Output Type :", None, QtGui.QApplication.UnicodeUTF8)) self.width_label.setText(QtGui.QApplication.translate("PovrayScenePropDialog", "Width :", None, QtGui.QApplication.UnicodeUTF8)) self.height_label.setText(QtGui.QApplication.translate("PovrayScenePropDialog", "Height :", None, QtGui.QApplication.UnicodeUTF8)) self.aspect_ratio_label.setText(QtGui.QApplication.translate("PovrayScenePropDialog", "Aspect Ratio :", None, QtGui.QApplication.UnicodeUTF8)) self.output_type_combox.setToolTip(QtGui.QApplication.translate("PovrayScenePropDialog", "Output image format", None, QtGui.QApplication.UnicodeUTF8)) self.output_type_combox.addItem(QtGui.QApplication.translate("PovrayScenePropDialog", "PNG", None, QtGui.QApplication.UnicodeUTF8)) self.output_type_combox.addItem(QtGui.QApplication.translate("PovrayScenePropDialog", "BMP", None, QtGui.QApplication.UnicodeUTF8)) self.width_spinbox.setToolTip(QtGui.QApplication.translate("PovrayScenePropDialog", "Width of output image", None, QtGui.QApplication.UnicodeUTF8)) self.width_spinbox.setSuffix(QtGui.QApplication.translate("PovrayScenePropDialog", " pixels", None, QtGui.QApplication.UnicodeUTF8)) self.height_spinbox.setToolTip(QtGui.QApplication.translate("PovrayScenePropDialog", "Height of output image", None, QtGui.QApplication.UnicodeUTF8)) self.height_spinbox.setSuffix(QtGui.QApplication.translate("PovrayScenePropDialog", " pixels", None, QtGui.QApplication.UnicodeUTF8)) self.aspect_ratio_value_label.setText(QtGui.QApplication.translate("PovrayScenePropDialog", "1.333 to 1", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setToolTip(QtGui.QApplication.translate("PovrayScenePropDialog", "Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setText(QtGui.QApplication.translate("PovrayScenePropDialog", "Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.ok_btn.setToolTip(QtGui.QApplication.translate("PovrayScenePropDialog", "OK", None, QtGui.QApplication.UnicodeUTF8)) self.ok_btn.setText(QtGui.QApplication.translate("PovrayScenePropDialog", "OK", None, QtGui.QApplication.UnicodeUTF8))
NanoCAD-master
cad/src/commands/PovraySceneProperties/PovrayScenePropDialog.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ PovraySceneProp.py - the PovraySceneProp class, including all methods needed by the POV-Ray Scene dialog. @author: Mark @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: mark 060602 - Created for NFR: "Insert > POV-Ray Scene". """ from PyQt4.Qt import SIGNAL, QDialog, QWhatsThis, QDialog from commands.PovraySceneProperties.PovrayScenePropDialog import Ui_PovrayScenePropDialog import foundation.env as env, os from utilities.Log import redmsg, greenmsg from PM.GroupButtonMixin import GroupButtonMixin from sponsors.Sponsors import SponsorableMixin from utilities.Comparison import same_vals class PovraySceneProp(QDialog, SponsorableMixin, GroupButtonMixin, Ui_PovrayScenePropDialog): cmdname = greenmsg("Insert POV-Ray Scene: ") prefix = 'POVRayScene' extension = ".pov" def __init__(self, win): QDialog.__init__(self, win) # win is parent. self.setupUi(self) self.connect(self.cancel_btn,SIGNAL("clicked()"),self.cancel_btn_clicked) self.connect(self.done_btn,SIGNAL("clicked()"),self.ok_btn_clicked) self.connect(self.height_spinbox,SIGNAL("valueChanged(int)"),self.change_height) self.connect(self.ok_btn,SIGNAL("clicked()"),self.ok_btn_clicked) self.connect(self.preview_btn,SIGNAL("clicked()"),self.preview_btn_clicked) self.connect(self.restore_btn,SIGNAL("clicked()"),self.restore_defaults_btn_clicked) self.connect(self.sponsor_btn,SIGNAL("clicked()"),self.open_sponsor_homepage) self.connect(self.whatsthis_btn,SIGNAL("clicked()"),self.whatsthis_btn_clicked) self.connect(self.width_spinbox,SIGNAL("valueChanged(int)"),self.change_width) self.connect(self.abort_btn,SIGNAL("clicked()"),self.cancel_btn_clicked) self.connect(self.grpbtn_1,SIGNAL("clicked()"),self.toggle_grpbtn_1) self.connect(self.grpbtn_2,SIGNAL("clicked()"),self.toggle_grpbtn_2) self.win = win self.glpane = self.win.glpane self.node = None self.previousParams = None self.sponsor_btn.setWhatsThis("""<b>NanoEngineer-1 Sponsor</b> <p>Click on the logo to learn more about this NanoEngineer-1 sponsor.</p>""") self.name_linedit.setWhatsThis("""<b>Node Name</b> <p>The POV-Ray Scene file node name as it appears in the Model Tree.</p>""") self.output_type_combox.setWhatsThis("""<b>Image Format </b>- the output image format when rendering an image from this POV-Ray Scene file.""") def setup(self, pov=None): """ Show the Properties Manager dialog. If <pov> is supplied, get the parameters from it and load the dialog widgets. """ if not self.win.assy.filename: env.history.message( self.cmdname + redmsg("Can't insert POV-Ray Scene until the current part has been saved.") ) return if not pov: self.node_is_new = True from model.PovrayScene import PovrayScene self.node = PovrayScene(self.win.assy, None) else: self.node_is_new = False self.node = pov self.name = self.originalName = self.node.name ini, self.originalPov, out = self.node.get_povfile_trio() self.width, self.height, self.output_type = self.node.get_parameters() self.update_widgets() self.previousParams = params = self.gather_parameters() self.show() def gather_parameters(self): """ Returns a tuple with the current parameter values from the widgets. """ self.node.try_rename(self.name_linedit.text()) # Next three lines fix bug 2026. Mark 060702. self.name_linedit.setText(self.node.name) # In case the name was illegal and "Preview" was pressed. name = self.node.name width = self.width_spinbox.value() height = self.height_spinbox.value() output_type = str(self.output_type_combox.currentText()).lower() return (name, width, height, output_type) def update_widgets(self): """ Update the widgets using the current attr values. """ self.name_linedit.setText(self.name) self.output_type_combox.setItemText(self.output_type_combox.currentIndex(), self.output_type.upper()) # This must be called before setting the values of the width and height spinboxes. Mark 060621. self.aspect_ratio = float(self.width) / float(self.height) aspect_ratio_str = "%.3f to 1" % self.aspect_ratio self.aspect_ratio_value_label.setText(aspect_ratio_str) self.width_spinbox.setValue(self.width) # Generates signal. self.height_spinbox.setValue(self.height) # Generates signal. def update_node(self, ok_pressed=False): """ Update the POV-Ray Scene node. """ self.set_params( self.node, self.gather_parameters()) ini, pov, out = self.node.get_povfile_trio() # If the node was renamed, rename the POV-Ray Scene file name, too. # Don't do this if the "Preview" button was pressed since the user could later # hit "Cancel". In that case we'd loose the original .pov file, which would not be good. # Mark 060702. if ok_pressed and self.originalName != self.node.name: if os.path.isfile(self.originalPov): if os.path.isfile(pov): # Normally, I'd never allow the user to delete an existing POV-Ray Scene file without asking. # For A8 I'll allow it since I've run out of time. # This will be fixed when Bruce implements the new File class in A9 (or later). Mark 060702. os.remove(pov) os.rename(self.originalPov, pov) # Write the POV-Ray Scene (.pov) file if this is a new node or if the node's ".pov" file doesn't exist. # Possible ways the ".pov" file could be missing from an existing node: # 1. the user renamed the node in the Model Tree, or # 2. the POV-Ray Scene node was deleted, which deletes the file in self.kill(), and then Undo was pressed, or # 3. the ".pov" file was deleted by the user another way (via OS). # In the future, the POV-Ray Scene should save the view quat in the MMP (info) record. Then it # would always be possible to regenerate the POV-Ray Scene file from the MMP record, even if # the node's .pov file didn't exist on disk anymore. Mark 060701. if self.node_is_new or not os.path.exists(pov): errorcode, filename_or_errortext = self.node.write_povrayscene_file() if errorcode: # The Pov-Ray Scene file could not be written, so remove the node. self.remove_node() env.history.message( self.cmdname + redmsg(filename_or_errortext) ) return def set_params(self, node, params): #bruce 060620, since pov params don't include name, but our params do # <node> should be a PovrayScene node name = params[0] pov_params = params[1:] node.name = name # this ought to be checked for being a legal name; maybe we should use try_rename ###e node.set_parameters(pov_params) # Warning: code in this class assumes a specific order and set of params must be used here # (e.g. in gather_parameters), so it might be clearer if set_parameters was just spelled out here # as three assignments to attrs of struct. On the other hand, these three parameters (in that order) # are also known to the node itself, for use in its mmp record format. Probably that's irrelevant # and we should still make this change during the next cleanup of these files. ###@@@ [bruce 060620 comment] return def remove_node(self): """ Delete this POV-Ray Scene node. """ if self.node != None: #&&& self.node.kill(require_confirmation = False) # This version prompts the user to confirm deleting the node if its file exists (usually). self.node.kill() # Assume the user wants to delete the node's POV-Ray Scene file. self.node = None self.win.mt.mt_update() # Property manager standard button slots. def ok_btn_clicked(self): """ Slot for the OK button """ self.win.assy.current_command_info(cmdname = self.cmdname) self.update_node(ok_pressed = True) if self.node_is_new: self.win.assy.addnode(self.node) self.node.update_icon() # In case we rewrote a lost POV-Ray Scene file in update_node(). self.win.mt.mt_update() # Update model tree regardless whether it is a new node or not, # since the user may have changed the name of an existing POV-Ray Scene node. env.history.message(self.cmdname + self.done_msg()) self.node = None QDialog.accept(self) def done_msg(self): """ Returns the message to print after the OK button has been pressed. """ if self.node_is_new: return "%s created." % self.name else: if not same_vals( self.previousParams, self.gather_parameters()): return "%s updated." % self.name else: return "%s unchanged." % self.name def cancel_btn_clicked(self): """ Slot for Cancel button. """ self.win.assy.current_command_info(cmdname = self.cmdname + " (Cancel)") if self.node_is_new: self.remove_node() else: self.set_params(self.node, self.previousParams) QDialog.accept(self) def restore_defaults_btn_clicked(self): """ Slot for Restore Defaults button. """ self.name, self.width, self.height, self.output_type = self.previousParams self.update_widgets() def preview_btn_clicked(self): """ Slot for Preview button. """ self.update_node() self.node.raytrace_scene() #&&& Should we print history message in this method or return the errorcode and text so the caller #&&& can decide what to do? I think it would be better to display the history msg in raytrace_scene. Mark 060701. #&&&errorcode, errortext = self.node.raytrace_scene() #&&&if errorcode: #&&& env.history.message( self.cmdname + redmsg(errortext) ) #&&&else: #&&& env.history.message( self.cmdname + errortext ) # "Rendering finished" message. def whatsthis_btn_clicked(self): """ Slot for the What's This button """ QWhatsThis.enterWhatsThisMode() # Property manager widget slots. def change_width(self, width): """ Slot for Width spinbox """ self.width = width self.update_height() def update_height(self): """ Updates height when width changes """ self.height = int (self.width / self.aspect_ratio) self.disconnect(self.height_spinbox,SIGNAL("valueChanged(int)"),self.change_height) self.height_spinbox.setValue(self.height) self.connect(self.height_spinbox,SIGNAL("valueChanged(int)"),self.change_height) def change_height(self, height): """ Slot for Height spinbox """ self.height = height self.update_width() def update_width(self): """ Updates width when height changes """ self.width = int (self.height * self.aspect_ratio) self.disconnect(self.width_spinbox,SIGNAL("valueChanged(int)"),self.change_width) self.width_spinbox.setValue(self.width) self.connect(self.width_spinbox,SIGNAL("valueChanged(int)"),self.change_width) # Property Manager groupbox button slots def toggle_grpbtn_1(self): """ Slot for first groupbox toggle button """ self.toggle_groupbox_in_dialogs(self.grpbtn_1, self.line2, self.name_linedit) def toggle_grpbtn_2(self): """ Slot for second groupbox toggle button """ self.toggle_groupbox_in_dialogs(self.grpbtn_2, self.line3, self.output_type_label, self.output_type_combox, self.width_label, self.width_spinbox, self.height_label, self.height_spinbox, self.aspect_ratio_label, self.aspect_ratio_value_label)
NanoCAD-master
cad/src/commands/PovraySceneProperties/PovraySceneProp.py
NanoCAD-master
cad/src/commands/Fuse/__init__.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ FuseChunks_GraphicsMode.py @author: Mark @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Originally by Mark as class 'fuseChunksMode'. Ninad 2008-01-25: Split Command and GraphicsMode classes out of class fuseChunksMode. The command class can be found in FuseChunks_Command.py """ from utilities.constants import green from utilities.constants import magenta from utilities.constants import blue from utilities.constants import darkred from graphics.drawing.CS_draw_primitives import drawline from graphics.behaviors.shape import get_selCurve_color from commands.Move.Move_GraphicsMode import Move_GraphicsMode from commands.Translate.TranslateChunks_GraphicsMode import TranslateChunks_GraphicsMode from commands.Rotate.RotateChunks_GraphicsMode import RotateChunks_GraphicsMode class _FuseChunks_GraphicsMode_preMixin: ### REVIEW: this should probably inherit from Move_GraphicsMode, # since it often calls its methods as if they were superclass methods. # (But its use as a mixin class may prevent this or make it difficult, # I don't know.) [bruce comment 080722/090310] """ The pre- Mixin class for various graphics modes that will be used for the FuseChunks_Command. This should strictly be a pre-Mixin class. The intention is to override some methods of Move_GraphicsMode, such as Draw_*, and use them in the graphics modes of FuseChunks_Command. The Move_GraphicsMode also has two subclasses TranslateChunks_GraphicsMode and RotateChunks_GraphicsMode. Even in FuseChunks mode (command), we need to use these two modes , at the same time we also need to override the Draw methods etc so that the 3D workspace shows things like fusable atoms and bonds. To achieve this, we have made this special Mixin class to define Draw methods etc. Then, the class FuseChunks_GraphicsMode inherits this first and then the Move_GraphicsMode (so that, for example self.Draw_other in that class actually uses the method defined in this mixin class instead of Move_GraphicsMode.Draw_other). We are doing similar thing in classes such as Translate_in_FuseChunks_GraphicsMode, where it uses Draw-related methods from this class and special drag-related methods from TranslateChunks_GraphicsMode @see: B{TranslateChunks_GraphicsMode} @see: B{Translate_in_FuseChunks_GraphicsMode} @see: B{RotateChunks_GraphicsMode} @see: B{Rotate_in_FuseChunks_GraphicsMode} @see: Move_GraphicsMode @see: FuseChunks_Command """ _recompute_fusables = True # _recompute_fusables is used to optimize redraws by skipping the # recomputing of fusables (bondable pairs or overlapping atoms). # When set to False, Draw() will not recompute fusables # before repainting the GLPane. When False, _recompute_fusables is # reset to True in Draw(), so it is the responsibility of whatever # triggers the next call of paintGL (which calls Draw()) (e.g. one # of our mouse event handlers which calls gl_update) to reset it # to False before each redraw if desired. For more info, see comments # in Draw(). [by Mark; comment clarified/corrected by bruce 090310] ### WARNING: this scheme can't work correctly in general. # See comments elsewhere. [bruce 090310] something_was_picked = False # 'something_was_picked' is a special boolean flag needed by Draw() # to determine when the state has changed from something selected # to nothing selected. It is used to properly update the tolerance # label in the Property Manager when all chunks are unselected. # It is set both here and in the associated command class. [by Mark?] ### NOTE ABOUT INCORRECT CODE # [bruce 090310-11 update and review comment]: # # The side effect of something_was_picked on the PM was done in # self.Draw, as was the recomputation related to _recompute_fusables. # # This is completely wrong -- these things belong in the Command, # not here in the GraphicsMode; the Command API has specific update # methods for those purposes, which these effects belong inside. # Doing them in the Draw methods will sometimes result in doing them # too often (causing a slowdown; see other comments about # _recompute_fusables), and other times not often enough (especially # now that we're optimizing graphics, in part by not always calling # the Draw methods unless certain things have changed). # # Today I am splitting Draw into submethods, some of which need not # be called every frame. For now, I put the questionable side effects # into Draw_preparation, which will always be called. This is most # correct given the present code, without refactoring it into the # command (for which I don't have time). In fact, it makes this more # correct than it was before, since it's called exactly once per # paintGL call (but the refactoring mentioned should still be done). def Enter_GraphicsMode(self): Move_GraphicsMode.Enter_GraphicsMode(self) self._recompute_fusables = True return def Draw_preparation(self): """ """ if self.o.is_animating or self.o.button == 'MMB': # Don't need to recompute fusables if we are animating between views # or zooming, panning or rotating with the MMB. self._recompute_fusables = False # _recompute_fusables is set to False when the bondable pairs or # overlapping atoms don't need to be recomputed. # Scenerios when _recompute_fusables is set to False: # 1. animating between views. Done above, boolean attr # 'self.o.is_animating' is checked. # 2. zooming, panning and rotating with MMB. Done above, # check if self.o.button == 'MMB' # 3. Zooming with mouse wheel, done in self.Wheel(). # If _recompute_fusables is False here, it is immediately reset to # True below. mark 060405 if self._recompute_fusables: # This is important and needed in case there is nothing selected. # I mention this because it looks redundant since is the first thing # done in find_bondable_pairs(). self.command.bondable_pairs = [] self.command.ways_of_bonding = {} self.command.overlapping_atoms = [] if self.o.assy.selmols: # Recompute fusables. This can be very expensive, especially # with large parts. self.command.find_fusables() if not self.something_was_picked: self.something_was_picked = True else: # Nothing is selected, so there can be no fusables. # Check if we need to update the slider tolerance label. # This fixed bug 502-14. Mark 050407 if self.something_was_picked: self.command.reset_tolerance_label() self.something_was_picked = False # Reset flag else: self._recompute_fusables = True Move_GraphicsMode.Draw_preparation(self) return def Draw_other(self): """ Draw bondable pairs or overlapping atoms. """ Move_GraphicsMode.Draw_other(self) if self.command.bondable_pairs: self.draw_bondable_pairs() elif self.command.overlapping_atoms: self.draw_overlapping_atoms() return def draw_bondable_pairs(self): """ Draws bondable pairs of singlets and the bond lines between them. Singlets in the selected chunk(s) are colored green. Singlets in the unselected chunk(s) are colored blue. Singlets with more than one way to bond are colored magenta. """ # Color of bond lines bondline_color = get_selCurve_color(0,self.o.backgroundColor) for s1,s2 in self.command.bondable_pairs: color = (self.command.ways_of_bonding[s1.key] > 1) and magenta or green s1.overdraw_with_special_color(color) color = (self.command.ways_of_bonding[s2.key] > 1) and magenta or blue s2.overdraw_with_special_color(color) # Draw bond lines between singlets drawline(bondline_color, s1.posn(), s2.posn()) return def draw_overlapping_atoms(self): """ Draws overlapping atoms. Atoms in the selected chunk(s) are colored green. Atoms in the unselected chunk(s) that will be deleted are colored darkred. """ for a1,a2 in self.command.overlapping_atoms: # a1 atoms are the selected chunk atoms a1.overdraw_with_special_color(green) # NFR/bug 945. Mark 051029. # a2 atoms are the unselected chunk(s) atoms a2.overdraw_with_special_color(darkred) return def leftDouble(self, event): # This keeps us from leaving Fuse Chunks mode, # as is the case in Move Chunks mode. return def Wheel(self, event): """ Mouse wheel event handler. [overrides Move_GraphicsMode.Wheel()] """ Move_GraphicsMode.Wheel(self, event) self._recompute_fusables = False # Setting this flag is intended to optimize redraws by # preventing the next Draw() from recomputing fusables # while zooming in/out. [Mark] ### WARNING: this scheme may not work correctly, since # Draw must be called multiple times per paintGL call # to implement mouseover highlighting. [Bruce 090310 comment] return pass # end of class _FuseChunks_GraphicsMode_preMixin # == class FuseChunks_GraphicsMode( _FuseChunks_GraphicsMode_preMixin, Move_GraphicsMode): """ The default Graphics mode for the FuseChunks_Command @see: _FuseChunks_GraphicsMode_preMixin for comments on multiple inheritance @see: B{FuseChunks_Command} where it is used as a default graphics mode class @see: B{FuseChunks_Command._createGraphicsMode} """ pass class Translate_in_FuseChunks_GraphicsMode( _FuseChunks_GraphicsMode_preMixin, TranslateChunks_GraphicsMode): """ When the translate groupbox of the FuseChunks Command property manager is active, the graphics mode for the command will be Translate_in_FuseChunks_GraphicsMode. @see: _FuseChunks_GraphicsMode_preMixin for comments on multiple inheritance @see: B{FuseChunks_Command._createGraphicsMode} """ pass class Rotate_in_FuseChunks_GraphicsMode( _FuseChunks_GraphicsMode_preMixin, RotateChunks_GraphicsMode): """ When the translate groupbox of the FuseChunks Command property manager is active, the graphics mode for the command will be Rotate_in_FuseChunks_GraphicsMode. @see: _FuseChunks_GraphicsMode_preMixin for comments on multiple inheritance @see: B{FuseChunks_Command._createGraphicsMode} """ pass # end
NanoCAD-master
cad/src/commands/Fuse/FuseChunks_GraphicsMode.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ FuseChunks_Command.py @author: Mark @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Originally by Mark as class 'fuseChunksMode'. Ninad 2008-01-25: Split Command and GraphicsMode classes out of class fuseChunksMode. The graphicsMode class can be found in FuseChunks_GraphicsMode.py TODO as of 2008-09-09: -refactor update ui related code. Example some methods call propMgr.updateMessage() etc. this needs to be in a central place... either in this calls or in PM._update_UI_do_updates() """ import foundation.env as env from geometry.VQT import vlen from model.elements import Singlet from platform_dependent.PlatformDependent import fix_plurals from commands.Fuse.FusePropertyManager import FusePropertyManager from utilities.constants import diINVISIBLE from commands.Move.Move_Command import Move_Command from commands.Fuse.fusechunksMode import fusechunksBase from commands.Fuse.fusechunksMode import fusechunks_lambda_tol_natoms, fusechunks_lambda_tol_nbonds #@ Warning: MAKEBONDS and FUSEATOMS must be the same exact strings used in the # PM combo box "fuseComboBox" widget in FusePropertyManager. # This implementation is fragile and should be fixed. Mark 2008-07-16 MAKEBONDS = 'Make bonds between chunks' FUSEATOMS = 'Fuse overlapping atoms' from commands.Fuse.FuseChunks_GraphicsMode import FuseChunks_GraphicsMode from commands.Fuse.FuseChunks_GraphicsMode import Translate_in_FuseChunks_GraphicsMode from commands.Fuse.FuseChunks_GraphicsMode import Rotate_in_FuseChunks_GraphicsMode from command_support.GraphicsMode_API import GraphicsMode_interface from ne1_ui.toolbars.Ui_FuseFlyout import FuseFlyout class FuseChunks_Command(Move_Command, fusechunksBase): """ Allows user to move chunks and fuse them to other chunks in the part. Two fuse methods are supported: 1. Make Bonds - bondpoints between chunks will form bonds when they are near each other. 2. Fuse Atoms - atoms between chunks will be fused when they overlap each other. """ # class constants PM_class = FusePropertyManager GraphicsMode_class = FuseChunks_GraphicsMode FlyoutToolbar_class = FuseFlyout commandName = 'FUSECHUNKS' featurename = "Fuse Chunks Mode" from utilities.constants import CL_ENVIRONMENT_PROVIDING command_level = CL_ENVIRONMENT_PROVIDING ### REVIEW: are the folowing all default values of instance variables? # Note that they are all dangerously mutable -- if they can correctly # be changed to None or (), that would be better. [bruce 080725 comment] bondable_pairs = [] # List of bondable singlets ways_of_bonding = {} # Number of bonds each singlet found bondable_pairs_atoms = [] # List of atom pairs that can be bonded overlapping_atoms = [] # List of overlapping atoms tol = 1.0 # in Angstroms # For "Make Bonds", tol is the distance between two bondable singlets # For "Fuse Atoms", tol is the distance between two atoms to be # considered overlapping fuse_mode = '' # The Fuse mode, either 'Make Bonds' or 'Fuse Atoms'. def _create_GraphicsMode(self): GM_class = self.GraphicsMode_class assert issubclass(GM_class, GraphicsMode_interface) args = [self] kws = {} self.graphicsMode = GM_class(*args, **kws) self.translate_graphicsMode = Translate_in_FuseChunks_GraphicsMode(*args, **kws) self.rotate_graphicsMode = Rotate_in_FuseChunks_GraphicsMode(*args, **kws) def command_entered(self): """ Extends superclass method. @see: baseCommand.command_entered() for documentation. """ super(FuseChunks_Command, self).command_entered() self.change_fuse_mode(str(self.propMgr.fuseComboBox.currentText())) # This maintains state of fuse mode when leaving/reentering mode, # and syncs the PM and glpane (and does a gl_update). if self.o.assy.selmols: self.graphicsMode.something_was_picked = True def command_enter_misc_actions(self): self.w.toolsFuseChunksAction.setChecked(1) def command_exit_misc_actions(self): self.w.toolsFuseChunksAction.setChecked(0) ## def Backup(self): # REVIEW: I suspect there is no way to call this method, so I commented it out. [bruce 080806 comment] ## """ ## Undo any bonds made between chunks. ## """ ## # This undoes only the last fused chunks. Will work on supporting ## # multiple undos when we get a single undo working. Mark 050326 ## ## # Bust bonds between last pair/set of fused chunks. ## if self.bondable_pairs_atoms: ## for a1, a2 in self.bondable_pairs_atoms: ## b = a1.get_neighbor_bond(a2) ## if b: b.bust() ## ## ## if self.merged_chunks: ## nchunks_str = "%d" % (len(self.merged_chunks) + 1,) ## msg = "Fuse Chunks: Bonds broken between %s chunks." % (nchunks_str) ## env.history.message(msg) ## msg = "Warning: Cannot separate the original chunks. You can " \ ## "do this yourself using <b>Modify > Separate</b>." ## env.history.message(orangemsg(msg)) ## ## cnames = "Their names were: " ## # Here are the original names... ## for chunk in self.merged_chunks: ## cnames += '[' + chunk.name + '] ' ## env.history.message(cnames) ## ## self.o.gl_update() ## ## else: ## msg = "Fuse Chunks: No bonds have been made yet. Undo ignored." ## env.history.message(redmsg(msg)) def tolerance_changed(self, val): """ Slot for tolerance slider. """ self.tol = val * .01 if self.o.assy.selmols: self.o.gl_update() else: # Since no chunks are selected, there are no bonds, but the slider # tolerance label still needs # updating. This fixed bug 502-14. Mark 050407 self.reset_tolerance_label() def reset_tolerance_label(self): """ Reset the tolerance label to 0 bonds or 0 overlapping atoms """ if self.fuse_mode == MAKEBONDS: tol_str = fusechunks_lambda_tol_nbonds(self.tol, 0, 0, 0) # 0 bonds else: # 0 overlapping atoms tol_str = fusechunks_lambda_tol_natoms(self.tol, 0) tolerenceLabel = tol_str self.propMgr.toleranceSlider.labelWidget.setText(tolerenceLabel) def change_fuse_mode(self, fuse_mode): """ Sets the Fuse mode """ if self.fuse_mode == fuse_mode: return # The mode did not change. Don't do anything. self.fuse_mode = str(fuse_mode) # Must cast here. if self.fuse_mode == MAKEBONDS: self.propMgr.fusePushButton.setText('Make Bonds') else: self.propMgr.fusePushButton.setText('Fuse Atoms') self.propMgr.updateMessage() self.o.gl_update() # the Draw() method will update based on the current # combo box item. def find_fusables(self): """ Finds bondable pairs or overlapping atoms, based on the Fuse Action combo box """ if self.fuse_mode == MAKEBONDS: self.find_bondable_pairs() else: self.find_overlapping_atoms() def find_bondable_pairs(self, chunk_list = None): """ Checks the bondpoints of the selected chunk to see if they are close enough to bond with any other bondpoints in a list of chunks. Hidden chunks are skipped. """ tol_str = fusechunksBase.find_bondable_pairs(self, chunk_list, None) tolerenceLabel = tol_str self.propMgr.toleranceSlider.labelWidget.setText(tolerenceLabel) def fuse_something(self): """ Slot for 'Make Bonds/Fuse Atoms' button. """ if self.fuse_mode == MAKEBONDS: self.make_bonds() else: self.fuse_atoms() def make_bonds(self): """ Make bonds between all bondable pairs of singlets """ self._make_bonds_1() self._make_bonds_2() self._make_bonds_3() self._make_bonds_4() def _make_bonds_2(self): # Merge the chunks if the "merge chunks" checkbox is checked if self.propMgr.mergeChunksCheckBox.isChecked() and self.bondable_pairs_atoms: for a1, a2 in self.bondable_pairs_atoms: # Ignore a1, they are atoms from the selected chunk(s) # It is possible that a2 is an atom from a selected chunk, # so check it if a2.molecule != a1.molecule: if a2.molecule not in self.merged_chunks: self.merged_chunks.append(a2.molecule) a1.molecule.merge(a2.molecule) def _make_bonds_4(self): msg = fix_plurals( "%d bond(s) made" % self.total_bonds_made) env.history.message(msg) # Update the slider tolerance label. This fixed bug 502-14. Mark 050407 self.reset_tolerance_label() if self.bondable_pairs_atoms: # This must be done before gl_update, or it will try to draw the # bondable singlets again, which generates errors. self.bondable_pairs = [] self.ways_of_bonding = {} self.w.win_update() ######### Overlapping Atoms methods ############# def find_overlapping_atoms(self, skip_hidden = True, ignore_chunk_picked_state = False): """ Checks atoms of the selected chunk to see if they overlap atoms in other chunks of the same type (element). Hidden chunks are skipped. """ # Future versions should allow more flexible rules for overlapping # atoms, but this needs to be discussed with others before implementing # anything. # For now, only atoms of the same type qualify as overlapping atoms. # As is, it is extremely useful for fusing chunks of diamond, # lonsdaleite or SiC, # which is done quite a lot with casings. This will save me hours of # modeling work. # Mark 050902 self.overlapping_atoms = [] for chunk in self.o.assy.selmols: if chunk.hidden or chunk.display == diINVISIBLE: # Skip selected chunk if hidden or invisible. # Fixes bug 970. mark 060404 continue # Loop through all the mols in the part to search for bondable # pairs of singlets. for mol in self.o.assy.molecules: if chunk is mol: continue # Skip itself if mol.hidden or mol.display == diINVISIBLE: continue # Skip hidden or invisible chunks if mol in self.o.assy.selmols: continue # Skip other selected chunks # Skip this mol if its bounding box does not overlap the # selected chunk's bbox. # Remember: chunk = a selected chunk, mol = a non-selected # chunk. if not chunk.overlapping_chunk(mol, self.tol): # print "Skipping ", mol.name continue else: # Loop through all the atoms in the selected chunk. # Use values() if the loop ever modifies chunk or mol-- for a1 in chunk.atoms.itervalues(): # Singlets can't be overlapping atoms -- if a1.element is Singlet: continue # We can skip mol if the atom lies outside its bbox. if not mol.overlapping_atom(a1, self.tol): continue # Loop through all the atoms in this chunk. for a2 in mol.atoms.itervalues(): # Only atoms of the same type can be overlapping. # This also screens singlets, since a1 can't be a # singlet. if a1.element is not a2.element: continue # Compares the distance between a1 and a2. # If the distance # is <= tol, then we have an overlapping atom. # I know this isn't a proper use of tol, # but it works for now. Mark 050901 if vlen (a1.posn() - a2.posn()) <= self.tol: # Add this pair to the list-- self.overlapping_atoms.append( (a1,a2) ) # No need to check other atoms in this chunk-- break # Update tolerance label and status bar msgs. natoms = len(self.overlapping_atoms) tol_str = fusechunks_lambda_tol_natoms(self.tol, natoms) tolerenceLabel = tol_str self.propMgr.toleranceSlider.labelWidget.setText(tolerenceLabel) def find_overlapping_atoms_to_delete_from_atomlists(self, atomlist_to_keep, atomlist_with_overlapping_atoms, tolerance = 1.1 ): """ @param atomlist_to_keep: Atomlist which will be used as a reference atom list. The atoms in this list will be used to find the atoms in the *other list* which overlap atom positions in *this list*. Thus, the atoms in 'atomlist_to_keep' will be preserved (and thus won't be appended to self.overlapping_atoms) @type atomlist_to_keep: list @param atomlist_with_overlapping_atoms: This list will be checked with the first list (atom_list_to_keep) to find overlapping atoms. The atoms in this list that overlap with the atoms from the original list will be appended to self.overlapping_atoms (and will be eventually deleted) """ overlapping_atoms_to_delete = [] # Remember: chunk = a selected chunk = atomlist to keep # mol = a non-selected -- to find overlapping atoms from # Loop through all the atoms in the selected chunk. # Use values() if the loop ever modifies chunk or mol-- for a1 in atomlist_to_keep: # Singlets can't be overlapping atoms. SKIP those if a1.is_singlet(): continue # Loop through all the atoms in atomlist_with_overlapping_atoms. for a2 in atomlist_with_overlapping_atoms: # Only atoms of the same type can be overlapping. # This also screens singlets, since a1 can't be a # singlet. if a1.element is not a2.element: continue # Compares the distance between a1 and a2. # If the distance # is <= tol, then we have an overlapping atom. # I know this isn't a proper use of tol, # but it works for now. Mark 050901 if vlen (a1.posn() - a2.posn()) <= tolerance: # Add this pair to the list-- overlapping_atoms_to_delete.append( (a1,a2) ) # No need to check other atoms in this chunk-- break return overlapping_atoms_to_delete def _delete_overlapping_atoms(self): pass def fuse_atoms(self): """ Deletes overlapping atoms found with the selected chunk(s). Only the overlapping atoms from the unselected chunk(s) are deleted. If the "Merge Chunks" checkbox is checked, then find_bondable_pairs() and make_bonds() is called, resulting in the merging of chunks. """ total_atoms_fused = 0 # The total number of atoms fused. # fused_chunks stores the list of chunks that contain overlapping atoms # (but no selected chunks, though) fused_chunks = [] # Delete overlapping atoms. for a1, a2 in self.overlapping_atoms: if a2.molecule not in fused_chunks: fused_chunks.append(a2.molecule) a2.kill() # print "Fused chunks list:", fused_chunks # Merge the chunks if the "merge chunks" checkbox is checked if self.propMgr.mergeChunksCheckBox.isChecked() and self.overlapping_atoms: # This will bond and merge the selected chunks only with # chunks that had overlapping atoms. #& This has bugs when the bonds don't line up nicely between # overlapping atoms in the selected chunk #& and the bondpoints of the deleted atoms' neighbors. # Needs a bug report. mark 060406. self.find_bondable_pairs(fused_chunks) self.make_bonds() # Print history msgs to inform the user what happened. total_atoms_fused = len(self.overlapping_atoms) msg = fix_plurals( "%d atom(s) fused with %d chunk(s)" % (total_atoms_fused, len(fused_chunks))) env.history.message(msg) #"%s => %s overlapping atoms" % (tol_str, natoms_str) # Update the slider tolerance label. self.reset_tolerance_label() self.overlapping_atoms = [] # This must be done before win_update(), or it will try to draw the # overlapping atoms again, which generates errors. self.w.win_update()
NanoCAD-master
cad/src/commands/Fuse/FuseChunks_Command.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ fusechunksMode.py - helpers for Fuse Chunks command and related functionality NOTE: the only class defined herein is fusechunksBase, so this module should be renamed. @author: Mark @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. """ import foundation.env as env from geometry.VQT import vlen from model.bonds import bond_at_singlets from utilities.Log import orangemsg from utilities.constants import diINVISIBLE def fusechunks_lambda_tol_nbonds(tol, nbonds, mbonds, bondable_pairs): """ Returns the bondable pairs tolerance string for the tolerance slider. """ if nbonds < 0: nbonds_str = "?" else: nbonds_str = "%d" % (nbonds,) if mbonds < 0: mbonds_str = "?" elif mbonds == 0: mbonds_str = " " else: mbonds_str = "(%d non-bondable) " % (mbonds,) tol_str = ("%d" % int(tol*100.0))[-3:] # fixed-width (3 digits) but using initial spaces # (doesn't have all of desired effect, due to non-fixed-width font) tol_str = "Tolerence:" + tol_str + "%" # return "%s => %s/%s bonds" % (tol_str,nbonds_str,mbonds_str) # return "%s => [%s bondable pairs] [%s bonds / %s multibonds] " % (tol_str,bondable_pairs,nbonds_str,mbonds_str) return "%s => %s bondable pairs %s" % (tol_str,bondable_pairs,mbonds_str) def fusechunks_lambda_tol_natoms(tol, natoms): """ Returns the overlapping atoms tolerance string for the tolerance slider. """ if natoms < 0: natoms_str = "?" else: natoms_str = "%d" % (natoms,) tol_str = (" %d" % int(tol*100.0))[-3:] # fixed-width (3 digits) but using initial spaces # (doesn't have all of desired effect, due to non-fixed-width font) tol_str = tol_str + "%" return "%s => %s overlapping atoms" % (tol_str, natoms_str) class fusechunksBase: """ Allows user to move chunks and fuse them to other chunks in the part. Two fuse methods are supported: 1. Make Bonds - bondpoints between chunks will form bonds when they are near each other. 2. Fuse Atoms - atoms between chunks will be fused when they overlap each other. """ bondable_pairs = [] # List of bondable singlets ways_of_bonding = {} # Number of bonds each singlet found bondable_pairs_atoms = [] # List of atom pairs that can be bonded overlapping_atoms = [] # List of overlapping atoms tol = 1.0 # in Angstroms # For "Make Bonds", tol is the distance between two bondable singlets # For "Fuse Atoms", tol is the distance between two atoms to be considered overlapping def find_bondable_pairs(self, chunk_list = None, selmols_list = None, ignore_chunk_picked_state = False ): """ Checks the bondpoints of the selected chunk to see if they are close enough to bond with any other bondpoints in a list of chunks. Hidden chunks are skipped. @param ignore_chunk_picked_state: If True, this method treats selected or unselected chunks without any difference. i.e. it finds bondable pairs even for a chunk that is 'picked' """ self.bondable_pairs = [] self.ways_of_bonding = {} if not chunk_list: chunk_list = self.o.assy.molecules if not selmols_list: selmols_list = self.o.assy.selmols for chunk in selmols_list: if chunk.hidden or chunk.display == diINVISIBLE: # Skip selected chunk if hidden or invisible. Fixes bug 970. mark 060404 continue # Loop through all the mols in the part to search for bondable pairs of singlets. # for mol in self.o.assy.molecules: for mol in chunk_list: if chunk is mol: continue # Skip itself if mol.hidden or mol.display == diINVISIBLE: continue # Skip hidden and invisible chunks. if mol.picked and not ignore_chunk_picked_state: continue # Skip selected chunks # Skip this mol if its bounding box does not overlap the selected chunk's bbox. # Remember: chunk = a selected chunk, mol = a non-selected chunk. if not chunk.overlapping_chunk(mol, self.tol): continue else: # Loop through all the singlets in the selected chunk. for s1 in chunk.singlets: # We can skip mol if the singlet lies outside its bbox. if not mol.overlapping_atom(s1, self.tol): continue # Loop through all the singlets in this chunk. for s2 in mol.singlets: # I substituted the line below in place of mergeable_singlets_Q_and_offset, # which compares the distance between s1 and s2. If the distance # is <= tol, then we have a bondable pair of singlets. I know this isn't # a proper use of tol, but it works for now. Mark 050327 if vlen (s1.posn() - s2.posn()) <= self.tol: # ok, ideal, err = mergeable_singlets_Q_and_offset(s1, s2, offset2 = V(0,0,0), self.tol) # if ok: # we can ignore ideal and err, we know s1, s2 can bond at this tol self.bondable_pairs.append( (s1,s2) ) # Add this pair to the list # Now increment ways_of_bonding for each of the two singlets. if s1.key in self.ways_of_bonding: self.ways_of_bonding[s1.key] += 1 else: self.ways_of_bonding[s1.key] = 1 if s2.key in self.ways_of_bonding: self.ways_of_bonding[s2.key] += 1 else: self.ways_of_bonding[s2.key] = 1 # Update tolerance label and status bar msgs. nbonds = len(self.bondable_pairs) mbonds, singlets_not_bonded, singlet_pairs = self.multibonds() tol_str = fusechunks_lambda_tol_nbonds(self.tol, nbonds, mbonds, singlet_pairs) return tol_str def find_bondable_pairs_in_given_atompairs(self, atomPairs): """ This is just a convience method that doesn't need chunk lists as an arguments. Finds the bondable pairs between the atom pairs provided in the atom pair list. The format is [(a1, a2), (a3, a4) ...]. This method is only used internally (no direct user interation involved) It skips the checks such as atom's display while finding the bondable pairs.. As of 2008-04-07 this method is not used. """ self.bondable_pairs = [] self.ways_of_bonding = {} for atm1, atm2 in atomPairs: #Skip the pair if its one and the same atom. if atm1 is atm2: continue #Loop through singlets (bondpoints) of atm1 (@see:Atom.singNeighbor) for s1 in atm1.singNeighbors(): #Loop through the 'singlets' i.e. bond point neigbors of atm2 for s2 in atm2.singNeighbors(): if vlen (s1.posn() - s2.posn()) <= self.tol: # Add this pair to the list self.bondable_pairs.append( (s1,s2) ) # Now increment ways_of_bonding for each of the two singlets. if s1.key in self.ways_of_bonding: self.ways_of_bonding[s1.key] += 1 else: self.ways_of_bonding[s1.key] = 1 if s2.key in self.ways_of_bonding: self.ways_of_bonding[s2.key] += 1 else: self.ways_of_bonding[s2.key] = 1 def make_bonds(self, assy = None): """ Make bonds between all bondable pairs of singlets """ self._make_bonds_1(assy) self._make_bonds_3() def _make_bonds_1(self, assy = None): """ Make bonds -- part 1. (Actually make the bonds using bond_at_singlets, call assy.changed() if you make any bonds, and record some info in several attrs of self.) """ if assy == None: assy = self.o.assy self.bondable_pairs_atoms = [] self.merged_chunks = [] singlet_found_with_multiple_bonds = False # True when there are singlets with multiple bonds. self.total_bonds_made = 0 # The total number of bondpoint pairs that formed bonds. singlets_not_bonded = 0 # Number of bondpoints not bonded. # print self.bondable_pairs # This first section of code bonds each bondable pair of singlets. for s1, s2 in self.bondable_pairs: # Make sure each singlet of the pair has only one way of bonding. # If either singlet has more than one ways to bond, we aren't going to bond them. if self.ways_of_bonding[s1.key] == 1 and self.ways_of_bonding[s2.key] == 1: # Record the real atoms in case I want to undo the bond later (before general Undo exists) # Currently, this undo feature is not implemented here. Mark 050325 a1 = s1.singlet_neighbor() a2 = s2.singlet_neighbor() self.bondable_pairs_atoms.append( (a1,a2) ) # Add this pair to the list bond_at_singlets(s1, s2, move = False) # Bond the singlets. assy.changed() # The assy has changed. else: singlet_found_with_multiple_bonds = True self.singlet_found_with_multiple_bonds = singlet_found_with_multiple_bonds def _make_bonds_3(self): """ Make bonds -- part 3. (Print history warning if self.singlet_found_with_multiple_bonds.) """ if self.singlet_found_with_multiple_bonds: mbonds, singlets_not_bonded, bp = self.multibonds() self.total_bonds_made = len(self.bondable_pairs_atoms) if singlets_not_bonded == 1: msg = "%d bondpoint had more than one way to bond. It was not bonded." % (singlets_not_bonded,) else: msg = "%d bondpoints had more than one way to bond. They were not bonded." % (singlets_not_bonded,) env.history.message(orangemsg(msg)) else: # All bondpoints had only one way to bond. self.total_bonds_made = len(self.bondable_pairs_atoms) def multibonds(self): """ Returns the following information about bondable pairs: - the number of multiple bonds - number of bondpoints (singlets) with multiple bonds - number of bondpoint pairs that will bond """ mbonds = 0 # number of multiple bonds mbond_singlets = [] # list of singlets with multiple bonds (these will not bond) sbond_singlets = 0 # number of singlets with single bonds (these will bond) for s1, s2 in self.bondable_pairs: if self.ways_of_bonding[s1.key] == 1 and self.ways_of_bonding[s2.key] == 1: sbond_singlets += 1 continue if self.ways_of_bonding[s1.key] > 1: if s1 not in mbond_singlets: mbond_singlets.append(s1) mbonds += self.ways_of_bonding[s1.key] - 1 # The first one doesn't count. if self.ways_of_bonding[s2.key] > 1: if s2 not in mbond_singlets: mbond_singlets.append(s2) mbonds += self.ways_of_bonding[s2.key] - 1 # The first one doesn't count. return mbonds, len(mbond_singlets), sbond_singlets pass # end of class fusechunksBase # end
NanoCAD-master
cad/src/commands/Fuse/fusechunksMode.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ FusePropertyManager.py @author: Ninad @version: $Id$ @copyright:2004-2007 Nanorex, Inc. All rights reserved. History: ninad070425 :1) Moved Fuse dashboard to Property manager 2) Implemented Translate/ Rotate enhancements ninad20070723: code cleanup to define a fusePropMgr object. This was a prerequisite for 'command sequencer' and also needed to resolve potential multiple inheritance issues. TODO: ninad20070723-- See if the signals can be connected in the fuseMde.connect_disconnect_signals OR better to call propMgr.connect_disconnect_signals in the fuseMde.connect_disconnect_signals? I think the latter will help decoupling ui elements from fuseMode. Same thing applies to other modes and Propert Managers (e.g. Move mode, Build Atoms mode) """ from PyQt4.Qt import SIGNAL from PyQt4.Qt import Qt from PM.PM_GroupBox import PM_GroupBox from PM.PM_ComboBox import PM_ComboBox from PM.PM_PushButton import PM_PushButton from PM.PM_CheckBox import PM_CheckBox from PM.PM_Slider import PM_Slider from commands.Move.MovePropertyManager import MovePropertyManager class FusePropertyManager(MovePropertyManager): # <title> - the title that appears in the property manager header. title = "Fuse Chunks" # <iconPath> - full path to PNG file that appears in the header. iconPath = "ui/actions/Tools/Build Tools/Fuse_Chunks.png" def __init__(self, command): """ Constructor for Fuse Property manager. @param command: The parent mode for this property manager @type command: L{fuseChunksmode} """ self.command = command MovePropertyManager.__init__(self, self.command) self.activate_translateGroupBox_in_fuse_PM() def _addGroupBoxes(self): """ Add various groupboxes to Fuse property manager. """ self.fuseOptionsGroupBox = PM_GroupBox( self, title = "Fuse Options") self._loadFuseOptionsGroupBox(self.fuseOptionsGroupBox) MovePropertyManager._addGroupBoxes(self) def _loadFuseOptionsGroupBox(self, inPmGroupBox): """ Load the widgets inside the Fuse Options groupbox. """ #@ Warning: If you change fuseChoices, you must also change the # constants MAKEBONDS and FUSEATOMS in FuseChunks_Command.py. # This implementation is fragile and should be fixed. Mark 2008-07-16 fuseChoices = ['Make bonds between chunks', 'Fuse overlapping atoms'] self.fuseComboBox = \ PM_ComboBox( inPmGroupBox, label = '', choices = fuseChoices, index = 0, setAsDefault = False, spanWidth = True) self.connect(self.fuseComboBox, SIGNAL("activated(const QString&)"), self.command.change_fuse_mode) self.fusePushButton = PM_PushButton( inPmGroupBox, label = "", text = "Make Bonds", spanWidth = True ) self.connect( self.fusePushButton, SIGNAL("clicked()"), self.command.fuse_something) self.toleranceSlider = PM_Slider( inPmGroupBox, currentValue = 100, minimum = 0, maximum = 300, label = \ 'Tolerance:100% => 0 bondable pairs' ) self.connect(self.toleranceSlider, SIGNAL("valueChanged(int)"), self.command.tolerance_changed) self.mergeChunksCheckBox = PM_CheckBox( inPmGroupBox, text = 'Merge chunks', widgetColumn = 0, state = Qt.Checked ) def activate_translateGroupBox_in_fuse_PM(self): """ Show contents of translate groupbox, deactivae the rotate groupbox. Also check the action that was checked when this groupbox was active last time. (if applicable). This method is called only when move groupbox button is clicked. @see: L{self.activate_translateGroupBox_in_fuse_PM} """ self.command.switchGraphicsModeTo(newGraphicsMode = 'TRANSLATE_CHUNKS') self.toggle_translateGroupBox() self.deactivate_rotateGroupBox() buttonToCheck = self.getTranslateButtonToCheck() if buttonToCheck: buttonToCheck.setChecked(True) else: buttonToCheck = self.transFreeButton buttonToCheck.setChecked(True) self.changeMoveOption(buttonToCheck) self.isTranslateGroupBoxActive = True self.command.graphicsMode.update_cursor() def activate_rotateGroupBox_in_fuse_PM(self): """ Show contents of rotate groupbox (in fuse PM), deactivae the translate groupbox. Also check the action that was checked when this groupbox was active last time. (if applicable). This method is called only when rotate groupbox button is clicked. @see: L{activate_rotateGroupBox_in_fuse_PM} """ self.command.switchGraphicsModeTo(newGraphicsMode = 'TRANSLATE_CHUNKS') self.toggle_rotateGroupBox() self.deactivate_translateGroupBox() buttonToCheck = self.getRotateButtonToCheck() if buttonToCheck: buttonToCheck.setChecked(True) else: buttonToCheck = self.rotateFreeButton buttonToCheck.setChecked(True) self.changeRotateOption(buttonToCheck) self.isTranslateGroupBoxActive = False self.command.graphicsMode.update_cursor() return def updateMessage(self, msg = ''): """ Updates the message box with an informative message. @param msg: The message to display. If msg is an empty string, a default message is displayed. @type msg: string Overrides the MovePropertyManager.updateMessage method @see: MovePropertyManager.updateMessage """ #@bug: BUG: The message box height is fixed. The verticle scrollbar # appears as the following message is long. It however tries to make the # cursor visible within the message box . This results in scrolling the # msg box to the last line and thus doesn't look good.-- ninad 20070723 if msg: self.MessageGroupBox.insertHtmlMessage( msg, setAsDefault = True ) return if self.fuseComboBox.currentIndex() == 0: #i.e. 'Make Bonds Between Chunks' msg = "To <b> make bonds</b> between two or more chunks, "\ "drag the selected chunk(s) such that their one or more "\ "bondpoints overlap with the other chunk(s). Then click the "\ "<b> Make Bonds </b> button to create bond(s) between them. " else: msg = "To <b>fuse overlapping atoms</b> in two or more chunks, "\ "drag the selected chunk(s) such that their one or more atoms "\ "overlap with the atoms in the other chunk(s). Then click the "\ "<b> Fuse Atoms </b>\ button to remove the overlapping atoms of "\ "unselected chunk. " self.MessageGroupBox.insertHtmlMessage( msg, setAsDefault = True ) return
NanoCAD-master
cad/src/commands/Fuse/FusePropertyManager.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ An example of a structure generator's user interface meant to be a template for developers. The AtomGeneratorDialog class is an example of how PropMgrBaseClass is used to build a structure generator's user interface (dialog) in NanoEngineer-1. The key points of interest are the methods: __init__, addGroupBoxes and add_whats_this_text. They all **must always** be overridden when a new structure generator dialog class is defined. The class variables <title> and <iconPath> should be changed to fit the new structure generator's role. The class static variables (prefixed with _s) and their accessor methods (Get.../Set...) are purely for the sake of example and may be omitted from any new implementation. @author: Jeff Birac @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. History: Jeff 2007-05-29: Based on Mark Sims' GrapheneGeneratorDialog.py, v1.17 Convention of variables' names: variable's role prefix examples ----------------- -------- ---------- - incoming parameter in... inData inObjectPointer - outgoing parameter outBufferPointer or function return out... outCalculation - I/O parameter io... ioDataBuffer - static variable s... sDefaultValue - local variable the... theUserName theTempValue - class member m... mObjectName (aka attribute or mPosition instance variable) mColor Mark 2007-07-24: Uses new PM module. """ from utilities.icon_utilities import geticon, getpixmap from PyQt4.Qt import Qt, SIGNAL from PM.PM_Dialog import PM_Dialog from PM.PM_GroupBox import PM_GroupBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_ComboBox import PM_ComboBox from PM.PM_SpinBox import PM_SpinBox from PM.PM_TextEdit import PM_TextEdit from PM.PM_PushButton import PM_PushButton from PM.PM_LineEdit import PM_LineEdit from PM.PM_CheckBox import PM_CheckBox from PM.PM_RadioButton import PM_RadioButton from PM.PM_ElementChooser import PM_ElementChooser class AtomGeneratorPropertyManager(PM_Dialog): """ Implements user interface to specify properties of an atom """ # The title that appears in the property manager header. title = "Insert Atom" # 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 PNG file that appears in the header. iconPath = "ui/actions/Command Toolbar/BuildAtoms/InsertAtom.png" # Jeff 20070530: # Private static variables (prefixed with '_s') are used to assure consistency # between related widgets and simplify code revision. # Example: The unit for coordinates is specified by _sCoordinateUnit. All # widgets related to coordinates should refer to _sCoordinateUnit rather than # hardcoding the unit for each coordinate widget. The advantage comes when # a later revision uses different units (or chosen possibly via a user # preference), the value of only _sCoordinateUnit (not blocks of code) # needs to be changed. All related widgets follow the new choice for units. _sMinCoordinateValue = -30.0 _sMaxCoordinateValue = 30.0 _sStepCoordinateValue = 0.1 _sCoordinateDecimals = 3 _sCoordinateUnit = 'Angstrom' _sCoordinateUnits = _sCoordinateUnit + 's' def __init__(self): """ Construct the Atom Property Manager. """ PM_Dialog.__init__( self, self.pmName, self.iconPath, self.title ) self.addGroupBoxes() self.add_whats_this_text() msg = "Edit the Atom parameters and select <b>Preview</b> to \ preview the structure. Click <b>Done</b> to insert the atom \ into the model." # This causes the "Message" box to be displayed as well. self.MessageGroupBox.insertHtmlMessage( msg, setAsDefault = False ) def getCartesianCoordinates(self): """ Gets the cartesian coordinates for the position of the atom specified in the coordinate spin boxes of the Atom Generator property manager. """ return ( self.xCoordinateField.value, self.yCoordinateField.value, self.zCoordinateField.value ) def getMinCoordinateValue(self): """ Get the minimum value allowed in the coordinate spin boxes of the Atom Generator property manager. """ return self.sel_sMinCoordinateValue def getMaxCoordinateValue(self): """ Get the maximum value allowed in the coordinate spin boxes of the Atom Generator property manager. """ return self._sMaxCoordinateValue def getStepCoordinateValue(self): """ Get the value by which a coordinate increases/decreases when the user clicks an arrow of a coordinate spin box in the Atom Generator property manager. """ return self._sStepCoordinateValue def getCoordinateDecimals(self): """ Get the number of decimal places given for a value in a coordinate spin box in the Atom Generator property manager. """ return self._sStepCoordinateValue def getCoordinateUnit(self): """ Get the unit (of measure) for the coordinates of the generated atom's position. """ return self._sCoordinateUnit def setCartesianCoordinates( self, inX, inY, inZ ): """ Set the cartesian coordinates for the position of the atom specified in the coordinate spin boxes of the Atom Generator property manager. """ # We may want to restrict self.xCoordinateField.value = inX self.yCoordinateField.value = inY self.zCoordinateField.value = inZ def setMinCoordinateValue( self, inMin ): """ Set the minimum value allowed in the coordinate spin boxes of the Atom Generator property manager. """ self._sMinCoordinateValue = inMin def setMaxCoordinateValue( self, inMax ): """ Set the maximum value allowed in the coordinate spin boxes of the Atom Generator property manager. """ self._sMaxCoordinateValue = inMax def setStepCoordinateValue( self, inStep ): """ Set the value by which a coordinate increases/decreases when the user clicks an arrow of a coordinate spin box in the Atom Generator property manager. """ self._sStepCoordinateValue = inStep def setCoordinateDecimals( self, inDecimals ): """ Set the number of decimal places given for a value in a coordinate spin box in the Atom Generator property manager. """ self._sStepCoordinateValue = inDecimals def setCoordinateUnit( self, inUnit ): """ Set the unit(s) (of measure) for the coordinates of the generated atom's position. """ self._sCoordinateUnit = inUnit self._sCoordinateUnits = inUnit + 's' def addGroupBoxes(self): """ Add the 1 groupbox for the Atom Property Manager. """ self.pmGroupBox1 = \ PM_GroupBox( self, title = "Atom Position" ) self.loadGroupBox1(self.pmGroupBox1) self.pmElementChooser = PM_ElementChooser(self) AddTestGroupBoxes = True # For testing. Mark 2007-05-24 if not AddTestGroupBoxes: # Add test widgets to their own groupbox. return """ self.testGroupBox1 = \ PM_GroupBox( self, title = "Test Widgets1" ) self.loadTestWidgets1(self.testGroupBox1) self.pmLineEditGroupBox = \ PM_GroupBox( self, title = "PM_LineEdit Widgets" ) self.loadLineEditGroupBox(self.pmLineEditGroupBox) """ """ self.radioButtonGroupBox = \ PM_GroupBox( self, title = "PM_RadioButtons" ) self.loadRadioButtonGroupBox(self.radioButtonGroupBox) self.pmToolButtonGroupBox = \ PM_GroupBox( self, title = "MMKit Widget" ) self.loadToolButtonGroupBox(self.pmToolButtonGroupBox) """ def loadGroupBox1(self, inPmGroupBox): """ Load widgets into groupbox 1. """ # User input to specify x-coordinate # of the generated atom's position. self.xCoordinateField = \ PM_DoubleSpinBox( inPmGroupBox, label = \ "ui/actions/Properties Manager/X_Coordinate.png", value = 0.0, setAsDefault = True, minimum = self._sMinCoordinateValue, maximum = self._sMaxCoordinateValue, singleStep = self._sStepCoordinateValue, decimals = self._sCoordinateDecimals, suffix = ' ' + self._sCoordinateUnits ) # User input to specify y-coordinate # of the generated atom's position. self.yCoordinateField = \ PM_DoubleSpinBox( inPmGroupBox, label = \ "ui/actions/Properties Manager/Y_Coordinate.png", value = 0.0, setAsDefault = True, minimum = self._sMinCoordinateValue, maximum = self._sMaxCoordinateValue, singleStep = self._sStepCoordinateValue, decimals = self._sCoordinateDecimals, suffix = ' ' + self._sCoordinateUnits ) # User input to specify z-coordinate # of the generated atom's position. self.zCoordinateField = \ PM_DoubleSpinBox( inPmGroupBox, label = \ "ui/actions/Properties Manager/Z_Coordinate.png", value = 0.0, setAsDefault = True, minimum = self._sMinCoordinateValue, maximum = self._sMaxCoordinateValue, singleStep = self._sStepCoordinateValue, decimals = self._sCoordinateDecimals, suffix = ' ' + self._sCoordinateUnits ) def add_whats_this_text(self): """ What's This... text for some of the widgets in the Atom Property Manager. :Jeff 2007-05-30: """ self.xCoordinateField.setWhatsThis("<b>x</b><p>: The x-coordinate (up "\ "to </p>" \ + str( self._sMaxCoordinateValue ) \ + self._sCoordinateUnits \ + ") of the Atom in " \ + self._sCoordinateUnits + '.') self.yCoordinateField.setWhatsThis("<b>y</b><p>: The y-coordinate (up" \ "to </p>"\ + str( self._sMaxCoordinateValue ) \ + self._sCoordinateUnits \ + ") of the Atom in " \ + self._sCoordinateUnits + '.') self.zCoordinateField.setWhatsThis("<b>z</b><p>: The z-coordinate (up" \ "to </p>" \ + str( self._sMaxCoordinateValue ) + self._sCoordinateUnits \ + ") of the Atom in " + self._sCoordinateUnits + '.') def loadTestWidgets1(self, inPmGroupBox): """ Adds widgets to <inPmGroupBox>. Used for testing purposes. Mark 2007-05-24 """ # I intend to create a special PropMgr to display all widget types # for testing purposes. For now, I just add them to the end of the # Graphene Sheet property manager. Mark 2007-05-22 self.spinBox = \ PM_SpinBox( inPmGroupBox, label = "Spinbox:", value = 5, setAsDefault = True, minimum = 2, maximum = 10, suffix = ' things', spanWidth = True ) self.doubleSpinBox = \ PM_DoubleSpinBox( inPmGroupBox, #label="Spanning DoubleSpinBox :", label = "", # No label value = 5.0, setAsDefault = True, minimum = 1.0, maximum = 10.0, singleStep = 1.0, decimals = 1, suffix = ' Suffix', spanWidth = True ) # Add a prefix example. self.doubleSpinBox.setPrefix("Prefix ") choices = [ "First", "Second", "Third (Default)", "Forth" ] self.comboBox1= \ PM_ComboBox( inPmGroupBox, label = 'Choices: ', choices = choices, index = 2, setAsDefault = True, spanWidth = False ) self.comboBox2= \ PM_ComboBox( inPmGroupBox, label = ' :Choices', labelColumn = 1, choices = choices, index = 2, setAsDefault = True, spanWidth = False ) self.comboBox3= \ PM_ComboBox( inPmGroupBox, label = ' Choices (SpanWidth = True):', labelColumn = 1, choices = choices, index = 2, setAsDefault = True, spanWidth = True ) self.textEdit = \ PM_TextEdit( inPmGroupBox, label = "TextEdit:", spanWidth = False ) self.spanTextEdit = \ PM_TextEdit( inPmGroupBox, label = "", spanWidth = True ) self.groupBox = \ PM_GroupBox( inPmGroupBox, title = "Group Box Title" ) self.comboBox2= \ PM_ComboBox( self.groupBox, label = "Choices:", choices = choices, index = 2, setAsDefault = True, spanWidth = False ) self.groupBox2 = \ PM_GroupBox( inPmGroupBox, title = "Group Box Title" ) self.comboBox3= \ PM_ComboBox( self.groupBox2, label = "Choices:", choices = choices, index = 2, setAsDefault = True, spanWidth = True ) self.pushButton1 = \ PM_PushButton( inPmGroupBox, label = "", text = "PushButton1" ) self.pushButton2 = \ PM_PushButton( inPmGroupBox, label = "", text = "PushButton2", spanWidth = True ) def loadLineEditGroupBox(self, inPmGroupBox): """ Load PM_LineEdit test widgets in group box. """ self.lineEdit1 = \ PM_LineEdit( inPmGroupBox, label = "Name:", text = "RotaryMotor-1", setAsDefault = True, spanWidth = False) self.lineEdit2 = \ PM_LineEdit( inPmGroupBox, label = ":Name", labelColumn = 1, text = "RotaryMotor-1", setAsDefault = True, spanWidth = False) self.lineEdit3 = \ PM_LineEdit( inPmGroupBox, label = "LineEdit (spanWidth = True):", text = "RotaryMotor-1", setAsDefault = False, spanWidth = True) def loadCheckBoxGroupBox(self, inPmGroupBox): """ Load PM_CheckBox test widgets in group box. """ self.checkBoxGroupBox = \ PM_GroupBox( inPmGroupBox, title = "<b> PM_CheckBox examples</b>" ) self.checkBox1 = \ PM_CheckBox( self.checkBoxGroupBox, text = "Widget on left:", widgetColumn = 1, state = Qt.Checked, setAsDefault = True, ) self.checkBox2 = \ PM_CheckBox( self.checkBoxGroupBox, text = "Widget on right", widgetColumn = 1, state = Qt.Checked, setAsDefault = True, ) def loadRadioButtonGroupBox(self, inPmGroupBox): """ Test for PM_RadioButtonGroupBox. """ #from PyQt4.Qt import QButtonGroup #self.radioButtonGroup = QButtonGroup() #self.radioButtonGroup.setExclusive(True) self.radioButton1 = \ PM_RadioButton( inPmGroupBox, label = "Display PM_CheckBox group box", spanWidth = False) self.radioButton2 = \ PM_RadioButton( inPmGroupBox, label = "Display PM_ComboBox group box", spanWidth = False) self.radioButton3 = \ PM_RadioButton( inPmGroupBox, label = "Display PM_DoubleSpinBox group box", spanWidth = False) self.radioButton4 = \ PM_RadioButton( inPmGroupBox, label = "Display PM_PushButton group box", spanWidth = False)
NanoCAD-master
cad/src/commands/BuildAtom/AtomGeneratorPropertyManager.py
NanoCAD-master
cad/src/commands/BuildAtom/__init__.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ AtomGenerator.py - an example of a structure generator class meant to be a template for developers. The AtomGenerator class is an example of how a structure generator is implemented for NanoEngineer-1. The key points of interest are the methods: __init__, gather_parameters and build_struct. They all **must always** be overridden when a new structure generator class is defined. The class variables cmd and prefix should be changed to fit the new structure generator's role. @author: Jeff Birac @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. History: Jeff 2007-05-30: Based on Will Ware's GrapheneGenerator.py Mark 2007-07-25: Uses new PM module. """ from utilities import debug_flags import foundation.env as env from model.chem import Atom from model.chunk import Chunk from geometry.VQT import V from model.elements import PeriodicTable from utilities.Log import greenmsg from commands.BuildAtom.AtomGeneratorPropertyManager import AtomGeneratorPropertyManager from command_support.GeneratorBaseClass import GeneratorBaseClass def enableAtomGenerator(enable): """ This function enables/disables the Atom Generator command by hiding or showing it in the Command Manager toolbar and menu. The enabling/disabling is done by the user via the "secret" NE1 debugging menu. To display the secret debugging menu, hold down Shift+Ctrl+Alt keys (or Shift+Cmd+Alt on Mac) and right click over the graphics area. Select "debug prefs submenu > Atom Generator example code" and set the value to True. The "Atom" option will then appear on the "Build" Command Manager toolbar/menu. @param enable: If true, the Atom Generator is enabled. Specifically, it will be added to the "Build" Command Manager toolbar and menu. @type enable: bool """ win = env.mainwindow() win.insertAtomAction.setVisible(enable) # AtomGeneratorPropertyManager must come BEFORE GeneratorBaseClass in this list. class AtomGenerator( AtomGeneratorPropertyManager, GeneratorBaseClass ): """ The Atom Generator class provides the "Build > Atom" command for NE1. It is intended to be a simple example of how to add a new NE1 command that builds (generates) a new structure using parameters from a Property Manager and inserts it into the current part. """ cmd = greenmsg("Build Atom: ") prefix = 'Atom' # used for gensym # Generators for DNA, nanotubes and graphene have their MT name generated # (in GeneratorBaseClass) from the prefix. create_name_from_prefix = True # pass window arg to constructor rather than use a global. def __init__( self, win ): AtomGeneratorPropertyManager.__init__(self) GeneratorBaseClass.__init__(self, win) ################################################### # How to build this kind of structure, along with # any necessary helper functions def gather_parameters( self ): """ Returns all the parameters from the Atom Generator's Property Manager needed to build a new atom (chunk). """ x = self.xCoordinateField.value() y = self.yCoordinateField.value() z = self.zCoordinateField.value() # Get the chemical symbol and atom type. outElement, outAtomType = \ self.pmElementChooser.getElementSymbolAndAtomType() return ( x, y, z, outElement, outAtomType ) def build_struct( self, name, parameters, position ): """ Build an Atom (as a chunk) according to the given parameters. @param name: The name which should be given to the toplevel Node of the generated structure. The name is also passed in self.name. @type name: str @param parameters: The parameter tuple returned from L{gather_parameters()}. @type parameters: tuple @param position: Unused. The xyz position is obtained from the I{parameters} tuple. @type position: position @return: The new structure, i.e. some flavor of a Node, which has not yet been added to the model. Its structure should depend only on the values of the passed parameters, since if the user asks to build twice, this method may not be called if the parameterss have not changed. @rtype: Node """ x, y, z, theElement, theAtomType = parameters # Create new chunk to contain the atom. outMolecule = Chunk( self.win.assy, self.name ) theAtom = Atom( theElement, V(x, y, z), outMolecule ) theAtom.set_atomtype( theAtomType ) theAtom.make_enough_bondpoints() return outMolecule
NanoCAD-master
cad/src/commands/BuildAtom/AtomGenerator.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ BuildCrystal_Command.py @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Note: Till Alpha8, this mode was called Cookie Cutter mode. In Alpha9 it has been renamed to 'Build Crystal' mode. -- ninad 20070511 Ninad 2008-08-22 - major cleanup: implemented new Command API methods, new flyouttoolbar object, moved command specific code in the PM class to here. """ import math # only for pi from Numeric import size, dot, sqrt, floor from OpenGL.GL import GL_COLOR_LOGIC_OP from OpenGL.GL import GL_DEPTH_TEST from OpenGL.GL import GL_XOR from OpenGL.GL import glLogicOp from OpenGL.GL import glTranslatef from OpenGL.GL import glRotatef from OpenGL.GL import GL_CLIP_PLANE1 from OpenGL.GL import glColor3fv from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import glFlush from OpenGL.GL import glPushMatrix from OpenGL.GL import GL_CLIP_PLANE0 from OpenGL.GL import glClipPlane from OpenGL.GL import glPopMatrix from PyQt4.Qt import Qt from PyQt4.Qt import QCursor import foundation.env as env from geometry.VQT import V, Q, A, norm, vlen from command_support.modes import basicMode from commands.BuildCrystal.BuildCrystal_PropertyManager import BuildCrystal_PropertyManager from ne1_ui.toolbars.Ui_BuildCrystalFlyout import BuildCrystalFlyout from utilities.Log import orangemsg from utilities.Log import redmsg from graphics.behaviors.shape import get_selCurve_color from geometry.Slab import Slab from commands.BuildCrystal.CrystalShape import CrystalShape import graphics.drawing.drawing_globals as drawing_globals from graphics.drawing.CS_draw_primitives import drawline from graphics.drawing.drawers import drawCircle from graphics.drawing.drawers import drawGrid from graphics.drawing.drawers import drawLineLoop from graphics.drawing.drawers import drawrectangle from graphics.drawing.drawers import findCell from utilities.constants import intRound from utilities.constants import diTUBES from utilities.constants import SELSHAPE_LASSO from utilities.constants import START_NEW_SELECTION from utilities.constants import white from utilities.constants import ADD_TO_SELECTION from utilities.constants import SUBTRACT_FROM_SELECTION from utilities.constants import SELSHAPE_RECT import foundation.changes as changes # == def _init_snapquats(): """ Return a tuple of lists of quats that can be snapped to. """ #bruce 080910 moved this here from GLPane.py, made it a function pi2 = math.pi / 2.0 pi3 = math.pi / 3.0 pi4 = math.pi / 4.0 xquats = [Q(1,0,0,0), Q(V(0,0,1),pi2), Q(V(0,0,1),math.pi), Q(V(0,0,1),-pi2), Q(V(0,0,1),pi4), Q(V(0,0,1),3 * pi4), Q(V(0,0,1),-pi4), Q(V(0,0,1),-3 * pi4)] pquats = [Q(1,0,0,0), Q(V(0,1,0),pi2), Q(V(0,1,0),math.pi), Q(V(0,1,0),-pi2), Q(V(1,0,0),pi2), Q(V(1,0,0),-pi2)] quats100 = [] for q in pquats: for q1 in xquats: quats100 += [(q + q1, 0)] rq = Q(V(0,1,0),pi2) pquats = [Q(V(0,1,0),pi4), Q(V(0,1,0),3 * pi4), Q(V(0,1,0),-pi4), Q(V(0,1,0),-3 * pi4), Q(V(1,0,0),pi4), Q(V(1,0,0),3 * pi4), Q(V(1,0,0),-pi4), Q(V(1,0,0),-3 * pi4), rq + Q(V(1,0,0),pi4), rq + Q(V(1,0,0),3 * pi4), rq + Q(V(1,0,0),-pi4), rq + Q(V(1,0,0),-3 * pi4)] quats110 = [] for q in pquats: for q1 in xquats: quats110 += [(q + q1, 1)] cq = Q(V(1,0,0),0.615479708) xquats = [Q(1,0,0,0), Q(V(0,0,1),pi3), Q(V(0,0,1),2 * pi3), Q(V(0,0,1),math.pi), Q(V(0,0,1),-pi3), Q(V(0,0,1),-2 * pi3)] pquats = [Q(V(0,1,0),pi4), Q(V(0,1,0),3 * pi4), Q(V(0,1,0),-pi4), Q(V(0,1,0),-3 * pi4)] quats111 = [] for q in pquats: for q1 in xquats: quats111 += [(q + cq + q1, 2), (q - cq + q1, 2)] allQuats = quats100 + quats110 + quats111 return allQuats, quats100, quats110, quats111 allQuats, quats100, quats110, quats111 = _init_snapquats() # == _superclass = basicMode # for both Command and GraphicsMode parts (a single class) class BuildCrystal_Command(basicMode): """ Build Crystal """ # class constants PM_class = BuildCrystal_PropertyManager #Flyout Toolbar FlyoutToolbar_class = BuildCrystalFlyout commandName = 'CRYSTAL' featurename = "Build Crystal Mode" from utilities.constants import CL_ENVIRONMENT_PROVIDING command_level = CL_ENVIRONMENT_PROVIDING backgroundColor = 0 / 255.0, 0 / 255.0, 0 / 255.0 backgroundGradient = False # Mark 051029. gridColor = 222 / 255.0, 148 / 255.0, 0 / 255.0 displayMode = diTUBES # displayMode isn't used except for updating the 'Display Mode' combobox in the Preference dialog. # BuildCrystal command uses its own attr <cookieDisplayMode> to display Tubes (default) or Spheres. selCurve_List = [] # <selCurve_List> contains a list of points used to draw the selection curve. # The points lay in the plane parallel to the screen, just beyond the front clipping # plane, so that they are always inside the clipping volume. defaultSelShape = SELSHAPE_LASSO # <defaultSelShape> determines whether the current *default* selection curve is a rectangle # or lasso. MAX_LATTICE_CELL = 25 layerColors = ((0.0, 85.0 / 255.0, 127 / 255.0), (85 / 255.0, 85 / 255.0, 0.0), (85 / 255.0, 85 / 255.0, 127 / 255.0), (170.0 / 255.0, 0.0, 127.0 / 255.0), (170.0 / 255.0, 0.0, 1.0), (1.0, 0.0, 127.0 / 255.0), ) LATTICE_TYPES = ['DIAMOND', 'LONSDALEITE', 'GRAPHITE'] MAX_LAYERS = 6 freeView = False drawingCookieSelCurve = False # <drawingCookieSelCurve> is used to let other methods know when # we are in the process of defining/drawing a selection curve, where: # True = in the process of defining selection curve # False = finished/not defining selection curve # command api methods def _command_enter_effects(self): """ Called from self.command_entered() """ #@TODO: merge this with command_entered when new command API porting #work is finished -- Ninad 2008-09-08 # Save original GLPane background color and gradient, to be restored #when exiting BuildCrystal_Command self.glpane_backgroundColor = self.o.backgroundColor self.o.backgroundColor = self.backgroundColor self.glpane_backgroundGradient = self.o.backgroundGradient self.o.backgroundGradient = self.backgroundGradient self.oldPov = V(self.o.pov[0], self.o.pov[1], self.o.pov[2]) self.setOrientSurf(self.snap2trackball()) self.o.pov -= 3.5 * self.o.out self.savedOrtho = self.o.ortho self.o.ortho = True self.cookieQuat = None ##Every time enters into this mode, we need to set this to False self.freeView = False self.propMgr.freeViewCheckBox.setChecked(self.freeView) self.gridShow = True self.propMgr.gridLineCheckBox.setChecked(self.gridShow) self.gridSnap = False self.propMgr.snapGridCheckBox.setChecked(self.gridSnap) self.showFullModel = self.propMgr.fullModelCheckBox.isChecked() self.cookieDisplayMode = str(self.propMgr.dispModeComboBox.currentText()) self.latticeType = self.LATTICE_TYPES[self.propMgr.latticeCBox.currentIndex()] self.layers = [] ## Stores 'surface origin' for each layer self.layers += [V(self.o.pov[0], self.o.pov[1], self.o.pov[2])] self.currentLayer = 0 self.drawingCookieSelCurve = False # <drawingCookieSelCurve> is used to let other methods know when # we are in the process of defining/drawing a selection curve, where: # True = in the process of defining selection curve # False = finished/not defining selection curve self.Rubber = False # Set to True in end_selection_curve() when doing a poly-rubber-band selection. self.lastDrawStored = [] def command_entered(self): """ Overrides superclass method. @see:baseCommand.command_entered() for documentation """ super(BuildCrystal_Command, self).command_entered() self._command_enter_effects() self.selectionShape = self.flyoutToolbar.getSelectionShape() #This can't be done in the above call. During this time, # the ctrlPanel can't find the BuildCrystal_Command, the nullMode # is used instead. I don't know if that's good or not, but # generally speaking, I think the code structure for mode # operations like enter/init/cancel, etc, are kind of confusing. # The code readability is also not very good. --Huaicai self.setThickness(self.propMgr.layerCellsSpinBox.value()) # I don't know if this is better to do here or just before setThickness (or if it matters): ####@@@@ # Disable Undo/Redo actions, and undo checkpoints, during this mode (they *must* be reenabled in command_will_exit()). # We do this last, so as not to do it if there are exceptions in the rest of the method, # since if it's done and never undone, Undo/Redo won't work for the rest of the session. # [bruce 060414; same thing done in some other modes] import foundation.undo_manager as undo_manager undo_manager.disable_undo_checkpoints('Build Crystal Mode') undo_manager.disable_UndoRedo('Build Crystal Mode', "in Build Crystal") # optimizing this for shortness in menu text # this makes Undo menu commands and tooltips look like "Undo #(not permitted in BuildCrutsl command)" (and similarly for Redo) def command_will_exit(self): """ Overrides superclass method. @see:baseCommand.command_will_exit() for documentation @NOTE: This method also calls the method that creates the crystal when the user hits 'Done' button. """ # Reenable Undo/Redo actions, and undo checkpoints #(disabled in command_entered); # do it first to protect it from exceptions in the rest of this method # (since if it never happens, Undo/Redo won't work for the rest of the session) # [bruce 060414; same thing done in some other modes] import foundation.undo_manager as undo_manager undo_manager.reenable_undo_checkpoints('Build Crystal Mode') undo_manager.reenable_UndoRedo('Build Crystal Mode') self.set_cmdname('Build Crystal') # this covers all changes while we were in the mode # (somewhat of a kluge, and whether this is the best place to do it is unknown; # without this the cmdname is "Done") ## if not self.savedOrtho: ## self.w.setViewPerspecAction.setChecked(True) self.o.setViewProjection(self.savedOrtho) #bruce 080909 cleanup, possible bugfix #Restore GL states self.o.redrawGL = True glDisable(GL_COLOR_LOGIC_OP) glEnable(GL_DEPTH_TEST) # Restore default background color. self.o.backgroundColor = self.glpane_backgroundColor self.o.backgroundGradient = self.glpane_backgroundGradient if self.commandSequencer.exit_is_forced: #(this comes from the old haveNontrivialState method) if self.o.shape != None: self._warnUserAboutAbandonedChanges() elif not self.commandSequencer.exit_is_cancel: #Call the method that Builds the crystal when user hits Done button if self.o.shape: self.o.shape.buildChunk(self.o.assy) self.o.shape = None self.selCurve_List = [] #bruce 080909 self.o.pov = V(self.oldPov[0], self.oldPov[1], self.oldPov[2]) #bruce 080909 super(BuildCrystal_Command, self).command_will_exit() def command_enter_misc_actions(self): """ Overrides superclass method. @see: baseCommand.command_enter_misc_actions() for documentation """ #@ATTENTION: the following code was originally in #BuildCrystals_PropertyManager.show() #It is moved here 'as is' -- Ninad 2008-08-22 self.win.buildCrystalAction.setChecked(True) #Set projection to ortho, display them self.w.setViewOrthoAction.setChecked(True) self.w.setViewOrthoAction.setEnabled(False) self.w.setViewPerspecAction.setEnabled(False) # Disable some action items in the main window. self.w.zoomToAreaAction.setEnabled(0) # Disable "Zoom to Area" self.w.setViewZoomtoSelectionAction.setEnabled(0) # Disable Zoom to Selection self.w.viewOrientationAction.setEnabled(0) #Disable Orientation Window # Temporarily disable the global display style combobox since this # has its own special "crystal" display styles (i.e. spheres and tubes). # I decided to leave them enabled since the user might want to see the # entire model and change the global display style. --Mark 2008-03-16 #self.win.statusBar().dispbarLabel.setEnabled(False) #self.win.statusBar().globalDisplayStylesComboBox.setEnabled(False) # Disable these toolbars self.w.buildToolsToolBar.setEnabled(False) self.w.simulationToolBar.setEnabled(False) def command_exit_misc_actions(self): """ Overrides superclass method. @see: baseCommand.command_exit_misc_actions() for documentation """ self.win.buildCrystalAction.setChecked(False) #@ATTENTION: the following code was originally in #BuildCrystals_PropertyManager.close() #It is moved here 'as is' -- Ninad 2008-08-22 self.w.zoomToAreaAction.setEnabled(1) # Enable "Zoom to Area" self.w.setViewZoomtoSelectionAction.setEnabled(1) # Enable Zoom to Selection self.w.viewOrientationAction.setEnabled(1) #Enable Orientation Window # See note above in initGui() about these. Mark 2008-01-30. #self.w.panToolAction.setEnabled(1) # Enable "Pan Tool" #self.w.rotateToolAction.setEnabled(1) # Enable "Rotate Tool" # Enable these toolbars self.w.buildToolsToolBar.setEnabled(True) self.w.simulationToolBar.setEnabled(True) # Restore global display style label and combobox. # (see note above in initGui(). ) #self.win.statusBar().dispbarLabel.setEnabled(False) #self.win.statusBar().globalDisplayStylesComboBox.setEnabled(False) # Restore view projection, enable them. self.w.setViewOrthoAction.setEnabled(True) self.w.setViewPerspecAction.setEnabled(True) def setFreeView(self, freeView): """ Enables/disables 'free view' mode. When <freeView> is True, crystal-cutting is frozen. """ self.freeView = freeView self.update_cursor_for_no_MB() if freeView: # Disable crystal cutting. #Save current pov before free view transformation self.cookiePov = V(self.o.pov[0], self.o.pov[1], self.o.pov[2]) env.history.message(orangemsg( "'Free View' enabled. You can not create crystal shapes while Free View is enabled.")) self.w.setViewOrthoAction.setEnabled(True) self.w.setViewPerspecAction.setEnabled(True) #Disable controls to change layer. self.propMgr.currentLayerComboBox.setEnabled(False) self.isAddLayerEnabled = self.propMgr.addLayerButton.isEnabled () self.propMgr.addLayerButton.setEnabled(False) self.propMgr.enableViewChanges(True) if self.drawingCookieSelCurve: #Cancel any unfinished crystal drawing self._afterCookieSelection() env.history.message(redmsg( "In free view mode,the unfinished crystal shape creation has been cancelled.")) else: ## Restore crystal cutting mode self.w.setViewOrthoAction.setChecked(True) self.w.setViewOrthoAction.setEnabled(False) self.w.setViewPerspecAction.setEnabled(False) #Restore controls to change layer/add layer self.propMgr.currentLayerComboBox.setEnabled(True) self.propMgr.addLayerButton.setEnabled(self.isAddLayerEnabled) self.propMgr.enableViewChanges(False) self.o.ortho = True if self.o.shape: self.o.quat = Q(self.cookieQuat) self.o.pov = V(self.cookiePov[0], self.cookiePov[1], self.cookiePov[2]) self.setOrientSurf(self.snap2trackball()) def showGridLine(self, show): self.gridShow = show self.o.gl_update() def setGridLineColor(self, c): """ Set the grid Line color to c. c is an object of QColor """ self.gridColor = c.red() / 255.0, c.green() / 255.0, c.blue() / 255.0 def changeDispMode(self, mode): """ Change crystal display mode as <mode>, which can be 'Tubes' or 'Spheres' """ self.cookieDisplayMode = str(mode) if self.o.shape: self.o.shape.changeDisplayMode(self.cookieDisplayMode) self.o.gl_update() def _Backup(self): # called only from our glpane context menu [made private by bruce 080806] if self.o.shape: self.o.shape.undo(self.currentLayer) # If no curves left, let users do what they can just like # when they first enter into crystal mode. if not self.o.shape.anyCurvesLeft(): self.StartOver() self.o.gl_update() # mouse and key events def keyRelease(self,key): _superclass.keyRelease(self, key) if key == Qt.Key_Escape and self.drawingCookieSelCurve: self._cancelSelection() def update_cursor_for_no_MB(self): """ Update the cursor for the BuildCrystal_Command """ if self.freeView: self.o.setCursor(QCursor(Qt.ArrowCursor)) return if self.drawingCookieSelCurve: # In the middle of creating a selection curve. return if self.o.modkeys is None: self.o.setCursor(self.w.CookieCursor) elif self.o.modkeys == 'Shift': self.o.setCursor(self.w.CookieAddCursor) elif self.o.modkeys == 'Control': self.o.setCursor(self.w.CookieSubtractCursor) elif self.o.modkeys == 'Shift+Control': self.o.setCursor(self.w.CookieSubtractCursor) else: print "Error in update_cursor_for_no_MB(): Invalid modkey=", self.o.modkeys return # == LMB down-click (button press) methods def leftShiftDown(self, event): self.leftDown(event) def leftCntlDown(self, event): self.leftDown(event) def leftDown(self, event): self.select_2d_region(event) # == LMB drag methods def leftShiftDrag(self, event): self.leftDrag(event) def leftCntlDrag(self, event): self.leftDrag(event) def leftDrag(self, event): self.continue_selection_curve(event) # == LMB up-click (button release) methods def leftShiftUp(self, event): self.leftUp(event) def leftCntlUp(self, event): self.leftUp(event) def leftUp(self, event): self.end_selection_curve(event) # == LMB double click method def leftDouble(self, event): """ End rubber selection """ if self.freeView or not self.drawingCookieSelCurve: return if self.Rubber and not self.rubberWithoutMoving: self.defaultSelShape = SELSHAPE_LASSO # defaultSelShape needs to be set to SELSHAPE_LASSO here since it # may have been set to SELSHAPE_RECT in continue_selection_curve() # while creating a polygon-rubber-band selection. self._traditionalSelect() # == end of LMB event handlers. def select_2d_region(self, event): # Copied from selectMode(). mark 060320. """ Start 2D selection of a region. """ if self.o.modkeys is None: self.start_selection_curve(event, START_NEW_SELECTION) if self.o.modkeys == 'Shift': self.start_selection_curve(event, ADD_TO_SELECTION) if self.o.modkeys == 'Control': self.start_selection_curve(event, SUBTRACT_FROM_SELECTION) if self.o.modkeys == 'Shift+Control': self.start_selection_curve(event, SUBTRACT_FROM_SELECTION) return def start_selection_curve(self, event, sense): """ Start a selection curve """ if self.freeView: return if self.Rubber: return self.selSense = sense # <selSense> is the type of selection. self.selCurve_length = 0.0 # <selCurve_length> is the current length (sum) of all the selection curve segments. self.drawingCookieSelCurve = True # <drawingCookieSelCurve> is used to let other methods know when # we are in the process of defining/drawing a selection curve, where: # True = in the process of defining selection curve # False = finished/not defining selection curve self.cookieQuat = Q(self.o.quat) ## Start color xor operations self.o.redrawGL = False glDisable(GL_DEPTH_TEST) glEnable(GL_COLOR_LOGIC_OP) glLogicOp(GL_XOR) if not self.selectionShape in ['DEFAULT', 'LASSO']: # Drawing one of the other selection shapes (not polygon-rubber-band or lasso). return if self.selectionShape == 'LASSO': self.defaultSelShape = SELSHAPE_LASSO selCurve_pt, selCurve_AreaPt = self._getPoints(event) # _getPoints() returns a pair (tuple) of points (Numeric arrays of x,y,z) # that lie under the mouse pointer, just beyond the near clipping plane # <selCurve_pt> and in the plane of the center of view <selCurve_AreaPt>. self.selCurve_List = [selCurve_pt] # <selCurve_List> contains the list of points used to draw the selection curve. The points lay in the # plane parallel to the screen, just beyond the front clipping plane, so that they are always # inside the clipping volume. self.o.selArea_List = [selCurve_AreaPt] # <selArea_List> contains the list of points that define the selection area. The points lay in # the plane parallel to the screen and pass through the center of the view. The list # is used by pickrect() and pickline() to make the selection. self.selCurve_StartPt = self.selCurve_PrevPt = selCurve_pt # <selCurve_StartPt> is the first point of the selection curve. It is used by # continue_selection_curve() to compute the net distance between it and the current # mouse position. # <selCurve_PrevPt> is the previous point of the selection curve. It is used by # continue_selection_curve() to compute the distance between the current mouse # position and the previous one. # Both <selCurve_StartPt> and <selCurve_PrevPt> are used by # basicMode.drawpick(). def continue_selection_curve(self, event): """ Add another segment to a selection curve for a lasso or polygon selection. """ if self.freeView: return if not self.drawingCookieSelCurve: return if self.Rubber: # Doing a poly-rubber-band selection. bareMotion() is updating the current rubber-band segment. return if not self.selectionShape in ['DEFAULT', 'LASSO']: return selCurve_pt, selCurve_AreaPt = self._getPoints(event) # The next point of the selection curve, where <selCurve_pt> is the point just beyond # the near clipping plane and <selCurve_AreaPt> is in the plane of the center of view. self.selCurve_List += [selCurve_pt] self.o.selArea_List += [selCurve_AreaPt] self.selCurve_length += vlen(selCurve_pt - self.selCurve_PrevPt) # add length of new line segment to <selCurve_length>. chord_length = vlen(selCurve_pt - self.selCurve_StartPt) # <chord_length> is the distance between the (first and last/current) endpoints of the # selection curve. if self.selectionShape == 'DEFAULT': if self.selCurve_length < 2 * chord_length: # Update the shape of the selection_curve. # The value of <defaultSelShape> can change back and forth between lasso and rectangle # as the user continues defining the selection curve. self.defaultSelShape = SELSHAPE_RECT else: self.defaultSelShape = SELSHAPE_LASSO self.selCurve_PrevPt = selCurve_pt env.history.statusbar_msg("Release left button to end selection; Press <Esc> key to cancel selection.") self.draw_selection_curve() def end_selection_curve(self, event): """ Close a selection curve and do the selection """ if self.freeView or not self.drawingCookieSelCurve: return selCurve_pt, selCurve_AreaPt = self._getPoints(event) if self.selCurve_length / self.o.scale < 0.03: #Rect_corner/circular selection if not self.selectionShape in ['DEFAULT', 'LASSO']: if not (self.selCurve_List and self.o.selArea_List): # The first click release self.selCurve_List = [selCurve_pt] self.selCurve_List += [selCurve_pt] self.selCurve_List += [selCurve_pt] self.o.selArea_List = [selCurve_AreaPt] self.o.selArea_List += [selCurve_AreaPt] if self.selectionShape == 'RECT_CORNER': self.defaultSelShape = SELSHAPE_RECT #Disable view changes when begin curve drawing self.propMgr.enableViewChanges(False) else: #The end click release self.o.selArea_List[-1] = selCurve_AreaPt if self.defaultSelShape == SELSHAPE_RECT: self._traditionalSelect() else: self._centerBasedSelect() elif self.selectionShape == 'DEFAULT': ##polygon-rubber-band/lasso selection self.selCurve_List += [selCurve_pt] self.o.selArea_List += [selCurve_AreaPt] if not self.Rubber: # The first click of a polygon selection. self.Rubber = True self.rubberWithoutMoving = True #Disable view changes when begin curve drawing self.propMgr.enableViewChanges(False) else: #This means single click/release without dragging for Lasso self.selCurve_List = [] self.o.selArea_List = [] self.drawingCookieSelCurve = False else: #Default(excluding rubber band)/Lasso selection self.selCurve_List += [selCurve_pt] self.o.selArea_List += [selCurve_AreaPt] self._traditionalSelect() def _anyMiddleUp(self): if self.freeView: return if self.cookieQuat: self.o.quat = Q(self.cookieQuat) self.o.gl_update() else: self.setOrientSurf(self.snap2trackball()) def middleDown(self, event): """ Disable this method when in curve drawing """ if not self.drawingCookieSelCurve: _superclass.middleDown(self, event) def middleUp(self, event): """ If self.cookieQuat: , which means: a shape object has been created, so if you change the view, and thus self.o.quat, then the shape object will be wrong ---Huaicai 3/23/05 """ if not self.drawingCookieSelCurve: _superclass.middleUp(self, event) self._anyMiddleUp() def middleCntlDown(self, event): """ Disable this action when cutting crystal. """ if self.freeView: _superclass.middleCntlDown(self, event) def middleCntlUp(self, event): """ Disable this action when cutting crystal. """ if self.freeView: _superclass.middleCntlUp(self, event) def Wheel(self, event): """ When in curve drawing stage, disable the zooming. """ if not self.drawingCookieSelCurve: _superclass.Wheel(self, event) def bareMotion(self, event): if self.freeView or not self.drawingCookieSelCurve: return False # False means not discarded [russ 080527] if self.Rubber or not self.selectionShape in ['DEFAULT', 'LASSO']: if not self.selCurve_List: return False p1, p2 = self._getPoints(event) try: if self.Rubber: self.pickLinePrev = self.selCurve_List[-1] else: self.selCurve_List[-2] = self.selCurve_List[-1] self.selCurve_List[-1] = p1 except: print self.selCurve_List if self.Rubber: self.rubberWithoutMoving = False env.history.statusbar_msg("Double click to end selection; Press <Esc> key to cancel selection.") else: env.history.statusbar_msg("Left click to end selection; Press <Esc> key to cancel selection.") self.draw_selection_curve() ######self.o.gl_update() return False def _afterCookieSelection(self): """ Restore some variable states after the each curve selection """ if self.selCurve_List: self.draw_selection_curve(True) self.drawingCookieSelCurve = False self.Rubber = False self.defaultSelShape = SELSHAPE_LASSO self.selCurve_List = [] self.o.selArea_List = [] env.history.statusbar_msg(" ") # Restore the cursor when the selection is done. self.update_cursor_for_no_MB() #Restore GL states self.o.redrawGL = True glDisable(GL_COLOR_LOGIC_OP) glEnable(GL_DEPTH_TEST) self.o.gl_update() return def _traditionalSelect(self): """ The original curve selection """ # Close the selection curve and selection area. self.selCurve_List += [self.selCurve_List[0]] self.o.selArea_List += [self.o.selArea_List[0]] # bruce 041213 comment: shape might already exist, from prior drags if not self.o.shape: self.o.shape = CrystalShape(self.o.right, self.o.up, self.o.lineOfSight, self.cookieDisplayMode, self.latticeType) self.propMgr.latticeCBox.setEnabled(False) self.propMgr.enableViewChanges(False) # took out kill-all-previous-curves code -- Josh if self.defaultSelShape == SELSHAPE_RECT: self.o.shape.pickrect(self.o.selArea_List[0], self.o.selArea_List[-2], self.o.pov, self.selSense, self.currentLayer, Slab(-self.o.pov, self.o.out, self.thickness)) else: self.o.shape.pickline(self.o.selArea_List, -self.o.pov, self.selSense, self.currentLayer, Slab(-self.o.pov, self.o.out, self.thickness)) if self.currentLayer < (self.MAX_LAYERS - 1) and self.currentLayer == len(self.layers) - 1: self.propMgr.addLayerButton.setEnabled(True) self._afterCookieSelection() return def _centerBasedSelect(self): """ Construct the right center based selection shape to generate the crystal. """ if not self.o.shape: self.o.shape = CrystalShape(self.o.right, self.o.up, self.o.lineOfSight, self.cookieDisplayMode, self.latticeType) self.propMgr.latticeCBox.setEnabled(False) self.propMgr.enableViewChanges(False) p1 = self.o.selArea_List[1] p0 = self.o.selArea_List[0] pt = p1 - p0 if self.selectionShape in ['RECTANGLE', 'DIAMOND']: hw = dot(self.o.right, pt)*self.o.right hh = dot(self.o.up, pt)*self.o.up if self.selectionShape == 'RECTANGLE': pt1 = p0 - hw + hh pt2 = p0 + hw - hh self.o.shape.pickrect(pt1, pt2, -self.o.pov, self.selSense, self.currentLayer, Slab(-self.o.pov, self.o.out, self.thickness)) elif self.selectionShape == 'DIAMOND': pp = [] pp += [p0 + hh]; pp += [p0 - hw] pp += [p0 - hh]; pp += [p0 + hw]; pp += [pp[0]] self.o.shape.pickline(pp, -self.o.pov, self.selSense, self.currentLayer, Slab(-self.o.pov, self.o.out, self.thickness)) elif self.selectionShape in ['HEXAGON', 'TRIANGLE', 'SQUARE']: if self.selectionShape == 'HEXAGON': sides = 6 elif self.selectionShape == 'TRIANGLE': sides = 3 elif self.selectionShape == 'SQUARE': sides = 4 hQ = Q(self.o.out, 2.0 * math.pi / sides) pp = [] pp += [p1] for ii in range(1, sides): pt = hQ.rot(pt) pp += [pt + p0] pp += [p1] self.o.shape.pickline(pp, -self.o.pov, self.selSense, self.currentLayer, Slab(-self.o.pov, self.o.out, self.thickness)) elif self.selectionShape == 'CIRCLE': self.o.shape.pickCircle(self.o.selArea_List, -self.o.pov, self.selSense, self.currentLayer, Slab(-self.o.pov, self.o.out, self.thickness)) if self.currentLayer < (self.MAX_LAYERS - 1) and self.currentLayer == len(self.layers) - 1: self.propMgr.addLayerButton.setEnabled(True) self._afterCookieSelection() return def _centerRectDiamDraw(self, color, pts, sType, lastDraw): """ Construct center based Rectange or Diamond to draw <Param> pts: (the center and a corner point) """ pt = pts[2] - pts[0] hw = dot(self.o.right, pt)*self.o.right hh = dot(self.o.up, pt)*self.o.up pp = [] if sType == 'RECTANGLE': pp = [pts[0] - hw + hh] pp += [pts[0] - hw - hh] pp += [pts[0] + hw - hh] pp += [pts[0] + hw + hh] elif sType == 'DIAMOND': pp += [pts[0] + hh]; pp += [pts[0] - hw] pp += [pts[0] - hh]; pp += [pts[0] + hw] if not self.lastDrawStored: self.lastDrawStored += [pp] self.lastDrawStored += [pp] self.lastDrawStored[0] = self.lastDrawStored[1] self.lastDrawStored[1] = pp if not lastDraw: drawLineLoop(color, self.lastDrawStored[0]) else: self.lastDrawStored = [] drawLineLoop(color, pp) return def _centerEquiPolyDraw(self, color, sides, pts, lastDraw): """ Construct a center based equilateral polygon to draw. <Param> sides: the number of sides for the polygon <Param> pts: (the center and a corner point) """ hQ = Q(self.o.out, 2.0 * math.pi / sides) pt = pts[2] - pts[0] pp = [] pp += [pts[2]] for ii in range(1, sides): pt = hQ.rot(pt) pp += [pt + pts[0]] if not self.lastDrawStored: self.lastDrawStored += [pp] self.lastDrawStored += [pp] self.lastDrawStored[0] = self.lastDrawStored[1] self.lastDrawStored[1] = pp if not lastDraw: drawLineLoop(color, self.lastDrawStored[0]) else: self.lastDrawStored = [] drawLineLoop(color, pp) return def _centerCircleDraw(self, color, pts, lastDraw): """ Construct center based hexagon to draw <Param> pts: (the center and a corner point) """ pt = pts[2] - pts[0] rad = vlen(pt) if not self.lastDrawStored: self.lastDrawStored += [rad] self.lastDrawStored += [rad] self.lastDrawStored[0] = self.lastDrawStored[1] self.lastDrawStored[1] = rad if not lastDraw: drawCircle(color, pts[0], self.lastDrawStored[0], self.o.out) else: self.lastDrawStored = [] drawCircle(color, pts[0], rad, self.o.out) return def _getXorColor(self, color): """ Get color for <color>. When the color is XORed with background color, it will get <color>. If background color is close to <color>, we'll use white color. """ bg = self.backgroundColor diff = vlen(A(color) - A(bg)) if diff < 0.5: return (1 - bg[0], 1 - bg[1], 1 - bg[2]) else: rgb = [] for ii in range(3): f = int(color[ii] * 255) b = int(bg[ii] * 255) rgb += [(f ^ b) / 255.0] return rgb def draw_selection_curve(self, lastDraw = False): """ Draw the selection curve. """ color = get_selCurve_color(self.selSense, self.backgroundColor) color = self._getXorColor(color) #& Needed since drawrectangle() in rectangle instance calls get_selCurve_color(), but can't supply bgcolor. #& This should be fixed. Later. mark 060212. if not self.selectionShape == 'DEFAULT': if self.selCurve_List: if self.selectionShape == 'LASSO': if not lastDraw: for pp in zip(self.selCurve_List[:-2],self.selCurve_List[1:-1]): drawline(color, pp[0], pp[1]) for pp in zip(self.selCurve_List[:-1],self.selCurve_List[1:]): drawline(color, pp[0], pp[1]) elif self.selectionShape == 'RECT_CORNER': if not lastDraw: drawrectangle(self.selCurve_List[0], self.selCurve_List[-2], self.o.up, self.o.right, color) drawrectangle(self.selCurve_List[0], self.selCurve_List[-1], self.o.up, self.o.right, color) else: xor_white = self._getXorColor(white) if not lastDraw: drawline(xor_white, self.selCurve_List[0], self.selCurve_List[1], True) drawline(xor_white, self.selCurve_List[0], self.selCurve_List[2], True) if self.selectionShape in ['RECTANGLE', 'DIAMOND']: self._centerRectDiamDraw(color, self.selCurve_List, self.selectionShape, lastDraw) elif self.selectionShape == 'CIRCLE': self._centerCircleDraw(color, self.selCurve_List, lastDraw) ###A work around for bug 727 ######self._centerEquiPolyDraw(color, 60, self.selCurve_List, lastDraw) elif self.selectionShape == 'HEXAGON': self._centerEquiPolyDraw(color, 6, self.selCurve_List, lastDraw) elif self.selectionShape == 'SQUARE': self._centerEquiPolyDraw(color, 4, self.selCurve_List, lastDraw) elif self.selectionShape == 'TRIANGLE': self._centerEquiPolyDraw(color, 3, self.selCurve_List, lastDraw) else: #Default selection shape if self.Rubber: if not lastDraw: drawline(color, self.selCurve_List[-2], self.pickLinePrev) drawline(color, self.selCurve_List[-2], self.selCurve_List[-1]) else: if not lastDraw: for pp in zip(self.selCurve_List[:-2],self.selCurve_List[1:-1]): drawline(color, pp[0], pp[1]) for pp in zip(self.selCurve_List[:-1],self.selCurve_List[1:]): drawline(color,pp[0],pp[1]) if self.defaultSelShape == SELSHAPE_RECT: # Draw the rectangle window if not lastDraw: drawrectangle(self.selCurve_List[0], self.selCurve_List[-2], self.o.up, self.o.right, color) drawrectangle(self.selCurve_List[0], self.selCurve_List[-1], self.o.up, self.o.right, color) glFlush() self.o.swapBuffers() #Update display return def Draw_model(self): _superclass.Draw_model(self) if self.showFullModel: self.o.assy.draw(self.o) return def Draw_other(self): _superclass.Draw_other(self) if self.gridShow: self.griddraw() if self.selCurve_List: ## XOR color operation doesn't request paintGL() call. self.draw_selection_curve() if self.o.shape: self.o.shape.draw(self.o, self.layerColors) return def Draw_after_highlighting(self, pickCheckOnly = False): """ Only draw translucent parts of the whole model when we are requested to draw the whole model. """ if self.showFullModel: return _superclass.Draw_after_highlighting(self, pickCheckOnly) return def griddraw(self): """ Assigned as griddraw for a diamond lattice grid that is fixed in space but cut out into a slab one nanometer thick parallel to the screen (and is equivalent to what the crystal-cutter will cut). """ # the grid is in modelspace but the clipping planes are in eyespace glPushMatrix() q = self.o.quat glTranslatef(-self.o.pov[0], -self.o.pov[1], -self.o.pov[2]) glRotatef(- q.angle * 180.0 / math.pi, q.x, q.y, q.z) glClipPlane(GL_CLIP_PLANE0, (0.0, 0.0, 1.0, 6.0)) glClipPlane(GL_CLIP_PLANE1, (0.0, 0.0, -1.0, 0.1)) glEnable(GL_CLIP_PLANE0) glEnable(GL_CLIP_PLANE1) glPopMatrix() glColor3fv(self.gridColor) drawGrid(1.5 * self.o.scale, -self.o.pov, self.latticeType) glDisable(GL_CLIP_PLANE0) glDisable(GL_CLIP_PLANE1) return def makeMenus(self): self.Menu_spec = [ ('Cancel', self.command_Cancel), ('Start Over', self.StartOver), ('Backup', self._Backup), ('Done', self.command_Done), # bruce 041217 #None, #('Add New Layer', self.addLayer), # bruce 041103 removed Copy, per Ninad email; # Josh says he might implement it for Alpha; # if/when he does, he can uncomment the following two lines. ## None, ## ('Copy', self.copy), ] def copy(self): print 'NYI' def addLayer(self): """ Add a new layer: the new layer will always be at the end """ if self.o.shape: lastLayerId = len(self.layers) - 1 pov = self.layers[lastLayerId] pov = V(pov[0], pov[1], pov[2]) pov -= self.o.shape.pushdown(lastLayerId) ## Make sure pushdown() doesn't return V(0,0,0) self.layers += [pov] size = len(self.layers) # Change the new layer as the current layer self.change2Layer(size - 1) return size # REVIEW: is return None in else case intended? def change2Layer(self, layerIndex): """ Change current layer to layer <layerIndex> """ if layerIndex == self.currentLayer: return assert layerIndex in range(len(self.layers)) pov = self.layers[layerIndex] self.currentLayer = layerIndex self.o.pov = V(pov[0], pov[1], pov[2]) maxCells = self._findMaxNoLattCell(self.currentLayer) self.propMgr.layerCellsSpinBox.setMaximum(maxCells) ##Cancel any selection if any. if self.drawingCookieSelCurve: env.history.message(redmsg("Layer changed during crystal shape creation, shape creation cancelled")) self._cancelSelection() self.o.gl_update() return def _findMaxNoLattCell(self, curLay): """ Find the possible max no of lattice cells for this layer """ if curLay == len(self.layers) - 1: return self.MAX_LATTICE_CELL else: depth = vlen(self.layers[curLay + 1] - self.layers[curLay]) num = int( depth/(drawing_globals.DiGridSp * sqrt(self.whichsurf + 1)) + 0.5) return num def setOrientSurf(self, num): """ Set the current view orientation surface to <num>, which can be one of values(0, 1, 2) representing 100, 110, 111 surface respectively. """ self.whichsurf = num self.setThickness(self.propMgr.layerCellsSpinBox.value()) button = self.propMgr.orientButtonGroup.button(self.whichsurf) button.setChecked(True) #self.w.statusBar().dispbarLabel.setText(button.toolTip()) #@ unnecessary. --Mark 2008-03-15 #bruce 080910 moved 5 snap* methods here from GLPane def snapquat100(self): self.snapquat(quats100) def snapquat110(self): self.snapquat(quats110) def snapquat111(self): self.snapquat(quats111) def snap2trackball(self): return self.snapquat(allQuats) def snapquat(self, qlist): glpane = self.glpane q1 = glpane.quat a = 1.1 what = 0 for q2, n in qlist: a2 = vlen((q2 - q1).axis) if a2 < a: a = a2 q = q2 what = n glpane.quat = Q(q) glpane.gl_update() return what def setThickness(self, num): self.thickness = num * drawing_globals.DiGridSp * sqrt(self.whichsurf + 1) s = "%3.3f Angstroms" % (self.thickness) self.propMgr.layerThicknessLineEdit.setText(s) def toggleFullModel(self, showFullModel): """ Turn on/off full model """ self.showFullModel = showFullModel self.o.gl_update() def _cancelSelection(self): """ Cancel selection before it's finished """ self._afterCookieSelection() if not self.o.shape: self.propMgr.enableViewChanges(True) return def changeLatticeType(self, lType): """ Change lattice type as 'lType'. """ self.latticeType = self.LATTICE_TYPES[lType] self.o.gl_update() def changeSelectionShape(self, newShape): if newShape != self.selectionShape: #Cancel current selection if any. Otherwise, it may cause #bugs like 587 if self.selCurve_List: ## env.history.message(redmsg("Current crystal shape creation cancelled as a different shape profile is selected. ")) self._cancelSelection() self.selectionShape = newShape def _project2Plane(self, pt): """ Project a 3d point <pt> into the plane parallel to screen and through "pov". Return the projected point. """ op = -self.o.pov np = self.o.lineOfSight v1 = op - pt v2 = dot(v1, np)*np vr = pt + v2 return vr def _snap100Grid(self, cellOrig, bLen, p2): """ Snap point <p2> to its nearest 100 surface grid point """ orig3d = self._project2Plane(cellOrig) out = self.o.out sqrt2 = 1.41421356 / 2 if abs(out[2]) > 0.5: rt0 = V(1, 0, 0) up0 = V(0,1, 0) right = V(sqrt2, -sqrt2, 0.0) up = V(sqrt2, sqrt2, 0.0) elif abs(out[0]) > 0.5: rt0 = V(0, 1, 0) up0 = V(0, 0, 1) right = V(0.0, sqrt2, -sqrt2) up = V(0.0, sqrt2, sqrt2) elif abs(out[1]) > 0.5: rt0 = V(0, 0, 1) up0 = V(1, 0, 0) right = V(-sqrt2, 0.0, sqrt2) up = V(sqrt2, 0.0, sqrt2) pt1 = p2 - orig3d pt = V(dot(rt0, pt1), dot(up0, pt1)) pt -= V(2 * bLen, 2 * bLen) pt1 = V(sqrt2 * pt[0]-sqrt2 * pt[1], sqrt2 * pt[0]+sqrt2 * pt[1]) dx = pt1[0] / (2 * sqrt2 * bLen) dy = pt1[1] / (2 * sqrt2 * bLen) if dx > 0: dx += 0.5 else: dx -= 0.5 ii = int(dx) if dy > 0: dy += 0.5 else: dy -= 0.5 jj = int(dy) nxy = orig3d + 4 * sqrt2 * bLen * up + ii * 2 * sqrt2 * bLen * right + jj * 2 * sqrt2 * bLen * up return nxy def _snap110Grid(self, offset, p2): """ Snap point <p2> to its nearest 110 surface grid point """ uLen = 0.87757241 DELTA = 0.0005 if abs(self.o.out[1]) < DELTA: #Looking between X-Z if self.o.out[2] * self.o.out[0] < 0: vType = 0 right = V(1, 0, 1) up = V(0, 1, 0) rt = V(1, 0, 0) else: vType = 2 if self.o.out[2] < 0: right = V(-1, 0, 1) up = V(0, 1, 0) rt = V(0, 0, 1) else: right = V(1, 0, -1) up = V(0, 1, 0) rt = V(1, 0, 0) elif abs(self.o.out[0]) < DELTA: # Looking between Y-Z if self.o.out[1] * self.o.out[2] < 0: vType = 0 right = V(0, 1, 1) up = V(1, 0, 0) rt = V(0, 0, 1) else: vType = 2 if self.o.out[2] > 0: right = V(0, -1, 1) up = V(1, 0, 0) rt = V(0, 0, 1) else: right = V(0, 1, -1) up = V(1, 0, 0) rt = V(0, 1, 0) elif abs(self.o.out[2]) < DELTA: # Looking between X-Y if self.o.out[0] * self.o.out[1] < 0: vType = 0 right = V(1, 1, 0) up = V(0, 0, 1) rt = (1, 0, 0) else: vType = 2 if self.o.out[0] < 0: right = V(1, -1 , 0) up = V(0, 0, 1) rt = (1, 0, 0) else: right = V(-1, 1, 0) up = V(0, 0, 1) rt = V(0, 1, 0) else: ##Sth wrong raise ValueError, self.o.out orig3d = self._project2Plane(offset) p2 -= orig3d pt = V(dot(rt, p2), dot(up, p2)) if vType == 0: ## projected orig-point is at the corner if pt[1] < uLen: uv1 = [[0,0], [1,1], [2, 0], [3, 1], [4, 0]] ij = self._findSnap4Corners(uv1, uLen, pt) elif pt[1] < 2 * uLen: if pt[0] < 2 * uLen: if pt[1] < 1.5 * uLen: ij = [1, 1] else: ij = [1, 2] else: if pt[1] < 1.5 * uLen: ij = [3, 1] else: ij = [3, 2] elif pt[1] < 3 * uLen: uv1 = [[0,3], [1,2], [2,3], [3, 2], [4, 3]] ij = self._findSnap4Corners(uv1, uLen, pt) else: if pt[1] < 3.5 * uLen: j = 3 else: j = 4 if pt[0] < uLen: i = 0 elif pt[0] < 3 * uLen: i = 2 else: i = 4 ij = [i, j] elif vType == 2: ## projected orig-point is in the middle if pt[1] < uLen: if pt[1] < 0.5 * uLen: j = 0 else: j = 1 if pt[0] < -1 * uLen: i = -2 elif pt[0] < uLen: i = 0 else: i = 2 ij = [i, j] elif pt[1] < 2 * uLen: uv1 = [[-2, 1], [-1, 2], [0, 1], [1, 2], [2, 1]] ij = self._findSnap4Corners(uv1, uLen, pt) elif pt[1] < 3 * uLen: if pt[1] < 2.5 * uLen: j = 2 else: j = 3 if pt[0] < 0: i = -1 else: i = 1 ij = [i, j] else: uv1 = [[-2, 4], [-1, 3], [0, 4], [1, 3], [2, 4]] ij = self._findSnap4Corners(uv1, uLen, pt) nxy = orig3d + ij[0] * uLen * right + ij[1] * uLen * up return nxy def _getNCartP2d(self, ax1, ay1, pt): """ Axis <ax> and <ay> is not perpendicular, so we project pt to axis <ax> or <ay> by parallel to <ay> or <ax>. The returned 2d coordinates are not cartesian coordinates """ ax = norm(ax1) ay = norm(ay1) try: lx = (ay[1] * pt[0] - ay[0] * pt[1]) / (ax[0] * ay[1] - ay[0] * ax[1]) ly = (ax[1] * pt[0] - ax[0] * pt[1]) / (ax[1] * ay[0] - ax[0] * ay[1]) except ZeroDivisionError: print " In _getNCartP2d() of BuildCrystal_Command.py, divide-by-zero detected." return None return V(lx, ly) def _snap111Grid(self, offset, p2): """ Snap point <p2> to its nearest 111 surface grid point """ DELTA = 0.00005 uLen = 0.58504827 sqrt6 = sqrt(6) orig3d = self._project2Plane(V(0, 0,0)) p2 -= orig3d if (self.o.out[0] > 0 and self.o.out[1] > 0 and self.o.out[2] > 0) or \ (self.o.out[0] < 0 and self.o.out[1] < 0 and self.o.out[2] < 0): axy =[V(1, 1, -2), V(-1, 2, -1), V(-2, 1, 1), V(-1, -1, 2), V(1, -2, 1), V(2, -1, -1), V(1, 1, -2)] elif (self.o.out[0] < 0 and self.o.out[1] < 0 and self.o.out[2] > 0) or \ (self.o.out[0] > 0 and self.o.out[1] > 0 and self.o.out[2] < 0): axy =[V(1, -2, -1), V(2, -1, 1), V(1, 1, 2), V(-1, 2, 1), V(-2, 1, -1), V(-1, -1, -2), V(1, -2, -1)] elif (self.o.out[0] < 0 and self.o.out[1] > 0 and self.o.out[2] > 0) or \ (self.o.out[0] > 0 and self.o.out[1] < 0 and self.o.out[2] < 0): axy =[V(2, 1, 1), V(1, 2, -1), V(-1, 1, -2), V(-2, -1, -1), V(-1, -2, 1), V(1, -1, 2), V(2, 1, 1)] elif (self.o.out[0] > 0 and self.o.out[1] < 0 and self.o.out[2] > 0) or \ (self.o.out[0] < 0 and self.o.out[1] > 0 and self.o.out[2] < 0): axy =[V(-1, -2, -1), V(1, -1, -2), V(2, 1, -1), V(1, 2, 1), V(-1, 1, 2), V(-2, -1, 1), V(-1, -2, -1)] vlen_p2 = vlen(p2) if vlen_p2 < DELTA: ax = axy[0] ay = axy[1] else: for ii in range(size(axy) -1): cos_theta = dot(axy[ii], p2) / (vlen(axy[ii]) * vlen_p2) ## the 2 vectors has an angle > 60 degrees if cos_theta < 0.5: continue cos_theta = dot(axy[ii + 1], p2) / (vlen(axy[ii + 1]) * vlen_p2) if cos_theta > 0.5: ax = axy[ii] ay = axy[ii + 1] break p2d = self._getNCartP2d(ax, ay, p2) i = intRound(p2d[0] / uLen / sqrt6) j = intRound(p2d[1] / uLen / sqrt6) nxy = orig3d + i * uLen * ax + j * uLen * ay return nxy def _findSnap4Corners(self, uv1, uLen, pt, vLen = None): """ Compute distance from point <pt> to corners and select the nearest corner. """ if not vLen: vLen = uLen hd = 0.5 * sqrt(uLen * uLen + vLen * vLen) ix = int(floor(pt[0] / uLen)) - uv1[0][0] if ix == -1: ix = 0 elif ix == (len(uv1) - 1): ix = len(uv1) - 2 elif ix < -1 or ix >= len(uv1): raise ValueError, (uv1, pt, uLen, ix) dist = vlen(V(uv1[ix][0] * uLen, uv1[ix][1] * vLen) - pt) if dist < hd: return uv1[ix] else: return uv1[ix + 1] def _getPoints(self, event): """ This method is used to get the points in near clipping plane and pov plane which are in line with the mouse clicking point on the screen plane. Adjust these 2 points if self.snapGrid == True. <event> is the mouse event. Return a tuple of those 2 points. """ p1, p2 = self.o.mousepoints(event, 0.01) # For each curve, the following value is constant, so it could be # optimized by saving it to the curve object. vlen_p1p2 = vlen(p1 - p2) if not self.gridSnap: return p1, p2 else: # Snap selection point to grid point cellOrig, uLen = findCell(p2, self.latticeType) if self.whichsurf == 0: p2 = self._snap100Grid(cellOrig, uLen, p2) elif self.whichsurf == 1: p2 = self._snap110Grid(cellOrig, p2) else: p2 = self._snap111Grid(cellOrig, p2) return p2 + vlen_p1p2 * self.o.out, p2 pass # end of class BuildCrystal_Command # == helper functions def hashAtomPos(pos): return int(dot(V(1000000, 1000,1), floor(pos * 1.2))) # end
NanoCAD-master
cad/src/commands/BuildCrystal/BuildCrystal_Command.py
# Copyright 2005-2008 Nanorex, Inc. See LICENSE file for details. """ BuildCrystal_PropertyManager.py Class used for the GUI controls for the BuildCrystal_Command. @version: $Id$ @copyright: 2005-2008 Nanorex, Inc. See LICENSE file for details. History: Note: Till Alpha8, this command was called Cookie Cutter mode. In Alpha9 it has been renamed to 'Build Crystal' mode. -- ninad 20070511 Ninad 2008-08-22: - renamed class CookieCntrlPanel to BuildCrystal_PropertyManager,also deleted the old CookiePropertyManager.py - major cleanup: moved flyout toolbar related code in its own class (see Ui_BuildCrystalFlyout); moved command specific code in the command class. """ from PyQt4.Qt import SIGNAL from PyQt4.Qt import QString from PyQt4.Qt import QColor from PyQt4.Qt import QColorDialog from commands.BuildCrystal.Ui_BuildCrystal_PropertyManager import Ui_BuildCrystal_PropertyManager _superclass = Ui_BuildCrystal_PropertyManager class BuildCrystal_PropertyManager(Ui_BuildCrystal_PropertyManager): def __init__(self, command): """ """ _superclass.__init__(self, command) msg = "Choose one of the selection shapes from the command toolbar. "\ "When drawing a <b>Polygon</b> shape, double-click to select the final vertex." self.updateMessage(msg = msg) def connect_or_disconnect_signals(self, isConnect): """ Connect signal to slots """ if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect change_connect(self.latticeCBox, SIGNAL("activated ( int )"), self.changeLatticeType) change_connect(self.orientButtonGroup, SIGNAL("buttonClicked(int)"), self.changeGridOrientation) change_connect(self.rotGridAntiClockwiseButton, SIGNAL("clicked()"), self.antiRotateView) change_connect(self.rotGridClockwiseButton, SIGNAL("clicked()"), self.rotateView) change_connect(self.addLayerButton,SIGNAL("clicked()"), self.addLayer) change_connect(self.currentLayerComboBox,SIGNAL("activated(int)"), self.changeLayer) change_connect(self.layerCellsSpinBox,SIGNAL("valueChanged(int)"), self.setThickness) #change_connect(self.gridColorButton,SIGNAL("clicked()"),self.changeGridColor) change_connect(self.gridLineCheckBox,SIGNAL("toggled(bool)"), self.showGridLine) change_connect(self.freeViewCheckBox,SIGNAL("toggled(bool)"), self.setFreeView) change_connect(self.fullModelCheckBox, SIGNAL("toggled(bool)"), self.toggleFullModel) change_connect(self.snapGridCheckBox, SIGNAL("toggled(bool)"), self.setGridSnap) change_connect(self.dispModeComboBox, SIGNAL("activated(const QString &)"), self.changeDispMode) def show(self): """ This is used to initialize GUI items which need to change every time the command becomes active. """ _superclass.show(self) self.latticeCBox.setEnabled(True) # Other things that have been lost at this point: # self.layerThicknessLineEdit self.layerCellsSpinBox.setValue(2) self.rotateGridByAngleSpinBox.setValue(45) self.currentLayerComboBox.clear() self.currentLayerComboBox.addItem("1") #QString(str(len(self.layers[0])))) ? ? ? self.addLayerButton.setEnabled(False) def close(self): """ Restore GUI items when exiting from the PM (command). """ _superclass.close(self) # Enable all those view options self.enableViewChanges(True) def enableViewChanges(self, enableFlag): """Turn on or off view changes depending on <param> 'enableFlag'. Turn off view changes is needed during the crystal-cutting stage. """ for c in self.orientButtonGroup.buttons(): c.setEnabled(enableFlag) self.rotateGridByAngleSpinBox.setEnabled(enableFlag) self.rotGridAntiClockwiseButton.setEnabled(enableFlag) self.rotGridClockwiseButton.setEnabled(enableFlag) self.w.enableViews(enableFlag) # Mark 051122. def changeSelectionShape(self, action): """Slot method that is called when user changes selection shape by GUI. """ command = self.command if not command.isCurrentCommand(): # [bruce 071008] return sShape = action.objectName() command.changeSelectionShape(sShape) return def setThickness(self, value): self.command.setThickness(value) def addLayer(self): self.addLayerButton.setEnabled(False) layerId = self.command.addLayer() self.currentLayerComboBox.addItem(QString(str(layerId))) self.currentLayerComboBox.setCurrentIndex(layerId-1) self.w.glpane.gl_update() def changeLayer(self, value): """Change current layer to <value> layer """ self.command.change2Layer(value) def setFreeView(self, freeView): """Slot function to switch between free view/crystal selection states """ self.command.setFreeView(freeView) def toggleFullModel(self, showFullModel): """Slot function for the check box of 'Full Model' in crystal-cutter dashboard """ self.command.toggleFullModel(showFullModel) def showGridLine(self, show): """Slot function""" self.command.showGridLine(show) def setGridSnap(self, snap): """Turn on/off the grid snap option """ self.command.gridSnap = snap pass def changeGridColor(self): """ Open the stand color chooser dialog to change grid line color """ c = QColorDialog.getColor(QColor(222,148,0), self) if c.isValid(): self.gridColorLabel.setPaletteBackgroundColor(c) self.command.setGridLineColor(c) def changeLatticeType(self, lType): self.command.changeLatticeType(lType) if lType != 0: #Changes to other lattice type #Disable the snap to grid feature self.setGridSnap(False) self.snapGridCheckBox.setEnabled(False) else: self.snapGridCheckBox.setEnabled(True) def changeDispMode(self, display_style): self.command.changeDispMode(display_style) def changeGridOrientation(self, value): if value == 0: self._orient100() elif value == 1: self._orient110() elif value == 2: self._orient111() def _rotView(self, direction): """ Rotate the view anti-clockwise or clockWise. If <direction> == True, anti-clockwise rotate, otherwise, clockwise rotate """ from math import pi from geometry.VQT import Q, V angle = self.rotateGridByAngleSpinBox.value() if not direction: angle = -angle angle = pi * angle/180.0 glpane = self.w.glpane glpane.quat += Q(V(0, 0, 1), angle) glpane.gl_update() def antiRotateView(self): """ Anti-clockwise rotatation """ self._rotView(True) def rotateView(self): """ clock-wise rotation """ self._rotView(False) def _orient100(self): """ Along one axis """ self.command.setOrientSurf(0) self.command.snapquat100() def _orient110(self): """ halfway between two axes """ self.command.setOrientSurf(1) self.command.snapquat110() def _orient111(self): """ equidistant from three axes """ self.command.setOrientSurf(2) self.command.snapquat111() pass # end
NanoCAD-master
cad/src/commands/BuildCrystal/BuildCrystal_PropertyManager.py
NanoCAD-master
cad/src/commands/BuildCrystal/__init__.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ CrystalShape.py -- handle freehand curves for crystal-cutting (?) @author: Huaicai, maybe others @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: bruce 071215 split class CrystalShape out of shape.py into its own module. Module classification: Contains graphics_behavior and operations and perhaps internal transient model code, all to help the graphics_mode (and command?) for Build Crystal (presently an unsplit_mode, BuildCrystal_Command). So the overall classification is not clear -- for now say "command" since nothing less does all the above. But it'll end up in a package for Build Crystal, so this might be ok. [bruce 071215] Note about cleaning up how this uses ColorSortedDisplayList [bruce 090114]: * it allocates one, and sometimes draws it in the usual ColorSorter.start/finish manner, other times uses glCallList on its .dl directly, and other times directly compiles its own OpenGL code into its .dl member. * part of this could be converted into CSDL.draw() calls, but the direct compiling of our own OpenGL code into a display list kept in the CSDL is not a formally supported use of the CSDL, and it won't necessarily keep working with CSDL.draw() (once we're using batched shader primitives for any primitives we draw here). Either we should add that kind of feature to the CSDL API (let any CSDL contain one or more optional "extra display lists for arbitrary outside use, to be drawn whenever that CSDL is drawn"), or fix this in some other way. * Until then, this code may stop drawing properly when batched shader primitives are fully implemented, and its use of .dl may become the only reason we need to keep that member around in CSDL. """ from Numeric import dot, floor from geometry.VQT import vlen, V from OpenGL.GL import glNewList, glEndList, glCallList from OpenGL.GL import GL_COMPILE_AND_EXECUTE from graphics.drawing.drawers import drawCircle from graphics.drawing.drawers import genDiam from graphics.drawing.CS_draw_primitives import drawcylinder from graphics.drawing.CS_draw_primitives import drawsphere from graphics.drawing.CS_draw_primitives import drawline from graphics.drawing.ColorSorter import ColorSorter from graphics.drawing.ColorSortedDisplayList import ColorSortedDisplayList from utilities.constants import SUBTRACT_FROM_SELECTION from utilities.constants import OUTSIDE_SUBTRACT_FROM_SELECTION from utilities.constants import ADD_TO_SELECTION from utilities.constants import START_NEW_SELECTION from utilities.constants import white from utilities.debug import print_compact_traceback from geometry.BoundingBox import BBox from graphics.behaviors.shape import simple_shape_2d from graphics.behaviors.shape import get_selCurve_color from graphics.behaviors.shape import shape from model.bonds import bond_atoms # == class _Circle(simple_shape_2d): """ Represents the area of a circle ortho projection intersecting with a slab. """ def __init__(self, shp, ptlist, origin, selSense, **opts): """ <Param> ptlist: the circle center and a point on the perimeter """ simple_shape_2d.__init__( self, shp, ptlist, origin, selSense, opts) def draw(self): """ the profile circle draw """ color = get_selCurve_color(self.selSense) drawCircle(color, self.ptlist[0], self.rad, self.slab.normal) def isin(self, pt): """ Test if a point is in the area """ if self.slab and not self.slab.isin(pt): return False p2d = self.project_2d(pt) dist = vlen(p2d - self.cirCenter) if dist <= self.rad : return True else: return False def _computeBBox(self): """ Construct the 3D bounding box for this volume. """ self.rad = vlen(self.ptlist[1] - self.ptlist[0]) self.cirCenter = self.project_2d(self.ptlist[0]) bbhi = self.cirCenter + V(self.rad, self.rad) bblo = self.cirCenter - V(self.rad, self.rad) x, y = self.right, self.up self.bbox = BBox(V(bblo, bbhi), V(x, y), self.slab) pass # == class CrystalShape(shape): """ This class is used to create cookies. It supports multiple parallel layers, each curve sits on a particular layer. """ def __init__(self, right, up, normal, mode, latticeType): shape.__init__(self, right, up, normal) # Each element is a dictionary object storing "carbon" info for a layer self.carbonPosDict = {} self.hedroPosDict = {} self.markedAtoms = {} # Each element is a dictionary for the bonds info for a layer self.bondLayers = {} self.displist = ColorSortedDisplayList() self.havelist = 0 self.dispMode = mode self.latticeType = latticeType self.layerThickness = {} self.layeredCurves = {} # A list of (merged bb, curves) for each layer def pushdown(self, lastLayer): """ Put down one layer from last layer """ th, n = self.layerThickness[lastLayer] #print "th, n", th, n return th * n def _saveMaxThickness(self, layer, thickness, normal): if layer not in self.layerThickness: self.layerThickness[layer] = (thickness, normal) elif thickness > self.layerThickness[layer][0]: self.layerThickness[layer] = (thickness, normal) def isin(self, pt, curves = None): """ returns 1 if <pt> is properly enclosed by the curves. """ #& To do: docstring needs to be updated. mark 060211. # bruce 041214 comment: this might be a good place to exclude points # which are too close to the screen to be drawn. Not sure if this # place would be sufficient (other methods call c.isin too). # Not done yet. ###e val = 0 if not curves: curves = self.curves for c in curves: if c.selSense == START_NEW_SELECTION or c.selSense == ADD_TO_SELECTION: val = val or c.isin(pt) elif c.selSense == OUTSIDE_SUBTRACT_FROM_SELECTION: val = val and c.isin(pt) elif c.selSense == SUBTRACT_FROM_SELECTION: val = val and not c.isin(pt) return val def pickCircle(self, ptlist, origin, selSense, layer, slabC): """ Add a new circle to the shape. """ c = _Circle(self, ptlist, origin, selSense, slab = slabC) self._saveMaxThickness(layer, slabC.thickness, slabC.normal) self._cutCookie(layer, c) self._addCurve(layer, c) def pickline(self, ptlist, origin, selSense, layer, slabC): """ Add a new curve to the shape. Args define the curve (see curve) and the selSense operator for the curve telling whether it adds or removes material. """ # Review: does "(see curve)" in this docstring # refer to class curve in shape.py, # which is not used in this module which was split from shape.py? # If not, what does it mean? # [bruce 071215 question] c = shape.pickline(self, ptlist, origin, selSense, slab = slabC) self._saveMaxThickness(layer, slabC.thickness, slabC.normal) self._cutCookie(layer, c) self._addCurve(layer, c) def pickrect(self, pt1, pt2, org, selSense, layer, slabC): """ Add a new rectangle to the shape. Args define the rectangle and the selSense operator for the curve telling whether it adds or removes material. """ c = shape.pickrect(self, pt1, pt2, org, selSense, slab = slabC) self._saveMaxThickness(layer, slabC.thickness, slabC.normal) self._cutCookie(layer, c) self._addCurve(layer, c) def _updateBBox(self, curveList): """ Recompute the bounding box for the list of curves """ bbox = BBox() for c in curveList[1:]: bbox.merge(c.bbox) curveList[0] = bbox def undo(self, currentLayer): """ This would work for shapes, if anyone called it. """ if self.layeredCurves.has_key(currentLayer): curves = self.layeredCurves[currentLayer] if len(curves) > 1: curves = curves[:-1] self._updateBBox(curves) self.layeredCurves[currentLayer] = curves ##Kludge to make the undo work. self.carbonPosDict[currentLayer] = {} self.hedroPosDict[currentLayer] = {} self.bondLayers[currentLayer] = {} for c in curves[1:]: self._cutCookie(currentLayer, c) self.havelist = 0 def clear(self, currentLayer): """ This would work for shapes, if anyone called it. """ curves = self.layeredCurves[currentLayer] curves = [] self.layeredCurves[currentLayer] = curves self.havelist = 0 def anyCurvesLeft(self): """ Return True if there are curve(s) left, otherwise, False. This can be used by user to decide if the shape object can be deleted. """ for cbs in self.layeredCurves.values(): if len(cbs) > 1: return True return False def combineLayers(self): """ """ # Experimental code to add all curves and bbox together # to make the molmake working. It may be removed later. for cbs in self.layeredCurves.values(): if cbs: self.bbox.merge(cbs[0]) self.curves += cbs[1:] def _hashAtomPos(self, pos): return int(dot(V(1000000, 1000, 1), floor(pos * 1.2))) def _addCurve(self, layer, c): """ Add curve into its own layer, update the bbox """ self.havelist = 0 if not layer in self.layeredCurves: bbox = BBox() self.layeredCurves[layer] = [bbox, c] else: self.layeredCurves[layer] += [c] self.layeredCurves[layer][0].merge(c.bbox) def _cellDraw(self, color, p0, p1): hasSinglet = False if type(p1) == type((1,)): v1 = p1[0] hasSinglet = True else: v1 = p1 if self.dispMode == 'Tubes': drawcylinder(color, p0, v1, 0.2) else: drawsphere(color, p0, 0.5, 1) if hasSinglet: drawsphere(color, v1, 0.2, 1) else: drawsphere(color, v1, 0.5, 1) drawline(white, p0, v1) def _anotherDraw(self, layerColor): """ The original way of selecting cookies, but do it layer by layer, so we can control how to display each layer. """ if self.havelist: glCallList(self.displist.dl) return glNewList(self.displist.dl, GL_COMPILE_AND_EXECUTE) for layer in self.layeredCurves.keys(): bbox = self.layeredCurves[layer][0] curves = self.layeredCurves[layer][1:] if not curves: continue color = layerColor[layer] for c in curves: c.draw() try: bblo, bbhi = bbox.data[1], bbox.data[0] allCells = genDiam(bblo - 1.6, bbhi + 1.6, self.latticeType) for cell in allCells: for pp in cell: p1 = p2 = None if self.isin(pp[0], curves): if self.isin(pp[1], curves): p1 = pp[0]; p2 = pp[1] else: p1 = pp[0]; p2 = ((pp[1]+pp[0])/2, ) elif self.isin(pp[1], curves): p1 = pp[1]; p2 = ((pp[1]+pp[0])/2, ) if p1 and p2: self._cellDraw(color, p1, p2) except: # bruce 041028 -- protect against exceptions while making display # list, or OpenGL will be left in an unusable state (due to the lack # of a matching glEndList) in which any subsequent glNewList is an # invalid operation. (Also done in chem.py; see more comments there.) print_compact_traceback( "bug: exception in shape.draw's displist; ignored: ") glEndList() self.havelist = 1 # return def _cutCookie(self, layer, c): """ For each user defined curve, cut the crystal for it, store carbon postion into a global dictionary, store the bond information into each layer. """ self.havelist = 0 bblo, bbhi = c.bbox.data[1], c.bbox.data[0] #Without +(-) 1.6, crystal for lonsdaileite may not be right allCells = genDiam(bblo - 1.6, bbhi + 1.6, self.latticeType) if self.carbonPosDict.has_key(layer): carbons = self.carbonPosDict[layer] else: carbons = {} if self.hedroPosDict.has_key(layer): hedrons = self.hedroPosDict[layer] else: hedrons = {} if c.selSense == SUBTRACT_FROM_SELECTION: markedAtoms = self.markedAtoms if not self.bondLayers or not self.bondLayers.has_key(layer): return else: bonds = self.bondLayers[layer] for cell in allCells: for pp in cell: ppInside = [False, False] for ii in range(2): if c.isin(pp[ii]): ppInside[ii] = True if ppInside[0] or ppInside[1]: self._logic0Bond(carbons, bonds, markedAtoms, hedrons, ppInside, pp) self. _removeMarkedAtoms(bonds, markedAtoms, carbons, hedrons) elif c.selSense == OUTSIDE_SUBTRACT_FROM_SELECTION: #& This differs from the standard selection scheme for Shift + Drag. mark 060211. #& This is marked for removal. mark 060320. if not self.bondLayers or not self.bondLayers.has_key(layer): return bonds = self.bondLayers[layer] newBonds = {}; newCarbons = {}; newHedrons = {}; insideAtoms = {} newStorage = (newBonds, newCarbons, newHedrons) for cell in allCells: for pp in cell: pph = [None, None] for ii in range(2): if c.isin(pp[ii]): pph[ii] = self._hashAtomPos(pp[ii]) if bonds.has_key(pph[ii]): insideAtoms[pph[ii]] = pp[ii] if (not pph[0]) and pph[1] and carbons.has_key(pph[1]): pph[0] = self._hashAtomPos(pp[0]) if bonds.has_key(pph[0]): newCarbons[pph[1]] = pp[1] newHedrons[pph[0]] = pp[0] if not newBonds.has_key(pph[0]): newBonds[pph[0]] = [(pph[1], 1)] else: newBonds[pph[0]] += [(pph[1], 1)] if insideAtoms: self._logic2Bond(carbons, bonds, hedrons, insideAtoms, newStorage) bonds, carbons, hedrons = newStorage elif c.selSense == ADD_TO_SELECTION: if self.bondLayers.has_key(layer): bonds = self.bondLayers[layer] else: bonds = {} for cell in allCells: for pp in cell: pph=[None, None] ppInside = [False, False] for ii in range(2): pph[ii] = self._hashAtomPos(pp[ii]) if c.isin(pp[ii]): ppInside[ii] = True if ppInside[0] or ppInside[1]: self._logic1Bond(carbons, hedrons, bonds, pp, pph, ppInside) elif c.selSense == START_NEW_SELECTION: # Added to make crystal cutter selection behavior # consistent when no modkeys pressed. mark 060320. carbons = {} bonds = {} hedrons = {} for cell in allCells: for pp in cell: pph = [None, None] ppInside = [False, False] for ii in range(2): pph[ii] = self._hashAtomPos(pp[ii]) if c.isin(pp[ii]): ppInside[ii] = True if ppInside[0] or ppInside[1]: self._logic1Bond(carbons, hedrons, bonds, pp, pph, ppInside) self.bondLayers[layer] = bonds self.carbonPosDict[layer] = carbons self.hedroPosDict[layer] = hedrons #print "bonds", bonds self.havelist = 1 return def _logic0Bond(self, carbons, bonds, markedAtoms, hedrons, ppInside, pp): """ For each pair of points<pp[0], pp[1]>, if both points are inside the curve and are existed carbons, delete the bond, and mark the 'should be' removed atoms. Otherwise, delete half bond or change full to half bond accoringly. """ def _deleteHalfBond(which_in): """ Internal function: when the value-- carbon atom is removed from an half bond, delete the half bond. """ markedAtoms[pph[which_in]] = pp[which_in] try: values = bonds[pph[0]] values.remove((pph[1], which_in)) bonds[pph[0]] = values if len(values) == 0: del bonds[pph[0]] #print "Delete half bond: ", pph[0], (pph[1], which_in) except: print "No such half bond: ", pph[0], (pph[1], which_in) def _changeFull2Half(del_id, which_in): """ internal function: If there is a full bond and when the value (2nd in a bond pair) carbon atom is removed, change it to half bond """ if not hedrons.has_key(pph[del_id]): hedrons[pph[del_id]] = pp[del_id] markedAtoms[pph[del_id]] = pp[del_id] if bonds.has_key(pph[0]): values = bonds[pph[0]] idex = values.index(pph[1]) values[idex] = (pph[1], which_in) bonds[pph[0]] = values ## print "Change full to half bond: ", pph[0], (pph[1], which_in) pph = [] pph += [self._hashAtomPos(pp[0])] pph += [self._hashAtomPos(pp[1])] if ppInside[0] and ppInside[1]: # Delete full bond if carbons.has_key(pph[0]) and carbons.has_key(pph[1]): markedAtoms[pph[0]] = pp[0] markedAtoms[pph[1]] = pp[1] values = bonds[pph[0]] values.remove(pph[1]) bonds[pph[0]] = values if len(values) == 0: del bonds[pph[0]] # Delete half bond elif carbons.has_key(pph[0]): #markedAtoms[pph[0]] = pp[0] _deleteHalfBond(0) # Delete half bond elif carbons.has_key(pph[1]): _deleteHalfBond(1) elif ppInside[0]: # Full bond becomes half bond, carbon becomes hedron if carbons.has_key(pph[0]) and carbons.has_key(pph[1]): markedAtoms[pph[0]] = pp[0] #_changeFull2Half(0, 1) # Delete half bond elif carbons.has_key(pph[0]): #markedAtoms[pph[0]] = pp[0] _deleteHalfBond(0) elif ppInside[1]: # Full bond becomes half bond, carbon becomes hedron if carbons.has_key(pph[1]) and carbons.has_key(pph[0]): _changeFull2Half(1, 0) # Delete half bond elif carbons.has_key(pph[1]): _deleteHalfBond(1) def _logic1Bond(self, carbons, hedrons, bonds, pp, pph, ppInside): """ For each pair of points <pp[0], pp[1]>, create a full bond if necessary and if both points are inside the curve ; otherwise, if one point is in while the other is not, create a half bond if necessary. """ if ppInside[0] and ppInside[1]: if (not pph[0] in carbons) and (not pph[1] in carbons): if pph[0] in hedrons: del hedrons[pph[0]] if pph[1] in hedrons: del hedrons[pph[1]] carbons[pph[0]] = pp[0] carbons[pph[1]] = pp[1] # create a new full bond self._createBond(bonds, pph[0], pph[1], -1, True) elif not pph[0] in carbons: if pph[0] in hedrons: del hedrons[pph[0]] carbons[pph[0]] = pp[0] # update half bond to full bond self._changeHf2FullBond(bonds, pph[0], pph[1], 1) elif not pph[1] in carbons: if pph[1] in hedrons: del hedrons[pph[1]] carbons[pph[1]] = pp[1] # update half bond to full bond self._changeHf2FullBond(bonds, pph[0], pph[1], 0) # create full bond else: self._createBond(bonds, pph[0], pph[1]) elif ppInside[0]: if (not pph[0] in carbons) and (not pph[1] in carbons): if pph[0] in hedrons: del hedrons[pph[0]] carbons[pph[0]] = pp[0] if not pph[1] in hedrons: hedrons[pph[1]] = pp[1] # create new half bond self._createBond(bonds, pph[0], pph[1], 0, True) elif not pph[0] in carbons: if pph[0] in hedrons: del hedrons[pph[0]] carbons[pph[0]] = pp[0] #update half bond to full bond self._changeHf2FullBond(bonds, pph[0], pph[1], 1) elif not pph[1] in carbons: if not pph[1] in hedrons: hedrons[pph[1]] = pp[1] # create half bond, with 0 in, 1 out self._createBond(bonds, pph[0], pph[1], 0) # create full bond else: self._createBond(bonds, pph[0], pph[1]) elif ppInside[1]: if (not pph[0] in carbons) and (not pph[1] in carbons): if pph[1] in hedrons: del hedrons[pph[1]] carbons[pph[1]] = pp[1] if not pph[0] in hedrons: hedrons[pph[0]] = pp[0] # create new half bond, with 1 in, 0 out self._createBond(bonds, pph[0], pph[1], 1, True) elif not pph[0] in carbons: if not pph[0] in hedrons: hedrons[pph[0]] = pp[0] # create half bond, with 1 in, 0 out self._createBond(bonds, pph[0], pph[1], 1) elif not pph[1] in carbons: if pph[1] in hedrons: del hedrons[pph[1]] carbons[pph[1]] = pp[1] # update half bond to full bond self._changeHf2FullBond(bonds, pph[0], pph[1], 0) # create full bond else: self._createBond(bonds, pph[0], pph[1]) return def _logic2Bond(self, carbons, bonds, hedrons, insideAtoms, newStorage): """ Processing all bonds having key inside the current selection curve. For a bond with the key outside, the value inside the selection curve, we deal with it when we scan the edges of each cell. To make sure no such bonds are lost, we need to enlarge the bounding box at least 1 lattice cell. """ newBonds, newCarbons, newHedrons = newStorage for a in insideAtoms.keys(): values = bonds[a] newValues = [] # The key <a> is carbon: if carbons.has_key(a): if not newCarbons.has_key(a): newCarbons[a] = insideAtoms[a] for b in values: if type(b) == type(1): #Full bond # If the carbon inside, keep the bond if insideAtoms.has_key(b): if not newCarbons.has_key(b): newCarbons[b] = insideAtoms[b] newValues += [b] else: # outside carbon, change it to h-bond if not newHedrons.has_key(b): newHedrons[b] = carbons[b] newValues += [(b, 0)] else: # Half bond, keep it if insideAtoms.has_key(b[0]): p = insideAtoms[b[0]] elif hedrons.has_key(b[0]): p = hedrons[b[0]] else: raise ValueError, (a, b[0]) if not newHedrons.has_key(b[0]): newHedrons[b[0]] = p newValues += [b] else: # The key <a> is not a carbon if not newHedrons.has_key(a): newHedrons[a] = insideAtoms[a] for b in values: # Inside h-bond, keep it if insideAtoms.has_key(b[0]): if not newHedrons.has_key(b[0]): newHedrons[b[0]] = insideAtoms[b[0]] newValues += [b] if newValues: newBonds[a] = newValues def _removeMarkedAtoms(self, bonds, markedAtoms, carbons, hedrons): """ Remove all carbons that should have been removed because of the new selection curve. Update bonds that have the carbon as key. For a bond who has the carbon as its value, we'll leave them as they are, untill the draw() call. When it finds a value of a bond can't find its carbon position, either remove the bond if it was a half bond or change it to half bond if it was full bond, and find its carbon position in markedAtoms{} """ for ph in markedAtoms.keys(): if carbons.has_key(ph): ## print "Remove carbon: ", ph if bonds.has_key(ph): values = bonds[ph] for b in values[:]: if type(b) == type(1): idex = values.index(b) values[idex] = (b, 1) ## print "Post processing: Change full to half bond: ", ph, values[idex] else: values.remove(b) ## print "Erase half bond:", ph, b # commented out. Mark 060205. bonds[ph] = values if len(values) == 0: del bonds[ph] else: hedrons[ph] = carbons[ph] del carbons[ph] def _changeHf2FullBond(self, bonds, key, value, which_in): """ If there is a half bond, change it to full bond. Otherwise, create a new full bond. <which_in>: the atom which exists before. """ foundHalfBond = False if bonds.has_key(key): values = bonds[key] for ii in range(len(values)): if type(values[ii]) == type((1, 1)) and values[ii][0] == value: values[ii] = value foundHalfBond = True break if not foundHalfBond: values += [value] ## bonds[key] = values elif not bonds.has_key(key): bonds[key] = [value] def _createBond(self, dict, key, value, half_in = -1, new_bond = False): """ Create a new bond if <new_bond> is True. Otherwise, search if there is such a full/half bond, change it appropriately if found. Otherwise, create a new bond. If <half_in> == -1, it's a full bond; otherwise, it means a half bond with the atom of <half_in> is inside. """ if not key in dict: if half_in < 0: dict[key] = [value] else: dict[key] = [(value, half_in)] else: values = dict[key] if half_in < 0: if new_bond: values += [value] else: found = False for ii in range(len(values)): if type(values[ii]) == type(1): if value == values[ii]: found = True break elif value == values[ii][0]: values[ii] = value found = True break if not found: values += [value] else: if new_bond: values +=[(value, half_in)] else: try: idex = values.index((value, half_in)) except: values += [(value, half_in)] dict[key] = values def changeDisplayMode(self, mode): self.dispMode = mode self.havelist = 0 def _bondDraw(self, color, p0, p1, carbonAt): if self.dispMode == 'Tubes': drawcylinder(color, p0, p1, 0.2) else: if carbonAt < 0: drawsphere(color, p0, 0.5, 1) drawsphere(color, p1, 0.5, 1) elif carbonAt == 0: drawsphere(color, p0, 0.5, 1) drawsphere(color, p1, 0.2, 1) elif carbonAt == 1: drawsphere(color, p0, 0.2, 1) drawsphere(color, p1, 0.5, 1) drawline(white, p0, p1) def draw(self, glpane, layerColor): """ Draw the shape. Find the bounding box for the curve and check the position of each carbon atom in a lattice would occupy for being 'in' the shape. A tube representation of the atoms thus selected is saved as a GL call list for fast drawing. This method is only for crystal-cutter mode. --Huaicai """ #bruce 090220 renamed first arg from win to glpane (which is what # was actually passed) and used it in ColorSorter.start (required now). if 0: self._anotherDraw(layerColor) return markedAtoms = self.markedAtoms if self.havelist: glCallList(self.displist.dl) return #russ 080225: Moved glNewList into ColorSorter.start for displist re-org. #russ 080225: displist side effect allocates a ColorSortedDisplayList. ColorSorter.start(glpane, self.displist) # grantham 20051205 try: for layer, bonds in self.bondLayers.items(): color = layerColor[layer] self.layeredCurves[layer][-1].draw() bonds = self.bondLayers[layer] carbons = self.carbonPosDict[layer] hedrons = self.hedroPosDict[layer] for cK, bList in bonds.items(): if carbons.has_key(cK): p0 = carbons[cK] for b in bList[:]: carbonAt = -1 if type(b) == type(1): #Full bond if carbons.has_key(b): p1 = carbons[b] else: #which means the carbon was removed p1 = markedAtoms[b] #print "Carbon was removed: ", b, p1 idex = bList.index(b) bList[idex] = (b, 0) hedrons[b] = p1 p1 = (p0 + p1) / 2.0 carbonAt = 0 else: #Half bond carbonAt = b[1] if b[1]: if carbons.has_key(b[0]): # otherwise, means the carbon has been removed. p1 = carbons[b[0]] if hedrons.has_key(cK): p0 = hedrons[cK] p0 = (p0 + p1) / 2.0 else: #half bond becomes full bond because of new selection p0 = carbons[cK] idex = bList.index(b) bList[idex] = b[0] else: # remove the half bond bList.remove(b) #print "delete half bond: (%d: " %cK, b if len(bList) == 0: del bonds[cK] break continue else: if hedrons.has_key(b[0]): p1 = hedrons[b[0]] p1 = (p0 + p1) / 2.0 else: # Which means half bond becomes full bond because of new selection p1 = carbons[b[0]] idex = bList.index(b) bList[idex] = b[0] self._bondDraw(color, p0, p1, carbonAt) bonds[cK] = bList except: # bruce 041028 -- protect against exceptions while making display # list, or OpenGL will be left in an unusable state (due to the lack # of a matching glEndList) in which any subsequent glNewList is an # invalid operation. (Also done in chem.py; see more comments there.) print "cK: ", cK print_compact_traceback( "bug: exception in shape.draw's displist; ignored: ") self.markedAtoms = {} ColorSorter.finish(draw_now = True) self.havelist = 1 # always set this flag, even if exception happened. def buildChunk(self, assy): """ Build Chunk for the cookies. First, combine bonds from all layers together, which may fuse some half bonds to full bonds. """ from model.chunk import Chunk from model.chem import Atom from utilities.constants import gensym numLayers = len(self.bondLayers) if numLayers: allBonds = {} allCarbons = {} #Copy the bonds, carbons and hedron from the first layer for ii in range(numLayers): if self.bondLayers.has_key(ii): for bKey, bValue in self.bondLayers[ii].items(): allBonds[bKey] = bValue del self.bondLayers[ii] break for carbons in self.carbonPosDict.values(): for cKey, cValue in carbons.items(): allCarbons[cKey] = cValue for hedrons in self.hedroPosDict.values(): for hKey, hValue in hedrons.items(): allCarbons[hKey] = hValue for bonds in self.bondLayers.values(): for bKey, bValues in bonds.items(): if bKey in allBonds: existValues = allBonds[bKey] for bValue in bValues: if type(bValue) == type((1, 1)): if bValue[1]: ctValue = (bValue[0], 0) else: ctValue = (bValue[0], 1) if ctValue in existValues: idex = existValues.index(ctValue) existValues[idex] = bValue[0] else: existValues += [bValue] else: existValues += [bValue] allBonds[bKey] = existValues else: allBonds[bKey] = bValues #print "allbonds: ", allBonds #print "allCarbons: ", allCarbons carbonAtoms = {} mol = Chunk(assy, gensym("Crystal", assy)) for bKey, bBonds in allBonds.items(): keyHedron = True if len(bBonds): for bond in bBonds: if keyHedron: if type(bBonds[0]) == type(1) or (not bBonds[0][1]): if not bKey in carbonAtoms: keyAtom = Atom("C", allCarbons[bKey], mol) carbonAtoms[bKey] = keyAtom else: keyAtom = carbonAtoms[bKey] keyHedron = False if keyHedron: if type(bond) != type((1, 1)): raise ValueError, (bKey, bond, bBonds) else: xp = (allCarbons[bKey] + allCarbons[bond[0]])/2.0 keyAtom = Atom("X", xp, mol) if type(bond) == type(1) or bond[1]: if type(bond) == type(1): bvKey = bond else: bvKey = bond[0] if not bvKey in carbonAtoms: bondAtom = Atom("C", allCarbons[bvKey], mol) carbonAtoms[bvKey] = bondAtom else: bondAtom = carbonAtoms[bvKey] else: xp = (allCarbons[bKey] + allCarbons[bond[0]])/2.0 bondAtom = Atom("X", xp, mol) bond_atoms(keyAtom, bondAtom) if len(mol.atoms) > 0: #bruce 050222 comment: much of this is not needed, since mol.pick() does it. # Note: this method is similar to one in BuildCrystal_Command.py. assy.addmol(mol) assy.unpickall_in_GLPane() # was unpickparts; not sure _in_GLPane is best (or that # this is needed at all) [bruce 060721] mol.pick() assy.mt.mt_update() return # from buildChunk pass # end of class CrystalShape # end
NanoCAD-master
cad/src/commands/BuildCrystal/CrystalShape.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ Ui_BuildCrystal_PropertyManager.py @author: Ninad @version:$Id$ UI file for Crystal Property Manager. e.g. UI for groupboxes (and its contents), button rows etc. History: - These options appeared in formerly 'cookie cutter dashboard' till Alpha8 - Post Alpha8 (sometime after 12/2006), the options were included in the BuildCrystal_PropertyManager (formerly Cookie Property Manager. ) - In Alpha 9 , 'Cookie Cutter' was renamed to 'Build Crystal' ninad 2007-09-10: Rewrote this class to make it use PM module classes. Ninad 2008-08-23: Renamed Ui_CookiePropertyManager to Ui_BuildCrystal_PropertyManager """ from PyQt4.Qt import Qt from PyQt4.Qt import QSize from PM.PM_GroupBox import PM_GroupBox from PM.PM_CheckBox import PM_CheckBox from PM.PM_ComboBox import PM_ComboBox from PM.PM_SpinBox import PM_SpinBox from PM.PM_PushButton import PM_PushButton from PM.PM_ToolButtonRow import PM_ToolButtonRow from PM.PM_LineEdit import PM_LineEdit from PM.PM_WidgetRow import PM_WidgetRow from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from PM.PM_Constants import PM_CANCEL_BUTTON from utilities.icon_utilities import geticon from command_support.Command_PropertyManager import Command_PropertyManager _superclass = Command_PropertyManager class Ui_BuildCrystal_PropertyManager(Command_PropertyManager): """ The Ui_BuildCrystal_PropertyManager class defines UI elements for the Property Manager of the B{Crystal mode}. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ # <title> - the title that appears in the property manager header. title = "Build Crystal" # <iconPath> - full path to PNG file that appears in the header. # The name of this Property Manager. This will be set to # the name of the PM_Dialog object via setObjectName(). pmName = title iconPath = "ui/actions/Tools/Build Structures/Build Crystal.png" def __init__(self, command): """ Constructor for the B{Crystal} property manager class that defines its UI. @param command: The parent mode where this Property Manager is used @type command: L{BuildCrystal_Command} """ _superclass.__init__(self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_WHATS_THIS_BUTTON) def _addGroupBoxes(self): """ Add various group boxes to the Property manager. """ self._addCrystalSpecsGroupbox() self._addLayerPropertiesGroupBox() self._addDisplayOptionsGroupBox() self._addAdvancedOptionsGroupBox() def _addCrystalSpecsGroupbox(self): """ Add 'Crystal groupbox' to the PM """ self.crystalSpecsGroupBox = \ PM_GroupBox(self, title = "Crystal Specifications") self._loadCrystalSpecsGroupBox(self.crystalSpecsGroupBox) def _addLayerPropertiesGroupBox(self): """ Add 'Layer Properties' groupbox to the PM """ self.layerPropertiesGroupBox = \ PM_GroupBox(self, title = "Layer Properties") self._loadLayerPropertiesGroupBox(self.layerPropertiesGroupBox) def _addAdvancedOptionsGroupBox(self): """ Add 'Advanced Options' groupbox """ self.advancedOptionsGroupBox = \ PM_GroupBox( self, title = "Advanced Options" ) self._loadAdvancedOptionsGroupBox(self.advancedOptionsGroupBox) def _addDisplayOptionsGroupBox(self): """ Add 'Display Options' groupbox """ self.displayOptionsGroupBox = PM_GroupBox(self, title = 'Display Options') self._loadDisplayOptionsGroupBox(self.displayOptionsGroupBox) def _loadCrystalSpecsGroupBox(self, inPmGroupBox): """ Load widgets in the Crystal Specifications group box. @param inPmGroupBox: The Crystal Specifications groupbox in the PM @type inPmGroupBox: L{PM_GroupBox} """ latticeChoices = ["Diamond", "Lonsdaleite"] self.latticeCBox = \ PM_ComboBox( inPmGroupBox, label = 'Lattice:', labelColumn = 0, choices = latticeChoices, index = 0, setAsDefault = True, spanWidth = False ) # Button list to create a toolbutton row. # Format: # - buttonType, # - buttonId, # - buttonText , # - iconPath # - tooltip # - shortcut # - column BUTTON_LIST = [ ( "QToolButton", 0, "Surface 100", "ui/actions/Properties Manager/Surface100.png", "Surface 100", "", 0), ( "QToolButton", 1, "Surface 110", "ui/actions/Properties Manager/Surface110.png", "Surface 110", "", 1), ( "QToolButton", 2, "Surface 111", "ui/actions/Properties Manager/Surface111.png", "Surface 110", "", 2) ] self.gridOrientationButtonRow = \ PM_ToolButtonRow(inPmGroupBox, title = "", label = "Orientation:", buttonList = BUTTON_LIST, checkedId = 0, setAsDefault = True, spanWidth = False ) self.orientButtonGroup = self.gridOrientationButtonRow.buttonGroup self.surface100_btn = self.gridOrientationButtonRow.getButtonById(0) self.surface110_btn = self.gridOrientationButtonRow.getButtonById(1) self.surface111_btn = self.gridOrientationButtonRow.getButtonById(2) self.rotateGridByAngleSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Rotate by: ", labelColumn = 0, value = 45, minimum = 0, maximum = 360, singleStep = 5, suffix = " degrees") GRID_ANGLE_BUTTONS = [ ("QToolButton", 0, "Anticlockwise", "ui/actions/Properties Manager/rotate_minus.png", "", "+", 0 ), ( "QToolButton", 1, "Clockwise", "ui/actions/Properties Manager/rotate_plus.png", "", "-", 1 ) ] self.gridRotateButtonRow = \ PM_ToolButtonRow( inPmGroupBox, title = "", buttonList = GRID_ANGLE_BUTTONS, label = 'Rotate grid:', isAutoRaise = False, isCheckable = False ) self.rotGridAntiClockwiseButton = \ self.gridRotateButtonRow.getButtonById(0) self.rotGridClockwiseButton = \ self.gridRotateButtonRow.getButtonById(1) def _loadLayerPropertiesGroupBox(self, inPmGroupBox): """ Load widgets in the Layer Properties group box. @param inPmGroupBox: The Layer Properties groupbox in the PM @type inPmGroupBox: L{PM_GroupBox} """ self.currentLayerComboBox = \ PM_ComboBox( inPmGroupBox, index = 0, spanWidth = True ) self.addLayerButton = PM_PushButton(inPmGroupBox) self.addLayerButton.setIcon( geticon('ui/actions/Properties Manager/addlayer.png')) self.addLayerButton.setFixedSize(QSize(26, 26)) self.addLayerButton.setIconSize(QSize(22, 22)) # A widget list to create a widget row. # Format: # - Widget type, # - widget object, # - column firstRowWidgetList = [('PM_ComboBox', self.currentLayerComboBox, 1), ('PM_PushButton', self.addLayerButton, 2) ] widgetRow = PM_WidgetRow(inPmGroupBox, title = '', widgetList = firstRowWidgetList, label = "Layer:", labelColumn = 0, ) self.layerCellsSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Lattice cells:", labelColumn = 0, value = 2, minimum = 1, maximum = 25 ) self.layerThicknessLineEdit = PM_LineEdit(inPmGroupBox, label = "Thickness:", text = "", setAsDefault = False, spanWidth = False ) #self.layerThicknessLineEdit.setReadOnly(True) self.layerThicknessLineEdit.setDisabled(True) tooltip = "Thickness of layer in Angstroms" self.layerThicknessLineEdit.setToolTip(tooltip) def _loadAdvancedOptionsGroupBox(self, inPmGroupBox): """ Load widgets in the Advanced Options group box. @param inPmGroupBox: The Advanced Options box in the PM @type inPmGroupBox: L{PM_GroupBox} """ self.snapGridCheckBox = \ PM_CheckBox(inPmGroupBox, text = "Snap to grid", state = Qt.Checked ) tooltip = "Snap selection point to a nearest cell grid point." self.snapGridCheckBox.setToolTip(tooltip) self.freeViewCheckBox = \ PM_CheckBox(inPmGroupBox, text = "Enable free view", state = Qt.Unchecked ) def _loadDisplayOptionsGroupBox(self, inPmGroupBox): """ Load widgets in the Display Options groupbox. @param inPmGroupBox: The Display Options groupbox @type inPmGroupBox: L{PM_GroupBox} """ displayChoices = ['Tubes', 'Spheres'] self.dispModeComboBox = \ PM_ComboBox( inPmGroupBox, label = 'Display style:', choices = displayChoices, index = 0, setAsDefault = False, spanWidth = False ) self.gridLineCheckBox = PM_CheckBox(inPmGroupBox, text = "Show grid lines", widgetColumn = 0, state = Qt.Checked) self.fullModelCheckBox = PM_CheckBox(inPmGroupBox, text = "Show model", widgetColumn = 0, state = Qt.Unchecked) def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. @note: Many PM widgets are still missing their "What's This" text. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_CookiePropertyManager whatsThis_CookiePropertyManager(self) def _addToolTipText(self): """ What's Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_CookiePropertyManager ToolTip_CookiePropertyManager(self)
NanoCAD-master
cad/src/commands/BuildCrystal/Ui_BuildCrystal_PropertyManager.py
NanoCAD-master
cad/src/commands/GroupProperties/__init__.py
# -*- coding: utf-8 -*- # Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. # Form implementation generated from reading ui file 'GroupPropDialog.ui' # # Created: Wed Sep 20 07:22:13 2006 # by: PyQt4 UI code generator 4.0.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_GroupPropDialog(object): def setupUi(self, GroupPropDialog): GroupPropDialog.setObjectName("GroupPropDialog") GroupPropDialog.resize(QtCore.QSize(QtCore.QRect(0,0,258,357).size()).expandedTo(GroupPropDialog.minimumSizeHint())) self.gridlayout = QtGui.QGridLayout(GroupPropDialog) self.gridlayout.setMargin(11) self.gridlayout.setSpacing(6) self.gridlayout.setObjectName("gridlayout") self.vboxlayout = QtGui.QVBoxLayout() self.vboxlayout.setMargin(0) self.vboxlayout.setSpacing(6) self.vboxlayout.setObjectName("vboxlayout") self.hboxlayout = QtGui.QHBoxLayout() self.hboxlayout.setMargin(0) self.hboxlayout.setSpacing(6) self.hboxlayout.setObjectName("hboxlayout") self.nameLabel = QtGui.QLabel(GroupPropDialog) self.nameLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.nameLabel.setObjectName("nameLabel") self.hboxlayout.addWidget(self.nameLabel) self.nameLineEdit = QtGui.QLineEdit(GroupPropDialog) self.nameLineEdit.setFocusPolicy(QtCore.Qt.StrongFocus) self.nameLineEdit.setAlignment(QtCore.Qt.AlignLeading) self.nameLineEdit.setObjectName("nameLineEdit") self.hboxlayout.addWidget(self.nameLineEdit) self.vboxlayout.addLayout(self.hboxlayout) self.mmpformatLabel = QtGui.QLabel(GroupPropDialog) self.mmpformatLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.mmpformatLabel.setObjectName("mmpformatLabel") self.vboxlayout.addWidget(self.mmpformatLabel) self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setMargin(0) self.hboxlayout1.setSpacing(6) self.hboxlayout1.setObjectName("hboxlayout1") self.statsView = QtGui.QListWidget(GroupPropDialog) self.statsView.setFocusPolicy(QtCore.Qt.NoFocus) self.statsView.setObjectName("statsView") self.hboxlayout1.addWidget(self.statsView) self.vboxlayout.addLayout(self.hboxlayout1) self.gridlayout.addLayout(self.vboxlayout,0,0,1,1) spacerItem = QtGui.QSpacerItem(20,16,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Expanding) self.gridlayout.addItem(spacerItem,1,0,1,1) self.hboxlayout2 = QtGui.QHBoxLayout() self.hboxlayout2.setMargin(0) self.hboxlayout2.setSpacing(6) self.hboxlayout2.setObjectName("hboxlayout2") self.okPushButton = QtGui.QPushButton(GroupPropDialog) self.okPushButton.setAutoDefault(True) self.okPushButton.setDefault(True) self.okPushButton.setObjectName("okPushButton") self.hboxlayout2.addWidget(self.okPushButton) self.cancelPushButton = QtGui.QPushButton(GroupPropDialog) self.cancelPushButton.setAutoDefault(True) self.cancelPushButton.setDefault(False) self.cancelPushButton.setObjectName("cancelPushButton") self.hboxlayout2.addWidget(self.cancelPushButton) self.gridlayout.addLayout(self.hboxlayout2,2,0,1,1) self.retranslateUi(GroupPropDialog) QtCore.QObject.connect(self.okPushButton,QtCore.SIGNAL("clicked()"),GroupPropDialog.accept) QtCore.QObject.connect(self.cancelPushButton,QtCore.SIGNAL("clicked()"),GroupPropDialog.reject) QtCore.QMetaObject.connectSlotsByName(GroupPropDialog) GroupPropDialog.setTabOrder(self.nameLineEdit,self.okPushButton) GroupPropDialog.setTabOrder(self.okPushButton,self.cancelPushButton) GroupPropDialog.setTabOrder(self.cancelPushButton,self.statsView) def retranslateUi(self, GroupPropDialog): GroupPropDialog.setWindowTitle(QtGui.QApplication.translate("GroupPropDialog", "Group Properties", None, QtGui.QApplication.UnicodeUTF8)) GroupPropDialog.setWindowIcon(QtGui.QIcon("ui/border/GroupProp")) self.nameLabel.setText(QtGui.QApplication.translate("GroupPropDialog", "Name:", None, QtGui.QApplication.UnicodeUTF8)) self.mmpformatLabel.setText(QtGui.QApplication.translate("GroupPropDialog", "Group Statistics:", None, QtGui.QApplication.UnicodeUTF8)) self.okPushButton.setText(QtGui.QApplication.translate("GroupPropDialog", "&OK", None, QtGui.QApplication.UnicodeUTF8)) self.okPushButton.setShortcut(QtGui.QApplication.translate("GroupPropDialog", "Alt+O", None, QtGui.QApplication.UnicodeUTF8)) self.cancelPushButton.setText(QtGui.QApplication.translate("GroupPropDialog", "&Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.cancelPushButton.setShortcut(QtGui.QApplication.translate("GroupPropDialog", "Alt+C", None, QtGui.QApplication.UnicodeUTF8))
NanoCAD-master
cad/src/commands/GroupProperties/GroupPropDialog.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GroupProp.py $Id$ """ import sys from PyQt4.Qt import QDialog, QListWidgetItem, SIGNAL from commands.GroupProperties.GroupPropDialog import Ui_GroupPropDialog from geometry.VQT import V class Statistics: def __init__(self, group): # Get statistics of group. group.init_statistics(self) group.getstatistics(self) def display(self, statsView): """ Display the statistics in the listview widget 'statsView' """ # Subtract singlets from total number of atoms self.num_atoms = self.natoms - self.nsinglets item = QListWidgetItem() item.setText("Measure Dihedral:" + str(self.num_mdihedral)) statsView.addItem(item) item = QListWidgetItem() item.setText("Measure Angle:" + str(self.num_mangle)) statsView.addItem(item) item = QListWidgetItem() item.setText("Measure Distance:" + str(self.num_mdistance)) statsView.addItem(item) item = QListWidgetItem() item.setText("Grid Plane:" + str(self.num_gridplane)) statsView.addItem(item) item = QListWidgetItem() item.setText("ESP Image:" + str(self.num_espimage)) statsView.addItem(item) item = QListWidgetItem() if sys.platform == "win32": item.setText("PC GAMESS:" + str(self.ngamess)) else: item.setText("GAMESS:" + str(self.ngamess)) statsView.addItem(item) item = QListWidgetItem() item.setText("Thermometers:" + str(self.nthermos)) statsView.addItem(item) item = QListWidgetItem() item.setText("Thermostats:" + str(self.nstats)) statsView.addItem(item) item = QListWidgetItem() item.setText("Anchors:" + str(self.nanchors)) statsView.addItem(item) item = QListWidgetItem() item.setText("Linear Motors:" + str(self.nlmotors)) statsView.addItem(item) item = QListWidgetItem() item.setText("Rotary Motors:" + str(self.nrmotors)) statsView.addItem(item) item = QListWidgetItem() item.setText("Groups:" + str(self.ngroups)) statsView.addItem(item) item = QListWidgetItem() item.setText("Bondpoints:" + str(self.nsinglets)) statsView.addItem(item) item = QListWidgetItem() item.setText("Atoms:" + str(self.num_atoms)) statsView.addItem(item) item = QListWidgetItem() item.setText("Chunks:" + str(self.nchunks)) statsView.addItem(item) class GroupProp(QDialog, Ui_GroupPropDialog): def __init__(self, group): QDialog.__init__(self) self.setupUi(self) self.connect(self.okPushButton,SIGNAL("clicked()"),self.accept) self.connect(self.cancelPushButton,SIGNAL("clicked()"),self.reject) self.group = group self.nameLineEdit.setText(group.name) # Get statistics of group and display them in the statView widget. stats = Statistics(group) stats.display(self.statsView) ################# # Cancel Button ################# def reject(self): QDialog.reject(self) ################# # OK Button ################# def accept(self): self.group.try_rename(self.nameLineEdit.text()) QDialog.accept(self)
NanoCAD-master
cad/src/commands/GroupProperties/GroupProp.py
NanoCAD-master
cad/src/commands/SelectChunks/__init__.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ SelectChunks_GraphicsMode.py The GraphicsMode part of the SelectChunks_Command. It provides the graphicsMode object for its Command class. The GraphicsMode class defines anything related to the *3D Graphics Area* -- For example: - Anything related to graphics (Draw method), - Mouse events - Cursors, - Key bindings or context menu @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. TODO: - Items mentioned in Select_GraphicsMode.py - Other items listed in Select_Command.py History: Ninad & Bruce 2007-12-13: Created new Command and GraphicsMode classes from the old class selectChunksMode and moved the GraphicsMode related methods into this class from selectChunksMode.py """ from PyQt4.Qt import QMouseEvent import foundation.env as env from model.bonds import Bond from model.chem import Atom from commands.Select.Select_GraphicsMode import DRAG_STICKINESS_LIMIT from model.chunk import Chunk from OpenGL.GL import glCallList from utilities.debug import print_compact_traceback, print_compact_stack from utilities.constants import orange, ave_colors, red from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.prefs_constants import mouseWheelTimeoutInterval_prefs_key from utilities.debug_prefs import debug_pref, Choice_boolean_True from utilities import debug_flags from geometry.VQT import V, vlen import time from commands.Select.Select_GraphicsMode import Select_basicGraphicsMode from utilities.GlobalPreferences import DEBUG_BAREMOTION _superclass = Select_basicGraphicsMode class SelectChunks_basicGraphicsMode(Select_basicGraphicsMode): """ """ #A list of movables that will be moved while dragging. #@seeself.getMovablesForLeftDragging() _leftDrag_movables = [] def Enter_GraphicsMode(self): """ Things needed while entering the GraphicsMode (e.g. updating cursor, setting some attributes etc). This method is called in self.command.command_entered() """ _superclass.Enter_GraphicsMode(self) #also calls self.reset_drag_vars() #etc self.o.assy.selectChunksWithSelAtoms_noupdate() # josh 10/7 to avoid race in assy init def leftDouble(self, event): """ Handles LMB doubleclick event. @see:self.chunkLeftDouble() """ self.ignore_next_leftUp_event = True if not self.obj_doubleclicked: return #this is a temporary fix for NFR bug 2569. 'Selectconnected chunks not #implemented yet if self.cursor_over_when_LMB_pressed == 'Empty Space': return chunk = None #Select neighboring DnaSegments if isinstance(self.obj_doubleclicked, Chunk): chunk = self.obj_doubleclicked elif isinstance(self.obj_doubleclicked, Atom): chunk = self.obj_doubleclicked.molecule elif isinstance(self.obj_doubleclicked, Bond): atm1 = self.obj_doubleclicked.atom1 atm2 = self.obj_doubleclicked.atom2 #@TODO" For now (2008-04-11, it considers only the chunk of a single #atom (and not atm2.molecule) chunk = atm1.molecule if chunk: self.chunkLeftDouble(chunk, event) return def chunkLeftDouble(self, chunk, event): """ Select the connected chunks Note: For Rattlesnake, the implementation is limited for DnaStrands and DnaSegment. See the following methods to know what it selects/ deselects @see: ops_select_Mixin.expandDnaComponentSelection() @see: ops_select_Mixin.contractDnaComponentSelection() @see: ops_select_Mixin._expandDnaStrandSelection() @see:ops_select_Mixin._contractDnaStrandSelection() @see: ops_select_Mixin._contractDnaSegmentSelection() @see: DnaStrand.get_DnaStrandChunks_sharing_basepairs() @see: DnaSegment.get_DnaSegments_reachable_thru_crossovers() @see: NFR bug 2749 for details. """ if self.selection_locked(): return if not isinstance(chunk, Chunk): return if chunk.isNullChunk(): #The chunk might have got deleted (during first leftUp operation #before it calls leftDouble-- Reason: it might have got deleted #during first leftUp of a Shift + Control double click. #When the chunk is killed, its treated as a _nullMol_Chunk before #the next update. For rattlesnake release, we don't support #delete connected on chunks so return from the left double. return dnaStrandOrSegment = chunk.parent_node_of_class(self.win.assy.DnaStrandOrSegment) if dnaStrandOrSegment: if self.o.modkeys == 'Control': self.win.assy.contractDnaComponentSelection(dnaStrandOrSegment) elif self.o.modkeys == 'Shift+Control': #Deleting conneced dna components not supported for Rattlesnake #release pass else: self.win.assy.expandDnaComponentSelection(dnaStrandOrSegment) else: #Selecting / deselecting / deleting connected regular chunks is not #supported for Rattlesnke release if self.o.modkeys == 'Control': pass ##self.o.assy.unselectConnected( [ chunk ] ) elif self.o.modkeys == 'Shift+Control': #Deleting conneced chunks not supported for Rattlesnake #release pass else: pass ##self.o.assy.selectConnected( [ chunk ] ) return def selectConnectedChunks(self): """ TODO: Not implemented yet. Need to define a method in ops_select to do this """ pass def rightShiftDown(self, event): _superclass.rightShiftDown(self, event) def rightCntlDown(self, event): _superclass.rightCntlDown(self, event) # Chunk selection helper methods. def atomLeftDown(self, a, event): """ Left down on an atom or a singlet(bondpoint) @param a: Atom or singlet @type a: Atom or singlet @param event: QMouseLeftDown event """ m = a.molecule #chunkLeftDown in turn calls self.objectSetUp().. self.chunkLeftDown(m, event) def atomLeftUp(self, a, event): """ Real atom <a> was clicked, so select, unselect or delete ITS CHUNK based on the current modkey. - If no modkey is pressed, clear the selection and pick atom's chunk <m>. - If Shift is pressed, pick <m>, adding it to the current selection. - If Ctrl is pressed, unpick <m>, removing it from the current selection. - If Shift+Control (Delete) is pressed, delete atom <m>. """ m = a.molecule #Don't know if deallocate_bc_in_use is needed. Keeping the old code. self.deallocate_bc_in_use() self.chunkLeftUp(m, event) def chunkLeftDown(self, a_chunk, event): """ Depending on the modifier key(s) pressed, it does various operations on chunk..typically pick or unpick the chunk(s) or do nothing. If an object left down happens, the left down method of that object calls this method (chunkLeftDown) as it is the 'SelectChunks_GraphicsMode' which is supposed to select Chunk of the object clicked @param a_chunk: The chunk of the object clicked (example, if the object is an atom, then it is atom.molecule @type a_chunk: B{Chunk} @param event: MouseLeftDown event @see: self.atomLeftDown @see: BuildDna_GraphicsMode.chunkLeftDown() (overrides this method) @see: self.chunkSetUp() """ #Don't select anything if the selection is locked. #see self.selection_locked() for more comments. if self.selection_locked(): return assert isinstance(a_chunk, Chunk) m = a_chunk #@REVIEW: The following code that checks if its a dna segment or strand #etc is probably not needed because now we have implemented the API #method self.end_selection_from_GLPane() (which is also called in this #method.) Needs cleanup -- Ninad 2008-04-17 #Fixed bug 2661 (see also similar code in self.chunkLeftUp() ) #Select the whole parent DnaStrand or DnaSegment group #instead of the chunk. #-- Ninad 2008-03-14 strandOrSegment = a_chunk.parent_node_of_class( self.win.assy.DnaStrandOrSegment) if 0: print "debug fyi: chunk %r .picked %r is in DnaStrandOrSegment %r .picked %r" % \ (a_chunk, a_chunk.picked, strandOrSegment, strandOrSegment.picked) ###### @@@@@@ bruce 080430 debug code ##### for 'rapid click selects subset of strand chunks' bug if strandOrSegment is not None: m = strandOrSegment if not m.picked and self.o.modkeys is None: self.o.assy.unpickall_in_GLPane() m.pick() self.o.selobj = None elif not m.picked and self.o.modkeys == 'Shift': m.pick() self.o.selobj = None elif self.o.modkeys == 'Control': if m.picked: m.unpick() self.o.selobj = None else: pass if m.picked: self.cursor_over_when_LMB_pressed = 'Picked Chunk' else: self.cursor_over_when_LMB_pressed = 'Unpicked Chunk' self.chunkSetUp(m, event) #Fixes bug because of which Nanotube segment is not selected from the #MT if the correspoinding chunk is selected from GLPane. #This was fixed AFTER Rattlesnake rc2 See also similar changes in #self.chunkLeftUp and self.bondLeftDown etc -- Ninad 2008-04-17 self.end_selection_from_GLPane() self.w.win_update() def chunkLeftUp(self, a_chunk, event): """ Depending on the modifier key(s) pressed, it does various operations on chunk. Example: if Shift and Control modkeys are pressed, it deletes the chunk @param a_chunk: The chunk of the object clicked (example, if the object is an atom, then it is atom.molecule @type a_chunk: B{Chunk} @param event: MouseLeftUp event @see: self.atomLeftUp() @see: self.chunkLeftDown() @see: self.leftShiftCntlUp() """ #Note: The following check is already done in #selectMode.doObjectspecificLeftUp. #self.chunkLeftUp method should never be called if #self.current_obj_clicked is False. The check below is added just #to be on a safer side and prints a warning. #UPDATE 2008-03-03: This warning is harmless. In certain situations, #(e.g. leftup on a bondPoint etc), this method is invoked. #although it is a bug, its harmless because we do proper check here. #So print a warning message if ATOM_DEBUG flag is enabled. if not self.current_obj_clicked: if debug_flags.atom_debug: print_compact_stack("Note: self.current_obj_clicked is False " "and still SelectChunks_GraphicsMode.chunkLeftUp is called. Make sure to " "call selectMode.objectSpecificLeftUp before calling " "SelectChunks_GraphicsMode.chunkLeftUp: ") return #Don't select anything if the selection is locked. #see self.selection_locked() for more comments. if self.selection_locked(): return assert isinstance(a_chunk, Chunk) m = a_chunk #@REVIEW: The following code that checks if its a dna segment or strand #etc is probably not needed because now we have implemented the API #method self.end_selection_from_GLPane() (which is also called in this #method.) Needs cleanup -- Ninad 2008-04-17 #Fixed bug 2661 (see also similar code in self.chunkLeftDown() ) #Select the whole parent DnaStrand or DnaSegment group #instead of the chunk. #-- Ninad 2008-03-14 strandOrSegment = a_chunk.parent_node_of_class(self.win.assy.DnaStrandOrSegment) if strandOrSegment is not None: m = strandOrSegment if self.o.modkeys is None: self.o.assy.unpickall_in_GLPane() m.pick() elif self.o.modkeys == 'Shift+Control': #REVIEW/ TODO: leftShiftCntl* need to be an API method parentNodesOfObjUnderMouse = [m] self.leftShiftCntlUp(event, parentNodesOfObjUnderMouse = parentNodesOfObjUnderMouse) #Fixes bug because of which Nanotube segment is not selected from the #MT if the correspoinding chunk is selected from GLPane. #REVIEW: Should we do the following only when self.o.modkeys is None? #probably not. Some basic tests indicate that the fix is also good #for shift + control deleting the segment from the GLPane. This was fixed #AFTER Rattlesnake rc2 See also similar changes in self.chunkLeftDown #and self.bondLeftDown -- Ninad 2008-04-17 self.end_selection_from_GLPane() self.w.win_update() def leftShiftCntlUp(self, event, parentNodesOfObjUnderMouse = ()): """ Do operations when Shift + control left up event occurs (As of 2008-05-02, this is now only implemented for and called from self.chunkLeftUp()) @param parentNodesOfObjUnderMouse: Parent chunk, of which, the object under mouse is a part of.or some other node such as a DnaStrand Or DnaSegment etc which the user probably wants to operate on. @see: self.chunkLeftUp() @see: self._do_leftShiftCntlUp_delete_operations() """ #TODO: This is a new method written on 2008-05-02 , especially to permit #some custom deleting in BuildDna graphicsMode (a subclass of this #class) . This method should also consider other possibilities #such as 'what if the object under mouse is a Jig or something else' #there is some code that already exists which needs to use this new #method (and this method needs to take care of that) . -- Ninad print "parentNodesOfObjUnderMouse =", parentNodesOfObjUnderMouse obj = self.get_obj_under_cursor(event) self._do_leftShiftCntlUp_delete_operations( event, obj, parentNodesOfObjUnderMouse = parentNodesOfObjUnderMouse) self.o.selobj = None def _do_leftShiftCntlUp_delete_operations(self, event, objUnderMouse, parentNodesOfObjUnderMouse = ()): """ Overridden in subclasses, default implementation just deletes the parent node of the object under cursor (provides as an argument) @param parentNodesOfObjUnderMouse: Tuple containing the parent chunk(s), of which, the object under mouse is a part of, or, some other node such as a DnaStrand Or DnaSegment etc which the user probably wants to operate on. @type: Tuple @see: self.chunkLeftUp() @see: self.leftShiftCntlUp() which calls this method. @see: BuildDna_GraphicsMode._do_leftShiftCntlUp_delete_operations() """ obj = objUnderMouse if obj is self.o.selobj: if parentNodesOfObjUnderMouse: try: for node in parentNodesOfObjUnderMouse: node.kill() except: print_compact_traceback( "Error deleting objects %r" % parentNodesOfObjUnderMouse) def bondLeftDown(self, b, event): """ Left down on a Bond <b> , so select or unselect its chunk or delete the bond <b> based on the current modkey. - If no modkey is pressed, clear the selection and pick <b>'s chunk(s). - If Shift is pressed, pick <b>'s chunk(s) , adding them to the current selection. - If Ctrl is pressed, unpick <b>'s chunk(s), removing them from the current selection. - If Shift+Control (Delete) is pressed, delete chunk(s) associated with this bond <b>. <event> is a LMB release event. """ self.cursor_over_when_LMB_pressed = 'Bond' self.bondSetup(b) if self.selection_locked(): return chunk1 = b.atom1.molecule chunk2 = b.atom2.molecule self.set_cmdname('Select Chunks') if chunk1 is chunk2: self.chunkLeftDown(chunk1, event) return #@TODO Fixes part of bug 2749. Method needs refactoring #-- Ninad 2008-04-07 dnaStrandOrSegment1 = chunk1.parent_node_of_class( self.win.assy.DnaStrandOrSegment) dnaStrandOrSegment2 = chunk2.parent_node_of_class( self.win.assy.DnaStrandOrSegment) if dnaStrandOrSegment1 is not None and \ dnaStrandOrSegment1 is dnaStrandOrSegment2: self.chunkLeftDown(chunk1, event) return if dnaStrandOrSegment1 is not None: chunk1 = dnaStrandOrSegment1 if dnaStrandOrSegment2 is not None: chunk2 = dnaStrandOrSegment2 if self.o.modkeys is None: if chunk1.picked and chunk2.picked: pass else: self.o.assy.unpickall_in_GLPane() if not chunk1.picked: chunk1.pick() if not chunk2.picked: chunk2.pick() self.o.selobj = None elif self.o.modkeys == 'Shift': if not chunk1.picked: chunk1.pick() if not chunk2.picked: chunk2.pick() self.o.selobj = None elif self.o.modkeys == 'Control': chunk1.unpick() chunk2.unpick() self.set_cmdname('Unselect Chunks') self.o.selobj = None else: pass if chunk1.picked or chunk2.picked: self.cursor_over_when_LMB_pressed = 'Picked Chunk' else: self.cursor_over_when_LMB_pressed = 'Unpicked Chunk' #Fixes bug because of which Nanotube segment is not selected from the #MT if the correspoinding chunk is selected from GLPane. #This was fixed AFTER Rattlesnake rc2 See also similar changes in #self.chunkLeftUp and self.bondLeftUp etc -- Ninad 2008-04-17 self.end_selection_from_GLPane() self.w.win_update() def bondLeftUp(self, b, event): #Note: The following check is already done in #selectMode.doObjectspecificLeftUp. #self.chunkLeftUp method should never be called if #self.current_obj_clicked is False. The check below is added just #to be on a safer side and prints a warning. if not self.current_obj_clicked: print_compact_stack("Note: self.current_obj_clicked is False " "and still SelectChunks_GraphicsMode.bondLeftUp is called. Make sure to " "call selectMode.objectSpecificLeftUp before calling " "SelectChunks_GraphicsMode.bondLeftUp: ") return if self.selection_locked(): return chunk1 = b.atom1.molecule chunk2 = b.atom2.molecule if chunk1 is chunk2: self.chunkLeftUp(chunk1, event) return #@TODO Fixes part of bug 2749. Method needs refactoring #-- Ninad 2008-04-07 dnaStrandOrSegment1 = chunk1.parent_node_of_class( self.win.assy.DnaStrandOrSegment) dnaStrandOrSegment2 = chunk2.parent_node_of_class( self.win.assy.DnaStrandOrSegment) if dnaStrandOrSegment1 is not None and \ dnaStrandOrSegment1 is dnaStrandOrSegment2: if self.o.modkeys != 'Shift+Control': self.chunkLeftDown(chunk1, event) else: self.leftShiftCntlUp(event, parentNodesOfObjUnderMouse = (chunk1)) return if dnaStrandOrSegment1 is not None: chunk1 = dnaStrandOrSegment1 if dnaStrandOrSegment2 is not None: chunk2 = dnaStrandOrSegment2 if self.o.modkeys is None: self.o.assy.unpickall_in_GLPane() chunk1.pick() chunk2.pick() self.o.selobj = None elif self.o.modkeys == 'Shift+Control': self.leftShiftCntlUp(event, parentNodesOfObjUnderMouse = (chunk1, chunk2)) #call API method to do any special selection (e.g. select the whole #DnaStrand if all its chunks are selected) self.end_selection_from_GLPane() # == Singlet helper methods def singletLeftDown(self, s, event): self.atomLeftDown(s, event) return def singletLeftUp(self, s, event): self.atomLeftUp(s, event) return # == LMB down-click (button press) methods def leftDown(self, event): """ Event handler for all LMB press events. """ # Note: the code of SelectAtoms_GraphicsMode and SelectChunks_GraphicsMode .leftDown methods # is very similar, so I'm removing the redundant comments from # this one (SelectChunks_GraphicsMode); see SelectAtoms_GraphicsMode to find them. # [bruce 071022] self.set_cmdname('ChunkClick') # TODO: this should be set again later (during the same drag) # to a more specific command name. self.reset_drag_vars() env.history.statusbar_msg(" ") self.LMB_press_event = QMouseEvent(event) self.LMB_press_pt_xy = (event.pos().x(), event.pos().y()) obj = self.get_obj_under_cursor(event) if obj is None: # Cursor over empty space. self.emptySpaceLeftDown(event) return method = getattr(obj, 'leftClick', None) if method: # This looks identical to the code from SelectAtoms_GraphicsMode.leftDown # which I just split into a separate method call_leftClick_method, # so I will shortly move that into our common superclass and # call it here instead of duplicating that code. #[bruce 071022 comment] gl_event_info = self.dragstart_using_GL_DEPTH( event, more_info = True) self._drag_handler_gl_event_info = gl_event_info farQ_junk, hitpoint, wX, wY, depth, farZ = gl_event_info del wX, wY, depth, farZ try: retval = method(hitpoint, event, self) except: print_compact_traceback("exception ignored "\ "in %r.leftClick: " % (obj,)) return self.drag_handler = retval # needed even if this is None if self.drag_handler is not None: #the psuedoMoveMode left down might still be needed even when #drag handler is not None #(especially to get the self._leftDrag_movables) self._leftDown_preparation_for_dragging(obj, event) self.dragHandlerSetup(self.drag_handler, event) return self.doObjectSpecificLeftDown(obj, event) if self.glpane.modkeys is None: self._leftDown_preparation_for_dragging(obj, event) self.w.win_update() return # from SelectChunks_GraphicsMode.leftDown def leftDrag(self, event): """ Overrides leftdrag method of superclass. A) If the mouse cursor was on Empty space during left down, it draws a selection curve B) If it was on an object, it translates translates the selection (free drag translate). This is called 'pseudo move mode' for convenience. Note that NE1 still remains in the SelectChunks_GraphicsMode while doing this. It calls separate method for objects that implement drag handler API @param event: mouse left drag event @see: selectMode.leftDrag @see: SelectChunks_GraphicsMode._leftDown_preparation_for_dragging @see: SelectChunks_GraphicsMode.leftDragTranslation """ if self.mouse_within_stickiness_limit(event, DRAG_STICKINESS_LIMIT): return self.current_obj_clicked = False # Copying some drag_handler checker code from SelectAtoms_GraphicsMode (with some # modifications) -- Ninad20070601 # [bruce 071022 removed some comments redundant with the # leftDrag method of SelectAtoms_GraphicsMode] if self.cursor_over_when_LMB_pressed == 'Empty Space': if self.drag_handler is not None: self.dragHandlerDrag(self.drag_handler, event) # does updates if needed else: self.emptySpaceLeftDrag(event) return if self.o.modkeys is not None: # If a drag event has happened after the cursor was over an atom # and a modkey is pressed, do a 2D region selection as if the # atom were absent. self.emptySpaceLeftDown(self.LMB_press_event) #bruce 060721 question: why don't we also do emptySpaceLeftDrag # at this point? return if self.drag_handler is not None: movables = self._leftDrag_movables if movables: if self.drag_handler not in movables: self.dragHandlerDrag(self.drag_handler, event) return elif len(movables) == 1: self.dragHandlerDrag(self.drag_handler, event) return #Free Drag Translate the selected (movable) objects. self.leftDragTranslation(event) def _leftDown_preparation_for_dragging(self, objectUnderMouse, event): """ Initialize variables required for translating the selection during leftDrag method (leftDragTranslation) . @param event: Mouse left down event @param objectUnderMouse: Object under the mouse during left down event. @see: self.leftDown() @see: self.getMovablesForLeftDragging() """ #pseudo move mode related initialization STARTS self.o.SaveMouse(event) self.picking = True self.dragdist = 0.0 self.transDelta = 0 # X, Y or Z deltas for translate. self.moveOffset = [0.0, 0.0, 0.0] # X, Y and Z offset for move. farQ_junk, self.movingPoint = self.dragstart_using_GL_DEPTH( event) self.startpt = self.movingPoint # Used in leftDrag() to compute move offset during drag op. self._leftDrag_movables = [] #Just for safety. This is already reset #in self.reset_drag_vars() #pseudo move mode related initialization ENDS #Defin the left drag movables. These will be computed once only in #the leftDown (and not each time duruing the leftDrag) self._leftDrag_movables = self.getMovablesForLeftDragging() return def leftDragTranslation(self, event): """ Translate the selected object(s) in the plane of the screen following the mouse. This is a free drag translate. @param event: mouse left drag event. @see: self.leftDrag @see: TranslateChunks_GraphicsMode.leftDrag #@see: self.getMovablesForLeftDragging() @note : This method uses some duplicate code (free drag translate code) from TranslateChunks_GraphicsMode.leftDrag """ self._leftDragFreeTranslation(event) def _leftDragFreeTranslation(self, event): """ @see: self.leftDrag() @see: self._leftDragFreeTranslation() @see: self._leftDragConstrainedTranslation() """ if not self.picking: return if not self._leftDrag_movables: return if self.movingPoint is None: self.leftDown(event) # Turn Off hover highlighting while translating the selection # This will be turned ON again in leftUp method. # [update, bruce 071121: it looks like it's turned back on # in bareMotion instead.] self._suppress_highlighting = True # This flag is required in various leftUp methods. It helps them # decide what to do upon left up. The flag value is set in # selectMode.objectSetup, selectMode.objectLeftDrag. # See those comments. Found a bit confusing but enough documentation # exists so ok self.current_obj_clicked = False # Move section deltaMouse = V(event.pos().x() - self.o.MousePos[0], self.o.MousePos[1] - event.pos().y(), 0.0) point = self.dragto( self.movingPoint, event) # Print status bar msg indicating the current translation delta. self.moveOffset = point - self.startpt # Fixed bug 929. mark 060111 msg = "Offset: [X: %.2f] [Y: %.2f] [Z: %.2f]" % (self.moveOffset[0], self.moveOffset[1], self.moveOffset[2]) env.history.statusbar_msg(msg) offset = point - self.movingPoint self.win.assy.translateSpecifiedMovables(offset, self._leftDrag_movables) self.movingPoint = point self.dragdist += vlen(deltaMouse) self.o.SaveMouse(event) self.o.gl_update() def leftUp(self, event): """ Event handler for all LMB release events. """ env.history.flush_saved_transients() if self.ignore_next_leftUp_event: # This event is the second leftUp of a double click, so ignore it. # [REVIEW: will resetting this flag here cause trouble for a triple # click? I guess/hope not, since that also calls leftDouble and # sets this. bruce comment 071022] self.ignore_next_leftUp_event = False self.update_selobj(event) # Fixes bug 1467. mark 060307. return if self.cursor_over_when_LMB_pressed == 'Empty Space': self.emptySpaceLeftUp(event) return if self.mouse_within_stickiness_limit(event, DRAG_STICKINESS_LIMIT): event = self.LMB_press_event # pretend the mouse didn't move -- this replaces our argument # event, for passing to *leftUp methods [bruce 060728 comment] obj = self.current_obj if obj is None: # Nothing dragged (or clicked); return. return #For drag handler API such as the one used in exprs.Highlightable #or in class ResizeHandle if self.drag_handler: self.dragHandlerLeftUp(self.drag_handler, event) self.leftUp_reset_a_few_drag_vars() self.doObjectSpecificLeftUp(obj, event) self.w.win_update() return # from SelectChunks_GraphicsMode.leftUp def reset_drag_vars(self): """ @see: SelectGraphicsMode.reset_drag_vars() for documentation """ _superclass.reset_drag_vars(self) #Clear the list of movables (to be moved while left dragging selection) #@see: self.psudoMoveModeLeftDown() self._leftDrag_movables = [] def leftUp_reset_a_few_drag_vars(self): """ reset a few drag vars at the end of leftUp -- might not be safe to reset them all (e.g. if some are used by leftDouble) """ self.current_obj = None #bruce 041130 fix bug 230 # later: i guess this attr had a different name then [bruce 060721] self.o.selatom = None #bruce 041208 for safety in case it's killed self._leftDrag_movables = [] return def bareMotion(self, event): """ Overrides selectMode.bareMotion. Called for motion with no button down Should not be called otherwise, call update_selatom or update_selobj directly instead. """ #The value of self.timeAtLastWheelEvent is set in #GraphicsMode.wheelEvent. #This time is used to decide whether to highlight the object #under the cursor. I.e. when user is scrolling the wheel to zoom in #or out, and at the same time the mouse moves slightly, we want to make #sure that the object is not highlighted. The value of elapsed time #is selected as 2.0 seconds arbitrarily. Based on some tests, this value #seems OK. Following fixes bug 2536. Note, another fix would be to #set self._suppress_highlighting to True. But this fix looks more #appropriate at the moment -- Ninad 2007-09-19 # # Note: I think 2.0 is too long -- this should probably be more like 0.5. # But I will not change this immediately, since I am fixing two other # contributing causes to bug 2606, and I want to see their effects one # at a time. @@@@@ # [bruce 080129 comment] # # update, bruce 080130: change time.clock -> time.time to fix one cause # of bug 2606. Explanation: time.clock is documented as returning # "either real time or CPU time", and at least on the Macs I tested, # it returns something that grows much more slowly than real time, # especially on the faster Mac of the two (like cpu time would do). # That is probably one of two or three bugs adding together to cause the # highlighting suppression bug 2606 reported by Paul -- the others are # the large timeout value of 2.0, and (predicted from the code, not yet # fully tested) that this timeout condition can discard not only a real # bareMotion event, but a fake zero-motion event intended to make sure # highlighting occurs after large mouse motions disabled it, which is # sent exactly once after motion stops (even if this timeout is still # running). I am fixing these one at a time to see their individual # effects. @@@@@ # # update: Mark 2008-05-26. Added user pref to set timeout interval # from the Preferences dialog. The default = 0.5 seconds, which is # much better than 2.0. # # russ 080527: Fix Bug 2606 (highlighting not turned on after wheel event.) # Return value to caller tells whether the bareMotion event was discarded. # if self.timeAtLastWheelEvent: time_since_wheel_event = time.time() - self.timeAtLastWheelEvent if time_since_wheel_event < env.prefs[mouseWheelTimeoutInterval_prefs_key]: if DEBUG_BAREMOTION: #bruce 080129 re highlighting bug 2606 reported by Paul print "debug fyi: ignoring %r.bareMotion since time_since_wheel_event is only %r " % \ (self, time_since_wheel_event) return True #Turn the highlighting back on if it was suppressed during, #for example, leftDrag if self._suppress_highlighting: self._suppress_highlighting = False _superclass.bareMotion(self, event) ### REVIEW: why do we now return False, rather than whatever this returns? # Needs explanation. [bruce 081002 question] return False def update_cursor_for_no_MB(self): """ Update the cursor for Select mode (Default implementation). """ # print "SelectChunks_GraphicsMode.update_cursor_for_no_MB(): button=",\ # self.o.button,"modkeys=",self.o.modkeys if self.o.modkeys is None: ##print "seeing modkeys is None",self.w.SelectArrowCursor #bruce 070628 ##self.o.gl_update() #bruce 070628, didn't help self.o.setCursor(self.w.SelectArrowCursor) elif self.o.modkeys == 'Shift': self.o.setCursor(self.w.SelectArrowAddCursor) elif self.o.modkeys == 'Control': self.o.setCursor(self.w.SelectArrowSubtractCursor) elif self.o.modkeys == 'Shift+Control': self.o.setCursor(self.w.DeleteCursor) else: print "Error in update_cursor_for_no_MB(): " \ "Invalid modkey=", self.o.modkeys return def drawHighlightedChunk(self, glpane, selobj, hicolor, hicolor2): """ Highlight the whole chunk to which 'selobj' belongs, using the 'hicolor'. If selobj is an external bond, highlight both its atoms' chunks, one in hicolor and one in hicolor2 (which chunk is which is arbitrary, for now). (External bonds connecting those two chunks will get drawn in hicolor.) @param selobj: the atom or bond (or other object) under the mouse @param hicolor: highlight color for selobj's chunk @param hicolor2: highlight color for selobj's "other chunk", if any @return: whether the caller should skip the usual selobj drawing (usually, this is just whether we drew something) @rtype: boolean @see: self._get_objects_to_highlight() @see: self.Draw_highlighted_selobj() """ # Ninad 070214 wrote this in GLPane; bruce 071008 moved it into # SelectChunks_GraphicsMode and slightly revised it (including, adding the return # value). # Bruce 080217 formalized hicolor2 as an arg (was hardcoded orange). assert hicolor is not None #bruce 070919 assert hicolor2 is not None something_drawn_highlighted = False #dictionary of objects to highlight. highlightObjectDict = self._get_objects_to_highlight(selobj, hicolor, hicolor2) #We could have even used simple lists here. one for objects to be #highlighted and one for highlight colors. Easy to change to that #implementation if we need to. for obj, color in highlightObjectDict.iteritems(): #obj = object to be drawn highlighted #color = highlight color if hasattr( obj, 'draw_highlighted'): obj.draw_highlighted(self.glpane, color) something_drawn_highlighted = True return something_drawn_highlighted def _get_objects_to_highlight(self, selobj, hiColor1, hiColor2): """ Returns a python dictionary with objects to be drawn highlighted as its keys and highlight color as their corresponding values. The object to be highlighted is determined based the current graphics mode using the glpane.selobj. The subclasses can override this method to return objects to be highlighted in that particular graphics mode. @param selobj: GLPane.selobj (object under cursoe which can be registered as a GLPane.selobj @param hiColor1 : highlight color 1 @paramhiColor2: alternative highlight color. Example: If there are two chunks that need to be highlighted, one chunk gets hiColor1 and other gets hiColor2. @TODO: - may be hiColors should be in a list to make it more general @return: dictionary of objects to be highlighted. @rtype: dict @see: self.drawHighlightedChunk() @see: self.Draw_highlighted_selobj() """ #Create a dictionary of objects to be drawn highlighted. #(object_to_highlight, highlight_color) will objectDict = {} chunkList = [] colorList = [] #Note: Make sure to check if its a 'DnaStrand' or a 'DnaSegment' so that #its draw_highlighted method gets called when applicable. There could be #several such things in the future. so need to think of a better way to #do it. #@TODO Following also fixes part of bug 2749. Method needs refactoring #-- Ninad 2008-04-07 if isinstance(selobj, Chunk): dnaStrandOrSegment = selobj.parent_node_of_class( self.win.assy.DnaStrandOrSegment) if dnaStrandOrSegment: chunkList = [dnaStrandOrSegment] else: chunkList = [selobj] colorList = [hiColor1] elif isinstance(selobj, Atom): dnaStrandOrSegment = selobj.molecule.parent_node_of_class( self.win.assy.DnaStrandOrSegment) if dnaStrandOrSegment: chunkList = [dnaStrandOrSegment] else: chunkList = [selobj.molecule] colorList = [hiColor1] elif isinstance(selobj, Bond): chunk1 = selobj.atom1.molecule chunk2 = selobj.atom2.molecule if chunk1 is chunk2: dnaStrandOrSegment = chunk1.parent_node_of_class( self.win.assy.DnaStrandOrSegment) if dnaStrandOrSegment: chunkList = [dnaStrandOrSegment] else: chunkList = [chunk1] colorList = [hiColor1] else: for c in [chunk1, chunk2]: dnaStrandOrSegment = c.parent_node_of_class( self.win.assy.DnaStrandOrSegment) if dnaStrandOrSegment: chunkList.append(dnaStrandOrSegment) else: chunkList.append(c) colorList = [hiColor1, hiColor2] for c in chunkList: i = chunkList.index(c) objectDict[c] = colorList[i] return objectDict def Draw_highlighted_selobj(self, glpane, selobj, hicolor): """ [overrides superclass method] @see: self._get_objects_to_highlight() @see: self.drawHighlightedChunk() """ # Ninad 070214 wrote this in GLPane; bruce 071008 moved it into # SelectChunks_GraphicsMode and slightly revised it. ## hicolor2 = orange # intended to visually differ from hicolor HHColor = env.prefs[hoverHighlightingColor_prefs_key] hicolor2 = ave_colors(0.5, HHColor, orange) #bruce 080217 revision to hicolor2 (since orange is a warning color) skip_usual_selobj_highlighting = self.drawHighlightedChunk(glpane, selobj, hicolor, hicolor2) # Note: if subclasses don't want that call, they should override # drawHighlightedChunk to do nothing and return False. # The prior code was equivalent to every subclass doing that. # - [bruce 071008] if not skip_usual_selobj_highlighting: _superclass.Draw_highlighted_selobj(self, glpane, selobj, hicolor) return def _getAtomHighlightColor(self, selobj): """ Return the Atom highlight color @return: Highlight color of the object (Atom or Singlet) The default implementation returns 'None' . Subclasses should override this method if they need atom highlight color. """ if self.o.modkeys == 'Shift+Control': return red return env.prefs[hoverHighlightingColor_prefs_key] def _getBondHighlightColor(self, selobj): """ Return the Bond highlight color @return: Highlight color of the object (Bond) The default implementation returns 'None' . Subclasses should override this method if they need bond highlight color. """ if self.o.modkeys == 'Shift+Control': return red return env.prefs[hoverHighlightingColor_prefs_key] class SelectChunks_GraphicsMode(SelectChunks_basicGraphicsMode): """ """ def __init__(self, command): self.command = command glpane = self.command.glpane SelectChunks_basicGraphicsMode.__init__(self, glpane) return # (the rest would come from GraphicsMode if post-inheriting it worked, # or we could split it out of GraphicsMode as a post-mixin to use there # and here) def _get_commandSequencer(self): return self.command.commandSequencer commandSequencer = property(_get_commandSequencer) def set_cmdname(self, name): self.command.set_cmdname(name) return
NanoCAD-master
cad/src/commands/SelectChunks/SelectChunks_GraphicsMode.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ SelectChunks_Command.py The 'Command' part of the Select Chunks Mode (SelectChunks_Command and SelectChunks_basicGraphicsMode are the two split classes of the old selectMolsMode) It provides the command object for its GraphicsMode class. The Command class defines anything related to the 'command half' of the mode -- For example: - Anything related to its current Property Manager, its settings or state - The model operations the command does (unless those are so simple that the mouse event bindings in the _GM half can do them directly and the code is still clean, *and* no command-half subclass needs to override them). @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. TODO: - Items mentioned in Select_GraphicsMode.py - Other items listed in Select_Command.py History: Ninad & Bruce 2007-12-13: Created new Command and GraphicsMode classes from the old class selectMolsMode and moved the Command related methods into this class from selectMolsMode.py """ from commands.Select.Select_Command import Select_Command from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode from utilities.Comparison import same_vals from model.chem import Atom from model.chunk import Chunk from model.bonds import Bond _superclass = Select_Command class SelectChunks_Command(Select_Command): """ The 'Command' part of the Select Chunks Mode (SelectChunks_Command and SelectChunks_basicGraphicsMode are the two split classes of the old selectMolsMode) It provides the command object for its GraphicsMode class. The Command class defines anything related to the 'command half' of the mode -- For example: - Anything related to its current Property Manager, its settings or state - The model operations the command does (unless those are so simple that the mouse event bindings in the _GM half can do them directly and the code is still clean, *and* no command-half subclass needs to override them). """ #GraphicsMode GraphicsMode_class = SelectChunks_GraphicsMode commandName = 'SELECTMOLS' # i.e. DEFAULT_COMMAND, but don't use that constant to define it here featurename = "Select Chunks Mode" from utilities.constants import CL_DEFAULT_MODE command_level = CL_DEFAULT_MODE # error if command subclass fails to override this #This attr is used for comparison purpose in self.command_update_UI() #Note the extra '_' at the beginning of this attr name.This is because #two classes use _previous_command_stack_change_indicator attr. If one of the #class is superclass of the other, then it could create a potential bug #(because we call _superclass.command_update_UI' in def command_update_UI) #But this is only a fix to a potential bug. As of 2008-11-24, SelectChunks_Command #is not a superclass of EditCommand. __previous_command_stack_change_indicator = None def command_enter_misc_actions(self): self.w.toolsSelectMoleculesAction.setChecked(True) def command_exit_misc_actions(self): self.w.toolsSelectMoleculesAction.setChecked(False) def command_update_UI(self): """ Extends superclass method. """ _superclass.command_update_UI(self) #Ths following code fixes a bug reported by Mark on 2008-11-10 #the bug is: #1. Insert DNA #2. Enter Break Strands command. Exit command. #3. Do a region selection to select the middle of the DNA duplex. #Notice that atoms are selected, not the strands/segment chunks. #The problem is the selection state is not changed back to the Select Chunks #the code that does this is in Enter_GraphicsMode. #(See SelectChunks_GraphicsMode) but when a command is 'resumed', that #method is not called. The fix for this is to check if the command stack #indicator changed in the command_update_state method, if it is changed #and if currentCommand is BuildDna_EditCommand, call the code that #ensures that chunks will be selected when you draw a selection lasso. #-- Ninad 2008-11-10 indicator = self.assy.command_stack_change_indicator() if same_vals(self.__previous_command_stack_change_indicator, indicator): return self.__previous_command_stack_change_indicator = indicator self.assy.selectChunksWithSelAtoms_noupdate() return call_makeMenus_for_each_event = True def makeMenus(self): # mark 060303. """ Make the GLPane context menu for Select Chunks. """ self.Menu_spec = [] selobj = self.glpane.selobj highlightedChunk = None if isinstance(selobj, Chunk): highlightedChunk = selobj if isinstance(selobj, Atom): highlightedChunk = selobj.molecule elif isinstance(selobj, Bond): chunk1 = selobj.atom1.molecule chunk2 = selobj.atom2.molecule if chunk1 is chunk2 and chunk1 is not None: highlightedChunk = chunk1 self.debug_Menu_spec = [ ('debug: invalidate selection', self.invalidate_selection), ('debug: update selection', self.update_selection), ] if highlightedChunk is not None: highlightedChunk.make_glpane_cmenu_items(self.Menu_spec, self) return _numberOfSelectedChunks = self.o.assy.getNumberOfSelectedChunks() if _numberOfSelectedChunks == 0: self.addStandardMenuItems() elif _numberOfSelectedChunks == 1: selectedChunk = self.o.assy.selmols[0] selectedChunk.make_glpane_cmenu_items(self.Menu_spec, self) elif _numberOfSelectedChunks > 1: self._makeEditContextMenus() self.Menu_spec.extend([None]) # inserts separator contextMenuList = [ ('Hide', self.o.assy.Hide), ('Reset atoms display of selected chunks', self.w.dispResetAtomsDisplay), ('Show invisible atoms of selected chunks', self.w.dispShowInvisAtoms), ] self.Menu_spec.extend(contextMenuList) else: self.addStandardMenuItems() return def addStandardMenuItems(self): """ Insert the 'standard' menu items for the GLPane context menu. """ self.Menu_spec.extend( [('Edit Color Scheme...', self.w.colorSchemeCommand)]) # Enable/Disable Jig Selection. # This is duplicated in depositMode.makeMenus(). if self.o.jigSelectionEnabled: self.Menu_spec.extend( [None, ('Enable jig selection', self.graphicsMode.toggleJigSelection, 'checked')]) else: self.Menu_spec.extend( [None, ('Enable jig selection', self.graphicsMode.toggleJigSelection, 'unchecked')]) return def invalidate_selection(self): #bruce 041115 (debugging method) """ [debugging method] invalidate all aspects of selected atoms or mols """ for mol in self.o.assy.selmols: print "already valid in mol %r: %r" % (mol, mol.invalid_attrs()) mol.invalidate_everything() for atm in self.o.assy.selatoms.values(): atm.invalidate_everything() return def update_selection(self): #bruce 041115 (debugging method) """ [debugging method] update all aspects of selected atoms or mols; no effect expected unless you invalidate them first """ for atm in self.o.assy.selatoms.values(): atm.update_everything() for mol in self.o.assy.selmols: mol.update_everything() return
NanoCAD-master
cad/src/commands/SelectChunks/SelectChunks_Command.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ GrapheneGenerator.py @author: Will @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. History: Mark 2007-05-17: Implemented PropMgrBaseClass. Mark 2007-07-24: Now uses new PM module. Mark 2007-08-06: Renamed GrapheneGeneratorDialog to GrapheneGeneratorPropertyManager. Ninad 2008-07-23: Cleanup to port Graphene generator to the EditCommand API. Now this class simply acts as a generator object called from the editcommand while creating the structure. """ from math import atan2, pi from model.chem import Atom from model.bonds import bond_atoms import model.bond_constants as bond_constants from model.chunk import Chunk import foundation.env as env from utilities.debug import Stopwatch from model.elements import PeriodicTable from utilities.Log import greenmsg from geometry.VQT import V sqrt3 = 3 ** 0.5 quartet = ((0, sqrt3 / 2), (0.5, 0), (1.5, 0), (2, sqrt3 / 2)) TOROIDAL = False #debug flag , don't commit it with True! class GrapheneGenerator: """ The Graphene Sheet Generator class for the "Build Graphene (Sheet)" command. """ def make(self, assy, name, params, position = V(0, 0, 0), editCommand = None): height, width, bond_length, endings = params PROFILE = False if PROFILE: sw = Stopwatch() sw.start() mol = Chunk(assy, name) atoms = mol.atoms z = 0.0 self.populate(mol, height, width, z, bond_length, endings, position) if PROFILE: t = sw.now() env.history.message(greenmsg("%g seconds to build %d atoms" % (t, len(atoms.values())))) return mol def populate(self, mol, height, width, z, bond_length, endings, position): """ Create a graphene sheet chunk. """ def add(element, x, y, atomtype='sp2'): atm = Atom(element, V(x, y, z), mol) atm.set_atomtype_but_dont_revise_singlets(atomtype) return atm num_atoms = len(mol.atoms) bond_dict = { } i = j = 0 y = -0.5 * height - 2 * bond_length while y < 0.5 * height + 2 * bond_length: i = 0 x = -0.5 * width - 2 * bond_length while x < 0.5 * width + 2 * bond_length: lst = [ ] for x1, y1 in quartet: atm = add("C", x + x1 * bond_length, y + y1 * bond_length) lst.append(atm) bond_dict[(i, j)] = lst bond_atoms(lst[0], lst[1], bond_constants.V_GRAPHITE) bond_atoms(lst[1], lst[2], bond_constants.V_GRAPHITE) bond_atoms(lst[2], lst[3], bond_constants.V_GRAPHITE) i += 1 x += 3 * bond_length j += 1 y += sqrt3 * bond_length imax, jmax = i, j for i in range(imax): for j in range(jmax - 1): lst1 = bond_dict[(i, j)] lst2 = bond_dict[(i, j+1)] bond_atoms(lst1[0], lst2[1], bond_constants.V_GRAPHITE) bond_atoms(lst1[3], lst2[2], bond_constants.V_GRAPHITE) for i in range(imax - 1): for j in range(jmax): lst1 = bond_dict[(i, j)] lst2 = bond_dict[(i+1, j)] bond_atoms(lst1[3], lst2[0], bond_constants.V_GRAPHITE) # trim to dimensions atoms = mol.atoms for atm in atoms.values(): x, y, z = atm.posn() xdim, ydim = width + bond_length, height + bond_length # xdim, ydim = width + 0.5 * bond_length, height + 0.5 * bond_length if (x < -0.5 * xdim or x > 0.5 * xdim or y < -0.5 * ydim or y > 0.5 * ydim): atm.kill() def trimCarbons(): """Trim all the carbons that only have one carbon neighbor. """ for i in range(2): for atm in atoms.values(): if not atm.is_singlet() and len(atm.realNeighbors()) == 1: atm.kill() if TOROIDAL: # This is for making electrical inductors. What would be # really good here would be to break the bonds that are # stretched by this and put back the bondpoints. angstromsPerTurn = 6.0 for atm in atoms.values(): x, y, z = atm.posn() r = (x**2 + y**2) ** .5 if 0.25 * width <= r <= 0.5 * width: angle = atan2(y, x) zdisp = (angstromsPerTurn * angle) / (2 * pi) atm.setposn(V(x, y, z + zdisp)) else: atm.kill() if endings == 1: # hydrogen terminations trimCarbons() for atm in atoms.values(): atm.Hydrogenate() elif endings == 2: # nitrogen terminations trimCarbons() dstElem = PeriodicTable.getElement('N') atomtype = dstElem.find_atomtype('sp2') for atm in atoms.values(): if len(atm.realNeighbors()) == 2: atm.Transmute(dstElem, force=True, atomtype=atomtype) for atm in atoms.values(): atm.setposn(atm.posn() + position) if num_atoms == len(mol.atoms): raise Exception("Graphene sheet too small - no atoms added")
NanoCAD-master
cad/src/commands/InsertGraphene/GrapheneGenerator.py
NanoCAD-master
cad/src/commands/InsertGraphene/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ Graphene_EditCommand.py @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version: $Id$ History: 2008-07-22: Ported the old graphene generator to the Editcommand API TODO: - Needs cleanup after command sequencer refactoring. The graphene generator was ported to EditCommand API to help the commandSequencer refactoring project. """ from utilities.Log import greenmsg from command_support.EditCommand import EditCommand from commands.InsertGraphene.GrapheneGenerator import GrapheneGenerator from utilities.constants import gensym from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode from ne1_ui.toolbars.Ui_GrapheneFlyout import GrapheneFlyout from commands.InsertGraphene.GrapheneGeneratorPropertyManager import GrapheneGeneratorPropertyManager _superclass = EditCommand class Graphene_EditCommand(EditCommand): GraphicsMode_class = SelectChunks_GraphicsMode #Property Manager PM_class = GrapheneGeneratorPropertyManager #Flyout Toolbar FlyoutToolbar_class = GrapheneFlyout cmd = greenmsg("Build Graphene: ") prefix = 'Graphene' # used for gensym cmdname = 'Build Graphene' commandName = 'BUILD_GRAPHENE' featurename = "Build Graphene" from utilities.constants import CL_ENVIRONMENT_PROVIDING command_level = CL_ENVIRONMENT_PROVIDING # for now; later might be subcommand of Build Nanotube?? create_name_from_prefix = True flyoutToolbar = None def _gatherParameters(self): """ Return the parameters from the property manager. """ return self.propMgr.getParameters() def runCommand(self): """ Overrides EditCommand.runCommand """ self.struct = None def _createStructure(self): """ Build a graphene sheet from the parameters in the Property Manager. """ # self.name needed for done message if self.create_name_from_prefix: # create a new name name = self.name = gensym(self.prefix, self.win.assy) # (in _build_struct) self._gensym_data_for_reusing_name = (self.prefix, name) else: # use externally created name self._gensym_data_for_reusing_name = None # (can't reuse name in this case -- not sure what prefix it was # made with) name = self.name params = self._gatherParameters() # self.win.assy.part.ensure_toplevel_group() structGenerator = GrapheneGenerator() struct = structGenerator.make(self.win.assy, name, params, editCommand = self) self.win.assy.part.topnode.addmember(struct) self.win.win_update() return struct def _modifyStructure(self, params): """ Modify the structure based on the parameters specified. Overrides EditCommand._modifystructure. This method removes the old structure and creates a new one using self._createStructure. See more comments in this method. """ #@NOTE: Unlike editcommands such as Plane_EditCommand or #DnaSegment_EditCommand this actually removes the structure and #creates a new one when its modified. #TODO: Change this implementation to make it similar to whats done #iin DnaSegment resize. (see DnaSegment_EditCommand) self._removeStructure() self.previousParams = params self.struct = self._createStructure() def _getStructureType(self): """ Subclasses override this method to define their own structure type. Returns the type of the structure this editCommand supports. This is used in isinstance test. @see: EditCommand._getStructureType() (overridden here) """ return self.win.assy.Chunk
NanoCAD-master
cad/src/commands/InsertGraphene/Graphene_EditCommand.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ @author: Mark @version:$Id$ History: Mark 2007-05-17: This used to be generated from its .ui file. Now it uses PropMgrBaseClass to construct its property manager dialog. Mark 2007-07-24: Now uses new PM module. Mark 2007-08-06: Renamed GrapheneGeneratorDialog to GrapheneGeneratorPropertyManager. Ninad 2008-07-22/23: ported this to EditCommand API (new superclass Editcommand_PM) """ from model.bonds import CC_GRAPHITIC_BONDLENGTH from PM.PM_GroupBox import PM_GroupBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_ComboBox import PM_ComboBox from command_support.EditCommand_PM import EditCommand_PM from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from PM.PM_Constants import PM_CANCEL_BUTTON from PM.PM_Constants import PM_PREVIEW_BUTTON _superclass = EditCommand_PM class GrapheneGeneratorPropertyManager(EditCommand_PM): """ The GrapheneGeneratorPropertyManager class provides a Property Manager for the "Build > Graphene (Sheet)" command. """ # The title that appears in the property manager header. title = "Graphene Generator" # 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 PNG file that appears in the header. iconPath = "ui/actions/Tools/Build Structures/Graphene.png" def __init__( self, command ): """ Construct the "Build Graphene" Property Manager. """ _superclass.__init__( self, command ) msg = "Edit the parameters below and click the <b>Preview</b> "\ "button to preview the graphene sheet. Clicking <b>Done</b> "\ "inserts it into the model." self.updateMessage(msg = msg) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_PREVIEW_BUTTON | \ PM_WHATS_THIS_BUTTON) def _addGroupBoxes(self): """ Add the group boxes to the Graphene Property Manager dialog. """ self.pmGroupBox1 = \ PM_GroupBox( self, title = "Graphene Parameters" ) self._loadGroupBox1(self.pmGroupBox1) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in groubox 1. """ self.heightField = \ PM_DoubleSpinBox( pmGroupBox, label = "Height :", value = 20.0, setAsDefault = True, minimum = 1.0, maximum = 100.0, singleStep = 1.0, decimals = 3, suffix = ' Angstroms') self.widthField = \ PM_DoubleSpinBox( pmGroupBox, label = "Width :", value = 20.0, setAsDefault = True, minimum = 1.0, maximum = 100.0, singleStep = 1.0, decimals = 3, suffix = ' Angstroms') self.bondLengthField = \ PM_DoubleSpinBox( pmGroupBox, 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( pmGroupBox, label = "Endings :", choices = endingChoices, index = 0, setAsDefault = True, spanWidth = False ) def getParameters(self): """ Return the parameters from this property manager to be used to create the graphene sheet. @return: A tuple containing the parameters @rtype: tuple @see: L{Graphene_EditCommand._gatherParameters()} where this is used """ height = self.heightField.value() width = self.widthField.value() bond_length = self.bondLengthField.value() endings = self.endingsComboBox.currentIndex() return (height, width, bond_length, endings) def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_GrapheneGeneratorPropertyManager whatsThis_GrapheneGeneratorPropertyManager(self) def _addToolTipText(self): """ Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_GrapheneGeneratorPropertyManager ToolTip_GrapheneGeneratorPropertyManager(self)
NanoCAD-master
cad/src/commands/InsertGraphene/GrapheneGeneratorPropertyManager.py
NanoCAD-master
cad/src/commands/CommentProperties/__init__.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ CommentProp.py - @author: Mark @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: 060520 mark: New feature for Alpha 8. Stores a comment in the MMP file, accessible from the Model Tree as a node. 060522 bruce: minor changes, including changing representation of comment text. 080717 bruce, revise for coding standards """ from PyQt4.Qt import QDialog, QTextEdit, SIGNAL from model.Comment import Comment from commands.CommentProperties.CommentPropDialog import Ui_CommentPropDialog import time import foundation.env as env from utilities.Log import redmsg, orangemsg, greenmsg, quote_html from utilities.qt4transition import qt4todo from utilities.debug import print_compact_traceback cmd = greenmsg("Insert Comment: ") # TODO: rename this global class CommentProp(QDialog, Ui_CommentPropDialog): """ The Comment dialog allows the user to add a comment to the Model Tree, which is saved in the MMP file. """ def __init__(self, win): QDialog.__init__(self, win) # win is parent. self.setupUi(self) self.win = win self.comment = None self.action = None # REVIEW, re self.action: # - if used only in messages (true in this file, but not yet # analyzed re external files), should change initial value to "". # - if not used in external files, should make private. # [bruce 080717 comment] def setup(self, comment = None): """ Show Comment dialog with current Comment text, for editing properties of an existing Comment node or creating a new one. @param comment: the comment node to edit, or None to create a new one. """ self.comment = comment if self.comment: self.comment_textedit.setPlainText(self.comment.get_text()) # Load comment text. qt4todo("self.comment_textedit.moveCursor(QTextEdit.MoveEnd, False)") # Sets cursor position to the end of the textedit document. QDialog.exec_(self) ###### Private methods ############################### def _create_comment(self): comment_text = self.comment_textedit.toPlainText() if not self.comment: self.comment = Comment(self.win.assy, None, comment_text) self.win.assy.addnode(self.comment) self.action = 'added' else: self.comment.set_text(comment_text) self.action = 'updated' def _remove_comment(self): if self.comment: self.comment.kill() self.win.mt.mt_update() self.comment = None def insert_date_time_stamp(self): """ Insert a date/time stamp in the comment at the current position. @note: slot method for self.date_time_btn, SIGNAL("clicked()"). """ timestr = "%s " % time.strftime("%m/%d/%Y %I:%M %p") self.comment_textedit.insertPlainText(timestr) def _done_history_msg(self): env.history.message(cmd + quote_html("%s %s." % (self.comment.name, self.action))) #bruce Qt4 070502 precaution: use quote_html ################# # Cancel Button ################# def reject(self): QDialog.reject(self) self.comment = None self.comment_textedit.setPlainText("") # Clear text. ################# # OK Button ################# def accept(self): """ Slot for the OK button """ try: self._create_comment() self._done_history_msg() self.comment = None except Exception, e: print_compact_traceback("Bug: exception in CommentProp.accept: ") #bruce Qt4 070502 env.history.message(cmd + redmsg("Bug: " + quote_html(" - ".join(map(str, e.args))))) #bruce Qt4 070502 bugfixes: use quote_html, say it's a bug (could say "internal error" if desired) self._remove_comment() self.win.mt.mt_update() QDialog.accept(self) self.comment_textedit.setPlainText("") # Clear text. pass # end of class CommentProp # end
NanoCAD-master
cad/src/commands/CommentProperties/CommentProp.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'COmmentPropDialog.ui' # # Created: Thu Aug 07 18:04:11 2008 # by: PyQt4 UI code generator 4.3.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_CommentPropDialog(object): def setupUi(self, CommentPropDialog): CommentPropDialog.setObjectName("CommentPropDialog") CommentPropDialog.resize(QtCore.QSize(QtCore.QRect(0,0,390,275).size()).expandedTo(CommentPropDialog.minimumSizeHint())) self.gridlayout = QtGui.QGridLayout(CommentPropDialog) # note: this change will be lost when this file is remade from the .ui file. # it's a short term workaround only. [bruce 080808] from utilities.GlobalPreferences import debug_pref_support_Qt_4point2 # doesn't seem to work with qt 4.2? #if not debug_pref_support_Qt_4point2(): # self.gridlayout.setContentsMargins(0,0,0,2) self.gridlayout.setSpacing(2) self.gridlayout.setObjectName("gridlayout") self.comment_textedit = QtGui.QTextEdit(CommentPropDialog) self.comment_textedit.setObjectName("comment_textedit") self.gridlayout.addWidget(self.comment_textedit,0,0,1,1) self.hboxlayout = QtGui.QHBoxLayout() self.hboxlayout.setSpacing(4) self.hboxlayout.setObjectName("hboxlayout") self.date_time_btn = QtGui.QPushButton(CommentPropDialog) self.date_time_btn.setObjectName("date_time_btn") self.hboxlayout.addWidget(self.date_time_btn) spacerItem = QtGui.QSpacerItem(81,25,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout.addItem(spacerItem) self.cancel_btn = QtGui.QPushButton(CommentPropDialog) self.cancel_btn.setObjectName("cancel_btn") self.hboxlayout.addWidget(self.cancel_btn) self.ok__btn = QtGui.QPushButton(CommentPropDialog) self.ok__btn.setObjectName("ok__btn") self.hboxlayout.addWidget(self.ok__btn) spacerItem1 = QtGui.QSpacerItem(20,20,QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Minimum) self.hboxlayout.addItem(spacerItem1) self.gridlayout.addLayout(self.hboxlayout,1,0,1,1) self.retranslateUi(CommentPropDialog) QtCore.QObject.connect(self.cancel_btn,QtCore.SIGNAL("clicked()"),CommentPropDialog.reject) QtCore.QObject.connect(self.ok__btn,QtCore.SIGNAL("clicked()"),CommentPropDialog.accept) QtCore.QMetaObject.connectSlotsByName(CommentPropDialog) def retranslateUi(self, CommentPropDialog): CommentPropDialog.setWindowTitle(QtGui.QApplication.translate("CommentPropDialog", "Comment", None, QtGui.QApplication.UnicodeUTF8)) self.date_time_btn.setText(QtGui.QApplication.translate("CommentPropDialog", "Date/Time Stamp", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setText(QtGui.QApplication.translate("CommentPropDialog", "Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.ok__btn.setText(QtGui.QApplication.translate("CommentPropDialog", "OK", None, QtGui.QApplication.UnicodeUTF8))
NanoCAD-master
cad/src/commands/CommentProperties/CommentPropDialog.py
NanoCAD-master
cad/src/commands/ColorScheme/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ ColorScheme_PropertyManager.py The ColorScheme_PropertyManager class provides a Property Manager for choosing various colors (example: background) @author: Urmi @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. To do: - Save/load hh and selection color style settings into/from favorites file. """ import os, time, fnmatch import foundation.env as env from command_support.Command_PropertyManager import Command_PropertyManager from widgets.prefs_widgets import connect_checkbox_with_boolean_pref from utilities.prefs_constants import getDefaultWorkingDirectory from utilities.prefs_constants import workingDirectory_prefs_key from utilities.Log import greenmsg, redmsg from PyQt4.Qt import SIGNAL from PyQt4.Qt import QFileDialog, QString, QMessageBox from PyQt4.Qt import QColorDialog, QPixmap, QIcon from PM.PM_GroupBox import PM_GroupBox from PM.PM_ComboBox import PM_ComboBox from PM.PM_CheckBox import PM_CheckBox from PM.PM_ToolButtonRow import PM_ToolButtonRow from PM.PM_ColorComboBox import PM_ColorComboBox from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from utilities.constants import yellow, orange, red, magenta, cyan, blue from utilities.constants import white, black, gray, green, darkgreen from widgets.widget_helpers import RGBf_to_QColor, QColor_to_RGBf from utilities.icon_utilities import geticon from utilities.debug import print_compact_traceback bg_BLUE_SKY = 0 bg_EVENING_SKY = 1 bg_SEAGREEN = 2 bg_BLACK = 3 bg_WHITE = 4 bg_GRAY = 5 bg_CUSTOM = 6 #hover highlighting # HHS = hover highlighting styles from utilities.prefs_constants import HHS_INDEXES from utilities.prefs_constants import HHS_OPTIONS # SS = selection styles from utilities.prefs_constants import SS_INDEXES from utilities.prefs_constants import SS_OPTIONS from utilities.prefs_constants import hoverHighlightingColorStyle_prefs_key from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.prefs_constants import selectionColorStyle_prefs_key from utilities.prefs_constants import selectionColor_prefs_key from utilities.prefs_constants import backgroundColor_prefs_key from utilities.prefs_constants import backgroundGradient_prefs_key from utilities.prefs_constants import fogEnabled_prefs_key colorSchemePrefsList = \ [backgroundGradient_prefs_key, backgroundColor_prefs_key, fogEnabled_prefs_key, hoverHighlightingColorStyle_prefs_key, hoverHighlightingColor_prefs_key, selectionColorStyle_prefs_key, selectionColor_prefs_key ] # = # Color Scheme Favorite File I/O functions. def writeColorSchemeToFavoritesFile( basename ): """ Writes a "favorite file" (with a .txt extension) to store all the color scheme settings (pref keys and their current values). @param basename: The filename (without the .txt extension) to write. @type basename: string @note: The favorite file is written to the directory $HOME/Nanorex/Favorites/ColorScheme. """ if not basename: return 0, "No name given." # Get filename and write the favorite file. favfilepath = getFavoritePathFromBasename(basename) writeColorSchemeFavoriteFile(favfilepath) # msg = "Problem writing file [%s]" % favfilepath return 1, basename def getFavoritePathFromBasename( basename ): """ Returns the full path to the favorite file given a basename. @param basename: The favorite filename (without the .txt extension). @type basename: string @note: The (default) directory for all favorite files is $HOME/Nanorex/Favorites/ColorScheme. """ _ext = "txt" # Make favorite filename (i.e. ~/Nanorex/Favorites/ColorScheme/basename.txt) from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir _dir = find_or_make_Nanorex_subdir('Favorites/ColorScheme') return os.path.join(_dir, "%s.%s" % (basename, _ext)) def writeColorSchemeFavoriteFile( filename ): """ Writes a favorite file to I{filename}. """ f = open(filename, 'w') # Write header f.write ('!\n! Color Scheme favorite file') f.write ('\n!Created by NanoEngineer-1 on ') timestr = "%s\n!\n" % time.strftime("%Y-%m-%d at %H:%M:%S") f.write(timestr) #write preference list in file without the NE version for pref_key in colorSchemePrefsList: val = env.prefs[pref_key] pref_keyArray = pref_key.split("/") pref_key = pref_keyArray[1] if isinstance(val, int): f.write("%s = %d\n" % (pref_key, val)) #tuples written as string for now elif isinstance(val, tuple): f.write("%s = %s\n" % (pref_key, val)) elif isinstance(val, str): f.write("%s = %s\n" % (pref_key, val)) elif isinstance(val, bool): f.write("%s = %d\n" % (pref_key, val)) else: print "Not sure what pref_key '%s' is." % pref_key f.close() def loadFavoriteFile( filename ): """ Loads a favorite file from anywhere in the disk. @param filename: The full path for the favorite file. @type filename: string """ if os.path.exists(filename): favoriteFile = open(filename, 'r') else: env.history.message("Favorite file to be loaded does not exist.") return 0 # do syntax checking on the file to figure out whether this is a valid # favorite file line = favoriteFile.readline() line = favoriteFile.readline() if line != "! Color Scheme favorite file\n": env.history.message(" Not a proper favorite file") favoriteFile.close() return 0 while 1: line = favoriteFile.readline() # marks the end of file if line == "": break # process each line to obtain pref_keys and their corresponding values if line[0] != '!': keyValuePair = line.split('=') pref_keyString = keyValuePair[0].strip() pref_value = keyValuePair[1].strip() try: if backgroundColor_prefs_key.endswith(pref_keyString): pref_valueToStore = tuple(map(float, pref_value[1:-1].split(','))) elif backgroundGradient_prefs_key.endswith(pref_keyString): pref_valueToStore = int(pref_value) elif fogEnabled_prefs_key.endswith(pref_keyString): pref_valueToStore = bool(int(pref_value)) elif hoverHighlightingColorStyle_prefs_key.endswith(pref_keyString): pref_valueToStore = str(pref_value) elif hoverHighlightingColor_prefs_key.endswith(pref_keyString): pref_valueToStore = tuple(map(float, pref_value[1:-1].split(','))) elif selectionColorStyle_prefs_key.endswith(pref_keyString): pref_valueToStore = str(pref_value) elif selectionColor_prefs_key.endswith(pref_keyString): pref_valueToStore = tuple(map(float, pref_value[1:-1].split(','))) else: print "Not sure what pref_key '%s' is." % pref_keyString continue except: msg = "\npref_key = '%s'\nvalue = %s" \ % (pref_keyString, pref_value) print_compact_traceback(msg) pref_key = findPrefKey( pref_keyString ) #add preference key and its corresponding value to the dictionary if pref_key: env.prefs[pref_key] = pref_valueToStore favoriteFile.close() #check if a copy of this file exists in the favorites directory. If not make # a copy of it in there favName = os.path.basename(str(filename)) name = favName[0:len(favName)-4] favfilepath = getFavoritePathFromBasename(name) if not os.path.exists(favfilepath): saveFavoriteFile(favfilepath, filename) return 1 def findPrefKey( pref_keyString ): """ Matches prefence key in the colorSchemePrefsList with pref_keyString from the favorte file that we intend to load. @param pref_keyString: preference from the favorite file to be loaded. @type pref_keyString: string @note: very inefficient since worst case time taken is proportional to the size of the list. If original preference strings are in a dictionary, access can be done in constant time """ for keys in colorSchemePrefsList: #split keys in colorSchemePrefsList into version number and pref_key pref_array= keys.split("/") if pref_array[1] == pref_keyString: return keys return None def saveFavoriteFile( savePath, fromPath ): """ Save favorite file to anywhere in the disk @param savePath: full path for the location where the favorite file is to be saved. @type savePath: string @param savePath: ~/Nanorex/Favorites/ColorScheme/$FAV_NAME.txt @type fromPath: string """ if savePath: saveFile = open(savePath, 'w') if fromPath: fromFile = open(fromPath, 'r') lines = fromFile.readlines() saveFile.writelines(lines) saveFile.close() fromFile.close() return # = _superclass = Command_PropertyManager class ColorScheme_PropertyManager(Command_PropertyManager): """ The ColorScheme_PropertyManager class provides a Property Manager for choosing background and other colors for the Choose Color toolbar command as well as the View/Color Scheme command @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Color Scheme" pmName = title iconPath = "ui/actions/View/ColorScheme.png" def __init__( self, command ): """ Constructor for the property manager. """ self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key] _superclass.__init__(self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) msg = "Edit the color scheme for NE1, including the background color, "\ "hover highlighting and selection colors, etc." self.updateMessage(msg) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect # Favorite buttons signal-slot connections. change_connect( self.applyFavoriteButton, SIGNAL("clicked()"), self.applyFavorite) change_connect( self.addFavoriteButton, SIGNAL("clicked()"), self.addFavorite) change_connect( self.deleteFavoriteButton, SIGNAL("clicked()"), self.deleteFavorite) change_connect( self.saveFavoriteButton, SIGNAL("clicked()"), self.saveFavorite) change_connect( self.loadFavoriteButton, SIGNAL("clicked()"), self.loadFavorite) # background color setting combo box. change_connect( self.backgroundColorComboBox, SIGNAL("activated(int)"), self.changeBackgroundColor ) #hover highlighting style combo box change_connect(self.hoverHighlightingStyleComboBox, SIGNAL("currentIndexChanged(int)"), self.changeHoverHighlightingStyle) change_connect(self.hoverHighlightingColorComboBox, SIGNAL("editingFinished()"), self.changeHoverHighlightingColor) #selection style combo box change_connect(self.selectionStyleComboBox, SIGNAL("currentIndexChanged(int)"), self.changeSelectionStyle) change_connect(self.selectionColorComboBox, SIGNAL("editingFinished()"), self.changeSelectionColor) def changeHoverHighlightingColor(self): """ Slot method for Hover Highlighting color chooser. Change the (3D) hover highlighting color. """ color = self.hoverHighlightingColorComboBox.getColor() env.prefs[hoverHighlightingColor_prefs_key] = color return def changeHoverHighlightingStyle(self, idx): """ Slot method for Hover Highlighting combobox. Change the (3D) hover highlighting style. """ env.prefs[hoverHighlightingColorStyle_prefs_key] = HHS_INDEXES[idx] def changeSelectionStyle(self, idx): """ Slot method for Selection color style combobox. Change the (3D) Selection color style. """ env.prefs[selectionColorStyle_prefs_key] = SS_INDEXES[idx] def changeSelectionColor(self): """ Slot method for Selection color chooser. Change the (3D) Selection color. """ color = self.selectionColorComboBox.getColor() env.prefs[selectionColor_prefs_key] = color return def show(self): """ Shows the Property Manager. Extends superclass method. """ self._updateAllWidgets() _superclass.show(self) def _addGroupBoxes( self ): """ Add the Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Favorites") self._loadGroupBox1( self._pmGroupBox1 ) self._pmGroupBox2 = PM_GroupBox( self, title = "Background") self._loadGroupBox2( self._pmGroupBox2 ) self._pmGroupBox3 = PM_GroupBox( self, title = "Highlighting and Selection") self._loadGroupBox3( self._pmGroupBox3 ) self._updateAllWidgets() def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box. """ # Other info # Not only loads the factory default settings but also all the favorite # files stored in the ~/Nanorex/Favorites/DnaDisplayStyle directory favoriteChoices = ['Factory default settings'] #look for all the favorite files in the favorite folder and add them to # the list from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir _dir = find_or_make_Nanorex_subdir('Favorites/ColorScheme') for file in os.listdir(_dir): fullname = os.path.join( _dir, file) if os.path.isfile(fullname): if fnmatch.fnmatch( file, "*.txt"): # leave the extension out favoriteChoices.append(file[0:len(file)-4]) self.favoritesComboBox = \ PM_ComboBox( pmGroupBox, choices = favoriteChoices, spanWidth = True) # PM_ToolButtonRow =============== # Button list to create a toolbutton row. # Format: # - QToolButton, buttonId, buttonText, # - iconPath, # - tooltip, shortcut, column BUTTON_LIST = [ ( "QToolButton", 1, "APPLY_FAVORITE", "ui/actions/Properties Manager/ApplyColorSchemeFavorite.png", "Apply Favorite", "", 0), ( "QToolButton", 2, "ADD_FAVORITE", "ui/actions/Properties Manager/AddFavorite.png", "Add Favorite", "", 1), ( "QToolButton", 3, "DELETE_FAVORITE", "ui/actions/Properties Manager/DeleteFavorite.png", "Delete Favorite", "", 2), ( "QToolButton", 4, "SAVE_FAVORITE", "ui/actions/Properties Manager/SaveFavorite.png", "Save Favorite", "", 3), ( "QToolButton", 5, "LOAD_FAVORITE", "ui/actions/Properties Manager/LoadFavorite.png", "Load Favorite", \ "", 4) ] self.favsButtonGroup = \ PM_ToolButtonRow( pmGroupBox, title = "", buttonList = BUTTON_LIST, spanWidth = True, isAutoRaise = False, isCheckable = False, setAsDefault = True, ) self.favsButtonGroup.buttonGroup.setExclusive(False) self.applyFavoriteButton = self.favsButtonGroup.getButtonById(1) self.addFavoriteButton = self.favsButtonGroup.getButtonById(2) self.deleteFavoriteButton = self.favsButtonGroup.getButtonById(3) self.saveFavoriteButton = self.favsButtonGroup.getButtonById(4) self.loadFavoriteButton = self.favsButtonGroup.getButtonById(5) def _loadGroupBox2(self, pmGroupBox): """ Load widgets in group box. """ #background color combo box self.backgroundColorComboBox = \ PM_ComboBox( pmGroupBox, label = "Color:", spanWidth = False) self._loadBackgroundColorItems() self.enableFogCheckBox = \ PM_CheckBox( pmGroupBox, text = "Enable fog" ) connect_checkbox_with_boolean_pref( self.enableFogCheckBox, fogEnabled_prefs_key ) return def _loadGroupBox3(self, pmGroupBox): """ Load widgets in group box. """ # hover highlighting style and color self.hoverHighlightingStyleComboBox = \ PM_ComboBox( pmGroupBox, label = "Highlighting:", ) self._loadHoverHighlightingStyleItems() hhColorList = [yellow, orange, red, magenta, cyan, blue, white, black, gray] hhColorNames = ["Yellow (default)", "Orange", "Red", "Magenta", "Cyan", "Blue", "White", "Black", "Other color..."] self.hoverHighlightingColorComboBox = \ PM_ColorComboBox(pmGroupBox, colorList = hhColorList, colorNames = hhColorNames, color = env.prefs[hoverHighlightingColor_prefs_key] ) # selection style and color self.selectionStyleComboBox = \ PM_ComboBox( pmGroupBox, label = "Selection:", ) self._loadSelectionStyleItems() selColorList = [darkgreen, green, orange, red, magenta, cyan, blue, white, black, gray] selColorNames = ["Dark green (default)", "Green", "Orange", "Red", "Magenta", "Cyan", "Blue", "White", "Black", "Other color..."] self.selectionColorComboBox = \ PM_ColorComboBox(pmGroupBox, colorList = selColorList, colorNames = selColorNames, color = env.prefs[selectionColor_prefs_key] ) return def _updateAllWidgets(self): """ Update all the PM widgets. This is typically called after applying a favorite. """ self._updateBackgroundColorComboBoxIndex() self.updateCustomColorItemIcon(RGBf_to_QColor(env.prefs[backgroundColor_prefs_key])) self.hoverHighlightingStyleComboBox.setCurrentIndex(HHS_INDEXES.index(env.prefs[hoverHighlightingColorStyle_prefs_key])) self.hoverHighlightingColorComboBox.setColor(env.prefs[hoverHighlightingColor_prefs_key]) self.selectionStyleComboBox.setCurrentIndex(SS_INDEXES.index(env.prefs[selectionColorStyle_prefs_key])) self.selectionColorComboBox.setColor(env.prefs[selectionColor_prefs_key]) return def _loadSelectionStyleItems(self): """ Load the selection color style combobox with items. """ for selectionStyle in SS_OPTIONS: self.selectionStyleComboBox.addItem(selectionStyle) return def _loadHoverHighlightingStyleItems(self): """ Load the hover highlighting style combobox with items. """ for hoverHighlightingStyle in HHS_OPTIONS: self.hoverHighlightingStyleComboBox.addItem(hoverHighlightingStyle) return def _loadBackgroundColorItems(self): """ Load the background color combobox with all the color options and sets the current background color """ backgroundIndexes = [bg_BLUE_SKY, bg_EVENING_SKY, bg_SEAGREEN, bg_BLACK, bg_WHITE, bg_GRAY, bg_CUSTOM] backgroundNames = ["Blue Sky (default)", "Evening Sky", "Sea Green", "Black", "White", "Gray", "Custom..."] backgroundIcons = ["Background_BlueSky", "Background_EveningSky", "Background_SeaGreen", "Background_Black", "Background_White", "Background_Gray", "Background_Custom"] backgroundIconsDict = dict(zip(backgroundNames, backgroundIcons)) backgroundNamesDict = dict(zip(backgroundIndexes, backgroundNames)) for backgroundName in backgroundNames: basename = backgroundIconsDict[backgroundName] + ".png" iconPath = os.path.join("ui/dialogs/Preferences/", basename) self.backgroundColorComboBox.addItem(geticon(iconPath), backgroundName) self._updateBackgroundColorComboBoxIndex() # Not needed, but OK. return def _updateBackgroundColorComboBoxIndex(self): """ Set current index in the background color combobox. """ if self.win.glpane.backgroundGradient: self.backgroundColorComboBox.setCurrentIndex(self.win.glpane.backgroundGradient - 1) else: if (env.prefs[ backgroundColor_prefs_key ] == black): self.backgroundColorComboBox.setCurrentIndex(bg_BLACK) elif (env.prefs[ backgroundColor_prefs_key ] == white): self.backgroundColorComboBox.setCurrentIndex(bg_WHITE) elif (env.prefs[ backgroundColor_prefs_key ] == gray): self.backgroundColorComboBox.setCurrentIndex(bg_GRAY) else: self.backgroundColorComboBox.setCurrentIndex(bg_CUSTOM) return def changeBackgroundColor(self, idx): """ Slot method for the background color combobox. """ #print "changeBackgroundColor(): Slot method called. Idx =", idx if idx == bg_BLUE_SKY: self.win.glpane.setBackgroundGradient(idx + 1) elif idx == bg_EVENING_SKY: self.win.glpane.setBackgroundGradient(idx + 1) elif idx == bg_SEAGREEN: self.win.glpane.setBackgroundGradient(idx + 1) elif idx == bg_BLACK: self.win.glpane.setBackgroundColor(black) elif idx == bg_WHITE: self.win.glpane.setBackgroundColor(white) elif idx == bg_GRAY: self.win.glpane.setBackgroundColor(gray) elif idx == bg_CUSTOM: #change background color to Custom Color self.chooseCustomBackgroundColor() else: msg = "Unknown color idx=", idx print_compact_traceback(msg) self.win.glpane.gl_update() # Needed! return def chooseCustomBackgroundColor(self): """ Choose a custom background color. """ c = QColorDialog.getColor(RGBf_to_QColor(self.win.glpane.getBackgroundColor()), self) if c.isValid(): self.win.glpane.setBackgroundColor(QColor_to_RGBf(c)) self.updateCustomColorItemIcon(c) else: # User cancelled. Need to reset combobox to correct index. self._updateBackgroundColorComboBoxIndex() return def updateCustomColorItemIcon(self, qcolor): """ Update the custom color item icon in the background color combobox with I{qcolor}. """ pixmap = QPixmap(16, 16) pixmap.fill(qcolor) self.backgroundColorComboBox.setItemIcon(bg_CUSTOM, QIcon(pixmap)) return def applyFavorite(self): """ Apply the color scheme settings stored in the current favorite (selected in the combobox) to the current color scheme settings. """ # Rules and other info: # The user has to press the button related to this method when he loads # a previously saved favorite file current_favorite = self.favoritesComboBox.currentText() if current_favorite == 'Factory default settings': env.prefs.restore_defaults(colorSchemePrefsList) # set it back to blue sky self.win.glpane.setBackgroundGradient(1) else: favfilepath = getFavoritePathFromBasename(current_favorite) loadFavoriteFile(favfilepath) if env.prefs[backgroundGradient_prefs_key]: self.win.glpane.setBackgroundGradient(env.prefs[backgroundGradient_prefs_key]) else: self.win.glpane.setBackgroundColor(env.prefs[backgroundColor_prefs_key]) #self.hoverHighlightingColorComboBox.setColor(env.prefs[hoverHighlightingColor_prefs_key]) #self.selectionColorComboBox.setColor(env.prefs[selectionColor_prefs_key]) self._updateAllWidgets() self.win.glpane.gl_update() return def addFavorite(self): """ Adds a new favorite to the user's list of favorites. """ # Rules and other info: # - The new favorite is defined by the current color scheme # settings. # - The user is prompted to type in a name for the new # favorite. # - The color scheme settings are written to a file in a special # directory on the disk # (i.e. $HOME/Nanorex/Favorites/ColorScheme/$FAV_NAME.txt). # - The name of the new favorite is added to the list of favorites in # the combobox, which becomes the current option. # Existence of a favorite with the same name is checked in the above # mentioned location and if a duplicate exists, then the user can either # overwrite and provide a new name. # Prompt user for a favorite name to add. from widgets.simple_dialogs import grab_text_line_using_dialog ok1, name = \ grab_text_line_using_dialog( title = "Add new favorite", label = "favorite name:", iconPath = "ui/actions/Properties Manager/AddFavorite.png", default = "" ) if ok1: # check for duplicate files in the # $HOME/Nanorex/Favorites/ColorScheme/ directory fname = getFavoritePathFromBasename( name ) if os.path.exists(fname): #favorite file already exists! _ext= ".txt" ret = QMessageBox.warning( self, "Warning!", "The favorite file \"" + name + _ext + "\"already exists.\n" "Do you want to overwrite the existing file?", "&Overwrite", "&Cancel", "", 0, # Enter == button 0 1) # Escape == button 1 if ret == 0: #overwrite favorite file ok2, text = writeColorSchemeToFavoritesFile(name) indexOfDuplicateItem = self.favoritesComboBox.findText(name) self.favoritesComboBox.removeItem(indexOfDuplicateItem) print "Add Favorite: removed duplicate favorite item." else: env.history.message("Add Favorite: cancelled overwriting favorite item.") return else: ok2, text = writeColorSchemeToFavoritesFile(name) else: # User cancelled. return if ok2: self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) msg = "New favorite [%s] added." % (text) else: msg = "Can't add favorite [%s]: %s" % (name, text) # text is reason why not env.history.message(msg) return def deleteFavorite(self): """ Deletes the current favorite from the user's personal list of favorites (and from disk, only in the favorites folder though). @note: Cannot delete "Factory default settings". """ currentIndex = self.favoritesComboBox.currentIndex() currentText = self.favoritesComboBox.currentText() if currentIndex == 0: msg = "Cannot delete '%s'." % currentText else: self.favoritesComboBox.removeItem(currentIndex) # delete file from the disk deleteFile= getFavoritePathFromBasename( currentText ) os.remove(deleteFile) msg = "Deleted favorite named [%s].\n" \ "and the favorite file [%s.txt]." \ % (currentText, currentText) env.history.message(msg) return def saveFavorite(self): """ Writes the current favorite (selected in the combobox) to a file, any where in the disk that can be given to another NE1 user (i.e. as an email attachment). """ cmd = greenmsg("Save Favorite File: ") env.history.message(greenmsg("Save Favorite File:")) current_favorite = self.favoritesComboBox.currentText() favfilepath = getFavoritePathFromBasename(current_favorite) #Check to see if favfilepath exists first if not os.path.exists(favfilepath): msg = "%s does not exist" % favfilepath env.history.message(cmd + msg) return formats = \ "Favorite (*.txt);;"\ "All Files (*.*)" directory = self.currentWorkingDirectory saveLocation = directory + "/" + current_favorite + ".txt" fn = QFileDialog.getSaveFileName( self, "Save Favorite As", # caption saveLocation, #where to save formats, # file format options QString("Favorite (*.txt)") # selectedFilter ) if not fn: env.history.message(cmd + "Cancelled") else: #remember this directory dir, fil = os.path.split(str(fn)) self.setCurrentWorkingDirectory(dir) saveFavoriteFile(str(fn), favfilepath) return def setCurrentWorkingDirectory(self, dir = None): if os.path.isdir(dir): self.currentWorkingDirectory = dir self._setWorkingDirectoryInPrefsDB(dir) else: self.currentWorkingDirectory = getDefaultWorkingDirectory() def _setWorkingDirectoryInPrefsDB(self, workdir = None): """ [private method] Set the working directory in the user preferences database. @param workdir: The fullpath directory to write to the user pref db. If I{workdir} is None (default), there is no change. @type workdir: string """ if not workdir: return workdir = str(workdir) if os.path.isdir(workdir): workdir = os.path.normpath(workdir) env.prefs[workingDirectory_prefs_key] = workdir # Change pref in prefs db. else: msg = "[" + workdir + "] is not a directory. Working directory was not changed." env.history.message( redmsg(msg)) return def loadFavorite(self): """ Prompts the user to choose a "favorite file" (i.e. *.txt) from disk to be added to the personal favorites list. """ # If the file already exists in the favorites folder then the user is # given the option of overwriting it or renaming it env.history.message(greenmsg("Load Favorite File:")) formats = \ "Favorite (*.txt);;"\ "All Files (*.*)" directory = self.currentWorkingDirectory if directory == '': directory= getDefaultWorkingDirectory() fname = QFileDialog.getOpenFileName(self, "Choose a file to load", directory, formats) if not fname: env.history.message("User cancelled loading file.") return else: dir, fil = os.path.split(str(fname)) self.setCurrentWorkingDirectory(dir) canLoadFile = loadFavoriteFile(fname) if canLoadFile == 1: #get just the name of the file for loading into the combobox favName = os.path.basename(str(fname)) name = favName[0:len(favName)-4] indexOfDuplicateItem = self.favoritesComboBox.findText(name) #duplicate exists in combobox if indexOfDuplicateItem != -1: ret = QMessageBox.warning( self, "Warning!", "The favorite file \"" + name + "\"already exists.\n" "Do you want to overwrite the existing file?", "&Overwrite", "&Rename", "&Cancel", 0, # Enter == button 0 1 # button 1 ) if ret == 0: self.favoritesComboBox.removeItem(indexOfDuplicateItem) self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) ok2, text = writeColorSchemeToFavoritesFile(name) msg = "Overwrote favorite [%s]." % (text) env.history.message(msg) elif ret == 1: # add new item to favorites folder as well as combobox self.addFavorite() else: #reset the display setting values to factory default factoryIndex = self.favoritesComboBox.findText( 'Factory default settings') self.favoritesComboBox.setCurrentIndex(factoryIndex) env.prefs.restore_defaults(colorSchemePrefsList) # set it back to blue sky self.win.glpane.setBackgroundGradient(1) self.win.glpane.gl_update() env.history.message("Cancelled overwriting favorite file.") return else: self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) msg = "Loaded favorite [%s]." % (name) env.history.message(msg) if env.prefs[backgroundGradient_prefs_key]: self.win.glpane.setBackgroundGradient(env.prefs[backgroundGradient_prefs_key]) else: self.win.glpane.setBackgroundColor(env.prefs[backgroundColor_prefs_key]) self.win.glpane.gl_update() return def _addWhatsThisText( self ): """ What's This text for widgets in the Color Scheme Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_ColorScheme_PropertyManager WhatsThis_ColorScheme_PropertyManager(self) def _addToolTipText(self): """ Tool Tip text for widgets in the Color Scheme Property Manager. """ #modify this for color schemes from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_ColorScheme_PropertyManager ToolTip_ColorScheme_PropertyManager(self)
NanoCAD-master
cad/src/commands/ColorScheme/ColorScheme_PropertyManager.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Urmi @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ import foundation.changes as changes from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode from command_support.EditCommand import EditCommand from utilities.constants import red from commands.ColorScheme.ColorScheme_PropertyManager import ColorScheme_PropertyManager # == GraphicsMode part _superclass_for_GM = SelectChunks_GraphicsMode class ColorScheme_GraphicsMode( SelectChunks_GraphicsMode ): """ Graphics mode for (DNA) Display Style command. """ pass # == Command part class ColorScheme_Command(EditCommand): """ """ # class constants #@TODO: may be it should inherit Select_Command. Check. commandName = 'COLOR_SCHEME' featurename = "Color Scheme" from utilities.constants import CL_GLOBAL_PROPERTIES command_level = CL_GLOBAL_PROPERTIES GraphicsMode_class = ColorScheme_GraphicsMode PM_class = ColorScheme_PropertyManager command_should_resume_prevMode = True command_has_its_own_PM = True
NanoCAD-master
cad/src/commands/ColorScheme/ColorScheme_Command.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ CoNTubGenerator.py - Generator functions which use cad/plugins/CoNTub. @author: Bruce @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. Also intended as a prototype of code which could constitute the nE-1 side of a "generator plugin API". Accordingly, the CoNTub-specific code should as much as possible be isolated into small parts of this, with most of it knowing nothing about CoNTub's specific functionality or parameters. """ # how to test this: execute this in a debugger: """ import commands.InsertHeterojunction.CoNTubGenerator as CoNTubGenerator reload(CoNTubGenerator) """ # Each time you do that, Insert menu gets a new command "Heterojunction". The first one is always the latest one. import os, sys, time import foundation.env as env import utilities.Initialize as Initialize from utilities.Log import quote_html, redmsg ##, orangemsg, greenmsg from command_support.ParameterDialog import ParameterDialog, ParameterPane from command_support.GeneratorController import GeneratorController from utilities.exception_classes import UserError, PluginBug from utilities.debug import print_compact_traceback from platform_dependent.PlatformDependent import find_or_make_any_directory, tempfiles_dir, find_plugin_dir import utilities.EndUser as EndUser debug_install = False def debug_run(): return False # change to env.debug() or a debug pref, someday; # also some debug prints we cause in other files don't check this, but they should ### one current bug: menu icon is nondeterministic. guess: need to keep a reference to the iconset that we make for it. # that seemed to help at first, but it's not enough, bug still happens sometimes when we reload this a lot! ####@@@@ from utilities.debug_prefs import use_property_pane # == def add_insert_menu_item(win, command, name_of_what_to_insert, options = ()): ###e this should be a method of MWsemantics.py menuIndex = 2 ### kluge - right after Nanotube, at the moment (since indices start from 0) menu = win.buildStructuresMenu menutext = "%s" % (name_of_what_to_insert,) undo_cmdname = "Insert %s" % (name_of_what_to_insert,) ## get this from caller, or, make it available to the command as it runs ###e but need to translate it ourselves, ##qApp.translate("Main Window", "Recent Files", None) ## self.connect(self.recentFilePopupMenu, SIGNAL('activated (int)'), self._openRecentFile) from widgets.menu_helpers import insert_command_into_menu insert_command_into_menu( menu, menutext, command, options = options, position = menuIndex, undo_cmdname = undo_cmdname) return # == try: output_counter except: output_counter = 0 def parse_arg_pattern(argpat): """ Turn argpat into a list of strings, each a nonempty constant or $param; allowed argpat formats are just these three: word, $param.word, $param [Someday we might extend this, perhaps even allowing expressions like $dict[$key].] """ # just break it at each '$' or '.' assert not '@' in argpat # use this as a marker for splitpoints #e (could be \00 in case '@' gets used in a real command line) argpat = argpat.replace('$','@$') argpat = argpat.replace('.','@.') argpat = argpat.split('@') if not argpat[0]: argpat = argpat[1:] assert argpat assert argpat == filter(None, argpat), \ "argpat %r should equal filtered one %r" % (argpat, filter(None, argpat)) # no other empty strings are legal return argpat def arg_str(arg): """ like str(arg) but suitable for use on a command line """ try: ###@@@ horrible temporary kluge for $T item -> value mapping res = {"None":0, "Hydrogen": 1, "Nitrogen": 7}[arg] arg = res except KeyError: pass return str(arg) ###e stub, probably good enough for contub class PluginlikeGenerator: """ Superclass for generators whose code is organized similar to that of a (future) plugin. Subclasses contain data and methods which approximate the functionality of metadata and/or code that would ultimately be found in a plugin directory. See the example subclass in this file for details. """ ok_to_install_in_UI = False # changed to True in instances which become ok to install into the UI; see also errorcode # default values of subclass-specific class constants what_we_generate = "Something" # init methods def register(subclass): # staticmethod win = env.mainwindow() try: instance = subclass(win) if instance.ok_to_install_in_UI: instance.install_in_UI() if debug_install: print "debug: registered", instance else: if debug_install: print "debug: didn't register", instance except: print_compact_traceback("bug in instantiating %r or installing its instance: " % subclass) return register = staticmethod(register) errorcode = 0 # this gets set to something true (by self.fatal) if an error occurs which should # permanently disable this plugin (during setup or use) errortext = "" # this gets set to errortext for the first error that permanently disabled this plugin def fatal(self, errortext, errorcode = 1): """ Our submethods call this to report a fatal setup/use error; it prints errortext appropriately and sets self.errorcode and self.errortext. """ if not errorcode: print "bug: fatal errorcode must be a boolean-true value, not %r" % (errorcode,) errorcode = 1 if self.errorcode: print "plugin %r bug: self.errorcode was already set before fatal was called" % (self.plugin_name,) if not self.errorcode or not self.errortext: self.errortext = errortext # permanent record for use by callers self.errorcode = errorcode msg = "plugin %r fatal error: %s" % (self.plugin_name, errortext,) print msg env.history.message(redmsg(quote_html(msg))) # it might be too early for this to be seen return errorcode def __init__(self, win): self.win = win # All these submethods should call self.fatal to report permanent fatal errors. # And after calling the ones that can, we should check self.errorcode before continuing. # Find plugin dir -- if we can't, it has to be a fatal error, # since (once this is using a real plugin API) we won't have the metadata # needed to install the plugin in the UI. path = self.find_plugin_dir() if self.errorcode: return self.plugin_dir = path # for error messages, and used by runtime methods # make sure the stuff we need is in the plugin dir (and try to use it to set up the dialogs, commands, etc) self.setup_from_plugin_dir() # this prints error msgs if it needs to if self.errorcode: return # don't create a working directory until the plugin is first used # (since we don't want to create one at all, if it's not used in the session, # since they might be created in a session-specific place) self.working_directory = None if debug_install: print "plugin init is permitting ok_to_install_in_UI = True" self.ok_to_install_in_UI = True return def find_plugin_dir(self): ok, path = find_plugin_dir(self.plugin_name) if ok: assert os.path.isdir(path) return path else: errortext = path self.fatal( errortext) return None pass def setup_from_plugin_dir(self): """ Using self.plugin_dir, setup dialogs, commands, etc. Report errors to self.fatal as usual. """ # The following will someday read metainfo from the plugin.desc file, # but for now we just grab that info from constants set by the subclass # (the subclass which won't exist when this is a real public plugin API). # param desc file (must exist) param_desc_path = os.path.join(self.plugin_dir, self.parameter_set_filename) self.param_desc_path = param_desc_path if not os.path.isfile(param_desc_path): return self.fatal("can't find param description file [%s]" % (param_desc_path,)) # executable (find its path, make sure it exists) self.executable # should be provided by subclass if sys.platform == 'win32': executable_names = [self.executable + ".exe", self.executable] # Windows: try both, in this order else: executable_names = [self.executable] # Linux or Mac: only try plain name self.executable_path = None for tryname in executable_names: executable_path = os.path.join(self.plugin_dir, "bin", tryname) if os.path.exists(executable_path): # assume if it exists at all, it's the command we want # (it might be a file or a symlink, and I'm not sure if isfile works across symlinks; # if it does, we'd want to use isfile here, and warn if exists but not isfile #k) self.executable_path = executable_path if debug_install: print "plugin exec path = %r" % (executable_path,) break continue if not self.executable_path: return self.fatal("can't find executable; looked for %s" % (executable_names,)) self.setup_commandline_info() # this is far below, just before the code that uses what it computes ###e maybe get the param set, create the dialog, etc # (even run a self test if it defines one? or wait 'til first used?) return whatsThisText = """<u><b>Insert Heterojunction</b></u> <p>A heterojunction is a joint connecting two carbon nanotubes which may differ in radius and chirality. The joint is made of sp<sup>2</sup>-hybridized carbon atoms, arranged in hexagons and pentagons (the pentagons allow for curvature of the surface) to join the two nanotubes with the same material they are composed of.</p> <p>This is Nanorex\'s modified version of the CoNTub source code written by S. Melchor and J. Dobado at the Universidad de Granada in Spain. Citations of this work should be formatted as follows:<p> <blockquote>"CoNTub: an algorithm for connecting two arbitrary carbon nanotubes." S. Melchor; J.A. Dobado. Journal of Chemical Information and Computer Sciences, 44, 1639-1646 (2004)</blockquote> <p>Nanorex\'s modifications include translation from Java to C++, performance improvement in bond inference, changing the output file format from pdb to mmp, and revising the stderr messages and exit code. </p>""" def install_in_UI(self): """ Create a menu command, or whatever other UI elements should invoke the plugin's generator. Report errors to self.fatal as usual. """ assert self.ok_to_install_in_UI #e create whatever we want to be persistent which was not already done in setup_from_plugin_dir (nothing yet?) #e install the necessary commands in the UI (eg in insert menu) ### WRONG -- menu text should not contain Insert, but undo cmdname should (so separate option is needed), and needs icon ###e add options for things like tooltip text, whatsthis text, iconset icon_path = self.find_title_icon() options = [('iconset', icon_path), ('whatsThis', self.whatsThisText)] self.menu_item_id = add_insert_menu_item( self.win, self.command_for_insert_menu, self.what_we_generate, options) ###e make that a menu item controller, and give it a method to disable the menu item, and do that on error(??) ###@@@ pass def find_title_icon(self): icon_path = os.path.join(self.plugin_dir, "images/HJ_icon.png") #######@@@@@@@ KLUGE - hardcode this relpath for now ###@@@ need to get icon name from one of the desc files (not positive which one, probably params but if there is one # for the overall "single generator command" then from that one), interpret it using an icon path, and then feed it # not only to this menu item, but to the generated dialog as well. this code to find it will be in setup_from_plugin_dir # I think. or maybe (also) called again each time we make the dialog? if not os.path.isfile(icon_path): print "didn't find [%s], using modeltree/junk.png" % icon_path icon_path = "modeltree/junk.png" # icon_path will be found later by imagename_to_pixmap I think; does it work with an abspath too?? #####@@@@@ return icon_path # runtime methods def create_working_directory_if_needed(self): """ If it hasn't been done already, create a temporary directory (fixed pathname per plugin per session) for this plugin to use. Report errors to self.fatal as usual. """ if self.working_directory: return subdir = os.path.join( tempfiles_dir(), "plugin-" + self.plugin_name ) errorcode, path = find_or_make_any_directory(subdir) if errorcode: # should never happen, but make sure caller checks self.errorcode (set by fatal) just in case #####@@@@@ errortext = path return self.fatal(errortext) self.working_directory = subdir return dialog = None param_desc_path_modtime = None def make_dialog_if_needed(self): """ Create self.dialog if necessary. """ # For developers, remake the dialog from its description file each time that file changes. # (The point of only remaking it then is not speed, but to test the code when it doesn't get remade, # since that's what always happens for non-developers.) # (Someday, when remaking it, copy its window geometry from the old one. Then put that code into the MMKit too. ###e) # For others, only make it the first time. if (EndUser.enableDeveloperFeatures() or env.debug()) and self.dialog: # For developers, remake the dialog if its description file changed (by zapping the old dialog here). zapit = False modtime = os.stat(self.param_desc_path).st_mtime if modtime != self.param_desc_path_modtime: zapit = True self.param_desc_path_modtime = modtime if zapit: #e save geometry? self.dialog.hide() self.dialog.destroy() ###k self.dialog = None pass if not self.dialog: if debug_run(): print "making dialog from", self.parameter_set_filename dialog_env = self # KLUGE... it needs to be something with an imagename_to_pixmap function that knows our icon_path. # the easiest way to make one is self... in future we want our own env, and to modify it by inserting that path... if use_property_pane(): # experimental, doesn't yet work [060623] parent = self.win.vsplitter2 ###@@@ could this parent be wrong? it acted like parent was self.win or so. clas = ParameterPane ###@@@ worked internally, buttons printed debug msgs, but didn't have any effects in GBC. else: # usual case parent = self.win clas = ParameterDialog self.dialog = clas( self.win, self.param_desc_path, env = dialog_env ) # this parses the description file and makes the dialog, # but does not show it and does not connect a controller to it. #e set its geometry if that was saved (from above code or maybe in prefs db) return def imagename_to_pixmap(self, imagename): # KLUGE, see comment where dialog_env is set to self ###@@@ might work but untested ###@@@ from utilities.icon_utilities import imagename_to_pixmap path = None for trydir in [self.plugin_dir, os.path.join(self.plugin_dir, "images")]: trypath = os.path.join( trydir, imagename ) if os.path.isfile(trypath): # assume it's the one we want path = trypath break if not path: path = imagename # use relative name return imagename_to_pixmap(path) def command_for_insert_menu(self): """ Run an Insert Whatever menu command to let the user generate things using this plugin. """ if self.errorcode: env.history.message(redmsg("Plugin %r is permanently disabled due to this error, reported previously: %s" % \ (self.plugin_name, self.errortext))) return self.create_working_directory_if_needed() assert not self.errorcode if debug_run(): print 'ought to insert a', self.what_we_generate self.make_dialog_if_needed() dialog = self.dialog ###e Not yet properly handled: retaining default values from last time it was used. (Should pass dict of them to the maker.) dialog.set_defaults({}) ### IMPLEM controller = GeneratorController(self.win, dialog, self) # Note: this needs both self and the dialog, to be inited. # So it takes care of telling the dialog to control it (and not some prior controller). dialog.show() # now it's able to take commands and run its callbacks; that does not happen inside this method, though, does it? # hmm, good question... if it's modal, this makes things easier (re preview and bug protection)... # and it means the undo wrapping was ok... but what do we do here to make it modal? # 1. find out by test if other generators are modal. # 2. find out from code, how. pass###e def build_struct(self, name, params, position): """ Same API as in GeneratorBaseClass (though we are not its subclass). On error, raise an exception. """ # get executable, append exe, ensure it exists program = self.executable_path # make command line args from params args, outfiles = self.command_line_args_and_outfiles(params, name) # makes param args and outputfile args; # args is a list of strings (including outfile names); # outfiles is a list of full pathnames of files this command might create # run executable using the way we run the sim exitcode = self.run_command(program, args) #e look at exitcode? if exitcode and debug_run(): print "generator exitcode: %r" % (exitcode,) if exitcode: # treat this as a fatal error for this run [to test, use an invalid chirality with m > n] msg = "Plugin %r exitcode: %r" % (self.plugin_name, exitcode) ## not needed, GBC UserError will do it, more or less: env.history.message(redmsg(msg)) ###e should: self.remove_outfiles(outfiles, complain_if_missing = False) raise UserError(msg) # this prints a redmsg; maybe we'd rather do that ourselves, and raise SilentUserError (nim)?? # look for outfiles # (if there are more than one specified, for now just assume all of them need to be there) for outfile in outfiles: if not os.path.exists(outfile): ###e should: self.remove_outfiles(outfiles, complain_if_missing = False) raise PluginBug( "generator output file should exist but doesn't: [%s]" % (outfile,) ) # insert file contents, rename the object in it, return that (see dna generator) thing = self.insert_output(outfiles, params, name) # we pass params, since some params might affect insertion (or postprocessing) # other than by affecting the command output ###@@@ WARNING: the following repositioning code is not correct for all kinds of "things", # only for single-chunk things like for CoNTub # (and also it probably belongs inside insert_output, not here): for atom in thing.atoms.values(): atom.setposn(atom.posn() + position) self.remove_outfiles(outfiles) return thing def setup_commandline_info(self): """ #doc [This is run at setup time, but we put this method here since the arg data it compiles (into a nonobvious internal format) is used to make the command lines at runtime, in the methods just below.] """ # command-line, output file info # examples: ## outputfiles_pattern = "$out1.mmp" ## executable_args_pattern = "$n1 $m1 $L1 $n2 $m2 $L2 $T 1 $out1.mmp" self.outputfiles_pattern # make sure subclass defines these self.executable_args_pattern self.outfile_pats = map( parse_arg_pattern, self.outputfiles_pattern.split()) self.cmdline_pats = map( parse_arg_pattern, self.executable_args_pattern.split()) if debug_install: print "got these parsed argpats: %r\nand outfiles: %r" % (self.cmdline_pats, self.outfile_pats) self.paramnames_dict = {} # for now, maps pn -> $pn self.outfile_paramname_extension_pairs = [] # one or more pairs of ($paramname_for_filebasename, extension), e.g. [('$out1', '.mmp')] self.paramnames_order = [] # needed for defining order of tuples from gather_parameters; leave out outfile params; # this attr will be used directly by our GeneratorController for pat in self.outfile_pats: assert len(pat) <= 2 # ok if no extension, at least for now try: baseparam, ext = pat except: baseparam, ext = pat, '' assert baseparam.startswith('$') assert not ext or ext.startswith('.') self.outfile_paramname_extension_pairs.append(( baseparam, ext )) ### leave in '$' -- useful to look up val self.outfile_paramnames = [pn[1:] for (pn, ext) in self.outfile_paramname_extension_pairs] for pat in self.cmdline_pats: for word in pat: if word.startswith('$'): name = word[1:] if name not in self.paramnames_dict: self.paramnames_dict[name] = word # so it maps x -> $x if name not in self.outfile_paramnames: self.paramnames_order.append(name) pass continue continue assert self.paramnames_dict assert self.paramnames_order assert self.outfile_paramname_extension_pairs if debug_install: print "outfile_paramname_extension_pairs:", self.outfile_paramname_extension_pairs print "paramnames_dict", self.paramnames_dict print "outfile_paramnames", self.outfile_paramnames print "paramnames_order", self.paramnames_order # see command_line_args_and_outfiles() for how all this is used return def command_line_args_and_outfiles(self, params, name): """ Given the parameter-value tuple (same order as self.paramnames_order), and the desired name of the generated structure in the MT (optional to use it here since insert code will also impose it), return a list of command line args, and a list of output files, for use in one command run. """ workdir = self.working_directory outfiles = [] args = [] paramvals = {} # $pn -> value for subst for pn, val in zip(self.paramnames_order, params): paramvals['$' + pn] = val for (pn, ext) in self.outfile_paramname_extension_pairs: # pn is like $out1, ext is empty or like .mmp, and only some exts are supported but that's up to insert method global output_counter output_counter += 1 basename = 'output%d' % output_counter #e improve? make it be the same if we preview?? (how? GBC AP doesn't tell us!) path = os.path.join( workdir, basename + ext) outfiles.append( path) assert pn not in paramvals paramvals[pn] = os.path.join( workdir, basename) # leave ext off of this, since cmdline pattern adds it back for argpat in self.cmdline_pats: arg = "" for word in argpat: if word.startswith('$'): arg += arg_str(paramvals[word]) else: arg += word assert arg args.append(arg) return args, outfiles def run_command(self, program, args): if debug_run(): print "will run this command:", program, args from PyQt4.Qt import QStringList, QProcess, QObject, SIGNAL, QDir # modified from runSim.py arguments = QStringList() if sys.platform == 'win32': program = "\"%s\"" % program # Double quotes needed by Windows. ###@@@ test this ### try it with blanks in output file name and in program name, once it works ###@@@ for arg in [program] + args: if arg: arguments.append(arg) self.simProcess = simProcess = QProcess() simProcess.setArguments(arguments) simProcess.setWorkingDirectory(QDir(self.working_directory)) # in case it writes random files if 1: # report stdout/stderr def blabout(): print "stdout:", simProcess.readStdout() ##e should also mention its existence in history, but don't copy it all there in case a lot def blaberr(): text = str(simProcess.readStderr()) # str since it's QString (i hope it can't be unicode) print "stderr:", text env.history.message(redmsg("%s stderr: " % self.plugin_name + quote_html(text))) # examples from CoNTub/bin/HJ: # stderr: BAD INPUT # stderr: Error: Indices of both tubes coincide QObject.connect(simProcess, SIGNAL("readyReadStdout()"), blabout) QObject.connect(simProcess, SIGNAL("readyReadStderr()"), blaberr) started = simProcess.start() ###k what is this code? i forget if true means ok or error if debug_run(): print "qprocess started:",started while 1: ###e need to make it abortable! from which abort button? ideally, one on the dialog; maybe cancel button?? # on exception: simProcess.kill() if simProcess.isRunning(): if debug_run(): print "still running" time.sleep(1) else: time.sleep(0.1) else: break if debug_run(): print "process done i guess: normalExit = %r, (if normal) exitStatus = %r" % \ (simProcess.normalExit(), simProcess.exitStatus()) if 1: QObject.disconnect(simProcess, SIGNAL("readyReadStdout()"), blabout) QObject.disconnect(simProcess, SIGNAL("readyReadStderr()"), blaberr) if simProcess.normalExit(): return simProcess.exitStatus() else: return -1 def insert_output(self, outfiles, params, name): ## return self.create_methane_test(params, name) if debug_run(): print "inserting output from",outfiles ###@@@ # modified from dna generator's local function insertmmp(filename, tfm) assert len(outfiles) == 1 # for now filename = outfiles[0] assert filename.endswith('.mmp') # for now; in future, also permit .pdb or anything else we know how to read assy = self.win.assy #k from files.mmp.files_mmp import readmmp ok_junk, grouplist = readmmp(assy, filename, isInsert = True) # WARNING: ok_junk is not a boolean; see readmmp doc for details if not grouplist: raise Exception("Trouble with output file: " + filename)###@@@ predict NameError: Exception (good enough for now) viewdata, mainpart, shelf = grouplist if len(mainpart.members) == 1: thing = mainpart.members[0] else: thing = mainpart # won't happen for now del viewdata #k or kill? thing.name = name shelf.kill() # wware 060704 - fix valence problems on the ends while True: found_one = False for atm in thing.atoms.values(): if atm.element.symbol == 'C' and len(atm.realNeighbors()) == 1: atm.kill() found_one = True if not found_one: break for atm in thing.atoms.values(): if atm.element.symbol == 'C' and len(atm.realNeighbors()) == 2: atm.set_atomtype('sp2', always_remake_bondpoints = True) # problem: for some kinds of errors, the only indication is that we're inserting a 0-atom mol, not a many-atom mol. hmm. ####@@@@ return thing # doesn't actually insert it, GBC does that def remove_outfiles(self, outfiles): print "removing these files is nim:", outfiles ###@@@ def create_methane_test(self, params, name): # example: build some methanes print "create_methane_test" assy = self.win.assy from geometry.VQT import V from model.chunk import Chunk from model.chem import Atom mol = Chunk(assy, 'bug') # name is reset below! n = max(params[0],1) for x in range(n): for y in range(2): ## build methane, much like make_Atom_and_bondpoints method does it pos = V(x,y,0) atm = Atom('C', pos, mol) atm.make_bondpoints_when_no_bonds() # notices atomtype mol.name = name ## assy.addmol(mol) return mol pass # end of class PluginlikeGenerator class HeterojunctionGenerator(PluginlikeGenerator): """ Encapsulate the plugin-specific data and code (or references to it) for the CoNTub plugin's heterojunction command. In a real plugin API, this data would come from the plugin directory, and this code would be equivalent to either code in nE-1 parameterized by metadata in the plugin directory, and/or actual code in the plugin directory. (The present example is clearly simple enough to be the contents of a metadata file, but not all of the other built-in generators are that simple.) """ topic = 'CoNTub' # for sponsor_keyword for GeneratorBaseClass's SponsorableMixin superclass (and for submenu?) what_we_generate = "Heterojunction" # used for insert menu item text, undo cmdname, history messages, new node names; not sure about wikihelp featurename menu_item_icon = "blablabla" plugin_name = "CoNTub" # used as directory name, looked for in ~/Nanorex/Plugins someday, and in cad/plugins now and someday... parameter_set_filename = "HJ-params.desc" executable = "HJ" # no .exe, we'll add that if necessary on Windows ## this might not be required of every class outputfiles_pattern = "$out1.mmp" executable_args_pattern = "$n1 $m1 $L1 $n2 $m2 $L2 $T 1 $out1.mmp" pass # end of class HeterojunctionGenerator def initialize(): # must be called after mainwindow exists if (Initialize.startInitialization(__name__)): return PluginlikeGenerator.register(HeterojunctionGenerator) Initialize.endInitialization(__name__) # end
NanoCAD-master
cad/src/commands/InsertHeterojunction/CoNTubGenerator.py
NanoCAD-master
cad/src/commands/InsertHeterojunction/__init__.py
NanoCAD-master
cad/src/commands/ElementColors/__init__.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ elementColors.py - dialog for changing element color table; related functions @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. """ from PyQt4.Qt import QDialog from PyQt4.Qt import SIGNAL from PyQt4.Qt import QVBoxLayout from PyQt4.Qt import QFileDialog from PyQt4.Qt import QMessageBox from PyQt4.Qt import QApplication from PyQt4.QtOpenGL import QGLFormat from commands.ElementColors.ElementColorsDialog import Ui_ElementColorsDialog from model.elements import PeriodicTable from utilities.constants import diTrueCPK, diBALL, diTUBES from graphics.widgets.ThumbView import ElementView from utilities.qt4transition import qt4todo from utilities.Log import redmsg # Mark 050311 from widgets.widget_helpers import RGBf_to_QColor import foundation.env as env class elementColors(QDialog, Ui_ElementColorsDialog): _displayList = (diTUBES, diBALL, diTrueCPK) def __init__(self, win): qt4todo('what to do with all those options?') ## ElementColorsDialog.__init__(self, win, None, 0, ## Qt.WStyle_Customize | Qt.WStyle_NormalBorder | ## Qt.WStyle_Title | Qt.WStyle_SysMenu) QDialog.__init__(self, win) self.setupUi(self) self.connect(self.okButton, SIGNAL("clicked()"), self.ok) self.connect(self.loadColorsPB, SIGNAL("clicked()"), self.read_element_rgb_table) self.connect(self.saveColorsPB, SIGNAL("clicked()"), self.write_element_rgb_table) self.connect(self.cancelButton, SIGNAL("clicked()"), self.reject) self.connect(self.defaultButton, SIGNAL("clicked()"), self.loadDefaultProp) self.connect(self.alterButton, SIGNAL("clicked()"), self.loadAlterProp) self.connect(self.elementButtonGroup, SIGNAL("clicked(int)"), self.setElementInfo) self.connect(self.previewPB, SIGNAL("clicked()"), self.preview_color_change) self.connect(self.restorePB, SIGNAL("clicked()"), self.restore_current_color) self.w = win self.fileName = None self.isElementModified = False self.isFileSaved = False self.oldTable = PeriodicTable.deepCopy() self.elemTable = PeriodicTable self.displayMode = self._displayList[0] # The next line fixes a bug. Thumbview expects self.gridLayout on # line 117 of Thumbview.py. Mark 2007-10-19. self.gridLayout = self.gridlayout self.elemGLPane = ElementView(self, "element glPane", self.w.glpane) # Put the GL widget inside the frame flayout = QVBoxLayout(self.elementFrame) flayout.setMargin(1) flayout.setSpacing(1) flayout.addWidget(self.elemGLPane, 1) def elementId(symbol): return PeriodicTable.getElement(symbol).eltnum self.toolButton6.setChecked(True) self.elementButtonGroup.setId(self.toolButton6, elementId("C")) self.elementButtonGroup.setId(self.toolButton8, elementId("O")) self.elementButtonGroup.setId(self.toolButton10, elementId("Ne")) self.elementButtonGroup.setId(self.toolButton9, elementId("F")) self.elementButtonGroup.setId(self.toolButton13, elementId("Al")) self.elementButtonGroup.setId(self.toolButton17, elementId("Cl")) self.elementButtonGroup.setId(self.toolButton5, elementId("B")) self.elementButtonGroup.setId(self.toolButton10_2, elementId("Ar")) self.elementButtonGroup.setId(self.toolButton15, elementId("P")) self.elementButtonGroup.setId(self.toolButton16, elementId("S")) self.elementButtonGroup.setId(self.toolButton14, elementId("Si")) self.elementButtonGroup.setId(self.toolButton33, elementId("As")) self.elementButtonGroup.setId(self.toolButton34, elementId("Se")) self.elementButtonGroup.setId(self.toolButton35, elementId("Br")) self.elementButtonGroup.setId(self.toolButton36, elementId("Kr")) self.elementButtonGroup.setId(self.toolButton32, elementId("Ge")) self.elementButtonGroup.setId(self.toolButton7, elementId("N")) self.elementButtonGroup.setId(self.toolButton2, elementId("He")) self.elementButtonGroup.setId(self.toolButton1, elementId("H")) self.elementButtonGroup.setId(self.toolButton0, elementId("X")) self.connect(self.toolButton6, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton8, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton10, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton9, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton13, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton17, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton5, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton10_2, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton15, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton16, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton14, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton33, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton34, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton35, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton36, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton32, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton7, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton2, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton1, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connect(self.toolButton0, SIGNAL("clicked()"), self.updateElemColorDisplay) self.connectChangingControls() self.saveColorsPB.setWhatsThis( """Save the current color settings for elements in a text file.""") self.defaultButton.setWhatsThis( """Restore current element colors to the default colors.""") self.loadColorsPB.setWhatsThis( """Load element colors from an external text file.""") self.alterButton.setWhatsThis( """Set element colors to the alternate color set.""") def closeEvent(self, e): """ When user closes dialog by clicking the 'X' button on the dialog title bar, this method is called """ self.ok() def connectChangingControls(self): self.connect(self.redSlider, SIGNAL("valueChanged(int)"), self.changeSpinRed) self.connect(self.redSpinBox, SIGNAL("valueChanged(int)"), self.changeSliderRed) self.connect(self.blueSlider, SIGNAL("valueChanged(int)"), self.changeSpinBlue) self.connect(self.blueSpinBox, SIGNAL("valueChanged(int)"), self.changeSliderBlue) self.connect(self.greenSlider, SIGNAL("valueChanged(int)"), self.changeSpinGreen) self.connect(self.greenSpinBox, SIGNAL("valueChanged(int)"), self.changeSliderGreen) def loadDefaultProp(self): """ Load default set of color/rvdw for the current periodic table """ self.elemTable.loadDefaults() self._updateModelDisplay() elemNum = self.elementButtonGroup.checkedId() self.setDisplay(elemNum) self.isElementModified = True def loadAlterProp(self): """ Load alternate set of color/rvdw for the current periodic table """ self.elemTable.loadAlternates() self._updateModelDisplay() elemNum = self.elementButtonGroup.checkedId() self.setDisplay(elemNum) self.isElementModified = True def changeDisplayMode(self, value): """ Called when any of the display mode radioButton clicked. Obsolete. """ assert value in [0, 1, 2] newMode = self._displayList[value] if newMode != self.displayMode: self.displayMode = newMode elemNum = self.elementButtonGroup.checkedId() elm = self.elemTable.getElement(elemNum) self.elemGLPane.refreshDisplay(elm, self.displayMode) def setElementInfo(self, value): """ Called as a slot from an element button push. """ self.setDisplay(value) def setDisplay(self, value): qt4todo('self.elementButtonGroup.setButton(value)') self.updateElemGraphDisplay() self.original_color = self.color element_color = RGBf_to_QColor(self.color) self.update_sliders_and_spinboxes(element_color) self.restorePB.setEnabled(0) # Disable Restore button. def update_sliders_and_spinboxes(self, color): self.redSlider.setValue(color.red()) self.greenSlider.setValue(color.green()) self.blueSlider.setValue(color.blue()) self.redSpinBox.setValue(color.red()) self.greenSpinBox.setValue(color.green()) self.blueSpinBox.setValue(color.blue()) def updateElemGraphDisplay(self): """ Update non user interactive controls display for current selected element: element label info and element graphics info """ elemNum = self.elementButtonGroup.checkedId() self.color = self.elemTable.getElemColor(elemNum) elm = self.elemTable.getElement(elemNum) self.elemGLPane.resetView() self.elemGLPane.refreshDisplay(elm, self.displayMode) def updateElemColorDisplay(self): """ Update GL display for user's color change. """ elemNum = self.elementButtonGroup.checkedId() self.color = self.elemTable.getElemColor(elemNum) elm = self.elemTable.getElement(elemNum) self.elemGLPane.updateColorDisplay(elm, self.displayMode) self.restorePB.setEnabled(1) # Enable Restore button. def read_element_rgb_table(self): """ Open file browser to select a file to read from, read the data, update elements color in the selector dialog and also the display models """ # Determine what directory to open. import os if self.w.assy.filename: odir = os.path.dirname(self.w.assy.filename) else: from utilities.prefs_constants import workingDirectory_prefs_key odir = env.prefs[workingDirectory_prefs_key] self.fileName = str( QFileDialog.getOpenFileName( self, "Load Element Color", odir, "Elements color file (*.txt);;All Files (*.*);;" )) if self.fileName: colorTable = readElementColors(self.fileName) if not colorTable: msg = "Error in element colors file: [" + self.fileName + "]. Colors not loaded." env.history.message(redmsg(msg)) else: msg = "Element colors loaded from file: [" + self.fileName + "]." env.history.message(msg) for row in colorTable: row[1] /= 255.0 row[2] /= 255.0 row[3] /= 255.0 self.elemTable.setElemColors(colorTable) self._updateModelDisplay() elemNum = self.elementButtonGroup.checkedId() self.setDisplay(elemNum) #After loading a file, reset the flag self.isElementModified = False def write_element_rgb_table(self): """ Save the current set of element preferences into an external file -- currently only r,g,b color of each element will be saved. """ if not self.fileName: from utilities.prefs_constants import workingDirectory_prefs_key sdir = env.prefs[workingDirectory_prefs_key] else: sdir = self.fileName fn = QFileDialog.getSaveFileName( self, "Save Element Colors As ...", sdir, "Element Color File (*.txt)" ) if fn: fn = str(fn) if fn[-4] != '.': fn += '.txt' import os if os.path.exists(fn): # ...and if the "Save As" file exists... # ... confirm overwrite of the existing file. ret = QMessageBox.warning( self, "Save Element Colors...", "The file \"" + fn + "\" already exists.\n" "Do you want to overwrite the existing file or cancel?", "&Overwrite", "&Cancel", "", 0, # Enter == button 0 1 ) # Escape == button 1 if ret == 1: # The user cancelled return # write the current set of element colors into a file saveElementColors(fn, self.elemTable.getAllElements()) env.history.message("Element colors saved in file: [" + fn + "]") #After saving a file, reset the flag self.isFileSaved = True def changeSpinRed(self, a0): self.redSpinBox.blockSignals(True) self.redSpinBox.setValue(a0) elemNum = self.elementButtonGroup.checkedId() self.elemTable.setElemColor(elemNum, [a0/255.0, self.color[1], self.color[2]]) self.updateElemColorDisplay() self.isElementModified = True self.redSpinBox.blockSignals(False) def changeSliderRed(self, a0): self.redSlider.blockSignals(True) self.redSlider.setValue(a0) elemNum = self.elementButtonGroup.checkedId() self.elemTable.setElemColor(elemNum, [a0/255.0, self.color[1], self.color[2]]) self.updateElemColorDisplay() self.isElementModified = True self.redSlider.blockSignals(False) def changeSpinBlue(self, a0): self.blueSpinBox.blockSignals(True) self.blueSpinBox.setValue(a0) elemNum = self.elementButtonGroup.checkedId() self.elemTable.setElemColor(elemNum, [self.color[0], self.color[1], a0/255.0]) self.updateElemColorDisplay() self.isElementModified = True self.blueSpinBox.blockSignals(False) def changeSliderBlue(self, a0): self.blueSlider.blockSignals(True) self.blueSlider.setValue(a0) elemNum = self.elementButtonGroup.checkedId() self.elemTable.setElemColor(elemNum, [self.color[0], self.color[1], a0/255.0]) self.updateElemColorDisplay() self.isElementModified = True self.blueSlider.blockSignals(False) def changeSpinGreen(self, a0): self.greenSpinBox.blockSignals(True) self.greenSpinBox.setValue(a0) elemNum = self.elementButtonGroup.checkedId() self.elemTable.setElemColor(elemNum, [self.color[0], a0/255.0, self.color[2]]) self.updateElemColorDisplay() self.isElementModified = True self.greenSpinBox.blockSignals(False) def changeSliderGreen(self, a0): self.greenSlider.blockSignals(True) self.greenSlider.setValue(a0) elemNum = self.elementButtonGroup.checkedId() self.elemTable.setElemColor(elemNum, [self.color[0], a0/255.0, self.color[2]]) self.updateElemColorDisplay() self.isElementModified = True self.greenSlider.blockSignals(False) def preview_color_change(self): # mark 060129. """ Slot for Preview button. Applies color changes for the current element in the GLPane, allowing the user to preview the color changes in the model before saving. """ self._updateModelDisplay() def restore_current_color(self): # mark 060129. """ Slot for the Restore button. Restores the current element color to the original (previous) color before any color change was made. """ self.update_sliders_and_spinboxes(RGBf_to_QColor(self.original_color)) self._updateModelDisplay() def ok(self): ## if self.isElementModified and not self.isFileSaved: ## ret = QMessageBox.question(self, "Warnings", ## "Do you want to save the element colors into a file?", ## QMessageBox.Yes, QMessageBox.No ) ## if ret == QMessageBox.Yes: ## self.write_element_rgb_table() #Save the color preference self.elemTable.close() self._updateModelDisplay() #bruce 090119 bugfix self.accept() def reject(self): """ If elements modified or external file loaded, restore current pref to original since our dialog is reused """ if self.isElementModified or self.fileName: self.elemTable.resetElemTable(self.oldTable) self._updateModelDisplay() QDialog.reject(self) def _updateModelDisplay(self): """ Update model display """ #bruce 090119 removed changeapp calls, not needed for a long time # (due to PeriodicTable.color_change_counter); # then replaced other calls of gl_update with calls of this method self.w.glpane.gl_update() # == #bruce 050414 moved readElementColors and saveElementColors from fileIO.py # into this module, and (while they were still in fileIO -- see its cvs diff) # slightly revised the wording/formatting of their docstrings. # Sometime they should be changed to print their error messages into the # history widget, not sys.stdout. def readElementColors(fileName): """ Read element colors (ele #, r, g, b) from a text file. Each element is on a new line. A line starting '#' is a comment line. <Parameter> fileName: a string for the input file name <Return>: A list of quardral tuples--(ele #, r, g, b) if succeed, otherwise 'None' """ try: lines = open(fileName, "rU").readlines() except: print "Exception occurred to open file: ", fileName return None elemColorTable = [] for line in lines: if not line.startswith('#'): try: words = line.split() row = map(int, words[:4]) # Check Element Number validity if row[0] >= 0 and row[0] <= 54: # Check RGB index values if row[1] < 0 or row[1] > 255 \ or row[2] < 0 or row[2] > 255 \ or row[3] < 0 or row[3] > 255: raise ValueError, "An RGB index value not in a valid range (0-255)." elemColorTable += [row] else: raise ValueError, "Element number value not in a valid range." except: # todo: env.history.redmsg print "Error in element color file [%s]." % (fileName,) print "Invalid value in line: %s" % (line,) print "Element color file not loaded." return None return elemColorTable def saveElementColors(fileName, elemTable): """ Write element colors (ele #, r, g, b) into a text file. Each element is on a new line. A line starting '#' is a comment line. <Parameter> fileName: a string for the input file name <Parameter> elemTable: A dictionary object of all elements in our periodical table """ assert type(fileName) == type(" ") try: f = open(fileName, "w") except: print "Exception occurred to open file %s to write: " % fileName return None f.write("# NanoEngineer-1.com Element Color File, Version 050311\n") f.write("# File format: ElementNumber r(0-255) g(0-255) b(0-255) \n") for eleNum, elm in elemTable.items(): col = elm.color r = int(col[0] * 255 + 0.5) g = int(col[1] * 255 + 0.5) b = int(col[2] * 255 + 0.5) f.write(str(eleNum) + " " + str(r) + " " + str(g) + " " + str(b) + "\n" ) f.close() # == Test code import sys if __name__ == '__main__': QApplication.setColorSpec(QApplication.CustomColor) app = QApplication(sys.argv) if not QGLFormat.hasOpenGL(): raise Exception("No Qt OpenGL support.") w = elementColors(None) app.setMainWidget(w) w.resize(400, 350) w.show() w.setCaption('box') app.exec_()
NanoCAD-master
cad/src/commands/ElementColors/elementColors.py
# -*- coding: utf-8 -*- # Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details. # Form implementation generated from reading ui file 'ElementColorsDialog.ui' # # Created: Wed Sep 20 10:09:44 2006 # by: PyQt4 UI code generator 4.0.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_ElementColorsDialog(object): def setupUi(self, ElementColorsDialog): ElementColorsDialog.setObjectName("ElementColorsDialog") ElementColorsDialog.resize(QtCore.QSize(QtCore.QRect(0,0,231,557).size()).expandedTo(ElementColorsDialog.minimumSizeHint())) palette = QtGui.QPalette() palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(0),QtGui.QColor(0,0,0)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(1),QtGui.QColor(230,231,230)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(2),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(3),QtGui.QColor(242,243,242)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(4),QtGui.QColor(115,115,115)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(5),QtGui.QColor(153,154,153)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(6),QtGui.QColor(0,0,0)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(7),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(8),QtGui.QColor(0,0,0)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(9),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(10),QtGui.QColor(230,231,230)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(11),QtGui.QColor(0,0,0)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(12),QtGui.QColor(0,0,128)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(13),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(14),QtGui.QColor(0,0,0)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(15),QtGui.QColor(0,0,0)) palette.setColor(QtGui.QPalette.Active,QtGui.QPalette.ColorRole(16),QtGui.QColor(232,232,232)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(0),QtGui.QColor(0,0,0)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(1),QtGui.QColor(230,231,230)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(2),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(3),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(4),QtGui.QColor(115,115,115)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(5),QtGui.QColor(153,154,153)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(6),QtGui.QColor(0,0,0)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(7),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(8),QtGui.QColor(0,0,0)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(9),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(10),QtGui.QColor(230,231,230)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(11),QtGui.QColor(0,0,0)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(12),QtGui.QColor(0,0,128)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(13),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(14),QtGui.QColor(0,0,255)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(15),QtGui.QColor(255,0,255)) palette.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.ColorRole(16),QtGui.QColor(232,232,232)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(0),QtGui.QColor(128,128,128)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(1),QtGui.QColor(230,231,230)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(2),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(3),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(4),QtGui.QColor(115,115,115)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(5),QtGui.QColor(153,154,153)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(6),QtGui.QColor(128,128,128)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(7),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(8),QtGui.QColor(128,128,128)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(9),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(10),QtGui.QColor(230,231,230)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(11),QtGui.QColor(0,0,0)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(12),QtGui.QColor(0,0,128)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(13),QtGui.QColor(255,255,255)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(14),QtGui.QColor(0,0,255)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(15),QtGui.QColor(255,0,255)) palette.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.ColorRole(16),QtGui.QColor(232,232,232)) ElementColorsDialog.setPalette(palette) self.gridlayout = QtGui.QGridLayout(ElementColorsDialog) self.gridlayout.setMargin(2) self.gridlayout.setSpacing(4) self.gridlayout.setObjectName("gridlayout") self.elementFrame = QtGui.QFrame(ElementColorsDialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(1)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.elementFrame.sizePolicy().hasHeightForWidth()) self.elementFrame.setSizePolicy(sizePolicy) self.elementFrame.setMinimumSize(QtCore.QSize(0,150)) self.elementFrame.setFrameShape(QtGui.QFrame.Box) self.elementFrame.setFrameShadow(QtGui.QFrame.Raised) self.elementFrame.setObjectName("elementFrame") self.gridlayout.addWidget(self.elementFrame,0,0,1,1) self.gridlayout1 = QtGui.QGridLayout() self.gridlayout1.setMargin(0) self.gridlayout1.setSpacing(6) self.gridlayout1.setObjectName("gridlayout1") self.hboxlayout = QtGui.QHBoxLayout() self.hboxlayout.setMargin(0) self.hboxlayout.setSpacing(6) self.hboxlayout.setObjectName("hboxlayout") self.textLabel2 = QtGui.QLabel(ElementColorsDialog) self.textLabel2.setMaximumSize(QtCore.QSize(40,32767)) self.textLabel2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.textLabel2.setObjectName("textLabel2") self.hboxlayout.addWidget(self.textLabel2) self.redSpinBox = QtGui.QSpinBox(ElementColorsDialog) self.redSpinBox.setEnabled(True) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(1),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.redSpinBox.sizePolicy().hasHeightForWidth()) self.redSpinBox.setSizePolicy(sizePolicy) self.redSpinBox.setFocusPolicy(QtCore.Qt.ClickFocus) self.redSpinBox.setMaximum(255) self.redSpinBox.setObjectName("redSpinBox") self.hboxlayout.addWidget(self.redSpinBox) self.gridlayout1.addLayout(self.hboxlayout,0,0,1,1) self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setMargin(0) self.hboxlayout1.setSpacing(6) self.hboxlayout1.setObjectName("hboxlayout1") self.textLabel2_2 = QtGui.QLabel(ElementColorsDialog) self.textLabel2_2.setMaximumSize(QtCore.QSize(40,32767)) self.textLabel2_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.textLabel2_2.setObjectName("textLabel2_2") self.hboxlayout1.addWidget(self.textLabel2_2) self.greenSpinBox = QtGui.QSpinBox(ElementColorsDialog) self.greenSpinBox.setEnabled(True) self.greenSpinBox.setFocusPolicy(QtCore.Qt.ClickFocus) self.greenSpinBox.setMaximum(255) self.greenSpinBox.setObjectName("greenSpinBox") self.hboxlayout1.addWidget(self.greenSpinBox) self.gridlayout1.addLayout(self.hboxlayout1,1,0,1,1) self.hboxlayout2 = QtGui.QHBoxLayout() self.hboxlayout2.setMargin(0) self.hboxlayout2.setSpacing(6) self.hboxlayout2.setObjectName("hboxlayout2") self.textLabel2_3 = QtGui.QLabel(ElementColorsDialog) self.textLabel2_3.setMaximumSize(QtCore.QSize(40,32767)) self.textLabel2_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.textLabel2_3.setObjectName("textLabel2_3") self.hboxlayout2.addWidget(self.textLabel2_3) self.blueSpinBox = QtGui.QSpinBox(ElementColorsDialog) self.blueSpinBox.setEnabled(True) self.blueSpinBox.setFocusPolicy(QtCore.Qt.ClickFocus) self.blueSpinBox.setMaximum(255) self.blueSpinBox.setObjectName("blueSpinBox") self.hboxlayout2.addWidget(self.blueSpinBox) self.gridlayout1.addLayout(self.hboxlayout2,2,0,1,1) self.blueSlider = QtGui.QSlider(ElementColorsDialog) self.blueSlider.setEnabled(True) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.blueSlider.sizePolicy().hasHeightForWidth()) self.blueSlider.setSizePolicy(sizePolicy) self.blueSlider.setMaximum(255) self.blueSlider.setOrientation(QtCore.Qt.Horizontal) self.blueSlider.setTickInterval(25) self.blueSlider.setObjectName("blueSlider") self.gridlayout1.addWidget(self.blueSlider,2,1,1,1) self.redSlider = QtGui.QSlider(ElementColorsDialog) self.redSlider.setEnabled(True) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.redSlider.sizePolicy().hasHeightForWidth()) self.redSlider.setSizePolicy(sizePolicy) self.redSlider.setMaximum(255) self.redSlider.setOrientation(QtCore.Qt.Horizontal) self.redSlider.setTickInterval(25) self.redSlider.setObjectName("redSlider") self.gridlayout1.addWidget(self.redSlider,0,1,1,1) self.greenSlider = QtGui.QSlider(ElementColorsDialog) self.greenSlider.setEnabled(True) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.greenSlider.sizePolicy().hasHeightForWidth()) self.greenSlider.setSizePolicy(sizePolicy) self.greenSlider.setMaximum(255) self.greenSlider.setOrientation(QtCore.Qt.Horizontal) self.greenSlider.setTickInterval(25) self.greenSlider.setObjectName("greenSlider") self.gridlayout1.addWidget(self.greenSlider,1,1,1,1) self.gridlayout.addLayout(self.gridlayout1,1,0,1,1) spacerItem = QtGui.QSpacerItem(20,16,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Fixed) self.gridlayout.addItem(spacerItem,6,0,1,1) self.elementButtonGroup = QtGui.QButtonGroup(ElementColorsDialog) elementButtonGroupWidget = QtGui.QGroupBox(ElementColorsDialog) elementButtonGroupWidget.setMinimumSize(QtCore.QSize(0,126)) self.elementButtonGroup.setObjectName("elementButtonGroup") self.gridlayout2 = QtGui.QGridLayout(elementButtonGroupWidget) self.gridlayout2.setMargin(2) self.gridlayout2.setSpacing(0) self.gridlayout2.setObjectName("gridlayout2") self.toolButton6 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton6) self.toolButton6.setMinimumSize(QtCore.QSize(30,30)) self.toolButton6.setCheckable(True) self.toolButton6.setObjectName("toolButton6") self.gridlayout2.addWidget(self.toolButton6,1,1,1,1) self.toolButton8 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton8) self.toolButton8.setMinimumSize(QtCore.QSize(30,30)) self.toolButton8.setCheckable(True) self.toolButton8.setObjectName("toolButton8") self.gridlayout2.addWidget(self.toolButton8,1,3,1,1) self.toolButton10 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton10) self.toolButton10.setMinimumSize(QtCore.QSize(30,30)) self.toolButton10.setCheckable(True) self.toolButton10.setObjectName("toolButton10") self.gridlayout2.addWidget(self.toolButton10,1,5,1,1) self.toolButton9 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton9) self.toolButton9.setMinimumSize(QtCore.QSize(30,30)) self.toolButton9.setCheckable(True) self.toolButton9.setObjectName("toolButton9") self.gridlayout2.addWidget(self.toolButton9,1,4,1,1) self.toolButton13 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton13) self.toolButton13.setMinimumSize(QtCore.QSize(30,30)) self.toolButton13.setCheckable(True) self.toolButton13.setObjectName("toolButton13") self.gridlayout2.addWidget(self.toolButton13,2,0,1,1) self.toolButton17 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton17) self.toolButton17.setMinimumSize(QtCore.QSize(30,30)) self.toolButton17.setCheckable(True) self.toolButton17.setObjectName("toolButton17") self.gridlayout2.addWidget(self.toolButton17,2,4,1,1) self.toolButton5 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton5) self.toolButton5.setMinimumSize(QtCore.QSize(30,30)) self.toolButton5.setCheckable(True) self.toolButton5.setObjectName("toolButton5") self.gridlayout2.addWidget(self.toolButton5,1,0,1,1) self.toolButton10_2 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton10_2) self.toolButton10_2.setMinimumSize(QtCore.QSize(30,30)) self.toolButton10_2.setCheckable(True) self.toolButton10_2.setObjectName("toolButton10_2") self.gridlayout2.addWidget(self.toolButton10_2,2,5,1,1) self.toolButton15 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton15) self.toolButton15.setMinimumSize(QtCore.QSize(30,30)) self.toolButton15.setCheckable(True) self.toolButton15.setObjectName("toolButton15") self.gridlayout2.addWidget(self.toolButton15,2,2,1,1) self.toolButton16 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton16) self.toolButton16.setMinimumSize(QtCore.QSize(30,30)) self.toolButton16.setCheckable(True) self.toolButton16.setObjectName("toolButton16") self.gridlayout2.addWidget(self.toolButton16,2,3,1,1) self.toolButton14 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton14) self.toolButton14.setMinimumSize(QtCore.QSize(30,30)) self.toolButton14.setCheckable(True) self.toolButton14.setObjectName("toolButton14") self.gridlayout2.addWidget(self.toolButton14,2,1,1,1) self.toolButton33 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton33) self.toolButton33.setMinimumSize(QtCore.QSize(30,30)) self.toolButton33.setCheckable(True) self.toolButton33.setObjectName("toolButton33") self.gridlayout2.addWidget(self.toolButton33,3,2,1,1) self.toolButton34 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton34) self.toolButton34.setMinimumSize(QtCore.QSize(30,30)) self.toolButton34.setCheckable(True) self.toolButton34.setObjectName("toolButton34") self.gridlayout2.addWidget(self.toolButton34,3,3,1,1) self.toolButton35 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton35) self.toolButton35.setMinimumSize(QtCore.QSize(30,30)) self.toolButton35.setCheckable(True) self.toolButton35.setObjectName("toolButton35") self.gridlayout2.addWidget(self.toolButton35,3,4,1,1) self.toolButton36 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton36) self.toolButton36.setMinimumSize(QtCore.QSize(30,30)) self.toolButton36.setCheckable(True) self.toolButton36.setObjectName("toolButton36") self.gridlayout2.addWidget(self.toolButton36,3,5,1,1) self.toolButton32 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton32) self.toolButton32.setMinimumSize(QtCore.QSize(30,30)) self.toolButton32.setCheckable(True) self.toolButton32.setObjectName("toolButton32") self.gridlayout2.addWidget(self.toolButton32,3,1,1,1) self.toolButton7 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton7) self.toolButton7.setMinimumSize(QtCore.QSize(30,30)) self.toolButton7.setCheckable(True) self.toolButton7.setObjectName("toolButton7") self.gridlayout2.addWidget(self.toolButton7,1,2,1,1) self.toolButton2 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton2) self.toolButton2.setMinimumSize(QtCore.QSize(30,30)) self.toolButton2.setCheckable(True) self.toolButton2.setObjectName("toolButton2") self.gridlayout2.addWidget(self.toolButton2,0,5,1,1) self.toolButton1 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton1) self.toolButton1.setMinimumSize(QtCore.QSize(30,30)) self.toolButton1.setCheckable(True) self.toolButton1.setObjectName("toolButton1") self.gridlayout2.addWidget(self.toolButton1,0,4,1,1) self.toolButton0 = QtGui.QToolButton(elementButtonGroupWidget) self.elementButtonGroup.addButton(self.toolButton0) self.toolButton0.setMinimumSize(QtCore.QSize(30,30)) self.toolButton0.setCheckable(True) self.toolButton0.setObjectName("toolButton0") self.gridlayout2.addWidget(self.toolButton0,0,3,1,1) self.gridlayout.addWidget(elementButtonGroupWidget,3,0,1,1) self.gridlayout3 = QtGui.QGridLayout() self.gridlayout3.setMargin(0) self.gridlayout3.setSpacing(6) self.gridlayout3.setObjectName("gridlayout3") self.saveColorsPB = QtGui.QPushButton(ElementColorsDialog) self.saveColorsPB.setAutoDefault(False) self.saveColorsPB.setObjectName("saveColorsPB") self.gridlayout3.addWidget(self.saveColorsPB,0,1,1,1) self.defaultButton = QtGui.QPushButton(ElementColorsDialog) self.defaultButton.setAutoDefault(False) self.defaultButton.setObjectName("defaultButton") self.gridlayout3.addWidget(self.defaultButton,1,0,1,1) self.loadColorsPB = QtGui.QPushButton(ElementColorsDialog) self.loadColorsPB.setAutoDefault(False) self.loadColorsPB.setObjectName("loadColorsPB") self.gridlayout3.addWidget(self.loadColorsPB,0,0,1,1) self.cancelButton = QtGui.QPushButton(ElementColorsDialog) self.cancelButton.setAutoDefault(False) self.cancelButton.setObjectName("cancelButton") self.gridlayout3.addWidget(self.cancelButton,2,1,1,1) self.alterButton = QtGui.QPushButton(ElementColorsDialog) self.alterButton.setAutoDefault(False) self.alterButton.setObjectName("alterButton") self.gridlayout3.addWidget(self.alterButton,1,1,1,1) self.okButton = QtGui.QPushButton(ElementColorsDialog) self.okButton.setAutoDefault(False) self.okButton.setDefault(False) self.okButton.setObjectName("okButton") self.gridlayout3.addWidget(self.okButton,2,0,1,1) self.gridlayout.addLayout(self.gridlayout3,5,0,1,1) spacerItem1 = QtGui.QSpacerItem(20,20,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Fixed) self.gridlayout.addItem(spacerItem1,4,0,1,1) self.hboxlayout3 = QtGui.QHBoxLayout() self.hboxlayout3.setMargin(0) self.hboxlayout3.setSpacing(6) self.hboxlayout3.setObjectName("hboxlayout3") spacerItem2 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout3.addItem(spacerItem2) self.previewPB = QtGui.QPushButton(ElementColorsDialog) self.previewPB.setAutoDefault(False) self.previewPB.setObjectName("previewPB") self.hboxlayout3.addWidget(self.previewPB) self.restorePB = QtGui.QPushButton(ElementColorsDialog) self.restorePB.setAutoDefault(False) self.restorePB.setObjectName("restorePB") self.hboxlayout3.addWidget(self.restorePB) self.gridlayout.addLayout(self.hboxlayout3,2,0,1,1) self.retranslateUi(ElementColorsDialog) QtCore.QObject.connect(self.cancelButton,QtCore.SIGNAL("clicked()"),ElementColorsDialog.reject) QtCore.QMetaObject.connectSlotsByName(ElementColorsDialog) ElementColorsDialog.setTabOrder(self.loadColorsPB,self.saveColorsPB) ElementColorsDialog.setTabOrder(self.saveColorsPB,self.defaultButton) ElementColorsDialog.setTabOrder(self.defaultButton,self.alterButton) ElementColorsDialog.setTabOrder(self.alterButton,self.okButton) ElementColorsDialog.setTabOrder(self.okButton,self.cancelButton) def retranslateUi(self, ElementColorsDialog): ElementColorsDialog.setWindowTitle(QtGui.QApplication.translate("ElementColorsDialog", "Element Color Settings", None, QtGui.QApplication.UnicodeUTF8)) self.textLabel2.setText(QtGui.QApplication.translate("ElementColorsDialog", "Red:", None, QtGui.QApplication.UnicodeUTF8)) self.textLabel2_2.setText(QtGui.QApplication.translate("ElementColorsDialog", "Green:", None, QtGui.QApplication.UnicodeUTF8)) self.textLabel2_3.setText(QtGui.QApplication.translate("ElementColorsDialog", "Blue:", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton6.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Carbon", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton6.setText(QtGui.QApplication.translate("ElementColorsDialog", "C", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton8.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Oxygen", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton8.setText(QtGui.QApplication.translate("ElementColorsDialog", "O", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton10.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Neon", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton10.setText(QtGui.QApplication.translate("ElementColorsDialog", "Ne", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton9.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Fluorine", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton9.setText(QtGui.QApplication.translate("ElementColorsDialog", "F", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton13.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Aluminum", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton13.setText(QtGui.QApplication.translate("ElementColorsDialog", "Al", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton17.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Chlorine", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton17.setText(QtGui.QApplication.translate("ElementColorsDialog", "Cl", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton5.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Boron", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton5.setText(QtGui.QApplication.translate("ElementColorsDialog", "B", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton10_2.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Argon", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton10_2.setText(QtGui.QApplication.translate("ElementColorsDialog", "Ar", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton15.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Phosphorus", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton15.setText(QtGui.QApplication.translate("ElementColorsDialog", "P", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton16.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Sulfur", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton16.setText(QtGui.QApplication.translate("ElementColorsDialog", "S", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton14.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Silicon", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton14.setText(QtGui.QApplication.translate("ElementColorsDialog", "Si", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton33.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Arsenic", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton33.setText(QtGui.QApplication.translate("ElementColorsDialog", "As", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton34.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Selenium", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton34.setText(QtGui.QApplication.translate("ElementColorsDialog", "Se", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton35.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Bromine", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton35.setText(QtGui.QApplication.translate("ElementColorsDialog", "Br", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton36.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Krypton", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton36.setText(QtGui.QApplication.translate("ElementColorsDialog", "Kr", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton32.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Germanium", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton32.setText(QtGui.QApplication.translate("ElementColorsDialog", "Ge", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton7.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Nitrogen", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton7.setText(QtGui.QApplication.translate("ElementColorsDialog", "N", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton2.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Helium", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton2.setText(QtGui.QApplication.translate("ElementColorsDialog", "He", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton1.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Hydrogen", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton1.setText(QtGui.QApplication.translate("ElementColorsDialog", "H", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton0.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Bondpoint", None, QtGui.QApplication.UnicodeUTF8)) self.toolButton0.setText(QtGui.QApplication.translate("ElementColorsDialog", "X", None, QtGui.QApplication.UnicodeUTF8)) self.saveColorsPB.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Save the current element color settings to a file", None, QtGui.QApplication.UnicodeUTF8)) self.saveColorsPB.setText(QtGui.QApplication.translate("ElementColorsDialog", "Save Colors ...", None, QtGui.QApplication.UnicodeUTF8)) self.defaultButton.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Restore current element colors to the default colors.", None, QtGui.QApplication.UnicodeUTF8)) self.defaultButton.setText(QtGui.QApplication.translate("ElementColorsDialog", "Restore Defaults", None, QtGui.QApplication.UnicodeUTF8)) self.loadColorsPB.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Load element colors from file", None, QtGui.QApplication.UnicodeUTF8)) self.loadColorsPB.setText(QtGui.QApplication.translate("ElementColorsDialog", "Load Colors ...", None, QtGui.QApplication.UnicodeUTF8)) self.cancelButton.setText(QtGui.QApplication.translate("ElementColorsDialog", "Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.alterButton.setToolTip(QtGui.QApplication.translate("ElementColorsDialog", "Set element colors to the alternate color set", None, QtGui.QApplication.UnicodeUTF8)) self.alterButton.setText(QtGui.QApplication.translate("ElementColorsDialog", "Set To Alternate", None, QtGui.QApplication.UnicodeUTF8)) self.okButton.setText(QtGui.QApplication.translate("ElementColorsDialog", "Ok", None, QtGui.QApplication.UnicodeUTF8)) self.previewPB.setText(QtGui.QApplication.translate("ElementColorsDialog", "Preview", None, QtGui.QApplication.UnicodeUTF8)) self.restorePB.setText(QtGui.QApplication.translate("ElementColorsDialog", "Restore", None, QtGui.QApplication.UnicodeUTF8))
NanoCAD-master
cad/src/commands/ElementColors/ElementColorsDialog.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ ExtrudePropertyManager.py - Property Manager for B{Extrude mode}. The UI is defined in L{Ui_ExtrudePropertyManager} @version: $Id$ @copyight: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-01-10: Split the ui code out of extrudeMode while converting extrude dashboard to extrude property manager. ninad 2007-07-25: code cleanup to create a propMgr object for extrude mode. Also moved many ui helper methods defined globally in extrudeMode.py to this class. """ import math from PyQt4.Qt import SIGNAL from PyQt4.Qt import Qt from commands.Extrude.Ui_ExtrudePropertyManager import Ui_ExtrudePropertyManager _superclass = Ui_ExtrudePropertyManager class ExtrudePropertyManager(Ui_ExtrudePropertyManager): """ The ExtrudePropertyManager class provides the Property Manager for the B{Extrude mode}. The UI is defined in L{Ui_ExtrudePropertyManager} """ def __init__(self, command): """ Constructor for the B{Extrude} property manager. @param command: The parent mode where this Property Manager is used @type command: L{ExtrudeMode} """ self.suppress_valuechanged = False _superclass.__init__(self, command) def show(self): """ Extends superclass method. """ _superclass.show(self) self.updateMessage() def connect_or_disconnect_signals(self, connect): """ Connect or disconnect widget signals sent to their slot methods. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean @see: L{extrudeMode.connect_or_disconnect_signals} where this is called """ if connect: change_connect = self.w.connect else: change_connect = self.w.disconnect # Connect or disconnect widget signals to slots for toggle in self.extrude_pref_toggles: change_connect(toggle, SIGNAL("stateChanged(int)"), self.command.toggle_value_changed) change_connect(self.extrudeSpinBox_n, SIGNAL("valueChanged(int)"), self.command.spinbox_value_changed) change_connect(self.extrudeSpinBox_x, SIGNAL("valueChanged(double)"), self.command.spinbox_value_changed) change_connect(self.extrudeSpinBox_y, SIGNAL("valueChanged(double)"), self.command.spinbox_value_changed) change_connect(self.extrudeSpinBox_z, SIGNAL("valueChanged(double)"), self.command.spinbox_value_changed) change_connect(self.extrudeSpinBox_length, SIGNAL("valueChanged(double)"), self.command.length_value_changed) slider = self.extrudeBondCriterionSlider change_connect(slider, SIGNAL("valueChanged(int)"), self.command.slider_value_changed) change_connect(self.extrude_productTypeComboBox, SIGNAL("activated(int)"), self.command.ptype_value_changed) def keyPressEvent(self, event): """ Extends superclass method. Provides a way to update 3D workspace when user hits Enter key. @see: self.preview_btn_clicked() """ #The following implements a NFR Mark needs. While in extrude mode, #if user changes values in the spinboxes, don't immediatey update #it on the 3D workspace -- because it takes long time to do so #on a big model. Instead provide a way to update , when, for example, #user hits 'Enter' after changing a spinbox value or hits preview #button. -- Ninad 2008-10-30 if event.key() == Qt.Key_Return: self.command.update_from_controls() _superclass.keyPressEvent(self, event) def preview_btn_clicked(self): """ Provides a way to update 3D workspace when user hits Preview button @see: a comment in self.keyPressEvent() @see: extrudeMode.update_from_controls() """ self.command.update_from_controls() def set_extrude_controls_xyz(self, (x, y, z) ): self.set_extrude_controls_xyz_nolength((x, y, z)) self.update_length_control_from_xyz() def set_extrude_controls_xyz_nolength(self, (x, y, z) ): self.extrudeSpinBox_x.setValue(x) self.extrudeSpinBox_y.setValue(y) self.extrudeSpinBox_z.setValue(z) def set_controls_minimal(self): #e would be better to try harder to preserve xyz ratio ll = 0.1 # kluge, but prevents ZeroDivisionError x = y = 0.0 z = ll self.call_while_suppressing_valuechanged( lambda: self.set_extrude_controls_xyz_nolength((x, y, z) ) ) self.call_while_suppressing_valuechanged( lambda: self.extrudeSpinBox_length.setValue(ll) ) # ZeroDivisionError after user sets xyz each to 0 by typing in them def get_extrude_controls_xyz(self): x = self.extrudeSpinBox_x.value() y = self.extrudeSpinBox_y.value() z = self.extrudeSpinBox_z.value() return (x,y,z) def update_length_control_from_xyz(self): x, y, z = self.get_extrude_controls_xyz() ll = math.sqrt(x*x + y*y + z*z) if ll < 0.1: # prevent ZeroDivisionError self.set_controls_minimal() return self.call_while_suppressing_valuechanged( lambda: self.extrudeSpinBox_length.setValue(ll) ) def update_xyz_controls_from_length(self): x, y, z = self.get_extrude_controls_xyz() ll = math.sqrt(x*x + y*y + z*z) if ll < 0.1: # prevent ZeroDivisionError self.set_controls_minimal() return length = self.extrudeSpinBox_length.value() rr = float(length) / ll self.call_while_suppressing_valuechanged( lambda: self.set_extrude_controls_xyz_nolength( (x*rr, y*rr, z*rr) ) ) def call_while_suppressing_valuechanged(self, func): old_suppress_valuechanged = self.suppress_valuechanged self.suppress_valuechanged = 1 try: res = func() finally: self.suppress_valuechanged = old_suppress_valuechanged return res def set_bond_tolerance_and_number_display(self, tol, nbonds = -1): #e -1 indicates not yet known ###e '?' would look nicer self.extrudeBondCriterionLabel.setText(\ self.lambda_tol_nbonds(tol,nbonds)) def set_bond_tolerance_slider(self, tol): # this will send signals! self.extrudeBondCriterionSlider.setValue(int(tol * 100)) def get_bond_tolerance_slider_val(self): ival = self.extrudeBondCriterionSlider.value() return ival / 100.0 def lambda_tol_nbonds(self, tol, nbonds): if nbonds == -1: nbonds_str = "?" else: nbonds_str = "%d" % (nbonds,) tol_str = (" %d" % int(tol * 100.0))[-3:] # fixed-width (3 digits) but using initial spaces # (doesn't have all of desired effect, due to non-fixed-width font) tol_str = tol_str + "%" return "Tolerance: %s => %s bonds" % (tol_str, nbonds_str) def updateMessage(self, msg = ''): """ Updates the message box with an informative message. """ if not msg: numCopies = self.extrudeSpinBox_n.value() - 1 if self.command.product_type == "straight rod": msg = "Drag one of the " + str(numCopies) + " copies on the right \ to position them. Bondpoints will highlight in blue and green \ pairs whenever bonds can be formed between them." else: msg = "Use the spinboxes below to position the copies. \ Bondpoints will highlight in blue and green pairs \ whenever bonds can be formed between them." self.MessageGroupBox.insertHtmlMessage( msg, setAsDefault = True )
NanoCAD-master
cad/src/commands/Extrude/ExtrudePropertyManager.py
NanoCAD-master
cad/src/commands/Extrude/__init__.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ Ui_ExtrudePropertyManager.py - UI elements for the B{Extrude Mode} Property Manager. @version: $Id$ @copyight: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-01-10: Split the ui code out of extrudeMode while converting extrude dashboard to extrude property manager. ninad 2007-09-10: Code clean up to use PM module classes """ from PyQt4.Qt import Qt from PM.PM_GroupBox import PM_GroupBox from PM.PM_CheckBox import PM_CheckBox from PM.PM_Slider import PM_Slider from PM.PM_ComboBox import PM_ComboBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_SpinBox import PM_SpinBox from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from PM.PM_Constants import PM_CANCEL_BUTTON from PM.PM_Constants import PM_PREVIEW_BUTTON from command_support.Command_PropertyManager import Command_PropertyManager _superclass = Command_PropertyManager class Ui_ExtrudePropertyManager(Command_PropertyManager): """ The Ui_ExtrudePropertyManager class defines UI elements for the Property Manager of the B{Extrude 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 """ # The title that appears in the Property Manager header title = "Extrude" # The name of this Property Manager. This will be set to # the name of the PM_Dialog object via setObjectName(). pmName = title # The relative path to the PNG file that appears in the header iconPath = "ui/actions/Properties Manager/Extrude.png" def __init__(self, command): """ Constructor for the B{Extrude} property manager class that defines its UI. @param command: The parent mode where this Property Manager is used @type command: L{extrudeMode} """ _superclass.__init__(self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_PREVIEW_BUTTON|\ PM_WHATS_THIS_BUTTON) msg = '' self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=False) def _addGroupBoxes(self): """ Add various group boxes to the Extrude Property manager. """ self._addProductSpecsGroupBox() self._addAdvancedOptionsGroupBox() #Define extrude preference toggles. This needs to be defined before #the superclass calls connect_or_disconnect_signals! Defining it in #_addGroupBoxes is not intuitive. But the problem is the superclass method #also makes connections in its __init__ method. This can be cleaned up #during major reafctoring of extrude Mode -- Ninad 2008-10-02 self.extrude_pref_toggles = ( self.showEntireModelCheckBox, self.showBondOffsetCheckBox, self.makeBondsCheckBox, self.mergeCopiesCheckBox, self.extrudePrefMergeSelection) def _addProductSpecsGroupBox(self): """ """ self.productSpecsGroupBox = \ PM_GroupBox( self, title = "Product Specifications" ) self._loadProductSpecsGroupBox(self.productSpecsGroupBox) def _addAdvancedOptionsGroupBox(self): """ Add 'Advanced Options' groupbox """ self.advancedOptionsGroupBox = \ PM_GroupBox( self, title = "Advanced Options" ) self._loadAdvancedOptionsGroupBox(self.advancedOptionsGroupBox) def _loadProductSpecsGroupBox(self, inPmGroupBox): """ Load widgets in the Product specifications group box. @param inPmGroupBox: The roduct specifications box in the PM @type inPmGroupBox: L{PM_GroupBox} """ productChoices = ['Rod', 'Ring'] self.extrude_productTypeComboBox = \ PM_ComboBox( inPmGroupBox, label = 'Final product:', labelColumn = 0, choices = productChoices, index = 0, setAsDefault = True, spanWidth = False ) # names used in the code, same order #if you comment out items from combobox, you also have to remove them # from this list unless they are at the end!!! self.extrude_productTypeComboBox_ptypes = ["straight rod", \ "closed ring", \ "corkscrew"] self.extrudeSpinBox_n = \ PM_SpinBox( inPmGroupBox, label = "Number of copies:", labelColumn = 0, value = 3, minimum = 1, maximum = 99 ) #@WARNING: This method initializes some instance varaiables for various #checkboxes. (Example: self.mergeCopiesCheckBox.default = False). #These values are needed in extrudemode.py. This #won't be needed once extrudeMode.py is cleaned up. -- ninad 2007-09-10 self.extrudeBondCriterionSlider = \ PM_Slider( inPmGroupBox, currentValue = 100, minimum = 0, maximum = 300, label = 'Tolerence' ) self.extrudeBondCriterionLabel = \ self.extrudeBondCriterionSlider.labelWidget self.extrudeBondCriterionSlider_dflt = 100 self.extrudeBondCriterionSlider.setPageStep(5) self.makeBondsCheckBox = \ PM_CheckBox(inPmGroupBox, text = 'Make bonds' , widgetColumn = 0, state = Qt.Checked ) self.makeBondsCheckBox.default = True self.makeBondsCheckBox.attr = 'whendone_make_bonds' self.makeBondsCheckBox.repaintQ = False def _loadAdvancedOptionsGroupBox(self, inPmGroupBox): """ Load widgets in the Advanced Options group box. @param inPmGroupBox: The Advanced Options box in the PM @type inPmGroupBox: L{PM_GroupBox} """ self.offsetSpecsGroupBox = PM_GroupBox(inPmGroupBox, title = 'Offset Between Copies:' ) self._loadOffsetSpecsGroupBox(self.offsetSpecsGroupBox) self.mergeOptionsGroupBox = PM_GroupBox(inPmGroupBox, title = 'Merge Options:' ) self._loadMergeOptionsGroupBox(self.mergeOptionsGroupBox) self.displayOptionsGroupBox = PM_GroupBox(inPmGroupBox, title = 'Display Options:') self._loadDisplayOptionsGroupBox(self.displayOptionsGroupBox) return def _loadDisplayOptionsGroupBox(self, inPmGroupBox): """ Load widgets in the Display Options groupbox (which is a groupbox within the B{Advanced Options group box} ) . @param inPmGroupBox: The Display Options groupbox @type inPmGroupBox: L{PM_GroupBox} @WARNING: This method initializes some instance varaiables for various checkboxes. (Example: self.mergeCopiesCheckBox.default = False). This won't be needed once extrudeMode.py is cleaned up. """ self.showEntireModelCheckBox = \ PM_CheckBox(inPmGroupBox, text = 'Show entire model' , widgetColumn = 1, state = Qt.Unchecked ) self.showEntireModelCheckBox.default = False self.showEntireModelCheckBox.attr = 'show_entire_model' self.showEntireModelCheckBox.repaintQ = True self.showBondOffsetCheckBox = \ PM_CheckBox(inPmGroupBox, text = 'Show bond-offset spheres' , widgetColumn = 1, state = Qt.Unchecked ) self.showBondOffsetCheckBox.default = False self.showBondOffsetCheckBox.attr = 'show_bond_offsets' self.showBondOffsetCheckBox.repaintQ = True def _loadMergeOptionsGroupBox(self, inPmGroupBox): """ Load widgets in the Merge Options groupbox (which is a groupbox within the B{Advanced Options group box}). @param inPmGroupBox: The Merge Options groupbox @type inPmGroupBox: L{PM_GroupBox} @WARNING: This method initializes some instance varaiables for various checkboxes. (Example: self.mergeCopiesCheckBox.default = False). This won't be needed once extrudeMode.py is cleaned up. """ self.mergeCopiesCheckBox = \ PM_CheckBox(inPmGroupBox, text = 'Merge copies' , widgetColumn = 1, state = Qt.Unchecked ) self.mergeCopiesCheckBox.default = False self.mergeCopiesCheckBox.attr = 'whendone_all_one_part' self.mergeCopiesCheckBox.repaintQ = False self.extrudePrefMergeSelection = \ PM_CheckBox(inPmGroupBox, text = 'Merge selection' , widgetColumn = 1, state = Qt.Unchecked ) self.extrudePrefMergeSelection.default = False self.extrudePrefMergeSelection.attr = 'whendone_merge_selection' self.extrudePrefMergeSelection.repaintQ = False def _loadOffsetSpecsGroupBox(self, inPmGroupBox): """ Load widgets in the Offset specs groupbox (which is a groupbox within the B{Advanced Options group box}). @param inPmGroupBox: The Offset Specs gropbox box @type inPmGroupBox: L{PM_GroupBox} """ self.extrudeSpinBox_length = \ PM_DoubleSpinBox( inPmGroupBox, label = "Total offset", value = 7.0, setAsDefault = True, minimum = 0.1, maximum = 2000.0, singleStep = 1, decimals = 3, suffix = ' Angstroms' ) self.extrudeSpinBox_x = \ PM_DoubleSpinBox( inPmGroupBox, label = "X offset", value = 0, minimum = -1000.0, maximum = 1000.0, singleStep = 1, decimals = 3, suffix = ' Angstroms' ) self.extrudeSpinBox_y = \ PM_DoubleSpinBox( inPmGroupBox, label = "Y offset", value = 0, minimum = -1000.0, maximum = 1000.0, singleStep = 1, decimals = 3, suffix = ' Angstroms' ) self.extrudeSpinBox_z = \ PM_DoubleSpinBox( inPmGroupBox, label = "Z offset", value = 0, minimum = -1000.0, maximum = 1000.0, singleStep = 1, decimals = 3, suffix = ' Angstroms' ) def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. @note: Many PM widgets are still missing their "What's This" text. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_ExtrudePropertyManager whatsThis_ExtrudePropertyManager(self) return
NanoCAD-master
cad/src/commands/Extrude/Ui_ExtrudePropertyManager.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ extrudeMode.py - Extrude mode, including its internal "rod" and "ring" modes. Unfinished [as of 050518], especially ring mode. @author: Bruce @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: by bruce, 040924/041011/041015... 050107... ninad 070110: retired extrude dashboard (in Qt4 branch). It was replaced with its 'Property Manager' (see Ui_ExtrudePropertyManager, ExtrudePropertyManager) ninad 20070725: code cleanup to create a propMgr object for extrude mode. Moved many ui helper methods to class ExtrudePropertyManager . Ninad 2008-09-22: ported ExtrudeMode class to use new command API (developed in August - September 2008) . TODO as of 2008-09-22: Extrude mode is a class developed early days of NanoEngineer-1. Lots of things have changed since then (example: Qt framework, major architectural changes etc) In genral it needs a major cleanup. Some items are listed below: - split it into command/GM parts - refactor and move helper functions in this file into their own modules. - several update methods need to be in central update methods in command and PM classes """ _EXTRUDE_LOOP_DEBUG = False # do not commit with True import math from utilities import debug_flags import foundation.env as env import foundation.changes as changes from Numeric import dot from OpenGL.GL import GL_CW from OpenGL.GL import glFrontFace from OpenGL.GL import GL_CCW from OpenGL.GL import GL_LIGHTING from OpenGL.GL import GL_BLEND from OpenGL.GL import GL_ONE_MINUS_SRC_ALPHA from OpenGL.GL import GL_SRC_ALPHA from OpenGL.GL import glBlendFunc from OpenGL.GL import glDepthMask from OpenGL.GL import GL_FALSE from OpenGL.GL import glColorMask from OpenGL.GL import glEnable from OpenGL.GL import GL_TRUE from OpenGL.GL import glDisable from PyQt4 import QtGui from PyQt4.Qt import Qt from PyQt4.Qt import SIGNAL from PyQt4.Qt import QCursor from utilities.debug_prefs import debug_pref, Choice, Choice_boolean_False from command_support.modes import basicMode from utilities.debug import print_compact_traceback, print_compact_stack from model.bonds import bond_at_singlets from utilities.icon_utilities import geticon from utilities.Log import redmsg from geometry.VQT import check_posns_near, check_quats_near from geometry.VQT import V, Q, norm, vlen, cross from commands.Extrude.ExtrudePropertyManager import ExtrudePropertyManager from graphics.drawing.CS_draw_primitives import drawline from model.chunk import Chunk from graphics.behaviors.shape import get_selCurve_color from graphics.drawables.handles import repunitHandleSet from graphics.drawables.handles import niceoffsetsHandleSet from graphics.drawables.handles import draggableHandle_HandleSet from utilities.constants import blue from utilities.constants import green from utilities.constants import common_prefix from ne1_ui.NE1_QWidgetAction import NE1_QWidgetAction from ne1_ui.toolbars.Ui_ExtrudeFlyout import ExtrudeFlyout # == _MAX_NCOPIES = 360 # max number of extrude-unit copies. # Motivation is to avoid "hangs from slowness". # Should this be larger? _KEEP_PICKED = False # whether to keep the repeated-unit copies all picked # (selected), or all unpicked, during the mode # == def reinit_extrude_controls(win, glpane = None, length = None, attr_target = None): """ Reinitialize the extrude controls; used whenever we enter the mode; win should be the main window (MWSemantics object). """ self = win dflt_ncopies_rod = debug_pref("Extrude: initial N", Choice([2,3,4,5,6,10,20], defaultValue = 3), prefs_key = True, non_debug = True ) #bruce 070410 # minor bug in that: it happens too early for a history message, so if it has its non-default value # when first used, the user doesn't get the usual orange history warning. #e refile these self.extrudeSpinBox_n_dflt_per_ptype = [dflt_ncopies_rod, 30] # default N depends on product type... not yet sure how to use this info ## in fact we can't use it while the bugs in changing N after going to a ring, remain... dflt_ncopies = self.extrudeSpinBox_n_dflt_per_ptype[0] #e 0 -> a named constant, it's also used far below self.propMgr.extrudeSpinBox_n.setValue(dflt_ncopies) x,y,z = 5,5,5 # default dir in modelspace, to be used as a last resort if glpane: # use it to set direction try: right = glpane.right x,y,z = right # use default direction fixed in eyespace if not length: length = 7.0 #k needed? except: print "fyi (bug?): in extrude: x,y,z = glpane.right failed" pass if length: # adjust the length to what the caller desires [Enter passes this] #######, based on the extrude unit (if provided); we'll want to do this more sophisticatedly (??) ##length = 7.0 ###### ll = math.sqrt(x*x + y*y + z*z) # should always be positive, due to above code rr = float(length) / ll x,y,z = (x * rr, y * rr, z * rr) self.propMgr.set_extrude_controls_xyz((x,y,z)) for toggle in self.propMgr.extrude_pref_toggles: if attr_target and toggle.attr: # do this first, so the attrs needed by the slot functions are there setattr(attr_target, toggle.attr, toggle.default) # this is the only place I initialize those attrs! ##for toggle in self.propMgr.extrude_pref_toggles: ##toggle.setChecked(True) ##### stub; change to use its sense & default if it has one -- via a method on it #e bonding-slider, and its label, showing tolerance, and # of bonds we wouldd make at current offset\ tol = self.propMgr.extrudeBondCriterionSlider_dflt / 100.0 self.propMgr.set_bond_tolerance_and_number_display(tol) self.propMgr.set_bond_tolerance_slider(tol) ### bug: at least after the reload menu item, reentering mode did not reinit slider to 100%. don\'t know why.\ self.propMgr.extrude_productTypeComboBox.setCurrentIndex(0) self.updateMessage() return # == _superclass = basicMode class extrudeMode(basicMode): """ Extrude mode. """ # class constants #Property Manager PM_class = ExtrudePropertyManager #Flyout Toolbar FlyoutToolbar_class = ExtrudeFlyout commandName = 'EXTRUDE' featurename = "Extrude Mode" from utilities.constants import CL_ENVIRONMENT_PROVIDING command_level = CL_ENVIRONMENT_PROVIDING # initial values of some instance variables. # note: some of these might be set by external code (e.g. in self.propMgr). # see self.togglevalue_changed() and ExtrudePropertyManager.connect_or_disconnect_signals() # methods for more info. mergeables = {} # in case not yet initialized when we Draw (maybe not needed) show_bond_offsets = False show_entire_model = True whendone_make_bonds = True whendone_all_one_part = True whendone_merge_selection = True final_msg_accum = "" # no __init__ method needed # methods related to entering this mode def ptype_value_changed(self, val): # note: uses val, below; called from ExtrudePropertyManager.py if not self.isCurrentCommand(): return old = self.product_type new = self.propMgr.extrude_productTypeComboBox_ptypes[val] if new != old: # print "product_type = %r" % (new,) self.product_type = new ## i will remove those "not neededs" as soon as this is surely past the josh demo snapshot [041017 night] self.needs_repaint = 1 #k not needed since update_from_controls would do this too, i hope! self.update_from_controls() ## not yet effective, even if we did it: self.recompute_bonds() self.repaint_if_needed() #k not needed since done at end of update_from_controls self.updateMessage() return bond_tolerance = -1.0 # this initial value can't agree with value computed from slider def slider_value_changed(self, valjunk): """ Slot method: The bond tolerance slider value changed. """ del valjunk ######k why don't we check suppress_value_changed? maybe we never set its value with that set? if not self.isCurrentCommand(): return old = self.bond_tolerance new = self.propMgr.get_bond_tolerance_slider_val() if new != old: self.needs_repaint = 1 # almost certain, from bond-offset spheres and/or bondable singlet colors self.bond_tolerance = new # one of the hsets has a radius_multiplier which must be patched to self.bond_tolerance # (kluge? not compared to what I was doing a few minutes ago...) try: hset = self.nice_offsets_handleset except AttributeError: print "must be too early to patch self.nice_offsets_handleset -- " \ "could be a problem, it will miss this event" ###@@@ else: hset.radius_multiplier = self.bond_tolerance # number of resulting bonds not yet known, will be set later self.propMgr.set_bond_tolerance_and_number_display(self.bond_tolerance) self.recompute_bonds() # re-updates set_bond_tolerance_and_number_display when done self.repaint_if_needed() ##e merge with self.update_offset_bonds_display, call that instead?? no need for now. return def toggle_value_changed(self, valjunk): del valjunk if not self.isCurrentCommand(): return self.needs_repaint = 0 for toggle in self.propMgr.extrude_pref_toggles: val = toggle.isChecked() attr = toggle.attr repaintQ = toggle.repaintQ if attr: old = getattr(self,attr,val) if old != val: setattr(self, attr, val) if repaintQ: self.needs_repaint = 1 else: # bad but tolerable: a toggle with no attr, but repaintQ, # forces repaint even when some *other* toggle changes! # (since we don't bother to figure out whether it changed) if repaintQ: self.needs_repaint = 1 print "shouldn't happen in current code - needless repaint" pass self.repaint_if_needed() def command_ok_to_enter(self): #bruce 080924 de-inlined _refuseEnter (since this was its only call) warn = True ok, mol = assy_extrude_unit(self.o.assy, really_make_mol = 0) if not ok: whynot = mol if warn: from utilities.Log import redmsg env.history.message(redmsg("%s refused: %r" % (self.get_featurename(), whynot,))) # Fixes bug 444. mark 060323 self.w.toolsExtrudeAction.setChecked(False) # this needs to be refactored away, somehow, # but is tolerable for now [bruce 080806 comment] return False else: # mol is nonsense, btw return True pass def command_entered(self): """ Extends superclass method. @see: basecommand.command_entered() for documentation. """ #NOTE: Most of the code below is copied (with some changes) from the #following methods that existed in the old command API #on or before 2008-09-22: #self.init_gui(), self.Enter(), self._command_entered_effects() #self.clear_command_state() # [-- Ninad Comment] _superclass.command_entered(self) #Copying all the code originally in self.Enter() that existed #on or before 2008-09-19 [--Ninad comment ] self.status_msg("preparing to enter %s..." % self.get_featurename()) # this msg won't last long enough to be seen, if all goes well #Clear command states self.mergeables = {} self.final_msg_accum = "" self.dragdist = 0.0 self.have_offset_specific_data = 0 #### also clear that data itself... self.bonds_for_current_offset_and_tol = (17,) # impossible value -- ok?? self.offset_for_bonds = None self.product_type = "straight rod" #e someday have a combobox for this self.circle_n = 0 self.__old_ptype = None self.singlet_color = {} self.initial_down = self.o.down self.initial_out = self.o.out initial_length = debug_pref("Extrude: initial offset length (A)", Choice([3.0, 7.0, 15.0, 30.0], defaultValue = 7.0 ), prefs_key = True, non_debug = True ) #bruce 070410 # Disable Undo/Redo actions, and undo checkpoints, during this mode # (they *must* be reenabled in command_will_exit). # We do this as late as possible before modifying the model [moved this code, bruce 080924], # so as not to do it if there are exceptions in the rest of the method, # since if it's done and never undone, Undo/Redo won't work for the rest of the session. # [bruce 060414, to mitigate bug 1625; same thing done in some other modes] import foundation.undo_manager as undo_manager undo_manager.disable_undo_checkpoints('Extrude') undo_manager.disable_UndoRedo('Extrude', "during Extrude") # this makes Undo menu commands and tooltips look like # "Undo (not permitted during Extrude)" (and similarly for Redo) self._command_entered_effects() # note: this modifies the model reinit_extrude_controls(self, self.o, length = initial_length, attr_target = self) #Bruce's old comment from before this was refactored 080922: # i think this [self.updateCommandToolbar and self.connect_or_disconnect_signals] # is safer *after* the first update_from_controls, not before it... # but i won't risk changing it right now (since tonight's bugfixes # might go into josh's demo). [041017 night] self.update_from_controls() return def command_will_exit(self): """ Extends superclass method. """ #NOTE: Most of the code below is copied (with some changes )from the #following methods that existed in the old command API #on or before 2008-09-22: #self.stateDone(), self.stateCancel(), self.haveNonTrivialState(), #self._stateDoneOrCancel(), self.restore_gui() # [-- Ninad Comment] # Reenable Undo/Redo actions, and undo checkpoints (disabled in init_gui); # do it first to protect it from exceptions in the rest of this method # (since if it never happens, Undo/Redo won't work for the rest of the session) # [bruce 060414; same thing done in some other modes] import foundation.undo_manager as undo_manager undo_manager.reenable_undo_checkpoints('Extrude') undo_manager.reenable_UndoRedo('Extrude') self.set_cmdname('Extrude') # this covers all changes while we were in the mode # (somewhat of a kluge, and whether this is the best place to do it is unknown; # without this the cmdname is "Done") if self.commandSequencer.exit_is_forced: if self.ncopies != 1: self._warnUserAboutAbandonedChanges() else: if self.commandSequencer.exit_is_cancel: cancelling = True self.propMgr.extrudeSpinBox_n.setValue(1) #e should probably do this in our subroutine instead of here else: cancelling = False #bugfix after changes in rev 14435. Always make sure to call #update from controls while exiting the command. (This should #be in an command_update_* method when extrude modeis refactored) self.update_from_controls() #Following code is copied from old method self._stateDoneOrCancel #(that method existed before 2008-09-25) ## self.update_from_controls() #k 041017 night - will this help or hurt? # since hard to know, not adding it now. # restore normal appearance [bruce 070407 revised this in case each mol is not a Chunk] for mol in self.molcopies: # mol might be Chunk, fake_merged_mol, or fake_copied_mol [bruce 070407] for chunk in true_Chunks_in(mol): try: del chunk._colorfunc # let class attr [added 050524] be visible again; exception if it already was #e also unpatch info from the atoms? not needed but might as well [nah] except: pass else: #bruce 060308 revision: do this outside the try/except, # in case bugs would be hidden otherwise chunk.changeapp(0) continue self.finalize_product(cancelling = cancelling) # this also emits status messages and does some cleanup of broken_externs... self.o.assy.update_parts() #bruce 050317: fix some of the bugs caused by user dragging some # repeat units into a different Part in the MT, deleting them, etc. # (At least this should fix bug 371 comment #3.) # This is redundant with the fix for that in make_inter_unit_bonds, # but is still the only place we catch the related bug when rebonding # the base unit to whatever we unbonded it from at the start (if anything). # (That bug is untested and this fix for it is untested.) _superclass.command_will_exit(self) def _command_entered_effects(self): """ [private] common code for self.command_entered() """ #Note: The old command API code was striped out on 2008-09-25. But keeping #this method instead of inlining it with command_entered, because #it makes command_entered easier to read - Ninad 2008-09-25 ### # find out what's selected, which if ok will be the repeating unit we will extrude... # explore its atoms, bonds, externs... # what's selected should be its own molecule if it isn't already... # for now let's hope it is exactly one (was checked in command_ok_to_enter, but not anymore). ok, mol = assy_extrude_unit(self.o.assy) if not ok: # after 041222 this should no longer happen, since checked in command_ok_to_enter whynot = mol self.status_msg("%s refused: %r" % (self.get_featurename(), whynot,)) return 1 # refused! assert isinstance(mol, fake_merged_mol) #bruce 070412 self.basemol = mol #bruce 070407 set self.separate_basemols; all uses of it must be read, # to fully understand fake_merged_mol semantics self.separate_basemols = true_Chunks_in(mol) # since mol might be a Chunk or a fake_merged_mol #bruce 080626 new feature: figure out where we want to add whatever new # nodes we create self.add_new_nodes_here = self._compute_add_new_nodes_here( self.separate_basemols) ## partly done new code [bruce 041222] ###@@@ # temporarily break bonds between our base unit (mol) and the rest # of the model; record the pairs of singlets thus formed, # both for rebonding when we're done, and to rule out unit-unit bonds # incompatible with that rebonding. self.broken_externs = [] # pairs of singlets from breaking of externs self.broken_extern_s2s = {} for bond in list(mol.externs): s1, s2 = bond.bust() # these will be rebonded when we're done assert s1.is_singlet() and s2.is_singlet() # order them so that s2 is in mol, s1 not in it [bruce 070514 Qt4: revised to fix bug 2311] if mol.contains_atom(s1): (s1,s2) = (s2,s1) assert s1 != s2 # redundant with following, but more informative assert mol.contains_atom(s2) assert not mol.contains_atom(s1) self.broken_externs.append((s1,s2)) self.broken_extern_s2s[s2] = s1 # set of keys; values not used as of 041222 # note that the atoms we unbonded (the neighbors of s1,s2) # might be neighbors of more than one singlet in this list. ####@@@ see paper notes - restore at end, also modify singlet-pairing alg # The following is necessary to work around a bug in this code, which is # its assumption (wrong, in general) that mol.copy_single_chunk().quat == mol.quat. # A better fix would be to stop using set_basecenter_and_quat, replacing # that with an equivalent use of mol.pivot and/or move and/or rot. self.basemol.full_inval_and_update() mark_singlets(self.separate_basemols, self.colorfunc) ###@@@ make this behave differently for broken_externs # now set up a consistent initial state, even though it will probably # be modified as soon as we look at the actual controls self.offset = V(15.0,16.0,17.0) # initial value doesn't matter self.ncopies = 1 self.molcopies = [self.basemol] #e if we someday want to also display "potential new copies" dimly, # they are not in this list #e someday we might optimize by not creating separate molcopies, # only displaying the same mol in many places # (or, having many mols but making them share their display lists -- # could mol.copy do that for us??) try: self.recompute_for_new_unit() # recomputes whatever depends on self.basemol except: msg = "in Enter, exception in recompute_for_new_unit" print_compact_traceback(msg + ": ") self.status_msg("%s refused: %s" % (self.get_featurename(), msg,)) return 1 # refused! self.recompute_for_new_bend() # ... and whatever depends on the bend # from each repunit to the next (varies only in ring mode) # (still nim as of 080727) return def command_enter_misc_actions(self): self.w.toolsExtrudeAction.setChecked(True) # Disable some QActions that will conflict with this mode. self.w.disable_QActions_for_extrudeMode(True) def command_exit_misc_actions(self): self.w.toolsExtrudeAction.setChecked(False) self.w.disable_QActions_for_extrudeMode(False) def _compute_add_new_nodes_here(self, nodes): #bruce 080626 """ If we are copying the given nodes, figure out where we'd like to add new nodes (as a group to call addchild on). """ assert nodes def _compute_it(): return common_prefix( *[self._ok_groups_for_copies_of_node(node) for node in nodes] ) groups = _compute_it() if not groups: nodes[0].part.ensure_toplevel_group() groups = _compute_it() assert groups return groups[-1] def _ok_groups_for_copies_of_node(self, node): #bruce 080626 """ Considering node alone, which groups (outermost first) do we think are ok as a place to add copies of it? @note: return value might be empty. If this is an issue, caller may want to call node.part.ensure_toplevel_group(), but it might cause bugs to do that in this method, since it should have no side effects on the node tree. """ res = node.containing_groups(within_same_part = True) # innermost first res = res[::-1] # outermost first while res and not res[-1].permit_addnode_inside(): res = res[:-1] return res def updateMessage(self): """ Update the message box win property manager with an informative message. """ self.propMgr.updateMessage() singlet_color = {} # we also do this in clear_command_state() def colorfunc(self, atom): # uses a hack in chem.py atom.draw to use mol._colorfunc return self.singlet_color.get(atom.info) # ok if this is None def asserts(self): assert len(self.molcopies) == self.ncopies assert self.molcopies[0] == self.basemol circle_n = 0 # we also do this in clear_command_state() # note: circle_n is still used (in ring mode), even though "revolve" # as separate mode is nim/obs/removed [bruce 080727 comment] def spinbox_value_changed(self, valjunk): """ Call this when any extrude spinbox value changed, except length. Note that this doesn't update the 3D workspace. For updating the workspace user needs to hit Preview or hit Enter. @see: self.update_from_controls() @see: ExtrudePropertyManager.keyPressEvent() @see: ExtrudePropertyManager.preview_btn_clicked() """ del valjunk if self.propMgr.suppress_valuechanged: return if not self.isCurrentCommand(): #e we should be even more sure to disconnect the connections causing this to be called ##print "fyi: not isCurrentCommand" ## # this happens when you leave and reenter mode... need to break qt connections return self.propMgr.update_length_control_from_xyz() def length_value_changed(self, valjunk): """ Call this when the length spinbox changes. Note that this doesn't update the 3D workspace. For updating the workspace user needs to hit Preview or hit Enter. @see: self.update_from_controls() @see: ExtrudePropertyManager.keyPressEvent() @see: ExtrudePropertyManager.preview_btn_clicked() """ del valjunk if self.propMgr.suppress_valuechanged: return if not self.isCurrentCommand(): ##print "fyi: not isCurrentCommand" return self.propMgr.update_xyz_controls_from_length() should_update_model_tree = 0 # avoid doing this when we don't need to (like during a drag) def want_center_and_quat(self, ii, ptype = None): """ Return desired basecenter and quat of molcopies[ii], relative to original ones, assuming they're same as in basemol. """ # update 070407: if self.basemol is a fake_merged_mol, we use the basecenter of its first true Chunk # (arbitrary choice which chunk, but has to be consistent with fake_copied_mol.set_basecenter_and_quat). # This is then compensated for in fake_copied_mol.set_basecenter_and_quat (for center -- it assumes all quats # are the same, true since they are all Q(1,0,0,0) due to full_inval_and_update). # At first I planned to revise this method to return info for passing to mov/rot/pivot instead -- but we'd have to do that # relative to initial orientation, not prior one, or risk buildup of roundoff errors, but there's no good way to think # of a chunk as "rotated from initial orientation" except via its basecenter & quat. # An improvement would be to officially temporarily disable re-choosing basecenter & quat in all these chunks, # rather than on relying on it not to happen "by luck" (since it only happens when we do ops we're not doing here -- # but note that nothing currently prevents user from doing them during this mode, unless UI tool disables do). # Meanwhile, the current scheme should be as correct for multiple base-chunks as it was for one. # See also the comments in fake_copied_mol.set_basecenter_and_quat, especially about how this affects ring mode. # Update, bruce 070411, fixing this now for fake_copied_mol ring mode: # - why does this use .center when what we set later is basecenter? guess: only ok since full_inval_and_update # sets basecenter to center. So if we return a new kind of center from fake_merged_mol, we need to preserve that relation, # treating center as the "default basecenter" from that thing, to which requested new ones are relative. offset = self.offset cn = self.circle_n ### does far-below code have bugs when ii >= cn?? that might explain some things i saw... basemol = self.basemol if not ptype: ptype = self.product_type #e the following should become the methods of product-type classes if ptype == "straight rod": # default for Extrude centerii = basemol.center + ii * offset # quatii = Q(1,0,0,0) quatii = basemol.quat elif ptype == "closed ring": self.update_ring_geometry() # TODO: only call this once, for all ii in a loop of calls of this method # extract some of the results saved by update_ring_geometry c_center = self.circle_center # use them for spoke number ii quatii_rel, spoke_vec = self._spoke_quat_and_vector(ii) quatii = basemol.quat + quatii_rel # [i'm not sure what the following old comment means -- bruce 070928] # (i think) this doesn't depend on where we are around the circle! centerii = c_center + spoke_vec else: self.status_msg("bug: unimplemented product type %r" % ptype) return self.want_center_and_quat(ii, "straight rod") if ii == 0: ###e we should warn if retvals are not same as basemol values; # need a routine to "compare center and quat", # like our near test for floats; # Numeric can help for center, but we need it for quat too if debug_flags.atom_debug: #bruce 050518 added this condition, at same time as bugfixing the checkers to not be noops check_posns_near( centerii, basemol.center ) check_quats_near( quatii, basemol.quat ) pass return centerii, quatii def update_ring_geometry(self, emit_messages = True): #bruce 070928 split this out of want_center_and_quat """ Recompute and set ring geometry attributes of self, namely self.circle_center, self.axis_dir, self.radius_vec, which depend on self.basemol, self.circle_n, and self.offset, and are used by self.want_center_and_quat(...) and by some debug drawing code. """ #e We store self.o.down (etc) when we enter the mode... # now we pick a circle in plane of that and current offset. # If this is ambiguous, we favor a circle in plane of initial down and out. # these are constants throughout the mode: down = self.initial_down out = self.initial_out basemol = self.basemol # these vary: offset = self.offset cn = self.circle_n tangent = norm(offset) axis = cross(down,tangent) # example, I think: left = cross(down,out) ##k if vlen(axis) < 0.001: #k guess axis = cross(down,out) if emit_messages: self.status_msg("error: offset too close to straight down, picking down/out circle") # worry: offset in this case won't quite be tangent to that circle. We'll have to make it so. ###NIM axis = norm(axis) # direction only # note: negating this direction makes the circle head up rather than down, # but doesn't change whether bonds are correct. towards_center = cross(offset,axis) # these are perp, axis is unit, so only cn is needed to make this correct length neg_radius_vec = towards_center * cn / (2 * math.pi) c_center = basemol.center + neg_radius_vec # circle center self.circle_center = c_center # be able to draw the axis self.axis_dir = axis radius_vec = - neg_radius_vec self.radius_vec = radius_vec # be able to draw "spokes", useful in case the axis is off-screen return def _spoke_quat_and_vector(self, ii): #bruce 070928 split this out of want_center_and_quat """ Assuming self.product_type == 'closed ring', and assuming self.update_ring_geometry() has just been called (unverifiable, but bugs if this is not true!), return a tuple (quatii_rel, spoke_vec) containing a quat which rotates self.radius_vec into spoke_vec, and spoke_vec itself, a "spoke vector" which should translate self.circle_center to the desired center of repeat unit ii (where unit 0 is self.basemol). """ cn = self.circle_n # extract results saved by assumed call of update_ring_geometry axis = self.axis_dir radius_vec = self.radius_vec c_center = self.circle_center quatii_rel = Q(axis, 2 * math.pi * ii / cn) * -1.0 spoke_vec = quatii_rel.rot( radius_vec ) return (quatii_rel, spoke_vec) __old_ptype = None # hopefully not needed in clear_command_state(), but i'm not sure, so i added it def update_from_controls(self): """ Make the number and position of the copies of basemol what they should be, based on current control values. Never modify the control values! (That would infloop.) This should be called in Enter and whenever relevant controls might change. It's also called during a mousedrag event if the user is dragging one of the repeated units. We optimize by checking which controls changed and only recomputing what might depend on those. When that's not possible (e.g. when no record of prior value to compare to current value), we'd better check an invalid flag for some of what we compute, and/or a changed flag for some of the inputs we use. @see: ExtrudePropertyManager.keyPressEvent() (the caller) @see: ExtrudePropertyManager.preview_btn_clicked() (the caller) """ self.asserts() # get control values want_n = self.propMgr.extrudeSpinBox_n.value() want_cn = 0 # sometimes changed below # limit N for safety ncopies_wanted = want_n ncopies_wanted = min(_MAX_NCOPIES, ncopies_wanted) # upper limit (in theory, also enforced by the spinbox) ncopies_wanted = max(1, ncopies_wanted) # always at least one copy ###e fix spinbox's value too?? also think about it on exit... if ncopies_wanted != want_n: msg = "ncopies_wanted is limited to safer value %r, not your requested value %r" % (ncopies_wanted, want_n) self.status_msg(msg) want_n = ncopies_wanted # redundant -- sorry for this unclear code # figure out, and store, effective circle_n now (only matters in ring mode, but always done) if not want_cn: want_cn = want_n # otherwise the cn control overrides the "use N" behavior cn_changed = (self.circle_n != want_cn) #### if we again used the sep slot method for that spinbox, this might be wrong self.circle_n = want_cn # note that self.ncopies is not yet adjusted to the want_n value, # and (if want_n > self.ncopies) self.ncopies will only be adjusted gradually # as we create new copies! So it should not be relied on as giving the final number of copies. # But it's ok for that to be private to this code, since what other code needs to know is the # number of so-far-made copies (always equals self.ncopies) and the params that affect their # location (which never includes self.ncopies, only ptype, self.offset, self.circle_n and someday some more). [041017 night] ######@@@ to complete the bugfix: # + don't now have someone else store circle_n, # + or fail to use it! # + [mostly] check all uses of ncopies for not affecting unit pos/rot. # and later, rewrite code to keep that stuff in self.want.x and self.have.x, # and do all update from this routine (maybe even do that part now). # + check product_type or ptype compares. (want_x, want_y, want_z) = self.propMgr.get_extrude_controls_xyz() offset_wanted = V(want_x, want_y, want_z) # (what are the offset units btw? i guess angstroms, but verify #k) # figure out whether product type might have changed -- affects pos/rot of molcopies ptype_changed = 0 if self.__old_ptype != self.product_type: ptype_changed = 1 self.__old_ptype = self.product_type # update the state: # first move the copies in common (between old and new states), # if anything changed which their location (pos/rot) might depend on. ncopies_common = min( ncopies_wanted, self.ncopies) # this many units already exist and will still exist #e rename to self.ncopies_have? no, just rename both of these to self.want.ncopies and self.have.ncopies. if offset_wanted != self.offset or cn_changed or ptype_changed: #e add more params if new ptypes use new params # invalidate all memoized data which is specific to these params self.have_offset_specific_data = 0 #misnamed self.offset = offset_wanted junk = self.want_center_and_quat(0) # this just asserts (inside the function) that the formulas don't want to move basemol for ii in range(1, ncopies_common): if 0: # this might accumulate position errors - don't do it: motion = (offset_wanted - self.offset)*ii self.molcopies[ii].move(motion) #k does this change picked state???? else: c, q = self.want_center_and_quat(ii) self.molcopies[ii].set_basecenter_and_quat( c, q) # now delete or make copies as needed (but don't adjust view until the end) while self.ncopies > ncopies_wanted: # delete a copy we no longer want self.should_update_model_tree = 1 ii = self.ncopies - 1 self.ncopies = ii old = self.molcopies.pop(ii) old.unpick() # work around a bug in assy.killmol [041009] ##### that's fixed now -- verify, and remove this old.kill() # might be faster than self.o.assy.killmol(old) self.asserts() while self.ncopies < ncopies_wanted: # make a new copy we now want self.should_update_model_tree = 1 #e the fact that it shows up immediately in model tree would permit user to change its color, etc; #e but we'll probably want to figure out a decent name for it, make a special group to put these in, etc ii = self.ncopies self.ncopies = ii + 1 # pre-050216 code: ## newmols = assy_copy(self.o.assy, [self.basemol]) # fyi: offset is redundant with mol.set_basecenter_and_quat (below) ## new = newmols[0] # new code 050216: new = self.basemol.copy_single_chunk(None) # None is the dad, and as of 050214 or so, passing any other dad is deprecated for now. #bruce 080314 using copy_single_chunk in place of copy. # This is a bug if self.basemol can be anything other than a Chunk or a # fake_merged_mol. I'm sure it can't be. In fact, it is almost certain that # self.basemol is always a fake_merged_mol, not a Chunk; # if true, this method could be renamed to copy_single_fake_merged_mol. # The point is to make it easy to find all uses and implems of copy methods # that need revision. The need for revision in this case is to generalize # what the extrude unit can be. if isinstance(new, fake_copied_mol):#bruce 070407 kluge ## new_nodes = [new._group] new_nodes = new._mols else: new_nodes = [new] for node in new_nodes: self.addnode(node) #e this is inefficient when adding many mols at once, needs change to inval system #e this is probably not the best place in the MT to add it # # Note: by test, in current code (using fake_copied_mol) # this is redundant, since the nodes have already been added # when the copy was made. But it's harmless so I'll leave it # in, in case there are some conditions in which that hasn't # happened. Also, soon I'll revise this to add it in a # better place, so it will no longer be redundant # (unless the addmol in copy_single_chunk is also fixed). # [bruce 080626 comment] # end 050216 changes if _KEEP_PICKED: pass ## done later: self.basemol.pick() else: ## self.basemol.unpick() node.unpick() # undo side effect of assy_copy #k maybe no longer needed [long before 050216] self.molcopies.append(new) c, q = self.want_center_and_quat(ii) self.molcopies[ii].set_basecenter_and_quat( c, q) self.asserts() if _KEEP_PICKED: self.basemol.pick() #041009 undo an unwanted side effect of assy_copy (probably won't matter, eventually) #k maybe no longer needed [long before 050216] else: self.basemol.unpick() # do this even if no copies made (matters e.g. when entering the mode) #k maybe no longer needed [long before 050216] ###@@@ now this looks like a general update function... hmm self.needs_repaint = 1 # assume this is always true, due to what calls us self.update_offset_bonds_display() def addnode(self, node): #bruce 080626 split this out """ Add node to the current part, in the best place for the purposes of this command. It's ok if this is called more than once on the same node. """ group = self.add_new_nodes_here #bruce 080626 new feature if group: group.addchild(node) else: self.o.assy.addnode(node) # note: addnode used to be called addmol return def update_offset_bonds_display(self): # should be the last function called by some user event method (??)... not sure if it always is! some weird uses of it... """ Update whatever is needed of the offset_specific_data, the bonds, and the display itself. """ ###### now, if needed, recompute (or start recomputing) the offset-specific data #####e worry about whether to do this with every mousedrag event... or less often if it takes too long ##### but ideally we do it, so as to show bonding that would happen at current offset if not self.have_offset_specific_data: self.have_offset_specific_data = 1 # even if the following has an exception try: self.recompute_offset_specific_data() except: print_compact_traceback("error in recompute_offset_specific_data: ") return # no more updates #### should just raise, once callers cleaner pass #obs comment in this loc? #e now we'd adjust view, or make drawing show if stuff is out of view; # make atom overlaps transparent or red; etc... # now update bonds (needed by most callers (not ncopies change!), so don't bother to have an invalid flag, for now...) if 1: self.recompute_bonds() # sets self.needs_repaint if bonds change; actually updates bond-specific ui displays # update model tree and/or glpane, as needed if self.should_update_model_tree: self.should_update_model_tree = 0 # reset first, so crashing calls are not redone self.needs_repaint = 0 self.w.win_update() # update glpane and model tree elif self.needs_repaint: # merge with self.repaint_if_needed() ###@@@ self.needs_repaint = 0 self.o.gl_update() # just update glpane return # == # These methods recompute things that depend on other things named in the methodname. # call them in the right order (this order) and at the right time. # If for some of them, we should only invalidate and not recompute until later (eg on buttonpress), # I did not yet decide how that will work. def recompute_for_new_unit(self): """ Recompute things which depend on the choice of rep unit (for now we use self.basemol to hold that). """ # for now we use self.basemol, #e but later we might not split it from a larger mol, but have a separate mol for it # these are redundant, do we need them? self.have_offset_specific_data = 0 self.bonds_for_current_offset_and_tol = (17,) self.show_bond_offsets_handlesets = [] # for now, assume no other function wants to keep things in this list hset = self.basemol_atoms_handleset = repunitHandleSet(target = self) for mol in self.separate_basemols:#bruce 070407 for atom in mol.atoms.values(): # make a handle for it... to use in every copy we show pos = atom.posn() ###e make this relative? dispdef = mol.get_dispdef(self.o) disp, radius = atom.howdraw(dispdef) info = None ##### hset.addHandle(pos, radius, info) self.basemol_singlets = list(self.basemol.singlets) #bruce 041222 precaution: copy list hset = self.nice_offsets_handleset = niceoffsetsHandleSet(target = self) hset.radius_multiplier = abs(self.bond_tolerance) # kluge -- might be -1 or 1 initially! (sorry, i'm in a hurry) # note: hset is used to test offsets via self.nice_offsets_handleset, # but is drawn and click-tested due to being in self.show_bond_offsets_handlesets # make a handle just for dragging self.nice_offsets_handleset hset2 = self.nice_offsets_handle = draggableHandle_HandleSet( \ motion_callback = self.nice_offsets_handleset.move , statusmsg = "use magenta center to drag the clickable suggested-offset display" ) hset2.addHandle( V(0,0,0), 0.66, None) hset2.addHandle( self.offset, 0.17, None) # kluge: will be kept patched with current offset hset.special_pos = self.offset # ditto self.show_bond_offsets_handlesets.extend([hset,hset2]) # (use of this list is conditioned on self.show_bond_offsets) ##e quadratic, slow alg; should worry about too many singlets # (rewritten from the obs functions explore, bondable_singlet_pairs_proto1) # note: this code will later be split out, and should not assume mol1 == mol2. # (but it does, see comments) mergeables = self.mergeables = {} sings1 = sings2 = self.basemol_singlets transient_id = (self, self.__class__.recompute_for_new_unit, "scanning all pairs") for i1 in range(len(sings1)): env.call_qApp_processEvents() #bruce 050908 replaced qApp.processEvents() # [bruce 050114, copied from movie.py] # Process queued events [enough to get statusbar msgs to show up] ###@@@ #e for safety we might want to pass the argument: QEventLoop::ExcludeUserInput; #e OTOH we'd rather have some way to let the user abort this if it takes too long! # (we don't yet have any known or safe way to abort it...) if i1 % 10 == 0 or i1 < 10: #bruce 050118 try only every 10th one, is it faster? #e should processEvents be in here too?? ###e would be more sensible: compare real time passed... env.history.message("scanning open bond pairs... %d/%d done" % (i1, len(sings1)) , transient_id = transient_id ) # this is our slowness warning ##e should correct that message for effect of i2 < i1 optim, by reporting better numbers... for i2 in range(len(sings2)): if i2 < i1: continue # results are negative of swapped i1,i2, SINCE MOLS ARE THE SAME # this order makes the slowness warning conservative... ie progress seems to speed up at the end ### warning: this optim is only correct when mol1 == mol2 # and (i think) when there is no "bend" relating them. # (but for i1 == i2 we do the calc -- no guarantee mol1 is identical to mol2.) s1 = sings1[i1] s2 = sings2[i2] (ok, ideal, err) = mergeable_singlets_Q_and_offset(s1, s2) if _EXTRUDE_LOOP_DEBUG: print "extrude loop %d, %d got %r" % (i1, i2, (ok, ideal, err)) if ok: mergeables[(i1,i2)] = (ideal, err) #e self.mergeables is in an obs format... but we still use it to look up (i1,i2) or their swapped form # final msg with same transient_id msg = "scanned %d open-bond pairs..." % ( len(sings1) * len(sings2) ,) # longer msg below env.history.message( msg, transient_id = transient_id, repaint = 1 ) env.history.message("") # make it get into history right away del transient_id # make handles from mergeables. # Note added 041222: the handle (i1,i2) corresponds to the possibility # of bonding singlet number i1 in unit[k] to singlet number i2 in unit[k+1]. # As of 041222 we have self.broken_externs, list of (s1,s2) where s1 is # something outside, and s2 is in the baseunit. We assume (without real # justification) that all this outside stuff should remain fixed and bound # to the baseunit; to avoid choosing unit-unit bonds which would prevent # that, we exclude (i1,i2) when singlet[i1] = s2 for some s2 in # self.broken_externs -- if we didn't, singlet[i1] in base unit would # need to bond to unit2 *and* to the outside stuff. excluded = 0 for (i1,i2),(ideal,err) in mergeables.items(): pos = ideal radius = err radius *= (1.1/0.77) * 1.0 # see a removed "bruce 041101" comment for why info = (i1,i2) if self.basemol_singlets[i1] not in self.broken_extern_s2s: hset.addHandle(pos, radius, info) else: excluded += 1 if i2 != i1: # correct for optimization above pos = -pos info = (i2,i1) if self.basemol_singlets[i2] not in self.broken_extern_s2s: hset.addHandle(pos, radius, info) else: excluded += 1 else: print "fyi: singlet %d is mergeable with itself (should never happen, except maybe in ring mode)" % i1 # handle has dual purposes: click to change the offset to the ideal, # or find (i1,i2) from an offset inside the (pos, radius) ball. msg = "scanned %d open-bond pairs; %d pairs could bond at some offset (as shown by bond-offset spheres)" % \ ( len(sings1) * len(sings2) , len(hset.handles) ) self.status_msg(msg) if excluded: print "fyi: %d pairs excluded due to external bonds to extruded unit" % excluded ###@@@ return def recompute_for_new_bend(self): """ Recompute things which depend on the choice of bend between units (for ring mode). """ pass have_offset_specific_data = 0 # we do this in clear_command_state() too def recompute_offset_specific_data(self): """ Recompute whatever depends on offset but not on tol or bonds -- nothing at the moment. """ pass def redo_look_of_bond_offset_spheres(self): # call to us moved from recompute_offset_specific_data to recompute_bonds """ #doc; depends on offset and tol and len(bonds) """ # kluge: try: # teensy magenta ball usually shows position of offset rel to the white balls (it's also draggable btw) if len( self.bonds_for_current_offset_and_tol ) >= 1: ### worked with > 1, will it work with >= 1? ######@@@ teensy_ball_pos = V(0,0,0) # ... but make it not visible if there are any bonds [#e or change color??] #e minor bug: it sometimes stays invisible even when there is only one bond again... # because we are not rerunning this when tol changes, but it depends on tol. Fix later. ####### else: teensy_ball_pos = self.offset #k i think this is better than using self.offset_for_bonds hset2 = self.nice_offsets_handle hset2.handle_setpos( 1, teensy_ball_pos ) # positions the teensy magenta ball hset = self.nice_offsets_handleset hset.special_pos = self.offset_for_bonds # tells the white balls who contain this offset to be slightly blue except: print "fyi: hset2/hset kluge failed" # don't call recompute_bonds, our callers do that if nec. return bonds_for_current_offset_and_tol = (17,) # we do this in clear_command_state() too offset_for_bonds = None def recompute_bonds(self): """ Call this whenever offset or tol changes. """ ##k 041017 night: temporary workaround for the bonds being wrong for anything but a straight rod: # in other products, use the last offset we used to compute them for a rod, not the current offset. # even better might be to "or" the sets of bonds created for each offset tried... but we won't get # that fancy for now. if self.product_type == "straight rod": self.offset_for_bonds = self.offset else: if not self.offset_for_bonds: msg = "error: bond-offsets not yet computed, but computing them for %r is not yet implemented" % self.product_type env.history.message(msg, norepeat_id = msg) return else: msg = "warning: for %r, correct bond-offset computation is not yet implemented;\n" \ "using bond-offsets computed for \"rod\", at last offset of the rod, not current offset" % \ self.product_type env.history.message(msg, norepeat_id = msg) #e we could optim by returning if only offset but not tol changed, but we don't bother yet self.redo_look_of_bond_offset_spheres() # uses both self.offset and self.offset_for_bonds # recompute what singlets to show in diff color, what bonds to make... # basic idea: see which nice-offset-handles contain the offset, count them, and recolor singlets they come from. hset = self.nice_offsets_handleset #e revise this code if we cluster these, esp. if we change their radius hh = hset.findHandles_containing(self.offset_for_bonds) # semi-kluge: this takes into account self.bond_tolerance, since it was patched into hset.radius_multiplier # kluge for comparing it with prior value; depends on order stability of handleset, etc hh = tuple(hh) if hh != self.bonds_for_current_offset_and_tol: self.needs_repaint = 1 # usually true at this point ##msg = "new set of %d nice bonds: %r" % (len(hh), hh) ##print msg ## self.status_msg(msg) -- don't obscure the scan msg yet ####### self.bonds_for_current_offset_and_tol = hh # change singlet color dict(??) for i1,i2 in ..., proc(i1, col1), proc(i2,col2)... self.singlet_color = {} for mol in self.molcopies: mol.changeapp(0) ##e if color should vary with bond closeness, we'd need changeapp for every offset change; # then for speed, we'd want to repeatedly draw one mol, not copies like now # (maybe we'd like to do that anyway). for (pos,radius,info) in hh: i1,i2 = info ####stub; we need to worry about repeated instances of the same one (as same of i1,i2 or not) def doit(ii, color): basemol_singlet = self.basemol_singlets[ii] mark = basemol_singlet.info self.singlet_color[mark] = color # when we draw atoms, somehow they find self.singlet_color and use it... doit(i1, blue) doit(i2, green) ###e now how do we make that effect the look of the base and rep units? patch atom.draw? # but as we draw the atom, do we look up its key? is that the same in the mol.copy?? nbonds = len(hh) self.propMgr.set_bond_tolerance_and_number_display( self.bond_tolerance, nbonds) ###e ideally we'd color the word "bonds" funny, or so, to indicate that offset_for_bonds != offset or that ptype isn't rod... #e repaint, or let caller do that (perhaps aftermore changes)? latter - only repaint at end of highest event funcs. return def draw_bond_lines(self, unit1, unit2): #bruce 050203 experiment ####@@@@ PROBABLY NEEDS OPTIMIZATION """ draw white lines showing the bonds we presently propose to make between the given adjacent units """ # works now, but probably needs optim or memo of find_singlets before commit -- # just store a mark->singlet table in the molcopies -- once when each one is made should be enough i think. hh = self.bonds_for_current_offset_and_tol self.prep_to_make_inter_unit_bonds() # needed for find_singlet; could be done just once each time bonds change, i think bondline_color = get_selCurve_color(0,self.o.backgroundColor) # Color of bond lines. mark 060305. for (pos,radius,info) in hh: i1,i2 = info ## not so simple as this: p1 = unit1.singlets[i1].posn() s1 = self.find_singlet(unit1,i1) # this is slow! need to optimize this (or make it optional) s2 = self.find_singlet(unit2,i2) p1 = s1.posn() p2 = s2.posn() drawline(bondline_color, p1, p2) ## #bruce 050324 experiment, worked: ## s1.overdraw_with_special_color(magenta) ## s2.overdraw_with_special_color(yellow) return # methods related to exiting this mode def finalize_product(self, cancelling = False): #bruce 050228 adding cancelling=0 to help fix bug 314 and unreported bugs """ if requested, make bonds and/or join units into one part; cancelling = True means just do cleanup, use diff msgs """ if not cancelling: desc = " (N = %d)" % self.ncopies #e later, also include circle_n if different and matters; and more for other product_types ##self.final_msg_accum = "extrude done: " self.final_msg_accum = "%s making %s%s: " % (self.get_featurename().split()[0], self.product_type, desc) # first word of commandName msg0 = "leaving mode, finalizing product..." # if this lasts long enough to read, something went wrong self.status_msg(self.final_msg_accum + msg0) # bruce 070407 not printing this anymore: ## print "fyi: extrude params not mentioned in statusbar: offset = %r, tol = %r" % (self.offset, self.bond_tolerance) else: msg = "%s cancelled (warning: might not fully restore initial state)" % (self.get_featurename().split()[0],) self.status_msg( msg) if self.whendone_make_bonds and not cancelling: # NIM - rebond base unit with its home molecule, if any [###@@@ see below] # (but not if product is a closed ring, right? not sure, actually, deps on which singlets are involved) #e even the nim-warning msg is nim... #e (once we do this, maybe do it even when not self.whendone_make_bonds??) # unit-unit bonds: bonds = self.bonds_for_current_offset_and_tol if not bonds: bonds_msg = "no bonds to make" else: bonds_msg = "making %d bonds per unit..." % len(bonds) self.status_msg(self.final_msg_accum + bonds_msg) if bonds: self.prep_to_make_inter_unit_bonds() for ii in range(1, self.ncopies): # 1 thru n-1 (might be empty range, that's ok) # bond unit ii with unit ii-1 self.make_inter_unit_bonds( self.molcopies[ii-1], self.molcopies[ii], bonds ) # uses self.basemol_singlets, etc if self.product_type == "closed ring" and not cancelling: # close the ring ###@@@ what about broken_externs? Need to modify bonding for ring, for this reason... ###@@@ self.make_inter_unit_bonds( self.molcopies[self.ncopies-1], self.molcopies[0], bonds ) bonds_msg = "made %d bonds per unit" % len(bonds) self.status_msg(self.final_msg_accum + bonds_msg) self.final_msg_accum += bonds_msg #bruce 050228 fix an unreported(?) bug -- do the following even when not whendone_make_bonds: # merge base back into its fragmented ancestral molecule... # but not until the end, for fear of messing up unit-unit bonding # (could be dealt with, but easier to skirt the issue). if not self.product_type == "closed ring": # 041222 finally implementing this... ###@@@ closed ring case has to be handled differently earlier... [but isn't yet, which is a probably-unreported bug] for s1,s2 in self.broken_externs: try: bond_at_singlets(s1, s2, move = False) except:#050228 print_compact_traceback("error fixing some broken bond, ignored: ") # can happen in ring mode, at least # 070410: if not cancelling, here is where we merge original selection (and each copy) # into a single chunk (or turn it into a group), if desired by a new debug_pref # (or dashboard checkbox (nim)). self.whendone_merge_each_unit = self.get_whendone_merge_each_unit() if self.whendone_merge_each_unit and not cancelling: for unit in self.molcopies: assert not isinstance(unit, Chunk) #bruce 070412 try: unit.internal_merge() except AttributeError: print "following exception in unit.internal_merge() concerns unit = %r" % (unit,) raise self.basemol = self.molcopies[0] self.separate_basemols = [self.basemol] # needed only if still used (unlikely); but harmless, so do it to be safe ###e other internal updates needed?? if self.whendone_all_one_part and not cancelling: # update, bruce 070410: "whendone_all_one_part" is now misnamed, since it's independent with "merge selection", # so it's now called Merge Copies in the UI (Qt3, desired for Qt4) rather than Merge Chunks. # rejoin base unit with its home molecule, if any -- NIM [even after 041222] #e even the nim-warning msg is nim... #e (once we do this, maybe do it even when not self.whendone_all_one_part??) # join all units into basemol self.final_msg_accum += "; " join_msg = "joining..." # this won't be shown for long, if no error self.status_msg(self.final_msg_accum + join_msg) product = self.basemol #e should use home mol, but that's nim for unit in self.molcopies[1:]: # all except basemol product.merge(unit) # also does unit.kill() self.product = product #e needed? if self.ncopies > 1: join_msg = "joined into one part" else: join_msg = "(one unit, nothing to join)" #e should we change ncopies and molcopies before another redraw could occur? self.final_msg_accum += join_msg self.status_msg(self.final_msg_accum) else: if self.ncopies > 1: self.final_msg_accum += " (left units as separate parts)" else: pass # what is there to say? if not cancelling: self.status_msg(self.final_msg_accum) return def get_whendone_merge_each_unit(self): #bruce 070410 # split this out so it can be exercised in Enter to make sure the pref appears in the menu, # and so there's one method to change if we make this a checkbox. # # update, bruce 070411, Qt4 only: I'm hooking this up to a checkbox, Qt4 branch only. # (The attr this accesses is created by reinit_extrude_controls.) (I also removed the # early call in self.Enter, since it's not needed after this change.) ## return debug_pref("Extrude: merge selection?", Choice_boolean_False, ## non_debug = True, prefs_key = True) return self.whendone_merge_selection # this is set/reset automatically when a PM checkbox is changed def prep_to_make_inter_unit_bonds(self): self.i1_to_mark = {} #e keys are a range of ints, could have used an array -- but entire alg needs revision anyway for i1, s1 in zip(range(len(self.basemol_singlets)), self.basemol_singlets): self.i1_to_mark[i1] = s1.info # used by self.find_singlet #e find_singlet could just look directly in self.basemol_singlets *right now*, # but not after we start removing the singlets from basemol! return def make_inter_unit_bonds(self, unit1, unit2, bonds = ()): # you must first call prep_to_make_inter_unit_bonds, once #e this is quadratic in number of singlets, sorry; not hard to fix ##print "bonds are %r",bonds if isinstance(unit1, Chunk): #bruce 070407 kluge: don't bother supporting this uncommon error message yet for fake_copied_mols etc. # To support it we'd have to scan & compare every true chunk. # Sometime it'd be good to do this... #e from utilities.Log import redmsg if (not unit1.assy) or (not unit2.assy): ###@@@ better test for mol.killed? #bruce 050317: don't bond to deleted units (though I doubt this # is sufficient to avoid bugs from user deleting them in the MT during this mode) ###@@@ this 'then clause', and the condition being inclusive enough, is untested as of 050317 msg = "warning: can't bond deleted repeat-units" #e should collapse several warnings into one env.history.message( redmsg( msg)) return if unit1.part != unit2.part: #bruce 050317: avoid making inter-part bonds (even if merging units could fix that) msg = "warning: can't bond repeat-units in different Parts" ###e could improve, name the parts, collapse several to 1 or name the units # (but not high priority, since we haven't documented this as a feature) env.history.message( redmsg( msg)) return for (offset,permitted_error,(i1,i2)) in bonds: # ignore offset,permitted_error; i1,i2 are singlet indices # assume no singlet appears twice in this list! # [not yet justified, 041015 1207p] s1 = self.find_singlet(unit1,i1) s2 = self.find_singlet(unit2,i2) if s1 and s2: # replace two singlets (perhaps in different mols) by a bond between their atoms bond_at_singlets(s1, s2, move = False) else: #e will be printed lots of times, oh well print "extrude warning: one or both of singlets %d,%d slated to bond in more than one way, not all bonds made" % (i1,i2) return def find_singlet(self, unit, i1): """ Find the singlet #i1 in unit, and return it, or None if it's not there anymore (should someday never happen, but can for now) (arg called i1 could actually be i1 or i2 in bonds list) (all this singlet-numbering is specific to our current basemol) (only works if you first once called prep_to_make_inter_unit_bonds) """ mark = self.i1_to_mark[i1] # note: mark is basemol key [i guess that means: singlet's Atom.key in basemol], # but unrelated to other mols' keys for unitmol in true_Chunks_in(unit): for atm in unitmol.atoms.itervalues(): #e optimize this someday -- its speed can probably matter if atm.info == mark: return atm print "extrude bug (trying to ignore it): singlet not found",unit,i1 # can happen until we remove dup i1,i2 from bonds return None # mouse events def leftDown(self, event): """ Move the touched repunit object, or handle (if any), in the plane of the screen following the mouse, or in some other way appropriate to the object. """ ####e Also highlight the object? (maybe even do that on mouseover ####) use bareMotion self.o.SaveMouse(event) # saves in self.o.MousePos, used in leftDrag thing = self.dragging_this = self.touchedThing(event) if thing: self.dragged_offset = self.offset # fyi: leftDrag directly changes only self.dragged_offset; # then recompute from controls (sp?) compares that to self.offset, changes that msg = thing.leftDown_status_msg() if not msg: msg = "touched %s" % (thing,) self.status_msg(msg) self.needs_repaint = 1 # for now, guess that this is always true (tho it's only usually true) thing.click() # click handle in appropriate way for its type (#e in future do only on some mouseups) self.repaint_if_needed() # (sometimes the click method already did the repaint, so this doesn't) return def status_msg(self, text): # bruce 050106 simplified this env.history.message(text) show_bond_offsets_handlesets = [] # (default value) the handlesets to be visible iff self.show_bond_offsets def touchedThing(self, event): """ Return None or the thing touched by this event. """ touchable_molecules = True if self.product_type != "straight rod": touchable_molecules = False # old comment: # This function won't work properly in this case. # Be conservative until that bug is fixed. It's not even safe to permit # a click on a handle (which this code is correct in finding), # since it might be obscured on the screen # by some atom the user is intending to click on. # The only safe thing to find in this case would be something purely draggable # with no hard-to-reverse effects, e.g. the "draggable magenta handle", # or the base unit (useful only once we permit dragging the model using it). # I might come back and make those exceptions here, # if I don't fix the overall bug soon enough. [bruce 041017] # # newer comment: # Only disable dragging repunits, don't disable dragging or clicking bond-offset spheres # (even though they might be clicked by accident when visually behind a repunit of the ring). # [bruce 041019] ## self.status_msg("(click or drag not yet implemented for product type %r; sorry)" % self.product_type) ## return None p1, p2 = self.o.mousepoints(event) # (no side effect. p1 is just at near clipping plane; p2 in center of view plane) ##print "touchedthing for p1 = %r, p2 = %r" % (p1,p2) res = [] # (dist, handle) pairs, arb. order, but only the frontmost one from each handleset if self.show_bond_offsets: for hset in self.show_bond_offsets_handlesets: dh = hset.frontDistHandle(p1, p2) # dh = (dist, handle) #######@@@ needs to use bond_tolerance, or get patched if dh: res.append(dh) #e scan other handlesets here, if we have any if touchable_molecules: #e now try molecules (if we have not coded them as their own handlesets too) -- only the base and rep units for now hset = self.basemol_atoms_handleset for ii in range(self.ncopies): ##print "try touch",ii offset = self.offset * ii dh = hset.frontDistHandle(p1, p2, offset = offset, copy_id = ii) if dh: res.append(dh) #e dh's handle contains copy_id, a code for which repunit if res: res.sort() dh = res[0] handle = dh[1] ##print "touched %r" % (handle,) return handle # nothing touched... need to warn? if not touchable_molecules: msg = redmsg("Dragging of repeat units not yet implemented for <b>Ring</b> product type.") self.propMgr.MessageGroupBox.insertHtmlMessage( msg, setAsDefault = False ) self.status_msg("(dragging of repeat units not yet implemented for product type %r; sorry)" % self.product_type) return None def leftDrag(self, event): """ Move the touched objects as determined by leftDown(). ###doc """ if self.dragging_this: self.doDrag(event, self.dragging_this) needs_repaint = 0 def doDrag(self, event, thing): """ drag thing, to new position in event. thing might be a handle (pos,radius,info) or something else... #doc """ # determine motion to apply to thing being dragged. #Current code is taken from TranslateChunks_GraphicsMode. # bruce question -- isn't this only right in central plane? # if so, we could fix it by using mousepoints() again. w=self.o.width+0.0 h=self.o.height+0.0 deltaMouse = V(event.pos().x() - self.o.MousePos[0], self.o.MousePos[1] - event.pos().y(), 0.0) move = self.o.quat.unrot(self.o.scale * deltaMouse/(h*0.5)) self.o.SaveMouse(event) # sets MousePos, for next time self.needs_repaint = 1 # for now, guess that this is always true (tho it's only usually true) thing.move(move) # move handle in the appropriate way for its type #e this needs to set self.needs_repaint = 1 if it changes any visible thing! ##### how does it know?? ... so for now we always set it *before* calling; # that way a repaint during the call can reset the flag. ## was: self.o.assy.movesel(move) self.repaint_if_needed() def repaint_if_needed(self): # see also the end of update_offset_bonds_display -- we're inlined ######fix if self.needs_repaint: self.needs_repaint = 0 self.o.gl_update() return def drag_repunit(self, copy_id, motion): """ Drag a repeat unit (copy_id > 0) or the base unit (id 0). """ assert type(copy_id) == type(1) and copy_id >= 0 if copy_id: # move repunit #copy_id by motion # compute desired motion for the offset which would give # this motion to the repunit # bug note -- the code that supplies motion to us is wrong, # for planes far from central plane -- fix later. motion = motion * (1.0 / copy_id) # store it, but not in self.offset, that's reserved for # comparison with the last value from the controls self.dragged_offset = self.dragged_offset + motion #obs comment?? i forget what it meant: #e recompute_for_new_offset self.force_offset_and_update( self.dragged_offset) else: pass##print "dragging base unit moves entire model (not yet implemented)" return def force_offset_and_update(self, offset): """ Change the controls to reflect offset, then update from the controls. """ x,y,z = offset self.propMgr.call_while_suppressing_valuechanged( lambda: self.propMgr.set_extrude_controls_xyz( (x, y, z) ) ) #e worry about too-low resolution of those spinbox numbers? # at least not in self.dragged_offset... #e status bar msg? no, caller can do it if they want to. self.update_from_controls() # this does a repaint at the end # (at least if the offset in the controls changed) def click_nice_offset_handle(self, handle): (pos,radius,info) = handle i1,i2 = info try: ideal, err = self.mergeables[(i1,i2)] except KeyError: ideal, err = self.mergeables[(i2,i1)] ideal = -1 * ideal self.force_offset_and_update( ideal) def leftUp(self, event): if self.dragging_this: ## self.doDrag(event, self.dragging_this) ## good idea? not sure. probably not. self.dragging_this = None #####e update, now that we know the final position of the dragged thing del self.dragged_offset return # == def leftShiftDown(self, event): pass ##self.StartDraw(event, 0) def leftCntlDown(self, event): pass ##self.StartDraw(event, 2) def leftShiftDrag(self, event): pass ##self.ContinDraw(event) def leftCntlDrag(self, event): pass ##self.ContinDraw(event) def leftShiftUp(self, event): pass ##self.EndDraw(event) def leftCntlUp(self, event): pass ##self.EndDraw(event) def update_cursor_for_no_MB(self): # Fixes bug 1638. mark 060312. """ Update the cursor for 'Extrude' mode (extrudeMode). """ self.o.setCursor(QCursor(Qt.ArrowCursor)) # == drawing helper methods (called by Draw API methods below) def _draw_hsets_transparent_before_model(self): """ """ #bruce 09010 split this out, and into two large pieces # before and after _draw_model #kluge, and messy experimental code [bruce 050218]; # looks good w/ crystal, bad w/ dehydrogenated hoop moiety... # probably better to compute colors, forget transparency. # or it might help just to sort them by depth... and/or # let hits of several work (hit sees transparency); not sure hset1 = self.nice_offsets_handle # opaque hset2 = self.nice_offsets_handleset # transparent # draw back faces of hset2 into depth buffer # (so far this also draws a color - which one? or does it? yes, white.) ## glCullFace(GL_FRONT) glFrontFace(GL_CW) ## glDisable(GL_LIGHTING) glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE) try: hset2.draw(self.o, color = list(self.o.backgroundColor))##green) # alpha factor inside draw method will be 0.25 but won't matter ###e wrong when the special_color gets mixed in # bugs 1139pm: the back faces are not altering depth buffer, # when invis, but are when color = green... why? # is it list vs tuple? does tuple fail for a vector? # they are all turning white or blue in synch, which is # wrong (and they are blue when *outside*, also wrong) # generally it's not working as expected... let alone # looking nice # If i stop disabling lighting above, then it works # better... confirms i'm now showing only insides of spheres # (with color = A(green), ) does A matter btw? seems not to. # ah, maybe the materialfv call in drawsphere assumes lighting... # [this never ended up being diagnosed, but it never came back # after i stopped disabling lighting] except: print_compact_traceback("exc in hset2.draw() backs: ") ## glCullFace(GL_BACK) glFrontFace(GL_CCW) glEnable(GL_LIGHTING) glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE) # draw front faces (default) of hset2, transparently, not altering depth buffer ## hsets = [hset2] glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # this fails since the symbols are not defined, tho all docs say they should be: ## const_alpha = 0.25 ## glBlendColor(1.0,1.0,1.0,const_alpha) # sets the CONSTANT_ALPHA to const_alpha ## glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA) # cf. redbook table 6-1 page 228 # so instead, I hacked hset2.draw to use alpha factor of 0.25, for now # it looked bad until I remembered that I also need to disable writing the depth buffer. # But the magenta handle should have it enabled... glDepthMask(GL_FALSE) try: hset2.draw(self.o) except: print_compact_traceback("exc in hset2.draw() fronts with _TRANSPARENT: ") glDisable(GL_BLEND) glDepthMask(GL_TRUE) # draw front faces again, into depth buffer only glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE) try: hset2.draw(self.o) except: print_compact_traceback("exc in hset2.draw() fronts depth: ") glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE) # draw model (and hset1) here, so it's obscured by those # invisible front and (less importantly) back faces # (this is done in _draw_model and then the following method; # it's split this way due to splitting of Draw in GM API, bruce 090310) return def _draw_model(self): #bruce 050218 split this out """ Draw the entire model including our base and repeat units, or just our base and repeat units, depending on settings. """ try: part = self.o.assy.part # "the model" if self.show_entire_model: part.draw(self.o) # includes before_drawing_model, etc else: part.before_drawing_model() #bruce 070928 fix predicted bug try: for mol in self.molcopies: #e use per-repunit drawing styles... ## dispdef = mol.get_dispdef( self.o) # not needed, since... dispdef = 'bug' mol.draw(self.o, dispdef) # ...dispdef arg not used (041013) # update, bruce 070407: now that mol can also be a fake_copied_mol, # it's simplest to just use a fake dispdef here. finally: part.after_drawing_model() #bruce 070928 fix predicted bug try: #bruce 050203 for unit1,unit2 in zip(self.molcopies[:-1],self.molcopies[1:]): self.draw_bond_lines(unit1,unit2) except: print_compact_traceback("exception in draw_bond_lines, ignored: ") print_compact_stack("stack from that exception was: ") except: print_compact_traceback("exception in _draw_model, ignored: ") return def _draw_hsets_transparent_after_model(self): """ """ #bruce 09010 split this out, and into two large pieces # before and after _draw_model hset1 = self.nice_offsets_handle # opaque try: hset1.draw(self.o) # opaque except: print_compact_traceback("exc in hset1.draw(): ") return def _draw_ring_axis_and_spokes(self): #bruce 09010 split this out """ """ if self.product_type == 'closed ring': try: from utilities.constants import red self.update_ring_geometry(emit_messages = False) # emit_messages = False to fix infinite redraw loop # when it chooses z-y plane and prints a message about that # [bruce 071001] center = self.circle_center # set by update_ring_geometry axis = self.axis_dir # ditto radius_vec = self.radius_vec # ditto # draw axis drawline( red, center, center + axis * 10, width = 2) for ii in range(self.circle_n): # draw spoke ii quatii_rel_junk, spoke_vec = self._spoke_quat_and_vector(ii) color = (ii and green) or blue drawline(color, center, center + spoke_vec, width = 2) pass except: msg = "exception using debug_pref(%r) ignored" % \ "Extrude: draw ring axis" print_compact_traceback(msg + ": ") pass pass return # == _TRANSPARENT = True #bruce 050218 experiment -- set to True for "transparent bond-offset # spheres" (works but doesn't always look good) #bruce 050222 update - Mark wants this "always on" for now... # but I ought to clean up the code sometime soon def Draw_other_before_model(self): """ Do non-CSDL/DrawingSet drawing, *before* Draw_model. """ _superclass.Draw_other_before_model(self) if self.show_bond_offsets: hsets = self.show_bond_offsets_handlesets if self._TRANSPARENT and len(hsets) == 2: hset1 = self.nice_offsets_handle hset2 = self.nice_offsets_handleset assert hset1 in hsets assert hset2 in hsets self._draw_hsets_transparent_before_model() pass pass return def Draw_model(self): """ Draw the model (using only CSDL/DrawingSet drawing). """ _superclass.Draw_model(self) self._draw_model() ### REVIEW: I'm not sure if this follows the rule of only using # CSDLs (not plain drawprimitives or immediate-mode OpenGL) # for drawing. (It does if it only calls Chunk draw methods, # except for ways in which ChunkDrawer still violates that rule, # but that will be fixed in ChunkDrawer.) [bruce 090311 comment] return def Draw_other(self): """ Do non-CSDL/DrawingSet drawing, *after* Draw_model. """ _superclass.Draw_other(self) if self.show_bond_offsets: hsets = self.show_bond_offsets_handlesets if self._TRANSPARENT and len(hsets) == 2: hset1 = self.nice_offsets_handle hset2 = self.nice_offsets_handleset assert hset1 in hsets assert hset2 in hsets self._draw_hsets_transparent_after_model() else: #pre-050218 code for hset in hsets: try: hset.draw(self.o) except: print_compact_traceback("exc in some hset.draw(): ") continue pass pass if debug_pref("Extrude: draw ring axis and spokes", Choice_boolean_False, prefs_key = True ): #bruce 070928 # [this used to happen before Draw_model, but its order # shouldn't matter. [bruce 090310]] self._draw_ring_axis_and_spokes() return # == ## Added this method to fix bug 1043 [Huaicai 10/04/05] def Draw_after_highlighting(self, pickCheckOnly = False): """ Only draw translucent parts of the whole model when we are requested to draw the whole model. """ if self.show_entire_model: return _superclass.Draw_after_highlighting(self, pickCheckOnly) return # == call_makeMenus_for_each_event = True #bruce 050914 enable dynamic context menus [fixes bug 971] def makeMenus(self): #e not yet reviewed for being good choices of what needs including in extrude cmenu self.Menu_spec = [ ('Cancel', self.command_Cancel), ('Start Over', self.StartOver), ('Done', self.command_Done), #bruce 041217 ] self.debug_Menu_spec = [ ('debug: reload module', self.extrude_reload), ] self.Menu_spec_control = [ ('Invisible', self.w.dispInvis), None, ('Default', self.w.dispDefault), ('Lines', self.w.dispLines), ('Ball & Stick', self.w.dispBall), ('Tubes', self.w.dispTubes), ('CPK', self.w.dispCPK), None, ('Color', self.w.dispObjectColor) ] return def extrude_reload(self): """ for debugging: try to reload extrudeMode.py and patch your glpane to use it, so no need to restart Atom. Might not always work. [But it did work at least once!] """ global extrudeMode print "extrude_reload: here goes.... (not fully working as of 080805)" # status as of 080805: mostly works, but: # - warns about duplicate featurename; # - extrude refuses entry since nothing is selected (should select repunit to fix); # - has some dna updater errors if it was extruding dna (might be harmless). try: self.propMgr.extrudeSpinBox_n.setValue(1) self.update_from_controls() print "reset ncopies to 1, to avoid dialog from exit_is_forced, and ease next use of the mode" except: print_compact_traceback("exception in resetting ncopies to 1 and updating, ignored: ") ## try: ## self.restore_gui() ## except: ## print_compact_traceback("exception in self.restore_gui(), ignored: ") self.commandSequencer.exit_all_commands() #bruce 080805 ## for clas in [extrudeMode]: ## try: ## self.commandSequencer.mode_classes.remove(clas) # was: self.__class__ ## except ValueError: ## print "a mode class was not in _commandTable (normal if last reload of it had syntax error)" self.commandSequencer.remove_command_object( self.commandName) #bruce 080805 import graphics.drawables.handles as handles reload(handles) import commands.Extrude.extrudeMode as _exm reload(_exm) from commands.Extrude.extrudeMode import extrudeMode # note global declaration above ## try: ## do_what_MainWindowUI_should_do(self.w) # remake interface (dashboard), in case it's different [041014] ## except: ## print_compact_traceback("exc in new do_what_MainWindowUI_should_do(), ignored: ") ## ## self.commandSequencer._commandTable['EXTRUDE'] = extrudeMode ## self.commandSequencer.mode_classes.append(extrudeMode) self.commandSequencer.register_command_class( self.commandName, extrudeMode ) #bruce 080805 # note: this does NOT do whatever recreation of a cached command # object might be needed (that's done only in _reinit_modes) print "about to reset command sequencer" # need to revise following to use some cleaner interface self.commandSequencer._reinit_modes() # leaves mode as nullmode as of 050911 self.commandSequencer.start_using_initial_mode( '$DEFAULT_MODE' ) ###e or could use commandName of prior self.commandSequencer.currentCommand print "done with _reinit_modes, now we'll try to reenter extrudeMode" self.commandSequencer.userEnterCommand( self.commandName) #bruce 080805 return pass # end of class extrudeMode # == # helper functions for extrudeMode.Enter def assy_merge_mols(assy, mollist): """ merge multiple mols (Chunks) in assy (namely, the elements of sequence mollist) into one mol in assy [destructively modifying the first mol in mollist to be the one], and return it """ # note: doesn't use assy arg, but assumes all mols in mollist are in same assy and Part [070408 comment] mollist = list(mollist) # be safe in case it's identical to assy.selmols, # which we might modify as we run assert len(mollist) >= 1 ## mollist.sort() #k ok for mols? should be sorted by name, or by ## # position in model tree groups, I think... ## for now, don't sort, use selection order instead. res = mollist[0] if 1: ## debug_pref("Extrude: leave base-chunks separate", Choice_boolean_False, non_debug = True, prefs_key = True): #bruce 070410 making this always happen now (but Enter should call # get_whendone_merge_each_unit to exercise debug pref); # when we're done we will do the merge differently # according to "merge selection" checkbox or debug_pref, in finalize_product, # not here when we enter the mode! # # could optim by not doing this when only one member, # but that might hide bugs and doesn't matter otherwise, so nevermind. res = fake_merged_mol(res) for mol in mollist[1:]: # ok if no mols in this loop res.merge(mol) #041116 new feature # note: this will unpick mol (modifying assy.selmols) and kill it return res def assy_fix_selmol_bugs(assy): """ Work around bugs in other code that prevent extrude from entering. """ # 041116 new feature; as of 041222, runs but don't know if it catches bugs # (maybe they were all fixed). # Note that selected chunks might be in clipboard, and as of 041222 # they are evidently also in assy.molecules, and extrude operates on them! # It even merges units from main model and clipboard... not sure that's good, # but ignore it until we figure out the correct model tree selection semantics # in general. for mol in list(assy.selmols): if (mol not in assy.molecules) or (not mol.dad) or (not mol.assy): try: it = " (%r) " % mol except: it = " (exception in its repr) " print "fyi: pruning bad mol %s left by prior bugs" % it try: mol.unpick() except: pass # but don't kill it (like i did before 041222) # in case it's in clipboard and user wants it still there #e worry about selatoms too? return def assy_extrude_unit(assy, really_make_mol = 1): """ If we can find a good extrude unit in assy, make it a molecule in there, and return (True, mol) [as of 070412 bugfixes, mol is always a fake_merged_mol]; else return (False, whynot). Note: we might modify assy even if we return False in the end!!! To mitigate that (for use in command_ok_to_enter), caller can pass really_make_mol = 0, and then we will not change anything in assy (unless it has bugs caught by assy_fix_selmol_bugs), and we'll return either (True, "not a mol") or (False, whynot). """ # bruce 041222: adding really_make_mol flag. ## not needed (and not good) after assy/part split, 050309: ## assy.unselect_clipboard_items() #bruce 050131 for Alpha assy_fix_selmol_bugs(assy) resmol = "not a mol" if assy.selmols: assert type(assy.selmols) == type([]) # assumed by this code; always true at the moment if really_make_mol: resmol = assy_merge_mols( assy, assy.selmols) # merge the selected mols into one return True, resmol #e in future, better to make them a group? or use them in parallel? elif assy.selatoms: if really_make_mol: res = [] def new_old(new, old): # new = fragment of selected atoms, old = rest of their mol assert new.atoms res.append(new) #e someday we might use old too, eg for undo or # for heuristics to help deal with neighbor-atoms... assy.modifySeparate(new_old_callback = new_old) # make the selected atoms into their own mols # note: that generates a status msg (as of 041222). assert res, "what happened to all those selected atoms???" resmol = assy_merge_mols( assy, res) # merge the newly made mol-fragments into one #e or for multiple mols, should we do several extrudes in parallel? hmm, might be useful... return True, resmol elif len(assy.molecules) == 1: # nothing selected, but exactly one molecule in all -- just use it if really_make_mol: resmol = assy.molecules[0] resmol = fake_merged_mol(resmol) #bruce 070412 bugfix, might be redundant # with another one or might fix other uncaught bugs return True, resmol else: ## print 'assy.molecules is',`assy.molecules` #debug return False, "Nothing selected to extrude." pass # == #e between two molecules, find overlapping atoms/bonds ("bad") or singlets ("good") -- # as a function of all possible offsets # (in future, some cases of overlapping atoms might be ok, # since those atoms could be merged into one) # (for now, we notice only bondable singlets, nothing about # overlapping atoms or bonds) cosine_of_permitted_noncollinearity = 0.5 #e we might want to adjust this parameter def mergeable_singlets_Q_and_offset(s1, s2, offset2 = None, tol = 1.0): """ Figure out whether singlets s1 and s2, presumed to be in different molecules (or in different copies, if now in the same molecule), could reasonably be merged (replaced with one actual bond), if s2.molecule was moved by approximately offset2 (or considering all possible offset2's if this arg is not supplied); and if so, what would be the ideal offset (slightly different from offset2) after this merging. Return (False, None, None) or (True, ideal_offset2, error_offset2), where error_offset2 gives the radius of a sphere of reasonable offset2 values, centered around ideal_offset2. The tol option, default 1.0, can be given to adjust the error_offset2 (by multiplying the standard value), both for returning it and for deciding whether to return (False,...) or (True,...). Larger tol values make it more likely that s1,s2 are considered bondable. To perform actual bonding, see bonds.bond_at_singlets. But note that it is quite possible for the same s1 to be considered bondable to more than one s2 (or vice versa), even for tol = 1.0 and especially for larger tol values. """ #bruce 050324 added tol option [###@@@ untested] for use by Mark in Fuse Chunks; # it's not yet used in extrudeMode, but could be if we changed to # recalculating bondable pairs more often, e.g. to fix bugs in ring mode. #e someday we might move this to a more general file #e once this works, we might need to optimize it, # since it redoes a lot of the same work # when called repeatedly for the same extrudable unit. res_bad = (False, None, None) a1 = s1.singlet_neighbor() a2 = s2.singlet_neighbor() r1 = a1.atomtype.rcovalent r2 = a2.atomtype.rcovalent dir1 = norm(s1.posn()-a1.posn()) dir2 = norm(s2.posn()-a2.posn()) # the open bond directions (from their atoms) should point approximately # opposite to each other -- per Josh suggestion, require them to be # within 60 deg. of collinear. closeness = - dot(dir1, dir2) # ideal is 1.0, terrible is -1.0 if closeness < cosine_of_permitted_noncollinearity: if _EXTRUDE_LOOP_DEBUG and closeness >= 0.0: print "rejected nonneg closeness of %r since less than %r" % \ (closeness, cosine_of_permitted_noncollinearity) return res_bad # ok, we'll merge. Just figure out the offset. At the end, compare to offset2. # For now, we'll just bend the half-bonds by the same angle to make them # point at each other, ignoring other bonds on their atoms. new_dir1 = norm( (dir1 - dir2) / 2 ) new_dir2 = - new_dir1 #e needed? a1_a2_offset = (r1 + r2) * new_dir1 # ideal offset, just between the atoms a1_a2_offset_now = a2.posn() - a1.posn() # present offset between atoms ideal_offset2 = a1_a2_offset - a1_a2_offset_now # required shift of a2 error_offset2 = (r1 + r2) / 2.0 # josh's guess (replaces 1.0 from the initial tests) error_offset2 *= tol # bruce 050324 new feature, untested ###@@@ if offset2 is not None: #bruce 050328 bugfix: don't use boolean test of offset2 #050513 != -> is not if vlen(offset2 - ideal_offset2) > error_offset2: return res_bad return (True, ideal_offset2, error_offset2) # == # detect reloading try: _already_loaded except: _already_loaded = 1 else: print "reloading extrudeMode.py" pass def mark_singlets(separate_basemols, colorfunc): for basemol in separate_basemols:#bruce 070407 [#e or could use true_Chunks_in] for a in basemol.atoms.itervalues(): ## a.info = a.key a.set_info(a.key) #bruce 060322 basemol._colorfunc = colorfunc # maps atoms to colors (due to a hack i will add) return def true_Chunks_in(mol): #bruce 070407 if isinstance(mol, Chunk): return [mol] else: return list(mol._mols) pass # not done: # for (i1,i2) in bonds: # assume no singlet appears twice in this list! # this is not yet justified, and if false will crash it when it makes bonds # == # bruce 070407 new stuff for making it possible to not merge the mols in assy_extrude_unit class virtual_group_of_Chunks: """ private superclass for sets of chunks treated in some ways as if they were one chunk. """ # Note: we don't define __init__ since it differs in each subclass. # But it's always required to somehow create a list, self._mols. # Note: we define some methods here even if only one subclass needs them, # when they'd clearly be correct for any virtual group of Chunks. def draw(self, glpane, dispdef): for mol in self._mols: mol.draw(glpane, dispdef) def changeapp(self, *args): for mol in self._mols: mol.changeapp(*args) def _get_externs(self): """ Get a list of bonds which bridge atoms in one of our chunks to atoms not in one of them. """ # alg: this is a subset of the union of the sets of externs of our chunks. ourmols = dict([(mol,1) for mol in self._mols]) #e could cache this, but not important is_ourmol = lambda mol: mol in ourmols res = [] for mol in self._mols: for bond in mol.externs: if not (is_ourmol(bond.atom1.molecule) and is_ourmol(bond.atom2.molecule)): res.append(bond) return res def _get_singlets(self): res = [] for mol in self._mols: res.extend(mol.singlets) return res def get_dispdef(self): assert 0, "need to zap all direct uses of get_dispdef in class %r" % (self.__class__.__name__) def unpick(self): for mol in self._mols: mol.unpick() return def kill(self): for mol in self._mols: mol.kill() return def internal_merge(self): """ Merge each of our chunks into the first one. """ first = self._mols[0] others = self._mols[1:] for other in others: first.merge(other) return pass # end of class virtual_group_of_Chunks class fake_merged_mol( virtual_group_of_Chunks): #e rename? 'extrude_unit_holder' """ private helper class for use in Extrude, to let it treat a set of chunks (comprising the extrude unit) as if they were merged into one chunk, without actually merging them. """ def __init__(self, mols): self._mols = [] try: mols = list(mols) except: mols = [mols] # kluge(?) -- let mols be a single mol or a list of them for mol in mols: self.merge(mol) def merge(self, mol): """ Unlike Chunk.merge(mol) (for mol being another chunk), only remember mol, don't steal its atoms and kill it. Also let mol be a Group, not just a Chunk (though we may define fewer methods correctly in that case, since we define just barely enough to get by in the current private use). We will let Extrude call this method and think it's really merging, though it's not. NOTE: it calls this not only in assy_extrude_unit, but in merging the copies to create the final product. We detect that (by class of mol) and act differently. """ if isinstance(mol, fake_copied_mol): # assume it's a copy of us, and this is during extrude's "final product merge"; # merge its mols into ours, in order assert len(self._mols) == len(mol._mols) for ourmol, itsmol in zip(self._mols, mol._mols): ourmol.merge(itsmol) else: # assume we're being initially built up by assy_merge_mols, so mol is a Chunk assert isinstance(mol, Chunk) self._mols.append(mol) return def __getattr__(self, attr): # in class fake_merged_mol if attr.startswith('__'): raise AttributeError, attr if attr == 'externs': return self._get_externs() # don't cache, since not constant (too slow?? ###) if attr == 'singlets': return self._get_singlets() # don't cache, since not constant if attr == 'quat': return getattr(self._mols[0], attr) # update 070411: self.center is computed and cached in full_inval_and_update; # before that, it's illegal to ask for it raise AttributeError, "%r has no %r" % (self, attr) ## def copy(self, dad): ## self.copy_single_chunk(dad) def copy_single_chunk(self, dad): """ copy our mols and store them in a new fake_copied_mol (which might make a Group from them, fyi) """ #bruce 080314 renamed (here and in class Chunk), added copy glue; see comment where it's called here assert dad is None ## copies = [mol.copy_single_chunk(None) for mol in self._mols] # this is wrong when there are bonds between these mols! # WARNING: the following code after our call to copy_nodes_in_order is similar to # other code after calls to the related function copied_nodes_for_DND, e.g. in depositMode.py. # A higher-level utility routine which does all this post-processing should be added to ops_copy.py. ###e from operations.ops_copy import copy_nodes_in_order #bruce 070525 precaution: use this instead of copied_nodes_for_DND, since order # (in fact, precise 1-1 orig-copy correspondence) matters here. oldnodes = self._mols newnodes = copy_nodes_in_order(list(self._mols)) #k list() wrapper is just a precaution, probably not needed # note: these copies are not yet added to the model (assy.tree). assert type(newnodes) == type([]) assert len(newnodes) == len(oldnodes) #k can one of these fail if we try to copy a jig w/o its atoms? probably yes! (low-pri bug) # (I don't know if extrude is documented to work for jigs, but it ought to, # but I'm sure there are several other things it's doing that also don't work in jigs.) [bruce 070412] ###k are these nodes renamed?? if not we'll have to do that now... assy = oldnodes[0].assy for newMol in newnodes: if newMol is not None: #bruce 070525 precaution from model.chunk import mol_copy_name newMol.name = mol_copy_name(newMol.name, assy) # this should work for any kind of node, unless it has an update bug for some of them, # but since the node doesn't yet have a dad, that's very unlikely. assy.addmol(newMol) # Note: this might not be the best location in assy, # but the caller can fix that. This might be easier # than fixing it here (if not, maybe we'll revise this). # (Maybe it's best to put this in the same DnaGroup # if there is one? Or, in the same Group except for # Groups with a controlled membership, like # DnaStrandOrSegment?) # REVIEW: it is necessary to add newMol to assy anywhere? # The method we override on class Chunk probably doesn't. # [bruce 080626] else: # can this ever happen? if so, we'll print way too much here... print "warning: extrude ignoring failed copy" ###k will we also need assy.update_parts()?? copies = newnodes return fake_copied_mol(copies, self) # self is needed for .center and for basecenters of originals (._mols), due to a kluge def full_inval_and_update(self): for mol in self._mols: mol.full_inval_and_update() assert mol.quat == Q(1,0,0,0) # KLUGE, but much here depends on this [bruce 070411] assert not (mol.center != mol.basecenter) # ditto [bruce 070411] # note: this "not !=" is how you have to compare Numeric arrays [bruce 070411] # note: this will fail if Chunk has user_specified_center (nim at the moment), # and Chunk.set_basecenter_and_quat may not be correct then anyway (not sure). # compute self.center as weighted average of component centers centers = [mol.center for mol in self._mols] weights = [mol.center_weight for mol in self._mols] self.center = weighted_average(weights, centers) return def contains_atom(self, atom): #bruce 070514, added to Node API 080305 """ [imitates Node API method] """ mol = atom.molecule assert mol.contains_atom(atom) # Note: this fact is not needed here, but this assert is the only test # of that implem of the new method contains_atom. It can be removed # once something else uses that method (or when we have a regression # test for it). return (mol in self._mols) pass # end of class fake_merged_mol # the methods/attrs we need to handle on the baseunit are: ##fake_merged_mol will delegate attr 'externs' + [needed to bust them so singlets have definite .info attr, preserved on copy] ##fake_merged_mol will delegate attr 'full_inval_and_update' + [needed to reset quats to 0, i think -- maybe since done by copy??] ##fake_merged_mol will delegate attr 'atoms' - not needed -- was in mark_singlets and another, both rewritten as loops ##fake_merged_mol will delegate attr 'get_dispdef' -- zapped the uses ##fake_merged_mol will delegate attr 'singlets' + [used in recompute_for_new_unit] ##fake_merged_mol will delegate attr 'center' - 1st mol ok ##fake_merged_mol will delegate attr 'quat' - 1st mol ok ##fake_merged_mol will delegate attr 'copy' + ##fake_merged_mol will delegate attr 'unpick' + ##fake_merged_mol will delegate attr 'changeapp' + ##fake_merged_mol will delegate attr 'draw' + def weighted_average(weights, centers): #bruce 070930 split this out #e refile? #e replace with preexisting implem? """ Centers and weights must be sequences of the same length; return the weighted average of centers using the given weights. The centers can be of any data type which works with sum(sequence) and has scalar * and /. The weights should be summable and convertable to floats. """ assert len(weights) == len(centers) >= 1 weighted_centers = [weights[i] * centers[i] for i in range(len(weights))] res = sum(weighted_centers) / float( sum(weights) ) # bug 2508 was evidently caused by effectively using sum(centers) here # instead of sum(weighted_centers) [bruce 070930] ## if len(weights) == 1: ## # sanity check [bruce 070928] ## # ideally we'd assert that the following values are very close: ## print "debug note re bug 2508: these points should be close: %r and %r" % (res , centers[0]) return res class fake_copied_mol( virtual_group_of_Chunks): #e rename? 'extrude_unit_copy_holder' """ private helper class for extrude, to serve as a "rep-unit" copy of a fake_merged_mol instance. Holds a list of copied mols (chunks) made by copying extrude's basemol when it's a fake_merged_mol, and (if desired) a Group made from them (for use in MT). @warning: our client extrudeMode will also do isinstance tests on this class, and peer into our private attrs like self._mols, so some of our semantics comes from client code that depends on our class. """ def __init__(self, copies, _a_fake_merged_mol): self._parent = _a_fake_merged_mol self._mols = copies # list of mol copies, made by an instance of fake_merged_mol, corresponding with its mols self._originals = _a_fake_merged_mol._mols # needed only in set_basecenter_and_quat (due to a kluge) assy = copies[0].assy ## self._group = Group('extruded', assy, None, copies) # not yet in MT; OBSOLETE except for delegation; # I worried that it might cause dad-conflict bugs in the members, but evidently it doesn't... # even so, safer to remove both this and __getattr__ (not only this, or __getattr__ infrecurs) return def set_basecenter_and_quat(self, c, q): std_basecenter = self._parent.center for mol, orig in zip(self._mols, self._originals): # Compute correct c for how our basemol differs from first one # (for explanation, see long comment in want_center_and_quat). # # Note: this is not ideal behavior for ring mode, in which q varies -- we should correct c for that, too, # but we don't [update, 070411: fixing that now], # which means we make several parallel rings (one per element of self._mols), # rather than one ring with a common center. To fix this, we'd correct c for q here, # and also compute an overall center in fake_merged_mol rather than just delegating it # to one of the components. c1 = c - std_basecenter # The caller's intent is to rotate self by q around its center, then shift self by c1, # all relative to self's starting point, as the caller recorded earlier (self.center and self.quat), # either on self or on its parent (from which self was copied, after full_inval_and_update). # Internally we do the same, except we correct for a different center of rotation. # # ... if we want self center to be *here*, where do we want component center to be? orig_offset = orig.center - std_basecenter net_offset = q.rot(orig_offset) - orig_offset c1 = c1 + net_offset mol.set_basecenter_and_quat(orig.basecenter + c1, q) return pass # end of class fake_copied_mol # end
NanoCAD-master
cad/src/commands/Extrude/extrudeMode.py
#Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ PartLibPropertyManager.py The PartLibPropertyManager class provides the Property Manager for the B{Partlib mode}. It lists the parts in the partlib and also shows the current selected part in its 'Preview' box. @author: Ninad @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-09-06 Created to support the Partlib mode. This could be a temporary implementation. See Note below. NOTE: In a future release, B{partlib} needs its own widget in the MainWindow like seen in popular cad softwares. (it probably shouldn't be in a Property manager). """ from commands.Paste.PastePropertyManager import PastePropertyManager from PM.PM_PartLib import PM_PartLib from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_PartLibPropertyManager class PartLibPropertyManager(PastePropertyManager): """ The PartLibPropertyManager class provides the Property Manager for the B{Partlib mode}. It lists the parts in the partlib and also shows the current selected part in its 'Preview' box. @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 """ # The title that appears in the Property Manager header title = "Part Library" # 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/Part_Library.png" def __init__(self, command): """ Constructor for the PartLibProperty Manager. @param command: The parent mode where this Property Manager is used @type command: L{PartLibPropertyManager} """ self.partLibGroupBox = None PastePropertyManager.__init__(self, command) self.updateMessage( """The part library contains structures and molecules that can be added to a project by selecting from the directory and double clicking in the 3D graphics area.""") def _update_UI_do_updates(self): """ @see: Command_PropertyManager._update_UI_do_updates() """ #This does nothing in this propMGr at present. return def _addGroupBoxes(self): """ Add various group boxes to this Property manager. """ self._addPreviewGroupBox() self._addPartLibGroupBox() def _addPartLibGroupBox(self): """ Add the part library groupbox to this property manager """ if not self.previewGroupBox: return elementViewer = self.previewGroupBox.elementViewer self.partLibGroupBox = PM_PartLib(self, win = self.command.w, elementViewer = elementViewer) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ self.partLibGroupBox.connect_or_disconnect_signals(isConnect) def getPastablePart(self): """ Returns the Pastable part and its hotspot (if any) @return: (L{Part}, L{Atom}) """ return self.partLibGroupBox.newModel, \ self.previewGroupBox.elementViewer.hotspotAtom def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ whatsThis_PartLibPropertyManager(self) return def _addToolTipText(self): """ Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_PartLibPropertyManager ToolTip_PartLibPropertyManager(self)
NanoCAD-master
cad/src/commands/PartLibrary/PartLibPropertyManager.py
NanoCAD-master
cad/src/commands/PartLibrary/__init__.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: TODO: """ import foundation.env as env from utilities.Log import orangemsg from commands.Paste.PasteFromClipboard_GraphicsMode import PasteFromClipboard_GraphicsMode class PartLibrary_GraphicsMode(PasteFromClipboard_GraphicsMode): def deposit_from_MMKit(self, atom_or_pos): """ Deposit the library part being previewed into the 3D workspace Calls L{self.deposit_from_Library_page} @param atom_or_pos: If user clicks on a bondpoint in 3D workspace, this is that bondpoint. NE1 will try to bond the part to this bondpoint, by Part's hotspot(if exists) If user double clicks on empty space, this gives the coordinates at that point. This data is then used to deposit the item. @type atom_or_pos: Array (vector) of coordinates or L{Atom} @return: (deposited_stuff, status_msg_text) Object deposited in the 3 D workspace. (Deposits the selected part as a 'Group'. The status message text tells whether the Part got deposited. @rtype: (L{Group} , str) @attention: This method needs renaming. L{BuildAtoms_Command} still uses it so simply overriden here. B{NEEDS CLEANUP}. @see: L{self.deposit_from_Library_page} """ deposited_stuff, status = self.command.deposit_from_Library_page(atom_or_pos) deposited_obj = 'Part' if deposited_stuff and self.pickit(): for d in deposited_stuff[:]: d.pickatoms() if deposited_stuff: self.w.win_update() status = self.ensure_visible( deposited_stuff, status) env.history.message(status) else: env.history.message(orangemsg(status)) return deposited_obj
NanoCAD-master
cad/src/commands/PartLibrary/PartLibrary_GraphicsMode.py
#Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ PartLibrary_Command.py Class PartLibrary_Command allows depositing parts from the partlib into the 3D workspace.Its property manager shows the current selected part in its 'Preview' box. The part can be deposited by doubleclicking on empty space in 3D workspace or if it has a hotspot, it can be deposited on a bondpoint of an existing model. User can return to previous mode by hitting 'Escape' key or pressing 'Done' button in the Part Library mode. @author: Bruce, Huaicai, Mark, Ninad @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: The Partlib existed as a tab in the MMKit of Build Atoms Command. (MMKit has been deprecated since 2007-08-29.) Now it has its own temporary mode. ninad 2007-09-06: Created. Split out some methods originally in depositMode.py to this file. """ import os from utilities.Log import greenmsg, quote_html, redmsg from model.chem import Atom from model.elements import Singlet from geometry.VQT import Q from operations.ops_copy import copied_nodes_for_DND from commands.Paste.PasteFromClipboard_Command import PasteFromClipboard_Command from commands.PartLibrary.PartLibPropertyManager import PartLibPropertyManager from ne1_ui.toolbars.Ui_PartLibraryFlyout import PartLibraryFlyout from commands.PartLibrary.PartLibrary_GraphicsMode import PartLibrary_GraphicsMode class PartLibrary_Command(PasteFromClipboard_Command): """ The PartLibrary_Command allows depositing parts from the partlib into the 3D workspace. Its property manager shows the current selected part in its 'Preview' box. The part can be deposited by doubleclicking on empty space in 3D workspace or if it has a hotspot, it can be deposited on a bondpoint of an existing model. User can return to previous mode by hitting 'Escape' key or pressing 'Done' button in this mode. """ commandName = 'PARTLIB' featurename = "Part Library" from utilities.constants import CL_EDIT_GENERIC command_level = CL_EDIT_GENERIC GraphicsMode_class = PartLibrary_GraphicsMode #Property Manager PM_class = PartLibPropertyManager #Flyout Toolbar FlyoutToolbar_class = PartLibraryFlyout def deposit_from_Library_page(self, atom_or_pos): """ Deposit a copy of the selected part from the Property Manager. @param atom_or_pos: If user clicks on a bondpoint in 3D workspace, this is that bondpoint. NE1 will try to bond the part to this bondpoint, by Part's hotspot(if exists) If user double clicks on empty space, this gives the coordinates at that point. This data is then used to deposit the item. @type atom_or_pos: Array (vector) of coordinates or L{Atom} @return: (deposited_stuff, status_msg_text) Object deposited in the 3 D workspace. (Deposits the selected part as a 'Group'. The status message text tells whether the Part got deposited. @rtype: (L{Group} , str) """ #Needs cleanup. Copying old code from deprecated 'depositMode.py' #-- ninad 2007-09-06 newPart, hotSpot = self.propMgr.getPastablePart() if not newPart: # Make sure a part is selected in the MMKit Library. # Whenever the MMKit is closed with the 'Library' page open, # MMKit.closeEvent() will change the current page to 'Atoms'. # This ensures that this condition never happens if the MMKit is # closed. # Mark 051213. return False, "No library part has been selected to paste." if isinstance(atom_or_pos, Atom): a = atom_or_pos if a.element is Singlet: if hotSpot : # bond the part to the singlet. return self._depositLibraryPart(newPart, hotSpot, a) else: # part doesn't have hotspot. #if newPart.has_singlets(): # need a method like this so we # can provide more descriptive msgs. # msg = "To bond this part, you must pick a hotspot by \ # left-clicking on a bondpoint of the library \ # part in the Modeling Kit's 3D thumbview." #else: # msg = "The library part cannot be bonded because it \ # has no bondpoints." msg = "The library part cannot be bonded because either " \ "it has no bondpoints"\ " or its hotspot hasn't been specified" return False, msg # nothing deposited else: # atom_or_pos was an atom, but wasn't a singlet. Do nothing. msg = "internal error: can't deposit onto a real atom %r" %a return False, msg else: # deposit into empty space at the cursor position #bruce 051227 note: looks like subr repeats these conds; #are they needed here? return self._depositLibraryPart(newPart, hotSpot, atom_or_pos) assert 0, "notreached" #Method _depositLibraryPart moved from deprecated depositMode.py to here #-- Ninad 2008-01-02 def _depositLibraryPart(self, newPart, hotspotAtom, atom_or_pos): # probably by Huaicai; revised by bruce 051227, 060627, 070501 """ This method serves as an overloaded method, <atom_or_pos> is the Singlet atom or the empty position that the new part <newPart> [which is an assy, at least sometimes] will be attached to or placed at. [If <atom_or_pos> is a singlet, <hotspotAtom> should be an atom in some chunk in <newPart>.] Currently, it doesn't consider group or jigs in the <newPart>. Not so sure if my attempt to copy a part into another assembly is all right. [It wasn't, so bruce 051227 revised it.] Copies all molecules in the <newPart>, change their assy attribute to current assembly, move them into <pos>. [bruce 051227 new feature:] return a list of new nodes created, and a message for history (currently almost a stub). [not sure if subrs ever print history messages... if they do we'd want to return those instead.] """ attach2Bond = False stuff = [] # list of deposited nodes [bruce 051227 new feature] if isinstance(atom_or_pos, Atom): attch2Singlet = atom_or_pos if hotspotAtom and hotspotAtom.is_singlet() and \ attch2Singlet .is_singlet(): newMol = hotspotAtom.molecule.copy_single_chunk(None) # [this can break interchunk bonds, # thus it still has bug 2028] newMol.set_assy(self.o.assy) hs = newMol.hotspot ha = hs.singlet_neighbor() # hotspot neighbor atom attch2Atom = attch2Singlet.singlet_neighbor() # attach to atom rotCenter = newMol.center rotOffset = Q(ha.posn()-hs.posn(), attch2Singlet.posn()-attch2Atom.posn()) newMol.rot(rotOffset) moveOffset = attch2Singlet.posn() - hs.posn() newMol.move(moveOffset) self.graphicsMode._createBond(hs, ha, attch2Singlet, attch2Atom) self.o.assy.addmol(newMol) stuff.append(newMol) #e if there are other chunks in <newPart>, #they are apparently copied below. [bruce 060627 comment] else: ## something is wrong, do nothing return stuff, "internal error" attach2Bond = True else: placedPos = atom_or_pos if hotspotAtom: hotspotAtomPos = hotspotAtom.posn() moveOffset = placedPos - hotspotAtomPos else: if newPart.molecules: moveOffset = placedPos - newPart.molecules[0].center #e not #the best choice of center [bruce 060627 comment] if attach2Bond: # Connect part to a bondpoint of an existing chunk for m in newPart.molecules: if not m is hotspotAtom.molecule: newMol = m.copy_single_chunk(None) # [this can break interchunk bonds, # thus it still has bug 2028] newMol.set_assy(self.o.assy) ## Get each of all other chunks' center movement for the ## rotation around 'rotCenter' coff = rotOffset.rot(newMol.center - rotCenter) coff = rotCenter - newMol.center + coff # The order of the following 2 statements doesn't matter newMol.rot(rotOffset) newMol.move(moveOffset + coff) self.o.assy.addmol(newMol) stuff.append(newMol) else: # Behaves like dropping a part anywhere you specify, independent #of existing chunks. # copy all nodes in newPart (except those in clipboard items), # regardless of node classes; # put it in a new Group if more than one thing [bruce 070501] # [TODO: this should be done in the cases above, too, but that's # not yet implemented, # and requires adding rot or pivot to the Node API and revising # the rot-calling code above, # and also reviewing the definition of the "hotspot of a Part" and # maybe of a "depositable clipboard item".] assert newPart.tree.is_group() nodes = list(newPart.tree.members) # might be [] assy = self.o.assy newnodes = copied_nodes_for_DND(nodes, autogroup_at_top = True, assy = assy) # Note: that calls name_autogrouped_nodes_for_clipboard # internally, if it forms a Group, # but we ignore that and rename the new node differently below, # whether or not it was autogrouped. We could just as well do # the autogrouping ourselves... # Note [bruce 070525]: it's better to call copied_nodes_for_DND # here than copy_nodes_in_order, even if we didn't need to # autogroup. One reason is that if some node is not copied, # that's not necessarily an error, since we don't care about 1-1 # orig-copy correspondence here. if not newnodes: if newnodes is None: print "bug: newnodes should not be None; nodes was %r (saved in debug._bugnodes)" % (nodes,) # TODO: This might be possible, for arbitrary partlib # contents, just not for legitimate ones... # but partlib will probably be (or is) user-expandable, #so we should turn this into history message, # not a bug print. But I'm not positive it's possible #w/o a bug, so review first. ###FIX [bruce 070501 comment] import utilities.debug as debug debug._bugnodes = nodes newnodes = [] msg = redmsg( "error: nothing to deposit in [%s]" % quote_html(str(newPart.name)) ) return [], msg assert len(newnodes) == 1 # due to autogroup_at_top = True # but the remaining code works fine regardless of len(newnodes), #in case we make autogroup a preference for newnode in newnodes: # Rename newnode based on the partlib name and a unique number. # It seems best to let the partlib mmp file contents (not just # filename) # control the name used here, so use newPart.tree.name rather # than just newPart.name. # (newPart.name is a complete file pathname; newPart.tree.name #is usually its basename w/o extension.) basename = str(newPart.tree.name) if basename == 'Untitled': # kluge, for the sake of 3 current partlib files, and files #saved only once by users (due to NE1 bug in save) dirjunk, base = os.path.split(newPart.name) basename, extjunk = os.path.splitext(base) from utilities.constants import gensym newnode.name = gensym( basename, assy) # name library part #bruce 080407 basename + " " --> basename, and pass assy # (per Mark NFR desire) #based on basename recorded in its mmp file's top node newnode.move(moveOffset) #k not sure this method is correctly #implemented for measurement jigs, named views assy.addnode(newnode) stuff.append(newnode) ## #bruce 060627 new code: fix bug 2028 (non-hotspot case only) ## # about interchunk bonds being broken ## nodes = newPart.molecules ## newnodes = copied_nodes_for_DND(nodes) ## if newnodes is None: ## print "bug: newnodes should not be None; nodes was %r (saved in debug._bugnodes)" % (nodes,) ## debug._bugnodes = nodes ## newnodes = [] # kluge ## for newMol in newnodes: ## # some of the following probably only work for Chunks, ## # though coding them for other nodes would not be hard ## newMol.set_assy(self.o.assy) ## newMol.move(moveOffset) ## self.o.assy.addmol(newMol) ## stuff.append(newMol) self.o.assy.update_parts() #bruce 051227 see if this fixes the #atom_debug exception in checkparts msg = greenmsg("Deposited library part: ") + " [" + \ quote_html(str(newPart.name)) + "]" #ninad060924 fix bug 1164 return stuff, msg ####@@@@ should revise this message ##(stub is by bruce 051227)
NanoCAD-master
cad/src/commands/PartLibrary/PartLibrary_Command.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ LinearMotor_EditCommand.py @author: Ninad @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. @version: $Id$ History: ninad 2007-10-09: Created. """ import foundation.env as env from utilities.Log import redmsg, greenmsg, orangemsg from model.jigs_motors import LinearMotor from operations.jigmakers_Mixin import atom_limit_exceeded_and_confirmed from command_support.Motor_EditCommand import Motor_EditCommand from commands.LinearMotorProperties.LinearMotorPropertyManager import LinearMotorPropertyManager class LinearMotor_EditCommand(Motor_EditCommand): """ The LinearMotor_EditCommand class provides an editCommand Object. The editCommand, depending on what client code needs it to do, may create a new linear motor or it may be used for an existing linear motor. """ PM_class = LinearMotorPropertyManager cmd = greenmsg("Linear Motor: ") commandName = 'LINEAR_MOTOR' featurename = "Linear Motor" def _gatherParameters(self): """ Return all the parameters from the Plane Property Manager. """ force = self.propMgr.forceDblSpinBox.value() stiffness = self.propMgr.stiffnessDblSpinBox.value() enable_minimize_state = self.propMgr.enableMinimizeCheckBox.isChecked() color = self.struct.color atoms = self.win.assy.selatoms_list() return (force, stiffness, enable_minimize_state, color, atoms) def _getStructureType(self): """ Subclasses override this method to define their own structure type. Returns the type of the structure this editCommand supports. This is used in isinstance test. @see: EditCommand._getStructureType() (overridden here) """ return LinearMotor def _createStructure(self): """ Create a Plane object. (The model object which this edit controller creates) """ assert not self.struct atoms = self.win.assy.selatoms_list() atomNumberRequirementMet, logMessage = \ self._checkMotorAtomLimits(len(atoms)) if atomNumberRequirementMet: self.win.assy.part.ensure_toplevel_group() motor = LinearMotor(self.win.assy) motor.findCenterAndAxis(atoms, self.win.glpane) self.win.assy.place_new_jig(motor) else: motor = None env.history.message(redmsg(logMessage)) return motor def _modifyStructure(self, params): """ Modifies the structure (Plane) using the provided params. @param params: The parameters used as an input to modify the structure (Plane created using this Plane_EditCommand) @type params: tuple """ assert self.struct assert params assert len(params) == 5 force, stiffness, enable_minimize_state, \ color, atoms = params numberOfAtoms = len(atoms) atomNumberRequirementMet, logMessage = \ self._checkMotorAtomLimits(numberOfAtoms) if not atomNumberRequirementMet: atoms = self.struct.atoms[:] logMessage = logMessage + " Motor will remain attached to the"\ " atoms listed in the <b>Attached Atoms</b> list in"\ " this property manager" logMessage = orangemsg(logMessage) self.propMgr.updateMessage(logMessage) assert len(atoms) > 0 self.struct.cancelled = False self.struct.force = force self.struct.stiffness = stiffness self.struct.enable_minimize = enable_minimize_state self.struct.color = color #Not sure if it is safe to do self.struct.atoms = atoms #Instead using 'setShaft method -- ninad 2007-10-09 self.struct.setShaft(atoms) self.struct.findCenterAndAxis(atoms, self.win.glpane) self.propMgr.updateAttachedAtomListWidget(atomList = atoms) self.win.win_update() # Update model tree self.win.assy.changed() ##=====================================## def _checkMotorAtomLimits(self, numberOfAtoms): """ """ logMessage = "" isAtomRequirementMet = True if numberOfAtoms == 0: logMessage = "No Atoms selected to create a Linear Motor. " isAtomRequirementMet = False return (isAtomRequirementMet, logMessage) if numberOfAtoms >= 2 and numberOfAtoms < 200: isAtomRequirementMet = True logMessage = "" return (isAtomRequirementMet, logMessage) # Print warning if over 200 atoms are selected. # The warning should be displayed in a MessageGroupBox. Mark 2007-05-28 if numberOfAtoms > 200: if not atom_limit_exceeded_and_confirmed(self.win, numberOfAtoms, limit = 200): logMessage = "Warning: Motor is attached to more than 200 "\ "atoms. This may result in a performance degradation" isAtomRequirementMet = True else: logMessage = "%s creation cancelled" % (self.cmdname) isAtomRequirementMet = False return (isAtomRequirementMet, logMessage) return (isAtomRequirementMet, logMessage)
NanoCAD-master
cad/src/commands/LinearMotorProperties/LinearMotor_EditCommand.py
NanoCAD-master
cad/src/commands/LinearMotorProperties/__init__.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ LinearMotorPropertyManager.py @author: Ninad @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-10-11: Created, deprecating the LinearMototorPropDialog.py """ from PyQt4.Qt import SIGNAL from PM.PM_GroupBox import PM_GroupBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_CheckBox import PM_CheckBox from PM.PM_PushButton import PM_PushButton from PM.PM_ColorComboBox import PM_ColorComboBox from command_support.MotorPropertyManager import MotorPropertyManager from utilities.constants import gray class LinearMotorPropertyManager(MotorPropertyManager): """ The LinearMotorProperty manager class provides UI and propMgr object for the LinearMotor_EditCommand. """ # The title that appears in the Property Manager header. title = "Linear Motor" # 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/Simulation/LinearMotor.png" 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 MotorPropertyManager.connect_or_disconnect_signals(self, isConnect) change_connect(self.directionPushButton, SIGNAL("clicked()"), self.reverse_direction) change_connect(self.motorLengthDblSpinBox, SIGNAL("valueChanged(double)"), self.change_motor_size) change_connect(self.motorWidthDblSpinBox, SIGNAL("valueChanged(double)"), self.change_motor_size) change_connect(self.spokeRadiusDblSpinBox, SIGNAL("valueChanged(double)"), self.change_motor_size) change_connect(self.motorColorComboBox, SIGNAL("editingFinished()"), self.change_jig_color) return 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. """ if self.command and self.command.struct: force = self.command.struct.force stiffness = self.command.struct.stiffness enable_minimize = self.command.struct.enable_minimize length = self.command.struct.length width = self.command.struct.width spoke_radius = self.command.struct.sradius normcolor = self.command.struct.normcolor else: force = 0.0 stiffness = 0.0 enable_minimize = False length = 10 width = 1 spoke_radius = 0.2 normcolor = gray self.forceDblSpinBox.setValue(force) self.stiffnessDblSpinBox.setValue(stiffness) self.enableMinimizeCheckBox.setChecked(enable_minimize) self.motorLengthDblSpinBox.setValue(length) self.motorWidthDblSpinBox.setValue(width) self.spokeRadiusDblSpinBox.setValue(spoke_radius) return def change_motor_size(self, gl_update=True): """ Slot method to change the jig's length, width and/or spoke radius. """ self.command.struct.length = self.motorLengthDblSpinBox.value() self.command.struct.width = self.motorWidthDblSpinBox.value() # spoke radius -- self.command.struct.sradius = self.spokeRadiusDblSpinBox.value() if gl_update: self.glpane.gl_update() return def _loadGroupBox1(self, pmGroupBox): """ Load widgets in MotorParamsGroupBox. """ if self.command and self.command.struct: force = self.command.struct.force stiffness = self.command.struct.stiffness enable_minimize = self.command.struct.enable_minimize else: force = 0.0 stiffness = 0.0 enable_minimize = False self.forceDblSpinBox = \ PM_DoubleSpinBox(pmGroupBox, label = "Force:", value = force, setAsDefault = True, minimum = 0.0, maximum = 5000.0, singleStep = 1.0, decimals = 1, suffix =' pN') self.stiffnessDblSpinBox = \ PM_DoubleSpinBox(pmGroupBox, label = "Stiffness:", value = stiffness, setAsDefault = True, minimum = 0.0, maximum = 1000.0, singleStep = 1.0, decimals = 1, suffix =' N/m') self.enableMinimizeCheckBox = \ PM_CheckBox(pmGroupBox, text ="Enable in minimize", widgetColumn = 1 ) self.enableMinimizeCheckBox.setChecked(enable_minimize) self.directionPushButton = \ PM_PushButton(pmGroupBox, label = "Direction :", text = "Reverse", spanWidth = False) return def _loadGroupBox2(self, pmGroupBox): """ Load widgets in groubox 2. """ if self.command and self.command.struct: length = self.command.struct.length width = self.command.struct.width spoke_radius = self.command.struct.sradius normcolor = self.command.struct.normcolor else: length = 10 width = 1 spoke_radius = 0.2 normcolor = gray self.motorLengthDblSpinBox = \ PM_DoubleSpinBox(pmGroupBox, label = "Motor length :", value = length, setAsDefault = True, minimum = 0.5, maximum = 500.0, singleStep = 0.5, decimals = 1, suffix = ' Angstroms') self.motorWidthDblSpinBox = \ PM_DoubleSpinBox(pmGroupBox, label="Motor width :", value = width, setAsDefault = True, minimum = 0.1, maximum = 50.0, singleStep = 0.1, decimals = 1, suffix = ' Angstroms') self.spokeRadiusDblSpinBox = \ PM_DoubleSpinBox(pmGroupBox, label = "Spoke radius :", value = spoke_radius, setAsDefault = True, minimum = 0.1, maximum = 50.0, singleStep = 0.1, decimals = 1, suffix = ' Angstroms') self.motorColorComboBox = \ PM_ColorComboBox(pmGroupBox, color = normcolor) return def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_LinearMotorPropertyManager whatsThis_LinearMotorPropertyManager(self) return def _addToolTipText(self): """ What's Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_LinearMotorPropertyManager ToolTip_LinearMotorPropertyManager(self) return
NanoCAD-master
cad/src/commands/LinearMotorProperties/LinearMotorPropertyManager.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ RotaryMotorPropertyManager.py @author: Mark @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. History: Mark 2007-05-28: Created as RotaryMotorGeneratorDialog.py Ninad 2007-10-09: - Deprecated RotaryMotorGeneratorDialog class - Created RotaryMotorPropertyManager class to match the EditCommand API. (and related changes) """ from PyQt4.Qt import SIGNAL from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_CheckBox import PM_CheckBox from PM.PM_PushButton import PM_PushButton from PM.PM_ColorComboBox import PM_ColorComboBox from utilities.constants import gray from command_support.MotorPropertyManager import MotorPropertyManager class RotaryMotorPropertyManager(MotorPropertyManager): """ The RotaryMotorProperty manager class provides UI and propMgr object for the RotaryMotor_EditCommand. """ # The title that appears in the Property Manager header. title = "Rotary Motor" # 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/Simulation/RotaryMotor.png" 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 MotorPropertyManager.connect_or_disconnect_signals(self, isConnect) change_connect(self.directionPushButton, SIGNAL("clicked()"), self.reverse_direction) change_connect(self.motorLengthDblSpinBox, SIGNAL("valueChanged(double)"), self.change_motor_size) change_connect(self.motorRadiusDblSpinBox, SIGNAL("valueChanged(double)"), self.change_motor_size) change_connect(self.spokeRadiusDblSpinBox, SIGNAL("valueChanged(double)"), self.change_motor_size) change_connect(self.motorColorComboBox, SIGNAL("editingFinished()"), self.change_jig_color) return 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. """ if self.command and self.command.struct: torque = self.command.struct.torque initial_speed = self.command.struct.initial_speed final_speed = self.command.struct.speed dampers_enabled = self.command.struct.dampers_enabled enable_minimize = self.command.struct.enable_minimize length = self.command.struct.length radius = self.command.struct.radius spoke_radius = self.command.struct.sradius normcolor = self.command.struct.normcolor else: torque = 0.0 initial_speed = 0.0 final_speed = 0.0 dampers_enabled = False enable_minimize = False length = 10.0 radius = 1.0 spoke_radius = 0.2 normcolor = gray self.torqueDblSpinBox.setValue(torque) self.initialSpeedDblSpinBox.setValue(initial_speed) self.finalSpeedDblSpinBox.setValue(final_speed) self.dampersCheckBox.setChecked(dampers_enabled) self.enableMinimizeCheckBox.setChecked(enable_minimize) self.motorLengthDblSpinBox.setValue(length) self.motorRadiusDblSpinBox.setValue(radius) self.spokeRadiusDblSpinBox.setValue(spoke_radius) return def change_motor_size(self, gl_update = True): """ Slot method to change the jig's length, radius and/or spoke radius. """ if self.command and self.command.struct: self.command.struct.length = \ self.motorLengthDblSpinBox.value()# motor length self.command.struct.radius = \ self.motorRadiusDblSpinBox.value() # motor radius self.command.struct.sradius = \ self.spokeRadiusDblSpinBox.value() # spoke radius if gl_update: self.glpane.gl_update() return def _loadGroupBox1(self, pmGroupBox): """ Load widgets in MotorParamsGroupBox. """ if self.command and self.command.struct: torque = self.command.struct.torque initial_speed = self.command.struct.initial_speed final_speed = self.command.struct.speed dampers_enabled = self.command.struct.dampers_enabled enable_minimize = self.command.struct.enable_minimize else: torque = 0.0 initial_speed = 0.0 final_speed = 0.0 dampers_enabled = False enable_minimize = False self.torqueDblSpinBox = \ PM_DoubleSpinBox(pmGroupBox, label = "Torque :", value = torque, setAsDefault = True, minimum = 0.0, maximum = 1000.0, singleStep = 1.0, decimals = 1, suffix =' nN-nm') self.initialSpeedDblSpinBox = \ PM_DoubleSpinBox(pmGroupBox, label = "Initial speed :", value = initial_speed, setAsDefault = True, minimum = 0.0, maximum = 100.0, singleStep = 1.0, decimals = 1, suffix = ' GHz') self.finalSpeedDblSpinBox = \ PM_DoubleSpinBox(pmGroupBox, label = "Final speed :", value = final_speed, setAsDefault = True, minimum = 0.0, maximum = 100.0, singleStep = 1.0, decimals = 1, suffix = ' GHz') self.dampersCheckBox = \ PM_CheckBox(pmGroupBox, text = "Dampers", widgetColumn = 0 ) self.dampersCheckBox.setChecked(dampers_enabled) self.enableMinimizeCheckBox = \ PM_CheckBox(pmGroupBox, text = "Enable in minimize", widgetColumn = 0 ) self.enableMinimizeCheckBox.setChecked(enable_minimize) self.directionPushButton = \ PM_PushButton(pmGroupBox, label = "Direction :", text = "Reverse", spanWidth = False) return def _loadGroupBox2(self, pmGroupBox): """ Load widgets in groubox 2. """ if self.command and self.command.struct: length = self.command.struct.length radius = self.command.struct.radius spoke_radius = self.command.struct.sradius normcolor = self.command.struct.normcolor else: length = 10 radius = 1 spoke_radius = 0.2 normcolor = gray self.motorLengthDblSpinBox = \ PM_DoubleSpinBox(pmGroupBox, label = "Motor length :", value = length, setAsDefault = True, minimum = 0.5, maximum = 500.0, singleStep = 0.5, decimals = 1, suffix = ' Angstroms') self.motorRadiusDblSpinBox = \ PM_DoubleSpinBox(pmGroupBox, label="Motor radius :", value = radius, setAsDefault = True, minimum = 0.1, maximum = 50.0, singleStep = 0.1, decimals = 1, suffix = ' Angstroms') self.spokeRadiusDblSpinBox = \ PM_DoubleSpinBox(pmGroupBox, label = "Spoke radius :", value = spoke_radius, setAsDefault = True, minimum = 0.1, maximum = 50.0, singleStep = 0.1, decimals = 1, suffix = ' Angstroms') self.motorColorComboBox = \ PM_ColorComboBox(pmGroupBox, color = normcolor) return def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_RotaryMotorPropertyManager whatsThis_RotaryMotorPropertyManager(self) return def _addToolTipText(self): """ What's Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_RotaryMotorPropertyManager ToolTip_RotaryMotorPropertyManager(self) return
NanoCAD-master
cad/src/commands/RotaryMotorProperties/RotaryMotorPropertyManager.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ RotaryMotor_EditCommand.py @author: Ninad @copyright: 2007 Nanorex, Inc. See LICENSE file for details. @version: $Id$ History: ninad 2007-10-09: Created. This deprecates 'RotoryMotorGenerator' """ import foundation.env as env from utilities.Log import redmsg, greenmsg, orangemsg from model.jigs_motors import RotaryMotor from operations.jigmakers_Mixin import atom_limit_exceeded_and_confirmed from command_support.Motor_EditCommand import Motor_EditCommand from commands.RotaryMotorProperties.RotaryMotorPropertyManager import RotaryMotorPropertyManager class RotaryMotor_EditCommand(Motor_EditCommand): """ The RotaryMotor_EditCommand class provides an editCommand Object. The editCommand, depending on what client code needs it to do, may create a new rotary motor or it may be used for an existing rotary motor. """ #Property Manager PM_class = RotaryMotorPropertyManager cmd = greenmsg("Rotary Motor: ") commandName = 'ROTARY_MOTOR' featurename = "Rotary Motor" def _gatherParameters(self): """ Return all the parameters from the Rotary Motor Property Manager. """ torque = self.propMgr.torqueDblSpinBox.value() initial_speed = self.propMgr.initialSpeedDblSpinBox.value() final_speed = self.propMgr.finalSpeedDblSpinBox.value() dampers_state = self.propMgr.dampersCheckBox.isChecked() enable_minimize_state = self.propMgr.enableMinimizeCheckBox.isChecked() color = self.struct.color atoms = self.win.assy.selatoms_list() return (torque, initial_speed, final_speed, dampers_state, enable_minimize_state, color, atoms) def _getStructureType(self): """ Subclasses override this method to define their own structure type. Returns the type of the structure this editCommand supports. This is used in isinstance test. @see: EditCommand._getStructureType() (overridden here) """ return RotaryMotor def _createStructure(self): """ Create a Rotary Motor object. (The model object which this edit controller creates) """ assert not self.struct atoms = self.win.assy.selatoms_list() atomNumberRequirementMet, logMessage = \ self._checkMotorAtomLimits(len(atoms)) if atomNumberRequirementMet: self.win.assy.part.ensure_toplevel_group() motor = RotaryMotor(self.win.assy) motor.findCenterAndAxis(atoms, self.win.glpane) self.win.assy.place_new_jig(motor) else: motor = None env.history.message(redmsg(logMessage)) return motor def _modifyStructure(self, params): """ Modifies the structure (Rotary Motor) using the provided params. @param params: The parameters used as an input to modify the structure (Rotary Motor created using this RotaryMotor_EditCommand) @type params: tuple """ assert self.struct assert params assert len(params) == 7 torque, initial_speed, final_speed, \ dampers_state, enable_minimize_state, \ color, atoms = params numberOfAtoms = len(atoms) atomNumberRequirementMet, logMessage = \ self._checkMotorAtomLimits(numberOfAtoms) if not atomNumberRequirementMet: atoms = self.struct.atoms[:] logMessage = logMessage + " Motor will remain attached to the"\ " atoms listed in the 'Motor Atoms' list in this" \ " property manager" logMessage = orangemsg(logMessage) self.propMgr.updateMessage(logMessage) assert len(atoms) > 0 self.struct.cancelled = False self.struct.torque = torque self.struct.initial_speed = initial_speed self.struct.speed = final_speed self.struct.dampers_enabled = dampers_state self.struct.enable_minimize = enable_minimize_state self.struct.color = color #Not sure if it is safe to do self.struct.atoms = atoms #Instead using 'setShaft method -- ninad 2007-10-09 self.struct.setShaft(atoms) self.struct.findCenterAndAxis(atoms, self.win.glpane) self.propMgr.updateAttachedAtomListWidget(atomList = atoms) self.win.win_update() # Update model tree self.win.assy.changed() ##=====================================## def _checkMotorAtomLimits(self, numberOfAtoms): """ Check if the number of atoms selected by the user, to which the motor is to be attached, is within acceptable limits. @param numberOfAtoms: Number of atoms selected by the user, to which the motor needs to be attached. @type numberOfAtoms: int """ logMessage = "" isAtomRequirementMet = False if numberOfAtoms == 0: logMessage = "No Atoms selected to create a Rotary Motor." isAtomRequirementMet = False return (isAtomRequirementMet, logMessage) # wware 051216, bug 1114, need >= 2 atoms for rotary motor if numberOfAtoms < 2: msg = redmsg("You must select at least two atoms to create"\ " a Rotary Motor.") logMessage = msg isAtomRequirementMet = False return (isAtomRequirementMet, logMessage) if numberOfAtoms >= 2 and numberOfAtoms < 200: isAtomRequirementMet = True logMessage = "" return (isAtomRequirementMet, logMessage) # Print warning if over 200 atoms are selected. # The warning should be displayed in a MessageGroupBox. Mark 2007-05-28 if numberOfAtoms > 200: if not atom_limit_exceeded_and_confirmed(self.win, numberOfAtoms, limit = 200): logMessage = "Warning: Motor is attached to more than 200 "\ "atoms. This may result in a performance degradation" isAtomRequirementMet = True else: logMessage = "%s creation cancelled" % (self.cmdname) isAtomRequirementMet = False return (isAtomRequirementMet, logMessage)
NanoCAD-master
cad/src/commands/RotaryMotorProperties/RotaryMotor_EditCommand.py
NanoCAD-master
cad/src/commands/RotaryMotorProperties/__init__.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GridPlaneProp.py $Id$ """ from PyQt4.Qt import QDialog from PyQt4.Qt import QWidget from PyQt4.Qt import SIGNAL from PyQt4.Qt import QColorDialog from commands.GridPlaneProperties.GridPlanePropDialog import Ui_GridPlanePropDialog from widgets.widget_helpers import RGBf_to_QColor, QColor_to_RGBf, get_widget_with_color_palette class GridPlaneProp(QDialog, Ui_GridPlanePropDialog): def __init__(self, gridPlane, glpane): QWidget.__init__(self) self.setupUi(self) self.connect(self.ok_btn,SIGNAL("clicked()"),self.accept) self.connect(self.cancel_btn,SIGNAL("clicked()"),self.reject) self.connect(self.choose_border_color_btn,SIGNAL("clicked()"),self.change_border_color) self.connect(self.choose_grid_color_btn,SIGNAL("clicked()"),self.change_grid_color) self.connect(self.width_spinbox,SIGNAL("valueChanged(int)"),self.change_width) self.connect(self.height_spinbox,SIGNAL("valueChanged(int)"),self.change_height) self.connect(self.x_spacing_spinbox,SIGNAL("valueChanged(int)"),self.change_x_spacing) self.connect(self.y_spacing_spinbox,SIGNAL("valueChanged(int)"),self.change_y_spacing) self.connect(self.grid_type_combox,SIGNAL("activated(int)"),self.change_grid_type) self.connect(self.line_type_combox,SIGNAL("activated(int)"),self.change_line_type) self.grid_plane = gridPlane self.glpane = glpane def setup(self): self.jig_attrs = self.grid_plane.copyable_attrs_dict() # Save the jig's attributes in case of Cancel. # Border color self.border_color = RGBf_to_QColor(self.grid_plane.normcolor) # Used as default color by Color Chooser # Grid color self.grid_color = RGBf_to_QColor(self.grid_plane.grid_color) # Used as default color by Color Chooser self.grid_color_pixmap = get_widget_with_color_palette( self.grid_color_pixmap, self.grid_color) self.border_color_pixmap = get_widget_with_color_palette( self.border_color_pixmap,self.border_color) self.name_linedit.setText(self.grid_plane.name) self.width_spinbox.setValue(self.grid_plane.width) self.height_spinbox.setValue(self.grid_plane.height) self.x_spacing_spinbox.setValue(self.grid_plane.x_spacing) self.y_spacing_spinbox.setValue(self.grid_plane.y_spacing) self.grid_type_combox.setCurrentIndex(self.grid_plane.grid_type) self.line_type_combox.setCurrentIndex(self.grid_plane.line_type) self._set_xyspacing_enabled(self.grid_plane.grid_type) def _set_xyspacing_enabled(self, grid_type): """ If <grid_type> == 1, which is SiC type, disable x, y spacing comboBox, otherwise, enable it. """ from utilities.prefs_constants import SiC_GRID, SQUARE_GRID if grid_type == SiC_GRID: self.x_spacing_spinbox.setEnabled(False) self.y_spacing_spinbox.setEnabled(False) else: self.x_spacing_spinbox.setEnabled(True) self.y_spacing_spinbox.setEnabled(True) def change_grid_type(self, grid_type): """ Slot method to change grid type """ self.grid_plane.grid_type = grid_type self._set_xyspacing_enabled(grid_type) self.glpane.gl_update() def change_line_type(self, line_type): """ Slot method to change grid line type """ self.grid_plane.line_type = line_type self.glpane.gl_update() def change_grid_color(self): """ Slot method to change grid color. """ color = QColorDialog.getColor(self.grid_color, self) if color.isValid(): self.grid_color = color self.grid_color_pixmap = get_widget_with_color_palette( self.grid_color_pixmap, self.grid_color) self.grid_plane.grid_color = QColor_to_RGBf(color) self.glpane.gl_update() def change_border_color(self): """ Slot method change border color. """ color = QColorDialog.getColor(self.border_color, self) if color.isValid(): self.border_color = color self.border_color_pixmap = get_widget_with_color_palette( self.border_color_pixmap,self.border_color) self.grid_plane.color = self.grid_plane.normcolor = QColor_to_RGBf(color) self.glpane.gl_update() def change_width(self, newWidth): """ Slot for Width spinbox """ self.grid_plane.width = float(newWidth) self.glpane.gl_update() def change_height(self, newHeight): """ Slot for Height spinbox """ self.grid_plane.height = float(newHeight) self.glpane.gl_update() def change_x_spacing(self, newXValue): """ Slot for X Spacing spinbox """ self.grid_plane.x_spacing = float(newXValue) self.glpane.gl_update() def change_y_spacing(self, newYValue): """ Slot for Y Spacing spinbox """ self.grid_plane.y_spacing = float(newYValue) self.glpane.gl_update() def accept(self): """ Slot for the 'OK' button """ self.grid_plane.cancelled = False self.grid_plane.try_rename(self.name_linedit.text()) self.grid_plane.width = float(self.width_spinbox.value()) self.grid_plane.height = float(self.height_spinbox.value()) self.grid_plane.x_spacing = float(self.x_spacing_spinbox.value()) self.grid_plane.y_spacing = float(self.y_spacing_spinbox.value()) self.grid_plane.assy.w.win_update() # Update model tree self.grid_plane.assy.changed() QDialog.accept(self) def reject(self): """ Slot for the 'Cancel' button """ self.grid_plane.attr_update(self.jig_attrs) # Restore attributes of the jig. self.glpane.gl_update() QDialog.reject(self)
NanoCAD-master
cad/src/commands/GridPlaneProperties/GridPlaneProp.py
NanoCAD-master
cad/src/commands/GridPlaneProperties/__init__.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'GridPlanePropDialog.ui' # # Created: Tue Feb 12 00:08:03 2008 # by: PyQt4 UI code generator 4.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_GridPlanePropDialog(object): def setupUi(self, GridPlanePropDialog): GridPlanePropDialog.setObjectName("GridPlanePropDialog") GridPlanePropDialog.resize(QtCore.QSize(QtCore.QRect(0,0,265,374).size()).expandedTo(GridPlanePropDialog.minimumSizeHint())) self.gridlayout = QtGui.QGridLayout(GridPlanePropDialog) self.gridlayout.setMargin(11) self.gridlayout.setSpacing(6) self.gridlayout.setObjectName("gridlayout") spacerItem = QtGui.QSpacerItem(101,16,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.MinimumExpanding) self.gridlayout.addItem(spacerItem,1,0,1,1) self.hboxlayout = QtGui.QHBoxLayout() self.hboxlayout.setMargin(0) self.hboxlayout.setSpacing(6) self.hboxlayout.setObjectName("hboxlayout") spacerItem1 = QtGui.QSpacerItem(92,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout.addItem(spacerItem1) self.ok_btn = QtGui.QPushButton(GridPlanePropDialog) self.ok_btn.setMinimumSize(QtCore.QSize(0,30)) self.ok_btn.setAutoDefault(False) self.ok_btn.setDefault(False) self.ok_btn.setObjectName("ok_btn") self.hboxlayout.addWidget(self.ok_btn) self.cancel_btn = QtGui.QPushButton(GridPlanePropDialog) self.cancel_btn.setMinimumSize(QtCore.QSize(0,30)) self.cancel_btn.setAutoDefault(False) self.cancel_btn.setObjectName("cancel_btn") self.hboxlayout.addWidget(self.cancel_btn) self.gridlayout.addLayout(self.hboxlayout,2,0,1,1) self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setMargin(0) self.hboxlayout1.setSpacing(6) self.hboxlayout1.setObjectName("hboxlayout1") self.vboxlayout = QtGui.QVBoxLayout() self.vboxlayout.setMargin(0) self.vboxlayout.setSpacing(6) self.vboxlayout.setObjectName("vboxlayout") self.textLabel1_4 = QtGui.QLabel(GridPlanePropDialog) self.textLabel1_4.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.textLabel1_4.setObjectName("textLabel1_4") self.vboxlayout.addWidget(self.textLabel1_4) self.textLabel1_5 = QtGui.QLabel(GridPlanePropDialog) self.textLabel1_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.textLabel1_5.setObjectName("textLabel1_5") self.vboxlayout.addWidget(self.textLabel1_5) self.textLabel1_5_2 = QtGui.QLabel(GridPlanePropDialog) self.textLabel1_5_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.textLabel1_5_2.setObjectName("textLabel1_5_2") self.vboxlayout.addWidget(self.textLabel1_5_2) self.colorTextLabel_3 = QtGui.QLabel(GridPlanePropDialog) self.colorTextLabel_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.colorTextLabel_3.setObjectName("colorTextLabel_3") self.vboxlayout.addWidget(self.colorTextLabel_3) self.colorTextLabel_4 = QtGui.QLabel(GridPlanePropDialog) self.colorTextLabel_4.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.colorTextLabel_4.setObjectName("colorTextLabel_4") self.vboxlayout.addWidget(self.colorTextLabel_4) self.textLabel1 = QtGui.QLabel(GridPlanePropDialog) self.textLabel1.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.textLabel1.setObjectName("textLabel1") self.vboxlayout.addWidget(self.textLabel1) self.textLabel1_3 = QtGui.QLabel(GridPlanePropDialog) self.textLabel1_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.textLabel1_3.setObjectName("textLabel1_3") self.vboxlayout.addWidget(self.textLabel1_3) self.textLabel2_3 = QtGui.QLabel(GridPlanePropDialog) self.textLabel2_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.textLabel2_3.setObjectName("textLabel2_3") self.vboxlayout.addWidget(self.textLabel2_3) self.textLabel2_3_2 = QtGui.QLabel(GridPlanePropDialog) self.textLabel2_3_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.textLabel2_3_2.setObjectName("textLabel2_3_2") self.vboxlayout.addWidget(self.textLabel2_3_2) self.hboxlayout1.addLayout(self.vboxlayout) self.vboxlayout1 = QtGui.QVBoxLayout() self.vboxlayout1.setMargin(0) self.vboxlayout1.setSpacing(6) self.vboxlayout1.setObjectName("vboxlayout1") self.name_linedit = QtGui.QLineEdit(GridPlanePropDialog) self.name_linedit.setAlignment(QtCore.Qt.AlignLeading) self.name_linedit.setObjectName("name_linedit") self.vboxlayout1.addWidget(self.name_linedit) self.hboxlayout2 = QtGui.QHBoxLayout() self.hboxlayout2.setMargin(0) self.hboxlayout2.setSpacing(6) self.hboxlayout2.setObjectName("hboxlayout2") self.vboxlayout2 = QtGui.QVBoxLayout() self.vboxlayout2.setMargin(0) self.vboxlayout2.setSpacing(6) self.vboxlayout2.setObjectName("vboxlayout2") self.hboxlayout3 = QtGui.QHBoxLayout() self.hboxlayout3.setMargin(0) self.hboxlayout3.setSpacing(6) self.hboxlayout3.setObjectName("hboxlayout3") self.grid_type_combox = QtGui.QComboBox(GridPlanePropDialog) self.grid_type_combox.setObjectName("grid_type_combox") self.hboxlayout3.addWidget(self.grid_type_combox) spacerItem2 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout3.addItem(spacerItem2) self.vboxlayout2.addLayout(self.hboxlayout3) self.hboxlayout4 = QtGui.QHBoxLayout() self.hboxlayout4.setMargin(0) self.hboxlayout4.setSpacing(6) self.hboxlayout4.setObjectName("hboxlayout4") self.line_type_combox = QtGui.QComboBox(GridPlanePropDialog) self.line_type_combox.setObjectName("line_type_combox") self.hboxlayout4.addWidget(self.line_type_combox) spacerItem3 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout4.addItem(spacerItem3) self.vboxlayout2.addLayout(self.hboxlayout4) self.hboxlayout5 = QtGui.QHBoxLayout() self.hboxlayout5.setMargin(0) self.hboxlayout5.setSpacing(6) self.hboxlayout5.setObjectName("hboxlayout5") self.grid_color_pixmap = QtGui.QLabel(GridPlanePropDialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(5)) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.grid_color_pixmap.sizePolicy().hasHeightForWidth()) self.grid_color_pixmap.setSizePolicy(sizePolicy) self.grid_color_pixmap.setMinimumSize(QtCore.QSize(40,0)) self.grid_color_pixmap.setFrameShape(QtGui.QFrame.Box) self.grid_color_pixmap.setFrameShadow(QtGui.QFrame.Plain) self.grid_color_pixmap.setScaledContents(True) self.grid_color_pixmap.setObjectName("grid_color_pixmap") self.hboxlayout5.addWidget(self.grid_color_pixmap) self.choose_grid_color_btn = QtGui.QPushButton(GridPlanePropDialog) self.choose_grid_color_btn.setEnabled(True) self.choose_grid_color_btn.setAutoDefault(False) self.choose_grid_color_btn.setObjectName("choose_grid_color_btn") self.hboxlayout5.addWidget(self.choose_grid_color_btn) spacerItem4 = QtGui.QSpacerItem(16,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout5.addItem(spacerItem4) self.vboxlayout2.addLayout(self.hboxlayout5) self.hboxlayout6 = QtGui.QHBoxLayout() self.hboxlayout6.setMargin(0) self.hboxlayout6.setSpacing(6) self.hboxlayout6.setObjectName("hboxlayout6") self.border_color_pixmap = QtGui.QLabel(GridPlanePropDialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(5)) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.border_color_pixmap.sizePolicy().hasHeightForWidth()) self.border_color_pixmap.setSizePolicy(sizePolicy) self.border_color_pixmap.setMinimumSize(QtCore.QSize(40,0)) self.border_color_pixmap.setFrameShape(QtGui.QFrame.Box) self.border_color_pixmap.setFrameShadow(QtGui.QFrame.Plain) self.border_color_pixmap.setScaledContents(True) self.border_color_pixmap.setObjectName("border_color_pixmap") self.hboxlayout6.addWidget(self.border_color_pixmap) self.choose_border_color_btn = QtGui.QPushButton(GridPlanePropDialog) self.choose_border_color_btn.setEnabled(True) self.choose_border_color_btn.setAutoDefault(False) self.choose_border_color_btn.setObjectName("choose_border_color_btn") self.hboxlayout6.addWidget(self.choose_border_color_btn) spacerItem5 = QtGui.QSpacerItem(16,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout6.addItem(spacerItem5) self.vboxlayout2.addLayout(self.hboxlayout6) self.hboxlayout7 = QtGui.QHBoxLayout() self.hboxlayout7.setMargin(0) self.hboxlayout7.setSpacing(6) self.hboxlayout7.setObjectName("hboxlayout7") self.width_spinbox = QtGui.QSpinBox(GridPlanePropDialog) self.width_spinbox.setMaximum(9999) self.width_spinbox.setMinimum(5) self.width_spinbox.setSingleStep(10) self.width_spinbox.setProperty("value",QtCore.QVariant(20)) self.width_spinbox.setObjectName("width_spinbox") self.hboxlayout7.addWidget(self.width_spinbox) spacerItem6 = QtGui.QSpacerItem(16,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout7.addItem(spacerItem6) self.vboxlayout2.addLayout(self.hboxlayout7) self.hboxlayout8 = QtGui.QHBoxLayout() self.hboxlayout8.setMargin(0) self.hboxlayout8.setSpacing(6) self.hboxlayout8.setObjectName("hboxlayout8") self.height_spinbox = QtGui.QSpinBox(GridPlanePropDialog) self.height_spinbox.setMaximum(9999) self.height_spinbox.setMinimum(5) self.height_spinbox.setSingleStep(10) self.height_spinbox.setProperty("value",QtCore.QVariant(20)) self.height_spinbox.setObjectName("height_spinbox") self.hboxlayout8.addWidget(self.height_spinbox) spacerItem7 = QtGui.QSpacerItem(16,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout8.addItem(spacerItem7) self.vboxlayout2.addLayout(self.hboxlayout8) self.hboxlayout9 = QtGui.QHBoxLayout() self.hboxlayout9.setMargin(0) self.hboxlayout9.setSpacing(6) self.hboxlayout9.setObjectName("hboxlayout9") self.x_spacing_spinbox = QtGui.QSpinBox(GridPlanePropDialog) self.x_spacing_spinbox.setMaximum(1000) self.x_spacing_spinbox.setMinimum(1) self.x_spacing_spinbox.setSingleStep(5) self.x_spacing_spinbox.setProperty("value",QtCore.QVariant(1)) self.x_spacing_spinbox.setObjectName("x_spacing_spinbox") self.hboxlayout9.addWidget(self.x_spacing_spinbox) spacerItem8 = QtGui.QSpacerItem(16,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout9.addItem(spacerItem8) self.vboxlayout2.addLayout(self.hboxlayout9) self.hboxlayout10 = QtGui.QHBoxLayout() self.hboxlayout10.setMargin(0) self.hboxlayout10.setSpacing(6) self.hboxlayout10.setObjectName("hboxlayout10") self.y_spacing_spinbox = QtGui.QSpinBox(GridPlanePropDialog) self.y_spacing_spinbox.setMaximum(1000) self.y_spacing_spinbox.setMinimum(1) self.y_spacing_spinbox.setSingleStep(5) self.y_spacing_spinbox.setProperty("value",QtCore.QVariant(1)) self.y_spacing_spinbox.setObjectName("y_spacing_spinbox") self.hboxlayout10.addWidget(self.y_spacing_spinbox) spacerItem9 = QtGui.QSpacerItem(16,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout10.addItem(spacerItem9) self.vboxlayout2.addLayout(self.hboxlayout10) self.hboxlayout2.addLayout(self.vboxlayout2) spacerItem10 = QtGui.QSpacerItem(16,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout2.addItem(spacerItem10) self.vboxlayout1.addLayout(self.hboxlayout2) self.hboxlayout1.addLayout(self.vboxlayout1) self.gridlayout.addLayout(self.hboxlayout1,0,0,1,1) self.retranslateUi(GridPlanePropDialog) self.line_type_combox.setCurrentIndex(1) QtCore.QObject.connect(self.ok_btn,QtCore.SIGNAL("clicked()"),GridPlanePropDialog.accept) QtCore.QObject.connect(self.cancel_btn,QtCore.SIGNAL("clicked()"),GridPlanePropDialog.reject) QtCore.QMetaObject.connectSlotsByName(GridPlanePropDialog) GridPlanePropDialog.setTabOrder(self.name_linedit,self.grid_type_combox) GridPlanePropDialog.setTabOrder(self.grid_type_combox,self.line_type_combox) GridPlanePropDialog.setTabOrder(self.line_type_combox,self.choose_grid_color_btn) GridPlanePropDialog.setTabOrder(self.choose_grid_color_btn,self.choose_border_color_btn) GridPlanePropDialog.setTabOrder(self.choose_border_color_btn,self.width_spinbox) GridPlanePropDialog.setTabOrder(self.width_spinbox,self.height_spinbox) GridPlanePropDialog.setTabOrder(self.height_spinbox,self.x_spacing_spinbox) GridPlanePropDialog.setTabOrder(self.x_spacing_spinbox,self.y_spacing_spinbox) GridPlanePropDialog.setTabOrder(self.y_spacing_spinbox,self.ok_btn) GridPlanePropDialog.setTabOrder(self.ok_btn,self.cancel_btn) def retranslateUi(self, GridPlanePropDialog): GridPlanePropDialog.setWindowTitle(QtGui.QApplication.translate("GridPlanePropDialog", "Grid Plane Properties", None, QtGui.QApplication.UnicodeUTF8)) self.ok_btn.setText(QtGui.QApplication.translate("GridPlanePropDialog", "&OK", None, QtGui.QApplication.UnicodeUTF8)) self.ok_btn.setShortcut(QtGui.QApplication.translate("GridPlanePropDialog", "Alt+O", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setText(QtGui.QApplication.translate("GridPlanePropDialog", "&Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setShortcut(QtGui.QApplication.translate("GridPlanePropDialog", "Alt+C", None, QtGui.QApplication.UnicodeUTF8)) self.textLabel1_4.setText(QtGui.QApplication.translate("GridPlanePropDialog", "Name :", None, QtGui.QApplication.UnicodeUTF8)) self.textLabel1_5.setText(QtGui.QApplication.translate("GridPlanePropDialog", "Grid Type :", None, QtGui.QApplication.UnicodeUTF8)) self.textLabel1_5_2.setText(QtGui.QApplication.translate("GridPlanePropDialog", "Line Type :", None, QtGui.QApplication.UnicodeUTF8)) self.colorTextLabel_3.setText(QtGui.QApplication.translate("GridPlanePropDialog", "Grid Color :", None, QtGui.QApplication.UnicodeUTF8)) self.colorTextLabel_4.setText(QtGui.QApplication.translate("GridPlanePropDialog", "Border Color :", None, QtGui.QApplication.UnicodeUTF8)) self.textLabel1.setText(QtGui.QApplication.translate("GridPlanePropDialog", "Width :", None, QtGui.QApplication.UnicodeUTF8)) self.textLabel1_3.setText(QtGui.QApplication.translate("GridPlanePropDialog", "Height :", None, QtGui.QApplication.UnicodeUTF8)) self.textLabel2_3.setText(QtGui.QApplication.translate("GridPlanePropDialog", "X Spacing :", None, QtGui.QApplication.UnicodeUTF8)) self.textLabel2_3_2.setText(QtGui.QApplication.translate("GridPlanePropDialog", "Y Spacing :", None, QtGui.QApplication.UnicodeUTF8)) self.grid_type_combox.addItem(QtGui.QApplication.translate("GridPlanePropDialog", "Square", None, QtGui.QApplication.UnicodeUTF8)) self.grid_type_combox.addItem(QtGui.QApplication.translate("GridPlanePropDialog", "SiC", None, QtGui.QApplication.UnicodeUTF8)) self.line_type_combox.addItem(QtGui.QApplication.translate("GridPlanePropDialog", "None", None, QtGui.QApplication.UnicodeUTF8)) self.line_type_combox.addItem(QtGui.QApplication.translate("GridPlanePropDialog", "Solid", None, QtGui.QApplication.UnicodeUTF8)) self.line_type_combox.addItem(QtGui.QApplication.translate("GridPlanePropDialog", "Dashed", None, QtGui.QApplication.UnicodeUTF8)) self.line_type_combox.addItem(QtGui.QApplication.translate("GridPlanePropDialog", "Dotted", None, QtGui.QApplication.UnicodeUTF8)) self.choose_grid_color_btn.setToolTip(QtGui.QApplication.translate("GridPlanePropDialog", "Change color", None, QtGui.QApplication.UnicodeUTF8)) self.choose_grid_color_btn.setText(QtGui.QApplication.translate("GridPlanePropDialog", "Choose...", None, QtGui.QApplication.UnicodeUTF8)) self.choose_border_color_btn.setToolTip(QtGui.QApplication.translate("GridPlanePropDialog", "Change color", None, QtGui.QApplication.UnicodeUTF8)) self.choose_border_color_btn.setText(QtGui.QApplication.translate("GridPlanePropDialog", "Choose...", None, QtGui.QApplication.UnicodeUTF8)) self.width_spinbox.setSuffix(QtGui.QApplication.translate("GridPlanePropDialog", " Angstroms", None, QtGui.QApplication.UnicodeUTF8)) self.height_spinbox.setSuffix(QtGui.QApplication.translate("GridPlanePropDialog", " Angstroms", None, QtGui.QApplication.UnicodeUTF8)) self.x_spacing_spinbox.setSuffix(QtGui.QApplication.translate("GridPlanePropDialog", " Angstroms", None, QtGui.QApplication.UnicodeUTF8)) self.y_spacing_spinbox.setSuffix(QtGui.QApplication.translate("GridPlanePropDialog", " Angstroms", None, QtGui.QApplication.UnicodeUTF8))
NanoCAD-master
cad/src/commands/GridPlaneProperties/GridPlanePropDialog.py
NanoCAD-master
cad/src/commands/QuteMol/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ QuteMol_Command.py @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version: $Id$ History: 2008-07-24 : Created TODO: """ import foundation.changes as changes from commands.SelectChunks.SelectChunks_Command import SelectChunks_Command from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode from commands.QuteMol.QuteMolPropertyManager import QuteMolPropertyManager _superclass = SelectChunks_Command class QuteMol_Command(SelectChunks_Command): commandName = 'QUTEMOL' featurename = "QuteMol" from utilities.constants import CL_EXTERNAL_ACTION command_level = CL_EXTERNAL_ACTION GraphicsMode_class = SelectChunks_GraphicsMode PM_class = QuteMolPropertyManager command_should_resume_prevMode = True command_has_its_own_PM = True flyoutToolbar = None
NanoCAD-master
cad/src/commands/QuteMol/QuteMol_Command.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ QuteMolPropertyManager.py A Property Manager command supporting external rendering by QuteMolX. @author: Mark @copyright: 2007 Nanorex, Inc. See LICENSE file for details. @version: $Id$ History: mark 20071202: Created. """ from PyQt4.Qt import SIGNAL from PyQt4.Qt import Qt from PM.PM_GroupBox import PM_GroupBox from PM.PM_ComboBox import PM_ComboBox from PM.PM_ToolButton import PM_ToolButton from PM.PM_Constants import PM_DONE_BUTTON, PM_WHATS_THIS_BUTTON import foundation.env as env from utilities.Log import greenmsg from graphics.rendering.qutemol.qutemol import launch_qutemol, write_qutemol_files from files.pdb.files_pdb import EXCLUDE_HIDDEN_ATOMS from files.pdb.files_pdb import EXCLUDE_DNA_AXIS_BONDS from files.pdb.files_pdb import EXCLUDE_DNA_AXIS_ATOMS from command_support.Command_PropertyManager import Command_PropertyManager _superclass = Command_PropertyManager class QuteMolPropertyManager(Command_PropertyManager): """ The QuteMolPropertyManager class provides a Property Manager for QuteMolX, allowing its launch for external rendering of the model. """ # The title that appears in the Property Manager header. title = "QuteMolX" # The name of this Property Manager. This will be set to # the name of the PM_Dialog object via setObjectName(). pmName = title # The relative path to the PNG file that appears in the header iconPath = "ui/actions/Properties Manager/QuteMol.png" # DNA Display choices. _axes_display_choices = [ "Render axes", "Hide axes" ] _bases_display_choices = [ "Render bases", "Hide bases" ] #"Color bases black", #"Color bases by type" ] # PDB exclude flags = _axesFlags | _basesFlags _axesFlags = EXCLUDE_HIDDEN_ATOMS _basesFlags = EXCLUDE_HIDDEN_ATOMS def __init__( self, command ): """ Constructor for the property manager. """ _superclass.__init__(self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) msg = "Select a QuteMolX rendering style and click the "\ "<b>Launch QuteMolX</b> button when ready." # This causes the "Message" box to be displayed as well. self.updateMessage(msg) def _addGroupBoxes(self): """ Add the 1st group box to the Property Manager. """ self.pmGroupBox1 = PM_GroupBox(self, title = "DNA Display Options") self._loadGroupBox1(self.pmGroupBox1) self.pmGroupBox2 = PM_GroupBox(self, title = "Launch") self._loadGroupBox2(self.pmGroupBox2) 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.axesCombobox = PM_ComboBox( pmGroupBox, label = 'Axes: ', choices = self._axes_display_choices, index = 0, setAsDefault = True, spanWidth = False ) self.basesCombobox = PM_ComboBox( pmGroupBox, label = 'Bases: ', choices = self._bases_display_choices, index = 0, setAsDefault = True, spanWidth = False ) def _loadGroupBox2(self, pmGroupBox): """ Load widgets in 2nd group box. @param pmGroupBox: The 1st group box in the PM. @type pmGroupBox: L{PM_GroupBox} """ self.launchQuteMolButton = PM_ToolButton( pmGroupBox, text = "Launch QuteMolX", iconPath = "ui/actions/Properties Manager/QuteMol.png", spanWidth = True ) self.launchQuteMolButton.setToolButtonStyle( Qt.ToolButtonTextBesideIcon) def _addWhatsThisText(self): """ "What's This" text for widgets in this Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_QuteMolPropertyManager whatsThis_QuteMolPropertyManager(self) def _addToolTipText(self): """ Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_QuteMolPropertyManager ToolTip_QuteMolPropertyManager(self) 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.axesCombobox, SIGNAL("currentIndexChanged(const QString&)"), self.changeAxesDisplay) change_connect(self.basesCombobox, SIGNAL("currentIndexChanged(const QString&)"), self.changeBasesDisplay) change_connect(self.launchQuteMolButton, SIGNAL("clicked()"), self.launchQuteMol) def updateMessage(self, msg = ''): """ Updates the message box with an informative message @param msg: Message to be displayed in the Message groupbox of the property manager @type msg: string """ self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault = False, minLines = 5) def changeAxesDisplay(self, optionText): """ Slot to change the axes display style. @param optionText: The text of the combobox option selected. @type optionText: str """ if optionText == self._axes_display_choices[0]: self._axesFlags = EXCLUDE_HIDDEN_ATOMS # Cannot display axes if axis atoms are excluded. self.basesCombobox.setCurrentIndex(0) elif optionText == self._axes_display_choices[1]: self._axesFlags = EXCLUDE_HIDDEN_ATOMS | EXCLUDE_DNA_AXIS_BONDS else: print "Unknown axes display option: ", optionText #print "Axes display option=", optionText #print "Axes Flags=", self._axesFlags def changeBasesDisplay(self, optionText): """ Slot to change the bases display style. @param optionText: The text of the combobox option selected. @type optionText: str """ if optionText == self._bases_display_choices[0]: self._basesFlags = EXCLUDE_HIDDEN_ATOMS elif optionText == self._bases_display_choices[1]: self._basesFlags = EXCLUDE_HIDDEN_ATOMS | EXCLUDE_DNA_AXIS_ATOMS # Cannot display axesif axis atoms are excluded. self.axesCombobox.setCurrentIndex(1) else: print "Unknown bases display option: ", optionText #print "Bases display option=", optionText #print "Bases Flags=", self._basesFlags def launchQuteMol(self): """ Slot for 'Launch QuteMolX' button. Opens the QuteMolX rendering program and loads a copy of the current model. Method: 1. Write a PDB file of the current part. 2. Write an atom attributes table text file containing atom radii and color information. 3. Launches QuteMolX (with the PDB file as an argument). """ cmd = greenmsg("QuteMolX : ") excludeFlags = self._axesFlags | self._basesFlags #print "Exclude flags=", excludeFlags pdb_file = write_qutemol_files(self.win.assy, excludeFlags) # Launch QuteMolX. It will verify the plugin. errorcode, msg = launch_qutemol(pdb_file) # errorcode is ignored. env.history.message(cmd + msg)
NanoCAD-master
cad/src/commands/QuteMol/QuteMolPropertyManager.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ Select_Command.py The 'Command' part of the Select Mode (Select_basicCommand and Select_basicGraphicsMode are the two split classes of the old selectMode) It provides the command object for its GraphicsMode class. The Command class defines anything related to the 'command half' of the mode -- For example: - Anything related to its current Property Manager, its settings or state - The model operations the command does (unless those are so simple that the mouse event bindings in the _GM half can do them directly and the code is still clean, *and* no command-half subclass needs to override them). @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. TODO: - Items mentioned in Select_GraphicsMode.py - The Enter method needs to be split into Enter_Command and Enter_GM parts History: Ninad & Bruce 2007-12-13: Created new Command and GraphicsMode classes from the old class selectMode and moved the Command related methods into this class from selectMode.py """ from command_support.Command import basicCommand from commands.Select.Select_GraphicsMode import Select_GraphicsMode from command_support.GraphicsMode_API import GraphicsMode_interface class Select_basicCommand(basicCommand): """ The 'Command' part of the Select Mode (Select_basicCommand and Select_basicGraphicsMode are the two split classes of the old selectMode) It provides the command object for its GraphicsMode class. The Command class defines anything related to the 'command half' of the mode -- For example: - Anything related to its current Property Manager, its settings or state - The model operations the command does (unless those are so simple that the mouse event bindings in the _GM half can do them directly and the code is still clean, *and* no command-half subclass needs to override them). @see: cad/doc/splitting_a_mode.py that gives a detailed explanation on how this is implemented. @see: B{Select_GraphicsMode}, B{Select_basicGraphicsMode} @see: B{Select_Command}, B{selectMode} @see: B{SelectChunks_Command}, B{SelectAtoms_basicCommand} which inherits this class """ # class constants from utilities.constants import CL_ABSTRACT command_level = CL_ABSTRACT # Don't highlight singlets. (This attribute is set to True in # SelectAtoms_Command) highlight_singlets = False def __init__(self, commandSequencer): """ ... """ basicCommand.__init__(self, commandSequencer) # Now do whatever might be needed to init the command object, # or in the mixed case, the command-related attrs of the mixed object. # That might be nothing, since most attrs can just be initialized in # Enter, since they should be reinitialized every time we enter the # command anyway. # (If it's nothing, we probably don't need this method, but it's ok # to have it for clarity, especially if there is more than one # superclass.) return def connect_or_disconnect_signals(self, connect): """ Subclasses should override this method """ pass def makeMenus(self): """ Overrided in subclasses. Default implementation does nothing @see: selectAtoms_Command.makeMenus @see: selectChunks_Command.makeMenus @see: self._makeEditContextMenu() @see: SelectChunks_EditCommand.makeMenus() """ pass def _makeEditContextMenus(self): """ Subclasses can call this method inside self.makeMenus() if they need context menu items for editing selected components such as Nanotube, DnaStrand , DnaSegments. Creates a context menu items to edit a selected component. If more than one type of components are selected, the edit options are not added. Example: if a DnaStrand is selected, this method will add a context menu 'Edit selected DnaStrand'. But if, along with DnaStrand, a DnaSegment is selected, it won't show options to edit the dna strand or dna segment. @see: SelectChunks_EditCommand.makeMenus() @see: se;f.makeMenus() """ selectedDnaSegments = self.win.assy.getSelectedDnaSegments() selectedDnaStrands = self.win.assy.getSelectedDnaStrands() selectedNanotubes = self.win.assy.getSelectedNanotubeSegments() numOfSegments = len(selectedDnaSegments) numOfStrands = len(selectedDnaStrands) numOfNanotubes = len(selectedNanotubes) #If both DnaSegments and DnaStrands are selected, we will not show #context menu for editing the selected entities i.e. Edit DnaSegment.. #AND "Edit DnaStrands..". This is based on a discussion with Mark. This #can be easily changed if we decide that way -- Ninad 2008-07-10 count = 0 for num in (numOfSegments, numOfStrands, numOfNanotubes): if num > 0: count += 1 if count > 1: return if numOfSegments or numOfStrands: self._makeDnaContextMenus() if numOfNanotubes: self._makeNanotubeContextMenus() return def _makeDnaContextMenus(self): """ Make Dna specific context menu that allows editing a *selected* DnaStrand or DnaSegment. @see: self._makeEditContextMenu() which calls this method """ contextMenuList = [] selectedDnaSegments = self.win.assy.getSelectedDnaSegments() selectedDnaStrands = self.win.assy.getSelectedDnaStrands() #If both DnaSegments and DnaStrands are selected, we will not show #context menu for editing the selected entities i.e. Edit DnaSegment.. AND #"Edit DnaStrands..". This is based on a discussion with Mark. This #can be easily changed if we decide that way -- Ninad 2008-07-10 if not selectedDnaStrands: if len(selectedDnaSegments) == 1: segment = selectedDnaSegments[0] item = (("Edit Selected DnaSegment..."), segment.edit) contextMenuList.append(item) contextMenuList.append(None) #adds a separator if len(selectedDnaSegments) > 1: item = (("Resize Selected DnaSegments "\ "(%d)..."%len(selectedDnaSegments)), self.win.resizeSelectedDnaSegments) contextMenuList.append(item) contextMenuList.append(None) if not selectedDnaSegments: if len(selectedDnaStrands) == 1: strand = selectedDnaStrands[0] item = (("Edit Selected DnaStrand..."), strand.edit) contextMenuList.append(item) self.Menu_spec.extend(contextMenuList) return def _makeNanotubeContextMenus(self): """ Make Nanotube specific context menu that allows editing a *selected* Nanotube @see: self._makeEditContextMenu() which calls this method """ contextMenuList = [] selectedNanotubes = self.win.assy.getSelectedNanotubeSegments() if len(selectedNanotubes) == 1: nanotube = selectedNanotubes[0] item = (("Edit Selected Nanotube..."), nanotube.edit) contextMenuList.append(item) self.Menu_spec.extend(contextMenuList) return class Select_Command(Select_basicCommand): # This is needed so the init code knows what kind of GM to make. GraphicsMode_class = Select_GraphicsMode def __init__(self, commandSequencer): Select_basicCommand.__init__(self, commandSequencer) self._create_GraphicsMode() return def _create_GraphicsMode(self): GM_class = self.GraphicsMode_class assert issubclass(GM_class, GraphicsMode_interface) args = [self] kws = {} self.graphicsMode = GM_class(*args, **kws) pass
NanoCAD-master
cad/src/commands/Select/Select_Command.py
NanoCAD-master
cad/src/commands/Select/__init__.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ Select_GraphicsMode_MouseHelpers_preMixin.py Mixin class for the Select_basicGraphicsMode. The only purpose of creating this mixin class was for easy understanding of the code in Select_basicGraphicsMode As the name suggest, this mixin class overrides the Mouse helper Methods (e.g. leftDown, objectLeftdown, objectSetUp etc) of the 'basicGraphicsMode' . This is a 'preMixin' class, meaning, it needs to be inherited by the subclass 'Select_basicGraphicsMode' _before_ it inherits the 'basicGraphicsMode' To be used as a Mixin class only for Select_basicGraphicsMode. @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. """ import foundation.env as env from model.bonds import Bond from model.chem import Atom from model.chunk import Chunk from model.jigs import Jig from utilities.debug import print_compact_stack from utilities.GlobalPreferences import DEBUG_BAREMOTION, DEBUG_BAREMOTION_VERBOSE _count = 0 # == from command_support.GraphicsMode import commonGraphicsMode class Select_GraphicsMode_MouseHelpers_preMixin(commonGraphicsMode): """ Mixin class for the Select_basicGraphicsMode. The only purpose of creating this mixin class was for easy understanding of the code in Select_basicGraphicsMode As the name suggest, this mixin class overrides the Mouse helper Methods (e.g. leftDown, objectLeftdown, objectSetUp etc) of the 'basicGraphicsMode' . This is a 'preMixin' class, meaning, it needs to be inherited by the subclass 'Select_basicGraphicsMode' _before_ it inherits the 'basicGraphicsMode' To be used as a Mixin class only for Select_basicGraphicsMode. @see: B{Select_basicGraphicsMode} """ #Define All Mouse related methods def bareMotion(self, event): """ called for motion with no button down [should not be called otherwise -- call update_selatom or update_selobj directly instead] """ # The mouse_exceeded_distance() conditional below is a # "hover highlighting" optimization. # It works by returning before calling update_selobj() if the mouse is # moving fast. This reduces unnecessary highlighting of objects whenever # the user moves the cursor quickly across the GLPane. In many cases, # this unnecessary highlighting degrades # interactive responsiveness and can also cause the user to select the # wrong objects (i.e. atoms), especially in large models. # # One problem with this approach (pointed out by Bruce) happens when the # user moves the # cursor quickly from one object and suddenly stops on another object, # expecting it (the 2nd object) to be highlighted. Since bareMotion() # is only called when the mouse is moving, and the distance between the # last two mouse move events is far, mouse_exceed_distance() will # return True. In that case, update_selobj() will not get called and the # object under the cursor will never get highlighted unless the user # jiggles the mouse slightly. To address this issue, a GLpane timer was # implemented. The timer calls bareMotion() whenever it expires and the # cursor hasn't moved since the previous timer event. [But at most once # after the cursor stops, or something like that -- see the code.] # For more details, read the docstring [and code] for GLPane.timerEvent(). # [probably by Mark, probably circa 060806] # # russ 080527: Fixed bug 2606. After a zoom wheelEvent, prevent # skipping highlight selection due to mouse_exceeded_distance. if self.mouse_exceeded_distance(event, 1) and not self.o.wheelHighlight: if DEBUG_BAREMOTION_VERBOSE: #bruce 080129 re highlighting bug 2606 reported by Paul print "debug fyi: skipping %r.bareMotion since mouse travelled too far" % self return False self.update_selobj(event) # note: this routine no longer updates glpane.selatom. For that see # self.update_selatom(). ###e someday, if new or prior selobj asks for it (by defining certain # methods), we'd tell it about this bareMotion and about changes in # selobj. [bruce 060726] return False # russ 080527 #Left mouse related event handlers -- # == LMB event handling methods ==================================== # Important Terms: [mark 060205] # # "selection curve": the collection of line segments drawn by the cursor # when definingthe selection area. These line segments become the selection # lasso when (and if) the selection rectangle disappears. When the selection # rectangle is still displayed,the selection curve consists of those line # segment that are drawn between opposite corners of the selection # rectangle. The line segments that define/draw the rectangle itself are not # part of the selection curve, however.Also, it is worth noting that the # line segments of the selection curve are also drawn just beyond the front # clipping plane. The variable <selCurve_List> contains the list # of points that draw the line segments of the selection curve. # # "selection area": determined by the selection curve, it is the area that # defines what # is picked (or unpicked). The variable <selArea_List> contains the list of # points that define the selection area used to pick/unpick objects. The # points in <selArea_List> lay in the plane parallel to the screen and pass # through the center of the view. # # "selection rectangle": the rectangular selection determined by the first # and last points of a selection curve. These two points define the # opposite corners of the rectangle. # # "selection lasso": the lasso selection defined by all the points #(and line segements)in the selection curve. # == LMB down-click (button press) methods def leftShiftDown(self, event): self.leftDown(event) def leftCntlDown(self, event): self.leftDown(event) def leftDown(self, event): self.select_2d_region(event) # == LMB drag methods def leftShiftDrag(self, event): self.leftDrag(event) def leftCntlDrag(self, event): self.leftDrag(event) def leftDrag(self, event): self.continue_selection_curve(event) # == LMB up-click (button release) methods def leftShiftUp(self, event): self.leftUp(event) def leftCntlUp(self, event): self.leftUp(event) def leftUp(self, event): self.end_selection_curve(event) # == LMB double click method def leftDouble(self, event): pass # == END of LMB event handlers. ============================================ # == START of Empty Space helper methods =================================== #& The Empty Space, Atom, Bond and Singlet helper methods should probably be #& moved to SelectAtoms_GraphicsMode. I put them here because I think there is a #& good chance that we'll allow intermixing of atoms, chunks and jigs #&(and other stuff) in any mode. Mark 060220. def emptySpaceLeftDown(self, event): self.objectSetup(None) self.cursor_over_when_LMB_pressed = 'Empty Space' self.select_2d_region(event) return def emptySpaceLeftDrag(self, event): self.continue_selection_curve(event) return def emptySpaceLeftUp(self, event): self.end_selection_curve(event) return # == END of Empty Space helper methods ===================================== # == START of object specific LMB helper methods =========================== def doObjectSpecificLeftDown(self, obj, event): """ Call objectLeftDown methods depending on the object instance. @param obj: object under consideration @type obj: instance @param event: Left down mouse event @type event: QMouseEvent instance """ if isinstance(obj, Chunk): self.chunkLeftDown(obj, event) if isinstance(obj, Atom) and obj.is_singlet(): self.singletLeftDown(obj, event)# Cursor over a singlet elif isinstance(obj, Atom) and not obj.is_singlet(): self.atomLeftDown(obj, event) # Cursor over a real atom elif isinstance(obj, Bond) and not obj.is_open_bond(): self.bondLeftDown(obj, event) #Cursor over a bond. elif isinstance(obj, Jig): self.jigLeftDown(obj, event) #Cursor over a jig. else: # Cursor is over something else other than an atom, singlet or bond. # (should be handled in caller) pass def doObjectSpecificLeftUp(self, obj, event): """ Call objectLeftUp methods depending on the object instance. @param obj: object under consideration @type obj: instance @param event: Left Up mouse event @type event: QMouseEvent instance """ #This flag initially gets set in selectMode.objectSetup. Then, #if the object is being dragged, the value is reset to False in #the object specific drag method . FYI: The comment in #selectMode.objectSetup suggests the this flag should not be set in #class.leftDrag method. (but instead object specific left drag) #So lets set that flag up in the method #selectMode.doObjectSpecificLeftDrag. Note that this method is #overridden in subclasses, so make sure to either set that flag in #those methods or always call the superclass method at the beginning. # In case of SelectChunks_GraphicsMode, the 'objects' are # really the selectedMovable. so it makes sense to set it in #SelectChunks_GraphicsMode.leftDragTranslation or call doObjectSpecificLeftDrag #somewhere -- Ninad 2007-11-15 #UPDATE 2007-11-15: #The self.current_obj_clicked is not valid for Singlets (bond #points) because singlet dragging and then doing left up actually forms #a bond. So It is important to continue down this method for that #condition even if self.current_obj_clicked is False. Otherwise bonds # won't be formed....Then should this check be done in each of the #objectLeftUp methods? But that would be too many methods in various #subclasses and it may cause bugs if someone forgets to add this check. if not self.current_obj_clicked: if isinstance(obj, Atom) and obj.is_singlet(): pass else: return if isinstance(obj, Chunk): self.chunkLeftUp(obj, event) elif isinstance(obj, Atom): if obj.is_singlet(): # Bondpoint self.singletLeftUp(obj, event) else: # Real atom self.atomLeftUp(obj, event) elif isinstance(obj, Bond): # Bond self.bondLeftUp(obj, event) elif isinstance(obj, Jig): # Jig self.jigLeftUp(obj, event) else: pass def doObjectSpecificLeftDrag(self, obj, event): """ Call objectLeftDrag methods depending on the object instance. Default implementation only sets flag self.current_obj_clicked to False. Subclasses should make sure to either set that flag in #those methods or always call the superclass method at the beginning. @param obj: object under consideration. @type obj: instance @param event: Left drag mouse event @type event: QMouseEvent instance @see: SelectAtoms_GraphicsMode.doObjectSpecificLeftDrag @see: self.doObjectSpecificLeftUp, self.objectSetup for comments """ #current object is not clicked but is dragged. Important to set this #flag. See self.doObjectSpecificLeftUp for more comments self.current_obj_clicked = False def objectSetup(self, obj): ###e [should move this up, below generic left* methods -- ##it's not just about atoms] # [this seems to be called (sometimes indirectly) by every leftDown # method, and by some methods in depmode that create objects and can # immediately drag them. Purpose is more general than just for a # literal "drag" -- # I guess it's for many things that immediately-subsequent leftDrag or # leftUp or leftDouble might need to know obj to decide on. I think I'll #call it for all new drag_handlers too. [bruce 060728 comment]] self.current_obj = obj # [used by leftDrag and leftUp to decide what #to do [bruce 060727 comment]] self.obj_doubleclicked = obj # [used by leftDouble and class-specific #leftDouble methods [bruce 060727 comment]] if obj is None: self.current_obj_clicked = False else: self.current_obj_clicked = True # [will be set back to False if obj is dragged, but only by # class-specific drag methods, not by leftDrag itself -- make # sure to consider doing that in drag_handler case too ##@@@@@ # [bruce 060727 comment]] # we need to store something unique about this event; # we'd use serno or time if it had one..instead this _count will do. global _count _count = _count + 1 self.current_obj_start = _count # used in transient_id argument #to env.history.message def atomSetup(self, a, event): """ Subclasses should override this method Setup for a click, double-click or drag event for real atom <a>. @see: selectatomsMode.atomSetup where this method is overridden. """ self.objectSetup(a) def atomLeftDown(self, a, event): """ Subclasses should override this method. @param a: Instance of class Atom @type a: B{Atom} @param event: the QMouseEvent. @see: SelectAtoms_GraphicsMode.atomLeftDown """ self.atomSetup(a, event) def atomLeftUp(self, a, event): """ Subclasses should override this method. The default implementation does nothing. @param a: Instance of class Atom @type a: B{Atom} @param event: the QMouseEvent. @see: SelectAtoms_GraphicsMode.atomLeftUp """ pass def atomLeftDouble(self): """ Subclasses should override this method. The default implementation does nothing. Atom double click event handler for the left mouse button. """ pass # == End of Atom selection and dragging helper methods # == Bond selection helper methods def bondLeftDown(self, b, event): # Bonds cannot be picked when highlighting is turned off. self.cursor_over_when_LMB_pressed = 'Bond' self.bondSetup(b) def bondSetup(self, b): """ Setup for a click or double-click event for bond <b>. Bond dragging is not supported. """ self.objectSetup(b) def bondLeftUp(self, b, event): """ Subclasses should override this method. The default implementation does nothing. Bond <b> was clicked, so select or unselect its atoms or delete bond <b> based on the current modkey. - If no modkey is pressed, clear the selection and pick <b>'s two atoms. - If Shift is pressed, pick <b>'s two atoms, adding them to the current selection. - If Ctrl is pressed, unpick <b>'s two atoms, removing them from the current selection. - If Shift+Control (Delete) is pressed, delete bond <b>. <event> is a LMB release event. """ pass def bondDelete(self, event): """ If the object under the cursor is a bond, delete it. @param event: A left mouse up event. @type event: U{B{QMouseEvent}<http://doc.trolltech.com/4/qmouseevent.html>} """ # see also: bond_utils.delete_bond #bruce 041130 in case no update_selatom happened yet self.update_selatom(event) # see warnings about update_selatom's delayed effect, # in its docstring or in leftDown. [bruce 050705 comment] selobj = self.o.selobj if isinstance( selobj, Bond) and not selobj.is_open_bond(): _busted_strand_bond = False if selobj.isStrandBond(): _busted_strand_bond = True msg = "breaking strand %s" % selobj.getStrandName() else: msg = "breaking bond %s" % selobj env.history.message_no_html(msg) # note: %r doesn't show bond type, but %s needs _no_html # since it contains "<-->" which looks like HTML. self.o.selobj = None # without this, the bond remains highlighted # even after it's broken (visible if it's toolong) ###e shouldn't we use set_selobj instead?? ##[bruce 060726 question] x1, x2 = selobj.bust() # this fails to preserve the bond type on the open bonds # -- not sure if that's bad, but probably it is if 1: # Note: this should be removed once the dna updater becomes # turned on by default. (It will cause no harm, but will be a slowdown # since everything it does will be undone or redone differently # by the updater.) [bruce 080228 comment] # After bust() selobj.isStrandBond() is too fragile, so I set # <_busted_strand_bond> and test it instead. - Mark 2007-10-23. if _busted_strand_bond: # selobj.isStrandBond(): self.o.assy.makeStrandChunkFromBrokenStrand(x1, x2) self.set_cmdname('Delete Bond') self.o.assy.changed() #k needed? self.w.win_update() #k wouldn't gl_update be enough? #[bruce 060726 question] def bondDrag(self, obj, event): """ Subclasses should override this method @see: SelectAtoms_GraphicsMode.bondDrag """ pass def bondLeftDouble(self): """ Subclasses should override this method @see: SelectAtoms_GraphicsMode.bondLeftDouble """ pass # == End of bond selection helper methods #== Chunk helper methods def chunkSetUp(self, a_chunk, event): """ Chunk setup (called from self.chunkLeftDown() @see: SelectChunks_GraphicsMode.chunkLeftDown() @see: BuildDna_GraphicsMode.chunkLeftDown() @see:self.objectSetup() """ self.objectSetup(a_chunk) def chunkLeftDown(self, a_chunk, event): """ Overridden is subclasses. Default implementation does nothing. Depending on the modifier key(s) pressed, it does various operations on chunk..typically pick or unpick the chunk(s) or do nothing. If an object left down happens, the left down method of that object calls this method (chunkLeftDown) as it is the 'SelectChunks_GraphicsMode' which is supposed to select Chunk of the object clicked @param a_chunk: The chunk of the object clicked (example, if the object is an atom, then it is atom.molecule @type a_chunk: B{Chunk} @param event: MouseLeftDown event @see: self.atomLeftDown @see: self.chunkLeftUp @see: SelectChunks_GraphicsMode.chunkLeftDown() """ pass def chunkLeftUp(self, a_chunk, event): """ Overridden is subclasses. Default implementation does nothing. Depending on the modifier key(s) pressed, it does various operations on chunk. Example: if Shift and Control modkeys are pressed, it deletes the chunk @param a_chunk: The chunk of the object clicked (example, if the object is an atom, then it is atom.molecule @type a_chunk: B{Chunk} @param event: MouseLeftUp event @see: self.atomLeftUp @see: self.chunkLeftdown @see: SelectChunks_GraphicsMode.chunkLeftUp() """ pass # == Singlet helper methods def singletLeftDown(self, s, event): self.cursor_over_when_LMB_pressed = 'Empty Space' self.select_2d_region(event) self.o.gl_update() # REVIEW (possible optim): can gl_update_highlight be extended to # cover this? [bruce 070626] return def singletSetup(self, s): pass def singletDrag(self, s, event): pass def singletLeftUp(self, s, event): pass def singletLeftDouble(self): """ Singlet double click event handler for the left mouse button. """ pass #Reference Geometry handler helper methods #@@ This and jig helper methods need to be combined. -- ninad 20070516 def geometryLeftDown(self, geom, event): self.jigLeftDown(geom, event) def geometryLeftUp(self, geom, event): self.jigLeftUp(geom, event) def geometryLeftDrag(self, geom, event): geometry_NewPt = self.dragto( self.jig_MovePt, event) # Print status bar msg indicating the current move offset. if 1: self.moveOffset = geometry_NewPt - self.jig_StartPt msg = "Offset: [X: %.2f] [Y: %.2f] [Z: %.2f]" % (self.moveOffset[0], self.moveOffset[1], self.moveOffset[2]) env.history.statusbar_msg(msg) offset = geometry_NewPt - self.jig_MovePt geom.move(offset) self.jig_MovePt = geometry_NewPt self.current_obj_clicked = False self.o.gl_update() def handleLeftDown(self, hdl, event): self.handle_MovePt = hdl.parent.getHandlePoint(hdl, event) self.handleSetUp(hdl) def handleLeftDrag(self, hdl, event): hdl.parent.resizeGeometry(hdl, event) handle_NewPt = hdl.parent.getHandlePoint(hdl, event) self.handle_MovePt = handle_NewPt self.current_obj_clicked = False self.o.gl_update() def handleLeftUp(self, hdl, event): pass def handleSetUp(self, hdl): self.objectSetup(hdl) # == Jig event handler helper methods def jigLeftDown(self, j, event): if not j.picked and self.o.modkeys is None: self.o.assy.unpickall_in_GLPane() # was unpickatoms, unpickparts #[bruce 060721] j.pick() if not j.picked and self.o.modkeys == 'Shift': j.pick() if j.picked: self.cursor_over_when_LMB_pressed = 'Picked Jig' else: self.cursor_over_when_LMB_pressed = 'Unpicked Jig' # Move section farQ_junk, self.jig_MovePt = self.dragstart_using_GL_DEPTH( event) #bruce 060316 replaced equivalent old code with this new method if 1: #bruce 060611 experiment, harmless, prototype of WidgetExpr-related # changes, might help Bauble; committed 060722 # [see also leftClick, which will eventually supercede this, # and probably could already -- bruce 060725] method = getattr(j, 'clickedOn', None) if method and method(self.jig_MovePt): return self.jig_StartPt = self.jig_MovePt # Used in leftDrag() to compute move #offset during drag op. self.jigSetup(j) def jigSetup(self, j): """ Setup for a click, double-click or drag event for jig <j>. """ self.objectSetup(j) def jigLeftUp(self, j, event): """ Jig <j> was clicked, so select, unselect or delete it based on the current modkey. - If no modkey is pressed, clear the selection and pick jig <j>. - If Shift is pressed, pick <j>, adding it to the current selection. - If Ctrl is pressed, unpick <j>, removing it from the current selection. - If Shift+Control (Delete) is pressed, delete jig <j>. """ self.deallocate_bc_in_use() if not self.current_obj_clicked: # Jig was dragged. Nothing to do but return. self.set_cmdname('Move Jig') self.o.assy.changed() return if self.selection_locked(): return nochange = False if self.o.modkeys is None: # isn't this redundant with jigLeftDown? [bruce 060721 question; #btw this method is very similar to atomLeftUp] self.o.assy.unpickall_in_GLPane() # was unpickatoms only #(but I think unpickall makes more sense) [bruce 060721] if j.picked: # bruce 060412 fix unreported bug: remove nochange = True, #in case atoms were just unpicked pass ## nochange = True else: j.pick() self.set_cmdname('Select Jig') elif self.o.modkeys == 'Shift': if j.picked: nochange = True else: j.pick() self.set_cmdname('Select Jig') elif self.o.modkeys == 'Control': if j.picked: j.unpick() self.set_cmdname('Unselect Jig') env.history.message("Unselected %r" % j.name) #bruce 060412 comment: I think a better term (in general) would #be "Deselect". else: # Already unpicked. nochange = True elif self.o.modkeys == 'Shift+Control': #fixed bug 1641. mark 060314. #bruce 060412 revised text env.history.message("Deleted %r" % j.name) # Build list of deleted jig's atoms before they are lost. self.atoms_of_last_deleted_jig.extend(j.atoms) #bruce 060412 #optimized this j.kill() #bruce 060412 wonders how j.kill() affects the idea of #double-clicking this same jig to delete its atoms too, # since the jig is gone by the time of the 2nd click. # See comments in jigLeftDouble for more info. self.set_cmdname('Delete Jig') self.w.win_update() return else: print_compact_stack('Invalid modkey = "' + str(self.o.modkeys) + '" ') return #call API method to do any additinal selection self.end_selection_from_GLPane() if nochange: return self.o.gl_update() def jigLeftDouble(self): """ Jig <j> was double clicked, so select, unselect or delete its atoms based on the current modkey. - If no modkey is pressed, pick the jig's atoms. - If Shift is pressed, pick the jig's atoms, adding them to the current selection. - If Ctrl is pressed, unpick the jig's atoms, removing them from the current selection. - If Shift+Control (Delete) is pressed, delete the jig's atoms. """ #bruce 060412 thinks that the jig transdelete feature (delete the jig's #atoms on shift-control-dblclick) # might be more dangerous than useful: # - it might happen on a wireframe jig, like an Anchor, if user intended # to transdelete on an atom instead; # - it might happen if user intended to delete jig and then delete an # atom behind it (epecially since the jig # becomes invisible after the first click), if two intended single # clicks were interpreted as a double click; # - it seems rarely needed, so it could just as well be in the jig's # context menu instead. # To mitigate this problem, I'll add a history message saying that it # happened. # I'll also optimize some loops (by removing [:]) and fix bug 1816 # (missing update). if self.o.modkeys == 'Control': for a in self.obj_doubleclicked.atoms: a.unpick() elif self.o.modkeys == 'Shift+Control': #bruce 060418 rewrote this, to fix bug 1816 and do other improvements # (though I think it should be removed, as explained above) atoms = self.atoms_of_last_deleted_jig # a list of atoms self.atoms_of_last_deleted_jig = [] # for safety if atoms: self.set_cmdname("Delete Jig's Atoms") #bruce 060412. Should it be something else? 'Delete Atoms', #'Delete Atoms of Jig', "Delete Jig's Atoms" # Note, this presently ends up as a separate operation in the # Undo stack from the first click deleting the jig, but in #the future these ops might be merged in the Undo stack, # and if they are, this command name should be changed to # cover deleting both the jig and its atoms. env.history.message("Deleted jig's %d atoms" % len(atoms)) # needed since this could be done by accident, and in some #cases could go unnoticed # (count could be wrong if jig.kill() already killed some # of the atoms for some reason; probably never happens) self.w.win_update() # fix bug 1816 for a in atoms: a.kill() ##e could be optimized using prekill else: for a in self.obj_doubleclicked.atoms: a.pick() self.o.gl_update() #bruce 060412 fix some possible unreported bugs return # == End of (most) Jig helper methods def selection_locked(self, msg = ''): """ Returns whether the current selection is 'locked' . If True, no changes to the current selection are possible from glpane (i.e using mouse opearions) But user can still select the objects using MT or using toolbar options such as 'select all'. @param msg: optional string to include in statusbar text """ isLocked = self.glpane.mouse_selection_lock_enabled if isLocked and msg: env.history.statusbar_msg("%s"% msg) return isLocked # == END of object specific LMB helper methods =============================
NanoCAD-master
cad/src/commands/Select/Select_GraphicsMode_MouseHelpers_preMixin.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ Select_GraphicsMode.py The GraphicsMode part of the Select_Command. It provides the graphicsMode object for its Command class. The GraphicsMode class defines anything related to the *3D Graphics Area* -- For example: - Anything related to graphics (Draw method), - Mouse events - Cursors, - Key bindings or context menu @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. TODO: - Select_basicGraphicsMode is the main GM class. It is inherited by a 'glue-in' class Select_GraphicsMode. See cad/doc/splitting_a_mode.py for a detailed explanation on how this is used. Note that the glue-in classes will be used until all the selectMode subclasses are split into GM and Command part. Once thats done you the class Select_basicGraphicsMode needs to be used (and rename that to Select_GraphicsMode) - See if context menu related method makeMenus defined in the command class needs to be moved to the GraphicsMode class - Other items listed in Select_Command.py - Redundant use of glRenderMode (see comment where that is used) See Bruce's comments in method get_jig_under_cursor +++ OLD comment -- might be outdated as of 2007-12-13 Some things that need cleanup in this code [bruce 060721 comment]: ####@@@@ - drag algorithms for various object types and modifier keys are split over lots of methods with lots of common but not identical code. For example, a set of atoms and jigs can be dragged in the same way, by two different pieces of code depending on whether an atom or jig in the set was clicked on. If this was cleaned up, so that objects clicked on would answer questions about how to drag them, and if a drag_handler object was created to handle the drag (or the object itself can act as one, if only it is dragged and if it knows how), the code would be clearer, some bugs would be easier to fix, and some NFRs easier to implement. [bruce 060728 -- I'm adding drag_handlers for use by new kinds of draggable or buttonlike things (only in selectAtoms mode and subclasses), but not changing how old dragging code works.] +++ History: Ninad & Bruce 2007-12-13: Created new Command and GraphicsMode classes from the old class selectMode and moved the GraphicsMode related methods into this class from selectMode.py """ from Numeric import dot from OpenGL.GL import GL_CLIP_PLANE0 from OpenGL.GL import GL_DEPTH_COMPONENT from OpenGL.GL import GL_FALSE from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import GL_PROJECTION from OpenGL.GL import GL_RENDER from OpenGL.GL import GL_SELECT from OpenGL.GL import GL_STENCIL_INDEX from OpenGL.GL import GL_TRUE from OpenGL.GL import glClipPlane from OpenGL.GL import glColorMask from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import glFlush from OpenGL.GL import glInitNames from OpenGL.GL import glMatrixMode from OpenGL.GL import glPopMatrix from OpenGL.GL import glPushMatrix from OpenGL.GL import glReadPixelsf from OpenGL.GL import glReadPixelsi from OpenGL.GL import glRenderMode from OpenGL.GL import glSelectBuffer from OpenGL.GLU import gluProject from OpenGL.GLU import gluUnProject from utilities.constants import GL_FAR_Z from utilities.constants import SELSHAPE_RECT from utilities.constants import SELSHAPE_LASSO from utilities.constants import SUBTRACT_FROM_SELECTION from utilities.constants import ADD_TO_SELECTION from utilities.constants import START_NEW_SELECTION from utilities.constants import DELETE_SELECTION from utilities.constants import black import foundation.env as env from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice from geometry.VQT import A, vlen from graphics.behaviors.shape import SelectionShape from model.bonds import Bond from model.chem import Atom from model.jigs import Jig from utilities.debug import print_compact_traceback from utilities.debug import print_compact_stack from utilities.prefs_constants import bondHighlightColor_prefs_key from utilities.prefs_constants import deleteBondHighlightColor_prefs_key from utilities import debug_flags debug_update_selobj_calls = False # do not commit with true DRAG_STICKINESS_LIMIT = 6 # in pixels; reset in each leftDown via a debug_pref #& To do: Make it a user pref in the Prefs Dialog. Also consider a # different var/pref #& for singlet vs. atom drag stickiness limits. Mark 060213. _ds_Choice = Choice([0,1,2,3,4,5,6,7,8,9,10], defaultValue = DRAG_STICKINESS_LIMIT) DRAG_STICKINESS_LIMIT_prefs_key = "A7/Drag Stickiness Limit" def set_DRAG_STICKINESS_LIMIT_from_pref(): #bruce 060315 global DRAG_STICKINESS_LIMIT DRAG_STICKINESS_LIMIT = debug_pref( "DRAG_STICKINESS_LIMIT (pixels)", _ds_Choice, non_debug = True, prefs_key = DRAG_STICKINESS_LIMIT_prefs_key) return set_DRAG_STICKINESS_LIMIT_from_pref() # also called in SelectAtoms_GraphicsMode.leftDown # (ideally, clean up this pref code a lot by not passing # DRAG_STICKINESS_LIMIT as an arg to the subr that uses it) # we do this early so the debug_pref is visible in the debug menu before # entering SelectAtoms_GraphicsMode. # == from command_support.GraphicsMode import basicGraphicsMode from commands.Select.Select_GraphicsMode_MouseHelpers_preMixin import Select_GraphicsMode_MouseHelpers_preMixin from temporary_commands.TemporaryCommand import ESC_to_exit_GraphicsMode_preMixin _superclass = basicGraphicsMode class Select_basicGraphicsMode( Select_GraphicsMode_MouseHelpers_preMixin, ESC_to_exit_GraphicsMode_preMixin, basicGraphicsMode ): """ The GraphicsMode part of the Select_Command. It provides the graphicsMode object for its Command class. The GraphicsMode class defines anything related to the 3D graphics area -- For example: - Anything related to graphics (Draw method), - Mouse events, cursors (for use in graphics area), - Key bindings or context menu (for use in graphics area). @see: cad/doc/splitting_a_mode.py that gives a detailed explanation about how this is implemented. @see: B{Select_GraphicsMode} @see: B{Select_Command}, B{Select_basicCommand}, B{selectMode} @see: B{Select_GraphicsMode_MouseHelpers_preMixin} @see: B{SelectChunks_basicGraphicsMode}, B{SelectAtoms_basicGraphicsMode} which inherits this class """ # class constants gridColor = (0.0, 0.0, 0.6) # default initial values savedOrtho = 0 selCurve_length = 0.0 # <selCurve_length> is the current length (sum) of all the selection #curve segments. selCurve_List = [] # <selCurve_List> contains a list of points used to draw the selection # curve. The points lay in the # plane parallel to the screen, just beyond the front clipping plane, # so that they are always # inside the clipping volume. selArea_List = [] # <selArea_List> contains a list of points that define the selection # area. The points lay in # the plane parallel to the screen and pass through the center of the # view. The list is used by pickrect() and pickline() to make the # selection. selShape = SELSHAPE_RECT # <selShape> the current selection shape. ignore_next_leftUp_event = False # Set to True in leftDouble() and checked by the left*Up() # event handlers to determine whether they should ignore the # (second) left*Up event generated by the second LMB up/release # event in a double click. #Boolean flag that is used in combination with #self.command.isHighlightingEnabled(). _suppress_highlighting = False def __init__(self, glpane): """ """ _superclass.__init__(self, glpane) # Now do whatever might be needed to init the graphicsMode object, # or the graphicsMode-related attrs of the mixed object. # # (Similar comments apply as for Select_basicCommand.__init__, below, # but note that for GraphicsModes, there is no Enter method. # Probably we will need to add something like an Enter_graphicsMode # method to the GraphicsMode API. In the meantime, the command's Enter # method has to initialize the graphicsMode object's attrs (which are # the graphics-related attrs of self, in the mixed case, but are # referred to as self.graphicsMode.attr so this will work in the split # case as well), which is a kluge.) #Initialize the flag often used in leftDrag methods of the subclasses #to avoid any attr errors. Note that this flag will often be reset in #self.reset_frag_vars() self.cursor_over_when_LMB_pressed = None #Initialize LMB_press_event self.LMB_press_event = None return def Enter_GraphicsMode(self): """ Things needed while entering the GraphicsMode (e.g. updating cursor, setting some attributes etc). @see: B{baseCommand.command_entered()} which calls this method """ _superclass.Enter_GraphicsMode(self) self.reset_drag_vars() self.ignore_next_leftUp_event = False # Set to True in leftDouble() and checked by the left*Up() # event handlers to determine whether they should ignore the # (second) left*Up event generated by the second LMB up/release # event in a double click. # == def _draw_this_test_instead(self): """ [private] Decide whether to draw a special test graphic in place of the model, and if so, which one. """ # TODO: move this test code into a specific test mode just for it, # so it doesn't clutter up or slow down this general-use mode. # # wware 060124 Embed Pyrex/OpenGL unit tests into the cad code # grantham 060207: # Set to 1 to see a small array of eight spheres. # Set to 2 to see the Large-Bearing model, but this is most effective if # the Large-Bearing has already been loaded normally into rotate mode #bruce 060209 set this from a debug_pref menu item, not a hardcoded flag TEST_PYREX_OPENGL = debug_pref("GLPane: TEST_PYREX_OPENGL", Choice([0,1,2])) # uncomment this line to set it in the old way: ## TEST_PYREX_OPENGL = 1 return TEST_PYREX_OPENGL def Draw_model(self): _superclass.Draw_model(self) # probably a noop -- actual model drawn below TEST_PYREX_OPENGL = self._draw_this_test_instead() if TEST_PYREX_OPENGL: # draw this test instead of the usual model from graphics.drawing.c_renderer import test_pyrex_opengl test_pyrex_opengl(TEST_PYREX_OPENGL) #bruce 090303 split this out (untested; # it did work long ago when first written, inlined here) # (revised again, 090310, still untested) pass else: # draw the usual model if self.bc_in_use is not None: #bruce 060414 self.bc_in_use.draw(self.o, 'fake dispdef kluge') self.o.assy.draw(self.o) return def Draw_other(self): _superclass.Draw_other(self) TEST_PYREX_OPENGL = self._draw_this_test_instead() if TEST_PYREX_OPENGL: pass else: #self.griddraw() if self.selCurve_List: self.draw_selection_curve() return # == def getMovablesForLeftDragging(self): """ Returns a list of movables that will be moved during this gaphics mode's left drag. In SelectChunks_GraphicsMode it is the selected movables in the assembly. However, some subclasses can override this method to provide a custom list of objects it wants to move during the left drag Example: In buildDna_GraphicsMode, it moving a dnaSegment axis chunk will move all the axischunk members of the dna segment and also its logical content chunks. @see: self._leftDrag_movables #attr @see: self._leftDown_preparation_for_dragging() @see: self.leftDragTranslation() @see:BuildDna_GraphicsMode.getMovablesForLeftDragging() """ movables = [] movables = self.win.assy.getSelectedMovables() contentChunksOfSelectedSegments = [] contentChunksOfSelectedStrands = [] selectedSegments = self.win.assy.getSelectedDnaSegments() selectedStrands = self.win.assy.getSelectedDnaStrands() for segment in selectedSegments: contentChunks = segment.get_all_content_chunks() contentChunksOfSelectedSegments.extend(contentChunks) for strand in selectedStrands: strandContentChunks = strand.get_all_content_chunks() contentChunksOfSelectedStrands.extend(strandContentChunks) #doing item in list' could be a slow operation. But this method will get #called only duting leftdown and not during leftDrag so it should be #okay -- Ninad 2008-04-08 for c in contentChunksOfSelectedSegments: if c not in movables: movables.append(c) #After appending appropriate content chunks of segment, do same thing for #strand content chunk list. #Remember that the contentChunksOfSelectedStrandscould contain chunks #that are already listed in contentChunksOfSelectedSegments for c in contentChunksOfSelectedStrands: if c not in movables: movables.append(c) return movables def reset_drag_vars(self): """ This resets (or initializes) per-drag instance variables, and is called in Enter and at beginning of leftDown. Subclasses can override this to add variables, but those methods should call this version too. @see L{SelectAtoms_GraphicsMode.reset_drag_vars} """ #IDEALLY(what we should impelment in future) -- #in each class it would reset only that class's drag vars #(the ones used by methods of that class, whether or not #those methods are only called in a subclass, but not the #ones reset by the superclass version of reset_drag_vars), #and in the subclass it would call the superclass version #rather than resetting all or mostly the same vars. #bruce 041124 split this out of Enter; as of 041130, # required bits of it are inlined into Down methods as bugfixes set_DRAG_STICKINESS_LIMIT_from_pref() self.cursor_over_when_LMB_pressed = None # <cursor_over_when_LMB_pressed> keeps track of what the cursor was over # when the LMB was pressed, which can be one of: # 'Empty Space' # 'Picked Atom' # 'Unpicked Atom' # 'Singlet' # 'Bond' # [later note: it is only used to compare to 'Empty Space'; # self.current_obj and other state variables are used instead of # checking for the other values; I don't know if the other values # are always correct. bruce 060721 comment] self.current_obj = None # current_obj is the object under the cursor when the LMB was # pressed. # [it is set to that obj by objectSetup, and set back to None by # some, but not all, mousedrag and mouseup methods. It's used by # leftDrag and leftUp to decide what to do, to what object. # When a drag_handler is in use, I think [bruce 060728] this will be # the drag_handler (not the selobj that it is for), but I'll still # have a separate self.drag_handler attr to also record that. One of # these is redundant, but this will most clearly separate old and # new code, while ensuring that if old code tests current_obj it # won't see a class it thinks it knows how to handle (even if I # sometimes use drag_handlers to drag old specialcase object # classes), and won't see None.(Other possibilities would be to not # have self.drag_handler at all, and/or to let this be the selobj # that a drag_handler was made for; these seem worse now, but I # mention them in case I need to switch to them.) # Maybe we'll need some uses of current_obj to filter it though a # self method which converts drag_handlers back to their underlying # objects (i.e. the selobj that they were made from or made for). # (Or have a .selobj attr.) #####@@@@@ [bruce 060728 comment]] self.current_obj_clicked = False # current_obj_clicked is used to determine if a lit up atom, singlet # or bond was picked (clicked)or not picked (dragged). It must be # set to False here so that a newly deposited atom doesn't pick # itself right away (although now this is the default behavior). # current_obj_clicked is set to True in *LeftDown() before it gets # dragged (if it does at all).If it is dragged, it is set to False # in *LeftDrag().*LeftUp() checks it to determine whether the object # gets picked or not. mark 060125. [bruce 060727 comments: it seems # to mean "was self.current_obj clicked, but not (yet) dragged", # and its basic point seems to be to let leftUp decide whether to # select the object,i.e. to not require all drags of objects to # select them.Note: it is set back to False only by class-specific # drag methods, not by leftDrag itself;similarly, it is used only # in class-specific mouseup methods, not by leftUp itself. # For drag_handlers, it looks like we should treat all # drag_handler uses as another object type,so we should set this in # the same way in the drag_handler-specific methods. Hmm, maybe we # want separate submethods like dragHandlerLeft*, just as for # Atom/Bond/Jig. #####@@@@@ # ] self.obj_doubleclicked = None # used by leftDouble() to determine the object that was double # clicked. # [bruce 060727 comments: This is the same object found by the first # click's leftDown -- mouse motion # is not checked for! That might be a bug -- if the mouse slipped # off this object, it might be betterto discard the entire drag (and # a stencil buffer test could check for this, without needing # glSelect). At least, this is always the correct object if anything # is.It is used in obj-class-specific leftDown methods, and assumed # to be an object of the right class (which seems ok, since # leftDouble uses isinstance on it to call one of those methods). # If a drag_handler is in use, this should probably be the # drag_handler itself(no current code compares it to any selobj -- # it only isinstances it to decide what drag code to run), but if # some Atoms/Bonds/Jigs ever use self as a drag_handler, our # isinstance tests on thiswill be problematic; we may need an "are # you acting as a drag_handler" method instead. #####@@@@@ # ] #bruce 060315 replaced drag_stickiness_limit_exceeded with # max_dragdist_pixels self.max_dragdist_pixels = 0 # used in mouse_within_stickiness_limit self.atoms_of_last_deleted_jig = [] # list of the real atoms connected to a deleted jig. # Used by jigLeftDouble() # to retreive the atoms of a recently deleted jig when double # clicking with 'Shift+Control'modifier keys pressed together. self.drag_handler = None #bruce 060725 return # == drag_handler event handler methods [bruce 060728]====================== # note: dragHandlerLeftDown() does not exist, since self.drag_handler is # only created by some other object's leftDown method def dragHandlerSetup(self, drag_handler, event): assert drag_handler is self.drag_handler #e clean up sometime? not sure #how self.cursor_over_when_LMB_pressed = 'drag_handler' # not presently used, #except for not being 'Empty Space' self.objectSetup(drag_handler) #bruce 060728 if not drag_handler.handles_updates(): self.w.win_update() # REVIEW (possible optim): can we (or some client code) make # gl_update_highlight cover this? [bruce 070626] return def dragHandlerDrag(self, drag_handler, event): ###e nim: for some kinds of them, we want to pick them in leftDown, ###then drag all picked objects, using self.dragto... try: method = getattr(drag_handler, 'DraggedOn', None) #e rename if method: old_selobj = self.o.selobj ###e args it might need: # - mode, for callbacks for things like update_selobj (which # needs a flag to avoid glselect) # - event, to pass to update_selobj (and maybe other callbacks # we offer)and ones it can callback for: # - offset, for convenient 3d motion of movable dragobjs # - maybe the mouseray, as two points? retval = method(event, self) # assume no update needed unless selobj changed #e so detect that... not sure if we need to, maybe set_selobj or #(probably) update_selobj does it? if old_selobj is not self.o.selobj: if 0 and env.debug(): print "debug fyi: selobj change noticed by " \ "dragHandlerDrag, %r -> %r" % (old_selobj , self.o.selobj) # WARNING: this is not a good enough detection, if any # outside code also does update_selobj and changes it, # since those changes won't be detected here. Apparently # this happens when the mouse moves back onto a real # selobj. Therefore I'm disabling this test for now. If # we need it, we'll need to store old_selobj in self, # between calls of this method. pass pass pass except: print_compact_traceback("bug: exception in dragHandlerDrag ignored:") return def dragHandlerLeftUp(self, drag_handler, event): try: method = getattr(drag_handler, 'ReleasedOn', None)#e rename if method: retval = method(self.o.selobj, event, self) #bruce 061120 changed args from (selobj, self) to #(selobj, event, self) [where self is the mode object] self.w.win_update() ##k not always needed, might be redundant, ##should let the handler decide ####@@@@ # REVIEW (possible optim): can we make gl_update_highlight # cover this? [bruce 070626] # lots of other stuff done by other leftUp methods here? ###@@@@ except: print_compact_traceback("bug: exception in dragHandlerLeftUp ignored:") pass def dragHandlerLeftDouble(self, drag_handler, event): # never called as of #070324; see also #testmode.leftDouble if env.debug(): print "debug fyi: dragHandlerLeftDouble is nim" return # == Selection Curve helper methods def select_2d_region(self, event): """ Start 2D selection of a region. """ if self.o.modkeys is None: self.start_selection_curve(event, START_NEW_SELECTION) if self.o.modkeys == 'Shift': self.start_selection_curve(event, ADD_TO_SELECTION) if self.o.modkeys == 'Control': self.start_selection_curve(event, SUBTRACT_FROM_SELECTION) if self.o.modkeys == 'Shift+Control': self.start_selection_curve(event, DELETE_SELECTION) return def start_selection_curve(self, event, sense): """ Start a new selection rectangle/lasso. """ self.selSense = sense # <selSense> is the type of selection. self.picking = True # <picking> is used to let continue_selection_curve() and # end_selection_curve() know # if we are in the process of defining/drawing a selection curve # or not, where: # True = in the process of defining selection curve # False = finished/not defining selection curve selCurve_pt, selCurve_AreaPt = \ self.o.mousepoints(event, just_beyond = 0.01) # mousepoints() returns a pair (tuple) of points (Numeric arrays # of x,y,z) # that lie under the mouse pointer, just beyond the near # clipping plane # <selCurve_pt> and in the plane of the center of view <selCurve_AreaPt>. self.selCurve_List = [selCurve_pt] # <selCurve_List> contains the list of points used to draw the # selection curve. The points lay in the plane parallel to the # screen, just beyond the front clipping plane, so that they are # alwaysinside the clipping volume. self.o.selArea_List = [selCurve_AreaPt] # <selArea_List> contains the list of points that define the # selection area. The points lay in the plane parallel to the # screen and pass through the center of the view. The list # is used by pickrect() and pickline() to make the selection. self.selCurve_StartPt = self.selCurve_PrevPt = selCurve_pt # <selCurve_StartPt> is the first point of the selection curve. # It is used by continue_selection_curve() to compute the net # distance between it and the current mouse position. # <selCurve_PrevPt> is the previous point of the selection curve. # It is used by continue_selection_curve() to compute the distance # between the current mouse position and the previous one. # Both <selCurve_StartPt> and <selCurve_PrevPt> are used by # basicMode.drawpick(). self.selCurve_length = 0.0 # <selCurve_length> is the current length (sum) of all the selection # curve segments. def continue_selection_curve(self, event): """ Add another line segment to the current selection curve. """ if not self.picking: return selCurve_pt, selCurve_AreaPt = self.o.mousepoints(event, 0.01) # The next point of the selection curve, where <selCurve_pt> is the # point just beyondthe near clipping plane and <selCurve_AreaPt> is # in the plane of the center of view. self.selCurve_List += [selCurve_pt] self.o.selArea_List += [selCurve_AreaPt] self.selCurve_length += vlen(selCurve_pt - self.selCurve_PrevPt) # add length of new line segment to <selCurve_length>. chord_length = vlen(selCurve_pt - self.selCurve_StartPt) # <chord_length> is the distance between the (first and # last/current) endpoints of the # selection curve. if self.selCurve_length < 2*chord_length: # Update the shape of the selection_curve. # The value of <selShape> can change back and forth between lasso # and rectangle as the user continues defining the selection curve. self.selShape = SELSHAPE_RECT else: self.selShape = SELSHAPE_LASSO self.selCurve_PrevPt = selCurve_pt self.o.gl_update() # REVIEW (possible optim): can gl_update_highlight be extended to # cover this? [bruce 070626] return def end_selection_curve(self, event): """ Close the selection curve and do the selection. """ #Don't select anything if the selection is locked. #@see: Select_GraphicsMode_MouseHelper_preMixin.selection_locked() if self.selection_locked(): self.selCurve_List = [] self.glpane.gl_update() return if not self.picking: return self.picking = False selCurve_pt, selCurve_AreaPt = self.o.mousepoints(event, 0.01) if self.selCurve_length / self.o.scale < 0.03: # didn't move much, call it a click #bruce 060331 comment: the behavior here is related to what it is # when we actually just click, # but it's implemented by different code -- for example, # delete_at_event in this case # as opposed to delete_atom_and_baggage in the other circumstance # (which both have similar # implementations of atom filtering and history messages, but are # in different files). It's not clear to me (reviewing this code) # whether the behavior should be (or is) identical; # whether or not it's identical, it would be better if common code # was used, to the extent that the behavior in these two # circumstances is supposed to be related. has_jig_selected = False if self.o.jigSelectionEnabled and self.jigGLSelect(event, self.selSense): has_jig_selected = True if not has_jig_selected: # NOTES about bugs in this code, and how to clean it up: # the following methods rely on findAtomUnderMouse, # even when highlighting is enabled (not sure why -- probably # a bad historical reason or oversight); this means they don't # work for clicking internal bonds (predicted bug), and they # don't work for jigs, which means the above jigGLSelect call # (which internally duplicates the GL_SELECT code used to # update selobj, and the picking effects of the following # depending on selSense) is presently necessary, whether # or not highlighting is enabled. # # TODO: This is a mess, but cleaning it up requires rewriting # all of the following at once: # - this code, and similar call of jigGLSelect in Move_GraphicsMode # - unpick_at_event and the 3 other methods below # - have them use selobj when highlighting is enabled # - if desired, have them update selobj even when highlighting # is disabled, as replacement for findAtomUnderMouse # which would work for jigs (basically equivalent to # existing code calling special jig select methods in those # cases, but without requiring duplicated code) # - this would permit completely removing the methods # jigGLSelect and get_jig_under_cursor from this class. # [bruce 080917 comment] if self.selSense == SUBTRACT_FROM_SELECTION: self.o.assy.unpick_at_event(event) elif self.selSense == ADD_TO_SELECTION: self.o.assy.pick_at_event(event) elif self.selSense == START_NEW_SELECTION: self.o.assy.onlypick_at_event(event) elif self.selSense == DELETE_SELECTION: self.o.assy.delete_at_event(event) else: print 'Error in end_selection_curve(): Invalid selSense=', self.selSense # Huaicai 1/29/05: to fix zoom messing up selection bug # In window zoom mode, even for a big selection window, the # selCurve_length/scale could still be < 0.03, so we need clean # selCurve_List[] to release the rubber band selection window. One # problem is its a single pick not as user expect as area pick else: self.selCurve_List += [selCurve_pt] # Add the last point. self.selCurve_List += [self.selCurve_List[0]] # Close the selection curve. self.o.selArea_List += [selCurve_AreaPt] # Add the last point. self.o.selArea_List += [self.o.selArea_List[0]] # Close the selection area. self.o.shape = SelectionShape(self.o.right, self.o.up, self.o.lineOfSight) # Create the selection shape object. ## eyeball = (-self.o.quat).rot(V(0,0,6*self.o.scale)) - self.o.pov eyeball = self.o.eyeball() #bruce 080912 change, should be equivalent if self.selShape == SELSHAPE_RECT : # prepare a rectangle selection self.o.shape.pickrect(self.o.selArea_List[0], selCurve_AreaPt, -self.o.pov, self.selSense, \ eye = (not self.o.ortho) and eyeball) else: # prepare a lasso selection self.o.shape.pickline(self.o.selArea_List, -self.o.pov, self.selSense, \ eye = (not self.o.ortho) and eyeball) self.o.shape.select(self.o.assy) # do the actual selection. self.o.shape = None #Call the API method that decides whether to select/deselect anything #else (e.g. pick a DnaGroup if all its content is selected) self.end_selection_from_GLPane() self.selCurve_List = [] # (for debugging purposes, it's sometimes useful to not reset # selCurve_List here, # so you can see it at the same time as the selection it caused.) self.w.win_update() # REVIEW (possible optim): can we make gl_update_highlight # (or something like it) cover this? # Note that both the curve itself, and what's selected, # are changing. [bruce 070626] # == End of Selection Curve helper methods def get_obj_under_cursor(self, event): # docstring appears wrong """ Return the object under the cursor. Only atoms, singlets and bonds are returned. Returns None for all other cases, including when a bond, jig or nothing is under the cursor. [warning: this docstring appears wrong.] @attention: This method was originally from class SelectAtoms_GraphicsMode. See code comment for details """ #@ATTENTION: This method was originally from class SelectAtoms_GraphicsMode. # It was mostly duplicated (with some changes) in SelectChunks_GraphicsMode # when that mode started permitting highlighting. # The has been modified and moved to selectMode class so that both # SelectAtoms_GraphicsMode and SelectChunks_GraphicsMode can use it -Ninad 2007-10-15 #bruce 060331 comment: this docstring appears wrong, since the code # looks like it can return jigs. #bruce 070322 note: this will be overridden (extended) in testmode, #which will sometimes return a "background object" # rather than None, in order that leftDown can be handled by # background_object.leftClick in the same way as for other #drag_handler-returning objects. # ### WARNING: this is slow, and redundant with highlighting -- ### only call it on mousedown or mouseup, never in move or drag. # [true as of 060726 and before; bruce 060726 comment] # It may be that it's not called when highlighting is on, and it has no # excuse to be, but I suspect it is anyway. # [bruce 060726 comment] if self.command.isHighlightingEnabled() and not self._suppress_highlighting: self.update_selatom(event) #bruce 041130 in case no update_selatom #happened yet # update_selatom() updates self.o.selatom and self.o.selobj. # self.o.selatom is either a real atom or a singlet [or None]. # self.o.selobj can be a bond, and is used in leftUp() to determine # if a bond was selected. # Warning: if there was no GLPane repaint event (i.e. paintGL call) # since the last bareMotion,update_selatom can't make selobj/selatom # correct until the next time paintGL runs. # Therefore, the present value might be out of date -- but it does # correspond to whateverhighlighting is on the screen, so whatever # it is should not be a surprise to the user,so this is not too # bad -- the user should wait for the highlighting to catch up to # the mouse motion before pressing the mouse. [bruce 050705 comment] # [might be out of context, copied from other code] obj = self.o.selatom # a "highlighted" atom or singlet if obj is None and self.o.selobj: obj = self.o.selobj # a "highlighted" bond # [or anything else, except Atom or Jig -- i.e. a #general/drag_handler/Drawable selobj [bruce 060728]] if env.debug(): # I want to know if either of these things occur #-- I doubt they do, but I'm not sure about Jigs [bruce 060728] # (this does happen for Jigs, see below) if isinstance(obj, Atom): print "debug fyi: likely bug: selobj is Atom but not in selatom: %r" % (obj,) elif isinstance(obj, Jig): print "debug fyi: selobj is a Jig in get_obj_under_cursor (comment is wrong), for %r" % (obj,) # I suspect some jigs can occur here # (and if not, we should put them here #-- I know of no excuse for jig highlighting # to work differently than for anything else) [bruce 060721] # update 070413: yes, this happens (e.g. select some # atoms and an rmotor jig, then drag the jig). pass if obj is None: # a "highlighted" jig [i think this comment is #misleading, it might really be nothing -- bruce 060726] obj = self.get_jig_under_cursor(event) # [this can be slow -- bruce comment 070322] if env.debug(): ####### print "debug fyi: get_jig_under_cursor returns %r" % (obj,) # [bruce 060721] pass else: # No hover highlighting obj = self.o.assy.findAtomUnderMouse(event, self.command.isWaterSurfaceEnabled(), singlet_ok = True) # Note: findAtomUnderMouse() only returns atoms and singlets, not # bonds or jigs. # This means that bonds can never be selected when highlighting # is turned off. # [What about jigs? bruce question 060721] return obj def update_selobj(self, event): #bruce 050610 """ Keep glpane.selobj up-to-date, as object under mouse, or None (whether or not that kind of object should get highlighted). Return True if selobj is already updated when we return, or False if that will not happen until the next paintGL. Warning: if selobj needs to change, this routine does not change it (or even reset it to None); it only sets flags and does gl_update, so that paintGL will run soon and will update it properly, and will highlight it if desired ###@@@ how is that controlled? probably by some statevar in self, passed to gl flag? This means that old code which depends on selatom being up-to-date must do one of two things: - compute selatom from selobj, whenever it's needed; - hope that paintGL runs some callback in this mode when it changes selobj, which updates selatom and outputs whatever statusbar message is appropriate. ####@@@@ doit... this is not yet fully ok. @attention: This method was originally from class SelectAtoms_GraphicsMode. See code comment for details """ #@ATTENTION: This method was originally from class SelectAtoms_GraphicsMode. # It was mostly duplicated (with some changes) in SelectChunks_GraphicsMode # when that mode started permitting highlighting. # The has been modified and moved to selectMode class so that both # SelectAtoms_GraphicsMode and SelectChunks_GraphicsMode can use it -Ninad 2007-10-12 #e see also the options on update_selatom; # probably update_selatom should still exist, and call this, and #provide those opts, and set selatom from this, # but see the docstring issues before doing this ####@@@@ # bruce 050610 new comments for intended code (#e clean them up and # make a docstring): # selobj might be None, or might be in stencil buffer. # Use that and depthbuffer to decide whether redraw is needed to look # for a new one. # Details: if selobj none, depth far or under water is fine, any other # depth means look for new selobj (set flag, glupdate). if selobj not # none, stencil 1 means still same selobj (if no stencil buffer, have to # guess it's 0); else depth far or underwater means it's now None #(repaint needed to make that look right, but no hittest needed) # and another depth means set flag and do repaint (might get same selobj #(if no stencil buffer or things moved)or none or new one, won't know # yet, doesn't matter a lot, not sure we even need to reset it to none # here first). # Only goals of this method: maybe glupdate, if so maybe first set flag, # and maybe set selobj none, but prob not(repaint sets new selobj, maybe # highlights it).[some code copied from modifyMode] if debug_update_selobj_calls: print_compact_stack("debug_update_selobj_calls: ") glpane = self.o # If animating or zooming/panning/rotating with the MMB, # do not hover highlight anything. For more info about is_animating, # see GLPane.animateToView(). [mark 060404] if self.o.is_animating or \ (self.o.button == "MMB" and not getattr(self, '_defeat_update_selobj_MMB_specialcase', False)): return # BUG: returning None violates this method's API (according to # docstring), but this apparently never mattered until now, # and it's not obvious how to fix it (probably to be correct # requires imitating the conditional set_selobj below); so # instead I'll just disable it in the new case that triggers it, # using _defeat_update_selobj_MMB_specialcase. # [bruce 070224] wX = event.pos().x() wY = glpane.height - event.pos().y() selobj = orig_selobj = glpane.selobj if selobj is not None: if glpane.stencilbits >= 1: # optimization: fast way to tell if we're still over the same # object as last time. (Warning: for now glpane.stencilbits is 1 # even when true number of bits is higher; should be easy to fix # when needed.) # # WARNING: a side effect of QGLWidget.renderText is to clear the # stencil buffer, which defeats this optimization. This has been # true since at least Qt 4.3.5 (which we use as of now), but was # undocumented until Qt 4.4. This causes extra redraws whenever # renderText is used when drawing a frame and the mouse # subsequently moves within one highlighted object, # but should not cause an actual bug unless it affects the # occurrence of a bug in other code. [bruce 081211 comment] # # Note: double buffering applies only to the color buffer, # not the stencil or depth buffers, which have only one copy. # Therefore, this code would not work properly if run during # paintGL (even if GL_READ_BUFFER was set to GL_FRONT), since # paintGL might be modifying the buffer it reads. The setting # of GL_READ_BUFFER should have no effect on this code. # [bruce 081211 comment, based on Russ report of OpenGL doc] stencilbit = glReadPixelsi(wX, wY, 1, 1, GL_STENCIL_INDEX)[0][0] # Note: if there's no stencil buffer in this OpenGL context, # this gets an invalid operation exception from OpenGL. # And by default there isn't one -- it has to be asked for # when the QGLWidget is initialized. # stencilbit tells whether the highlighted drawing of selobj # got drawn at this point on the screen (due to both the shape # of selobj, and to the depth buffer contents when it was drawn) # but might be 0 even if it was drawn (due to the renderText # effect mentioned above). else: stencilbit = 0 # the correct value is "don't know"; 0 is conservative # maybe todo: collapse this code if stencilbit not used below; # and/or we might need to record whether we used this # conservative value if stencilbit: return True # same selobj, no need for gl_update to change highlighting # We get here for no prior selobj, # or for a prior selobj that the mouse has moved off of the visible/highlighted part of, # or for a prior selobj when we don't know whether the mouse moved off of it or not # (due to lack of a stencil buffer, i.e. very limited graphics card or OpenGL implementation). # # We have to figure out selobj afresh from the mouse position (using depth buffer and/or GL_SELECT hit-testing). # It might be the same as before (if we have no stencil buffer, or if it got bigger or moved) # so don't set it to None for now (unless we're sure from the depth that it should end up being None) -- # let it remain the old value until the new one (perhaps None) is computed during paintGL. # # Specifically, if this method can figure out the correct new setting of glpane.selobj (None or some object), # it should set it (###@@@ or call a setter? neither -- let end-code do this) and set new_selobj to that # (so code at method-end can repaint if new_selobj is different than orig_selobj); # and if not, it should set new_selobj to instructions for paintGL to find selobj (also handled by code at method-end). ###@@@ if we set it to None, and it wasn't before, we still have to redraw! ###@@@ ###e will need to fix bugs by resetting selobj when it moves or view changes etc (find same code as for selatom). wZ = glReadPixelsf(wX, wY, 1, 1, GL_DEPTH_COMPONENT)[0][0] # depth (range 0 to 1, 0 is nearest) of most recent drawing at this mouse position new_selobj_unknown = False # following code should either set this True or set new_selobj to correct new value (None or an object) if wZ >= GL_FAR_Z: ## Huaicai 8/17/05 for blue sky plane z value # far depth (this happens when no object is touched) new_selobj = None else: #For commands like SelectChunks_Command, the 'water surface' #is not defined. if self.command.isWaterSurfaceEnabled(): # compare to water surface depth cov = - glpane.pov # center_of_view (kluge: we happen to know this is where the water surface is drawn) try: junk, junk, cov_depth = gluProject( cov[0], cov[1], cov[2] ) except: print_compact_traceback( "gluProject( cov[0], cov[1], cov[2] ) exception ignored, for cov == %r: " % (cov,) ) cov_depth = 2 # too deep to matter (depths range from 0 to 1, 0 is nearest to screen) water_depth = cov_depth if wZ >= water_depth: #print "behind water: %r >= %r" % (wZ , water_depth) new_selobj = None # btw, in contrast to this condition for a new selobj, an existing one will # remain selected even when you mouseover the underwater part (that's intentional) else: # depth is in front of water new_selobj_unknown = True else: new_selobj_unknown = True if new_selobj_unknown: # Only the next paintGL call can figure out the selobj (in general), # so set glpane.glselect_wanted to the command to do that and the # necessary info for doing it. # Note: it might have been set before and not yet used; # if so, it's good to discard that old info, as we do. glpane.glselect_wanted = (wX, wY, wZ) # mouse pos, depth ###e and soon, instructions about whether to highlight selobj # based on its type (as predicate on selobj) ###e should also include current count of number of times # glupdate was ever called because model looks different, # and inval these instrs if that happens again before they # are used (since in that case wZ is no longer correct) # [addendum, bruce 081230: this is nonmodular -- we should call # a glpane method to set that, and make it private.] # don't change glpane.selobj (since it might not even need to # change) (ok??#k) -- the next paintGL will do that -- # UNLESS the current mode wants us to change it # [new feature, bruce 061218, perhaps a temporary kluge, but helps # avoid a logic bug in this code, experienced often in testmode # due to its slow redraw] # # Note: I'm mostly guessing that this should be found in # (and unique to) graphicsMode rather than currentCommand, # in spite of being set only in testmode by current code. # That does make this code simpler, since graphicsMode is self. # [bruce 071010, same comment and change done in both duplications # of this code, and in other places] if hasattr(self, 'UNKNOWN_SELOBJ'): # for motivation, see comment above, dated 061218 glpane.selobj = getattr(self, 'UNKNOWN_SELOBJ') ## print "\n*** changed glpane.selobj from %r to %r" % (orig_selobj, glpane.selobj) #bruce 081230 part of fix for bug 2964 -- repaint the status bar # now, to work around a Qt or Mac OS bug (of unknown cause) which # otherwise might prevent it from being repainted later when # we store a message about a new selobj (in set_selobj or at the # end of paintGL). We need both lines to make sure this actually # repaints it now, even if the prior message was " " or "". env.history.statusbar_msg("") env.history.statusbar_msg(" ") glpane.gl_update_for_glselect() else: # it's known (to be a specific object or None) if new_selobj is not orig_selobj: # this is the right test even if one or both of those is None. # (Note that we never figure out a specific new_selobj, above, # except when it's None, but that might change someday # and this code can already handle that.) glpane.set_selobj( new_selobj, "Select mode") #e use setter func, if anything needs to observe changes to # this? or let paintGL notice the change (whether it or elseone # does it) and report that? # Probably it's better for paintGL to report it, so it doesn't # happen too often or too soon! # And in the glselect_wanted case, that's the only choice, # so we needed code for that anyway. # Conclusion: no external setter func is required; maybe glpane # has an internal one and tracks prior value. glpane.gl_update_highlight() # this might or might not highlight that selobj ###e need to tell it how to decide?? # someday -- we'll need to do this in a callback when selobj is set: ## self.update_selatom(event, msg_about_click = True) # but for now, I removed the msg_about_click option, since it's no longer used, # and can't yet be implemented correctly (due to callback issue when selobj # is not yet known), and it tried to call a method defined only in depositMode, # describe_leftDown_action, which I'll also remove or comment out. [bruce 071025] return not new_selobj_unknown # from update_selobj def update_selatom(self, event, singOnly = False, resort_to_prior = True): """ THE DEFAULT IMPLEMENTATION OF THIS METHOD DOES NOTHING. Subclasses should override this method as needed. @see: SelectAtoms_GraphicsMode.update_selatom for documentation. @see: selectMode.get_obj_under_cursor """ # REVIEW: are any of the calls to this in selectMode methods, # which do nothing except in subclasses of SelectAtoms_GraphicsMode, # indications that the code they're in doesn't make sense except # in such subclasses? [bruce 071025 question] #I am not sure what you mean above. Assuming you meant: Is there a #method in this class selectMode, that calls this method # (i.e. calls selectMode.update_selatom) #Yes, there is a method self.selectMode.get_obj_under_cursor that calls #this method and thats why I kept a default implemetation that does #nothing -- Ninad 2007-11-16 # No, I meant: is the fact that that call (for example) does nothing # (when not using a subclass of SelectAtoms_GraphicsMode) # a sign that some refactoring is desirable, which would (among # other effects) end up moving all calls of update_selatom into # subclasses of SelectAtoms* classes? [bruce 080917 reply] pass def get_jig_under_cursor(self, event): """ Use the OpenGL picking/selection to select any jigs. Restore the projection and modelview matrices before returning. """ ####@@@@ WARNING: The original code for this, in GLPane, has been ### duplicated and slightly modified # in at least three other places (search for glRenderMode to find them). # TWO OF THEM ARE METHODS IN THIS CLASS! This is bad; common code # should be used. Furthermore, I suspect it's sometimes needlessly # called more than once per frame; # that should be fixed too. [bruce 060721 comment] # BUG: both methods like this in this class are wrong when left/right # stereo is enabled. Ideally they should be removed. # For more info, see similar comment in jigGLSelect. # [bruce 080917 comment] if not self.o.jigSelectionEnabled: return None wX = event.pos().x() wY = self.o.height - event.pos().y() gz = self._calibrateZ(wX, wY) # note: this redraws the entire model if gz >= GL_FAR_Z: # Empty space was clicked--This may not be true for translucent face [Huaicai 10/5/05] return None pxyz = A(gluUnProject(wX, wY, gz)) pn = self.o.out pxyz -= 0.0002 * pn dp = - dot(pxyz, pn) # Save project matrix before it's changed glMatrixMode(GL_PROJECTION) glPushMatrix() current_glselect = (wX, wY, 3, 3) self.o._setup_projection( glselect = current_glselect) glSelectBuffer(self.o.SIZE_FOR_glSelectBuffer) glRenderMode(GL_SELECT) glInitNames() glMatrixMode(GL_MODELVIEW) glPushMatrix() # Save modelview matrix before it's changed assy = self.o.assy try: glClipPlane(GL_CLIP_PLANE0, (pn[0], pn[1], pn[2], dp)) glEnable(GL_CLIP_PLANE0) def func(): assy.draw(self.o) self.o._call_func_that_draws_model( func, drawing_phase = 'main') self.o.call_Draw_after_highlighting(self, pickCheckOnly = True) glDisable(GL_CLIP_PLANE0) except: # BUG: this except clause looks wrong. It doesn't return, # therefore it results in two calls of glRenderMode(GL_RENDER). # [bruce 080917 comment] # Restore Model view matrix, select mode to render mode msg = "exception in code around mode.Draw_after_highlighting() " \ "during GL_SELECT; ignored; restoring modelview matrix: " print_compact_traceback(msg + ": ") glPopMatrix() glRenderMode(GL_RENDER) else: # Restore Model view matrix glPopMatrix() # Restore project matrix and set matrix mode to ModelView glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glFlush() hit_records = list(glRenderMode(GL_RENDER)) for (near,far,names) in hit_records: # see example code, renderpass.py if debug_flags.atom_debug and 0: print "hit record: near,far,names:",near,far,names if 1: # partial workaround for bug 1527. This can be removed once that bug (in drawer.py) # is properly fixed. This exists in two places -- GLPane.py and modes.py. [bruce 060217] if names and names[-1] == 0: print "%d(m) partial workaround for bug 1527: removing 0 from end of namestack:" % env.redraw_counter, names names = names[:-1] if names: obj = assy.object_for_glselect_name(names[-1]) #self.glselect_dict[id(obj)] = obj # now these can be rerendered specially, at the end of mode.Draw if isinstance(obj, Jig): return obj return None # from get_jig_under_cursor # == #bruce 060414 move selatoms optimization (won't be enabled by default in A7) # (very important for dragging atomsets that are part of big chunks but not # all of them) # UNFINISHED -- still needs: # - failsafe for demolishing bc if drag doesn't end properly # - disable undo cp's when bc exists (or maybe during any drag of any kind # in any mode) # - fix checkparts assertfail (or disable checkparts) when bc exists and # atom_debug set # - not a debug pref anymore # - work for single atom too (with its baggage, implying all bps for real # atoms in case chunk rule for that matters) # - (not directly related:) # review why reset_drag_vars is only called in SelectAtoms_GraphicsMode but the # vars are used in the superclass selectMode # [later 070412: maybe because the methods calling it are themselves only # called from SelectAtoms_GraphicsMode? it looks that way anyway] # [later 070412: ###WARNING: in Qt3, reset_drag_vars is defined in # SelectAtoms_GraphicsMode, but in Qt4, it's defined in selectMode.] # bc_in_use = None # None, or a BorrowerChunk in use for the current drag, # which should be drawn while in use, and demolished when the drag #is done (without fail!) #####@@@@@ need failsafe _reusable_borrowerchunks = [] # a freelist of empty BorrowerChunks not now # being used (a class variable, not instance # variable) def allocate_empty_borrowerchunk(self): """ Someone wants a BorrowerChunk; allocate one from our freelist or a new one """ while self._reusable_borrowerchunks: # try to use one from this list bc = self._reusable_borrowerchunks.pop() if bc.assy is self.o.assy: # bc is still suitable for reuse return bc else: # it's not bc.destroy() continue pass # list is empty, just return a new one from model.BorrowerChunk import BorrowerChunk return BorrowerChunk(self.o.assy) def deallocate_borrowerchunk(self, bc): bc.demolish() # so it stores nothing now, but can be reused later; #repeated calls must be ok self._reusable_borrowerchunks.append(bc) def deallocate_bc_in_use(self): """ If self.bc_in_use is not None, it's a BorrowerChunk and we need to deallocate it -- this must be called at the end of any drag which might have allocated it. """ if self.bc_in_use is not None: self.deallocate_borrowerchunk( self.bc_in_use ) self.bc_in_use = None return def mouse_within_stickiness_limit(self, event, drag_stickiness_limit_pixels): #bruce 060315 reimplemented this """ Check if mouse has never been dragged beyond <drag_stickiness_limit_pixels> while holding down the LMB (left mouse button) during the present drag. Return True if it's never exceeded this distance from its starting point, False if it has. Distance is measured in pixels. Successive calls need not pass the same value of the limit. """ try: xy_orig = self.LMB_press_pt_xy except: # This can happen when leftDown was never called before leftDrag (there's a reported traceback bug about it, # an AttributeError about LMB_press_pt, which this attr replaces). # In that case pretend the mouse never moves outside the limit during this drag. return True # this would be an incorrect optimization: ## if self.max_dragdist_pixels > drag_stickiness_limit_pixels: ## return False # optimization -- but incorrect, in case future callers plan to pass a larger limit!! xy_now = (event.pos().x(), event.pos().y()) # must be in same coordinates as self.LMB_press_pt_xy in leftDown dist = vlen(A(xy_orig) - A(xy_now)) #e could be optimized (e.g. store square of dist), probably doesn't matter self.max_dragdist_pixels = max( self.max_dragdist_pixels, dist) return self.max_dragdist_pixels <= drag_stickiness_limit_pixels def mouse_exceeded_distance(self, event, pixel_distance): """ Check if mouse has been moved beyond <pixel_distance> since the last mouse 'move event'. Return True if <pixel_distance> is exceeded, False if it hasn't. Distance is measured in pixels. """ try: xy_last = self.xy_last except: self.xy_last = (event.pos().x(), event.pos().y()) return False xy_now = (event.pos().x(), event.pos().y()) dist = vlen(A(xy_last) - A(xy_now)) #e could be optimized (e.g. store square of dist), probably doesn't matter self.xy_last = xy_now return dist > pixel_distance #==HIGHLIGHTING =========================================================== def selobj_highlight_color(self, selobj): """ [GraphicsMode API method] If we'd like this selobj to be highlighted on mouseover (whenever it's stored in glpane.selobj), return the desired highlight color. If we'd prefer it not be highlighted (though it will still be stored in glpane.selobj and prevent any other objs it obscures from being stored there or highlighted), return None. @param selobj: The object in the GLPane to be highlighted @TODO: exceptions are ignored and cause the default highlight color to be used ..should clean that up sometime """ # Mode API method originally by bruce 050612. # This has been refactored further and moved to the superclass # from SelectAtoms_GraphicsMode. -- Ninad 2007-10-14 if not self.command.isHighlightingEnabled(): return None #####@@@@@ if self.drag_handler, we should probably let it # override all this # (so it can highlight just the things it might let you # DND its selobj to, for example), # even for Atom/Bondpoint/Bond/Jig, maybe even when not # self.command.isHighlightingEnabled(). [bruce 060726 comment] if isinstance(selobj, Atom): return self._getAtomHighlightColor(selobj) elif isinstance(selobj, Bond): return self._getBondHighlightColor(selobj) elif isinstance(selobj, Jig): return self._getJigHighlightColor(selobj) else: return self._getObjectDefinedHighlightColor(selobj) def _getAtomHighlightColor(self, selobj): """ Return the Atom highlight color. Default implementation returns 'None' Overridden in subclasses. @return: Highlight color of the object (Atom or Singlet) """ return None def _getBondHighlightColor(self, selobj): """ Return the Bond highlight color @return: Highlight color of the object (Bond) The default implementation returns 'None' . Subclasses should override this method if they need bond highlight color. """ return None def _getJigHighlightColor(self, selobj): """ Return the Jig highlight color. Subclasses can override this method. @return: Highlight color of the Jig """ assert isinstance(selobj, Jig) if not self.o.jigSelectionEnabled: #mark 060312. # jigSelectionEnabled set from GLPane context menu. return None if self.o.modkeys == 'Shift+Control': return env.prefs[deleteBondHighlightColor_prefs_key] else: return env.prefs[bondHighlightColor_prefs_key] def _getObjectDefinedHighlightColor(self, selobj): """ Return the highlight color defined by the object itself. """ # Let the object tell us its highlight color, if it's not one we have # a special case for here (and if no drag_handler told us instead # (nim, above)). # Note: this color will be passed to selobj.draw_in_abs_coords when # selobj is asked to draw its highlight; but even if that method plans # to ignore that color arg, # this method better return a real color (or at least not None or # (maybe) anything false), # otherwise GLPane will decide it's not a valid selobj and not # highlight it at all. # (And in that case, will a context menu work on it # (if it wasn't nim for that kind of selobj)? I don't know.) # [bruce 060722 new feature; revised comment 060726] method = getattr(selobj, 'highlight_color_for_modkeys', None) if method: return method(self.o.modkeys) # Note: this API might be revised; it only really makes sense # if the mode created the selobj to fit its # current way of using modkeys, perhaps including not only its # code but its active-tool state. #e Does it make sense to pass the drag_handler, even if we let it # override this? # Yes, since it might like to ask the object (so it needs an API # to do that), or let the obj decide, # based on properties of the drag_handler. #e Does it make sense to pass the obj being dragged without a # drag_handler? # Yes, even more so. Not sure if that's always called the same #thing, depending on its type. # If not, we can probably just kluge it by self.this or self.that, # if they all get reset each drag. ###@@@ print "unexpected selobj class in mode.selobj_highlight_color:", selobj # Return black color so that an error becomes more obvious #(bruce comments) return black def _calibrateZ(self, wX, wY): # by huaicai; bruce 071013 moved this here from GraphicsMode """ Because of translucent plane drawing or other special drawing, the depth value may not be accurate. We need to redraw them so we'll have correct Z values. """ # REVIEW: why does this not need to clear the depth buffer? # If caller needs to, that needs to be documented. # [bruce 080917 comment] glMatrixMode(GL_MODELVIEW) glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE) if self.o.call_Draw_after_highlighting(self, pickCheckOnly = True): # Only when we have translucent planes drawn def func(): self.o.assy.draw(self.o) self.o._call_func_that_draws_model( func, drawing_phase = 'main') pass wZ = glReadPixelsf(wX, wY, 1, 1, GL_DEPTH_COMPONENT) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) return wZ[0][0] def jigGLSelect(self, event, selSense): # by huaicai; bruce 071013 moved this here from GraphicsMode """ Use the OpenGL picking/selection to select any jigs. Restore the projection and modelview matrices before returning. """ ## [Huaicai 9/22/05]: Moved it from selectMode class, so it can be called in move mode, which ## is asked for by Mark, but it's not intended for any other mode. # [since then I moved it back here, since move == modify is a subclass of this -- bruce 071013] # ### WARNING: The original code for this, in GLPane, has been duplicated and slightly modified # in at least three other places (search for glRenderMode to find them). TWO OF THEM ARE METHODS # IN THIS CLASS! This is bad; common code # should be used. Furthermore, I suspect it's sometimes needlessly called more than once per frame; # that should be fixed too. [bruce 060721 comment] # BUG: both methods like this in this class are wrong when left/right # stereo is enabled. The best fix would be to remove them completely, # since they should never have existed at all, since general highlighting # code handles jigs. Unfortunately removing them is hard -- # for how to do it, see comment near the call of this method # in this file. [bruce 080917 comment] # this method has two calls, one in this file and one in commands/Move/Move_GraphicsMode # [bruce 090227 comment] wX = event.pos().x() wY = self.o.height - event.pos().y() gz = self._calibrateZ(wX, wY) # note: this sometimes redraws the entire model if gz >= GL_FAR_Z: # Empty space was clicked--This may not be true for translucent face [Huaicai 10/5/05] return False pxyz = A(gluUnProject(wX, wY, gz)) pn = self.o.out pxyz -= 0.0002*pn dp = - dot(pxyz, pn) # Save project matrix before it's changed glMatrixMode(GL_PROJECTION) glPushMatrix() current_glselect = (wX,wY,3,3) self.o._setup_projection( glselect = current_glselect) glSelectBuffer(self.o.SIZE_FOR_glSelectBuffer) glRenderMode(GL_SELECT) glInitNames() glMatrixMode(GL_MODELVIEW) glPushMatrix() ## Save model/view matrix before it's changed assy = self.o.assy try: glClipPlane(GL_CLIP_PLANE0, (pn[0], pn[1], pn[2], dp)) glEnable(GL_CLIP_PLANE0) def func(): assy.draw(self.o) self.o._call_func_that_draws_model( func, drawing_phase = 'main') self.o.call_Draw_after_highlighting(self, pickCheckOnly = True) glDisable(GL_CLIP_PLANE0) except: # Restore Model view matrix, select mode to render mode glPopMatrix() glRenderMode(GL_RENDER) msg = "exception in drawing during GL_SELECT, ignored; restoring modelview matrix" print_compact_traceback(msg + ": ") else: # Restore Model view matrix glPopMatrix() # Restore project matrix and set matrix mode to Model/View glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glFlush() hit_records = list(glRenderMode(GL_RENDER)) if debug_flags.atom_debug and 0: print "%d hits" % len(hit_records) for (near,far,names) in hit_records: # see example code, renderpass.py if 1: # partial workaround for bug 1527. This can be removed once that bug (in drawer.py) # is properly fixed. This exists in two places -- GLPane.py and modes.py. [bruce 060217] if names and names[-1] == 0: print "%d(m) partial workaround for bug 1527: removing 0 from end of namestack:" % env.redraw_counter, names names = names[:-1] if names: obj = assy.object_for_glselect_name(names[-1]) #self.glselect_dict[id(obj)] = obj # now these can be rerendered specially, at the end of mode.Draw if isinstance(obj, Jig): if selSense == SUBTRACT_FROM_SELECTION: #Ctrl key, unpick picked if obj.picked: obj.unpick() elif selSense == ADD_TO_SELECTION: #Shift key, Add pick if not obj.picked: obj.pick() else: #Without key press, exclusive pick assy.unpickall_in_GLPane() # was: unpickparts, unpickatoms [bruce 060721] if not obj.picked: obj.pick() return True return False # from jigGLSelect def toggleJigSelection(self): self.o.jigSelectionEnabled = not self.o.jigSelectionEnabled pass # end of class Select_basicGraphicsMode # == class Select_GraphicsMode(Select_basicGraphicsMode): """ """ # Imitate the init and property code in GraphicsMode, but don't inherit it. # (Remember to replace all the occurrences of its superclass with our own.) # (When this is later merged with its superclass, most of this can go away # since we'll then be inheriting GraphicsMode here.) # (Or can we inherit GraphicsMode *after* the main superclass, and not have # to do some of this? I don't know. ### find out! [I think I did this in PanLikeMode.] # At least we'd probably still need this __init__ method. # If this pattern works, then in *our* subclasses we'd instead post-inherit # this class, Select_GraphicsMode.) def __init__(self, command): self.command = command glpane = self.command.glpane Select_basicGraphicsMode.__init__(self, glpane) return # (the rest would come from GraphicsMode if post-inheriting it worked, # or we could split it out of GraphicsMode as a post-mixin to use there # and here) def _get_commandSequencer(self): return self.command.commandSequencer commandSequencer = property(_get_commandSequencer) def set_cmdname(self, name): self.command.set_cmdname(name) return pass # end
NanoCAD-master
cad/src/commands/Select/Select_GraphicsMode.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ selectMode.py -- Select Chunks and Select Atoms modes, also used as superclasses for some other modes @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. - Ninad 070216 moved selectAtomsMode and selectMolsMode out of selectMode.py -- Update 2008-08-22: class selectMolsMode and SelectAtomsMode have been deprecated and are replaced by SelectChunks_Command and SelectAtoms_Command(the change was made perhaps sometime last year) """ from commands.Select.Select_Command import Select_basicCommand from commands.Select.Select_GraphicsMode import Select_basicGraphicsMode from command_support.modes import anyMode class selectMode(Select_basicCommand, Select_basicGraphicsMode, anyMode): """ """ # NOTE: Inheriting from superclass anymode is harmless. It is done as # Not sure whether it's needed. It is put in case there is an isinstance # assert in other code # Ignore it for now, because it will go away when everything is split and # we simplify these split modes to have only the main two classes. def __init__(self, commandSequencer): glpane = commandSequencer.assy.glpane Select_basicCommand.__init__(self, commandSequencer) # was just basicCommand in original Select_basicGraphicsMode.__init__(self, glpane) # was just basicGraphicsMode in original return # (the rest would come from basicMode if post-inheriting it worked, # or we could split it out of basicMode as a post-mixin to use there and here) def __get_command(self): return self command = property(__get_command) def __get_graphicsMode(self): return self graphicsMode = property(__get_graphicsMode)
NanoCAD-master
cad/src/commands/Select/selectMode.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ StereoProperties_PropertyManager.py The StereoProperties_PropertyManager class provides a Property Manager for the Stereo View command. @author: Piotr @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ import foundation.env as env from PyQt4.Qt import SIGNAL from PM.PM_Slider import PM_Slider from PM.PM_GroupBox import PM_GroupBox from PM.PM_ComboBox import PM_ComboBox from PM.PM_CheckBox import PM_CheckBox from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from utilities.prefs_constants import stereoViewMode_prefs_key from utilities.prefs_constants import stereoViewAngle_prefs_key from utilities.prefs_constants import stereoViewSeparation_prefs_key from command_support.Command_PropertyManager import Command_PropertyManager _superclass = Command_PropertyManager class StereoProperties_PropertyManager(Command_PropertyManager): """ The StereoProperties_PropertyManager class provides a Property Manager for the Stereo View 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 = "Stereo View" pmName = title iconPath = "ui/actions/View/Stereo_View.png" def __init__( self, command ): """ Constructor for the property manager. """ _superclass.__init__(self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) msg = "Modify the Stereo View 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 change_connect(self.stereoEnabledCheckBox, SIGNAL("toggled(bool)"), self._enableStereo ) change_connect( self.stereoModeComboBox, SIGNAL("currentIndexChanged(int)"), self._stereoModeComboBoxChanged ) change_connect(self.stereoSeparationSlider, SIGNAL("valueChanged(int)"), self._stereoModeSeparationSliderChanged ) change_connect(self.stereoAngleSlider, SIGNAL("valueChanged(int)"), self._stereoModeAngleSliderChanged ) def _addGroupBoxes( self ): """ Add the Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Settings") self._loadGroupBox1( self._pmGroupBox1 ) #@ self._pmGroupBox1.hide() def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box. """ #stereoSettingsGroupBox = PM_GroupBox( None ) self.stereoEnabledCheckBox = \ PM_CheckBox(pmGroupBox, text = 'Enable Stereo View', widgetColumn = 1 ) stereoModeChoices = ['Relaxed view', 'Cross-eyed view', 'Red/blue anaglyphs', 'Red/cyan anaglyphs', 'Red/green anaglyphs'] self.stereoModeComboBox = \ PM_ComboBox( pmGroupBox, label = "Stereo Mode:", choices = stereoModeChoices, setAsDefault = True) self.stereoModeComboBox.setCurrentIndex(env.prefs[stereoViewMode_prefs_key]-1) self.stereoSeparationSlider = \ PM_Slider( pmGroupBox, currentValue = 50, minimum = 0, maximum = 300, label = 'Separation' ) self.stereoSeparationSlider.setValue(env.prefs[stereoViewSeparation_prefs_key]) self.stereoAngleSlider = \ PM_Slider( pmGroupBox, currentValue = 50, minimum = 0, maximum = 100, label = 'Angle' ) self.stereoAngleSlider.setValue(env.prefs[stereoViewAngle_prefs_key]) self._updateWidgets() def _addWhatsThisText( self ): """ What's This text for widgets in the Stereo Property Manager. """ pass def _addToolTipText(self): """ Tool Tip text for widgets in the Stereo Property Manager. """ pass def _enableStereo(self, enabled): """ Enable stereo view. """ glpane = self.o if glpane: glpane.set_stereo_enabled( enabled) # switch to perspective mode if enabled: # store current projection mode glpane.__StereoProperties_last_ortho = glpane.ortho if glpane.ortho: # dont use glpane.setViewProjection # because we don't want to modify # default projection setting glpane.ortho = 0 else: # restore default mode if hasattr(glpane, "__StereoProperties_last_ortho"): projection = glpane.__StereoProperties_last_ortho if glpane.ortho != projection: glpane.ortho = projection self._updateWidgets() glpane.gl_update() def _stereoModeComboBoxChanged(self, mode): """ Change stereo mode. @param mode: stereo mode (0=relaxed, 1=cross-eyed, 2=red/blue, 3=red/cyan, 4=red/green) @type value: int """ env.prefs[stereoViewMode_prefs_key] = mode + 1 self._updateSeparationSlider() def _stereoModeSeparationSliderChanged(self, value): """ Change stereo view separation. @param value: separation (0..300) @type value: int """ env.prefs[stereoViewSeparation_prefs_key] = value def _stereoModeAngleSliderChanged(self, value): """ Change stereo view angle. @param value: stereo angle (0..100) @type value: int """ env.prefs[stereoViewAngle_prefs_key] = value def _updateSeparationSlider(self): """ Update the separation slider widget. """ if self.stereoModeComboBox.currentIndex() >= 2: # for anaglyphs disable the separation slider self.stereoSeparationSlider.setEnabled(False) else: # otherwise, enable the separation slider self.stereoSeparationSlider.setEnabled(True) def _updateWidgets(self): """ Update stereo PM widgets. """ if self.stereoEnabledCheckBox.isChecked(): self.stereoModeComboBox.setEnabled(True) self.stereoSeparationSlider.setEnabled(True) self.stereoAngleSlider.setEnabled(True) self._updateSeparationSlider() else: self.stereoModeComboBox.setEnabled(False) self.stereoSeparationSlider.setEnabled(False) self.stereoAngleSlider.setEnabled(False)
NanoCAD-master
cad/src/commands/StereoProperties/StereoProperties_PropertyManager.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Piotr @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode from commands.SelectChunks.SelectChunks_Command import SelectChunks_Command from commands.StereoProperties.StereoProperties_PropertyManager import StereoProperties_PropertyManager # == GraphicsMode part class StereoProperties_GraphicsMode(SelectChunks_GraphicsMode ): """ Graphics mode for StereoProperties command. """ pass # == Command part class StereoProperties_Command(SelectChunks_Command): """ """ # class constants GraphicsMode_class = StereoProperties_GraphicsMode PM_class = StereoProperties_PropertyManager commandName = 'STEREO_PROPERTIES' featurename = "Stereo View Properties" from utilities.constants import CL_GLOBAL_PROPERTIES command_level = CL_GLOBAL_PROPERTIES command_should_resume_prevMode = True command_has_its_own_PM = True flyoutToolbar = None
NanoCAD-master
cad/src/commands/StereoProperties/StereoProperties_Command.py
NanoCAD-master
cad/src/commands/StereoProperties/__init__.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'MinimizeEnergyPropDialog.ui' # # Created: Fri Jun 06 11:55:35 2008 # by: PyQt4 UI code generator 4.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_MinimizeEnergyPropDialog(object): def setupUi(self, MinimizeEnergyPropDialog): MinimizeEnergyPropDialog.setObjectName("MinimizeEnergyPropDialog") MinimizeEnergyPropDialog.resize(QtCore.QSize(QtCore.QRect(0,0,300,500).size()).expandedTo(MinimizeEnergyPropDialog.minimumSizeHint())) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(3),QtGui.QSizePolicy.Policy(3)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MinimizeEnergyPropDialog.sizePolicy().hasHeightForWidth()) MinimizeEnergyPropDialog.setSizePolicy(sizePolicy) MinimizeEnergyPropDialog.setMinimumSize(QtCore.QSize(300,500)) self.gridlayout = QtGui.QGridLayout(MinimizeEnergyPropDialog) self.gridlayout.setMargin(9) self.gridlayout.setSpacing(6) self.gridlayout.setObjectName("gridlayout") spacerItem = QtGui.QSpacerItem(221,21,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Expanding) self.gridlayout.addItem(spacerItem,5,0,1,1) self.hboxlayout = QtGui.QHBoxLayout() self.hboxlayout.setMargin(0) self.hboxlayout.setSpacing(6) self.hboxlayout.setObjectName("hboxlayout") self.whatsthis_btn = QtGui.QToolButton(MinimizeEnergyPropDialog) self.whatsthis_btn.setObjectName("whatsthis_btn") self.hboxlayout.addWidget(self.whatsthis_btn) spacerItem1 = QtGui.QSpacerItem(41,23,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout.addItem(spacerItem1) self.cancel_btn = QtGui.QPushButton(MinimizeEnergyPropDialog) self.cancel_btn.setAutoDefault(False) self.cancel_btn.setObjectName("cancel_btn") self.hboxlayout.addWidget(self.cancel_btn) self.ok_btn = QtGui.QPushButton(MinimizeEnergyPropDialog) self.ok_btn.setAutoDefault(False) self.ok_btn.setObjectName("ok_btn") self.hboxlayout.addWidget(self.ok_btn) self.gridlayout.addLayout(self.hboxlayout,6,0,1,1) self.buttonGroup8_2 = QtGui.QGroupBox(MinimizeEnergyPropDialog) self.buttonGroup8_2.setObjectName("buttonGroup8_2") self.vboxlayout = QtGui.QVBoxLayout(self.buttonGroup8_2) self.vboxlayout.setMargin(4) self.vboxlayout.setSpacing(4) self.vboxlayout.setObjectName("vboxlayout") self.minimize_engine_combobox = QtGui.QComboBox(self.buttonGroup8_2) self.minimize_engine_combobox.setObjectName("minimize_engine_combobox") self.vboxlayout.addWidget(self.minimize_engine_combobox) self.gridlayout.addWidget(self.buttonGroup8_2,0,0,1,1) self.buttonGroup8 = QtGui.QGroupBox(MinimizeEnergyPropDialog) self.buttonGroup8.setObjectName("buttonGroup8") self.vboxlayout1 = QtGui.QVBoxLayout(self.buttonGroup8) self.vboxlayout1.setMargin(4) self.vboxlayout1.setSpacing(2) self.vboxlayout1.setObjectName("vboxlayout1") self.minimize_all_rbtn = QtGui.QRadioButton(self.buttonGroup8) self.minimize_all_rbtn.setChecked(True) self.minimize_all_rbtn.setObjectName("minimize_all_rbtn") self.vboxlayout1.addWidget(self.minimize_all_rbtn) self.minimize_sel_rbtn = QtGui.QRadioButton(self.buttonGroup8) self.minimize_sel_rbtn.setObjectName("minimize_sel_rbtn") self.vboxlayout1.addWidget(self.minimize_sel_rbtn) self.electrostaticsForDnaDuringMinimize_checkBox = QtGui.QCheckBox(self.buttonGroup8) self.electrostaticsForDnaDuringMinimize_checkBox.setChecked(True) self.electrostaticsForDnaDuringMinimize_checkBox.setObjectName("electrostaticsForDnaDuringMinimize_checkBox") self.vboxlayout1.addWidget(self.electrostaticsForDnaDuringMinimize_checkBox) self.enableNeighborSearching_check_box = QtGui.QCheckBox(self.buttonGroup8) self.enableNeighborSearching_check_box.setChecked(True) self.enableNeighborSearching_check_box.setObjectName("enableNeighborSearching_check_box") self.vboxlayout1.addWidget(self.enableNeighborSearching_check_box) self.gridlayout.addWidget(self.buttonGroup8,1,0,1,1) self.watch_motion_groupbox = QtGui.QGroupBox(MinimizeEnergyPropDialog) self.watch_motion_groupbox.setCheckable(True) self.watch_motion_groupbox.setObjectName("watch_motion_groupbox") self.gridlayout1 = QtGui.QGridLayout(self.watch_motion_groupbox) self.gridlayout1.setMargin(4) self.gridlayout1.setSpacing(2) self.gridlayout1.setObjectName("gridlayout1") self.update_asap_rbtn = QtGui.QRadioButton(self.watch_motion_groupbox) self.update_asap_rbtn.setChecked(True) self.update_asap_rbtn.setObjectName("update_asap_rbtn") self.gridlayout1.addWidget(self.update_asap_rbtn,0,0,1,1) self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setMargin(0) self.hboxlayout1.setSpacing(2) self.hboxlayout1.setObjectName("hboxlayout1") self.update_every_rbtn = QtGui.QRadioButton(self.watch_motion_groupbox) self.update_every_rbtn.setObjectName("update_every_rbtn") self.hboxlayout1.addWidget(self.update_every_rbtn) self.update_number_spinbox = QtGui.QSpinBox(self.watch_motion_groupbox) self.update_number_spinbox.setMaximum(9999) self.update_number_spinbox.setMinimum(1) self.update_number_spinbox.setProperty("value",QtCore.QVariant(1)) self.update_number_spinbox.setObjectName("update_number_spinbox") self.hboxlayout1.addWidget(self.update_number_spinbox) self.update_units_combobox = QtGui.QComboBox(self.watch_motion_groupbox) self.update_units_combobox.setObjectName("update_units_combobox") self.hboxlayout1.addWidget(self.update_units_combobox) spacerItem2 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout1.addItem(spacerItem2) self.gridlayout1.addLayout(self.hboxlayout1,1,0,1,1) self.gridlayout.addWidget(self.watch_motion_groupbox,2,0,1,1) self.groupBox20 = QtGui.QGroupBox(MinimizeEnergyPropDialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(5)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.groupBox20.sizePolicy().hasHeightForWidth()) self.groupBox20.setSizePolicy(sizePolicy) self.groupBox20.setObjectName("groupBox20") self.hboxlayout2 = QtGui.QHBoxLayout(self.groupBox20) self.hboxlayout2.setMargin(4) self.hboxlayout2.setSpacing(4) self.hboxlayout2.setObjectName("hboxlayout2") self.vboxlayout2 = QtGui.QVBoxLayout() self.vboxlayout2.setMargin(0) self.vboxlayout2.setSpacing(2) self.vboxlayout2.setObjectName("vboxlayout2") self.endrms_lbl = QtGui.QLabel(self.groupBox20) self.endrms_lbl.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.endrms_lbl.setObjectName("endrms_lbl") self.vboxlayout2.addWidget(self.endrms_lbl) self.endmax_lbl = QtGui.QLabel(self.groupBox20) self.endmax_lbl.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.endmax_lbl.setObjectName("endmax_lbl") self.vboxlayout2.addWidget(self.endmax_lbl) self.cutoverrms_lbl = QtGui.QLabel(self.groupBox20) self.cutoverrms_lbl.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.cutoverrms_lbl.setObjectName("cutoverrms_lbl") self.vboxlayout2.addWidget(self.cutoverrms_lbl) self.cutovermax_lbl = QtGui.QLabel(self.groupBox20) self.cutovermax_lbl.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.cutovermax_lbl.setObjectName("cutovermax_lbl") self.vboxlayout2.addWidget(self.cutovermax_lbl) self.hboxlayout2.addLayout(self.vboxlayout2) self.vboxlayout3 = QtGui.QVBoxLayout() self.vboxlayout3.setMargin(0) self.vboxlayout3.setSpacing(2) self.vboxlayout3.setObjectName("vboxlayout3") self.endRmsDoubleSpinBox = QtGui.QDoubleSpinBox(self.groupBox20) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(3),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.endRmsDoubleSpinBox.sizePolicy().hasHeightForWidth()) self.endRmsDoubleSpinBox.setSizePolicy(sizePolicy) self.endRmsDoubleSpinBox.setDecimals(3) self.endRmsDoubleSpinBox.setMaximum(501.0) self.endRmsDoubleSpinBox.setProperty("value",QtCore.QVariant(1.0)) self.endRmsDoubleSpinBox.setObjectName("endRmsDoubleSpinBox") self.vboxlayout3.addWidget(self.endRmsDoubleSpinBox) self.endMaxDoubleSpinBox = QtGui.QDoubleSpinBox(self.groupBox20) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(3),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.endMaxDoubleSpinBox.sizePolicy().hasHeightForWidth()) self.endMaxDoubleSpinBox.setSizePolicy(sizePolicy) self.endMaxDoubleSpinBox.setDecimals(2) self.endMaxDoubleSpinBox.setMaximum(2501.0) self.endMaxDoubleSpinBox.setProperty("value",QtCore.QVariant(0.0)) self.endMaxDoubleSpinBox.setObjectName("endMaxDoubleSpinBox") self.vboxlayout3.addWidget(self.endMaxDoubleSpinBox) self.cutoverRmsDoubleSpinBox = QtGui.QDoubleSpinBox(self.groupBox20) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(3),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cutoverRmsDoubleSpinBox.sizePolicy().hasHeightForWidth()) self.cutoverRmsDoubleSpinBox.setSizePolicy(sizePolicy) self.cutoverRmsDoubleSpinBox.setDecimals(2) self.cutoverRmsDoubleSpinBox.setMaximum(12500.0) self.cutoverRmsDoubleSpinBox.setProperty("value",QtCore.QVariant(0.0)) self.cutoverRmsDoubleSpinBox.setObjectName("cutoverRmsDoubleSpinBox") self.vboxlayout3.addWidget(self.cutoverRmsDoubleSpinBox) self.cutoverMaxDoubleSpinBox = QtGui.QDoubleSpinBox(self.groupBox20) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(3),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cutoverMaxDoubleSpinBox.sizePolicy().hasHeightForWidth()) self.cutoverMaxDoubleSpinBox.setSizePolicy(sizePolicy) self.cutoverMaxDoubleSpinBox.setDecimals(2) self.cutoverMaxDoubleSpinBox.setMaximum(60001.0) self.cutoverMaxDoubleSpinBox.setProperty("value",QtCore.QVariant(0.0)) self.cutoverMaxDoubleSpinBox.setObjectName("cutoverMaxDoubleSpinBox") self.vboxlayout3.addWidget(self.cutoverMaxDoubleSpinBox) self.hboxlayout2.addLayout(self.vboxlayout3) spacerItem3 = QtGui.QSpacerItem(80,20,QtGui.QSizePolicy.MinimumExpanding,QtGui.QSizePolicy.Minimum) self.hboxlayout2.addItem(spacerItem3) self.gridlayout.addWidget(self.groupBox20,3,0,1,1) self.hboxlayout3 = QtGui.QHBoxLayout() self.hboxlayout3.setMargin(0) self.hboxlayout3.setSpacing(6) self.hboxlayout3.setObjectName("hboxlayout3") spacerItem4 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout3.addItem(spacerItem4) self.restore_btn = QtGui.QPushButton(MinimizeEnergyPropDialog) self.restore_btn.setObjectName("restore_btn") self.hboxlayout3.addWidget(self.restore_btn) self.gridlayout.addLayout(self.hboxlayout3,4,0,1,1) self.retranslateUi(MinimizeEnergyPropDialog) QtCore.QMetaObject.connectSlotsByName(MinimizeEnergyPropDialog) def retranslateUi(self, MinimizeEnergyPropDialog): MinimizeEnergyPropDialog.setWindowTitle(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Minimize Energy", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.ok_btn.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "OK", None, QtGui.QApplication.UnicodeUTF8)) self.ok_btn.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Minimize Energy", None, QtGui.QApplication.UnicodeUTF8)) self.buttonGroup8_2.setTitle(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Minimize physics engine", None, QtGui.QApplication.UnicodeUTF8)) self.minimize_engine_combobox.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Choose the simulation engine with which to minimize energy.", None, QtGui.QApplication.UnicodeUTF8)) self.minimize_engine_combobox.addItem(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "NanoDynamics-1 (Default)", None, QtGui.QApplication.UnicodeUTF8)) self.minimize_engine_combobox.addItem(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "GROMACS with ND1 Force Field", None, QtGui.QApplication.UnicodeUTF8)) self.minimize_engine_combobox.addItem(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Background GROMACS with ND1 Force Field", None, QtGui.QApplication.UnicodeUTF8)) self.buttonGroup8.setTitle(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Minimize Options", None, QtGui.QApplication.UnicodeUTF8)) self.minimize_all_rbtn.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Perform energy minimization on all the atoms in the workspace", None, QtGui.QApplication.UnicodeUTF8)) self.minimize_all_rbtn.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Minimize all", None, QtGui.QApplication.UnicodeUTF8)) self.minimize_sel_rbtn.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Perform energy minimization on only the atoms that have been selected", None, QtGui.QApplication.UnicodeUTF8)) self.minimize_sel_rbtn.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Minimize selection", None, QtGui.QApplication.UnicodeUTF8)) self.electrostaticsForDnaDuringMinimize_checkBox.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Electrostatics for DNA reduced model", None, QtGui.QApplication.UnicodeUTF8)) self.enableNeighborSearching_check_box.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Enable neighbor searching (slow but accurate)", None, QtGui.QApplication.UnicodeUTF8)) self.watch_motion_groupbox.setTitle(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Watch motion in real time", None, QtGui.QApplication.UnicodeUTF8)) self.update_asap_rbtn.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Update every 2 seconds, or faster if it doesn\'t slow adjustments by more than 20%", None, QtGui.QApplication.UnicodeUTF8)) self.update_asap_rbtn.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Update as fast as possible", None, QtGui.QApplication.UnicodeUTF8)) self.update_every_rbtn.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Specify how often to update the screen during adjustments", None, QtGui.QApplication.UnicodeUTF8)) self.update_every_rbtn.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Update every", None, QtGui.QApplication.UnicodeUTF8)) self.update_number_spinbox.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Specify how often to update the screen during adjustments", None, QtGui.QApplication.UnicodeUTF8)) self.update_units_combobox.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Specify how often to update the screen during adjustments", None, QtGui.QApplication.UnicodeUTF8)) self.update_units_combobox.addItem(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "frames", None, QtGui.QApplication.UnicodeUTF8)) self.update_units_combobox.addItem(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "seconds", None, QtGui.QApplication.UnicodeUTF8)) self.update_units_combobox.addItem(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "minutes", None, QtGui.QApplication.UnicodeUTF8)) self.update_units_combobox.addItem(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "hours", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox20.setTitle(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Convergence criteria", None, QtGui.QApplication.UnicodeUTF8)) self.endrms_lbl.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Target RMS force (pN)", None, QtGui.QApplication.UnicodeUTF8)) self.endrms_lbl.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "EndRMS:", None, QtGui.QApplication.UnicodeUTF8)) self.endmax_lbl.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Target max force (pN)", None, QtGui.QApplication.UnicodeUTF8)) self.endmax_lbl.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "EndMax:", None, QtGui.QApplication.UnicodeUTF8)) self.cutoverrms_lbl.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Cutover RMS force (pN)", None, QtGui.QApplication.UnicodeUTF8)) self.cutoverrms_lbl.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "CutoverRMS:", None, QtGui.QApplication.UnicodeUTF8)) self.cutovermax_lbl.setToolTip(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Cutover max force (pN)", None, QtGui.QApplication.UnicodeUTF8)) self.cutovermax_lbl.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "CutoverMax:", None, QtGui.QApplication.UnicodeUTF8)) self.endRmsDoubleSpinBox.setSuffix(QtGui.QApplication.translate("MinimizeEnergyPropDialog", " pN", None, QtGui.QApplication.UnicodeUTF8)) self.endMaxDoubleSpinBox.setSuffix(QtGui.QApplication.translate("MinimizeEnergyPropDialog", " pN", None, QtGui.QApplication.UnicodeUTF8)) self.cutoverRmsDoubleSpinBox.setSuffix(QtGui.QApplication.translate("MinimizeEnergyPropDialog", " pN", None, QtGui.QApplication.UnicodeUTF8)) self.cutoverMaxDoubleSpinBox.setSuffix(QtGui.QApplication.translate("MinimizeEnergyPropDialog", " pN", None, QtGui.QApplication.UnicodeUTF8)) self.restore_btn.setText(QtGui.QApplication.translate("MinimizeEnergyPropDialog", "Restore Defaults", None, QtGui.QApplication.UnicodeUTF8))
NanoCAD-master
cad/src/commands/MinimizeEnergy/MinimizeEnergyPropDialog.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ whatsThis_for_MinimizeEnergyDialog.py This file provides functions for setting the "What's This" and tooltip text for widgets in the NE1 Minimize Energy dialog only. Edit WhatsThisText_for_MainWindow.py to set "What's This" and tooltip text for widgets in the Main Window. @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ def whatsThis_MinimizeEnergyDialog(minimizeEnergyDialog): """ Assigning the I{What's This} text for the Minimize Energy dialog. """ _med = minimizeEnergyDialog _med.update_every_rbtn.setWhatsThis( """<b>Update every <i>n units.</u></b> <p> Specify how often to update the model during the adjustment. This allows the user to monitor results during adjustments. </p>""") _med.update_asap_rbtn.setWhatsThis( """<b>Update as fast as possible</b> <p> Update every 2 seconds, or faster (up to 20x/sec) if it doesn't slow adjustments by more than 20% </p>""") _text = \ """<b>EndRMS</b> <p> Continue until this RMS force is reached. </p>""" _med.endrms_lbl.setWhatsThis(_text) _med.endRmsDoubleSpinBox.setWhatsThis(_text) _text = \ """<b>EndMax</b> <p> Continue until no interaction exceeds this force. </p>""" _med.endmax_lbl.setWhatsThis(_text) _med.endMaxDoubleSpinBox.setWhatsThis(_text) _text = \ """<b>CutoverMax</b> <p>Use steepest descent until no interaction exceeds this force. </p>""" _med.cutovermax_lbl.setWhatsThis(_text) _med.cutoverMaxDoubleSpinBox.setWhatsThis(_text) _text = \ """<b>CutoverRMS</b> <p> Use steepest descent until this RMS force is reached. </p>""" _med.cutoverRmsDoubleSpinBox.setWhatsThis(_text) _med.cutoverrms_lbl.setWhatsThis(_text) _med.minimize_all_rbtn.setWhatsThis( """<b>Minimize All</b> <p>Perform energy minimization on all the atoms in the workspace. </p>""") _med.minimize_sel_rbtn.setWhatsThis( """<b>Minimize Selection</b> <p> Perform energy minimization on the atoms that are currently selected. </p>""") _med.watch_motion_groupbox.setWhatsThis( """<b>Watch Motion In Real Time</b> <p> Enables real time graphical updates during minimization runs. """) _med.update_asap_rbtn.setWhatsThis( """<b>Update as fast as possible</b> <p> Update every 2 seconds, or faster (up to 20x/sec) if it doesn't slow minimization by more than 20%. </p>""") _med.update_every_rbtn.setWhatsThis( """<b>Update every <i>n units.</u></b> <p> Specify how often to update the model during the minimization. This allows the user to monitor minimization results while the minimization is running. </p>""") _med.update_number_spinbox.setWhatsThis( """<b>Update every <i>n units.</u></b> <p> Specify how often to update the model during the minimization. This allows the user to monitor minimization results while the minimization is running. </p>""") _med.update_units_combobox.setWhatsThis( """<b>Update every <i>n units.</u></b> <p> Specify how often to update the model during the minimization. This allows the user to monitor minimization results while the minimization is running.</p>""") _med.cancel_btn.setWhatsThis( """<b>Cancel</b> <p> Dismiss this dialog without taking any action. </p>""") _med.ok_btn.setWhatsThis( """<b>Minimize Energy</b> <p> Using the parameters specified above perform energy minimization on some or all of the atoms. </p>""") _med.setWhatsThis("""<u><b>Minimize Energy</b></u> <p> The potential energy of a chemical structure is a function of the relative positions of its atoms. To obtain this energy with complete accuracy involves a lot of computer time spent on quantum mechanical calculations, which cannot be practically done on a desktop computer. To get an approximate potential energy without all that, we represent the energy as a series of terms involving geometric properties of the structure: lengths of chemical bonds, angles between pairs and triples of chemical bonds, etc. </p> <p> As is generally the case with physical systems, the gradient of the potential energy represents the forces acting on various particles. The atoms want to move in the direction that most reduces the potential energy. Energy minimization is a process of adjusting the atom positions to try to find a global minimum of the potential energy. Each atom contributes three variables (its x, y, and z coordinates) so the search space is multi-dimensional. The global minimum is the configuration that the atoms will settle into if lowered to zero Kelvin. </p>""") return
NanoCAD-master
cad/src/commands/MinimizeEnergy/WhatsThisText_for_MinimizeEnergyDialog.py
NanoCAD-master
cad/src/commands/MinimizeEnergy/__init__.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ MinimizeEnergyProp.py - the MinimizeEnergyProp class, including all methods needed by the Minimize Energy dialog. @author: Mark @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: mark 060705 - Created for Alpha 8 NFR: "Simulator > Minimize Energy". To do: - implement/enforce constrains between all convergence values. """ from PyQt4.Qt import QDialog from PyQt4.Qt import QButtonGroup from PyQt4.Qt import QAbstractButton from PyQt4.Qt import SIGNAL from PyQt4.Qt import QWhatsThis from PyQt4.Qt import QSize from utilities.Log import greenmsg, redmsg, orangemsg, _graymsg, quote_html from commands.MinimizeEnergy.MinimizeEnergyPropDialog import Ui_MinimizeEnergyPropDialog from PM.GroupButtonMixin import GroupButtonMixin #@from sponsors.Sponsors import SponsorableMixin from utilities.icon_utilities import geticon from utilities.prefs_constants import Minimize_watchRealtimeMinimization_prefs_key from utilities.prefs_constants import Minimize_endRMS_prefs_key as endRMS_prefs_key from utilities.prefs_constants import Minimize_endMax_prefs_key as endMax_prefs_key from utilities.prefs_constants import Minimize_cutoverRMS_prefs_key as cutoverRMS_prefs_key from utilities.prefs_constants import Minimize_cutoverMax_prefs_key as cutoverMax_prefs_key from utilities.prefs_constants import Minimize_minimizationEngine_prefs_key from utilities.prefs_constants import electrostaticsForDnaDuringMinimize_prefs_key from utilities.prefs_constants import neighborSearchingInGromacs_prefs_key from utilities.debug import print_compact_traceback from utilities.debug import reload_once_per_event import foundation.env as env from utilities import debug_flags from ne1_ui.prefs.Preferences import get_pref_or_optval from widgets.widget_helpers import double_fixup from utilities.debug_prefs import debug_pref, Choice_boolean_False from widgets.prefs_widgets import connect_checkbox_with_boolean_pref #class MinimizeEnergyProp(QDialog, SponsorableMixin, GroupButtonMixin, Ui_MinimizeEnergyPropDialog): class MinimizeEnergyProp(QDialog, Ui_MinimizeEnergyPropDialog): cmdname = greenmsg("Minimize Energy: ") # WARNING: self.cmdname might be used by one of the superclasses plain_cmdname = "Minimize Energy" def __init__(self, win): QDialog.__init__(self, win) # win is parent. self.setupUi(self) self.watch_motion_buttongroup = QButtonGroup() self.watch_motion_buttongroup.setExclusive(True) for obj in self.watch_motion_groupbox.children(): if isinstance(obj, QAbstractButton): self.watch_motion_buttongroup.addButton(obj) #fix some icon problems self.setWindowIcon( geticon('ui/border/MinimizeEnergy.png')) self.connect(self.cancel_btn, SIGNAL("clicked()"), self.cancel_btn_clicked) self.connect(self.ok_btn, SIGNAL("clicked()"), self.ok_btn_clicked) self.connect(self.restore_btn, SIGNAL("clicked()"), self.restore_defaults_btn_clicked) self.whatsthis_btn.setIcon( geticon('ui/actions/Properties Manager/WhatsThis.png')) self.whatsthis_btn.setIconSize(QSize(22, 22)) self.whatsthis_btn.setToolTip('Enter "What\'s This?" help mode') self.connect(self.whatsthis_btn, SIGNAL("clicked()"), QWhatsThis.enterWhatsThisMode) connect_checkbox_with_boolean_pref( self.electrostaticsForDnaDuringMinimize_checkBox, electrostaticsForDnaDuringMinimize_prefs_key) connect_checkbox_with_boolean_pref( self.enableNeighborSearching_check_box, neighborSearchingInGromacs_prefs_key) self.connect(self.minimize_engine_combobox, SIGNAL("activated(int)"), self.update_minimize_engine) self.minimize_engine_combobox.setCurrentIndex( env.prefs[Minimize_minimizationEngine_prefs_key]) self.connect(self.endRmsDoubleSpinBox, SIGNAL("valueChanged(double)"), self.changeEndRms) self.connect(self.endMaxDoubleSpinBox, SIGNAL("valueChanged(double)"), self.changeEndMax) self.connect(self.cutoverRmsDoubleSpinBox, SIGNAL("valueChanged(double)"), self.changeCutoverRms) self.connect(self.cutoverMaxDoubleSpinBox, SIGNAL("valueChanged(double)"), self.changeCutoverMax) self.endRmsDoubleSpinBox.setSpecialValueText("Automatic") self.endMaxDoubleSpinBox.setSpecialValueText("Automatic") self.cutoverRmsDoubleSpinBox.setSpecialValueText("Automatic") self.cutoverMaxDoubleSpinBox.setSpecialValueText("Automatic") self.win = win self.previousParams = None self.setup_ruc() self.seltype = 'All' self.minimize_selection_enabled = True #bruce 080513 # Assign "What's This" text for all widgets. from commands.MinimizeEnergy.WhatsThisText_for_MinimizeEnergyDialog import whatsThis_MinimizeEnergyDialog whatsThis_MinimizeEnergyDialog(self) self.update_widgets() # to make sure self attrs are set return def setup_ruc(self): """ #doc """ #bruce 060705 use new common code, if it works from widgets.widget_controllers import realtime_update_controller self.ruc = realtime_update_controller( #( self.update_btngrp, self.update_number_spinbox, self.update_units_combobox ), ( self.watch_motion_buttongroup, self.update_number_spinbox, self.update_units_combobox ), self.watch_motion_groupbox, Minimize_watchRealtimeMinimization_prefs_key ) ## can't do this yet: self.ruc.set_widgets_from_update_data( self.previous_movie._update_data ) # includes checkbox # for A8, only the checkbox will be persistent; the others will be sticky only because the dialog is not remade at runtime return def setup(self): """ Setup and show the Minimize Energy dialog. """ # Get widget parameters, update widgets, save previous parameters (for Restore Defaults) and show dialog. # set up default & enabled choices for Minimize Selection vs. Min All # (details revised to fix nfr bug 2848, item 1, bruce 080513; # prior code used selection nonempty to determine default seltype) selection = self.win.assy.selection_from_glpane() # a compact rep of the currently selected subset of the Part's stuff if selection.nonempty(): ## self.seltype = 'Sel' self.seltype = 'All' self.minimize_selection_enabled = True else: self.seltype = 'All' self.minimize_selection_enabled = False self.update_widgets() # only the convergence criteria, for A8, plus All/Sel command from self.seltype self.previousParams = self.gather_parameters() # only used in case Cancel wants to restore them; only conv crit for A8 self.exec_() # Show dialog as a modal dialog. return def gather_parameters(self): ###e should perhaps include update_data from ruc (not sure it's good) -- but no time for A8 """ Returns a tuple with the current parameter values from the widgets. Also sets those in env.prefs. Doesn't do anything about self.seltype, since that is a choice of command, not a parameter for a command. """ return tuple([env.prefs[key] for key in (endRMS_prefs_key, endMax_prefs_key, cutoverRMS_prefs_key, cutoverMax_prefs_key)]) def update_widgets(self, update_seltype = True): """ Update the widgets using the current env.prefs values and self attrs. """ if update_seltype: if self.seltype == 'All': self.minimize_all_rbtn.setChecked(1) else: # note: this case might no longer ever happen after today's # change, but I'm not sure. Doesn't matter. [bruce 080513] self.minimize_sel_rbtn.setChecked(1) self.minimize_sel_rbtn.setEnabled( self.minimize_selection_enabled) pass # Convergence Criteria groupbox # WARNING: some of the following code is mostly duplicated by Preferences code self.endrms = get_pref_or_optval(endRMS_prefs_key, -1.0, 0.0) self.endRmsDoubleSpinBox.setValue(self.endrms) self.endmax = get_pref_or_optval(endMax_prefs_key, -1.0, 0.0) self.endMaxDoubleSpinBox.setValue(self.endmax) self.cutoverrms = get_pref_or_optval(cutoverRMS_prefs_key, -1.0, 0.0) self.cutoverRmsDoubleSpinBox.setValue(self.cutoverrms) self.cutovermax = get_pref_or_optval(cutoverMax_prefs_key, -1.0, 0.0) self.cutoverMaxDoubleSpinBox.setValue(self.cutovermax) self.update_minimize_engine() ###e also watch in realtime prefs for this -- no, thats in another method for now return def ok_btn_clicked(self): """ Slot for OK button """ QDialog.accept(self) if env.debug(): print "ok" self.gather_parameters() ### kluge: has side effect on env.prefs # (should we pass these as arg to Minimize_CommandRun rather than thru env.prefs??) if debug_flags.atom_debug: print "debug: reloading runSim & sim_commandruns on each use, for development" import simulation.runSim as runSim reload_once_per_event(runSim) # bug: only works some of the times runSim.py is modified, # don't know why; might be that sim_commandruns.py # also needs to be modified, but touching them both # doesn't seem to work consistently either. # [bruce 080520] import simulation.sim_commandruns as sim_commandruns reload_once_per_event(sim_commandruns) from simulation.sim_commandruns import Minimize_CommandRun # do this in gather? if self.minimize_all_rbtn.isChecked(): self.seltype = 'All' seltype_name = "All" else: self.seltype = 'Sel' seltype_name = "Selection" self.win.assy.current_command_info(cmdname = self.plain_cmdname + " (%s)" % seltype_name) # cmdname for Undo update_cond = self.ruc.get_update_cond_from_widgets() engine = self.minimize_engine_combobox.currentIndex() env.prefs[Minimize_minimizationEngine_prefs_key] = engine cmdrun = Minimize_CommandRun( self.win, self.seltype, type = 'Minimize', update_cond = update_cond, engine = engine) cmdrun.run() return def cancel_btn_clicked(self): """ Slot for Cancel button """ if env.debug(): print "cancel" # restore values we grabbed on entry. for key,val in zip((endRMS_prefs_key, endMax_prefs_key, cutoverRMS_prefs_key, cutoverMax_prefs_key), self.previousParams): env.prefs[key] = val self.update_widgets(update_seltype = False) #k might not matter since we're about to hide it, but can't hurt QDialog.reject(self) return def restore_defaults_btn_clicked(self): """ Slot for Restore Defaults button """ # restore factory defaults # for A8, only for conv crit, not for watch motion settings self.minimize_engine_combobox.setCurrentIndex(0) # ND1 env.prefs.restore_defaults([endRMS_prefs_key, endMax_prefs_key, cutoverRMS_prefs_key, cutoverMax_prefs_key]) self.update_widgets(update_seltype = False) return # Dialog slots def update_minimize_engine(self, ignoredIndex = 0): """ Slot for the Minimize Engine comobox. """ engineIndex = self.minimize_engine_combobox.currentIndex() if engineIndex == 0: # NanoDynamics-1 # Minimize options widgets. self.electrostaticsForDnaDuringMinimize_checkBox.setEnabled(False) self.enableNeighborSearching_check_box.setEnabled(False) # Watch minimize in real time widgets. self.watch_motion_groupbox.setEnabled(True) # Converence criteria widgets self.endMaxDoubleSpinBox.setEnabled(True) self.cutoverRmsDoubleSpinBox.setEnabled(True) self.cutoverMaxDoubleSpinBox.setEnabled(True) else: # GROMACS # Minimize options widgets. self.electrostaticsForDnaDuringMinimize_checkBox.setEnabled(True) self.enableNeighborSearching_check_box.setEnabled(True) # Watch minimize in real time widgets. self.watch_motion_groupbox.setEnabled(False) # Converence criteria widgets self.endMaxDoubleSpinBox.setEnabled(False) self.cutoverRmsDoubleSpinBox.setEnabled(False) self.cutoverMaxDoubleSpinBox.setEnabled(False) return def changeEndRms(self, endRms): """ Slot for EndRMS. """ if endRms: env.prefs[endRMS_prefs_key] = endRms else: env.prefs[endRMS_prefs_key] = -1.0 return def changeEndMax(self, endMax): """ Slot for EndMax. """ if endMax: env.prefs[endMax_prefs_key] = endMax else: env.prefs[endMax_prefs_key] = -1.0 return def changeCutoverRms(self, cutoverRms): """ Slot for CutoverRMS. """ if cutoverRms: env.prefs[cutoverRMS_prefs_key] = cutoverRms else: env.prefs[cutoverRMS_prefs_key] = -1.0 return def changeCutoverMax(self, cutoverMax): """ Slot for CutoverMax. """ if cutoverMax: env.prefs[cutoverMax_prefs_key] = cutoverMax else: env.prefs[cutoverMax_prefs_key] = -1.0 return pass # end of class MinimizeEnergyProp # end
NanoCAD-master
cad/src/commands/MinimizeEnergy/MinimizeEnergyProp.py
# Copyright 2005-2008 Nanorex, Inc. See LICENSE file for details. """ @copyright: 2005-2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: Ninad 2008-08-04: Created by splitting PasteFromClipboard_Command class into command and GraphicsMode. TODO: """ from commands.BuildAtoms.BuildAtoms_GraphicsMode import BuildAtoms_GraphicsMode import foundation.env as env from utilities.Log import orangemsg, redmsg _superclass = BuildAtoms_GraphicsMode class PasteFromClipboard_GraphicsMode(BuildAtoms_GraphicsMode): def deposit_from_MMKit(self, atom_or_pos): """ Deposit the clipboard item being previewed into the 3D workspace Calls L{self.deposit_from_Clipboard_page} @attention: This method needs renaming. L{depositMode} still uses it so simply overriden here. B{NEEDS CLEANUP}. @see: L{self.deposit_from_Clipboard_page} """ if self.o.modkeys is None: # no Shift or Ctrl modifier key. self.o.assy.unpickall_in_GLPane() deposited_stuff, status = \ self.command.deposit_from_Clipboard_page(atom_or_pos) deposited_obj = 'Chunk' self.o.selatom = None if deposited_stuff: self.w.win_update() status = self.ensure_visible( deposited_stuff, status) env.history.message(status) else: env.history.message(orangemsg(status)) return deposited_obj def transdepositPreviewedItem(self, singlet): """ Trans-deposit the current object in the preview groupbox of the property manager on all singlets reachable through any sequence of bonds to the singlet <singlet>. """ # bruce 060412: fix bug 1677 (though this fix's modularity should be # improved; perhaps it would be better to detect this error in # deposit_from_MMKit). # See also other comments dated today about separate fixes of some # parts of that bug. mmkit_part = self.command.MMKit_clipboard_part() # a Part or None if mmkit_part and self.o.assy.part is mmkit_part: env.history.message(redmsg("Can't transdeposit the MMKit's current"\ " clipboard item onto itself.")) return _superclass.transdepositPreviewedItem(self, singlet)
NanoCAD-master
cad/src/commands/Paste/PasteFromClipboard_GraphicsMode.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ PastePropertyManager.py The PastePropertyManager class provides the Property Manager for the B{Paste mode}. @author: Ninad @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-08-29: Created to support new 'Paste mode'. """ from commands.BuildAtoms.BuildAtomsPropertyManager import BuildAtomsPropertyManager from PM.PM_Clipboard import PM_Clipboard from utilities.Comparison import same_vals class PastePropertyManager(BuildAtomsPropertyManager): """ The PastePropertyManager class provides the Property Manager for the B{Paste mode}. It lists the 'pastable' clipboard items and also shows the current selected item in its 'Preview' box. @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 """ # The title that appears in the Property Manager header title = "Paste Items" # The name of this Property Manager. This will be set to # the name of the PM_Dialog object via setObjectName(). pmName = title # The relative path to the PNG file that appears in the header iconPath = "ui/actions/Properties Manager/clipboard-full.png" def __init__(self, command): """ Constructor for the B{Paste} property manager class that defines its UI. @param command: The parent mode where this Property Manager is used @type command: L{PasteFromClipboard_Command} """ self.clipboardGroupBox = None self._previous_model_changed_params = None BuildAtomsPropertyManager.__init__(self, command) self.updateMessage("Double click on empty space inside the 3D" \ "workspace to paste the item shown in "\ "the <b> Preview </b> box. Click the check mark to exit Paste" " Items") def _update_UI_do_updates(self): """ Overrides superclass method. @see: PasteFromClipboard_Command.command_update_internal_state() which is called before any command/ PM update UI. """ currentParams = self._current_model_changed_params() if same_vals(currentParams, self._previous_model_changed_params): return #update the self._previous_model_changed_params with this new param set. self._previous_model_changed_params = currentParams self.update_clipboard_items() # Fixes bugs 1569, 1570, 1572 and 1573. mark 060306. # Note and bugfix, bruce 060412: doing this now was also causing # traceback bugs 1726, 1629, # and the traceback part of bug 1677, and some related #(perhaps unreported) bugs. # The problem was that this is called during pasteBond's addmol #(due to its addchild), before it's finished, # at a time when the .part structure is invalid (since the added # mol's .part has not yet been set). # To fix bugs 1726, 1629 and mitigate bug 1677, I revised the # interface to MMKit.update_clipboard_items # (in the manner which was originally recommented in #call_after_next_changed_members's docstring) # so that it only sets a flag and updates (triggering an MMKit # repaint event), deferring all UI effects to # the next MMKit event. pass def _current_model_changed_params(self): """ Returns a tuple containing the parameters that will be compared against the previously stored parameters. This provides a quick test to determine whether to do more things in self._update_UI_do_updates() @see: self._update_UI_do_updates() which calls this @see: self._previous_model_changed_params attr. """ #As of 2008-09-18, this is used to update the list widget in the PM #that lists the 'pastable' items. return self.command.pastables_list def _addGroupBoxes(self): """ Add various group boxes to the Paste Property manager. """ self._addPreviewGroupBox() self._addClipboardGroupBox() def _addClipboardGroupBox(self): """ Add the 'Clipboard' groupbox """ if not self.previewGroupBox: return elementViewer = self.previewGroupBox.elementViewer self.clipboardGroupBox = \ PM_Clipboard(self, win = self.command.w, elementViewer = elementViewer) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ self.clipboardGroupBox.connect_or_disconnect_signals(isConnect) def getPastable(self): """ Retrieve the 'pastable' clipboard item. @return: The pastable clipboard item @rtype: L{molecule} or L{Group} """ self.command.pastable = self.previewGroupBox.elementViewer.model return self.command.pastable def update_clipboard_items(self): """ Update the items in the clipboard groupbox. """ if self.clipboardGroupBox: self.clipboardGroupBox.update() def updateMessage(self, msg = ''): """ Update the message box in the property manager with an informative message. """ if not msg: msg = "Double click on empty space inside the 3D workspace,"\ " to paste the item shown in the <b> Preview </b> box. <br>" \ " To return to the previous mode hit, <b>Escape </b> key or press "\ "<b> Done </b>" # Post message. self.MessageGroupBox.insertHtmlMessage(msg, minLines = 5) def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_PasteItemsPropertyManager whatsThis_PasteItemsPropertyManager(self) def _addToolTipText(self): """ Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_PasteItemPropertyManager ToolTip_PasteItemPropertyManager(self)
NanoCAD-master
cad/src/commands/Paste/PastePropertyManager.py
NanoCAD-master
cad/src/commands/Paste/__init__.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ PasteFromClipboard_Command.py PasteFromClipboard_Command allows depositing clipboard items into the 3D workspace. Its property manager lists the'pastable' clipboard items and also shows the current selected item in its 'Preview' box. User can return to previous mode by hitting 'Escape' key or pressing 'Done' button in the Paste mode. @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: Ninad 2007-08-29: Created. Ninad 2008-01-02: Moved several methods originally in class depositMode to PasteFromClipboard_Command. Ninad 2008-08-02: refactored into command and graphics mode classes, other things needed for the command stack refactoring project. TODO: - some methods in Command and GraphicsMode part are not appropriate in those classes eg. deposit_from_MMKit method in the Graphicsmode class. This will need further clanup. - rename PasteFromClipboard_Command to PastFromClipboard_Command """ from foundation.Group import Group from model.chem import Atom from model.chunk import Chunk from model.elements import Singlet from operations.pastables import is_pastable from operations.pastables import find_hotspot_for_pasting from model.bonds import bond_at_singlets from utilities.Comparison import same_vals from commands.Paste.PastePropertyManager import PastePropertyManager from commands.BuildAtoms.BuildAtoms_Command import BuildAtoms_Command from ne1_ui.toolbars.Ui_PasteFromClipboardFlyout import PasteFromClipboardFlyout from commands.Paste.PasteFromClipboard_GraphicsMode import PasteFromClipboard_GraphicsMode _superclass = BuildAtoms_Command class PasteFromClipboard_Command(BuildAtoms_Command): """ PasteFromClipboard_Command allows depositing clipboard items into the 3D workspace. Its property manager lists the 'pastable' clipboard items and also shows the current selected item in its 'Preview' box. User can return to previous mode by hitting 'Escape' key or pressing 'Done' button in the Paste mode. """ commandName = 'PASTE' featurename = "Paste From Clipboard" from utilities.constants import CL_EDIT_GENERIC command_level = CL_EDIT_GENERIC #Don't resume previous mode (buggy if set to True) [ninad circa 080102] command_should_resume_prevMode = False #See Command.anyCommand for details about the following flag command_has_its_own_PM = True #GraphicsMode GraphicsMode_class = PasteFromClipboard_GraphicsMode #Property Manager PM_class = PastePropertyManager #Flyout Toolbar FlyoutToolbar_class = PasteFromClipboardFlyout def __init__(self, commandSequencer): """ Constructor for the class PasteFromClipboard_Command. PasteFromClipboard_Command allows depositing clipboard items into the 3D workspace. Its property manager lists the 'pastable' clipboard items and also shows the current selected item in its 'Preview' box. User can return to previous mode by hitting 'Escape' key or pressing 'Done' button in the Paste mode. @param commandSequencer: The command sequencer (GLPane) object """ self.pastables_list = [] #@note: not needed here? self._previous_model_changed_params = None _superclass.__init__(self, commandSequencer) def command_entered(self): """ Overrides superclass method @see: baseCommand.command_entered() for documentation. """ _superclass.command_entered(self) self.pastable = None #k would it be nicer to preserve it from the past?? # note, this is also done redundantly in init_gui. self.pastables_list = [] # should be ok, since model_changed comes after this... def command_update_internal_state(self): """ Extends superclass method. @see: baseCommand.command_update_internal_state() @see: PastePropertyManager._update_UI_do_updates() """ _superclass.command_update_internal_state(self) currentParams = self._current_model_changed_params() #Optimization. Return from the model_changed method if the #params are the same. if same_vals(currentParams, self._previous_model_changed_params): return #update the self._previous_model_changed_params with this new param set. self._previous_model_changed_params = currentParams #This was earlier -- self.update_gui_0() self._update_pastables_list() def _current_model_changed_params(self): """ Returns a tuple containing the parameters that will be compared against the previously stored parameters. This provides a quick test to determine whether to do more things in self.model_changed() @see: self.model_changed() which calls this @see: self._previous_model_changed_params attr. """ params = None memberList = [] try: ###@@@@ need this to avoid UnboundLocalError: local variable 'shelf' ##referenced before assignment # but that got swallowed the first time we entered mode! # but i can't figure out why, so neverind for now [bruce 050121] shelf = self.glpane.assy.shelf if hasattr(shelf, 'members'): memberList = list(shelf.members) else: memberList = [shelf] except AttributeError: # this is normal, until I commit new code to Utility and model tree! #[bruce 050121] pass params = (memberList) return params def _update_pastables_list(self): #bruce 050121 split this out and heavily revised it """ """ #UPDATE 2008-08-20: # This method was earlier update_gui_0() which was called from # 'def update_gui()'. All update_gui_* methods have been removed 080821. #See model_changed() method where this method is called. #Note that the code in this method is old and needs to be revised #-- [Ninad comment] # [Warning, bruce 050316: when this runs, new clipboard items might not # yet have # their own Part, or the correct Part! So this code should not depend # on the .part member of any nodes it uses. If this matters, a quick # (but inefficient) fix would be to call that method right here... # except that it might not be legal to do so! Instead, we'd probably # need # to arrange to do the actual updating (this method) only at the end of # the current user event. We'll need that ability pretty soon for other # reasons (probably for Undo), so it's ok if we need it a bit sooner.] # Subclasses update the contents of self.propMgr.clipboardGroupBox # (Note; earlier depositMode used to update self.w.pasteComboBox items, # but this implementation has been changed since 2007-09-04 after # introduction of L{PasteFromClipboard_Command}) # to match the set of pastable objects on the clipboard, # which is cached in pastables_list for use, # and update the current item to be what it used to be (if that is # still available in the list), else the last item (if there are any # items). #First update self.pastable if not self.pastable: self.update_pastable() # update the list of pastable things - candidates are all objects # on the clipboard members = self.o.assy.shelf.members[:] ## not needed or correct since some time ago [bruce 050110]: ## members.reverse() # bruce 041124 -- model tree seems to have them ##backwards self.pastables_list = filter( is_pastable, members) # experiment 050122: mark the clipboard items to influence their #appearance # in model tree... not easy to change their color, so maybe we'll let # this # change their icon (just in chunk.py for now). Not yet done. We'd # like the # one equal to self.pastable (when self.depositState == 'Clipboard' # and this is current mode) # to look the most special. But that needs to be recomputed more often # than this runs. Maybe we'll let the current mode have an # mtree-icon-filter?? # Or, perhaps, let it modify the displayed text in the mtree, # from node.name. ###@@@ for mem in members: mem._note_is_pastable = False # set all to false... for mem in self.pastables_list: mem._note_is_pastable = True # ... then change some of those to true if not self.pastables_list: # insert a text label saying why spinbox is empty [bruce 041124] if members: whynot = "(no clips are pastable)" # this text should not be #longer than the one below, for now else: whynot = "(clipboard is empty)" self.pastable = None else: # choose the best current item for self.pastable and spinbox # position # (this is the same pastable as before, if it's still available) if self.pastable not in self.pastables_list: # (works even if #self.pastable is None) self.pastable = self.pastables_list[-1] # use the last one (presumably the most recently added) # (no longer cares about selection of clipboard items #-- bruce 050121) assert self.pastable # can fail if None is in the list or "not in" #doesn't work right for None #e future: if model tree indicates self.pastable somehow, e.g. by color #of its name, update it. (It might as well also show "is_pastables" #that way.) ###@@@ good idea... return def update_pastable(self): """ Update self.pastable based on current selected pastable in the clipboard """ members = self.o.assy.shelf.members[:] self.pastables_list = filter( is_pastable, members) try: cx = self.propMgr.clipboardGroupBox.currentRow() self.pastable = self.pastables_list[cx] except: # various causes, mostly not errors self.pastable = None return def MMKit_clipboard_part(self): #bruce 060412; implem is somewhat of a #guess, based on the code of self.deposit_from_MMKit """ If the MMKit is currently set to a clipboard item, return that item's Part, else return None. """ if not self.pastable: return None return self.pastable.part def deposit_from_Clipboard_page(self, atom_or_pos): """ Deposit the clipboard item being previewed into the 3D workspace Called in L{self.deposit_from_MMKit} @attention: This method needs renaming. L{depositMode} still uses this so simply overriden here. B{NEEDS CLEANUP}. @see: L{self.deposit_from_MMKit} """ self.update_pastable() if isinstance(atom_or_pos, Atom): a = atom_or_pos if a.element is Singlet: if self.pastable: # bond clipboard object to the singlet # do the following before <a> (the singlet) is killed a0 = a.singlet_neighbor() chunk, desc = self.pasteBond(a) if chunk: status = "replaced bondpoint on %r with %s" % (a0, desc) else: status = desc else: #Nothing selected from the Clipboard to paste, so do nothing status = "nothing selected to paste" #k correct?? chunk = None else: if self.pastable: # deposit into empty space at the cursor position chunk, status = self.pasteFree(atom_or_pos) else: # Nothing selected from the Clipboard to paste, so do nothing status = "Nothing selected to paste" chunk = None return chunk, status # paste the pastable object where the cursor is (at pos) # warning: some of the following comment is obsolete (read all of it for # the details) # ###@@@ should clean up this comment and code # - bruce 041206 fix bug 222 by recentering it now -- # in fact, even better, if there's a hotspot, put that at pos. # - bruce 050121 fixing bug in feature of putting hotspot on water # rather than center. I was going to remove it, since Ninad disliked it # and I can see problematic aspects of it; but I saw that it had a bug # of picking the "first singlet" if there were several (and no hotspot), # so I'll fix that bug first, and also call fix_bad_hotspot to work # around invalid hotspots if those can occur. If the feature still seems # objectionable after this, it can be removed (or made a nondefault # preference). # ... bruce 050124: that feature bothers me, decided to remove it #completely. def pasteFree(self, pos): self.update_pastable() pastable = self.pastable # as of 050316 addmol can change self.pastable! # (if we're operating in the same clipboard item it's stored in, # and if adding numol makes that item no longer pastable.) # And someday the copy operation itself might auto-addmol, for # some reason; so to be safe, save pastable here before we change # current part at all. chunk, status = self.o.assy.paste(pastable, pos) return chunk, status def pasteBond(self, sing): """ If self.pastable has an unambiguous hotspot, paste a copy of self.pastable onto the given singlet; return (the copy, description) or (None, whynot) """ self.update_pastable() pastable = self.pastable # as of 050316 addmol can change self.pastable! See comments in #pasteFree. # bruce 041123 added return values (and guessed docstring). # bruce 050121 using subr split out from this code ok, hotspot_or_whynot = find_hotspot_for_pasting(pastable) if not ok: whynot = hotspot_or_whynot return None, whynot hotspot = hotspot_or_whynot if isinstance(pastable, Chunk): numol = pastable.copy_single_chunk(None) hs = numol.hotspot or numol.singlets[0] # todo: should use find_hotspot_for_pasting again bond_at_singlets(hs,sing) # this will move hs.molecule (numol) to match # bruce 050217 comment: hs is now an invalid hotspot for numol, # and that used to cause bug 312, but this is now fixed in getattr # every time the hotspot is retrieved (since it can become invalid # in many other ways too),so there's no need to explicitly forget # it here. if self.graphicsMode.pickit(): numol.pickatoms() #bruce 060412 worries whether pickatoms is illegal or #ineffective (in both pasteBond and pasteFree) # given that numol.part is presumably not yet set (until after #addmol). But these seem to work # (assuming I'm testing them properly), so I'm not changing #this. [Why do they work?? ###@@@] self.o.assy.addmol(numol) # do this last, in case it computes bbox return numol, "copy of %r" % pastable.name elif isinstance(pastable, Group): msg = "Pasting a group with hotspot onto a bond point " \ "is not implemented" return None, msg ##if debug_flags.atom_debug: ###@@@ EXPERIMENTAL CODE TO PASTE a GROUP WITH A HOTSPOT ##if 0: ### hotspot neighbor atom ##attch2Singlet = atom_or_pos ##hotspot_neighbor = hotspot.singlet_neighbor() ### attach to atom ##attch2Atom = attch2Singlet.singlet_neighbor() ##rotOffset = Q(hotspot_neighbor.posn() - hotspot.posn(), ##attch2Singlet.posn() - attch2Atom.posn()) ##rotCenter = newMol.center ##newMol.rot(rotOffset) ##moveOffset = attch2Singlet.posn() - hs.posn() ##newMol.move(moveOffset) ##self.graphicsMode._createBond(hotspot, ##hotspot_neighbor, ##attch2Singlet, ##attch2Atom) ##self.o.assy.addmol(newMol) ########## ####newGroup = self.pasteGroup(pos, pastable) ##return newGroup, "copy of %r" % newGroup.name
NanoCAD-master
cad/src/commands/Paste/PasteFromClipboard_Command.py
NanoCAD-master
cad/src/commands/ThermostatProperties/__init__.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ StatProp.py - edit properties of Thermostat jig $Id$ """ from PyQt4 import QtGui from PyQt4.Qt import QDialog from PyQt4.Qt import SIGNAL from PyQt4.Qt import QColorDialog from commands.ThermostatProperties.StatPropDialog import Ui_StatPropDialog from widgets.widget_helpers import RGBf_to_QColor, QColor_to_RGBf, get_widget_with_color_palette class StatProp(QDialog, Ui_StatPropDialog): def __init__(self, stat, glpane): QDialog.__init__(self) self.setupUi(self) self.connect(self.cancel_btn, SIGNAL("clicked()"), self.reject) self.connect(self.ok_btn, SIGNAL("clicked()"), self.accept) self.connect(self.choose_color_btn, SIGNAL("clicked()"), self.change_jig_color) self.jig = stat self.glpane = glpane jigtype_name = self.jig.__class__.__name__ self.setWindowIcon(QtGui.QIcon("ui/border/"+ jigtype_name)) def setup(self): self.jig_attrs = self.jig.copyable_attrs_dict() # Save the jig's attributes in case of Cancel. # Jig color self.jig_QColor = RGBf_to_QColor(self.jig.normcolor) # Used as default color by Color Chooser self.jig_color_pixmap = get_widget_with_color_palette( self.jig_color_pixmap, self.jig_QColor) # Jig name self.nameLineEdit.setText(self.jig.name) self.molnameLineEdit.setText(self.jig.atoms[0].molecule.name) self.tempSpinBox.setValue(int(self.jig.temp)) def change_jig_color(self): """ Slot method to change the jig's color. """ color = QColorDialog.getColor(self.jig_QColor, self) if color.isValid(): self.jig_QColor = color self.jig_color_pixmap = get_widget_with_color_palette( self.jig_color_pixmap, self.jig_QColor) self.jig.color = self.jig.normcolor = QColor_to_RGBf(color) self.glpane.gl_update() def accept(self): """ Slot for the 'OK' button """ self.jig.try_rename(self.nameLineEdit.text()) self.jig.temp = self.tempSpinBox.value() self.jig.assy.w.win_update() # Update model tree self.jig.assy.changed() QDialog.accept(self) def reject(self): """ Slot for the 'Cancel' button """ self.jig.attr_update(self.jig_attrs) # Restore attributes of the jig. self.glpane.gl_update() QDialog.reject(self)
NanoCAD-master
cad/src/commands/ThermostatProperties/StatProp.py
# -*- coding: utf-8 -*- # Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. # Form implementation generated from reading ui file 'StatPropDialog.ui' # # Created: Wed Sep 20 09:07:17 2006 # by: PyQt4 UI code generator 4.0.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_StatPropDialog(object): def setupUi(self, StatPropDialog): StatPropDialog.setObjectName("StatPropDialog") StatPropDialog.resize(QtCore.QSize(QtCore.QRect(0,0,299,202).size()).expandedTo(StatPropDialog.minimumSizeHint())) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(7),QtGui.QSizePolicy.Policy(7)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(StatPropDialog.sizePolicy().hasHeightForWidth()) StatPropDialog.setSizePolicy(sizePolicy) StatPropDialog.setSizeGripEnabled(True) self.vboxlayout = QtGui.QVBoxLayout(StatPropDialog) self.vboxlayout.setMargin(11) self.vboxlayout.setSpacing(6) self.vboxlayout.setObjectName("vboxlayout") self.hboxlayout = QtGui.QHBoxLayout() self.hboxlayout.setMargin(0) self.hboxlayout.setSpacing(6) self.hboxlayout.setObjectName("hboxlayout") self.vboxlayout1 = QtGui.QVBoxLayout() self.vboxlayout1.setMargin(0) self.vboxlayout1.setSpacing(6) self.vboxlayout1.setObjectName("vboxlayout1") self.nameTextLabel = QtGui.QLabel(StatPropDialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(5)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.nameTextLabel.sizePolicy().hasHeightForWidth()) self.nameTextLabel.setSizePolicy(sizePolicy) self.nameTextLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.nameTextLabel.setObjectName("nameTextLabel") self.vboxlayout1.addWidget(self.nameTextLabel) self.temp_lbl = QtGui.QLabel(StatPropDialog) self.temp_lbl.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.temp_lbl.setObjectName("temp_lbl") self.vboxlayout1.addWidget(self.temp_lbl) self.molnameTextLabel = QtGui.QLabel(StatPropDialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(5)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.molnameTextLabel.sizePolicy().hasHeightForWidth()) self.molnameTextLabel.setSizePolicy(sizePolicy) self.molnameTextLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.molnameTextLabel.setObjectName("molnameTextLabel") self.vboxlayout1.addWidget(self.molnameTextLabel) self.colorTextLabel = QtGui.QLabel(StatPropDialog) self.colorTextLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.colorTextLabel.setObjectName("colorTextLabel") self.vboxlayout1.addWidget(self.colorTextLabel) self.hboxlayout.addLayout(self.vboxlayout1) self.vboxlayout2 = QtGui.QVBoxLayout() self.vboxlayout2.setMargin(0) self.vboxlayout2.setSpacing(6) self.vboxlayout2.setObjectName("vboxlayout2") self.nameLineEdit = QtGui.QLineEdit(StatPropDialog) self.nameLineEdit.setEnabled(True) self.nameLineEdit.setAlignment(QtCore.Qt.AlignLeading) self.nameLineEdit.setObjectName("nameLineEdit") self.vboxlayout2.addWidget(self.nameLineEdit) self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setMargin(0) self.hboxlayout1.setSpacing(6) self.hboxlayout1.setObjectName("hboxlayout1") self.hboxlayout2 = QtGui.QHBoxLayout() self.hboxlayout2.setMargin(0) self.hboxlayout2.setSpacing(6) self.hboxlayout2.setObjectName("hboxlayout2") self.tempSpinBox = QtGui.QSpinBox(StatPropDialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(1),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tempSpinBox.sizePolicy().hasHeightForWidth()) self.tempSpinBox.setSizePolicy(sizePolicy) self.tempSpinBox.setMaximum(9999) self.tempSpinBox.setProperty("value",QtCore.QVariant(300)) self.tempSpinBox.setObjectName("tempSpinBox") self.hboxlayout2.addWidget(self.tempSpinBox) self.K_lbl = QtGui.QLabel(StatPropDialog) self.K_lbl.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.K_lbl.setObjectName("K_lbl") self.hboxlayout2.addWidget(self.K_lbl) self.hboxlayout1.addLayout(self.hboxlayout2) spacerItem = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout1.addItem(spacerItem) self.vboxlayout2.addLayout(self.hboxlayout1) self.molnameLineEdit = QtGui.QLineEdit(StatPropDialog) self.molnameLineEdit.setEnabled(True) self.molnameLineEdit.setAlignment(QtCore.Qt.AlignLeading) self.molnameLineEdit.setReadOnly(True) self.molnameLineEdit.setObjectName("molnameLineEdit") self.vboxlayout2.addWidget(self.molnameLineEdit) self.hboxlayout3 = QtGui.QHBoxLayout() self.hboxlayout3.setMargin(0) self.hboxlayout3.setSpacing(6) self.hboxlayout3.setObjectName("hboxlayout3") self.hboxlayout4 = QtGui.QHBoxLayout() self.hboxlayout4.setMargin(0) self.hboxlayout4.setSpacing(6) self.hboxlayout4.setObjectName("hboxlayout4") self.jig_color_pixmap = QtGui.QLabel(StatPropDialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(5)) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.jig_color_pixmap.sizePolicy().hasHeightForWidth()) self.jig_color_pixmap.setSizePolicy(sizePolicy) self.jig_color_pixmap.setMinimumSize(QtCore.QSize(40,0)) self.jig_color_pixmap.setScaledContents(True) self.jig_color_pixmap.setObjectName("jig_color_pixmap") self.hboxlayout4.addWidget(self.jig_color_pixmap) self.choose_color_btn = QtGui.QPushButton(StatPropDialog) self.choose_color_btn.setEnabled(True) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(1),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.choose_color_btn.sizePolicy().hasHeightForWidth()) self.choose_color_btn.setSizePolicy(sizePolicy) self.choose_color_btn.setAutoDefault(False) self.choose_color_btn.setObjectName("choose_color_btn") self.hboxlayout4.addWidget(self.choose_color_btn) self.hboxlayout3.addLayout(self.hboxlayout4) spacerItem1 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout3.addItem(spacerItem1) self.vboxlayout2.addLayout(self.hboxlayout3) self.hboxlayout.addLayout(self.vboxlayout2) self.vboxlayout.addLayout(self.hboxlayout) spacerItem2 = QtGui.QSpacerItem(20,20,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Expanding) self.vboxlayout.addItem(spacerItem2) self.hboxlayout5 = QtGui.QHBoxLayout() self.hboxlayout5.setMargin(0) self.hboxlayout5.setSpacing(6) self.hboxlayout5.setObjectName("hboxlayout5") spacerItem3 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout5.addItem(spacerItem3) self.ok_btn = QtGui.QPushButton(StatPropDialog) self.ok_btn.setMinimumSize(QtCore.QSize(0,0)) self.ok_btn.setAutoDefault(False) self.ok_btn.setDefault(False) self.ok_btn.setObjectName("ok_btn") self.hboxlayout5.addWidget(self.ok_btn) self.cancel_btn = QtGui.QPushButton(StatPropDialog) self.cancel_btn.setMinimumSize(QtCore.QSize(0,0)) self.cancel_btn.setAutoDefault(False) self.cancel_btn.setDefault(False) self.cancel_btn.setObjectName("cancel_btn") self.hboxlayout5.addWidget(self.cancel_btn) self.vboxlayout.addLayout(self.hboxlayout5) self.retranslateUi(StatPropDialog) QtCore.QObject.connect(self.cancel_btn,QtCore.SIGNAL("clicked()"),StatPropDialog.reject) QtCore.QObject.connect(self.ok_btn,QtCore.SIGNAL("clicked()"),StatPropDialog.accept) QtCore.QMetaObject.connectSlotsByName(StatPropDialog) StatPropDialog.setTabOrder(self.nameLineEdit,self.tempSpinBox) StatPropDialog.setTabOrder(self.tempSpinBox,self.molnameLineEdit) StatPropDialog.setTabOrder(self.molnameLineEdit,self.choose_color_btn) StatPropDialog.setTabOrder(self.choose_color_btn,self.ok_btn) StatPropDialog.setTabOrder(self.ok_btn,self.cancel_btn) def retranslateUi(self, StatPropDialog): StatPropDialog.setWindowTitle(QtGui.QApplication.translate("StatPropDialog", "Stat Properties", None, QtGui.QApplication.UnicodeUTF8)) self.nameTextLabel.setText(QtGui.QApplication.translate("StatPropDialog", "Name :", None, QtGui.QApplication.UnicodeUTF8)) self.temp_lbl.setText(QtGui.QApplication.translate("StatPropDialog", "Temperature :", None, QtGui.QApplication.UnicodeUTF8)) self.molnameTextLabel.setText(QtGui.QApplication.translate("StatPropDialog", "Attached to :", None, QtGui.QApplication.UnicodeUTF8)) self.colorTextLabel.setText(QtGui.QApplication.translate("StatPropDialog", "Color :", None, QtGui.QApplication.UnicodeUTF8)) self.K_lbl.setText(QtGui.QApplication.translate("StatPropDialog", "Kelvin", None, QtGui.QApplication.UnicodeUTF8)) self.choose_color_btn.setToolTip(QtGui.QApplication.translate("StatPropDialog", "Change color", None, QtGui.QApplication.UnicodeUTF8)) self.choose_color_btn.setText(QtGui.QApplication.translate("StatPropDialog", "Choose...", None, QtGui.QApplication.UnicodeUTF8)) self.ok_btn.setText(QtGui.QApplication.translate("StatPropDialog", "&OK", None, QtGui.QApplication.UnicodeUTF8)) self.ok_btn.setShortcut(QtGui.QApplication.translate("StatPropDialog", "Alt+O", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setText(QtGui.QApplication.translate("StatPropDialog", "&Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setShortcut(QtGui.QApplication.translate("StatPropDialog", "Alt+C", None, QtGui.QApplication.UnicodeUTF8))
NanoCAD-master
cad/src/commands/ThermostatProperties/StatPropDialog.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ InternalCoordinatesToCartesian.py @author: EricM from code by Piotr @version:$Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from geometry.VQT import V from Numeric import zeros, Float, cos, sin, sqrt, pi DEG2RAD = (pi/180.0) class InternalCoordinatesToCartesian(object): """ Translator to convert internal coordinates (such as those in AMBER .in files, as described by http://amber.scripps.edu/doc/prep.html) into cartesian coordinates. Internal coordinates represent the location of each point relative to three other already defined points. Indicies for those three points are given, along with distances, angles, and torsion angles among the given points. Each point in either cartesian or internal coordinates has three degrees of freedom, but they are specified differently between the two systems. To use: Create the translator object. If you wish to add the resulting structure onto a particular location on an existing structure, you should pass in suitable cartesian coordinates for the initialCoordinates, which define the position and orientation of the coordinate system used to translate the points. If you leave this as None, the results will begin at the origin in a standard orientation. For each set of internal coordinates represenging one point, call addInternal() passing in the internal coordinates. For each point so defined, you can retrieve the cartesian equivalent coordinates with a call to getCartesian(). """ def __init__(self, length, initialCoordinates): """ @param length: How many points will be converted, including the 3 dummy points. @param initialCoordinates: Either None, or an array of three sets of x, y, z cartesian coordinates. These are the coordinates of the three dummy points, indices 1, 2, and 3, which are defined before any actual data points are added. """ self._coords = zeros([length+1, 3], Float) if (initialCoordinates): self._coords[1][0] = initialCoordinates[0][0] self._coords[1][1] = initialCoordinates[0][1] self._coords[1][2] = initialCoordinates[0][2] self._coords[2][0] = initialCoordinates[1][0] self._coords[2][1] = initialCoordinates[1][1] self._coords[2][2] = initialCoordinates[1][2] self._coords[3][0] = initialCoordinates[2][0] self._coords[3][1] = initialCoordinates[2][1] self._coords[3][2] = initialCoordinates[2][2] else: self._coords[1][0] = -1.0 self._coords[1][1] = -1.0 self._coords[1][2] = 0.0 self._coords[2][0] = -1.0 self._coords[2][1] = 0.0 self._coords[2][2] = 0.0 self._coords[3][0] = 0.0 self._coords[3][1] = 0.0 self._coords[3][2] = 0.0 self._nextIndex = 4 def addInternal(self, i, na, nb, nc, r, theta, phi): """ Add another point, given its internal coordinates. Once added via this routine, the cartesian coordinates for the point can be retrieved with getCartesian(). @param i: Index of the point being added. After this call, a call to getCartesian with this index value will succeed. Index values less than 4 are ignored. Index values should be presented here in sequence beginning with 4. @param na: Index value for point A. Point 'i' will be 'r' distance units from point A. @param nb: Index value for point B. Point 'i' will be located such that the angle i-A-B is 'theta' degrees. @param nc: Index value for point C. Point 'i' will be located such that the torsion angle i-A-B-C is 'torsion' degrees. @param r: Radial distance (in same units as resulting cartesian coordinates) between A and i. @param theta: Angle in degrees of i-A-B. @param phi: Torsion angle in degrees of i-A-B-C """ if (i < 4): return if (i != self._nextIndex): raise IndexError, "next index is %d not %r" % (self._nextIndex, i) cos_theta = cos(DEG2RAD * theta) xb = self._coords[nb][0] - self._coords[na][0] yb = self._coords[nb][1] - self._coords[na][1] zb = self._coords[nb][2] - self._coords[na][2] rba = 1.0 / sqrt(xb*xb + yb*yb + zb*zb) if abs(cos_theta) >= 0.999: # Linear case # Skip angles, just extend along A-B. rba = r * rba * cos_theta xqd = xb * rba yqd = yb * rba zqd = zb * rba else: xc = self._coords[nc][0] - self._coords[na][0] yc = self._coords[nc][1] - self._coords[na][1] zc = self._coords[nc][2] - self._coords[na][2] xyb = sqrt(xb*xb + yb*yb) inv = False if xyb < 0.001: # A-B points along the z axis. tmp = zc zc = -xc xc = tmp tmp = zb zb = -xb xb = tmp xyb = sqrt(xb*xb + yb*yb) inv = True costh = xb / xyb sinth = yb / xyb xpc = xc * costh + yc * sinth ypc = yc * costh - xc * sinth sinph = zb * rba cosph = sqrt(abs(1.0- sinph * sinph)) xqa = xpc * cosph + zc * sinph zqa = zc * cosph - xpc * sinph yzc = sqrt(ypc * ypc + zqa * zqa) if yzc < 1e-8: coskh = 1.0 sinkh = 0.0 else: coskh = ypc / yzc sinkh = zqa / yzc sin_theta = sin(DEG2RAD * theta) sin_phi = -sin(DEG2RAD * phi) cos_phi = cos(DEG2RAD * phi) # Apply the bond length. xd = r * cos_theta yd = r * sin_theta * cos_phi zd = r * sin_theta * sin_phi # Compute the atom position using bond and torsional angles. ypd = yd * coskh - zd * sinkh zpd = zd * coskh + yd * sinkh xpd = xd * cosph - zpd * sinph zqd = zpd * cosph + xd * sinph xqd = xpd * costh - ypd * sinth yqd = ypd * costh + xpd * sinth if inv: tmp = -zqd zqd = xqd xqd = tmp self._coords[i][0] = xqd + self._coords[na][0] self._coords[i][1] = yqd + self._coords[na][1] self._coords[i][2] = zqd + self._coords[na][2] self._nextIndex = self._nextIndex + 1 def getCartesian(self, index): """ Return the cartesian coordinates for a point added via addInternal(). Units are the same as for the 'r' parameter of addInternal(). """ if (index < self._nextIndex and index > 0): return V(self._coords[index][0], self._coords[index][1], self._coords[index][2]) raise IndexError, "%r not defined" % index
NanoCAD-master
cad/src/geometry/InternalCoordinatesToCartesian.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ geometry.py -- miscellaneous purely geometric routines. @author: Josh @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. History: - Made by bruce 060119 from code (mostly by Josh) split out of other files. """ # Note: this module should not import from model modules # (such as those defining class Atom or Chunk). Callers # should handle model or ui dependent features themselves, # e.g. extract geometric info from model objects before # passing it here, or generate history warnings, or make up # default axes based on the screen direction. The code in # this file should remain purely geometric. import math from Numeric import transpose, minimum, maximum, remainder, size, add from Numeric import Float, zeros, multiply, sign, dot from LinearAlgebra import solve_linear_equations, eigenvectors from utilities import debug_flags # for atom_debug from geometry.VQT import V, A, cat, norm, cross, X_AXIS, Y_AXIS def selection_polyhedron(basepos, borderwidth = 1.8): """ Given basepos (a Numeric array of 3d positions), compute and return (as a list of vertices, each pair being an edge to draw) a simple bounding polyhedron, convenient for designating the approximate extent of this set of points. (This is used on the array of atom and open bond positions in a chunk to designate a selected chunk.) Make every face farther out than it needs to be to enclose all points in basepos, by borderwidth (default 1.8). Negative values of borderwidth might sometimes work, but are likely to fail drastically if the polyhedron is too small. The orientation of the faces matches the coordinate axes used in basepos (in typical calls, these are chunk-relative). [#e Someday we might permit caller-specified orientation axes. The axes of inertia would be interesting to try.] """ #bruce 060226/060605 made borderwidth an argument (non-default values untested); documented retval format #bruce 060119 split this out of shakedown_poly_evals_evecs_axis() in chunk.py. # Note, it has always had some bad bugs for certain cases, like long diagonal rods. if not len(basepos): return [] # a guess # find extrema in many directions xtab = dot(basepos, polyXmat) mins = minimum.reduce(xtab) - borderwidth maxs = maximum.reduce(xtab) + borderwidth polyhedron = makePolyList(cat(maxs,mins)) # apparently polyhedron is just a long list of vertices [v0,v1,v2,v3,...] to be passed to GL_LINES # (via drawlinelist), which will divide them into pairs and draw lines v0-v1, v2-v3, etc. # Maybe we should generalize the format, so some callers could also draw faces. # [bruce 060226/060605 comment] return polyhedron # == helper definitions for selection_polyhedron [moved here from drawer.py by bruce 060119] # mat mult by rowvector list and max/min reduce to find extrema D = math.sqrt(2.0)/2.0 T = math.sqrt(3.0)/3.0 # 0 1 2 3 4 5 6 7 8 9 10 11 12 # 13 14 15 16 17 18 19 20 21 22 23 24 25 polyXmat = A([[1, 0, 0, D, D, D, D, 0, 0, T, T, T, T], [0, 1, 0, D, -D, 0, 0, D, D, T, T, -T, -T], [0, 0, 1, 0, 0, D, -D, D, -D, T, -T, T, -T]]) del D, T polyMat = cat(transpose(polyXmat),transpose(polyXmat)) polyTab = [( 9, (0,7,3), [3,0,5,2,7,1,3]), (10, (0,1,4), [3,1,8,15,6,0,3]),#(10, (0,4,1), [3,0,6,15,8,1,3]), (11, (8,11,7), [4,14,21,2,5,0,4]), (12, (8,4,9), [4,0,6,15,20,14,4]), (22, (5,10,9), [18,13,16,14,20,15,18]), (23, (10,6,11), [16,13,19,2,21,14,16]), (24, (1,2,5), [8,1,17,13,18,15,8]), (25, (3,6,2), [7,2,19,13,17,1,7])] #( 9, (0,7,3), [3,0,5,2,7,1,3]), #(10, (0,1,4), [3,1,8,15,6,0,3]), #(11, (8,11,7), [4,14,21,2,5,0,4]), #(12, (8,4,9), [4,0,6,15,20,14,4]), #(22, (5,10,9), [18,13,16,14,20,15,18]), #(23, (10,6,11), [16,13,19,2,21,14,16]), #(24, (1,2,5), [8,1,17,13,18,15,8]), #(25, (3,6,2), [7,2,19,13,17,1,7])] ##(22, (10,5,9), [16,13,18,15,20,14,16]), #(23, (10,6,11), [16,13,19,2,21,14,16]), #(24, (2, 5, 1), [17,13,18,15,8,1,17]), #(25, (2,3,6), [17,1,7,2,19,13,17])] def planepoint(v,i,j,k): mat = V(polyMat[i],polyMat[j],polyMat[k]) vec = V(v[i],v[j],v[k]) return solve_linear_equations(mat, vec) def makePolyList(v): xlines = [[],[],[],[],[],[],[],[],[],[],[],[]] segs = [] for corner, edges, planes in polyTab: linx = [] for i in range(3): l,s,r = planes[2*i:2*i+3] e = remainder(i+1,3) p1 = planepoint(v,corner,l,r) if abs(dot(p1,polyMat[s])) <= abs(v[s]): p2 = planepoint(v,l,s,r) linx += [p1] xlines[edges[i]] += [p2] xlines[edges[e]] += [p2] segs += [p1,p2] else: p1 = planepoint(v,corner,l,s) p2 = planepoint(v,corner,r,s) linx += [p1,p2] xlines[edges[i]] += [p1] xlines[edges[e]] += [p2] e=edges[0] xlines[e] = xlines[e][:-2] + [xlines[e][-1],xlines[e][-2]] for p1,p2 in zip(linx, linx[1:]+[linx[0]]): segs += [p1,p2] ctl = 12 for lis in xlines[:ctl]: segs += [lis[0],lis[3],lis[1],lis[2]] assert type(segs) == type([]) #bruce 041119 return segs def trialMakePolyList(v): # [i think this is experimental code by Huaicai, never called, perhaps never tested. -- bruce 051117] pMat = [] for i in range(size(v)): pMat += [polyMat[i] * v[i]] segs = [] for corner, edges, planes in polyTab: pts = size(planes) for i in range(pts): segs += [pMat[corner], pMat[planes[i]]] segs += [pMat[planes[i]], pMat[planes[(i+1)%pts]]] return segs # == def inertia_eigenvectors(basepos, already_centered = False): """ Given basepos (an array of positions), compute and return (as a 2-tuple) the lists of eigenvalues and eigenvectors of the inertia tensor (computed as if all points had the same mass). These lists are always length 3, even for len(basepos) of 0,1, or 2, overlapping or colinear points, etc, though some evals will be 0 in these cases. Optional small speedup: if caller knows basepos is centered at the origin, it can say so. """ #bruce 060119 split this out of shakedown_poly_evals_evecs_axis() in chunk.py basepos = A(basepos) # make sure it's a Numeric array if not already_centered and len(basepos): center = add.reduce(basepos)/len(basepos) basepos = basepos - center # compute inertia tensor tensor = zeros((3,3),Float) for p in basepos: rsq = dot(p, p) m= - multiply.outer(p, p) m[0,0] += rsq m[1,1] += rsq m[2,2] += rsq tensor += m evals, evecs = eigenvectors(tensor) assert len(evals) == len(evecs) == 3 return evals, evecs if 0: # self-test; works fine as of 060119 def testie(points): print "ie( %r ) is %r" % ( points, inertia_eigenvectors(points) ) map( testie, [ [], [V(0,0,0)], [V(0,0,1)], # not centered [V(0,0,-1), V(0,0,1)], [V(0,0,-1), V(0,0,0), V(0,0,1)], [V(0,1,1), V(0,-1,-1), V(0,1,-1), V(0,-1,1)], [V(1,4,9), V(1,4,-9), V(1,-4,9), V(1,-4,-9), V(-1,4,9), V(-1,4,-9), V(-1,-4,9), V(-1,-4,-9)], ]) # == def unzip(pairs): """ inverse of zip, for a list of pairs. [#e should generalize.] [#e probably there's a simple general implem - transpose?] """ return [pair[0] for pair in pairs], [pair[1] for pair in pairs] def compute_heuristic_axis( basepos, type, evals_evecs = None, already_centered = False, aspect_threshhold = 0.95, numeric_threshhold = 0.0001, near1 = None, near2 = None, nears = (), dflt = None ): #bruce 060120 adding nears; will doc this and let it fully replace near1 and near2, but not yet, # since Mark is right now adding code that calls this with near1 and near2 ###@@@ """ Given basepos (an array of positions), compute and return an axis in one of various ways according to 'type' (choices are listed below), optionally adjusting the algorithm using aspect_threshhold (when are two dimensions close enough to count as circular), and numeric_threshhold (roughly, precision of coordinate values) (numeric_threshhold might be partly nim ###). Optional speed optimizations: if you know basepos is already_centered, you can say so; if (even better) you have the value of inertia_eigenvectors(basepos, already_centered = already_centered), you can pass that value so it doesn't have to be recomputed. (Computing it is the only way basepos is used in this routine.) The answer is always arbitrary in sign, so try to disambiguate it using (in order) whichever of near1, near2, and dflt is provided (by making it have positive dot product with the first one possible); but if none of those are provided and helpful (not perpendicular), return the answer with an arbitrary sign. If the positions require an arbitrary choice within a plane, and near1 is provided, try to choose the direction in that plane closest to near1; if they're all equally close (using numeric_threshhold), try near2 in the same way (ideally near2 should be perpendicular to near1). If the positions require a completely arbitrary choice, return dflt. Typical calls from the UI pass near1 = out of screen, near2 = up (parallel to screen), dflt = out of screen or None (depending on whether caller wants to detect the need to use dflt in order to print a warning). [#k guesses] Typical calls with no UI pass near1 = V(0,0,1), near2 = V(0,1,0), dflt = V(0,0,1). Choices of type (required argument) are: 'normal' - try to return the shortest axis; if ambiguous, use near directions to choose within a plane, or return dflt for a blob. Works for 2 or more points; treats single point (or no points) as a blob. This should be used by rotary and linear motors, since they want to connect to atoms on a surface (intention as of 060119), and by viewNormalTo. 'parallel' - try to return the longest axis; otherwise like 'normal'. This should be used by viewParallelTo. 'chunk' - for slabs close enough to circles or squares (using aspect_threshhold), like 'normal', otherwise like 'parallel'. This is used for computing axes of chunks for purposes of how they interactively slide in certain UI modes. (Note that viewParallelTo and viewNormalTo, applied to a chunk or perhaps to jigs containing sets of atoms, should compute their own values as if applied to the same atoms, since the chunk or jig will compute its axis in a different way, both in choice of type argument, and in values of near1, near2, and dflt.) """ #bruce 060119 split this out of shakedown_poly_evals_evecs_axis() in chunk.py, added some options. # Could clean it up by requiring caller to pass evals_evecs (no longer needing args basepos and already_centered). # According to tested behavior of inertia_eigenvectors, we don't need any special cases for # len(basepos) in [0,1,2], or points overlapping or colinear, etc! if evals_evecs is None: evals_evecs = inertia_eigenvectors( basepos, already_centered = already_centered) del basepos evals, evecs = evals_evecs # evals[i] tells you moment of inertia when rotating around axis evecs[i], which is larger if points are farther from axis. # So for a slab of dims 1x4x9, for axis '1' we see dims '4' and '9' and eval is the highest in that case. valvecs = zip(evals, evecs) valvecs.sort() evals, evecs = unzip(valvecs) # (custom helper function, inverse of zip in this case) assert evals[0] <= evals[1] <= evals[2] # evals[0] is now the lowest-valued evals[i] (i.e. longest axis, heuristically), evals[2] the highest. # (The heuristic relating this to axis-length assumes a uniform density of points # over some volume or its smooth-enough surface.) if type == 'chunk': if aspect_too_close( evals[0], evals[1], aspect_threshhold ): # sufficiently circular-or-square pancake/disk/slab/plane type = 'normal' # return the axle of a wheel else: # anything else type = 'parallel' # return the long axis pass if type == 'normal': # we want the shortest axis == largest eval; try axis (evec) with largest eval first: evals.reverse() evecs.reverse() elif type == 'parallel': # we want longest axis == shortest eval; order is already correct pass else: assert 0, "unrecognized type %r" % (type,) axes = [ evecs[0] ] for i in [1,2]: # order of these matters, I think if aspect_too_close( evals[0], evals[i], aspect_threshhold ): axes.append( evecs[i] ) del evals, evecs #bruce 060120 adding nears; will replace near1, near2, but for now, accept them all, use in that order: goodvecs = [near1, near2] + list(nears) # len(axes) now tells us how ambiguous the answer is, and axes are the vectors to make it from. if len(axes) == 1: # we know it up to a sign. answer = best_sign_on_vector( axes[0], goodvecs + [dflt], numeric_threshhold ) elif len(axes) == 2: # the answer is arbitrary within a plane. answer = best_vector_in_plane( axes, goodvecs, numeric_threshhold ) # (this could be None if caller didn't provide orthogonal near1 and near2) else: assert len(axes) == 3 # the answer is completely arbitrary answer = dflt return answer # end of compute_heuristic_axis # == helper functions for compute_heuristic_axis (likely to also be generally useful) def aspect_too_close( dim1, dim2, aspect_threshhold ): """ Are dim1 and dim2 (positive or zero real numbers) as close to 1:1 ratio as aspect_threshhold is to 1.0? """ # make sure it doesn't matter whether aspect_threshhold or 1/aspect_threshhold is passed aspect_threshhold = float(aspect_threshhold) if aspect_threshhold > 1: aspect_threshhold = 1.0 / aspect_threshhold if dim2 < dim1: dim2, dim1 = dim1, dim2 return dim1 >= (dim2 * aspect_threshhold) def best_sign_on_vector(vec, goodvecs, numeric_threshhold): """ vec is an arbitrary vector, and goodvecs is a list of unit vectors or (ignored) zero vectors or Nones; return vec or - vec, whichever is more in the same direction as the first goodvec which helps determine this (i.e. which is not zero or None, and is not perpendicular to vec, using numeric_threshhold to determine what's too close to call). If none of the goodvecs help, just return vec (this always happens if vec itself is too small, so it's safest if vec is a unit vector, though it's not required). """ for good in goodvecs: if good is not None: d = dot(vec, good) s = sign_with_threshhold(d, numeric_threshhold) if s: # it helps! return s * vec return vec def sign_with_threshhold( num, thresh ): """ Return -1, 0, or 1 as num is << 0, close to 0, or >> 0, where "close to 0" means abs(num) <= thresh. """ if abs(num) <= thresh: return 0 return sign(num) def best_vector_in_plane( axes, goodvecs, numeric_threshhold ): """ axes is a list of two orthonormal vectors defining a plane, and goodvecs is a list of unit vectors or (ignored) zero vectors or Nones; return whichever unit vector in the plane defined by axes is closest in direction to the first goodvec which helps determine this (i.e. which is not zero or None, and is not perpendicular to the plane, using numeric_threshhold to determine what's too close to call). If none of the goodvecs help, return None. """ x,y = axes for good in goodvecs: if good is not None: dx = dot(x,good) # will be 0 for good = V(0,0,0); not sensible for vlen(good) other than 0 or 1 dy = dot(y,good) if abs(dx) < numeric_threshhold and abs(dy) < numeric_threshhold: continue # good is perpendicular to the plane (or is zero) return norm(dx * x + dy * y) return None def arbitrary_perpendicular( vec, nicevecs = [] ): #bruce 060608, probably duplicates other code somewhere (check in VQT?) """ Return an arbitrary unit vector perpendicular to vec (a Numeric array, 3 floats), making it from vec and as-early-as-possible nicevecs (if any are passed). """ nicevecs = map(norm, nicevecs) + [X_AXIS, Y_AXIS] # we'll look at vec and each nicevec until they span a subspace which includes a perpendicular. # if we're not done, it means our subspace so far is spanned by just vec itself. vec = norm(vec) if not vec: return nicevecs[0] # the best we can do for nice in nicevecs: res = norm( nice - vec * dot(nice, vec) ) if res: return res return nicevecs[0] # should never happen def matrix_putting_axis_at_z(axis): #bruce 060608 """ Return an orthonormal matrix which can be used (via dot(points, matrix) for a Numeric array of 3d points) to transform points so that axis transforms to the z axis. (Not sure if it has determinant 1 or -1. If you're sure, change it to always be determinant 1.) """ # this code was modified from ops_select.py's findAtomUnderMouse, as it prepares to call Chunk.findAtomUnderMouse z = norm(axis) x = arbitrary_perpendicular(axis) y = cross(z,x) matrix = transpose(V(x,y,z)) return matrix """ notes, 060119, probably can be removed soon: motor axis - use 'view normal to' algorithm chunk axis - weirdest case - ### - for 1x4x9 take 9, but for 1x9x9 take 1. view normal to - for 1x4x9, take the short '1' dim; if answer ambiguous w/in a plane (atoms are in a sausage; aspect_threshhold?), prefer axis w/in that plane near the current one view parallel to - for 1x4x9, take the long '9' dim; if answer is ambiguous w/in a plane (atom plane is circular) (use aspect_threshhold to decide it's ambiguous) prefer an axis w/in that plane near the current one those work fine for 2 atoms (in different posns), as if 1x1x9 slab; for single atom or blob or 1x1x1 slab, in those cases, just return None (let caller do noop), or could return exact current axis... so the options are: - normal, parallel, or chunk - aspect_threshhold 0.95 - numeric_threshhold 0.0001 """ #end
NanoCAD-master
cad/src/geometry/geometryUtilities.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ NeighborhoodGenerator.py -- linear time way to find overlapping or nearby atoms. @author: Will @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Will wrote this in bonds.py for use in bond inference. Bruce 080411 moved it into its own module, classifying it as geometry (i.e. moving it into that source package) since it's essentially purely geometric (and could easily be generalized to be entirely so) -- all it assumes about "atoms" is that they have a few methods like .posn() and .is_singlet(), and it needs no imports from model. """ import struct from Numeric import floor from geometry.VQT import vlen # == # This is an order(N) operation that produces a function which gets a # list of potential neighbors in order(1) time. This is handy for # inferring bonds for PDB files that lack any bonding information. class NeighborhoodGenerator: """ Given a list of atoms and a radius, be able to quickly take a point and generate a neighborhood, which is a list of the atoms within that radius of the point. Reading in the list of atoms is done in O(n) time, where n is the number of atoms in the list. Generating a neighborhood around a point is done in O(1) time. So this is a pretty efficient method for finding neighborhoods, especially if the same generator can be used many times. """ def __init__(self, atomlist, maxradius, include_singlets = False): self._buckets = { } self._oldkeys = { } self._maxradius = 1.0 * maxradius self.include_singlets = include_singlets for atom in atomlist: self.add(atom) def _quantize(self, vec): """ Given a point in space, partition space into little cubes so that when the time comes, it will be quick to locate and search the cubes right around a point. """ maxradius = self._maxradius return (int(floor(vec[0] / maxradius)), int(floor(vec[1] / maxradius)), int(floor(vec[2] / maxradius))) def add(self, atom, _pack = struct.pack): buckets = self._buckets if self.include_singlets or not atom.is_singlet(): # The keys of the _buckets dictionary are 12-byte strings. # Comparing them when doing lookups should be quicker than # comparisons between tuples of integers, so dictionary # lookups will go faster. i, j, k = self._quantize(atom.posn()) key = _pack('lll', i, j, k) buckets.setdefault(key, []).append(atom) self._oldkeys[atom.key] = key def atom_moved(self, atom): """ If an atom has been added to a neighborhood generator and is later moved, this method must be called to refresh the generator's position information. This only needs to be done during the useful lifecycle of the generator. """ oldkey = self._oldkeys[atom.key] self._buckets[oldkey].remove(atom) self.add(atom) def region(self, center, _pack = struct.pack): """ Given a position in space, return the list of atoms that are within the neighborhood radius of that position. """ buckets = self._buckets def closeEnough(atm, radius = self._maxradius): return vlen(atm.posn() - center) < radius lst = [ ] x0, y0, z0 = self._quantize(center) for x in range(x0 - 1, x0 + 2): for y in range(y0 - 1, y0 + 2): for z in range(z0 - 1, z0 + 2): # keys are 12-byte strings, see rationale above key = _pack('lll', x, y, z) if buckets.has_key(key): lst += filter(closeEnough, buckets[key]) return lst def remove(self, atom): key = self._quantize(atom.posn()) try: self._buckets[key].remove(atom) except: pass pass # end of class NeighborhoodGenerator # end
NanoCAD-master
cad/src/geometry/NeighborhoodGenerator.py
NanoCAD-master
cad/src/geometry/__init__.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ VQT.py - Vectors, Quaternions, and [no longer in this file] Trackballs Vectors are a simplified interface to the Numeric arrays. A relatively full implementation of Quaternions (but note that we use the addition operator to multiply them). @author: Josh @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. Note: bruce 071216 moved class Trackball into its own file, so the remaining part of this module can be classified as "geometry" (though it also contains some plain old "math"). """ import math from utilities import debug_flags from foundation.state_utils import DataMixin import Numeric _DEBUG_QUATS = False #bruce 050518; I'll leave this turned on in the main sources for awhile #bruce 080401 update: good to leave this on for now, but turn it off soon # as an optimization -- no problems turned up so far, but the upcoming # PAM3+5 code is about to use it a lot more. #bruce 090306 turned this off intType = type(2) floType = type(2.0) numTypes = [intType, floType] def V(*v): return Numeric.array(v, Numeric.Float) def A(a): return Numeric.array(a, Numeric.Float) def cross(v1, v2): #bruce 050518 comment: for int vectors, this presumably gives an int vector result # (which is correct, and unlikely to cause bugs even in calling code unaware of it, # but ideally all calling code would be checked). return V(v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]) def vlen(v1): #bruce 050518 question: is vlen correct for int vectors, not only float ones? # In theory it should be, since sqrt works for int args and always gives float answers. # And is it correct for Numeric arrays of vectors? I don't know; norm is definitely not. return Numeric.dot(v1, v1) ** 0.5 def norm(v1): #bruce 050518 questions: # - Is this correct for int vectors, not only float ones? # In theory it should be, since vlen is always a float (see above). # - Is it correct for Numeric arrays of vectors (doing norm on each one alone)? # No... clearly the "if" makes the same choice for all of them, but even ignoring that, # it gives an alignment exception for any vector-array rather than working at all. # I don't know how hard that would be to fix. lng = Numeric.dot(v1, v1) ** 0.5 if lng: return v1 / lng # bruce 041012 optimized this by using lng instead of # recomputing vlen(v1) -- code was v1 / vlen(v1) else: return v1 + 0 def angleBetween(vec1, vec2): """ Return the angle between two vectors, in degrees, but try to cover all the weird cases where numerical anomalies could pop up. """ # paranoid acos(dotproduct) function, wware 051103 # [TODO: should merge with threepoint_angle_in_radians] TEENY = 1.0e-10 lensq1 = Numeric.dot(vec1, vec1) if lensq1 < TEENY: return 0.0 lensq2 = Numeric.dot(vec2, vec2) if lensq2 < TEENY: return 0.0 #Replaced earlier formula "vec1 /= lensq1 ** .5" to fix the #following bug: #The above formula was modifying the arguments using the /= statement. #Numeric.array objects (V objects) are mutable, and op= operators modify #them so replacing [--ninad 20070614 comments, based on an email #conversation with Bruce where he noticed the real problem.] vec1 = vec1 / lensq1 ** .5 vec2 = vec2 / lensq2 ** .5 # The case of nearly-equal vectors will be covered by the >= 1.0 clause. #diff = vec1 - vec2 #if dot(diff, diff) < TEENY: # return 0.0 dprod = Numeric.dot(vec1, vec2) if dprod >= 1.0: return 0.0 if dprod <= -1.0: return 180.0 return (180 / math.pi) * math.acos(dprod) def threepoint_angle_in_radians(p1, p2, p3): """ Given three points (Numeric arrays of floats), return the angle p1-p2-p3 in radians. """ #bruce 071030 made this from chem.atom_angle_radians. # TODO: It ought to be merged with angleBetween. # (I don't know whether that one is actually better.) # Also compare with def angle in jigs_motors. v1 = norm(p1 - p2) v2 = norm(p3 - p2) dotprod = Numeric.dot(v1, v2) if dotprod > 1.0: #bruce 050414 investigating bugs 361 and 498 (probably the same underlying bug); # though (btw) it would probably be better to skip this [now caller's] angle-printing entirely ###e # if angle obviously 0 since atoms 1 and 3 are the same. # This case (dotprod > 1.0) can happen due to numeric roundoff in norm(); # e.g. I've seen this be 1.0000000000000002 (as printed by '%r'). # If not corrected, it can make acos() return nan or have an exception! dotprod = 1.0 elif dotprod < -1.0: dotprod = -1.0 ang = math.acos(dotprod) return ang def atom_angle_radians(atom1, atom2, atom3): """ Return the angle between the positions of atom1-atom2-atom3, in radians. These "atoms" can be any objects with a .posn() method which returns a Numeric array of three floats. If these atoms are bonded, this is the angle between the atom2-atom1 and atom2-atom3 bonds, but this function does not assume they are bonded. Warning: current implementation is inaccurate for angles near 0.0 or pi (0 or 180 degrees). """ res = threepoint_angle_in_radians( atom1.posn(), atom2.posn(), atom3.posn() ) return res # p1 and p2 are points, v1 is a direction vector from p1. # return (dist, wid) where dist is the distance from p1 to p2 # measured in the direction of v1, and wid is the orthogonal # distance from p2 to the p1-v1 line. # v1 should be a unit vector. def orthodist(p1, v1, p2): dist = Numeric.dot(v1, p2 - p1) wid = vlen(p1 + dist * v1 - p2) return (dist, wid) #bruce 050518 added these: X_AXIS = V(1, 0, 0) Y_AXIS = V(0, 1, 0) Z_AXIS = V(0, 0, 1) # == class Q(DataMixin): """ Quaternion class. Many constructor forms: Q(W, x, y, z) is the quaternion with axis vector x,y,z and cos(theta/2) = W (e.g. Q(1,0,0,0) is no rotation [used a lot]) [Warning: the python argument names are not in the same order as in the usage-form above! This is not a bug, just possibly confusing.] Q(x, y, z), where x, y, and z are three orthonormal vectors describing a right-handed coordinate frame, is the quaternion that rotates the standard axes into that reference frame (the frame has to be right handed, or there's no quaternion that can do it!) Q(V(x,y,z), theta) is what you probably want [axis vector and angle]. [used widely] #doc -- units of theta? (guess: radians) Q(vector, vector) gives the quat that rotates between them [used widely] [which such quat? presumably the one that does the least rotation in all] [remaining forms were undocumented until 050518:] Q(number) gives Q(1,0,0,0) [perhaps never used, not sure] Q(quat) gives a copy of that quat [used fairly often] Q([W,x,y,z]) (for any sequence type) gives the same quat as Q(W, x, y, z) [used for parsing csys records, maybe in other places]. @warning: These quaternion objects use "+" for multiply and "*" for exponentiation, relative to "textbook" quaternions. This is not a bug, but might cause confusion if not understood, especially when making use of external reference info about quaternions. """ # History: # class by Josh. # bruce 050518 revised and extended docstring, revised some comments, # and fixed some bugs: # - added first use of constructor form "Q(x, y, z) where x, y, and z are # three orthonormal vectors", and bugfixed it (it had never worked before) # - other fixes listed below # a few other bugfixes since then, and new features for copy_val # manoj fixed a typo in the docstring, sin -> cos # bruce 080401 revised docstring, added warning about 'use "+" for multiply' # (issue was pointed out long ago by wware) counter = 50 # initial value of instance variable # [bruce 050518 moved it here, fixing bug in which it sometimes didn't get inited] def __init__(self, x, y = None, z = None, w = None): if w is not None: # 4 numbers # [bruce comment 050518: note than ints are not turned to floats, # and no checking (of types or values) or normalization is done, # and that these arg names don't correspond to their meanings, # which are W,x,y,z (as documented) rather than x,y,z,w.] self.vec = V(x, y, z, w) elif z is not None: # three axis vectors # Just use first two # [bruce comments 050518: # - bugfix/optim: test z for None, not for truth value # (only fixes z = V(0,0,0) which is not allowed here anyway, so not very important) # - This case was not used until now, and was wrong for some or all inputs # (not just returning the inverse quat as I initially thought); # so I fixed it. # - The old code sometimes used 'z' but the new code never does # (except to decide to use this case, and when _DEBUG_QUATS to check the results). # Q(x, y, z) where x, y, and z are three orthonormal vectors # is the quaternion that rotates the standard axes into that # reference frame ##e could have a debug check for vlen(x), y,z, and ortho and right-handed... # but when this is false (due to caller bugs), the check_posns_near below should catch it. xfixer = Q( X_AXIS, x) y_axis_2 = xfixer.rot(Y_AXIS) yfixer = twistor( x, y_axis_2, y) res = xfixer res += yfixer # warning: modifies res -- xfixer is no longer what it was if _DEBUG_QUATS: check_posns_near( res.rot(X_AXIS), x, "x" ) check_posns_near( res.rot(Y_AXIS), y, "y" ) check_posns_near( res.rot(Z_AXIS), z, "z" ) self.vec = res.vec if _DEBUG_QUATS: res = self # sanity check check_posns_near( res.rot(X_AXIS), x, "sx" ) check_posns_near( res.rot(Y_AXIS), y, "sy" ) check_posns_near( res.rot(Z_AXIS), z, "sz" ) return # old code (incorrect and i think never called) commented out long ago, removed in rev. 1.27 [bruce 060228] elif type(y) in numTypes: # axis vector and angle [used often] v = (x / vlen(x)) * Numeric.sin(y * 0.5) self.vec = V(Numeric.cos(y * 0.5), v[0], v[1], v[2]) elif y is not None: # rotation between 2 vectors [used often] #bruce 050518 bugfix/optim: test y for None, not for truth value # (only fixes y = V(0,0,0) which is not allowed here anyway, so not very important) # [I didn't yet verify it does this in correct order; could do that from its use # in bonds.py or maybe the new indirect use in jigs.py (if I checked iadd too). ###@@@] #bruce 050730 bugfix: when x and y are very close to equal, original code treats them as opposite. # Rewriting it to fix that, though not yet in an ideal way (just returns identity). # Also, when they're close but not that close, original code might be numerically unstable. # I didn't fix that problem. x = norm(x) y = norm(y) dotxy = Numeric.dot(x, y) v = cross(x, y) vl = Numeric.dot(v, v) ** .5 if vl<0.000001: # x, y are very close, or very close to opposite, or one of them is zero if dotxy < 0: # close to opposite; treat as actually opposite (same as pre-050730 code) ax1 = cross(x, V(1, 0, 0)) ax2 = cross(x, V(0, 1, 0)) if vlen(ax1)>vlen(ax2): self.vec = norm(V(0, ax1[0],ax1[1],ax1[2])) else: self.vec = norm(V(0, ax2[0],ax2[1],ax2[2])) else: # very close, or one is zero -- we could pretend they're equal, but let's be a little # more accurate than that -- vl is sin of desired theta, so vl/2 is approximately sin(theta/2) # (##e could improve this further by using a better formula to relate sin(theta/2) to sin(theta)), # so formula for xyz part is v/vl * vl/2 == v/2 [bruce 050730] xyz = v / 2.0 sintheta2 = vl / 2.0 # sin(theta/2) costheta2 = (1 - sintheta2**2) ** .5 # cos(theta/2) self.vec = V(costheta2, xyz[0], xyz[1], xyz[2]) else: # old code's method is numerically unstable if abs(dotxy) is close to 1. I didn't fix this. # I also didn't review this code (unchanged from old code) for correctness. [bruce 050730] theta = math.acos(min(1.0, max(-1.0, dotxy))) if Numeric.dot(y, cross(x, v)) > 0.0: theta = 2.0 * math.pi - theta w = Numeric.cos(theta * 0.5) s = ((1 - w**2)**.5) / vl self.vec = V(w, v[0]*s, v[1]*s, v[2]*s) pass elif type(x) in numTypes: # just one number [#k is this ever used?] self.vec = V(1, 0, 0, 0) else: #bruce 050518 comment: a copy of the quat x, or of any length-4 sequence [both forms are used] self.vec = V(x[0], x[1], x[2], x[3]) return # from Q.__init__ def __getattr__(self, attr): # in class Q if attr.startswith('_'): raise AttributeError, attr #bruce 060228 optim (also done at end) if attr == 'w': return self.vec[0] elif attr in ('x', 'i'): return self.vec[1] elif attr in ('y', 'j'): return self.vec[2] elif attr in ('z', 'k'): return self.vec[3] elif attr == 'angle': if -1.0 < self.vec[0] < 1.0: return 2.0 * math.acos(self.vec[0]) else: return 0.0 elif attr == 'axis': return V(self.vec[1], self.vec[2], self.vec[3]) elif attr == 'matrix': # this the transpose of the normal form # so we can use it on matrices of row vectors # [bruce comment 050518: there is a comment on self.vunrot() # which seems to contradict the above old comment by Josh. # Josh says he revised the transpose situation later than he wrote the rest, # so he's not surprised if some comments (or perhaps even rarely-used # code cases?? not sure) are out of date. # I didn't yet investigate the true situation. # To clarify the code, I'll introduce local vars w,x,y,z, mat. # This will optimize it too (avoiding 42 __getattr__ calls!). # ] w, x, y, z = self.vec self.__dict__['matrix'] = mat = Numeric.array([ [1.0 - 2.0 * (y**2 + z**2), 2.0 * (x*y + z*w), 2.0 * (z*x - y*w)], [2.0 * (x*y - z*w), 1.0 - 2.0 * (z**2 + x**2), 2.0 * (y*z + x*w)], [2.0 * (z*x + y*w), 2.0 * (y*z - x*w), 1.0 - 2.0 * (y**2 + x**2)]]) return mat raise AttributeError, 'No %r in Quaternion' % (attr,) #bruce 060209 defining __eq__ and __ne__ for efficient state comparisons # given presence of __getattr__ (desirable for Undo). # (I don't think it needs a __nonzero__ method, and if it had one # I don't know if Q(1,0,0,0) should be False or True.) #bruce 060222 note that it also now needs __eq__ and __ne__ to be # compatible with its _copyOfObject (they are). # later, __ne__ no longer needed since defined in DataMixin. # override abstract method of DataMixin def _copyOfObject(self): #bruce 051003, for use by state_utils.copy_val (in class Q) return self.__class__(self) # override abstract method of DataMixin def __eq__(self, other): #bruce 070227 revised this try: if self.__class__ is not other.__class__: return False except AttributeError: # some objects have no __class__ (e.g. Numeric arrays) return False return not (self.vec != other.vec) # assumes all quats have .vec; true except for bugs #bruce 070227 fixed "Numeric array == bug" encountered by this line (when it said "self.vec == other.vec"), # which made Q(1, 0, 0, 0) == Q(0.877583, 0.287655, 0.38354, 0) (since they're equal in at least one component)!! # Apparently it was my own bug, since it says above that I wrote this method on 060209. pass def __getitem__(self, num): return self.vec[num] def setangle(self, theta): """ Set the quaternion's rotation to theta (destructive modification). (In the same direction as before.) """ theta = Numeric.remainder(theta / 2.0, math.pi) self.vec[1:] = norm(self.vec[1:]) * Numeric.sin(theta) self.vec[0] = Numeric.cos(theta) self.__reset() return self def __reset(self): if self.__dict__.has_key('matrix'): del self.__dict__['matrix'] def __setattr__(self, attr, value): #bruce comment 050518: # - possible bug (depends on usage, unknown): this doesn't call __reset #bruce comments 080417: # - note that the x,y,z used here are *not* the same as the ones # that would normally be passed to the constructor form Q(W, x, y, z). # - it is likely that this is never used (though it is often called). # - the existence of this method might be a significant slowdown, # because it runs (uselessly) every time methods in this class # set any attributes of self, such as vec or counter. # If we can determine that it is never used, we should remove it. # Alternatively we could reimplement it using properties of a # new-style class. if attr == "w": self.vec[0] = value elif attr == "x": self.vec[1] = value elif attr == "y": self.vec[2] = value elif attr == "z": self.vec[3] = value else: self.__dict__[attr] = value def __len__(self): return 4 def __add__(self, q1): # TODO: optimize using self.vec, q1.vec """ Q + Q1 is the quaternion representing the rotation achieved by doing Q and then Q1. """ return Q(q1.w*self.w - q1.x*self.x - q1.y*self.y - q1.z*self.z, q1.w*self.x + q1.x*self.w + q1.y*self.z - q1.z*self.y, q1.w*self.y - q1.x*self.z + q1.y*self.w + q1.z*self.x, q1.w*self.z + q1.x*self.y - q1.y*self.x + q1.z*self.w) def __iadd__(self, q1): # TODO: optimize using self.vec, q1.vec """ this is self += q1 """ temp = V(q1.w*self.w - q1.x*self.x - q1.y*self.y - q1.z*self.z, q1.w*self.x + q1.x*self.w + q1.y*self.z - q1.z*self.y, q1.w*self.y - q1.x*self.z + q1.y*self.w + q1.z*self.x, q1.w*self.z + q1.x*self.y - q1.y*self.x + q1.z*self.w) self.vec = temp self.counter -= 1 if self.counter <= 0: self.counter = 50 self.normalize() self.__reset() return self def __sub__(self, q1): return self + (-q1) def __isub__(self, q1): return self.__iadd__(-q1) def __mul__(self, n): """ multiplication by a scalar, i.e. Q1 * 1.3, defined so that e.g. Q1 * 2 == Q1 + Q1, or Q1 = Q1 * 0.5 + Q1 * 0.5 Python syntax makes it hard to do n * Q, unfortunately. """ # review: couldn't __rmul__ be used to do n * Q? in theory yes, # but was some other problem referred to, e.g. in precedence? I don't know. [bruce 070227 comment] # [update, bruce 071216: I think n * Q has been found to work by test -- not sure. # Maybe Python now uses this def to do it?] if type(n) in numTypes: nq = + self # scalar '+' to copy self nq.setangle(n * self.angle) return nq else: raise ValueError, "can't multiply %r by %r" % (self, n) #bruce 070619 revised this (untested) def __imul__(self, n): #bruce 051107 bugfix (untested): replace arg q2 with n, since body used n (old code must have never been tested either) if type(n) in numTypes: self.setangle(n * self.angle) self.__reset() return self else: raise ValueError, "can't multiply %r by %r" % (self, n) #bruce 070619 revised this (untested) def __div__(self, q2): """ Return this quat divided by a number, or (untested, might not work) another quat. """ #bruce 051107: revised docstring. permit q2 to be a number (new feature). # Warning: the old code (for q2 a quat) is suspicious, since it appears to multiply two quats, # but that multiplication is not presently implemented, if I understand the __mul__ implem above! # This should be analyzed and cleaned up. if type(q2) in numTypes: #bruce 051107 new feature return self * (1.0 / q2) # old code (looks like it never could have worked, but this is not verified [bruce 051107]): return self * q2.conj()*(1.0/(q2 * q2.conj()).w) def __repr__(self): return 'Q(%g, %g, %g, %g)' % (self.w, self.x, self.y, self.z) def __str__(self): a= "<q:%6.2f @ " % (2.0 * math.acos(self.w) * 180 / math.pi) l = Numeric.sqrt(self.x**2 + self.y**2 + self.z**2) if l: z = V(self.x, self.y, self.z) / l a += "[%4.3f, %4.3f, %4.3f] " % (z[0], z[1], z[2]) else: a += "[%4.3f, %4.3f, %4.3f] " % (self.x, self.y, self.z) a += "|%8.6f|>" % vlen(self.vec) return a def __pos__(self): ## return Q(self.w, self.x, self.y, self.z) # [optimized by bruce 090306, not carefully tested] return Q(self.vec) def __neg__(self): return Q(self.w, -self.x, -self.y, -self.z) def conj(self): return Q(self.w, -self.x, -self.y, -self.z) def normalize(self): w = self.vec[0] v = V(self.vec[1],self.vec[2],self.vec[3]) length = Numeric.dot(v, v) ** .5 if length: s = ((1.0 - w**2)**0.5) / length self.vec = V(w, v[0]*s, v[1]*s, v[2]*s) else: self.vec = V(1, 0, 0, 0) return self def unrot(self, v): return Numeric.matrixmultiply(self.matrix, v) def vunrot(self, v): # for use with row vectors # [bruce comment 050518: the above old comment by Josh seems to contradict # the comment about 'matrix' in __getattr__ (also old and by Josh) # that it's the transpose of the normal form so it can be used for row vectors. # See the other comment for more info.] return Numeric.matrixmultiply(v, Numeric.transpose(self.matrix)) def rot(self, v): return Numeric.matrixmultiply(v, self.matrix) pass # end of class Q # == def twistor(axis, pt1, pt2): #bruce 050724 revised code (should not change the result) """ Return the quaternion that, rotating around axis, will bring pt1 closest to pt2. """ #bruce 050518 comment: now using this in some cases of Q.__init__; not the ones this uses! theta = twistor_angle(axis, pt1, pt2) return Q(axis, theta) def twistor_angle(axis, pt1, pt2): #bruce 050724 split this out of twistor() q = Q(axis, V(0, 0, 1)) pt1 = q.rot(pt1) pt2 = q.rot(pt2) a1 = math.atan2(pt1[1],pt1[0]) a2 = math.atan2(pt2[1],pt2[0]) theta = a2 - a1 return theta def proj2sphere(x, y): """ project a point from a tangent plane onto a unit sphere """ d = (x*x + y*y) ** .5 theta = math.pi * 0.5 * d s = Numeric.sin(theta) if d > 0.0001: return V(s*x/d, s*y/d, Numeric.cos(theta)) else: return V(0.0, 0.0, 1.0) def ptonline(xpt, lpt, ldr): """ return the point on a line (point lpt, direction ldr) nearest to point xpt """ ldr = norm(ldr) return Numeric.dot(xpt - lpt, ldr) * ldr + lpt def planeXline(ppt, pv, lpt, lv): """ Find the intersection of a line (point lpt on line, unit vector lv along line) with a plane (point ppt on plane, unit vector pv perpendicular to plane). Return the intersection point, or None if the line and plane are (almost) parallel. WARNING: don't use a boolean test on the return value, since V(0,0,0) is a real point but has boolean value False. Use "point is not None" instead. """ d = Numeric.dot(lv, pv) if abs(d) < 0.000001: return None return lpt + lv * (Numeric.dot(ppt - lpt, pv) / d) def cat(a, b): """ concatenate two arrays (the Numeric Python version is a mess) """ #bruce comment 050518: these boolean tests look like bugs! # I bet they should be testing the number of entries being 0, or so. # So I added some debug code to warn us if this happens. if not a: if (_DEBUG_QUATS or debug_flags.atom_debug): print "_DEBUG_QUATS: cat(a, b) with false a -- is it right?", a return b if not b: if (_DEBUG_QUATS or debug_flags.atom_debug): print "_DEBUG_QUATS: cat(a, b) with false b -- is it right?", b return a r1 = Numeric.shape(a) r2 = Numeric.shape(b) if len(r1) == len(r2): return Numeric.concatenate((a, b)) if len(r1) < len(r2): return Numeric.concatenate((Numeric.reshape(a,(1,) + r1), b)) else: return Numeric.concatenate((a, Numeric.reshape(b,(1,) + r2))) def Veq(v1, v2): """ tells if v1 is all equal to v2 """ return Numeric.logical_and.reduce(v1 == v2) #bruce comment 050518: I guess that not (v1 != v2) would also work (and be slightly faster) # (in principle it would work, based on my current understanding of Numeric...) # == bruce 050518 moved the following here from extrudeMode.py (and bugfixed/docstringed them) def floats_near(f1, f2): #bruce, circa 040924, revised 050518 to be relative, 050520 to be absolute for small numbers. """ Say whether two floats are "near" in value (just for use in sanity-check assertions). """ ## return abs( f1 - f2 ) <= 0.0000001 ## return abs( f1 - f2 ) <= 0.000001 * max(abs(f1),abs(f2)) return abs( f1 - f2 ) <= 0.000001 * max( abs(f1), abs(f2), 0.1) #e maybe let callers pass a different "scale" than 0.1? def check_floats_near(f1, f2, msg = ""): #bruce, circa 040924 """ Complain to stdout if two floats are not near; return whether they are. """ if floats_near(f1, f2): return True # means good (they were near) if msg: fmt = "not near (%s):" % msg else: fmt = "not near:" # fmt is not a format but a prefix print fmt, f1, f2 return False # means bad def check_posns_near(p1, p2, msg=""): #bruce, circa 040924 """ Complain to stdout if two length-3 float vectors are not near; return whether they are. """ res = True #bruce 050518 bugfix -- was False (which totally disabled this) for i in [0, 1, 2]: res = res and check_floats_near(p1[i],p2[i],msg+"[%d]"%i) return res def check_quats_near(q1, q2, msg=""): #bruce, circa 040924 """ Complain to stdout if two quats are not near; return whether they are. """ res = True #bruce 050518 bugfix -- was False (which totally disabled this) for i in [0, 1, 2, 3]: res = res and check_floats_near(q1[i],q2[i],msg+"[%d]"%i) return res # == test code [bruce 070227] if __name__ == '__main__': print "tests started" q1 = Q(1, 0, 0, 0) print q1, `q1` q2 = Q(V(0.6, 0.8, 0), 1) print q2, `q2` assert not (q1 == q2), "different quats equal!" # this bug was fixed on 070227 assert q1 != V(0, 0, 0) # this did print_compact_traceback after that was fixed; now that's fixed too # can't work yet: assert q2 * 2 == 2 * q2 # this means you have to run this from cad/src as ./ExecSubDir.py geometry/VQT.py from utilities.Comparison import same_vals q3 = Q(1, 0, 0, 0) assert same_vals( q1, q3 ), "BUG: not same_vals( Q(1,0,0,0), Q(1,0,0,0) )" print "tests done" # end
NanoCAD-master
cad/src/geometry/VQT.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ BoundingBox.py @author: Josh @version:$Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. History: This class BBox was originally in shape.py. Moved to its own module on 2007-10-17. Module classification: [bruce 080103] This is mainly geometry, so I will put it there ("optimistically"), even though it also includes graphics code, and hardcoded constants (at least 1.8 and 10.0, as of now) whose values come from considerations about its use for our model objects (atoms). """ from graphics.drawing.drawers import drawwirebox from Numeric import add, subtract, sqrt from Numeric import maximum, minimum, dot from geometry.VQT import V, A, cat from utilities.constants import black # piotr 080402 moved this to constants, default value = 1.8A from utilities.constants import BBOX_MARGIN class BBox: """ implement a bounding box in 3-space BBox(PointList) BBox(point1, point2) BBox(2dpointpair, 3dx&y, slab) data is stored hi, lo so we can use subtract.reduce """ def __init__(self, point1 = None, point2 = None, slab = None): # Huaicai 4/23/05: added some comments below to help understand the code. if slab: # convert from 2d (x, y) coordinates into its 3d world (x, y, 0) #coordinates(the lower-left and upper-right corner). #In another word, the 3d coordinates minus the z offset of the plane x = dot(A(point1), A(point2)) # Get the vector from upper-right point to the lower-left point dx = subtract.reduce(x) # Get the upper-left and lower right corner points oc = x[1] + V(point2[0]*dot(dx,point2[0]), point2[1]*dot(dx,point2[1])) # Get the four 3d cooridinates on the bottom crystal-cutting plane sq1 = cat(x,oc) + slab.normal*dot(slab.point, slab.normal) # transfer the above 4 3d coordinates in parallel to get that on #the top plane, put them together sq1 = cat(sq1, sq1+slab.thickness*slab.normal) self.data = V(maximum.reduce(sq1), minimum.reduce(sq1)) elif point2: # just 2 3d points self.data = V(maximum(point1, point2), minimum(point1, point2)) elif point1: # list of points: could be 2d or 3d? +/- 1.8 to make the bounding #box enclose the vDw ball of an atom? self.data = V(maximum.reduce(point1) + BBOX_MARGIN, minimum.reduce(point1) - BBOX_MARGIN) else: # a null bbox self.data = None def add(self, point): vl = cat(self.data, point) self.data = V(maximum.reduce(vl), minimum.reduce(vl)) def merge(self, bbox): if self.data and bbox.data: self.add(bbox.data) else: self.data = bbox.data def draw(self): if self.data: drawwirebox(black, add.reduce(self.data) / 2, subtract.reduce(self.data) / 2 ) def center(self): if self.data: return add.reduce(self.data)/2.0 else: return V(0, 0, 0) def isin(self, pt): return (minimum(pt,self.data[1]) == self.data[1] and maximum(pt,self.data[0]) == self.data[0]) def scale(self): """ Return the maximum distance from self's geometric center to any point in self (i.e. the corner-center distance). Note: This is the radius of self's bounding sphere, which is as large as, and usually larger than, the bounding sphere of self's contents. Note: self's box dimensions are slightly larger than needed to enclose its data, due to hardcoded constants in its construction methods. [TODO: document, make optional] """ if not self.data: return 10.0 #x=1.2*maximum.reduce(subtract.reduce(self.data)) dd = 0.5*subtract.reduce(self.data) # dd = halfwidths in each dimension (x,y,z) x = sqrt(dd[0]*dd[0] + dd[1]*dd[1] + dd[2]*dd[2]) # x = half-diameter of bounding sphere of self #return max(x, 2.0) return x def copy(self, offset = None): if offset: return BBox(self.data[0] + offset, self.data[1] + offset) return BBox(self.data[0], self.data[1]) pass # end
NanoCAD-master
cad/src/geometry/BoundingBox.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ Slab.py - a slab in space, with a 3d-point-in-slab test @author: not sure; could be found from svn/cvs annotate @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. Module classification: geometry Note: bruce 071215 split class Slab our of shape.py into its own module. """ from Numeric import dot from geometry.VQT import norm class Slab: """ defines a slab in space which can tell you if a point is in the slab """ def __init__(self, point, normal, thickness): self.point = point self.normal = norm(normal) self.thickness = thickness def isin(self, point): d = dot(point - self.point, self.normal) return d >= 0 and d <= self.thickness def __str__(self): return '<slab of '+`self.thickness`+' at '+`self.point`+'>' pass # end
NanoCAD-master
cad/src/geometry/Slab.py
NanoCAD-master
cad/src/dna/__init__.py
NanoCAD-master
cad/src/dna/DnaSequenceEditor/__init__.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ Ui_DnaSequenceEditor.py @author: Ninad @copyright: 2007 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: Ninad 2007-11-28: Created. TODO: - NFR: Add "Position" field. - NFR: Add "Accept" and "Cancel" checkboxes to take/abort the new sequence. - NFR: Support both "Insert" and "Overtype" modes in sequence field. - Split out find and replace widgets to their own class (low priority) - Create superclass that both the DNA and Protein sequence editors can use. BUGS: Bug 2956: Problems related to changing strand direction to "3' to 5'" direction: - Complement sequence field is offset from the sequence field when typing overhang characters. - The sequence field overhang coloring is not correct. """ from PyQt4.Qt import QToolButton from PyQt4.Qt import QPalette from PyQt4.Qt import QTextOption from PyQt4.Qt import QLabel, QString from PyQt4.Qt import QAction, QMenu from PyQt4.Qt import Qt from PM.PM_Colors import getPalette from PM.PM_Colors import sequenceEditStrandMateBaseColor from PM.PM_DockWidget import PM_DockWidget from PM.PM_WidgetRow import PM_WidgetRow from PM.PM_ToolButton import PM_ToolButton from PM.PM_ComboBox import PM_ComboBox from PM.PM_TextEdit import PM_TextEdit from PM.PM_LineEdit import PM_LineEdit from PM.PM_PushButton import PM_PushButton from utilities.icon_utilities import geticon, getpixmap from utilities.debug import print_compact_traceback _superclass = PM_DockWidget class Ui_DnaSequenceEditor(PM_DockWidget): """ The Ui_DnaSequenceEditor class defines UI elements for the Sequence Editor object. The sequence editor is usually visible while in while editing a DnaStrand. It is a DockWidget that is docked at the bottom of the MainWindow. """ _title = "Sequence Editor" _groupBoxCount = 0 _lastGroupBox = None def __init__(self, win): """ Constructor for the Ui_DnaSequenceEditor @param win: The parentWidget (MainWindow) for the sequence editor """ self.win = win # Should parentWidget for a docwidget always be win? #Not necessary but most likely it will be the case. parentWidget = win _superclass.__init__(self, parentWidget, title = self._title) #A flag used to restore the state of the Reports dock widget #(which can be accessed through View > Reports) see self.show() and #self.closeEvent() for more details. self._reportsDockWidget_closed_in_show_method = False self.setFixedHeight(90) return def show(self): """ Shows the sequence editor. While doing this, it also closes the reports dock widget (if visible) the state of the reports dockwidget will be restored when the sequence editor is closed. @see:self.closeEvent() """ self._reportsDockWidget_closed_in_show_method = False #hide the history widget first #(It will be shown back during self.close) #The history widget is hidden or shown only when both # 'View > Full Screen' and View > Semi Full Screen actions # are *unchecked* #Thus show or close methods won't do anything to history widget # if either of the above mentioned actions is checked. if self.win.viewFullScreenAction.isChecked() or \ self.win.viewSemiFullScreenAction.isChecked(): pass else: if self.win.reportsDockWidget.isVisible(): self.win.reportsDockWidget.close() self._reportsDockWidget_closed_in_show_method = True _superclass.show(self) return def closeEvent(self, event): """ Overrides close event. Makes sure that the visible state of the reports widgetis restored when the sequence editor is closed. @see: self.show() """ _superclass.closeEvent(self, event) if self.win.viewFullScreenAction.isChecked() or \ self.win.viewSemiFullScreenAction.isChecked(): pass else: if self._reportsDockWidget_closed_in_show_method: self.win.viewReportsAction.setChecked(True) self._reportsDockWidget_closed_in_show_method = False return def _loadWidgets(self): """ Overrides PM.PM_DockWidget._loadWidgets. Loads the widget in this dockwidget. """ self._loadMenuWidgets() self._loadTextEditWidget() return def _loadMenuWidgets(self): """ Load the various menu widgets (e.g. Open, save sequence options, Find and replace widgets etc. """ #Note: Find and replace widgets might be moved to their own class. self.loadSequenceButton = PM_ToolButton( self, iconPath = "ui/actions/Properties Manager/Open.png") self.saveSequenceButton = PM_ToolButton( self, iconPath = "ui/actions/Properties Manager/Save_Strand_Sequence.png") self.loadSequenceButton.setAutoRaise(True) self.saveSequenceButton.setAutoRaise(True) # Only supporting 5' to 3' direction until bug 2956 is fixed. # Mark 2008-12-19 editDirectionChoices = ["5' to 3'"] # , "3' to 5'"] self.baseDirectionChoiceComboBox = \ PM_ComboBox( self, choices = editDirectionChoices, index = 0, spanWidth = False ) #Find and replace widgets -- self.findLineEdit = \ PM_LineEdit( self, label = "", spanWidth = False) self.findLineEdit.setMaximumWidth(60) self.replaceLineEdit = \ PM_LineEdit( self, label = "", spanWidth = False) self.replaceLineEdit.setMaximumWidth(60) self.findOptionsToolButton = PM_ToolButton(self) self.findOptionsToolButton.setMaximumWidth(12) self.findOptionsToolButton.setAutoRaise(True) self.findOptionsToolButton.setPopupMode(QToolButton.MenuButtonPopup) self._setFindOptionsToolButtonMenu() self.findNextToolButton = PM_ToolButton( self, iconPath = "ui/actions/Properties Manager/Find_Next.png") self.findNextToolButton.setAutoRaise(True) self.findPreviousToolButton = PM_ToolButton( self, iconPath = "ui/actions/Properties Manager/Find_Previous.png") self.findPreviousToolButton.setAutoRaise(True) self.replacePushButton = PM_PushButton(self, text = "Replace") self.warningSign = QLabel(self) self.warningSign.setPixmap( getpixmap('ui/actions/Properties Manager/Warning.png')) self.warningSign.hide() self.phraseNotFoundLabel = QLabel(self) self.phraseNotFoundLabel.setText("Sequence Not Found") self.phraseNotFoundLabel.hide() # NOTE: Following needs cleanup in the PM_WidgetRow/ PM_WidgetGrid # but this explanation is sufficient until thats done -- # When the widget type starts with the word 'PM_' , the # PM_WidgetRow treats it as a well defined widget and thus doesn't try # to create a QWidget object (or its subclasses) # This is the reason why qLabels such as self.warningSign and # self.phraseNotFoundLabel are defined as PM_Labels and not 'QLabels' # If they were defined as 'QLabel'(s) then PM_WidgetRow would have # recreated the label. Since we want to show/hide the above mentioned # labels (and if they were recreated as mentioned above), # we would have needed to define those something like this: # self.phraseNotFoundLabel = widgetRow._widgetList[-2] #Cleanup in PM_widgetGrid could be to check if the widget starts with #'Q' instead of 'PM_' #Widgets to include in the widget row. widgetList = [('PM_ToolButton', self.loadSequenceButton, 0), ('PM_ToolButton', self.saveSequenceButton, 1), ('QLabel', " Sequence direction:", 2), ('PM_ComboBox', self.baseDirectionChoiceComboBox , 3), ('QLabel', " Find:", 4), ('PM_LineEdit', self.findLineEdit, 5), ('PM_ToolButton', self.findOptionsToolButton, 6), ('PM_ToolButton', self.findPreviousToolButton, 7), ('PM_ToolButton', self.findNextToolButton, 8), ('QLabel', " Replace:", 9), ('PM_TextEdit', self.replaceLineEdit, 10), ('PM_PushButton', self.replacePushButton, 11), ('PM_Label', self.warningSign, 12), ('PM_Label', self.phraseNotFoundLabel, 13), ('QSpacerItem', 5, 5, 14) ] widgetRow = PM_WidgetRow(self, title = '', widgetList = widgetList, label = "", spanWidth = True ) return def _loadTextEditWidget(self): """ Load the SequenceTexteditWidgets. """ self.sequenceTextEdit = \ PM_TextEdit( self, label = " Sequence: ", spanWidth = False, permit_enter_keystroke = False) self.sequenceTextEdit.setCursorWidth(2) self.sequenceTextEdit.setWordWrapMode( QTextOption.WrapAnywhere ) self.sequenceTextEdit.setFixedHeight(20) #The StrandSequence 'Mate' it is a read only etxtedit that shows #the complementary strand sequence. self.sequenceTextEdit_mate = \ PM_TextEdit(self, label = "", spanWidth = False, permit_enter_keystroke = False ) palette = getPalette(None, QPalette.Base, sequenceEditStrandMateBaseColor) self.sequenceTextEdit_mate.setPalette(palette) self.sequenceTextEdit_mate.setFixedHeight(20) self.sequenceTextEdit_mate.setReadOnly(True) self.sequenceTextEdit_mate.setWordWrapMode(QTextOption.WrapAnywhere) #Important to make sure that the horizontal and vertical scrollbars #for these text edits are never displayed. for textEdit in (self.sequenceTextEdit, self.sequenceTextEdit_mate): textEdit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) textEdit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) return def _getFindLineEditStyleSheet(self): """ Return the style sheet for the findLineEdit. This sets the following properties only: - background-color This style is set whenever the searchStrig can't be found (sets a light red color background to the lineedit when this happens) @return: The line edit style sheet. @rtype: str """ styleSheet = "QLineEdit {"\ "background-color: rgb(255, 102, 102)"\ "}" #Not used: # background-color: rgb(217, 255, 216)\ return styleSheet def _setFindOptionsToolButtonMenu(self): """ Sets the menu for the findOptionstoolbutton that appears a small menu button next to the findLineEdit. """ self.findOptionsMenu = QMenu(self.findOptionsToolButton) self.caseSensitiveFindAction = QAction(self.findOptionsToolButton) self.caseSensitiveFindAction.setText('Match Case') self.caseSensitiveFindAction.setCheckable(True) self.caseSensitiveFindAction.setChecked(False) self.findOptionsMenu.addAction(self.caseSensitiveFindAction) self.findOptionsMenu.addSeparator() self.findOptionsToolButton.setMenu(self.findOptionsMenu) return def _addToolTipText(self): """ What's Tool Tip text for widgets in this Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_DnaSequenceEditor ToolTip_DnaSequenceEditor(self) return def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_DnaSequenceEditor whatsThis_DnaSequenceEditor(self) return
NanoCAD-master
cad/src/dna/DnaSequenceEditor/Ui_DnaSequenceEditor.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ DnaSequenceEditor.py @copyright: 2007 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: Ninad 2007-11-20: Created. NOTE: Methods such as _sequenceChanged, _stylizeSequence are copied from the old DnaGeneratorPropertyManager where they were originally defined. This old PM used to implement a 'DnaSequenceEditor text editor'. That file hasn't been deprecated yet -- 2007-11-20 TODO: Ninad 2007-11-28 (reviewed and updated by Mark 2008-12-17) - File open-save strand sequence needs more work. - The old method '_setSequence' that inserts a sequence into the text edit is slow. Apparently it replaces the whole sequence each time. This needs to be cleaned up. - Should the Find and Replace widgets and methods be defined in their own class and then called here? - Implement synchronizeLengths(). It doesn't do anything for now. - Create superclass that both the DNA and Protein sequence editors can use. BUGS: Bug 2956: Problems related to changing strand direction to "3' to 5'" direction: - Complement sequence field is offset from the sequence field when typing overhang characters. - The sequence field overhang coloring is not correct. Implementation Notes as of 2007-11-20 (reviewed and updated by Mark 2008-12-17): The Sequence Editor is shown when you edit a DnaStrand (if visible, the 'Reports' dockwidget is hidden at the same time). The editor is a docked at the bottom of the mainwindow. It has two text edits -- 'Strand' and 'Mate'. The 'Mate' (which might be renamed in future) is a readonly widget. It shows the complement of the sequence you enter in the 'Sequence' field. The user can Open or Save the strand sequence using the options in the sequence editor. """ import foundation.env as env import os import re from PyQt4.Qt import SIGNAL from PyQt4.Qt import QTextCursor, QRegExp from PyQt4.Qt import QString from PyQt4.Qt import QFileDialog from PyQt4.Qt import QMessageBox from PyQt4.Qt import QTextCharFormat, QBrush from PyQt4.Qt import QRegExp from PyQt4.Qt import QTextDocument from PyQt4.Qt import QPalette from dna.model.Dna_Constants import basesDict from dna.model.Dna_Constants import getComplementSequence from dna.model.Dna_Constants import getReverseSequence from PM.PM_Colors import getPalette from PM.PM_Colors import sequenceEditorNormalColor from PM.PM_Colors import sequenceEditorChangedColor from PM.PM_Colors import pmMessageBoxColor from utilities.prefs_constants import workingDirectory_prefs_key from dna.DnaSequenceEditor.Ui_DnaSequenceEditor import Ui_DnaSequenceEditor from utilities import debug_flags from utilities.debug import print_compact_stack from dna.model.Dna_Constants import MISSING_COMPLEMENTARY_STRAND_ATOM_SYMBOL class DnaSequenceEditor(Ui_DnaSequenceEditor): """ Creates a dockable sequence editor. The sequence editor has two text edit fields -- Strand and Mate and has various options such as load a sequence from file or save the current sequence etc. By default the sequence editor is docked in the bottom area of the mainwindow. The sequence editor shows up in Dna edit mode. """ validSymbols = QString(' <>~!@#%&_+`=$*()[]{}|^\'"\\.;:,/?') sequenceFileName = None current_strand = None # The current strand. _sequence_changed = False # Set to True when the sequence has been changed by the user. _previousSequence = "" # The previous sequence, just before the user changed it. def __init__(self, win): """ Creates a dockable sequence editor """ Ui_DnaSequenceEditor.__init__(self, win) self.isAlreadyConnected = False self.isAlreadyDisconnected = False #Flag used in self._sequenceChanged so that it doesn't get called #recusrively in the text changed signal while changing the sequence #in self.textEdit while in that method. self._suppress_textChanged_signal = False #Initial complement sequence set while reading in the strand sequence #of the strand being edited. #@see: self._setComplementSequence(), self._determine_complementSequence() self._initial_complementSequence = '' 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 """ #@see: BuildDna_PropertyManager.connect_or_disconnect_signals #for a comment about these flags. 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.loadSequenceButton, SIGNAL("clicked()"), self.openStrandSequenceFile) change_connect(self.saveSequenceButton, SIGNAL("clicked()"), self.saveStrandSequence) change_connect(self.baseDirectionChoiceComboBox, SIGNAL('currentIndexChanged(int)'), self._reverseSequence) change_connect( self.sequenceTextEdit, SIGNAL("textChanged()"), self._sequenceChanged ) change_connect( self.sequenceTextEdit, SIGNAL("editingFinished()"), self._assignStrandSequence ) change_connect( self.sequenceTextEdit, SIGNAL("cursorPositionChanged()"), self._cursorPosChanged) change_connect( self.findLineEdit, SIGNAL("textEdited(const QString&)"), self.findLineEdit_textEdited) change_connect( self.findNextToolButton, SIGNAL("clicked()"), self.findNext) change_connect( self.findPreviousToolButton, SIGNAL("clicked()"), self.findPrevious) change_connect( self.replacePushButton, SIGNAL("clicked()"), self.replace) return def update_state(self, bool_enable = True): """ Update the state of this widget by enabling or disabling it depending upon the flag bool_enable. @param bool_enable: If True , enables the widgets inside the sequence editor @type bool_enable: boolean """ for widget in self.children(): if hasattr(widget, 'setEnabled'): #The following check ensures that even when all widgets in the #Sequence Editor docWidget are disabled, the 'close' ('x') #and undock button in the top right corner are still accessible #for the user. Using self.setEnabled(False) disables #all the widgets including the corner buttons so that method #is not used -- Ninad 2008-01-17 if widget.__class__.__name__ != 'QAbstractButton': widget.setEnabled(bool_enable) return def _reverseSequence(self, itemIndex): """ Reverse the strand sequence and update the StrandTextEdit widgets. This is used when the 'strand direction' combobox item changes. Example: If the sequence direction option is 5' to 3' then while adding the bases, those get added to extend the 3' end. Changing the direction (3' to 5') reverses the existing sequence in the text edit (which was meant to be for 5' to 3') @param itemIndex: currentIndex of combobox @type itemIndex: int @see self._determine_complementSequence() and bug 2787 """ sequence = str(self.getPlainSequence()) complementSequence = str(self.sequenceTextEdit_mate.toPlainText()) reverseSequence = getReverseSequence(sequence) #Important to reverse the complement sequence separately #see bug 2787 for implementation notes. #@see self._determine_complementSequence() reverseComplementSequence = getReverseSequence(complementSequence) self._setComplementSequence(reverseComplementSequence) self._setSequence(reverseSequence) return def _sequenceChanged( self ): """ (private) Slot for the Strand Sequence textedit widget. Assumes the sequence changed directly by user's keystroke in the textedit. Other methods... """ if not self.current_strand: # Precaution return if self._suppress_textChanged_signal: return self._suppress_textChanged_signal = True cursorPosition = self.getCursorPosition() theSequence = self.getPlainSequence() theSequence.replace(" ", "X") # Space = X (unassigned). if False: # Set to True for debugging statements. if theSequence == self._previousSequence: print "The sequence did not change (YOU SHOULD NEVER SEE THIS)." elif len(theSequence) < len(self._previousSequence): print "Character(s) were deleted from the sequence." elif len(theSequence) == len(self._previousSequence): print "A character was replaced. The sequence length is the same." else: print "Character(s) where added to the sequence." pass # Insert the sequence; it will be "stylized" by _setSequence(). self._updateSequenceAndItsComplement(theSequence) # If the sequence in the text edit (field) is different from the current # strand's sequence, change the sequence field bg color to pink to # indicate that the sequence is different. If they are the same, # change the sequence field background (back) to white. if theSequence != self.current_strand.getStrandSequence(): self._sequence_changed = True else: self._sequence_changed = False self._previousSequence = theSequence self._updateSequenceBgColor() self.synchronizeLengths() self._suppress_textChanged_signal = False return def _assignStrandSequence(self): """ (private) Slot for the "editingFinished()" signal generated by the PM_TextEdit whenever the user presses the Enter key in the sequence text edit field. Assigns the sequence in the sequence editor text field to the current strand. The method it invokes also assigns complimentary bases to the mate strand(s). @see: DnaStrand.setStrandSequence @note: the method was copied from DnaStrand_EditCommand.assignStrandSequence() """ if not self.current_strand: #Fixes bug 2923 return sequenceString = self.getPlainSequence() sequenceString = str(sequenceString) #assign strand sequence only if it not the same as the current sequence seq = self.current_strand.getStrandSequence() if seq != sequenceString: self.current_strand.setStrandSequence(sequenceString) self.updateSequence(cursorPos = self.getCursorPosition()) return def _updateSequenceBgColor(self): """ Updates the sequence field background color (pink = changed, white = unchanged). """ if self._sequence_changed: bgColor = sequenceEditorChangedColor else: bgColor = sequenceEditorNormalColor palette = getPalette(None, QPalette.Base, bgColor) self.sequenceTextEdit.setPalette(palette) 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() outSequence = outSequence.toUpper() 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 = { ' ':'&#032;', '<':'&lt;', '>':'&gt;' } 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. #The <pre> tag is important to keep the fonts 'fixed pitch' i.e. #all the characters occupy the same size. This is important because #we have two text edits. (strand and Mate) the 'Mate' edit gets updated #as you type in letters in the 'StrandEdit' and these two should #appear to user as having equal lengths. outSequence = self._fixedPitchSequence(outSequence) return outSequence def _updateSequenceAndItsComplement(self, inSequence, inRestoreCursor = True): """ Update the main strand sequence and its complement. (private method) Updating the complement sequence is done as explaned in the method docstring of self._detemine_complementSequence() Note that the callers outside the class must call self.updateSequence(), but never call this method. @see: self.setsequence() -- most portion (except for calling self._determine_complementSequence() is copied over from _setSequence. @see: self._updateSequenceAndItsComplement() @see: self._determine_complementSequence() """ #Find out complement sequence complementSequence = self._determine_complementSequence(inSequence) htmlSequence = self._colorExtraSequenceCharacters(inSequence) htmlSequence = self._fixedPitchSequence(htmlSequence) complementSequence = self._fixedPitchSequence(complementSequence) # Get current cursor position before inserting inSequence. if inRestoreCursor: cursorPos = self.getCursorPosition() else: cursorPos = 0 # Specify that theSequence is definitely HTML format, because # Qt can get confused between HTML and Plain Text. self.sequenceTextEdit.insertHtml( htmlSequence ) #@@@ Generates signal??? self.sequenceTextEdit_mate.insertHtml(complementSequence) self.setCursorPosition(inCursorPos = cursorPos) return def _determine_complementSequence(self, inSequence): """ Determine the complementary sequence based on the main sequence. It does lots of thing than just obtaining the information by using 'getComplementSequence'. Examples of what it does: 1. Suppose you have a duplex with 10 basepairs. You are editing strand A and you lengthen it to create a sticky end. Lets assume that it is lengthened by 5 bases. Since there will be no complementary strand baseatoms for these, the sequence editor will show an asterisk('*'), indicating that its missing the strand mate base atom. Sequence Editor itself doesn't check each time if the strand mate is missing. Rather, it relies on what the caller supplied as the initial complement sequence. (@see: self._setComplementSequence) . The caller determines the sequence of the strand being edited and also its complement. If the complement doesn't exist, it replace the complement with a '*' and passes this information to the sequence editor. Everytime sequence editor is updating its sequnece, it updates the mate sequence and skips the positions marked '*' (by using self._initial_complementSequence), and thus those remain unaltered. If user enters a sequence which has more characters than the original sequence, then it doesn't update the complement portion of that extra portion of the sequence. This gives a visual indication of where the sequence ends. (see NFR bug 2787). Reversing the sequence also reverses the complement (including the '*' positions) @see Bug 2787 for details of the implementation. @see: self._setComplementSequence() @see: self._updateSequenceAndItsComplement() @see: self._setSequence() @see: DnaStrand_PropertyManager.updateSequence() (the caller) @see: Dna_Constants.MISSING_COMPLEMENTARY_STRAND_ATOM_SYMBOL @see: DnaStrand.getStrandSequenceAndItsComplement() """ if not self._initial_complementSequence: #This is unlikely. Do nothing in this case. return '' complementSequence = '' #Make sure that the insequence is a string object inSequence = str(inSequence) #Do the following only when the length of sequence (inSequence) is #greater than or equal to length of original complement sequence #REVIEW This could be SLOW, need to think of a better way to do this. if len(inSequence) >= len(self._initial_complementSequence): for i in range(len(self._initial_complementSequence)): if self._initial_complementSequence[i] == \ MISSING_COMPLEMENTARY_STRAND_ATOM_SYMBOL: complementSequence += self._initial_complementSequence[i] else: complementSequence += getComplementSequence(inSequence[i]) else: #Use complementSequence as a list object as we will need to modify #some of the charactes within it. We can't do for example #string[i] = 'X' as it is not permitted in python. So we will first #treat the complementSequence as a list, do necessary modifications #to it and then convert is back to a string. #TODO: see if re.sub or re.subn can be used directly to replace #some characters (the reason re.suib is not used here is that #it does find and repalce for all matching patterns, which we don't # want here ) complementSequence = list(self._initial_complementSequence) for i in range(len(inSequence)): if complementSequence[i] != MISSING_COMPLEMENTARY_STRAND_ATOM_SYMBOL: complementSequence[i] = getComplementSequence(inSequence[i]) #Now there is additinal complementary sequence (because lenght of the #main sequence provided is less than the 'original complementary #sequence' (or the 'original main strand sequence) . In this case, #for the remaining complementary sequence, we will use unassigned #base symbol 'X' . #Example: If user starts editing a strand, #the initial strand sequence and its complement are shown in the #sequence editor. Now, the user deletes some characters from the #main sequence (using , e.g. backspace in sequence text edit to #delete those), here, we will assume that this deletion of a #character is as good as making it an unassigned base 'X', #so its new complement will be of course 'X' --Ninad 2008-04-10 extra_length = len(complementSequence) - len(inSequence) #do the above mentioned replacement count = extra_length while count > 0: if complementSequence[-count] != MISSING_COMPLEMENTARY_STRAND_ATOM_SYMBOL: complementSequence[-count] = 'X' count -= 1 #convert the complement sequence back to a string complementSequence = ''.join(complementSequence) return complementSequence def _setComplementSequence(self, complementSequence): """ Set the complement sequence field to I{complementSequence}. (private) This is typically called immediately before or after calling self._setSequence(). @param complementSequence: the complementary sequence determined by the caller. This string may contain characters '*' which indicate that there is a missing strand mate atom for the strand you are editing. The Sequence Editorkeeps the '*' characters while determining the compelment sequence (if the main sequence is changed by the user) @type complementSequence: str See method docstring self._detemine_complementSequence() for more information. @see: self.updateSequence() @see: self._setSequence() @see: self._updateSequenceAndItsComplement() @see: self._determine_complementSequence() @see: DnaStrand_PropertyManager.updateSequence() """ self._initial_complementSequence = complementSequence complementSequence = self._fixedPitchSequence(complementSequence) self.sequenceTextEdit_mate.insertHtml(complementSequence) return def _setSequence( self, inSequence, inStylize = True, inRestoreCursor = True ): """ Replace the current strand sequence with the new sequence text. (private method) This is typically called immediately before or after calling self._setComplementSequence(). @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: Restores cursor to previous position. 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. @see: self.updateSequence() @see: self._setComplementSequence() @see: self._updateSequenceAndItsComplement() @see: self._determine_complementSequence() """ if inStylize: #Temporary fix for bug 2604-- #Temporarily disabling the code that 'stylizes the sequence' #that code is too slow and takes a long time for a file to load. # Example: NE1 hangs while loading M13 sequence (8kb file) if we #stylize the sequence .-- Ninad 2008-01-22 ##inSequence = self.stylizeSequence( inSequence ) # Color any overhang sequence characters gray. htmlSequence = self._colorExtraSequenceCharacters(inSequence) #Make the sequence 'Fixed pitch'. htmlSequence = self._fixedPitchSequence(htmlSequence) # Specify that theSequence is definitely HTML format, because # Qt can get confused between HTML and Plain Text. self._suppress_textChanged_signal = True self.sequenceTextEdit.insertHtml( htmlSequence ) self._suppress_textChanged_signal = False self.setCursorPosition(0) return def clear(self): """ Clear the sequence and mate fields. """ if 0: print "Cleared" self.sequenceTextEdit.insertHtml("<font color=gray></font>") self.sequenceTextEdit_mate.insertHtml("<font color=gray></font>") return def _colorExtraSequenceCharacters(self, inSequence): """ Returns I{inSequence} with html tags that color any extra overhang characters gray. @param inSequence: The sequence. @type inSequence: QString @return: inSequence with the html tags to color any overhang characters. @rtype: string """ strandLength = self.current_strand.getNumberOfBases() if len(inSequence) <= strandLength: return inSequence sequence = inSequence[:strandLength] overhang = inSequence[strandLength:] return sequence + "<font color=gray>" + overhang + "</font>" def _fixedPitchSequence(self, sequence): """ Make the sequence 'fixed-pitched' i.e. width of all characters should be constance """ #The <pre> tag is important to keep the fonts 'fixed pitch' i.e. #all the characters occupy the same size. This is important because #we have two text edits. (strand and Mate) the 'Mate' edit gets updated #as you type in letters in the 'StrandEdit' and these two should #appear to user as having equal lengths. fixedPitchSequence = "<html>" + "<pre>" + sequence fixedPitchSequence += "</pre>" + "</html>" return fixedPitchSequence 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 updateSequence(self, strand = None, cursorPos = -1): """ Updates and shows the sequence editor with the sequence of I{strand}. This is the main (public) method to call to update the sequence editor. @param strand: the strand. If strand is None (default), update the sequence of the current strand (i.e. self.current_strand). @type strand: DnaStrand @param cursorPos: the position in the sequence in which to place the cursor. If cursorPos is negative, the cursor position is placed at the end of the sequence (default). @type cursorPos: int """ if strand == " ": self.current_strand = None self.clear() return if strand: assert isinstance(strand, self.win.assy.DnaStrand) self.current_strand = strand else: # Use self.current_strand. Make sure it's not None (as a precaution). assert isinstance(self.current_strand, self.win.assy.DnaStrand) sequence, complementSequence = \ self.current_strand.getStrandSequenceAndItsComplement() if sequence: sequence = QString(sequence) sequence = sequence.toUpper() #Set the initial sequence (read in from the file) self._setSequence(sequence) #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._setComplementSequence(complementSequence) else: msg = "DnaStrand '%s' has no sequence." % self.current_strand.name print_compact_traceback(msg) self._setSequence(msg) self._setComplementSequence("") # Set cursor position. self.setCursorPosition(cursorPos) # Update the bg color to white. self._sequence_changed = False self._previousSequence = sequence self._updateSequenceBgColor() # Update window title with name of current protein. titleString = 'Sequence Editor for ' + self.current_strand.name self.setWindowTitle(titleString) if not self.isVisible(): #Show the sequence editor if it isn't visible. #ATTENTION: the sequence editor will (temporarily) close the #Reports dockwidget (if it is visible). The Reports dockwidget #is restored when the sequence Editor is closed. self.show() return def setCursorPosition(self, inCursorPos = -1): """ Set the cursor position to I{inCursorPos} in the sequence textedit widget. @param inCursorPos: the position in the sequence in which to place the cursor. If cursorPos is negative, the cursor position is placed at the end of the sequence (default). @type inCursorPos: int """ # Make sure cursorPos is in the valid range. if inCursorPos < 0: cursorPos = self.getSequenceLength() anchorPos = self.getSequenceLength() elif inCursorPos >= self.getSequenceLength(): cursorPos = self.getSequenceLength() anchorPos = self.getSequenceLength() else: cursorPos = inCursorPos anchorPos = inCursorPos # Useful print statements for debugging. #print "setCursorPosition(): Sequence=", self.getPlainSequence() #print "setCursorPosition(): Final inCursorPos=%d\ncursorPos=%d, anchorPos=%d" % (inCursorPos, cursorPos, anchorPos) # Finally, set the cursor position in the sequence. cursor = self.sequenceTextEdit.textCursor() cursor.setPosition(anchorPos, QTextCursor.MoveAnchor) cursor.setPosition(cursorPos, QTextCursor.KeepAnchor) self.sequenceTextEdit.setTextCursor( cursor ) return 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 of the strand textEdit changes. When this happens, this method also changes the cursor position of the 'Mate' text edit. Because of this, both the text edit widgets in the Sequence Editor scroll 'in sync'. """ strandSequence = self.sequenceTextEdit.toPlainText() strandSequence_mate = self.sequenceTextEdit_mate.toPlainText() #The cursorChanged signal is emitted even before the program enters #_setSequence() (or before the 'textChanged' signal is emitted) #So, simply return if the 'Mate' doesn't have same number of characters #as the 'Strand text edit' (otherwise it will print warning message # while setting the cursor_mate position later in the method. if strandSequence.length() != strandSequence_mate.length(): return cursor = self.sequenceTextEdit.textCursor() cursor_mate = self.sequenceTextEdit_mate.textCursor() if cursor_mate.position() != cursor.position(): cursor_mate.setPosition( cursor.position(), QTextCursor.MoveAnchor ) #After setting position, it is important to do setTextCursor #otherwise no effect will be observed. self.sequenceTextEdit_mate.setTextCursor(cursor_mate) return def synchronizeLengths( self ): """ Guarantees the values of the duplex length and strand length spinboxes agree with the strand sequence (textedit). @note: synchronizeLengths doesn't do anything for now """ ##self.updateStrandLength() ##self.updateDuplexLength() return def openStrandSequenceFile(self): """ Open (read) the user specified Strand sequence file and enter the sequence in the Strand sequence Text edit. Note that it ONLY reads the FIRST line of the file. @TODO: It only reads in the first line of the file. Also, it doesn't handle any special cases. (Once the special cases are clearly defined, that functionality will be added. """ if self.parentWidget.assy.filename: odir = os.path.dirname(self.parentWidget.assy.filename) else: odir = env.prefs[workingDirectory_prefs_key] self.sequenceFileName = \ str(QFileDialog.getOpenFileName( self, "Load Strand Sequence", odir, "Strand Sequnce file (*.txt);;All Files (*.*);;")) lines = self.sequenceFileName try: lines = open(self.sequenceFileName, "rU").readlines() except: print "Exception occurred to open file: ", self.sequenceFileName return sequence = lines[0] sequence = QString(sequence) sequence = sequence.toUpper() self._updateSequenceAndItsComplement(sequence) return def _writeStrandSequenceFile(self, fileName, strandSequence): """ Writes out the strand sequence (in the Strand Sequence editor) into a file. """ try: f = open(fileName, "w") except: print "Exception occurred to open file %s to write: " % fileName return None f.write(str(strandSequence)) f.close() return def saveStrandSequence(self): """ Save the strand sequence entered in the Strand text edit in the specified file. """ if not self.sequenceFileName: sdir = env.prefs[workingDirectory_prefs_key] else: sdir = self.sequenceFileName fileName = QFileDialog.getSaveFileName( self, "Save Strand Sequence As ...", sdir, "Strand Sequence File (*.txt)" ) if fileName: fileName = str(fileName) if fileName[-4] != '.': fileName += '.txt' if os.path.exists(fileName): # ...and if the "Save As" file exists... # ... confirm overwrite of the existing file. ret = QMessageBox.warning( self, "Save Strand Sequence...", "The file \"" + fileName + "\" already exists.\n"\ "Do you want to overwrite the existing file or cancel?", "&Overwrite", "&Cancel", "", 0, # Enter == button 0 1 ) # Escape == button 1 if ret == 1: # The user cancelled return # write the current set of element colors into a file self._writeStrandSequenceFile( fileName, str(self.sequenceTextEdit.toPlainText())) return # ==== Methods to support find and replace. # Should this (find and replace) be in its own class? -- Ninad 2007-11-28 def findNext(self): """ Find the next occurence of the search string in the sequence """ self._findNextOrPrevious() return def findPrevious(self): """ Find the previous occurence of the search string in the sequence """ self._findNextOrPrevious(findPrevious = True) return def _findNextOrPrevious(self, findPrevious = False): """ Find the next or previous matching string depending on the findPrevious flag. It also considers into account various findFlags user might have set (e.g. case sensitive search) @param findPrevious: If true, this method will find the previous occurance of the search string. @type findPrevious: boolean """ findFlags = QTextDocument.FindFlags() if findPrevious: findFlags |= QTextDocument.FindBackward if self.caseSensitiveFindAction.isChecked(): findFlags |= QTextDocument.FindCaseSensitively if not self.sequenceTextEdit.hasFocus(): self.sequenceTextEdit.setFocus() searchString = self.findLineEdit.text() cursor = self.sequenceTextEdit.textCursor() found = self.sequenceTextEdit.find(searchString, findFlags) #May be the cursor reached the end of the document, set it at position 0 #to redo the search. This makes sure that the search loops over as #user executes findNext multiple times. if not found: if findPrevious: sequence_QString = self.sequenceTextEdit.toPlainText() newCursorStartPosition = sequence_QString.length() else: newCursorStartPosition = 0 cursor.setPosition( newCursorStartPosition, QTextCursor.MoveAnchor) self.sequenceTextEdit.setTextCursor(cursor) found = self.sequenceTextEdit.find(searchString, findFlags) #Display or hide the warning widgets (that say 'sequence not found' #based on the boolean 'found' self._toggleWarningWidgets(found) return def _toggleWarningWidgets(self, found): """ If the given searchString is not found in the sequence string, toggle the display of the 'sequence not found' warning widgets. Also enable or disable the 'Replace' button accordingly @param found: Flag that decides whether to sho or hide warning @type found: boolean @see: self.findNext, self.findPrevious """ if not found: self.findLineEdit.setStyleSheet(self._getFindLineEditStyleSheet()) self.phraseNotFoundLabel.show() self.warningSign.show() self.replacePushButton.setEnabled(False) else: self.findLineEdit.setStyleSheet("") self.phraseNotFoundLabel.hide() self.warningSign.hide() self.replacePushButton.setEnabled(True) return def findLineEdit_textEdited(self, searchString): """ Slot method called whenever the text in the findLineEdit is edited *by the user* (and not by the setText calls). This is useful in dynamically searching the string as it gets typed in the findLineedit. """ self.findNext() #findNext sets the focus inside the sequenceTextEdit. So set it back to #to the findLineEdit to permit entering more characters. if not self.findLineEdit.hasFocus(): self.findLineEdit.setFocus() return def replace(self): """ Find a string matching the searchString given in the findLineEdit and replace it with the string given in the replaceLineEdit. """ searchString = self.findLineEdit.text() replaceString = self.replaceLineEdit.text() sequence = self.sequenceTextEdit.toPlainText() #Its important to set focus on the sequenceTextEdit otherwise, #cursor.setPosition and setTextCursor won't have any effect if not self.sequenceTextEdit.hasFocus(): self.sequenceTextEdit.setFocus() cursor = self.sequenceTextEdit.textCursor() selectionStart = cursor.selectionStart() selectionEnd = cursor.selectionEnd() sequence.replace( selectionStart, (selectionEnd - selectionStart), replaceString ) #Move the cursor position one step back. This is important to do. #Example: Let the sequence be 'AAZAAA' and assume that the #'replaceString' is empty. Now user hits 'replace' , it deletes first #'A' . Thus the new sequence starts with the second A i.e. 'AZAAA' . # Note that the cursor position is still 'selectionEnd' i.e. cursor # position index is 1. #Now you do 'self.findNext' -- so it starts with cursor position 1 #onwards, thus missing the 'A' before the character Z. That's why #the following is done. cursor.setPosition((selectionEnd - 1), QTextCursor.MoveAnchor) self.sequenceTextEdit.setTextCursor(cursor) #Set the sequence in the text edit. This could be slow. See comments #in self._updateSequenceAndItsComplement for more info. self._updateSequenceAndItsComplement(sequence) #Find the next occurance of the 'seqrchString' in the sequence. self.findNext() return
NanoCAD-master
cad/src/dna/DnaSequenceEditor/DnaSequenceEditor.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_constants.py -- constants for dna_updater @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ # note: the debug flags that were in this file # have been moved into utilities.debug_flags [bruce 080228] # end
NanoCAD-master
cad/src/dna/updater/dna_updater_constants.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_atoms.py - enforce rules on newly changed PAM atoms and bonds @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from utilities.constants import noop as STUB_FUNCTION # FIX all uses from dna.updater.dna_updater_globals import get_changes_and_clear from dna.updater.dna_updater_globals import ignore_new_changes from dna.updater.dna_updater_utils import remove_killed_atoms from dna.updater.dna_updater_utils import remove_error_atoms from utilities import debug_flags from dna.updater.fix_atom_classes import fix_atom_classes fix_bond_classes = STUB_FUNCTION from dna.updater.fix_deprecated_elements import fix_deprecated_elements from dna.updater.delete_bare_atoms import delete_bare_atoms from dna.updater.dna_updater_prefs import pref_permit_bare_axis_atoms from dna.updater.fix_bond_directions import fix_local_bond_directions ##from dna.updater.convert_from_PAM5 import convert_from_PAM5 # == def update_PAM_atoms_and_bonds(changed_atoms): """ Update PAM atoms and bonds. @param changed_atoms: an atom.key -> atom dict of all changed atoms that this update function needs to consider, which includes no killed atoms. THIS WILL BE MODIFIED to include all atoms changed herein, and to remove any newly killed atoms. @return: None """ # == # fix atom & bond classes, and break locally-illegal bonds # (Note that the dna updater only records changed bonds # by recording both their atoms as changed -- it has no # list of "changed bonds" themselves.) # note: these fix_ functions are called again below, on new atoms. fix_atom_classes( changed_atoms) fix_bond_classes( changed_atoms) # Fixes (or breaks if locally-illegal) all bonds of those atoms. # ("Locally" means "just considering that bond and its two atoms, # not worrying about other bonds on those atoms. ### REVIEW: true now? desired?) # NOTE: new bondpoints must be given correct classes by bond.bust, # since we don't fix them in this outer method! # (Can this be done incrementally? ### REVIEW) # IMPLEM THAT ### # depending on implem, fixing classes might record more atom changes; # if so, those functions also fixed the changed_atoms dict we passed in, # and we can ignore whatever additional changes were recorded: ignore_new_changes( "from fixing atom & bond classes") # == # fix deprecated elements, and the classes of any new objects this creates # (covering all new atoms, and all their bonds) # (note: we might also extend this to do PAM 3/3+5/5 conversions. not sure.) fix_deprecated_elements( changed_atoms) # changes more atoms; # implem is allowed to depend on atom & bond classes being correct # NOTE: this may kill some atoms that remain in changed_atoms # or get added to it below. Subroutines must tolerate killed atoms # until we remove them again. # Grab new atoms the prior step made, to include in subsequent steps. # (Note also that atoms already in changed_atoms might have been killed # and/or transmuted during the prior step.) new_atoms = get_changes_and_clear() if new_atoms: fix_atom_classes( new_atoms) # must tolerate killed atoms fix_bond_classes( new_atoms) # sufficient, since any changed bonds (if alive) must be new bonds. # @@@@ did that break illegal bonds, or do we do that somewhere else? [080117 Q] # Note: do changed_atoms.update only after fixing classes on new_atoms, # so any new atoms that replace old ones in new_atoms also make it # into changed_atoms. Note that this effectively replaces all old atoms # in changed_atoms. (Note that this only works because new atoms have # the same keys as old ones. Also note that none of this matters as of # 071120, since fixing classes doesn't make new objects in the present # implem.) changed_atoms.update( new_atoms ) ignore_new_changes( "from fixing classes after fixing deprecated elements") # == # delete bare atoms (axis atoms without strand atoms, or vice versa). if not pref_permit_bare_axis_atoms(): delete_bare_atoms( changed_atoms) # must tolerate killed atoms; can kill more atoms and break bonds, # but we can ignore those changes; BUT it can change neighbor atom # structure, and those changes are needed by subsequent steps # (though no need to fix their classes or look for bareness again, # as explained inside that function) # Grab newly changed atoms from that step (neighbors of deleted atoms), # to include in subsequent steps. (But no need to fix their classes # or again call delete_bare_atoms, as explained inside that function.) # (Note also that atoms already in changed_atoms might have been killed # during that step.) new_atoms = get_changes_and_clear() if new_atoms: if debug_flags.DEBUG_DNA_UPDATER: print "dna_updater: will scan %d new changes from delete_bare_atoms" % len(new_atoms) changed_atoms.update( new_atoms ) # == # Fix local directional bond issues: # - directional bond chain branches (illegal) # - missing bond directions (when fixable locally -- most are not) # - inconsistent bond directions # # The changes caused by these fixes include only: # - setting atom._dna_updater__error to a constant error code string on some atoms # - setting or unsetting bond direction on open bonds (changes from this could be ignored here) # Tentative conclusion: no need to do anything to new changed atoms # except scan them later; need to ignore atoms with _dna_updater__error set # when encountered in changed_atoms (remove them now? or in that function?) # and to stop on them when finding chains or rings. # [Note: geometric warnings (left-handed DNA, major groove on wrong side) # are not yet implemented. REVIEW whether they belong here or elsewhere -- # guess: later, once chains and ladders are known. @@@@] fix_local_bond_directions( changed_atoms) new_atoms = get_changes_and_clear() if new_atoms: if debug_flags.DEBUG_DNA_UPDATER: print "dna_updater: will scan %d new changes from fix_local_bond_directions" % len(new_atoms) changed_atoms.update( new_atoms ) # == remove_killed_atoms( changed_atoms) remove_error_atoms( changed_atoms) # replaced with code at a later stage [bruce 080408]; # we might revive this to detect Pl5 atoms that are bridging Ss3 atoms # (an error to fix early to prevent bugs) # or to make a note of ladders that need automatic conversion # due to displaying PAM5 in PAM35 form by default # ## # == ## ## # Convert from PAM5 to PAM3+5, per-atom part. [080312, unfinished] ## ## # Potential optimization (not known whether it'd be significant): ## # only do this after operations that might introduce new PAM5 atoms ## # (like mmp read, mmp insert, or perhaps Dna Generator) ## # or that change any setting that causes them to become convertable. ## # This is not practical now, since errors or non-whole base pairs prevent ## # conversion, and almost any operation can remove those errors or make the ## # base pairs whole. ## ## convert_from_PAM5( changed_atoms) ## # note: this replaces Pl5 with direct bonds, and may do more (undecided), ## # but some conversion might be done later after ladders are constructed. ## # So it might be misnamed. ### ## ## ignore_new_changes( "from converting PAM5 to PAM3+5") ## ## remove_killed_atoms( changed_atoms) return # from update_PAM_atoms_and_bonds # end
NanoCAD-master
cad/src/dna/updater/dna_updater_atoms.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_follow_strand.py - helper function for dna_updater_ladders. @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from utilities.constants import noop _FAKE_AXIS_FOR_BARE_STRANDS = [1] # arbitrary non-false object comparable using 'is' # (it might be enough for it to be not None, even if false) # (the code could be simplified to let it just be None, # but it's not worth the trouble right now) # [bruce 080117] def dna_updater_follow_strand(phase, strand, strand_axis_info, break_axis, break_strand, axis_break_between_Q = None): """ If phase is 1: Loop over strand's base atoms, watching the strand join and leave axis chains and move along them; break both axis and strand whenever it joins, leaves, or moves discontinuously along axis (treating lack of Ax as moving continuously on an imaginary Ax chain different from all real ones) (for details, see the code comments). The breaks must be done only virtually, by calling the provided functions with the 3 args (chain, index, whichside) -- the API for those functions should be the same as for the method break_chain_later of the helper class chains_to_break in the calling code. If phase is 2: Same, but the only breaks we make are strand_breaks at the same places at which axis_break_between_Q says the axis has a break (for its API doc see chains_to_break.break_between_Q in caller). @return: None """ # For phase 1: # # Loop over strand's base atoms, watching the strand join and leave # axis chains and move along them. If it jumps (moves more than one base) # or stays on the same atom (implying that it switched ladder sides -- # not physically realistic, but we can't depend on it never happening), # pretend that it left the axis and rejoined it. Leaving the axis # (pretend or really) breaks the strand there (in terms of which ladder # rail it will end up in) and breaks the axis after the leaving point # (or on both sides of that axis atom, if we didn't yet know the # direction of travel of the strand along the axis, since we just # entered the axis). Joining an axis breaks that axis before that # point, relative to the direction we'll travel in, so record this # and break the axis as we start to travel. # # The only other case is if we just change directions, i.e. we hit axis # atoms A, B, A. (This is not physically realistic, if only due to the # implied base stacking, but we can't depend on it not happening.) # This implies we changed sides of the axis (from one ladder rail to # the other), but we don't know if that was before or after B, so we # pretend we left and rejoined both before and after B. (In fact, # since either leaving or joining requires a break, maybe both these # breaks are always required. If not, extra breaks at this stage are ok, # since they'll be fixed later when we merge ladders.) # # In more detail: in case we switched after B in that A B A sequence, # do whatever a jump after B would do (no special case required). # In case we switched sides before B, we wish we'd done a jump at the # prior step, but we know enough now (in the step when we detect this) # to do all the same things that would do, so do them now. # # About rings -- we could be aware of ring index circular order, # but we want rings in ladders to be "aligned" in terms of indexes # in those ladders (one index for all 3 atoms on one ladder rung), # so the easiest way to ensure that is just to pretend rings are # chains at this stage (for both strand and axis rings), and break # strands whereever they go around the ring (jumping from end to # start). This means we should just ignore ring index circularity. # # (We may or may not patch this later by noticing which ladders are # whole rings... since moebius rings are possible, or partial rings # (axis rail is ring, strand rail is not), it's probably best to # ignore this on ladders and just follow the individual chains as # needed.) # To get started, we're in the state of having left some axis # (all done with it) and about to enter a new one. The loop body # can't know that, so record an impossible value of which axis # we're in. In general, the loop variables need to know which # axis we were in, where we were, and which way we were going # or that we just entered it, with a special case for having # been in no axis or having been all done with the prior axis. # (For phase 2, just modify this slightly.) if strand.baselength() == 0: # This was not supposed to be possible, but it can happen in the MMKit # for the "bare Pl atom". Maybe the strand should refuse to be made then, # but this special case seems to fix the assertion error we otherwise # got below, from "assert prior_axis is not None # since at least one s_atom", # so for now, permit it (with debug print) and see if it causes any other trouble. print "fyi: dna_updater_follow_strand bailing on 0-length strand %r" % (strand,) return assert phase in (1,2) if phase == 2: break_strand_phase2 = break_strand break_strand = noop # optimization break_axis = noop # optimization assert callable( axis_break_between_Q) assert callable( break_strand_phase2) else: assert axis_break_between_Q is None break_strand_phase2 = None # not used, but mollify pylint assert callable(break_axis) assert callable(break_strand) prior_axis = None prior_index = None prior_direction = None # normally, -1 or 1, or 0 for "just entered" for s_atom, s_index in list(strand.baseatom_index_pairs()) + [(None, None)]: if s_atom is None: # last iteration, just to make strand seem to jump off prior_axis # at the end assert prior_axis is not None # since at least one s_atom (axis, index) = None, None else: try: (axis, index) = strand_axis_info[s_atom.key] # Note: this fails for a bare strand atom (permittable # by debug_prefs), e.g. in the mmkit -- and more # importantly is now permitted "officially" for # representing single strands, # at least until we implement some 'unpaired-base' atoms. # So, pretend all bare strand atoms live on a special # fake axis and move along it continuously. except KeyError: axis = _FAKE_AXIS_FOR_BARE_STRANDS index = s_index # always acts like continuous motion pass # set the variables jumped, new_direction, changed_direction; # these are their values unless changed explicitly just below: jumped = False new_direction = 0 # unknown changed_direction = False if axis is prior_axis: # 'is' is ok since these are objects, both current, so disjoint in atoms delta = index - prior_index # ok to ignore ring index circularity (see above for why) if delta not in (-1,1): # see long comment above for why even 0 means we jumped jumped = True else: new_direction = delta # only used if we don't jump if phase == 2: if (axis is not _FAKE_AXIS_FOR_BARE_STRANDS) and \ axis_break_between_Q(axis, index, prior_index): # break the strand to match the axis break we just passed over break_strand_phase2(strand, s_index, -1) if prior_direction and new_direction != prior_direction: jumped = True new_direction = 0 # required when we pretend to jump changed_direction = True del delta else: jumped = True # (after this, jumped, new_direction, changed_direction are final) # We need helper routines to do a jump, since there are two # different jumps we might do. We need them in pieces since # we can't always call them all at once for one jump. # (This would be true even if we recorded all jumps and # did them all later, since we don't find out what to record # except in these pieces, during different steps.) def do_jump_from_axis(from_axis, from_index, from_direction): # break from_axis after the leaving point, # or on both sides of that if we had just entered it # (in which case "after" is an undefined direction). if from_direction == 1: break_axis( from_axis, from_index, 1) elif from_direction == -1: break_axis( from_axis, from_index, -1) else: break_axis( from_axis, from_index, 1) break_axis( from_axis, from_index, -1) return def do_jump_of_strand( strand, new_s_index): # break strand at the jump break_strand( strand, new_s_index, -1) return def do_jump_to_axis_once_new_direction_known( to_axis, entry_index, new_direction): # break backwards, before entry point break_axis( to_axis, entry_index, - new_direction) return if jumped: assert new_direction == 0 if prior_axis is not None and prior_axis is not _FAKE_AXIS_FOR_BARE_STRANDS: do_jump_from_axis( prior_axis, prior_index, prior_direction) if s_index is not None: do_jump_of_strand( strand, s_index) # set up to break new axis before the entry point -- # this is done by recording the state as described above, # so the next loop iteration will do it (by calling # do_jump_to_axis_once_new_direction_known), once it knows # the direction of travel. (If we leave immediately and # never know the direction, do_jump_from_axis breaks # the axis in both directions and takes care of it.) if changed_direction: # (rare, not physically realistic; see long comment above) # The after-jump is taken care of, but we have to do the # before-jump too (see long comment above for details). # We know the axis atom path was A B A (with B being prior # and A being current), so we know all necessary indices, # since we can compute arbitrarily old strand indices. # The jump to do right here is A1 -> B A2 where A2 is # current step (and steps A1 and A2 had same axis atom)... # uh oh, we don't know what the prior direction was at # that time -- just use the worst case of 0, which breaks # axis on both sides of A. A1_axis = axis A1_index = index X_to_A1_direction = 0 # worst-case guess do_jump_from_axis( A1_axis, A1_index, X_to_A1_direction ) B_strand = strand B_s_index = s_index - 1 do_jump_of_strand( B_strand, B_s_index) B_axis = axis B_index = prior_index A1_to_B_direction = prior_direction B_to_A2_direction = - A1_to_B_direction # (same axis) # note: not new_direction, since we zeroed that artificially! assert B_to_A2_direction in (-1, 1) do_jump_to_axis_once_new_direction_known( B_axis, B_index, B_to_A2_direction ) pass else: # we didn't jump assert new_direction in (-1,1) assert not changed_direction assert prior_axis is axis if not prior_direction: # we just entered this axis in the prior step - # break it before entry point if axis is not _FAKE_AXIS_FOR_BARE_STRANDS: do_jump_to_axis_once_new_direction_known( axis, prior_index, new_direction ) pass # record state for the next iteration: prior_axis = axis prior_index = index prior_direction = new_direction continue # for s_atom, s_index in strand.baseatom_index_pairs() return # from dna_updater_follow_strand # end
NanoCAD-master
cad/src/dna/updater/dna_updater_follow_strand.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_prefs.py - access to preferences settings affecting the dna updater @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: bruce 080317 revised many debug_pref menu texts, prefs_keys, non_debug settings """ from utilities.debug_prefs import debug_pref, Choice_boolean_True, Choice_boolean_False from utilities.debug_prefs import Choice import foundation.env as env from utilities.Log import orangemsg from utilities.GlobalPreferences import dna_updater_is_enabled from utilities import debug_flags # == def initialize_prefs(): """ """ # make debug prefs appear in debug menu pref_fix_deprecated_PAM3_atoms() pref_fix_deprecated_PAM5_atoms() pref_fix_bare_PAM3_atoms() pref_fix_bare_PAM5_atoms() pref_permit_bare_axis_atoms() pref_print_bond_direction_errors() pref_per_ladder_colors() pref_draw_internal_markers() pref_dna_updater_convert_to_PAM3plus5() pref_mmp_save_convert_to_PAM5() pref_renderers_convert_to_PAM5() pref_minimizers_convert_to_PAM5() pref_fix_after_readmmp_before_updaters() pref_fix_after_readmmp_after_updaters() _update_our_debug_flags('arbitrary value') # makes them appear in the menu, # and also sets their debug flags # to the current pref values return # == def pref_fix_deprecated_PAM3_atoms(): res = debug_pref("DNA: fix deprecated PAM3 atoms?", Choice_boolean_True, ## non_debug = True, # disabled, bruce 080317 prefs_key = "A10/DNA: fix deprecated PAM3 atoms?", # changed, bruce 080317 call_with_new_value = _changed_dna_updater_behavior_pref ) return res def pref_fix_deprecated_PAM5_atoms(): res = debug_pref("DNA: fix deprecated PAM5 atoms?", Choice_boolean_True, # False -> True, 080201 ## non_debug = True, # disabled, bruce 080317 prefs_key = "A10/DNA: fix deprecated PAM5 atoms?", # changed, bruce 080317 call_with_new_value = _changed_dna_updater_behavior_pref ) return res def pref_fix_bare_PAM3_atoms(): res = debug_pref("DNA: fix bare PAM3 atoms?", Choice_boolean_True, ## non_debug = True, # disabled, bruce 080317 prefs_key = "A10/DNA: fix bare PAM3 atoms?", # changed, bruce 080317 call_with_new_value = _changed_dna_updater_behavior_pref ) return res def pref_fix_bare_PAM5_atoms(): res = debug_pref("DNA: fix bare PAM5 atoms?", Choice_boolean_True, # False -> True, 080201 ## non_debug = True, # disabled, bruce 080317 prefs_key = "A10/DNA: fix bare PAM5 atoms?", # changed, bruce 080317 call_with_new_value = _changed_dna_updater_behavior_pref ) return res def dna_updater_warn_when_transmuting_deprecated_elements(): #bruce 080416 (not in .rc2) res = debug_pref("DNA: warn when transmuting deprecated PAM elements?", Choice_boolean_False, # warning is not useful for a released version, # and is distracting since it always happens during Insert DNA ## non_debug = True, prefs_key = "A10/DNA: warn when transmuting deprecated PAM elements?", ) return res def pref_permit_bare_axis_atoms(): #bruce 080407; seems to work, so I hope we can make it the default soon, # but would require adaptations in strand edit props, to delete them manually # and to tolerate their existence when extending one strand. # warning: like all updater behavior prefs, changing it at runtime and then # undoing to before that point might cause undo bugs, # so it requires atom_debug to see it. res = debug_pref("DNA: permit bare axis atoms? ", Choice_boolean_False, ## non_debug = True, prefs_key = True, call_with_new_value = _changed_dna_updater_behavior_pref ) return res def legal_numbers_of_strand_neighbors_on_axis(): #bruce 080407 if pref_permit_bare_axis_atoms(): return (0, 1, 2) else: return (1, 2) pass # == def pref_print_bond_direction_errors(): # really this means "print verbose details of them" -- they're always summarized, even when this is off res = debug_pref( "DNA: debug: print bond direction errors?", #bruce 080317 revised text Choice_boolean_False, ## non_debug = True, # disabled, bruce 080317 prefs_key = "A10/DNA updater: print bond direction errors?", # changed, bruce 080317 ) return res def pref_per_ladder_colors(): res = debug_pref("DNA: debug: per-ladder colors?", Choice_boolean_False, non_debug = True, prefs_key = "A10/DNA: debug: per-ladder colors?" ) return res def pref_draw_internal_markers(): res = debug_pref("DNA: draw internal DnaMarkers?", #bruce 080317 revised text Choice_boolean_False, non_debug = True, prefs_key = "A10/DNA: draw internal markers?", # changed, bruce 080317 call_with_new_value = (lambda val: env.mainwindow().glpane.gl_update()) ) return res # == # PAM3+5 prefs. [bruce 080312] # (These will either turn into User Prefs or per-assy settings (perhaps saved in mmp file), # or perhaps become finer-grained that that (applicable to portions of the model, # e.g. specific base pairs.) # Note: each minimizer may need a separate pref, since support for each one differs, # in how it works and how NE1 gets feedback from it that refers to specific atoms and bonds. # Note: the DNA Generator model choice may also need to change somehow, for this. # WARNING: as of 080416, these are mostly not yet implemented, and setting them # may cause bugs. The names don't reflect this. So I am hiding them (removing # non_debug = True). Unfortunately this didn't make it into .rc2 (since I forgot # about it) so it may not make it into the release. [bruce 080416] #update: these are still not implemented fully, and setting them will # still cause bugs (e.g. some aspects of bug 2842). This won't change for v1.1 # release. [bruce 080523] def pref_dna_updater_convert_to_PAM3plus5(): res = debug_pref("DNA: edit as PAM3+5? ", Choice_boolean_False, # when True, I'll remove the ending space ## non_debug = True, prefs_key = True, call_with_new_value = _changed_dna_updater_behavior_pref ) return res def pref_mmp_save_convert_to_PAM5(): # has one use, in save_mmp_file [as of 080519] res = debug_pref("DNA: save as PAM5? ", Choice_boolean_False, # when True, I'll remove the ending space ## non_debug = True, prefs_key = True ) return res def pref_renderers_convert_to_PAM5(): # never yet used [as of 080519] res = debug_pref("DNA: render externally as PAM5?", # e.g. QuteMol, POV-Ray Choice_boolean_False, ## non_debug = True, prefs_key = True ) return res def pref_minimizers_convert_to_PAM5(): # never yet used [as of 080519] res = debug_pref("DNA: minimize in PAM5? ", # i.e. for ND-1 (GROMACS or not) Choice_boolean_False, # when True, I'll remove the ending space ## non_debug = True, prefs_key = True ) return res # == def pref_fix_after_readmmp_before_updaters(): res = debug_pref("DNA: do fix_after_readmmp_before_updaters? ", Choice_boolean_True, # might change to False for release -- risky, maybe slow, and no huge need # update, bruce 080408: for now, leave it on, just remove debug prints and non_debug = True # for both related prefs; decide later whether it's slow based on profiles ## non_debug = True, prefs_key = True ) return res def pref_fix_after_readmmp_after_updaters(): # temporary kluge (since probably not enough to protect this # from making updater exceptions much worse in effect): # disable when dna updater is off, to work around bug in that case # (described in checkin mail today) # (only needed in "after" version) [bruce 080319] if not dna_updater_is_enabled(): print "bug: the permanent version of this fix is not working, noticed in pref_fix_after_readmmp_after_updaters" res = debug_pref("DNA: do fix_after_readmmp_after_updaters? ", Choice_boolean_True, # same comment as for before_updaters version ## non_debug = True, prefs_key = True ) return res and dna_updater_is_enabled() # only ok to do this if dna updater is on # == def pref_debug_dna_updater(): # 080228; note: accessed using flags matching debug_flags.DEBUG_DNA_UPDATER* res = debug_pref("DNA: updater debug prints", Choice(["off", "minimal", "on", "verbose"], ## defaultValue = "on", # todo: revise defaultValue after debugging # defaultValue left "on" for now, though a bit verbose, bruce 080317 defaultValue = "off" #bruce 080702 revised this, and the prefs key ), non_debug = True, prefs_key = "v111/DNA updater: debug prints", # changed, bruce 080317, 080702 call_with_new_value = _update_our_debug_flags ) return res def pref_dna_updater_slow_asserts(): # 080228; note: accessed using debug_flags.DNA_UPDATER_SLOW_ASSERTS res = debug_pref("DNA: updater slow asserts?", ## Choice_boolean_True, # todo: test speed effect; revise before release if too slow Choice_boolean_False, #bruce 080702 revised this, and the prefs key non_debug = True, prefs_key = "v111/DNA updater: slow asserts?", # changed, bruce 080317, 080702 call_with_new_value = _update_our_debug_flags ) return res # == def _changed_dna_updater_behavior_pref(val): if val: msg = "Note: to apply new DNA prefs value to existing atoms, " \ "run \"DNA: rescan all atoms\" in debug->other menu." env.history.message(orangemsg(msg)) return def _changed_dna_updater_behavior_pref_2(val): # rename! but, not currently used. _changed_dna_updater_behavior_pref( True) # always print the message def _update_our_debug_flags(val): del val # make sure the flags we control are defined in debug_flags # (i.e. that we got the right module here, and spelled them correctly) # (if not, this will fail the first time it runs) debug_flags.DEBUG_DNA_UPDATER debug_flags.DEBUG_DNA_UPDATER_VERBOSE debug_flags.DNA_UPDATER_SLOW_ASSERTS debug_flags.DEBUG_DNA_UPDATER_MINIMAL # update them all from the debug prefs debug_option = pref_debug_dna_updater() # "off", "minimal", "on", or "verbose" debug_flags.DEBUG_DNA_UPDATER_MINIMAL = (debug_option in ("minimal", "on", "verbose",)) debug_flags.DEBUG_DNA_UPDATER = (debug_option in ("on", "verbose",)) debug_flags.DEBUG_DNA_UPDATER_VERBOSE = (debug_option in ("verbose",)) debug_flags.DNA_UPDATER_SLOW_ASSERTS = pref_dna_updater_slow_asserts() return # end
NanoCAD-master
cad/src/dna/updater/dna_updater_prefs.py