python_code
stringlengths
0
992k
repo_name
stringlengths
8
46
file_path
stringlengths
5
162
NanoCAD-master
cad/src/cnt/commands/__init__.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ BuildNanotube_PropertyManager.py @author: Ninad, Mark @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: 2008-01-11 Ninad: Created """ import foundation.env as env from PyQt4.Qt import SIGNAL from PM.PM_GroupBox import PM_GroupBox from PM.PM_PushButton import PM_PushButton from PM.PM_SelectionListWidget import PM_SelectionListWidget 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 utilities.Comparison import same_vals from cnt.model.NanotubeSegment import getAllNanotubeSegmentsInPart _superclass = EditCommand_PM class BuildNanotube_PropertyManager(EditCommand_PM): """ The BuildNanotube_PropertyManager class provides a Property Manager for the B{Build > CNT } command. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Build Nanotube" pmName = title iconPath = "ui/actions/Command Toolbar/BuildNanotube/BuildNanotube.png" def __init__( self, command ): """ Constructor for the Build Nanotube property manager. """ #Attributes for self._update_UI_do_updates() to keep track of changes #in these , since the last call of that method. These are used to #determine whether certain UI updates are needed. self._previousSelectionParams = None self._previousStructureParams = None self._previousCommandStackParams = None #see self.connect_or_disconnect_signals for comment about this flag self.isAlreadyConnected = False self.isAlreadyDisconnected = False EditCommand_PM.__init__( self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) return def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ #TODO: This is a temporary fix for a bug. When you invoke a temporary #mode, entering such a temporary mode keeps the signals of PM from the #previous mode connected (but while exiting that temporary mode and #reentering the previous mode, it actually reconnects the signal! #This gives rise to lots of bugs. This needs a more general fix in #the Temporary mode API. # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py if isConnect and self.isAlreadyConnected: return if not isConnect and self.isAlreadyDisconnected: return self.isAlreadyConnected = isConnect self.isAlreadyDisconnected = not isConnect if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect self.nanotubeListWidget.connect_or_disconnect_signals(isConnect) change_connect(self.editNanotubePropertiesButton, SIGNAL("clicked()"), self._editNanotube) return def enable_or_disable_gui_actions(self, bool_enable = False): """ Enable or disable some gui actions when this property manager is opened or closed, depending on the bool_enable. """ #For new command API, we will always show the exit button to check #if Exit button really exits the subcommand and the parent command #(earlier there were bugs) . Regaring 'whether this should be the #default behavior', its a UI design issue and we will worry about it #later -- Ninad 2008-08-27 (based on an email exchanged with Bruce) pass def _update_UI_do_updates(self): """ Overrides superclass method. @see: Command_PropertyManager._update_UI_do_updates() """ newSelectionParams = self._currentSelectionParams() current_struct_params = self._currentStructureParams() selection_params_unchanged = same_vals(newSelectionParams, self._previousSelectionParams) #introducing self._previousStructureParams and #adding structure_params_unchanged check to the 'if' condition below #fixes bug 2910. structure_params_unchanged = same_vals(self._previousStructureParams, current_struct_params) current_command_stack_params = self._currentCommandStackParams() #Check if command stack params changed since last call of this #PM update method. This is used to fix bugs like 2940 command_stack_params_unchanged = same_vals( self._previousCommandStackParams, current_command_stack_params) #No need to proceed if any of the selection/ structure and commandstack #parameters remained unchanged since last call. --- [CONDITION A] if selection_params_unchanged and \ structure_params_unchanged and \ command_stack_params_unchanged: return self._previousStructureParams = current_struct_params self._previousSelectionParams = newSelectionParams self._previousCommandStackParams = current_command_stack_params if structure_params_unchanged: #NOTE: We checked if either of the selection struct or command stack #parameters or both changed. (this was referred as '[CONDITION A]' #above). So, this condition (structure_params_unchanged)also means #either selection or command stack or both parameters were changed. if not command_stack_params_unchanged: #update the nanotube list widget *before* updating the selection if #the command stack changed. This ensures that the selection box #appears around the list widget items that are selected. self.updateNanotubesListWidget() selectedNanotubeSegments = newSelectionParams self.nanotubeListWidget.updateSelection(selectedNanotubeSegments) self.updateNanotubePropertiesButton() return self.updateNanotubesListWidget() return def _currentCommandStackParams(self): """ The return value is supposed to be used by BUILD_NANOTUBE command PM ONLY and NOT by any subclasses. Returns a tuple containing current command stack change indicator and the name of the command 'BUILD_NANOTUBE'. These parameters are then used to decide whether updating widgets in this property manager is needed, when self._update_UI_do_updates() is called. @NOTE: - Command_PropertyManager.update_UI() already does a check to see if any of the global change indicators in assembly (command_stack_change, model_change, selection_change) changed since last call and then only calls self._update_UI_do_updates(). - But this method is just used to keep track of the local command stack change counter in order to update the list widgets. - This is used to fix bug 2940 @see: self._update_UI_do_updates() """ commandStackCounter = self.command.assy.command_stack_change_indicator() #Append 'BUILD_NANOTUBE to the tuple to be returned. This is just to remind #us that this method is meant for BUILD_NANOTUBE command PM only. (and not #by any subclasses) Should we assert this? I think it will slow things #down so this comment is enough -- Ninad 2008-09-30 return (commandStackCounter, 'BUILD_NANOTUBE') def _currentSelectionParams(self): """ Returns a tuple containing current selection parameters. These parameters are then used to decide whether updating widgets in this property manager is needed when L{self.model_changed} method is called. @return: A tuple that contains total number of selected nanotubes. @rtype: tuple @NOTE: This method may be renamed in future. It's possible that there are other groupboxes in the PM that need to be updated when something changes in the glpane. """ selectedNanotubeSegments = [] if self.command is not None: # and self.command.hasValidStructure(): selectedNanotubeSegments = self.win.assy.getSelectedNanotubeSegments() return (selectedNanotubeSegments) def _currentStructureParams(self): """ Return current structure parameters of interest to self.model_changed. Right now it only returns the number of nanotubes within the structure (or None). This is a good enough check (and no need to compare each and every nanotube within the structure with a previously stored set of strands). """ params = None if self.command: # and self.command.hasValidStructure(): nanotubeSegmentList = [] nanotubeSegmentList = getAllNanotubeSegmentsInPart(self.win.assy) params = len(nanotubeSegmentList) return params def close(self): """ Closes the Property Manager. Overrides EditCommand_PM.close() """ #Clear tags, if any, due to the selection in the self.strandListWidget. #self.nanotubeListWidget.clear() env.history.statusbar_msg("") EditCommand_PM.close(self) return def show(self): """ Show the PM. Extends superclass method. @note: _update_UI_do_updates() gets called immediately after this and updates PM widgets with their correct values/settings. """ env.history.statusbar_msg("") EditCommand_PM.show(self) # NOTE: Think about moving this msg to _update_UI_do_updates() where # custom msgs can be created based on the current selection, etc. # Mark 2008-12-14 msg = "Select <b>Insert Nanotube</b> to create a nanotube or "\ "select an existing nantube to modify it." self.updateMessage(msg) return def _editNanotube(self): """ Slot for the "Edit Properties" button. """ #if not self.command.hasValidStructure(): # return nanotubeSegment = self.win.assy.getSelectedNanotubeSegment() if nanotubeSegment: nanotubeSegment.edit() return def _addWhatsThisText( self ): """ What's This text for widgets in the CNT Property Manager. """ pass def _addToolTipText(self): """ Tool Tip text for widgets in the CNT Property Manager. """ pass def _addGroupBoxes( self ): """ Add the Nanotube Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Nanotubes" ) self._loadGroupBox1( self._pmGroupBox1 ) return def _loadGroupBox1(self, pmGroupBox): """ load widgets in groupbox1 """ self.nanotubeListWidget = PM_SelectionListWidget(pmGroupBox, self.win, label = "", heightByRows = 12) self.nanotubeListWidget.setObjectName('nanotubeListWidget') self.nanotubeListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE') self.editNanotubePropertiesButton = PM_PushButton(pmGroupBox, label = "", text = "Edit Properties..." ) self.editNanotubePropertiesButton.setEnabled(False) return def updateNanotubesListWidget(self): """ Updates the nanotubes (selection) groupbox. This includes both the nanotube selection list widget (showing all nanotubes in the part) and the B{Edit Properties} button just below it (enabled if only one of the nanotubes is selected). """ nanotubeSegmentList = getAllNanotubeSegmentsInPart(self.win.assy) if nanotubeSegmentList: self.nanotubeListWidget.insertItems( row = 0, items = nanotubeSegmentList) else: self.nanotubeListWidget.clear() self.updateNanotubePropertiesButton() return def updateNanotubePropertiesButton(self): """ Enables the B{Edit Properties} button if a single nanotube is currently selected. Otherwise, the button is disabled. """ self.editNanotubePropertiesButton.setEnabled( bool(self.win.assy.getSelectedNanotubeSegment())) return
NanoCAD-master
cad/src/cnt/commands/BuildNanotube/BuildNanotube_PropertyManager.py
NanoCAD-master
cad/src/cnt/commands/BuildNanotube/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ BuildNanotube_GraphicsMode.py @author: Ninad, Mark @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: TODO as of 2008-05-06: Needs Refactoring. It was originally duplicated from BuildDna_GraphicsMode (for an experimental implementation of new Nanotube command) There needs to be a common superclass for Build'Structure' mode and all the edit structure modes (commands) such as DnaSegment, DnaStrand_GraphicsMode, EditNanotube_GraphicsMode etc """ from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode from cnt.model.NanotubeSegment import NanotubeSegment from commands.Select.Select_GraphicsMode import DRAG_STICKINESS_LIMIT DEBUG_CLICK_ON_OBJECT_ENTERS_ITS_EDIT_COMMAND = True _superclass = SelectChunks_GraphicsMode class BuildNanotube_GraphicsMode(SelectChunks_GraphicsMode): """ Graphics mode for the Build Nanotube command. """ def chunkLeftUp(self, aChunk, event): """ Upon chunkLeftUp, it enters the nanotube edit command. This is an alternative implementation. As of 2008-03-03, we have decided to change this implementation. Keeping the related methods alive if, in future, we want to switch to this implementation and/or add a user preference to do this. """ _superclass.chunkLeftUp(self, aChunk, event) if self.glpane.modkeys is not None: #Don't go further if some modkey is pressed. We will call the #edit method of the nanotube only if no modifier key is #pressed return if not self.mouse_within_stickiness_limit(event, DRAG_STICKINESS_LIMIT): return #@TODO: If the object under mouse was double clicked, don't enter the #edit mode, instead do appropriate operation such as expand selection or #contract selection (done in superclass) #Note: when the object is just single clicked, it becomes editable). if self.editObjectOnSingleClick(): if aChunk.picked: segmentGroup = aChunk.parent_node_of_class(NanotubeSegment) if segmentGroup is not None: segmentGroup.edit() return def editObjectOnSingleClick(self): """ Subclasses can override this method. If this method returns True, when you left click on a DnaSegment or a DnaStrand, it becomes editable (i.e. program enters the edit command of that particular object if that object is editable) @see: MakeCrossover_GraphicsMode.editObjectOnSingleClick() """ if DEBUG_CLICK_ON_OBJECT_ENTERS_ITS_EDIT_COMMAND: return True return False def _drawCursorText(self): """ Draw the text near the cursor. It gives information about length of the nanotube. """ if hasattr(self.command, 'grabbedHandle') and \ hasattr(self.command, 'getCursorText'): if self.command.grabbedHandle is not None: #Draw the text next to the cursor that gives info about #nanotube length, etc. text , textColor = self.command.getCursorText() self.glpane.renderTextNearCursor(text, offset = 30, textColor = textColor) pass pass return pass
NanoCAD-master
cad/src/cnt/commands/BuildNanotube/BuildNanotube_GraphicsMode.py
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details. """ BuildNanotube_EditCommand.py @author: Ninad @version: $Id$ @copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details. History: Ninad 2008-01-11: Created """ from command_support.EditCommand import EditCommand from utilities.Log import greenmsg from ne1_ui.toolbars.Ui_NanotubeFlyout import NanotubeFlyout from model.chem import Atom from model.bonds import Bond from cnt.commands.BuildNanotube.BuildNanotube_GraphicsMode import BuildNanotube_GraphicsMode from cnt.commands.BuildNanotube.BuildNanotube_PropertyManager import BuildNanotube_PropertyManager _superclass = EditCommand class BuildNanotube_EditCommand(EditCommand): """ BuildNanotube_EditCommand provides a convenient way to insert or edit a Nanotube. """ # class constants GraphicsMode_class = BuildNanotube_GraphicsMode PM_class = BuildNanotube_PropertyManager #Flyout Toolbar FlyoutToolbar_class = NanotubeFlyout cmd = greenmsg("Build Nanotube: ") prefix = 'Nanotube' # used for gensym cmdname = "Build Nanotube" commandName = 'BUILD_NANOTUBE' featurename = "Build Nanotube" from utilities.constants import CL_ENVIRONMENT_PROVIDING command_level = CL_ENVIRONMENT_PROVIDING command_should_resume_prevMode = False command_has_its_own_PM = True create_name_from_prefix = True #The following class constant is used in creating dynamic menu items (using self.makeMenus) #if this flag is not defined, the menu doesn't get created #or use of self.graphicsMode in self.makeMenus throws errors. #See also other examples of its use in older Commands such as #BuildAtoms_Command (earlier depositmode) call_makeMenus_for_each_event = True def command_enter_misc_actions(self): """ Overrides superclass method. @see: baseCommand.command_enter_misc_actions() for documentation """ self.w.buildNanotubeAction.setChecked(True) return def runCommand(self): """ Overrides EditCommand.runCommand """ self.struct = None self.existingStructForEditing = False self.propMgr.updateNanotubesListWidget() return def keep_empty_group(self, group): """ Returns True if the empty group should not be automatically deleted. otherwise returns False. The default implementation always returns False. Subclasses should override this method if it needs to keep the empty group for some reasons. Note that this method will only get called when a group has a class constant autdelete_when_empty set to True. (and as of 2008-03-06, it is proposed that cnt_updater calls this method when needed. @see: Command.keep_empty_group() which is overridden here. """ bool_keep = EditCommand.keep_empty_group(self, group) if not bool_keep: if group is self.struct: bool_keep = True return bool_keep def makeMenus(self): """ Create context menu for this command. (Build Nanotube mode) @see: chunk.make_glpane_cmenu_items @see: EditNanotube_EditCommand.makeMenus """ if not hasattr(self, 'graphicsMode'): return selobj = self.glpane.selobj if selobj is None: self._makeEditContextMenus() return self.Menu_spec = [] highlightedChunk = None if isinstance(selobj, self.assy.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 if highlightedChunk is not None: highlightedChunk.make_glpane_cmenu_items(self.Menu_spec, self) return
NanoCAD-master
cad/src/cnt/commands/BuildNanotube/BuildNanotube_EditCommand.py
NanoCAD-master
cad/src/cnt/commands/InsertNanotube/__init__.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ InsertNanotube_EditCommand.py provides an editCommand object for generating a nanotube (CNT or BNNT). This command should be invoked only from NanotubeProperties_EditCommand @author: Mark Sims, Ninad Sathaye @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: - Mark 2008-03-8: This file created from a copy of InsertDna_EditCommand.py and edited. """ import foundation.env as env from command_support.EditCommand import EditCommand from cnt.model.NanotubeSegment import NanotubeSegment from utilities.Log import greenmsg from geometry.VQT import V, vlen from utilities.exception_classes import PluginBug, UserError from cnt.commands.InsertNanotube.InsertNanotube_PropertyManager import InsertNanotube_PropertyManager from utilities.constants import gensym from cnt.temporary_commands.NanotubeLineMode import NanotubeLine_GM from utilities.prefs_constants import insertNanotubeEditCommand_cursorTextCheckBox_angle_prefs_key from utilities.prefs_constants import insertNanotubeEditCommand_cursorTextCheckBox_length_prefs_key from utilities.prefs_constants import insertNanotubeEditCommand_showCursorTextCheckBox_prefs_key from utilities.prefs_constants import cursorTextColor_prefs_key _superclass = EditCommand class InsertNanotube_EditCommand(EditCommand): """ InsertNanotube_EditCommand that provides an editCommand object for generating carbon or boron nitride nanotube. This command should be invoked only from InsertNanotube_EditCommand User can create as many nanotubes as he/she needs just by specifying two end points for each nanotube. This uses NanotubeLineMode_GM class as its GraphicsMode """ #Graphics Mode set to CntLine graphics mode GraphicsMode_class = NanotubeLine_GM #Property Manager PM_class = InsertNanotube_PropertyManager cmd = greenmsg("Insert Nanotube: ") prefix = 'Nanotube' # used for gensym cmdname = "Insert Nanotube" commandName = 'INSERT_NANOTUBE' featurename = "Insert Nanotube" from utilities.constants import CL_SUBCOMMAND command_level = CL_SUBCOMMAND command_parent = 'BUILD_NANOTUBE' command_should_resume_prevMode = True command_has_its_own_PM = True # Generators for DNA, nanotubes and graphene have their MT name # generated (in GeneratorBaseClass) from the prefix. create_name_from_prefix = True #required by NanotubeLine_GM mouseClickPoints = [] #This is set to InsertNanotube_EditCommand.flyoutToolbar (as of 2008-01-14, #it only uses flyoutToolbar = None def __init__(self, commandSequencer): """ Constructor for InsertNanotube_EditCommand """ _superclass.__init__(self, commandSequencer) #Maintain a list of segments created while this command was running. self._segmentList = [] def command_entered(self): """ Overrides superclass method. @see: basecommand.command_entered() for documentation. """ _superclass.command_entered(self) if isinstance(self.graphicsMode, NanotubeLine_GM): self._setParamsForCntLineGraphicsMode() self.mouseClickPoints = [] #Clear the segmentList as it may still be maintaining a list of segments #from the previous run of the command. self._segmentList = [] def command_will_exit(self): """ Overrides superclass method. @see: basecommand.command_will_exit() for documentation. """ if isinstance(self.graphicsMode, NanotubeLine_GM): self.mouseClickPoints = [] self.graphicsMode.resetVariables() self._segmentList = [] _superclass.command_will_exit(self) def _getFlyoutToolBarActionAndParentCommand(self): """ See superclass for documentation. @see: self.command_update_flyout() """ flyoutActionToCheck = 'insertNanotubeAction' parentCommandName = None return flyoutActionToCheck, parentCommandName def runCommand(self): """ Overrides EditCommand.runCommand """ self.struct = None return def createStructure(self): """ Overrides superclass method. Creates the structure (NanotubeSegment) """ assert self.propMgr is not None if self.struct is not None: self.struct = None self.win.assy.part.ensure_toplevel_group() self.propMgr.endPoint1 = self.mouseClickPoints[0] self.propMgr.endPoint2 = self.mouseClickPoints[1] ntLength = vlen(self.mouseClickPoints[0] - self.mouseClickPoints[1]) self.preview_or_finalize_structure(previewing = True) #Now append this ntSegment to self._segmentList self._segmentList.append(self.struct) #clear the mouseClickPoints list self.mouseClickPoints = [] self.graphicsMode.resetVariables() return 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.NanotubeSegment def _finalizeStructure(self): """ Finalize the structure. This is a step just before calling Done method. to exit out of this command. Subclasses may overide this method @see: EditCommand_PM.ok_btn_clicked @see: EditNanotube_EditCommand where this method is overridden. """ #The following can happen in this case: User creates first nanotube, #Now clicks inside 3D workspace to define the first point of the #next nanotube. Now moves the mouse to draw cnt rubberband line. #and then its 'Done' When it does that, it has modified the #'number of base pairs' value in the PM and then it uses that value #to modify self.struct ...which is the first segment user created! #In order to avoid this, either self.struct should be set to None after #its appended to the segment list (in self.createStructure) #Or it should compute the number of base pairs each time instead of #relying on the corresponding value in the PM. The latter is not #advisable if we support modifying the number of base pairs from the #PM (and hitting preview) while in InsertNanotube command. #In the mean time, I think this solution will always work. if len(self.mouseClickPoints) == 1: return else: _superclass._finalizeStructure(self) return def _gatherParameters(self): """ Return the parameters from the property manager UI. @return: The nanotube, which contains all the attrs. @rtype: Nanotube """ return self.propMgr.getParameters() 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. This was needed for the structures like this (Cnt, Nanotube etc) . . See more comments in the method. @see: a note in self._createStructure() about use of ntSegment.setProps """ #@NOTE: Unlike editcommands such as Plane_EditCommand, this #editCommand actually removes the structure and creates a new one #when its modified. We don't yet know if the CNT object model # will solve this problem. (i.e. reusing the object and just modifying #its attributes. Till that time, we'll continue to use #what the old GeneratorBaseClass use to do ..i.e. remove the item and # create a new one -- Ninad 2007-10-24 self._removeStructure() self.previousParams = params self.struct = self._createStructure() return def cancelStructure(self): """ Overrides Editcommand.cancelStructure ..calls _removeSegments which deletes all the segments created while this command was running @see: B{EditCommand.cancelStructure} """ _superclass.cancelStructure(self) self._removeSegments() return def _removeSegments(self): """ Remove the segments created while in this command This deletes all the segments created while this command was running @see: L{self.cancelStructure} """ segmentList = self._segmentList #@@@ rename segmentList to nanotubeSegmentList for segment in segmentList: #can segment be None? Lets add this condition to be on the safer #side. if segment is not None: segment.kill_with_contents() self._revertNumber() self._segmentList = [] self.win.win_update() def _createStructure(self): """ Creates and returns the structure (in this case a L{Group} object that contains the nanotube chunk. @return : group containing the nanotube chunk. @rtype: L{Group} @note: This needs to return a CNT object once that model is implemented """ # 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 # Create the model tree group node. # Make sure that the 'topnode' of this part is a Group (under which the # Nanotube group will be placed), if the topnode is not a group, make it # a 'Group' (applicable to Clipboard parts). See part.py # --Part.ensure_toplevel_group method. This is an important line # and it fixes bug 2585 self.win.assy.part.ensure_toplevel_group() ntSegment = NanotubeSegment(self.name, self.win.assy, self.win.assy.part.topnode, editCommand = self) try: # Make the nanotube. <ntGroup> will contain one chunk: # - Axis (Segment) # No error checking here; do all error checking in _gatherParameters(). nanotube = self._gatherParameters() position = V(0.0, 0.0, 0.0) self.nanotube = nanotube # needed for done msg #@ ntChunk = nanotube.build(self.name, self.win.assy, position) ntSegment.addchild(ntChunk) #set some properties such as ntRise and its two endpoints. #This information will be stored on the NanotubeSegment object so that #it can be retrieved while editing this object. #WARNING 2008-03-05: Since self._modifyStructure calls #self._createStructure() If in the near future, we actually permit #modifying a #structure (such as a nanotube) without actually recreating the #entire structure, then the following properties must be set in #self._modifyStructure as well. Needs more thought. #props =(nanotube.getChirality(), # nanotube.getType(), # nanotube.getEndings(), # nanotube.getEndPoints()) ntSegment.setProps(nanotube.getParameters()) return ntSegment except (PluginBug, UserError): # Why do we need UserError here? Mark 2007-08-28 self._segmentList.remove(ntSegment) ntSegment.kill_with_contents() raise PluginBug("Internal error while trying to create Nanotube.") def getCursorText(self, endPoint1, endPoint2): """ This is used as a callback method in CntLine mode @see: NanotubeLineMode.setParams, NanotubeLineMode_GM.Draw """ text = "" textColor = env.prefs[cursorTextColor_prefs_key] # Mark 2008-08-28 if endPoint1 is None or endPoint2 is None: return text, textColor if not env.prefs[insertNanotubeEditCommand_showCursorTextCheckBox_prefs_key]: return text, textColor vec = endPoint2 - endPoint1 ntLength = vlen(vec) lengthString = self._getCursorText_length(ntLength) thetaString = '' if env.prefs[insertNanotubeEditCommand_cursorTextCheckBox_angle_prefs_key]: theta = self.glpane.get_angle_made_with_screen_right(vec) thetaString = '%5.2f deg'%theta commaString = ", " text = lengthString if text and thetaString: text += commaString text += thetaString return text , textColor def _getCursorText_length(self, nanotubeLength): """ Returns a string that gives the length of the Nanotube for the cursor text """ nanotubeLengthString = '' if env.prefs[insertNanotubeEditCommand_cursorTextCheckBox_length_prefs_key]: lengthUnitString = 'A' #change the unit of length to nanometers if the length is > 10A #fixes part of bug 2856 if nanotubeLength > 10.0: lengthUnitString = 'nm' nanotubeLength = nanotubeLength * 0.1 nanotubeLengthString = "%5.3f%s"%(nanotubeLength, lengthUnitString) return nanotubeLengthString def isRubberbandLineSnapEnabled(self): """ This returns True or False based on the checkbox state in the PM. This is used as a callback method in CntLine mode (NanotubeLine_GM) @see: NanotubeLine_GM.snapLineEndPoint where the boolean value returned from this method is used @return: Checked state of the linesnapCheckBox in the PM @rtype: boolean """ return self.propMgr.lineSnapCheckBox.isChecked() def getDisplayStyleForNtRubberbandLine(self): """ This is used as a callback method in ntLine mode. @return: The current display style for the rubberband line. @rtype: string @see: NanotubeLineMode.setParams, NanotubeLineMode_GM.Draw """ return self.propMgr.ntRubberBandLineDisplayComboBox.currentText() # Things needed for CntLine_GraphicsMode (NanotubeLine_GM) ====================== def _setParamsForCntLineGraphicsMode(self): """ Needed for CntLine_GraphicsMode (NanotubeLine_GM). The method names need to be revised (e.g. callback_xxx. The prefix callback_ was for the earlier implementation of CntLine mode where it just used to supply some parameters to the previous mode using the callbacks from the previousmode. """ self.mouseClickLimit = None self.nanotube = self.propMgr.nanotube self.ntType = self.nanotube.getType() self.n, self.m = self.nanotube.getChirality() self.ntRise = self.nanotube.getRise() self.ntDiameter = self.nanotube.getDiameter() self.jigList = self.win.assy.getSelectedJigs() self.callbackMethodForCursorTextString = \ self.getCursorText self.callbackForSnapEnabled = self.isRubberbandLineSnapEnabled self.callback_rubberbandLineDisplay = \ self.getDisplayStyleForNtRubberbandLine
NanoCAD-master
cad/src/cnt/commands/InsertNanotube/InsertNanotube_EditCommand.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ InsertNanotube_PropertyManager.py @author: Mark Sims @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. Mark 2008-03-09: - Created. Copied and edited InsertDna_PropertyManager.py. """ __author__ = "Mark" from PyQt4.Qt import SIGNAL from PyQt4.Qt import Qt from PyQt4.Qt import QAction from PM.PM_ComboBox import PM_ComboBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_GroupBox import PM_GroupBox from PM.PM_SpinBox import PM_SpinBox from PM.PM_LineEdit import PM_LineEdit from PM.PM_ToolButton import PM_ToolButton from PM.PM_CoordinateSpinBoxes import PM_CoordinateSpinBoxes from PM.PM_CheckBox import PM_CheckBox from geometry.VQT import V 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 ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_InsertNanotube_PropertyManager from utilities.prefs_constants import insertNanotubeEditCommand_cursorTextCheckBox_angle_prefs_key from utilities.prefs_constants import insertNanotubeEditCommand_cursorTextCheckBox_length_prefs_key from utilities.prefs_constants import insertNanotubeEditCommand_showCursorTextCheckBox_prefs_key from widgets.prefs_widgets import connect_checkbox_with_boolean_pref from cnt.model.NanotubeParameters import NanotubeParameters from command_support.DnaOrCnt_PropertyManager import DnaOrCnt_PropertyManager _superclass = DnaOrCnt_PropertyManager class InsertNanotube_PropertyManager( DnaOrCnt_PropertyManager): """ The InsertNanotube_PropertyManager class provides a Property Manager for the B{Build > Nanotube > CNT} command. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Insert Nanotube" pmName = title iconPath = "ui/actions/Command Toolbar/BuildNanotube/InsertNanotube.png" def __init__( self, command ): """ Constructor for the Nanotube property manager. """ self.endPoint1 = None self.endPoint2 = None self.nanotube = NanotubeParameters() # A 5x5 CNT. _superclass.__init__( self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_WHATS_THIS_BUTTON) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect change_connect( self.ntTypeComboBox, SIGNAL("currentIndexChanged(const QString&)"), self._ntTypeComboBoxChanged ) change_connect(self.chiralityNSpinBox, SIGNAL("valueChanged(int)"), self._chiralityFixup) change_connect(self.chiralityMSpinBox, SIGNAL("valueChanged(int)"), self._chiralityFixup) change_connect(self.endingsComboBox, SIGNAL("currentIndexChanged(const QString&)"), self._endingsComboBoxChanged ) # This spin box is currently hidden. change_connect(self.bondLengthDoubleSpinBox, SIGNAL("valueChanged(double)"), self._bondLengthChanged) change_connect(self.showCursorTextCheckBox, SIGNAL('stateChanged(int)'), self._update_state_of_cursorTextGroupBox) def show(self): _superclass.show(self) self.updateMessage("Specify the nanotube parameters below, then click "\ "two endpoints in the graphics area to insert a nanotube.") def _update_widgets_in_PM_before_show(self): """ Update various widgets in this Property manager. Overrides MotorPropertyManager._update_widgets_in_PM_before_show. The various widgets , (e.g. spinboxes) will get values from the structure for which this propMgr is constructed for (self.editcCntroller.struct) @see: MotorPropertyManager._update_widgets_in_PM_before_show @see: self.show where it is called. """ pass def _addGroupBoxes( self ): """ Add the Insert Nanotube Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Endpoints" ) self._loadGroupBox1( self._pmGroupBox1 ) self._pmGroupBox1.hide() self._pmGroupBox2 = PM_GroupBox( self, title = "Parameters" ) self._loadGroupBox2( self._pmGroupBox2 ) self._displayOptionsGroupBox = PM_GroupBox( self, title = "Display Options" ) self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox ) self._pmGroupBox3 = PM_GroupBox( self, title = "Nanotube Distortion" ) self._loadGroupBox3( self._pmGroupBox3 ) self._pmGroupBox3.hide() #@ Temporary. self._pmGroupBox4 = PM_GroupBox( self, title = "Multi-Walled CNTs" ) self._loadGroupBox4( self._pmGroupBox4 ) self._pmGroupBox4.hide() #@ Temporary. self._pmGroupBox5 = PM_GroupBox( self, title = "Advanced Options" ) self._loadGroupBox5( self._pmGroupBox5 ) self._pmGroupBox5.hide() #@ Temporary. def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 1. """ #Following toolbutton facilitates entering a temporary NanotubeLineMode #to create a CNT using endpoints of the specified line. self.specifyCntLineButton = PM_ToolButton( pmGroupBox, text = "Specify Endpoints", iconPath = "ui/actions/Properties Manager/Pencil.png", spanWidth = True ) self.specifyCntLineButton.setCheckable(True) self.specifyCntLineButton.setAutoRaise(True) self.specifyCntLineButton.setToolButtonStyle( Qt.ToolButtonTextBesideIcon) #EndPoint1 and endPoint2 coordinates. These widgets are hidden # as of 2007- 12 - 05 self._endPoint1SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox, label = "End Point 1") self.x1SpinBox = self._endPoint1SpinBoxes.xSpinBox self.y1SpinBox = self._endPoint1SpinBoxes.ySpinBox self.z1SpinBox = self._endPoint1SpinBoxes.zSpinBox self._endPoint2SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox, label = "End Point 2") self.x2SpinBox = self._endPoint2SpinBoxes.xSpinBox self.y2SpinBox = self._endPoint2SpinBoxes.ySpinBox self.z2SpinBox = self._endPoint2SpinBoxes.zSpinBox self._endPoint1SpinBoxes.hide() self._endPoint2SpinBoxes.hide() def _loadGroupBox2(self, pmGroupBox): """ Load widgets in group box 2. """ _ntTypeChoices = ['Carbon', 'Boron Nitride'] self.ntTypeComboBox = \ PM_ComboBox( pmGroupBox, label = "Type:", choices = _ntTypeChoices, setAsDefault = True) self.ntRiseDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Rise:", value = self.nanotube.getRise(), setAsDefault = True, minimum = 2.0, maximum = 4.0, decimals = 3, singleStep = 0.01 ) self.ntRiseDoubleSpinBox.hide() # Nanotube Length self.ntLengthLineEdit = \ PM_LineEdit( pmGroupBox, label = "Nanotube Length: ", text = "0.0 Angstroms", setAsDefault = False) self.ntLengthLineEdit.setDisabled(True) self.ntLengthLineEdit.hide() # Nanotube diameter self.ntDiameterLineEdit = \ PM_LineEdit( pmGroupBox, label = "Diameter: ", setAsDefault = False) self.ntDiameterLineEdit.setDisabled(True) self.updateNanotubeDiameter() self.chiralityNSpinBox = \ PM_SpinBox( pmGroupBox, label = "Chirality (n):", value = self.nanotube.getChiralityN(), minimum = 2, maximum = 100, setAsDefault = True ) self.chiralityMSpinBox = \ PM_SpinBox( pmGroupBox, label = "Chirality (m):", value = self.nanotube.getChiralityM(), minimum = 0, maximum = 100, setAsDefault = True ) # How about having user prefs for CNT and BNNT bond lengths? # I'm guessing that if the user wants to set these values, they will # do it once and would like those bond length values persist forever. # Need to discuss with others to determine if this spinbox comes out. # --Mark 2008-03-29 self.bondLengthDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Bond length:", value = self.nanotube.getBondLength(), setAsDefault = True, minimum = 1.0, maximum = 3.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) #self.bondLengthDoubleSpinBox.hide() endingChoices = ["Hydrogen", "None"] # Removed:, "Nitrogen"] self.endingsComboBox= \ PM_ComboBox( pmGroupBox, label = "Endings:", choices = endingChoices, index = 0, setAsDefault = True, spanWidth = False ) def _loadGroupBox3(self, inPmGroupBox): """ Load widgets in group box 3. """ self.zDistortionDoubleSpinBox = \ PM_DoubleSpinBox( inPmGroupBox, label = "Z-distortion:", value = 0.0, setAsDefault = True, minimum = 0.0, maximum = 10.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) self.xyDistortionDoubleSpinBox = \ PM_DoubleSpinBox( inPmGroupBox, label = "XY-distortion:", value = 0.0, setAsDefault = True, minimum = 0.0, maximum = 2.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) self.twistSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Twist:", value = 0, setAsDefault = True, minimum = 0, maximum = 100, # What should maximum be? suffix = " deg/A" ) self.bendSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Bend:", value = 0, setAsDefault = True, minimum = 0, maximum = 360, suffix = " deg" ) def _loadGroupBox4(self, inPmGroupBox): """ Load widgets in group box 4. """ # "Number of Nanotubes" SpinBox self.mwntCountSpinBox = \ PM_SpinBox( inPmGroupBox, label = "Number:", value = 1, setAsDefault = True, minimum = 1, maximum = 10, suffix = " nanotubes" ) self.mwntCountSpinBox.setSpecialValueText("SWNT") # "Spacing" lineedit. self.mwntSpacingDoubleSpinBox = \ PM_DoubleSpinBox( inPmGroupBox, label = "Spacing:", value = 2.46, setAsDefault = True, minimum = 1.0, maximum = 10.0, singleStep = 0.1, decimals = 3, suffix = " Angstroms" ) def _loadGroupBox5(self, pmGroupBox): """ Load widgets in group box 5. """ self._rubberbandLineGroupBox = PM_GroupBox( pmGroupBox, title = 'Rubber band Line:') ntLineChoices = ['Ladder'] self.ntRubberBandLineDisplayComboBox = \ PM_ComboBox( self._rubberbandLineGroupBox , label = " Display as:", choices = ntLineChoices, setAsDefault = True) self.lineSnapCheckBox = \ PM_CheckBox(self._rubberbandLineGroupBox , text = 'Enable line snap' , widgetColumn = 1, state = Qt.Checked ) def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Overrides DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox """ connect_checkbox_with_boolean_pref( self.showCursorTextCheckBox , insertNanotubeEditCommand_showCursorTextCheckBox_prefs_key ) def _params_for_creating_cursorTextCheckBoxes(self): """ Returns params needed to create various cursor text checkboxes connected to prefs_keys that allow custom cursor texts. @return: A list containing tuples in the following format: ('checkBoxTextString' , preference_key). PM_PrefsCheckBoxes uses this data to create checkboxes with the the given names and connects them to the provided preference keys. (Note that PM_PrefsCheckBoxes puts thes within a GroupBox) @rtype: list @see: PM_PrefsCheckBoxes @see: self._loadDisplayOptionsGroupBox where this list is used. @see: Superclass method which is overridden here -- DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = \ [ #Format: (" checkbox text", prefs_key) ("Nanotube length", insertNanotubeEditCommand_cursorTextCheckBox_length_prefs_key ), ("Angle", insertNanotubeEditCommand_cursorTextCheckBox_angle_prefs_key ) ] return params def _addToolTipText(self): """ Tool Tip text for widgets in the Insert Nanotube Property Manager. """ pass def _setEndPoints(self): """ Set the two endpoints of the nanotube using the values from the X, Y, Z coordinate spinboxes in the property manager. @note: The group box containing the 2 sets of XYZ spin boxes are currently hidden. """ # First endpoint (origin) of nanotube x1 = self.x1SpinBox.value() y1 = self.y1SpinBox.value() z1 = self.z1SpinBox.value() # Second endpoint (direction vector/axis) of nanotube. x2 = self.x2SpinBox.value() y2 = self.y2SpinBox.value() z2 = self.z2SpinBox.value() if not self.endPoint1: self.endPoint1 = V(x1, y1, z1) if not self.endPoint2: self.endPoint2 = V(x2, y2, z2) self.nanotube.setEndPoints(self.endPoint1, self.endPoint2) # Need arg "recompute=True", which will recompute the second # endpoint (endPoint2) using the nanotube rise. def getParameters(self): """ Return the parameters from this property manager to be used to create the nanotube. @return: A nanotube instance with its attrs set to the current parameters in the property manager. @rtype: L{Nanotube} @see: L{InsertNanotube_EditCommand._gatherParameters} where this is used """ self._setEndPoints() return (self.nanotube) def _ntTypeComboBoxChanged( self, type ): """ Slot for the Type combobox. It is called whenever the Type choice is changed. @param inIndex: The new index. @type inIndex: int """ self.nanotube.setType(str(type)) self.bondLengthDoubleSpinBox.setValue(self.nanotube.getBondLength()) #self.bondLengthDoubleSpinBox.setValue(ntBondLengths[inIndex]) def _bondLengthChanged(self, bondLength): """ Slot for the B{Bond Length} spinbox. """ self.nanotube.setBondLength(bondLength) self.updateNanotubeDiameter() return def _chiralityFixup(self, spinBoxValueJunk = None): """ Slot for several validators for different parameters. This gets called whenever the user changes the n, m chirality values. @param spinBoxValueJunk: This is the Spinbox value from the valueChanged signal. It is not used. We just want to know that the spinbox value has changed. @type spinBoxValueJunk: double or None @see: PM_SpinBox.setValue() for a note about blockSignals. """ _n, _m = self.nanotube.setChirality(self.chiralityNSpinBox.value(), self.chiralityMSpinBox.value()) #self.n, self.m = self.nanotube.getChirality() #QSpinBox.setValue emits valueChanged signal. We don't want that here. #so temporarily blockSignal by passing the blockSignals flag. self.chiralityNSpinBox.setValue(_n, blockSignals = True) self.chiralityMSpinBox.setValue(_m, blockSignals = True) self.updateNanotubeDiameter() def updateNanotubeDiameter(self): """ Update the nanotube Diameter lineEdit widget. """ diameterText = "%-7.4f Angstroms" % (self.nanotube.getDiameter()) self.ntDiameterLineEdit.setText(diameterText) # ntRiseDoubleSpinBox is currently hidden. self.ntRiseDoubleSpinBox.setValue(self.nanotube.getRise()) def _endingsComboBoxChanged(self, endings): """ Slot for the B{Ending} combobox. @param endings: The option's text. @type endings: string """ self.nanotube.setEndings(str(endings)) return def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ whatsThis_InsertNanotube_PropertyManager(self) return
NanoCAD-master
cad/src/cnt/commands/InsertNanotube/InsertNanotube_PropertyManager.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ EditNanotube_EditCommand.py @author: Ninad, Mark @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. While in this command, user can (a) Highlight and then left drag the resize handles located at the two 'endpoints' of the nanotube to change its length. (b) Highlight and then left drag any nanotube atom to translate the nanotube along its axis. History: Mark 2008-03-10: Created from copy of DnaSegment_EditCommand.py """ import foundation.env as env from command_support.EditCommand import EditCommand from utilities.exception_classes import PluginBug, UserError from geometry.VQT import V, vlen from geometry.VQT import cross, norm from utilities.constants import gensym from exprs.State_preMixin import State_preMixin from exprs.attr_decl_macros import Instance, State from exprs.__Symbols__ import _self from exprs.Exprs import call_Expr from exprs.Exprs import norm_Expr from exprs.ExprsConstants import Width, Point from widgets.prefs_widgets import ObjAttr_StateRef from model.chunk import Chunk from model.chem import Atom from model.bonds import Bond from utilities.debug_prefs import debug_pref, Choice_boolean_True from utilities.constants import noop from utilities.Comparison import same_vals from utilities.debug import print_compact_stack from graphics.drawables.RotationHandle import RotationHandle from cnt.model.NanotubeSegment import NanotubeSegment from cnt.commands.EditNanotube.EditNanotube_ResizeHandle import EditNanotube_ResizeHandle from cnt.commands.EditNanotube.EditNanotube_GraphicsMode import EditNanotube_GraphicsMode from utilities.prefs_constants import editNanotubeEditCommand_cursorTextCheckBox_length_prefs_key from utilities.prefs_constants import editNanotubeEditCommand_showCursorTextCheckBox_prefs_key from utilities.prefs_constants import cursorTextColor_prefs_key from cnt.commands.EditNanotube.EditNanotube_PropertyManager import EditNanotube_PropertyManager CYLINDER_WIDTH_DEFAULT_VALUE = 0.0 HANDLE_RADIUS_DEFAULT_VALUE = 1.2 ORIGIN = V(0,0,0) #Flag that appends rotation handles to the self.handles (thus enabling their #display and computation while in EditNanotube_EditCommand DEBUG_ROTATION_HANDLES = False def pref_nt_segment_resize_by_recreating_nanotube(): res = debug_pref("Nanotube Segment: resize by recreating whole nanotube", Choice_boolean_True, non_debug = True, prefs_key = True ) return res class EditNanotube_EditCommand(State_preMixin, EditCommand): """ Command to edit a NanotubeSegment (nanotube). """ # class constants GraphicsMode_class = EditNanotube_GraphicsMode PM_class = EditNanotube_PropertyManager commandName = 'EDIT_NANOTUBE' featurename = "Edit Nanotube" from utilities.constants import CL_SUBCOMMAND command_level = CL_SUBCOMMAND command_parent = 'BUILD_NANOTUBE' command_should_resume_prevMode = True command_has_its_own_PM = True flyoutToolbar = None call_makeMenus_for_each_event = True handlePoint1 = State( Point, ORIGIN) handlePoint2 = State( Point, ORIGIN) #The minimum 'stopper'length used for resize handles #@see: self._update_resizeHandle_stopper_length for details. _resizeHandle_stopper_length = State(Width, -100000) rotationHandleBasePoint1 = State( Point, ORIGIN) rotationHandleBasePoint2 = State( Point, ORIGIN) #See self._update_resizeHandle_radius where this gets changed. #also see EditNanotube_ResizeHandle to see how its implemented. handleSphereRadius1 = State(Width, HANDLE_RADIUS_DEFAULT_VALUE) handleSphereRadius2 = State(Width, HANDLE_RADIUS_DEFAULT_VALUE) cylinderWidth = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) cylinderWidth2 = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) #@TODO: modify the 'State params for rotation_distance rotation_distance1 = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) rotation_distance2 = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) leftHandle = Instance( EditNanotube_ResizeHandle( command = _self, height_ref = call_Expr( ObjAttr_StateRef, _self, 'cylinderWidth'), origin = handlePoint1, fixedEndOfStructure = handlePoint2, direction = norm_Expr(handlePoint1 - handlePoint2), sphereRadius = handleSphereRadius1, range = (_resizeHandle_stopper_length, 10000) )) rightHandle = Instance( EditNanotube_ResizeHandle( command = _self, height_ref = call_Expr( ObjAttr_StateRef, _self, 'cylinderWidth2'), origin = handlePoint2, fixedEndOfStructure = handlePoint1, direction = norm_Expr(handlePoint2 - handlePoint1), sphereRadius = handleSphereRadius2, range = (_resizeHandle_stopper_length, 10000) )) rotationHandle1 = Instance( RotationHandle( command = _self, rotationDistanceRef = call_Expr( ObjAttr_StateRef, _self, 'rotation_distance1'), center = handlePoint1, axis = norm_Expr(handlePoint1 - handlePoint2), origin = rotationHandleBasePoint1, radiusVector = norm_Expr(rotationHandleBasePoint1 - handlePoint1) )) rotationHandle2 = Instance( RotationHandle( command = _self, rotationDistanceRef = call_Expr( ObjAttr_StateRef, _self, 'rotation_distance2'), center = handlePoint2, axis = norm_Expr(handlePoint2 - handlePoint1), origin = rotationHandleBasePoint2, radiusVector = norm_Expr(rotationHandleBasePoint2 - handlePoint2) )) def __init__(self, commandSequencer): """ Constructor for InsertDna_EditCommand """ glpane = commandSequencer.assy.glpane State_preMixin.__init__(self, glpane) EditCommand.__init__(self, commandSequencer) #Graphics handles for editing the structure . self.handles = [] self.grabbedHandle = None #Initialize DEBUG preference pref_nt_segment_resize_by_recreating_nanotube() return def editStructure(self, struct = None): EditCommand.editStructure(self, struct) if self.hasValidStructure(): #TODO 2008-03-25: better to get all parameters from self.struct and #set it in propMgr? This will mostly work except that reverse is #not true. i.e. we can not specify same set of params for #self.struct.setProps ...because endPoint1 and endPoint2 are derived. #by the structure when needed. self.propMgr.setParameters(self.struct.getProps()) #Store the previous parameters. Important to set it after you #set nanotube attrs in the propMgr. #self.previousParams is used in self._previewStructure and #self._finalizeStructure to check if self.struct changed. self.previousParams = self._gatherParameters() self._updateHandleList() self.updateHandlePositions() return def hasValidStructure(self): """ Tells the caller if this edit command has a valid structure. Overrides EditCommand.hasValidStructure() """ #(By Bruce 2008-02-13) isValid = EditCommand.hasValidStructure(self) if not isValid: return isValid # would like to check here whether it's empty of axis chunks; # instead, this will do for now (probably too slow, though): p1, p2 = self.struct.nanotube.getEndPoints() return (p1 is not None) 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.NanotubeSegment def _updateHandleList(self): """ Updates the list of handles (self.handles) @see: self.editStructure @see: EditNanotube_GraphicsMode._drawHandles() """ # note: if handlePoint1 and/or handlePoint2 can change more often than this # runs, we'll need to rerun the two assignments above whenever they # change and before the handle is drawn. An easy way would be to rerun # these assignments in the draw method of our GM. [bruce 080128] self.handles = [] # guess, but seems like a good idea [bruce 080128] self.handles.append(self.leftHandle) self.handles.append(self.rightHandle) if DEBUG_ROTATION_HANDLES: self.handles.append(self.rotationHandle1) self.handles.append(self.rotationHandle2) return def updateHandlePositions(self): """ Update handle positions and also update the resize handle radii and their 'stopper' lengths. @see: self._update_resizeHandle_radius() @see: self._update_resizeHandle_stopper_length() @see: EditNanotube_GraphicsMode._drawHandles() """ self.handlePoint1 = None # Needed! self.handlePoint2 = None #TODO: Call this method less often by implementing model_changed #see bug 2729 for a planned optimization self.cylinderWidth = CYLINDER_WIDTH_DEFAULT_VALUE self.cylinderWidth2 = CYLINDER_WIDTH_DEFAULT_VALUE self._update_resizeHandle_radius() handlePoint1, handlePoint2 = self.struct.nanotube.getEndPoints() if 0: # Debug prints print "updateHandlePositions(): handlePoint1=", handlePoint1 print "updateHandlePositions(): handlePoint2=", handlePoint2 if handlePoint1 is not None and handlePoint2 is not None: # (that condition is bugfix for deleted axis segment, bruce 080213) self.handlePoint1, self.handlePoint2 = handlePoint1, handlePoint2 #Update the 'stopper' length where the resize handle being dragged #should stop. See self._update_resizeHandle_stopper_length() #for more details self._update_resizeHandle_stopper_length() if DEBUG_ROTATION_HANDLES: self.rotation_distance1 = CYLINDER_WIDTH_DEFAULT_VALUE self.rotation_distance2 = CYLINDER_WIDTH_DEFAULT_VALUE #Following computes the base points for rotation handles. #to be revised -- Ninad 2008-02-13 unitVectorAlongAxis = norm(self.handlePoint1 - self.handlePoint2) v = cross(self.glpane.lineOfSight, unitVectorAlongAxis) self.rotationHandleBasePoint1 = self.handlePoint1 + norm(v) * 4.0 self.rotationHandleBasePoint2 = self.handlePoint2 + norm(v) * 4.0 return def _update_resizeHandle_radius(self): """ Finds out the sphere radius to use for the resize handles, based on atom /chunk or glpane display (whichever decides the display of the end atoms. The default value is 1.2. @see: self.updateHandlePositions() """ self.handleSphereRadius1 = HANDLE_RADIUS_DEFAULT_VALUE self.handleSphereRadius2 = HANDLE_RADIUS_DEFAULT_VALUE return def _update_resizeHandle_stopper_length(self): """ Update the limiting length at which the resize handle being dragged should 'stop' without proceeding further in the drag direction. The segment resize handle stops when you are dragging it towards the other resizeend and the distance between the two ends reaches two duplexes. The self._resizeHandle_stopper_length computed in this method is used as a lower limit of the 'range' option provided in declaration of resize handle objects (see class definition for the details) @see: self.updateHandlePositions() """ total_length = vlen(self.handlePoint1 - self.handlePoint2) nanotubeRise = self.struct.nanotube.getRise() self._resizeHandle_stopper_length = - total_length + nanotubeRise return def _gatherParameters(self): """ Return the parameters from the property manager UI. @return: The endpoints of the nanotube. @rtype: tuple (endPoint1, endPoint2). """ return self.propMgr.getParameters() def _createStructure(self): """ Returns the current NanotubeSegment being edited with a new nanotube chunk. @return : Nanotube segment that include the new nanotube chunk. @rtype: L{NanotubeSegment} """ try: # Create a new nanotube chunk using new params. n, m, type, endings, endPoint1, endPoint2 = self._gatherParameters() from cnt.model.NanotubeParameters import NanotubeParameters self.nanotube = NanotubeParameters() nanotube = self.nanotube nanotube.setChirality(n, m) nanotube.setType(type) nanotube.setEndings(endings) nanotube.setEndPoints(endPoint1, endPoint2) position = V(0.0, 0.0, 0.0) ntChunk = nanotube.build(self.struct.name, self.win.assy, position) nanotube.computeEndPointsFromChunk(ntChunk) # Needed. self.struct.addchild(ntChunk) #WARNING 2008-03-05: #When we actually permit modifying a nanotube without recreating it, #then the following properties must be set in self._modifyStructure #as well. Needs more thought. props =(nanotube.getChirality(), nanotube.getType(), nanotube.getEndings(), nanotube.getEndPoints()) self.struct.setProps(props) return self.struct except (PluginBug, UserError): self.struct.kill() raise PluginBug("Internal error while trying to recreate a NanotubeSegment.") return None def _modifyStructure(self, params): """ Modify the structure based on the parameters specified. Overrides EditCommand._modifystructure. This method removes the old nanotube and replaces it with a new one using self._createStructure. """ if not pref_nt_segment_resize_by_recreating_nanotube(): self._modifyStructure_NEW_SEGMENT_RESIZE(params) return # To modify the structure, we need to: # 1. Delete the current nanotube chunk inside the NanotubeSegment group. # 2. Create a new new nanotube chunk using nanotube.build() # 3. Add the newly generated nanotube to this NanotubeSegment. # 4. Update all the nanotube parameters. # Note: Steps 2-4 are done in self._createStructure() assert self.struct self.struct.members[0].kill() # Delete the current nanotube chunk. self.previousParams = params self.struct = self._createStructure() return def _modifyStructure_NEW_SEGMENT_RESIZE(self, params): #@ NOT FIXED """ This resizes without recreating whole nanotube Overrides EditCommand._modifystructure. @attention: is not implemented. """ #@TODO: - rename this method from _modifyStructure_NEW_SEGMENT_RESIZE #to self._modifyStructure, after more testing #This method is used for debug prefence: #'Nanotube Segment: resize without recreating whole nanotube' #see also self.modifyStructure_NEW_SEGMENT_RESIZE assert self.struct from utilities.debug import print_compact_stack print_compact_stack("_modifyStructure_NEW_SEGMENT_RESIZE() not fixed!" ) print "Params =", params self.nanotube = params #@ length_diff = self._determine_how_to_change_length() #@ if length_diff == 0: print_compact_stack("BUG: length_diff is always ZERO." ) return elif length_diff > 0: print "Nanotube longer by ", length_diff, ", angstroms." else: print "Nanotube shorter by ", length_diff, ", angstroms." return if numberOfBasePairsToAddOrRemove != 0: #@@@@ Not reached. resizeEnd_final_position = self._get_resizeEnd_final_position( ladderEndAxisAtom, abs(numberOfBasePairsToAddOrRemove), nanotubeRise ) self.nanotube.modify(self.struct, length_diff, ladderEndAxisAtom.posn(), resizeEnd_final_position) #Find new end points of structure parameters after modification #and set these values in the propMgr. new_end1 , new_end2 = self.struct.nanotube.getEndPoints() #@ params_to_set_in_propMgr = (new_end1, new_end2) #TODO: Need to set these params in the PM #and then self.previousParams = params_to_set_in_propMgr self.previousParams = params return def _get_resizeEnd_final_position(self, ladderEndAxisAtom, numberOfBases, nanotubeRise): final_position = None if self.grabbedHandle: final_position = self.grabbedHandle.currentPosition else: other_axisEndAtom = self.struct.getOtherAxisEndAtom(ladderEndAxisAtom) axis_vector = ladderEndAxisAtom.posn() - other_axisEndAtom.posn() segment_length_to_add = 0 #@ final_position = ladderEndAxisAtom.posn() + norm(axis_vector)*segment_length_to_add return final_position def getStructureName(self): """ Returns the name string of self.struct if there is a valid structure. Otherwise returns None. This information is used by the name edit field of this command's PM when we call self.propMgr.show() @see: EditNanotube_PropertyManager.show() @see: self.setStructureName """ if self.hasValidStructure(): return self.struct.name return None def setStructureName(self, name): """ Sets the name of self.struct to param <name> (if there is a valid structure. The PM of this command callss this method while closing itself @param name: name of the structure to be set. @type name: string @see: EditNanotube_PropertyManager.close() @see: self.getStructureName() """ #@BUG: We call this method in self.propMgr.close(). But propMgr.close() #is called even when the command is 'cancelled'. That means the #structure will get changed even when user hits cancel button or #exits the command by clicking on empty space. #This should really be done in self._finalizeStructure but that #method doesn't get called when you click on empty space to exit #the command. See EditNanotube_GraphicsMode.leftUp for a detailed #comment. if self.hasValidStructure(): self.struct.name = name return def getCursorText(self): """ This is used as a callback method in NanotubeLine mode @see: NanotubeLineMode.setParams, NanotubeLineMode_GM.Draw """ if self.grabbedHandle is None: return text = '' textColor = env.prefs[cursorTextColor_prefs_key] if not env.prefs[editNanotubeEditCommand_showCursorTextCheckBox_prefs_key]: return text, textColor currentPosition = self.grabbedHandle.currentPosition fixedEndOfStructure = self.grabbedHandle.fixedEndOfStructure nanotubeLength = vlen( currentPosition - fixedEndOfStructure ) nanotubeLengthString = self._getCursorText_length(nanotubeLength) text = nanotubeLengthString #@TODO: The following updates the PM as the cursor moves. #Need to rename this method so that you that it also does more things #than just to return a textString -- Ninad 2007-12-20 self.propMgr.ntLengthLineEdit.setText(nanotubeLengthString) return text, textColor def _getCursorText_length(self, nanotubeLength): """ Returns a string that gives the length of the Nanotube for the cursor text """ nanotubeLengthString = '' if env.prefs[editNanotubeEditCommand_cursorTextCheckBox_length_prefs_key]: lengthUnitString = 'A' #change the unit of length to nanometers if the length is > 10A #fixes part of bug 2856 if nanotubeLength > 10.0: lengthUnitString = 'nm' nanotubeLength = nanotubeLength * 0.1 nanotubeLengthString = "%5.3f%s"%(nanotubeLength, lengthUnitString) return nanotubeLengthString def modifyStructure(self): """ Called when a resize handle is dragged to change the length of the segment. (Called upon leftUp) . This method assigns the new parameters for the segment after it is resized and calls preview_or_finalize_structure which does the rest of the job. Note that Client should call this public method and should never call the private method self._modifyStructure. self._modifyStructure is called only by self.preview_or_finalize_structure @see: B{EditNanotube_ResizeHandle.on_release} (the caller) @see: B{SelectChunks_GraphicsMode.leftUp} (which calls the the relevent method in DragHandler API. ) @see: B{exprs.DraggableHandle_AlongLine}, B{exprs.DragBehavior} @see: B{self.preview_or_finalize_structure } @see: B{self._modifyStructure} As of 2008-02-01 it recreates the structure @see: a note in self._createStructure() about use of ntSegment.setProps """ if not pref_nt_segment_resize_by_recreating_nanotube(): self.modifyStructure_NEW_SEGMENT_RESIZE() return if self.grabbedHandle is None: return self.propMgr.endPoint1 = self.grabbedHandle.fixedEndOfStructure self.propMgr.endPoint2 = self.grabbedHandle.currentPosition #@length = vlen(self.propMgr.endPoint1 - self.propMgr.endPoint2 ) #@ self.preview_or_finalize_structure(previewing = True) self.updateHandlePositions() self.glpane.gl_update() return def modifyStructure_NEW_SEGMENT_RESIZE(self): #@ NOT FIXED """ Called when a resize handle is dragged to change the length of the segment. (Called upon leftUp) . This method assigns the new parameters for the segment after it is resized and calls preview_or_finalize_structure which does the rest of the job. Note that Client should call this public method and should never call the private method self._modifyStructure. self._modifyStructure is called only by self.preview_or_finalize_structure @see: B{EditNanotube_ResizeHandle.on_release} (the caller) @see: B{SelectChunks_GraphicsMode.leftUp} (which calls the the relevent method in DragHandler API. ) @see: B{exprs.DraggableHandle_AlongLine}, B{exprs.DragBehavior} @see: B{self.preview_or_finalize_structure } @see: B{self._modifyStructure} As of 2008-02-01 it recreates the structure @see: a note in self._createStructure() about use of ntSegment.setProps """ #TODO: need to cleanup this and may be use use something like #self.previousParams = params in the end -- 2008-03-24 (midnight) #@TODO: - rename this method from modifyStructure_NEW_SEGMENT_RESIZE #to self.modifyStructure, after more testing #This method is used for debug prefence: #'Nanotube Segment: resize without recreating whole duplex' #see also self._modifyStructure_NEW_SEGMENT_RESIZE if self.grabbedHandle is None: return self.propMgr.endPoint1 = self.grabbedHandle.fixedEndOfStructure self.propMgr.endPoint2 = self.grabbedHandle.currentPosition DEBUG_DO_EVERYTHING_INSIDE_MODIFYSTRUCTURE_METHOD = False if DEBUG_DO_EVERYTHING_INSIDE_MODIFYSTRUCTURE_METHOD: # TO DO: this entire block of code. --Mark 2008-04-03 print_compact_stack("modifyStructure_NEW_SEGMENT_RESIZE(): NOT FIXED") length = vlen(self.grabbedHandle.fixedEndOfStructure - \ self.grabbedHandle.currentPosition ) endAtom1, endAtom2 = self.struct.getAxisEndAtoms() #@ for atm in (endAtom1, endAtom2): if not same_vals(self.grabbedHandle.fixedEndOfStructure, atm.posn()): ladderEndAxisAtom = atm break endPoint1, endPoint2 = self.struct.nanotube.getEndPoints() old_dulex_length = vlen(endPoint1 - endPoint2) nanotubeRise = self.struct.getProps() #@ params_to_set_in_propMgr = ( self.grabbedHandle.origin, self.grabbedHandle.currentPosition, ) ##self._modifyStructure(params) ############################################ self.nanotube = NanotubeParameters() #@ Creates 5x5 CNT. Missing PM params. length_diff = self._determine_how_to_change_length() ladderEndAxisAtom = self.get_axisEndAtom_at_resize_end() #@ #@ Nanotube class needs modify() method. self.nanotube.modify(self.struct, length_diff, ladderEndAxisAtom.posn(), self.grabbedHandle.currentPosition) #TODO: Important note: How does NE1 know that structure is modified? #Because number of base pairs parameter in the PropMgr changes as you #drag the handle . This is done in self.getCursorText() ... not the #right place to do it. OR that method needs to be renamed to reflect #this as suggested in that method -- Ninad 2008-03-25 self.preview_or_finalize_structure(previewing = True) ##self.previousParams = params_to_set_in_propMgr self.glpane.gl_update() return def get_axisEndAtom_at_resize_end(self): ladderEndAxisAtom = None if self.grabbedHandle is not None: ladderEndAxisAtom = self.struct.getAxisEndAtomAtPosition(self.grabbedHandle.origin) else: endAtom1, endAtom2 = self.struct.getAxisEndAtoms() ladderEndAxisAtom = endAtom2 return ladderEndAxisAtom def _determine_how_to_change_length(self): #@ NEEDS WORK """ Returns the difference in length between the original nanotube and the modified nanotube, where: 0 = no change in length > 0 = lengthen < 0 = trim """ nanotubeRise = self.struct.nanotube.getRise() endPoint1, endPoint2 = self.struct.nanotube.getEndPoints() #@ original_nanotube_length = vlen(endPoint1 - endPoint2) new_nanotube_length = vlen(endPoint1 - endPoint2) #@ return new_nanotube_length - original_nanotube_length #@ ALWAYS RETURNS ZERO def makeMenus(self): """ Create context menu for this command. """ if not hasattr(self, 'graphicsMode'): return selobj = self.glpane.selobj if selobj is None: return self.Menu_spec = [] 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 if highlightedChunk is None: return highlightedChunk.make_glpane_cmenu_items(self.Menu_spec, self) return
NanoCAD-master
cad/src/cnt/commands/EditNanotube/EditNanotube_EditCommand.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ EditNanotube_GraphicsMode.py Graphics mode for EditNanotube_EditCommand. While in this command, user can (a) Highlight and then left drag the resize handles located at the two 'endpoints' of the nanotube to change its length. (b) Highlight and then left drag any nanotube atom to translate the nanotube segment along the axis @author: Ninad, Mark @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: Created 2008-03-10 from copy of DnaSegment_GraphicsMode.py Recreated 2008-04-02 from copy of DnaSegment_GraphicsMode.py """ from Numeric import dot from PyQt4.Qt import QMouseEvent from cnt.commands.BuildNanotube.BuildNanotube_GraphicsMode import BuildNanotube_GraphicsMode from cnt.model.NanotubeSegment import NanotubeSegment from graphics.drawing.drawNanotubeLadder import drawNanotubeLadder import foundation.env as env import math from geometry.VQT import V, norm, A, Q, vlen from utilities.constants import gray, black, darkred from utilities.debug import print_compact_traceback from commands.Select.Select_GraphicsMode import DRAG_STICKINESS_LIMIT from model.chem import Atom from model.bonds import Bond SPHERE_RADIUS = 2.0 SPHERE_DRAWLEVEL = 2 from cnt.commands.BuildNanotube.BuildNanotube_GraphicsMode import DEBUG_CLICK_ON_OBJECT_ENTERS_ITS_EDIT_COMMAND _superclass = BuildNanotube_GraphicsMode class EditNanotube_GraphicsMode(BuildNanotube_GraphicsMode): """ Graphics mode for EditNanotube_EditCommand. """ _sphereColor = darkred _sphereOpacity = 0.5 #The flag that decides whether to draw the handles. This flag is #set during left dragging, when no handle is 'grabbed'. This optimizes the #drawing code as it skips handle drawing code and also the computation #of handle positions each time the mouse moves #@see self.leftUp , self.leftDrag, self.Draw_other for more details _handleDrawingRequested = True #Some left drag variables used to drag the whole segment along axis or #rotate the segment around its own axis of for free drag translation _movablesForLeftDrag = [] #The common center is the center about which the list of movables (the segment #contents are rotated. #@see: self.leftADown where this is set. #@see: self.leftDrag where it is used. _commonCenterForRotation = None _axis_for_constrained_motion = None #Flags that decide the type of left drag. #@see: self.leftADown where it is set and self.leftDrag where these are used _translateAlongAxis = False _rotateAboutAxis = False _freeDragWholeStructure = False cursor_over_when_LMB_pressed = '' def Enter_GraphicsMode(self): _superclass.Enter_GraphicsMode(self) #Precaution self.clear_leftA_variables() return def bareMotion(self, event): """ @see: self.update_cursor_for_no_MB """ value = _superclass.bareMotion(self, event) #When the cursor is over a specific atom, we need to display #a different icon. (e.g. when over a strand atom, it should display # rotate cursor) self.update_cursor() return value def update_cursor_for_no_MB(self): """ Update the cursor for Select mode (Default implementation). """ _superclass.update_cursor_for_no_MB(self) #minor optimization -- don't go further into the method if #nothing is highlighted i.e. self.o.selobj is None. if self.o.selobj is None: return if self.command and hasattr(self.command.struct, 'isAncestorOf'): if not self.command.struct.isAncestorOf(self.o.selobj): return if self.o.modkeys is None: if isinstance(self.o.selobj, Atom): self.o.setCursor(self.win.translateAlongCentralAxisCursor) elif isinstance(self.o.selobj, Bond): self.o.setCursor(self.win.TranslateSelectionCursor) return def leftDown(self, event): """ """ self.reset_drag_vars() self.clear_leftA_variables() obj = self.get_obj_under_cursor(event) if obj is None: self.cursor_over_when_LMB_pressed = 'Empty Space' #@see dn_model.NanotubeSegment.isAncestorOf. #It checks whether the object under the #cursor (which is glpane.selobj) is contained within the NanotubeSegment #currently being edited #Example: If the object is an Atom, it checks whether the #atoms is a part of the dna segment. *being edited* #(i.e. self.comman.struct). If its not (e.g. its an atom of another #dna segment, then the this method returns . (leftDrag on structures #NOT being edited won't do anything-- a desirable effect) if self.command and hasattr(self.command.struct, 'isAncestorOf'): if not self.command.struct.isAncestorOf(obj): _superclass.leftDown(self, event) return else: #Optimization: This value will be used in self.leftDrag. # Instead of checking everytime whether the #self.command.struct contains the highlighted objetc #(glpane.selobj) _superclass.leftDown(self, event) self.cursor_over_when_LMB_pressed = 'Structure Being Edited' self.LMB_press_event = QMouseEvent(event) # Make a copy of this event #and save it. # We will need it later if we change our mind and start selecting a 2D # region in leftDrag().Copying the event in this way is necessary #because Qt will overwrite <event> later (in # leftDrag) if we simply set self.LMB_press_event = event. mark 060220 self.LMB_press_pt_xy = (event.pos().x(), event.pos().y()) # <LMB_press_pt_xy> is the position of the mouse in window coordinates #when the LMB was pressed. #Used in mouse_within_stickiness_limit (called by leftDrag() and other #methods). # We don't bother to vertically flip y using self.height #(as mousepoints does), # since this is only used for drag distance within single drags. #Subclasses should override one of the following method if they need #to do additional things to prepare for dragging. self._leftDown_preparation_for_dragging(obj, event) return def clear_leftA_variables(self): self._movablesForLeftDrag = [] self._commonCenterForRotation = None self._axis_for_constrained_motion = None _translateAlongAxis = False _rotateAboutAxis = False _freeDragWholeStructure = False return def _leftDown_preparation_for_dragging(self, objectUnderMouse, event): """ Handle left down event. Preparation for rotation 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.leftDragRotation Overrides _superclass._leftDown_preparation_for_dragging """ self.o.SaveMouse(event) self.picking = True self.dragdist = 0.0 farQ_junk, self.movingPoint = self.dragstart_using_GL_DEPTH( event) self.leftADown(objectUnderMouse, event) return def leftADown(self, objectUnderMouse, event): """ Method called during mouse left down . It sets some parameters necessary for rotating the structure around its own axis (during a left drag to follow) In graphics modes such as RotateChunks_GraphicsMode, rotating entities around their own axis is acheived by holding down 'A' key and then left dragging , thats why the method is named as 'leftADrag' (A= Axis) """ ma = V(0, 0, 0) if self.command and self.command.struct: ma = self.command.struct.getAxisVector() self._axis_for_constrained_motion = self.command.struct.getAxisVector() #@see: NanotubeSegment.get_all_content_chunks() for details about #what it returns. See also NanotubeSegment.isAncestorOf() which #is called in self.leftDown to determine whether the NanotubeSegment #user is editing is an ancestor of the selobj. (it also considers #'logical contents' while determining whether it is an ancestor. #-- Ninad 2008-03-11 self._movablesForLeftDrag = self.command.struct.get_all_content_chunks() ma = norm(V(dot(ma,self.o.right),dot(ma,self.o.up))) self.Zmat = A([ma,[-ma[1],ma[0]]]) obj = objectUnderMouse if obj is None: # Cursor over empty space. self.emptySpaceLeftDown(event) #Left A drag is not possible unless the cursor is over a #selected object. So make sure to let self.leftAError method sets #proper flag so that left-A drag won't be done in this case. return if isinstance(obj, Atom): self._translateAlongAxis = True self._rotateAboutAxis = False self._freeDragWholeStructure = False elif 0: #@@@ isinstance(obj, Atom): # Rotate about axis not supported. self._translateAlongAxis = False self._rotateAboutAxis = True self._freeDragWholeStructure = False #The self._commonCenterForrotation is a point on segment axis #about which the whole segment will be rotated. Specifying this #as a common center for rotation fixes bug 2578. We determine this #by selecting the center of the axis atom that is connected #(bonded) to the strand atom being left dragged. Using this as a #common center instead of the avaraging the center of the segment #axis atoms has an advantage. We compute the rotation offset 'dy' #with reference to the strand atom being dragged, so it seems more #appropriate to use the nearest axis center for segment rotation #about axis. But what happens if the axis is not straigt but is #curved? Should we select the averaged center of all axis atoms? #..that may not be right. Or should we take _average center_ of #a the following axis atoms --strand atoms axis_neighbors and #axis atom centers directly connected to this axis atom. # -- Ninad 2008-03-25 self._commonCenterForRotation = obj.axis_neighbor().posn() elif isinstance(obj, Bond): self._translateAlongAxis = False self._rotateAboutAxis = False self._freeDragWholeStructure = True self.o.SaveMouse(event) self.dragdist = 0.0 return def leftUp(self, event): """ Method called during Left up event. """ _superclass.leftUp(self, event) self.update_selobj(event) self.update_cursor() self.o.gl_update() #Reset the flag that decides whether to draw the handles. This flag is #set during left dragging, when no handle is 'grabbed'. See the #class definition for more details about this flag. if self.command and self.command.handles: if not self._handleDrawingRequested: self._handleDrawingRequested = True pass pass return def leftDrag(self, event): """ Method called during Left drag event. """ if self.mouse_within_stickiness_limit(event, DRAG_STICKINESS_LIMIT): # [let this happen even for drag_handlers -- bruce 060728] return self.current_obj_clicked = False #If there is a drag handler (e.g. a segment resize handle is being #dragged, call its drag method and don't proceed further. #NOTE: #In SelectChunks_GraphicsMode.leftDrag, there is a condition statement #which checks if self.drag_handler is in assy.getSelecteedMovables #I don't know why it does that... I think it always assums that the #drag handler is officially a node in the MT? In our case, #the drag handler is a 'Highlightable' object (actually #an instance of 'EditNanotube_ResizeHandle' (has superclass from #exprs module ..which implements API for a highlightable object #So it doesn't get registered in the selectMovables list. Thats why #we are not calling _superclass.leftDrag. The above mentioned #method in the superclass needs to be revised -- Ninad 2008-02-01 if self.drag_handler is not None: self.dragHandlerDrag(self.drag_handler, event) return #If the cursor was not over something that belonged to structure #being edited (example - atom or bond of a differnt NanotubeSegment) #don't do left drag.(left drag will work only for the NanotubeSegment #eing edited) if self.cursor_over_when_LMB_pressed != 'Structure Being Edited': return #Duplicates some code from SelectChunks_GraphicsMode.leftDrag #see a to do comment below in this method if self.cursor_over_when_LMB_pressed == 'Empty Space': 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 #TODO: This duplicates some code from SelectChunks_GraphicsMode.leftDrag #Following code will never be called if a handle is grabbed. #Thus, it instructs what to do for other cases (when user is not moving #the draggable handles) #First, don't draw handles (set the flag here so that self.Draw_other knows #not to draw handles) This skips unnecessary computation of new handle #position during left dragging. The flag is reset to True in leftUp if self.command and self.command.handles: if self.command.grabbedHandle is None: self._handleDrawingRequested = False #Copies AND modifies some code from Move_GraphicsMode for doing #leftDrag translation or rotation. 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) offset = None if self._translateAlongAxis: offset = dx * self._axis_for_constrained_motion for mol in self._movablesForLeftDrag: mol.move(offset) if self._rotateAboutAxis: rotation_quat = Q(self._axis_for_constrained_motion, -dy) self.o.assy.rotateSpecifiedMovables( rotation_quat, movables = self._movablesForLeftDrag, commonCenter = self._commonCenterForRotation ) if self._freeDragWholeStructure: try: point = self.dragto( self.movingPoint, event) offset = point - self.movingPoint self.o.assy.translateSpecifiedMovables(offset, movables = self._movablesForLeftDrag) self.movingPoint = point except: #may be self.movingPoint is not defined in leftDown? #(e.g. _superclass.leftDown doesn't get called or as a bug? ) print_compact_traceback("bug:unable to free drag the whole segment") if offset: # Update the nanotube endpoints. endPt1, endPt2 = self.command.struct.nanotube.getEndPoints() endPt1 += offset endPt2 += offset self.command.struct.nanotube.setEndPoints(endPt1, endPt2) self.dragdist += vlen(deltaMouse) #k needed?? [bruce 070605 comment] self.o.SaveMouse(event) self.o.assy.changed() #ninad060924 fixed bug 2278 self.o.gl_update() return def drawHighlightedChunk(self, glpane, selobj, hicolor, hicolor2): """ [overrides SelectChunks_basicGraphicsMode method] """ # bruce 071008 (intending to be equivalent to prior code) return False def Draw_other(self): """ """ _superclass.Draw_other(self) if self._handleDrawingRequested: self._drawHandles() return def _drawHandles(self): """ Draw the handles for the command.struct """ if 0: #self.command and self.command.hasValidStructure(): for handle in self.command.handles: handle.draw() if self.command and self.command.hasValidStructure(): for handle in self.command.handles: if handle.hasValidParamsForDrawing(): handle.draw() handleType = '' if self.command.grabbedHandle is not None: if self.command.grabbedHandle in [self.command.rotationHandle1, self.command.rotationHandle2]: handleType = 'ROTATION_HANDLE' else: handleType = 'RESIZE_HANDLE' # self.command.struct is (temporarily?) None after a nanotube segment # has been resized. This causes a trackback. This seems to fix it. # --Mark 2008-04-01 if not self.command.struct: return if handleType and handleType == 'RESIZE_HANDLE': #use self.glpane.displayMode for rubberbandline displayMode drawNanotubeLadder(self.command.grabbedHandle.fixedEndOfStructure, self.command.grabbedHandle.currentPosition, self.command.struct.nanotube.getRise(), self.glpane.scale, self.glpane.lineOfSight, ladderWidth = self.command.struct.nanotube.getDiameter(), beamThickness = 4.0, beam1Color = gray, beam2Color = gray, ) self._drawCursorText() else: #No handle is grabbed. But may be the structure changed #(e.g. while dragging it ) and as a result, the endPoint positions #are modified. So we must update the handle positions because #during left drag (when handle is not dragged) we skip the #handle drawing code and computation to update the handle positions #TODO: see bug 2729 for planned optimization self.command.updateHandlePositions() return pass
NanoCAD-master
cad/src/cnt/commands/EditNanotube/EditNanotube_GraphicsMode.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ EditNanotube_PropertyManager.py @author: Ninad, Mark @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. TODO: as of 2008-01-18 See EditNanotube_EditCommand for details. """ from PyQt4.Qt import SIGNAL from PM.PM_GroupBox import PM_GroupBox from command_support.DnaOrCnt_PropertyManager import DnaOrCnt_PropertyManager 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_SpinBox import PM_SpinBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_LineEdit import PM_LineEdit from geometry.VQT import V, vlen from utilities.debug import print_compact_stack from utilities.prefs_constants import editNanotubeEditCommand_cursorTextCheckBox_length_prefs_key from utilities.prefs_constants import editNanotubeEditCommand_showCursorTextCheckBox_prefs_key from widgets.prefs_widgets import connect_checkbox_with_boolean_pref _superclass = DnaOrCnt_PropertyManager class EditNanotube_PropertyManager( DnaOrCnt_PropertyManager ): """ The NanotubeSegmenta_PropertyManager class provides a Property Manager for the EditNanotube_EditCommand. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Nanotube Properties" pmName = title iconPath = "ui/actions/Command Toolbar/BuildNanotube/EditNanotube.png" def __init__( self, command ): """ Constructor for the Cnt Segment Properties property manager. """ #For model changed signal self.previousSelectionParams = None #see self.connect_or_disconnect_signals for comment about this flag self.isAlreadyConnected = False self.isAlreadyDisconnected = False # Initialized here. Their values will be set in # _update_widgets_in_PM_before_show() self.endPoint1 = V(0, 0, 0) self.endPoint2 = V(0, 0, 0) _superclass.__init__( self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_WHATS_THIS_BUTTON) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect change_connect(self.nameLineEdit, SIGNAL("editingFinished()"), self._nameChanged) change_connect(self.showCursorTextCheckBox, SIGNAL('stateChanged(int)'), self._update_state_of_cursorTextGroupBox) return def show(self): """ Show this property manager. Overrides EditCommand_PM.show() This method also retrives the name information from the command's structure for its name line edit field. @see: EditNanotube_EditCommand.getStructureName() @see: self.close() """ _superclass.show(self) #if self.command is not None: #name = self.command.getStructureName() #if name is not None: #self.nameLineEdit.setText(name) def close(self): """ Close this property manager. Also sets the name of the self.command's structure to the one displayed in the line edit field. @see self.show() @see: EditNanotube_EditCommand.setStructureName """ if self.command is not None: name = str(self.nameLineEdit.text()) self.command.setStructureName(name) _superclass.close(self) def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Overrides DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox """ connect_checkbox_with_boolean_pref( self.showCursorTextCheckBox , editNanotubeEditCommand_showCursorTextCheckBox_prefs_key) def _params_for_creating_cursorTextCheckBoxes(self): """ Returns params needed to create various cursor text checkboxes connected to prefs_keys that allow custom cursor texts. @return: A list containing tuples in the following format: ('checkBoxTextString' , preference_key). PM_PrefsCheckBoxes uses this data to create checkboxes with the the given names and connects them to the provided preference keys. (Note that PM_PrefsCheckBoxes puts thes within a GroupBox) @rtype: list @see: PM_PrefsCheckBoxes @see: self._loadDisplayOptionsGroupBox where this list is used. @see: Superclass method which is overridden here -- DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = \ [ #Format: (" checkbox text", prefs_key) ("Nanotube length", editNanotubeEditCommand_cursorTextCheckBox_length_prefs_key) ] return params def setParameters(self, params): """ This is called when entering "Nanotube Segment Properties (i.e. "Edit properties...") to retrieve and set parameters of the nanotube segment that might be modified during this command and are needed to regenerate the nanotube segment. @param params: The parameters of the nanotube segment. These parameters are retreived via L{NanotubeSegment.getProps()}, called from L{EditNanotube_EditCommand.editStructure()}. Parameters: - n, m (chirality) - type (i.e. carbon or boron nitride) - endings (none, hydrogen, nitrogen) - endpoints (endPoint1, endPoint2) @type params: list (n, m), type, endings, (endPoint1, endPoint2) @note: Any widgets in the property manager that display these parameters should be updated here. @see: L{NanotubeSegment.getProps()} TODO: - Make this a EditCommand_PM API method? - See also the routines GraphicsMode.setParams or object.setProps ..better to name them all in one style? """ (self.n, self.m), self.type, self.endings,\ (self.endPoint1, self.endPoint2) = params # This is needed to update the endpoints since the Nanotube segment # may have been moved (i.e. translated or rotated). In that case, # the endpoints are not updated, so we recompute them here. nanotubeChunk = self.command.struct.members[0] self.endPoint1, self.endPoint2, radius = \ self.command.struct.nanotube.computeEndPointsFromChunk(nanotubeChunk) if 0: print "\n--------------" print "setParameters():" print "Struct=", self.command.struct print "N, M:", self.n, self.m print "type:", self.type print "endings:", self.endings print "pt1, pt2:", self.endPoint1, self.endPoint2 def getParameters(self): """ Get the parameters that the edit command will use to determine if any have changed. If any have, then the nanotube will be modified. """ if 0: print "\n--------------" print "getParameters():" print "Struct=", self.command.struct print "N, M:", self.n, self.m print "type:", self.type print "endings:", self.endings print "pt1, pt2:", self.endPoint1, self.endPoint2 return (self.n, self.m, self.type, self.endings, self.endPoint1, self.endPoint2) def _update_widgets_in_PM_before_show(self): """ This is called only when user is editing an existing structure. Its different than self.update_widgets_in_pm_before_show. (that method is called just before showing the property manager) @see: EditNanotube_EditCommand.editStructure() """ if self.command and self.command.hasValidStructure(): self.nanotube = self.command.struct.nanotube self.n, self.m = self.nanotube.getChirality() self.type = self.nanotube.getType() self.endings = self.nanotube.getEndings() self.endPoint1, self.endPoint2 = self.nanotube.getEndPoints() pass # Note that _update_widgets_in_PM_before_show() is called in # self.show, before you connect the signals. So, for the # 'first show' we will need to manually set the value of any # widgets that need updated. But later, when a different # NanotubeSegment is clicked, (while still in # EditNanotube_EditCommand, the propMgr will already be connected # so any calls in that case is redundant. self.updateNameField() self.updateLength() self.updateNanotubeDiameter() self.updateChirality() return def _update_UI_do_updates(self): """ Overrides superclass method. @see: Command_PropertyManager._update_UI_do_updates() """ self._update_widgets_in_PM_before_show() if self.command.struct: msg = "Editing structure <b>%s</b>." % \ self.command.getStructureName() else: msg = "Select a nanotube to edit." self.updateMessage(msg) return def _addGroupBoxes( self ): """ Add the Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Parameters" ) self._loadGroupBox1( self._pmGroupBox1 ) self._displayOptionsGroupBox = PM_GroupBox( self, title = "Display Options" ) self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox ) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 4. """ self.nameLineEdit = PM_LineEdit( pmGroupBox, label = "Name:", text = "", setAsDefault = False) # Nanotube Length self.ntLengthLineEdit = \ PM_LineEdit( pmGroupBox, label = "Length: ", text = "0.0 Angstroms", setAsDefault = False) self.ntLengthLineEdit.setDisabled(True) # Nanotube Radius self.ntDiameterLineEdit = \ PM_LineEdit( pmGroupBox, label = "Nanotube Diameter: ", setAsDefault = False) self.ntDiameterLineEdit.setDisabled(True) # Nanotube chirality. These are disabled (read-only) for now. --Mark self.chiralityNSpinBox = \ PM_SpinBox( pmGroupBox, label = "Chirality (n) :", minimum = 2, maximum = 100, setAsDefault = True ) self.chiralityNSpinBox.setDisabled(True) self.chiralityMSpinBox = \ PM_SpinBox( pmGroupBox, label = "Chirality (m) :", minimum = 0, maximum = 100, setAsDefault = True ) self.chiralityMSpinBox.setDisabled(True) def _addWhatsThisText(self): """ Add what's this text. """ pass def _addToolTipText(self): """ Add Tooltip text """ pass def _nameChanged(self): """ Slot for "Name" field. @TODO: Include a validator for the name field. """ _name = str(self.nameLineEdit.text()) if not _name: # Minimal test. Need to implement a validator. self.updateNameField() return self.command.setStructureName(_name) msg = "Editing structure <b>%s</b>." % _name self.updateMessage(msg) return def updateNameField(self): """ Update the name field showing the name of the currently selected protein. clear the combobox list. """ if self.command.hasValidStructure(): self.nameLineEdit.setEnabled(True) self.nameLineEdit.setText(self.command.getStructureName()) else: self.nameLineEdit.setDisabled(True) self.nameLineEdit.setText("") return def updateLength( self ): """ Update the nanotube Length lineEdit widget. """ if self.command.hasValidStructure(): _nanotubeLength = vlen(self.endPoint1 - self.endPoint2) _lengthText = "%-7.4f Angstroms" % (_nanotubeLength) else: _lengthText = "" self.ntLengthLineEdit.setText(_lengthText) return def updateNanotubeDiameter(self): """ Update the nanotube Diameter lineEdit widget. """ if self.command.hasValidStructure(): _diameterText = "%-7.4f Angstroms" % (self.nanotube.getDiameter()) else: _diameterText = "" self.ntDiameterLineEdit.setText(_diameterText) return def updateChirality( self ): """ Update the nanotube chirality spinboxes (read-only). """ if self.command.hasValidStructure(): n, m = self.nanotube.getChirality() else: n = 0 m = 0 self.chiralityNSpinBox.setValue(n) self.chiralityMSpinBox.setValue(m) return pass # End of EditNanotube_PropertyManager class
NanoCAD-master
cad/src/cnt/commands/EditNanotube/EditNanotube_PropertyManager.py
NanoCAD-master
cad/src/cnt/commands/EditNanotube/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ EditNanotube_ResizeHandle.py @author: Ninad, Mark @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version: $Id$ @license: GPL TODO: Attributes such as height_ref need to be renamed. But this should really be done in the superclass exprs.DraggableHandle_AlongLine. """ from exprs.attr_decl_macros import Option from exprs.attr_decl_macros import State from exprs.Set import Action from exprs.__Symbols__ import _self from exprs.Overlay import Overlay from exprs.ExprsConstants import Drawable from exprs.ExprsConstants import Color from exprs.ExprsConstants import Point from exprs.ExprsConstants import ORIGIN from exprs.Rect import Sphere from exprs.Arrow import Arrow import foundation.env as env from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.prefs_constants import selectionColor_prefs_key from utilities.constants import olive from geometry.VQT import V from exprs.DraggableHandle import DraggableHandle_AlongLine from exprs.ExprsConstants import StateRef class EditNanotube_ResizeHandle(DraggableHandle_AlongLine): """ Provides a resize handle for editing the length of an existing NanotubeSegment. """ #Handle color will be changed depending on whether the the handle is grabbed #So this is a 'State variable and its value is used in 'appearance' #(given as an optional argument to 'Sphere') handleColor = State( Color, olive) #The state ref that determines the radius (of the sphere) of this handle. #See EditNanotube_EditCommand._determine_resize_handle_radius() for more #details sphereRadius = Option(StateRef, 1.2) #Stateusbar text. Variable needs to be renamed in superclass. sbar_text = Option(str, "Drag the handle to resize the segment", doc = "Statusbar text on mouseover") #Command object specified as an 'Option' during instantiation of the class #see EditNanotube_EditCommand class definition. command = Option(Action, doc = 'The Command which instantiates this handle') #Current position of the handle. i.e. it is the position of the handle #under the mouse. (its differert than the 'orifinal position) #This variable is used in self.command.graphicsMode to draw a rubberband #line and also to specify the endPoint2 of the structure while modifying #it. See EditNanotube_EditCommand.modifyStructure for details. currentPosition = _self.origin + _self.direction*_self.height_ref.value #Fixed end of the structure (self.command.struct) ..meaning that end won't #move while user grabbs and draggs this handle (attached to a the other #'moving endPoint) . This variable is used to specify endPoint1 of the #structure while modifyin it. See EditNanotube_EditCommand.modifyStructure #and self.on_release for details. fixedEndOfStructure = Option(Point, V(0, 0, 0)) #If this is false, the 'highlightable' object i.e. this handle #won't be drawn. See DraggableHandle.py for the declararion of #the delegate(that defines a Highlightable) We define a If_Exprs to check #whether to draw the highlightable object. should_draw = State(bool, True) appearance = Overlay( Sphere(_self.sphereRadius, handleColor, center = ORIGIN), Arrow( color = handleColor, arrowBasePoint = ORIGIN + _self.direction*2.0*_self.sphereRadius, tailPoint = ORIGIN, tailRadius = _self.sphereRadius*0.3, scale = _self.command.glpane.scale) ) HHColor = env.prefs[hoverHighlightingColor_prefs_key] appearance_highlighted = Option( Drawable, Overlay( Sphere(_self.sphereRadius, HHColor, center = ORIGIN), Arrow( color = HHColor, arrowBasePoint = ORIGIN + _self.direction*2.0*_self.sphereRadius, tailPoint = ORIGIN, tailRadius = _self.sphereRadius*0.3, scale = _self.command.glpane.scale) )) def on_press(self): """ Actions when handle is pressed (grabbed, during leftDown event) @see: B{SelectChunks.GraphicsMode.leftDown} @see: B{EditNanotube_EditCommand.grabbedHandle} @see: B{EditNanotube_GraphicsMode.Draw} (which uses some attributes of the current grabbed handle of the command. @see: B{DragHandle_API} """ #Change the handle color when handle is grabbed. See declaration of #self.handleColor in the class definition. self.handleColor = env.prefs[selectionColor_prefs_key] #assign 'self' as the curent grabbed handle of the command. self.command.grabbedHandle = self def on_drag(self): """ Method called while dragging this handle . @see: B{DragHandle_API} """ #Does nothing at the moment. pass def on_release(self): """ This method gets called during leftUp (when the handle is released) @see: B{EditNanotube_EditCommand.modifyStructure} @see: self.on_press @see: B{SelectChunks.GraphicsMode.leftUp} @see: B{DragHandle_API} """ self.handleColor = olive if self.command and hasattr(self.command, 'modifyStructure'): self.command.modifyStructure() #Clear the grabbed handle attribute (the handle is no longer #grabbed) self.command.grabbedHandle = None def hasValidParamsForDrawing(self): """ Returns True if the handles origin and direction are not 'None'. @see: NanotubeSesgment_GraphicsMode._draw_handles() where the caller uses this to decide whether this handle can be drawn without a problem. """ #NOTE: Better to do it in the drawing code of this class? #But it uses a delegate to draw stuff (see class Highlightable) #May be we should pass this method to that delegate as an optional #argument -- Ninad 2008-04-02 #NOTES: See also: #delegate in class DraggableHandle defined as -- #delegate = If_Exprs(_self.should_draw, Highlightable(....)) if self.origin is None: self.should_draw = False else: self.should_draw = True return self.should_draw
NanoCAD-master
cad/src/cnt/commands/EditNanotube/EditNanotube_ResizeHandle.py
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad, Mark @copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details. @version: $Id$ @license: GPL TODO: - User Preferences for different rubberband line display styles """ from utilities.constants import gray, black, darkred, blue, white from graphics.drawing.drawNanotubeLadder import drawNanotubeLadder from temporary_commands.LineMode.Line_Command import Line_Command from temporary_commands.LineMode.Line_GraphicsMode import Line_GraphicsMode # == GraphicsMode part _superclass_for_GM = Line_GraphicsMode class NanotubeLine_GM( Line_GraphicsMode ): """ Custom GraphicsMode for use as a component of NanotubeLineMode. @see: L{NanotubeLineMode} for more comments. @see: InsertNanotube_EditCommand where this is used as a GraphicsMode class. The default command part in this file is a Default class implementation of self.command (see class NanotubeLineMode) """ # The following valuse are used in drawing the 'sphere' that represent the # first endpoint of the line. See Line_GraphicsMode.Draw_other for details. endPoint1_sphereColor = white endPoint1_sphereOpacity = 1.0 text = '' def leftUp(self, event): """ Left up method """ if self.command.mouseClickLimit is None: if len(self.command.mouseClickPoints) == 2: self.endPoint2 = None self.command.createStructure() #DISABLED AS OF 2008-01-11. (Implementation changed -- #See InsertNanotube_EditCommand.createStructure for new #implementaion) ##self.command.callback_addSegments() self.glpane.gl_update() return def snapLineEndPoint(self): """ Snap the line to the specified constraints. To be refactored and expanded. @return: The new endPoint2 i.e. the moving endpoint of the rubberband line . This value may be same as previous or snapped so that it lies on a specified vector (if one exists) @rtype: B{A} """ if self.command.callbackForSnapEnabled() == 1: endPoint2 = _superclass_for_GM.snapLineEndPoint(self) else: endPoint2 = self.endPoint2 return endPoint2 def Draw_other(self): """ Draw the Nanotube rubberband line (a ladder representation) """ _superclass_for_GM.Draw_other(self) if self.endPoint2 is not None and \ self.endPoint1 is not None: # Draw the ladder. drawNanotubeLadder( self.endPoint1, self.endPoint2, self.command.nanotube.getRise(), self.glpane.scale, self.glpane.lineOfSight, ladderWidth = self.command.nanotube.getDiameter(), beamThickness = 4.0, ) return pass # end of class NanotubeLine_GM # == Command part class NanotubeLineMode(Line_Command): # not used as of 080111, see docstring """ [no longer used as of 080111, see details below] Encapsulates the Line_Command functionality. @see: L{Line_Command} @see: InsertNanotube_EditCommand.getCursorText() NOTE: [2008-01-11] The default NanotubeLineMode (command) part is not used as of 2008-01-11 Instead, the interested commands use its GraphicsMode class. However, its still possible to use and implement the default command part. (The old implementation of generating Cnt using endpoints of a line used this default command class (NanotubeLineMode). so the method in this class such as self.createStructure does nothing . @see: InsertNanotube_EditCommand where the GraphicsMode class of this command is used """ # class constants commandName = 'NANOTUBE_LINE_MODE' featurename = "Nanotube Line Mode" # (This featurename is sometimes user-visible, # but is probably not useful. See comments in Line_Command # for more info and how to fix. [bruce 071227]) from utilities.constants import CL_UNUSED command_level = CL_UNUSED GraphicsMode_class = NanotubeLine_GM def setParams(self, params): assert len(params) == 5 self.mouseClickLimit, \ self.cntRise, \ self.callbackMethodForCursorTextString, \ self.callbackForSnapEnabled, \ self.callback_rubberbandLineDisplay = params def createStructure(self): """ Does nothing. @see: NanotubeLineMode_GM.leftUp @see: comment at the beginning of the class """ return pass # end
NanoCAD-master
cad/src/cnt/temporary_commands/NanotubeLineMode.py
NanoCAD-master
cad/src/cnt/temporary_commands/__init__.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ ExprsMeta.py -- one metaclass, to take care of whatever is best handled using a metaclass, and intended to be used for all or most classes in this module. @author: Bruce @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. === ####### need to insert improved text for the following, drafted 061025 in notesfile: ######@@@@@@ here it is, not quite done, but i might still edit it in the text file, and/or wikify it == Python provides several ways for class attributes to determine how instance attributes are computed. To summarize: the class attributes can be constants, functions, or other descriptors, with corresponding instance attribute accesses resulting in constants, bound methods, or fairly arbitrary behavior. We want to add a few specific ways of our own: - class attributes which are formulas in _self, for which instance.attr should be a read-only per-instance memoized invalidatable/recomputable value computed by the formula - class attributes which are like a "descriptor expression", but with the "descriptor" knowing the class and attr it was assigned to (which ordinary ones don't know): - for example, resulting in instance.attr acting like a dict of individually invalidatable/recomputable values, defined by a method or formula on the key, extensible as new keys are used, with the permitted keys either unlimited, fitting some type or pattern, or listed explicitly by a once-computable method or formula [###e (details unclear -- does this mean all exprs include details of what gets memoized, at what level inside??)] - specially-named methods, assigned to _prefix_attr rather than directly to attr, which nonetheless control what instance.attr does (similarly to one of the ways mentioned above), with subclasses able to override superclasses about attr even if they define its behavior by assigning to different class attributes (one to attr itself, one to _prefix1_attr, one to _prefix2_attr). (This way is most convenient when you want to express the behavior using Python code rather than as formulas.) We find a metaclass to be the simplest way of achieving certain key aspects of those desires: - Descriptor exprs might be shared among attrs or between classes -- they don't know their cls/attr location, and it's not even unique (meaning they'd be wrong to cache cls/attr info inside themselves, even if they knew it). A metaclass can wrap descriptors (or the like) with this location info, with the resulting wrapped exprs being unique (so they can be allowed to cache data which depends on this location info). Effectively, it can wrap things that follow our own descriptor protocol to produce things that follow Python's. - Overriding of attr assignments doesn't normally affect related attrs; if some class defines contradicting values for attr and _prefix1_attr and _prefix2_attr, all meant to control instance.attr in different ways, the defn to follow should be the one defined in the innermost class, but you can't easily tell which one that is. (If Python copies superclass dicts into subclass dicts, maybe you can't tell at all, absent metaclasses, except by something as klugy as comparing line numbers found inside function code objects and their classes.) - We could solve this just by recording the class and attr of each def, as we'll do to solve the prior problem... ### could we really use that info to solve this? should we? - But what we actually do is have the metaclass create something directly on the attr, which says how it's supposed to be defined in that class (and is a descriptor which causes that to actually happen in the right way). This scheme has the advantage of dispensing with any need for __getattr__ (I think). (Note, it could also do it by creating a special prefix attr saying which other prefix attr controls the def. Should it?? ####) The actual creation of the class/attr-specific descriptor for runtime use is best done lazily, on first use of that attr in an instance. This lets it more safely import code, more easily access inherited class attrs, etc... and lets most of the system be more similar to non-metaclass-based code. The metaclass just records enough info, and makes it active in the right places, to allow this to happen properly. ======= old text, not sure it's all obs/redundant now: Reasons we needed a metaclass, and some implementation subtleties: - If there are ways of defining how self.attr behaves using different class attributes (e.g. attr or _C_attr or _CV_attr), overriding by subclasses would not normally work as intended if subclasses tried to override different attrs than the ones providing the superclass behavior. (E.g., defining _C_attr in a subclass would not override a formula or constant assigned directly to attr in a superclass.) ExprsMeta solves this problem by detecting each class's contributions to the intended definition of attr (for any attr) from any class attributes related to attr (e.g. attr or _xxx_attr), and encoding these as descriptors on attr itself. (Those descriptors might later replace themselves when first used in a given class, but only with descriptors on the same attr.) - Some objects assigned to attr in a class don't have enough info to act well as descriptors, and/or might be shared inappropriately on multiple attrs in the same or different classes. (Formulas on _self, assigned to attr, can have both problems.) ExprsMeta replaces such objects with unshared, wrapped versions which know the attr they're assigned to. Note that it only does this in the class in which they are syntactically defined -- they might be used from either that class or a subclass of it, and if they replace themselves again when used, they should worry about that. Python probably copies refs to them into each class's __dict__, but these copies are all shared. This means they should not modify themselves in ways which depend on which subclass they're used from. For example, if a descriptor assigned by ExprsMeta makes use of other attributes besides its main definining attribute, those other attributes might be overridden independently of the main one, which means their values need to be looked for independently in each class the descriptor is used in. This means two things: 1. The descriptor needs to cache its knowledge about how to work in a specific class, in that class, not in itself (not even if it's already attached to that class, since it might be attached to both a class and its subclass). It should do this by creating a new descriptor (containing that class-specific knowledge) and assigning it only into one class. 2. In case I'm wrong about Python copying superclass __dict__ refs into subclass __dicts__, or in case this behavior changes, or in case Python does this copying lazily rather than at class-definition time, each class-specific descriptor should verify it's used from the correct class each time. If it wants to work correctly when that fails (rather than just assertfailing), it should act just like a non-class-specific descriptor and create a new class-specific copy assigned to the subclass it's used from. Note that the simplest scheme combines points 1 and 2 by making each of these descriptors the same -- it caches info for being used from the class it's initially assigned to, but always checks this and creates a subclass-specific descriptor (and delegates that use to it) if used from a subclass. All we lose by fully merging those points is the check on my beliefs about Python. Hopefully a simple flag can handle that by asserting (warning when false) that the copying into a subclass happens at most once. What ExprsMeta handles specifically: - formulas on _self assigned directly to attr (in a class) - _C_attr methods (or formulas??), making use of optional _TYPE_attr or _DEFAULT_attr declarations (#k can those decls be formulas??) - _CV_attr methods (or formulas??), making use of optional _CK_attr methods (or formulas??), and/or other sorts of decls as above - _options (abbrev for multiple _DEFAULT_), but not _args """ # == imports # from python library from idlelib.Delegator import Delegator # from modules in cad/src from utilities.constants import remove_prefix ##from env import seen_before from utilities.debug import print_compact_traceback, print_compact_stack # from this exprs package in cad/src from exprs.py_utils import printnim, printfyi from exprs.lvals import Lval, LvalDict2, call_but_discard_tracked_usage from exprs.Exprs import is_Expr from exprs.Exprs import is_pure_expr from exprs.Exprs import canon_expr from exprs.Exprs import is_Expr_pyinstance from exprs.Exprs import getattr_Expr from exprs.Exprs import constant_Expr from exprs.Exprs import expr_serno from exprs.Exprs import expr_is_Instance from exprs.Exprs import is_Expr_pyclass from exprs.__Symbols__ import _E_ATTR, _self # == # added 061201: as of 061204 not sure if still needed (guess: no), tho still active FAKE_ATTR = "<FAKE_ATTR>" # not a possible attr name, but a string in case used in __repr__ FAKE_CLSNAME = "<FAKE_CLSNAME>" class ClassAttrSpecific_NonDataDescriptor(object): """ Abstract class for descriptors which cache class- and attr- specific info (according to the scheme described in the ExprsMeta module's docstring). Actually, there's a pair of abstract classes, one each for Data and NonData descriptors. To make our implem of self.copy_for_subclass() correct in our subclasses (so they needn't override it), we encourage them to not redefine __init__, but to rely on our implem of __init__ which stores all its arguments in fixed attrs of self, namely clsname, attr, args, and kws, and then calls self._init1(). [self.cls itself is not yet known, but must be set before first use, by calling _ExprsMeta__set_cls.] TODO: rename _init1 to something more specific. """ __copycount = 0 cls = None clsname = attr = '<unset>' # probably never seen def __init__(self, clsname, attr, *args, **kws): # to simplify #e perhaps this got called from a subclass init method, which stored some additional info of its own, # but most subclasses can just let us store args/kws and use that, and not need to override copy_for_subclass. [#k] self.clsname = clsname #######@@@@@@ fix for this in CV_rule too ## self.cls = cls # assume this is the class we'll be assigned into (though we might be used from it or any subclass) self.attr = attr # assume this is the attr of that class we'll be assigned into self.args = args self.kws = kws ###e Q: If self (in subclass methods) needs to compute things which copy_for_subclass should copy # into a copy of self made for a subclass of self.cls, rather than recomputing on its own, # should they be stored by self into self.kws, # then detected in copy.kws by copy._init1? # (Or, kept in copy.kws, and used directly from there by copy's other methods)?? # Example: our formula-handling subclass might need to modify its arg val from the one it gets passed. # (Or it might turn out that's done before calling it, so this issue might not come up for that example.) self._init1() #e super init? def __repr__(self): #061205 moved this here from a subclass, and removed the worse ones in other subclasses return "<%s at %#x for %r in %r>" % (self.__class__.__name__, id(self), self.attr, self.clsname) def _init1(self): """ #doc [subclasses can override this] """ pass def _ExprsMeta__set_cls(self, cls): """ [private method for ExprsMeta to call when it knows the defining class] """ self.cls = cls if self.clsname == FAKE_CLSNAME: self.clsname = cls.__name__ else: assert self.clsname == cls.__name__ #k #e should we store only the class id and name, to avoid ref cycles? Not very important since classes are not freed too often. return def _ExprsMeta__set_attr(self, attr): # see class State_helper discussion for motivation """ [private method for ExprsMeta to call when it knows the defining attr] """ # 061201, not always called(?) or needed, experimental print "called _ExprsMeta__set_attr",self,attr ####k does it ever happen? if not, it's probably obs; even if so, might be unneeded [cmt 061204] # update: this probably never happens, since until 071107, it referenced # an undefined symbol FAKE_ATTRNAME (probably a typo) if self.attr == FAKE_ATTR: self.attr = attr else: assert self.attr == attr, "%r already has an attr, but another one %r is trying to be set in it" % (self, attr) return def check(self, cls2): ###e remove all calls of this when it works (need to optim) cls = self.cls assert cls is not None, "self.cls None in check, self.clsname = %r, self.attr = %r" % \ (self.clsname, self.attr) # need to call _ExprsMeta__set_cls before now assert self.clsname == cls.__name__, "self.clsname %r != cls.__name__ %r for self %r, cls %r" % \ (self.clsname, cls.__name__, self, cls) # make sure no one changed this since we last checked attr = self.attr assert cls.__dict__[attr] is self if cls2 is not None: #k can that ever fail?? assert issubclass(cls2, cls), "cls2 should be subclass of cls (or same class): %r subclass of %r" % (cls2, cls) return def __get__(self, obj, cls): """ [subclasses should NOT override this -- override get_for_our_cls instead] """ # WARNING: similar code to __set__ in a subclass self.check(cls) #e remove when works (need to optim) if obj is None: ## print_compact_stack("fyi, __get__ direct from class of attr %r in obj %r: " % (self.attr, self)) # Note: for what this is about, see long comment near printnim in FormulaScanner far below. [061101] # # Update: disabled print, since this now happens routinely in ObjAttr_StateRef # for getting a data_descriptor_Expr_descriptor [bruce 070815] # # Note: this print was also causing tracebacks in pychecker (see EricM email to cad list), # so it's lucky that we no longer need it. But it was legitimate, so that was a pychecker bug # which might bite us in the future. [bruce 070817] return self assert cls is not None, "I don't know if this ever happens, or what it means if it does, or how to handle it" #k in py docs #e remove when works (need to optim) if cls is not self.cls: copy = self.copy_for_subclass(cls) # e.g. from 'InstanceOrExpr' to 'Rect' attr = self.attr ## cls.__dict__[attr] = copy # oops, this doesn't work: TypeError: object does not support item assignment # turns out it's a dictproxy object (created on the fly, like unbound methods are), as (I guess) is any new style # class's __dict__. Guess: this is so you can't violate a descriptor's ability to control what set/del does. # You can still modify the actual class dict using setattr -- if the descriptor permits. # So, what to do? Can I get my descriptor to permit this? Depends which kind it is! *This* class can't handle it # (no __set__ method), but which one do I actually use? (And for that matter, would they both even work re my # assumptions about access order when I wrote them? #####k) # Hmm -- CV_rule uses a nondata desc (no __set__, problem), but C_rule uses a data desc. Why is that? # C_rule comment says it has to be a data descriptor. CV_rule likes to be overridden by an instance it makes, # so likes to be non-data (though it does have code to not require this). Conclusion: simplest fix is to # use only the subclass that has __set__, and make that __set__ sometimes work, and change the above code to use it. # I will try this for now [061103 830p], then look for a better fix someday, e.g. not needing this copy at all # (I forget why I needed it). ... wait, the suggestion fails -- it would get into __set__, but then what could that do # to actually change the class dict? It could store something in the instance but not in the class!! # Does that mean it's reversed -- without __set__ I'm ok since I can use setattr? If so, I can fix this by # changing C_rule to not store into same attr in instance.__dict__ so it can use a non-data descriptor. # But WAIT AGAIN, the descriptor will gate access to the instance, not necessarily to the class -- we'll have to try it. setattr( cls, attr, copy) # this might fail in the DataDescriptor subclass used in C_rule, but I don't know. ###k if 0: print "setattr( cls, attr, copy) worked for supporting %r from %r for attr %r in %r" % \ (cls , self.cls, attr, self) ####@@@@ self is relevant so we see which kind of descriptor it worked for # btw it also might "succeed but not have the desired effect". What's the predicted bug if it silently has no effect? ##k return copy.__get__(obj, cls) return self.get_for_our_cls(obj) # we have no __set__ or __delete__ methods, since we need to be a non-data descriptor. def get_for_our_cls(self, obj): """ [Subclass should implement] do the __get__ for our class (initializing our class-specific info if necessary) """ return None def copy_for_subclass(self, cls): if 0: printfyi("copy_for_subclass from %r to %r" % (self.cls.__name__, cls.__name__))###@@@ copy = self.__class__(cls.__name__, self.attr, *self.args, **self.kws) copy._ExprsMeta__set_cls(cls) copy.__copycount = self.__copycount + 1 #k needed anymore?? ## if copy.__copycount > 1: ## if not seen_before("ClassAttrSpecific_{Non,}DataDescriptor copied again"): ## print "once-per-session developer warning: this copy got copied again:", \ ## self, "for class %s" % self.cls.__name__, "copied as", copy, "for class %s" % cls.__name__ # Note: this may be normal for Rect -> Spacer, and it's probably not an error at all. # If this keeps seeming true, remove the message. # (For that matter, I could probably remove the copying behavior entirely. ##k) [061205 comment] # Update 070323: it's happened for more cases of inheritance chains, all legit, e.g. # for '_delegate' in 'DraggablyBoxed' and for 'per_frame_state' in '_cmd_DrawOnSurface_BG', # and AFAIK it's ok when this happens, so I'm removing the warning. return copy pass # end of class ClassAttrSpecific_NonDataDescriptor class ClassAttrSpecific_DataDescriptor(ClassAttrSpecific_NonDataDescriptor): """ Like our superclass, but has __set__ and __delete__ methods so as to be a data descriptor. (Defining either method would be enough to make Python treat us as a data descriptor, but we'd rather complain equally about either one running, so we define both.) Our implems of __set__ and __delete__ just assert 0; subclasses can override them (with other errors or to make them work), but don't need to. WARNING: if subclasses did intend to override them, most likely they'd need overhead code like our superclass has in __get__, so in practice such overriding is not yet supported -- to support it, we'd want to add that sort of code to this class (perhaps sharing common code with our superclass's __get__). [FYI about when to use a data or non-data descriptor: - If a Python descriptor (of any kind, not just the kind created by one of these classes) wants to store info of its own in instance.__dict__[attr], it has to be a data descriptor, since otherwise that info would be retrieved directly by getattr, rather than going through the descriptor. (It might need to intercept that (for example) either to alter the data, or record the fact of its retrieval.) - If it doesn't want to store anything there, then it can be either data or non-data. (Of course it has to be "data" if it wants to support setattr or delattr.) - If it wants to store something there and does want getattr to retrieve it directly (as an optim), then it ought to be a non-data descriptor, asusming it doesn't need to support set or del. ] """ def __set__(self, obj, val): """ [subclasses should NOT override this -- override set_for_our_cls instead] """ # WARNING: similar code to __get__ in our superclass if obj is None: print_compact_stack("fyi, __set__ direct from class of attr %r in obj %r: " % (self.attr, self)) ####@@@@ ever happens? # what this is about -- see long comment near printnim in FormulaScanner far below [061101] return cls = obj.__class__ #### TOTAL GUESS, but otherwise I have to panic since cls is not passed in [061117] self.check(cls) #e remove when works (need to optim) ## assert cls is not None, "I don't know if this ever happens, or what it means if it does, or how to handle it" #k in py docs ## #e remove when works (need to optim) if cls is not self.cls: copy = self.copy_for_subclass(cls) # e.g. from 'InstanceOrExpr' to 'Rect' attr = self.attr setattr( cls, attr, copy) # this might fail in the DataDescriptor subclass used in C_rule, but I don't know. ###k if 1: print "setattr( cls, attr, copy) worked for supporting __set__ %r from %r for attr %r in %r" % \ (cls , self.cls, attr, self) ####@@@@ self is relevant so we see which kind of descriptor it worked for # btw it also might "succeed but not have the desired effect". What's the predicted bug if it silently has no effect? ##k return copy.__set__(obj, val) return self.set_for_our_cls(obj, val) def set_for_our_cls(self, obj, val): """ [Subclass should implement -- do the __set__ for our class (initializing our class-specific info if necessary)] """ assert 0, "subclass %r of %r should implement set_for_our_cls" % (self.__class__, self) def __delete__(self, *args): # note: descriptor protocol wants __delete__, not __del__! print "note: ClassAttrSpecific_DataDescriptor.__delete__ is about to assert 0" assert 0, "__delete__ is not yet supported in this abstract class" pass # end of class ClassAttrSpecific_DataDescriptor # == class C_rule(ClassAttrSpecific_DataDescriptor): """ One of these should be stored on attr by ExprsMeta when it finds a _C_attr compute method, formula (if supported #k), or constant, or when it finds a formula directly on attr. """ # implem note: this class has to be a data descriptor, because it wants to store info of its own in instance.__dict__[attr], # without that info being retrieved as the value of instance.attr. If it would be less lazy (and probably less efficient too) # and store that info somewhere else, it wouldn't matter whether it was a data or non-data descriptor. def get_for_our_cls(self, instance): # make sure cls-specific info is present -- we might have some, in the form of _TYPE_ decls around compute rule?? not sure. ##e # (none for now) # now find instance-specific info -- # namely an Lval object for instance.attr, which we store in instance.__dict__[attr] # (though in theory, we could store it anywhere, as long as we'd find a # different one for each instance, and delete it when instance got deleted) attr = self.attr try: lval = instance.__dict__[attr] except KeyError: # (this happens once per attr per instance) # Make a compute method for instance.attr, letting instance have first dibs (in case it's customized this attr), # otherwise using self's default method. # NOTE: this would not work for constant formulas like _DEFAULT_color = gray, except for the call of canon_expr (to be added) # on all _DEFAULT_attr values -- otherwise instance.attr would just grab gray, never going through this code which # looks for an override. In this way alone, _DEFAULT_attr is more powerful than an ordinary (private) attr. # Beware -- this may seem to mask the bug in which private attrs can also be overridden by customizing option values. # (As of 061101 that bug is fixed, except it was never tested for either before or after the fix.) compute_method = self.compute_method_from_customized_instance(instance) ## if compute_method: ## printnim("custom override should only work for _DEFAULT_! not private attr formulas")#but we don't know prefix here ## #k when we do know prefix here, should we decide _DEFAULT_ is special here, or pass to above method to ask instance?? if not compute_method: compute_method = self.make_compute_method_for_instance(instance) # make a new Lval object from the compute_method lval = instance.__dict__[attr] = Lval(compute_method) return lval.get_value() # this does usage tracking, validation-checking, recompute if needed # Notes: # [from when this code was in class _C_rule used by InvalidatableAttrsMixin in lvals.py; probably still applicable now] # - There's a reference cycle between compute_method and instance, which is a memory leak. # This could be fixed by using a special Lval (stored in self, not instance, but with data stored in instance) # which we'd pass instance to on each use. (Or maybe a good solution is a C-coded metaclass, for making instance?) # - The __set__ in our superclass detects the error of the compute method setting the attr itself. Good enough for now. # Someday, if we use a special Lval object that is passed self and enough into to notice that itself, # then we could permit compute objects to do that, if desired. But the motivation to permit that is low. # - There is no provision for direct access to the Lval object (e.g. to directly call its .set_formula method). # We could add one if needed, but I don't know the best way. Maybe find this property (self) and use a get_lval method, # which is passed the instance? Or, setattr(instance, '_lval_' + attr, lval). def compute_method_from_customized_instance(self, instance): """ See if we permit instance to customize self.attr's formula, and if instance has done so; if so, return a compute method from that; else return None. """ permit_override = self.kws.get('permit_override', False) #e do in __init__ with pop, so we can check for unknown options? if not permit_override: return None try: instance.custom_compute_method # defined e.g. by InstanceOrExpr except AttributeError: return None printfyi("DEPRECATED: compute_method_from_customized_instance (since _DEFAULT_ is); attr %r" % (self.attr,)) ##k 061103 return instance.custom_compute_method(self.attr) # a method or None def make_compute_method_for_instance(self, instance): """ #doc; doesn't consider per-instance customized compute methods. """ assert 0, "subclass should implement this" pass # end of class C_rule class C_rule_for_method(C_rule): def _init1(self): ## () = self.args is a syntax error! assert len(self.args) == 0 #e could/should we assert no unknown kws?? def make_compute_method_for_instance(self, instance): return getattr(instance, '_C_' + self.attr) # kluge, slightly, but it's the simplest and most efficient way ###e maybe a better way is to grab the function from cls.__dict__ and call its __get__? pass class C_rule_for_formula(C_rule): def _init1(self): (self.formula,) = self.args #e could/should we assert no unknown kws?? def make_compute_method_for_instance(self, instance): return self.formula._e_compute_method(instance, '$' + self.attr) # index arg is a guess, 061110 pass def choose_C_rule_for_val(clsname, attr, val, **kws): """ return a new object made from the correct class out of C_rule_for_method or C_rule_for_formula or a val-specified wrapper, depending on val """ if is_pure_expr(val): # assume val is a formula on _self # first scan it for subformulas that need replacement, and return replaced version, also recording info in scanner scanner = kws.pop('formula_scanner', None) if scanner: ## val0 = val # debug msg only val = scanner.scan(val, attr) #e more args? ## if val0 is not val: ## print "scanner replaces %r by %r" % (val0, val) ## else: ## print "scanner leaves unchanged %r" % (val0,) wrapper = getattr(val, '_e_wants_this_descriptor_wrapper', None) # new feature 061203; 061204 moved after scanner as bugfix if wrapper: assert issubclass(wrapper, ClassAttrSpecific_NonDataDescriptor) return wrapper(clsname, attr, val, **kws) flag = getattr(val, '_e_is_lval_formula', False) assert not flag # 061203 if flag: # new feature 061117, for State macro and the like [note 061203: that State macro is obs, new one doesn't use this] # it's a formula for an lval, rather than for a val! print "should not happen yet: val = %r, flag = %r" % (val,flag) # an expr or so?? return C_rule_for_lval_formula(clsname, attr, val, **kws) return C_rule_for_formula(clsname, attr, val, **kws) elif is_Expr(val): print("Instance case needs review in choose_C_rule_for_val") # does this ever happen? in theory, it can... (depending on needs_wrap_by_ExprsMeta) return val ###k not sure caller can take this #e support constant val?? not for now. else: return C_rule_for_method(clsname, attr, **kws) ###KLUGE (should change): they get val as a bound method directly from cls, knowing it came from _C_attr pass class C_rule_for_lval_formula(ClassAttrSpecific_DataDescriptor): #061117 - review all comments before done! ###OBS as of 061203 """ #doc; used for obs-061117 version of State macro, not sure it'll ever be used as of newer 061203 version of it, maybe for its #e-refexpr """ ###nim: type-formula def _init1(self): (self.lval_formula,) = self.args assert 0, "no one should be calling this yet...." #####@@@@@@ def make_lval_for_instance(self, instance): """ return an lval (found or made by our formula) for this instance """ print "make_lval_for_instance",(self, instance)#####@@@@@ #e not sure what to do if this formula turns out to be time-dependent... what should be invalidated if it does?? #### # for now, just be safe and discard tracked usage, tho it might be better to replace the lval with a new one if it invals.#e index = '$' + self.attr # guess, 061117 lval = eval_and_discard_tracked_usage( self.lval_formula, instance, index) return lval def get_for_our_cls(self, instance): print "get_for_our_cls",(self, self.attr, instance, )#####@@@@@ attr = self.attr try: lval = instance.__dict__[attr] except KeyError: # (this happens at most once per attr per instance, iff the attr is gotten-from before it's ever been set, in this instance) lval = instance.__dict__[attr] = self.make_lval_for_instance(instance) if not lval.can_get_value(): ###e should optim by doing this only on exception from get_value # note: this has to be checked whether we found or made the lval # preventable by prior set (in this instance or a prior one), or by lval having an initval_compute_method raise AttributeError, "attr %r hasn't been set yet in class %r" % (attr, self.cls) ####k or LvalError_ValueIsUnset??? I think not... when less tired, explain why. [061117 late] # old code, whose index might be needed in state_Expr ##k: ## index = '$$' + self.attr # guess, 061117 ## initval = eval_and_discard_tracked_usage(initval_expr, instance, index) ## # note: we need to discard tracked usage from initval_computer ## # (which is not an error -- initval_expr is allowed to be time-dependent, ## # but we don't want to recompute anything when it changes) ## # note: this is not evaluated until the moment it's needed; that's important, since ## # (1) it's legal for this to be an error to eval at times before when we need it; ## # (2) its value might change before we need it, and it's defined to give us the value at the time of first need. ## lval.set_constant_value(initval) # needed so .get_value() will work; .get_value() is still needed for its usage-tracking return lval.get_value() # this does usage tracking, validation-checking, recompute if needed def set_for_our_cls(self, instance, val): print "set_for_our_cls",(self, self.attr, instance, val)#####@@@@@ attr = self.attr try: lval = instance.__dict__[attr] except KeyError: # (this happens at most once per attr per instance, iff the attr is set before it's ever been gotten-from, in this instance) lval = instance.__dict__[attr] = self.make_lval_for_instance(instance) # note: that lval's initval_expr is never evaluated, if it's not needed since we set it before getting from it; # (that's not just an optim -- it's legal for initval_expr to be an error to eval in cases where we won't eval it) # (note that just because set-before-get happened in this instance doesn't mean it happened overall -- # otoh we might discard older unused initval exprs # [those points are related, but i am a bit too tired to explain (or see exactly) how]) lval.set_constant_value(val) ###e probably set_constant_value should be renamed set_value, to fit with StateRefInterface [070312] return ## def __repr__(self): ## return "<%s at %#x for %r>" % (self.__class__.__name__, id(self), self.attr)#061117 changed self.lval_formula -> self.attr pass # end of class C_rule_for_lval_formula # # historical note [061117 841p]: see cvs rev 1.42 for a version of this class # which misguidely handled initval_expr itself, and a comment explaining why that was wrong. def eval_and_discard_tracked_usage(formula, instance, index): #061117 #e refile into Exprs? #e see also other calls of call_but_discard_tracked_usage """ Evaluate a formula (for an instance, at an index) which is allowed to be time-dependent, but for which we don't want to recompute anything when its value changes. This works by discarding tracked usage from the eval. Usage advice: If ordinary eval is called instead of this (for formulas whose value changes can occur but should not trigger recomputes of whatever our caller is computing), changes to this formula's value would incorrectly invalidate whatever our caller happens to be recomputing, which might be a bug, or more likely would just be a big performance hit (causing needless recomputes of arbitrarily lots of stuff). """ #e could be more efficient, but doesn't matter too much -- so far only used when initializing Instance objects computer = formula._e_compute_method(instance, index) return call_but_discard_tracked_usage( computer) class data_descriptor_Expr_descriptor(ClassAttrSpecific_DataDescriptor): """ #doc @note: used only in class State(data_descriptor_Expr) """ def _init1(self): (self.expr,) = self.args self.expr._e_set_descriptor(self) # whether it stores anything is up to the specific subclass def get_for_our_cls(self, instance): # print "get_for_our_cls",(self, self.attr, instance, ) assert self.attr != FAKE_ATTR return self.expr._e_get_for_our_cls(self, instance) #e or pass self.attr rather than self? def set_for_our_cls(self, instance, val): # print "set_for_our_cls",(self, self.attr, instance, val) assert self.attr != FAKE_ATTR return self.expr._e_set_for_our_cls(self, instance, val) #e or pass self.attr rather than self? ## def __repr__(self): ## return "<%s at %#x for %r>" % (self.__class__.__name__, id(self), self.attr) def _StateRef__your_attr_in_obj_ref( self, instance): #bruce 070815 return self.expr._e_StateRef__your_attr_in_obj_ref( self, instance) pass # end of class data_descriptor_Expr_descriptor # == class CV_rule(ClassAttrSpecific_NonDataDescriptor): """ One of these should be stored by ExprsMeta when it finds a _CV_attr compute method, formula (if supported #k), or constant (if supported #k). """ prefixV = '_CV_' prefixK = '_CK_' def get_for_our_cls(self, instance): attr = self.attr # Make sure cls-specific info is present -- we might have some, in the form of _TYPE_ decls around compute rule?? not sure. ##e # In principle, we certainly have some in the form of the optional _CK_ compute method... # but our current code finds it easier to make this instance-specific and just grab a bound method for each instance. if 0: # if it's ever class-specific we might do something like this: try: compute_methodK = self.compute_methodK except AttributeError: compute_methodK = getattr(self.cls, self.prefixK + attr, None) #e process it if it's a formula or constant sequence self.compute_methodK = compute_methodK # Now find instance-specific info -- # which is a RecomputableDict object for our attr in instance, and our bound V and K methods. # (Formulas or constants for them are not yet supported. ###e nim) try: rdobj = instance.__dict__[attr] print "warning: rdobj was not found directly, but it should have been, since this is a non-data descriptor", self #e more? except KeyError: # make a new object from the compute_methods (happens once per attr per instance) rdobj = instance.__dict__[attr] = self.make_rdobj_for_instance(instance) return rdobj # this object is exactly what instance.attr retrieves (directly, from now on, or warning above gets printed) def make_rdobj_for_instance(self, instance): #e refile into a subclass?? (so some other subclass can use formulas) #e actually, splitting rhs types into subclasses would not work, # since main subclass can change whether it assigns formula or function to _CV_attr!!! # ditto for C_rule -- say so there... wait, i might be wrong for C_rule and for _CV_ here, # since self is remade for each one, but not for _CK_ (since indeply overridden) if that # needn't match _CV_ in type. hmm. #####@@@@@ attr = self.attr compute_methodV = getattr(instance, self.prefixV + attr) # should always work ## compute_methodV = bound_compute_method_to_callable( compute_methodV, ## formula_symbols = (_self, _i), ###IMPLEM _i ## constants = True ) ## # also permit formulas in _self and _i, or constants (either will be converted to a callable) assert callable(compute_methodV) compute_methodK = getattr(instance, self.prefixK + attr, None) # optional method or [nim] formula or constant, or None (None can mean missing, since legal constant values are sequences) if compute_methodK is not None: ## compute_methodK = bound_compute_method_to_callable( compute_methodK, ## formula_symbols = (_self,), ## constants = True ) assert callable(compute_methodK) obj = RecomputableDict(compute_methodV, compute_methodK) return obj # Note: we have no __set__ method, so in theory (since Python will recognize us as a non-data descriptor), # once we've stored obj in instance.__dict__ above, it will be gotten directly # without going through __get__. We print a warning above if that fails. # Note: similar comments about memory leaks apply, as for C_rule. pass # end of class CV_rule class CV_rule_for_val(CV_rule):pass ####k guess off top of head, much later than the code was written [061103] def choose_CV_rule_for_val(clsname, attr, val): """ return an appropriate CV_rule object, depending on val """ if is_formula(val): assert 0, "formulas on _CV_attr are not yet supported" # when they are, we'll need _self and _i both passed to _e_compute_method else: # constants are not supported either, for now # so val is a python compute method (as a function) ###KLUGE: CV_rule gets val as a bound method, like C_rule does return CV_rule_for_val(clsname, attr) pass # == # prefix_X_ routines process attr0, val on clsname, where attr was prefix _X_ plus attr0, and return val0 # where val0 can be directly assigned to attr0 in cls (not yet known); nothing else from defining cls should be assigned to it. def prefix_C_(clsname, attr0, val, **kws): ###k **kws is suspicious but needed at the moment - kluge?? [061101] val0 = choose_C_rule_for_val(clsname, attr0, val, **kws) return val0 def prefix_CV_(clsname, attr0, val, **kws): val0 = choose_CV_rule_for_val(clsname, attr0, val) ###k even worse, needed in call but not ok here -- worse kluge?? [061101] return val0 def prefix_nothing(clsname, attr0, val, **kws): # assume we're only called for a formula -- but [as of 061117] it might be a formula for an lval, rather than for a val! ## assert is_formula(val) permit_override = kws.get('permit_override', False) # it's a kluge to know about this here if not permit_override and not needs_wrap_by_ExprsMeta(val): ## print "why is this val not special? (in clsname %r, attr0 %r) val = %r" % (clsname, attr0, val) printnim("not needs_wrap_by_ExprsMeta(val)") #kluge 061030: i changed this to a warning, then to printnim since common, due to its effect on ConstantExpr(10), # tho the proper fix is different -- entirely change how _DEFAULT_ works. (see notesfile). # But on 061101 we fixed _DEFAULT_ differently so this is still an issue -- it's legit to turn formulas # on _DEFAULT_attr into e.g. ConstantExpr(10) which doesn't contain _self. # Guess: in that case it implicitly DOES contain it! kluge for now: ignore test when permitting override. ###@@@ val0 = choose_C_rule_for_val(clsname, attr0, val, **kws) return val0 def prefix_DEFAULT_(clsname, attr0, val, **kws): """ #doc WARNING: caller has to also know something about _DEFAULT_, since it declares attr0 as an option """ printfyi("_DEFAULT_ is deprecated and may soon be unsupported") #070121 if 'kluge061103': assert val is canon_expr(val) else: val = canon_expr(val) # needed even for constant val, so instance rules will detect overrides in those instances ##e could optim somehow, for instances of exprs that didn't do an override for attr0 assert is_formula(val) # make sure old code would now always do the following, as we do for now: ## did this 061101 -- printnim("here is one place we could put in code to disallow override except for _DEFAULT_") ## return prefix_nothing(clsname, attr0, val, permit_override = True, **kws) ###k GUESS this is bad syntax kws['permit_override'] = True return prefix_nothing(clsname, attr0, val, **kws) # old code before 061029 837p: ## if not hasattr(val, '_e_compute_method'): ###e improve condition ## # if val is not a formula or any sort of expr, it can just be a constant. e.g. _DEFAULT_color = gray ## # what if it's a method?? that issue is ignored for now. (bug symptom: bound method might show up as the value. not sure.) ## # what if it's a "constant classname" for an expr? that's also ignored. that won't be in this condition... ## # (the bug symptom for that would be a complaint that it's not special (since it doesn't have _self).) ## # Q: if it's a formula or expr, not free in _self, should we just let that expr itself be the value?? ## # This might make sense... it ought to mean, the value doesn't depend on self (unless it's a bound method, also ok maybe). ## #####@@@@@ ## return val ## return prefix_nothing(clsname, attr0, val) prefix_map = {'':prefix_nothing, '_C_':prefix_C_, '_DEFAULT_': prefix_DEFAULT_, '_CV_':prefix_CV_, } #e this could be more modular, less full of duplicated prefix constants and glue code def attr_prefix(attr): # needn't be fast for prefix in prefix_map: #.keys() if prefix and attr.startswith(prefix): return prefix return '' def needs_wrap_by_ExprsMeta(val, msg_info = ''): # renamed from val_is_special, and revised, 061203 """ #doc val needs_wrap_by_ExprsMeta if it's an Expr pyinstance (for now) [no longer has to contain _self as a free variable] """ if not is_Expr_pyinstance(val): return False ## if not val._e_free_in('_self'):###WRONG I think, re State... changed now ## if msg_info: ## msg_info = " (%r)" % (msg_info,) ## print "weird val%s: an Expr that is not free in _self" % msg_info, val ## return True ## was False until 061203 1009p # and what it printed for was: ##weird val (('open_icon', 'ToggleShow')): an Expr that is not free in _self <Overlay#3945(a)> ##weird val (('closed_icon', 'ToggleShow')): an Expr that is not free in _self <Overlay#3952(a)> ##weird val (('openclose', 'ToggleShow')): an Expr that is not free in _self <Highlightable#3959(a)> ## ##weird val (('var', 'toggler')): an Expr that is not free in _self <State#6617: (<constant_Expr#6615: <type 'int'>>, <constant_Expr#6616: 0>)> ##weird val (('_value', 'toggler')): an Expr that is not free in _self <Highlightable#6647(a)> if val._e_is_instance: #061203 print "POSSIBLE BUG: val._e_is_instance true, for val being wrapped as Expr by ExprsMeta: %r" % (val,)#k ever happens?? return True ## return is_Expr_pyinstance(val) and val._e_free_in('_self') # 061201 Q: are there any implicit ways of containing _self? A: not presently. But note that in sequential class assignments # like x = Arg(), y = x + 1, y contains _self since Arg() does. We depend on that in the current code. # THIS WILL BE AN ISSUE FOR THINGS LIKE PROPERTY EXPRS, and I wonder if it even has caused some bugs I've seen and # wondered about? I vaguely recall one of those "should have been processed by ExprsMeta" prints which I didn't understand. ###k # The actual text is "this formula needed wrapping by ExprsMeta to become a compute rule" btw. # ## outtake: and val.has_args [now would be val._e_has_args] ## outtake: hasattr(val, '_e_compute_method') # this was also true for classes ##e 061101: we'll probably call val to ask it in a fancier way... not sure... Instance/Arg/Option might not need this # if they *turn into* a _self expr! See other comments with this date [i hope they have it anyway] is_formula = is_Expr #####e review these -- a lot of them need more cases anyway def is_attr_equals_self_attr_assignment(attr, val, classname = "?"): #070324 split out this predicate """ is the assignment attr = val of the exact form attr = _self.attr (for the same attr, ie recursive)? """ if isinstance(val, getattr_Expr) \ and val._e_args[0] is _self \ and isinstance( val._e_args[1], constant_Expr) \ and val._e_args[1]._e_constant_value == attr: assert len(val._e_args) == 2, \ "in class %s: dflt arg is not allowed in attr = getattr_Expr(_self, attr, dflt) (attr = %r)" % (classname, attr) return True return False # == class ExprsMeta(type): # follows 'MyMeta' metaclass example from http://starship.python.net/crew/mwh/hacks/oop-after-python22-1.txt def __new__(cls, name, bases, ns): # Notes: # - this code runs once per class, so it needn't be fast. # - cls is NOT the class object being defined -- that doesn't exist yet, since it's our job to create it and return it! # (It's the class ExprsMeta.) # - But we know which class is being defined, since we have its name in the argument <name>. data_for_attr = {} processed_vals = [] orig_ns_keys = ns.keys() # only used in exception text, for debugging # handle _options [deprecated since 061101] by turning it into equivalent _DEFAULT_ decls _options = ns.pop('_options', None) if _options is not None: print "_options (defined in class %s) is deprecated, since a later formula rhs won't see attr in namespace" % name assert type(_options) is type({}) for optname, optval in _options.items(): # _DEFAULT_optname = optval attr = '_DEFAULT_' + optname assert not ns.has_key(attr), \ "error: can't define %r both as %r and inside _options in the same class %r (since ExprsMeta is its metaclass); ns contained %r" % \ ( optname, attr, name, orig_ns_keys ) ns[attr] = optval # no need to check for ns[optname] here -- this will be caught below -- but the error message will be misleading # since it will pretend you defined it using _DEFAULT_; so we'll catch that case here, at least # (though this doesn't catch a conflict with some other way of defining optname; that'll still have misleading error # msg below). assert not ns.has_key(optname), \ "error: can't define %r directly and inside _options in the same class %r (since ExprsMeta is its metaclass); ns contained %r" % \ ( optname, name, orig_ns_keys ) del attr continue del optname, optval del _options # Remove "attr = _self.attr" entirely, before any other ns processing. [070324] # (This has to be done here, to permit _C_attr to coexist with that form.) # (I ran into this for a0 and _C_a0 in SimpleColumn, 070321, and in one or two other places since then.) for attr, val in ns.items(): prefix = attr_prefix(attr) if not prefix: if is_attr_equals_self_attr_assignment(attr, val): del ns[attr] continue # look for special vals, or vals assigned to special prefixes, in the new class object's original namespace # (since we will modify these in the namespace we'll actually use to create it) for attr, val in ns.iteritems(): # [070210 removed "draw decorators" (autowrap of draw function by _e_decorate_draw), # introduced 070104 but still nim, since it seems simpler and good enough # just to filter all kid-draw-calls thru a new method IorE.drawkid(kid). # (last here in cvs rev 1.66)] # The desired transform is something like # If attr has a special prefix, or val has a special value, run attr-prefix-specific code # for defining what value to actually store on attr-without-its-prefix. Error if we are told # to store more than one value on attr. #obs?: # which might create new items in this namespace (either replacing ns[attr], # or adding or wrapping ns[f(attr)] for f(attr) being attr without its prefix). # (If more than one object here wants to control the same descriptor, # complain for now; later we might run them in a deterministic order somehow.) prefix = attr_prefix(attr) if prefix: attr0 = remove_prefix(attr, prefix) if ns.has_key(attr0): # assert not is_attr_equals_self_attr_assignment(attr0, ns[attr0]) # since already removed earlier # remove when works assert 0, \ "error: can't define both %r and %r in the same class %r (since ExprsMeta is its metaclass); ns contained %r" % \ ( attr0, attr, name, orig_ns_keys ) #e change that to a less harmless warning? # note: it's not redundant with the similar assert below, except when *both* prefix and needs_wrap_by_ExprsMeta(val). # note: ns contains just the symbols defined in class's scope in the source code, plus __doc__ and __module__. else: attr0 = attr if hasattr(val, '_ExprsMeta__set_attr'): # note 061203: maybe not needed after all, tho not harmful, might help catch errors ### PROBLEM: true for symbolic expr val. # POSSIBLE SOLUTION: exclude _[A-Z] attrnames, not _[a-z]. (Hmm: _S_ATTR_??) # DONE INSTEAD [061203]: exclude any attr which might be name-mangled (starts _ but not __, contains __). #k also check val is a pyinstance, not pyclass? no need for now. # 061201 #e should we do this after prefix processing, instead? doesn't matter for now, not mixed with prefixes or needs_wrap_by_ExprsMeta. ##k but make sure these vals work with formula scanning for _self.attr replacement! #####IMPLEM val._ExprsMeta__set_attr(attr) #e could set clsname too, or pass it to this same method, if needed if prefix or needs_wrap_by_ExprsMeta(val, msg_info = (attr, name)): ok = True if not prefix and attr.startswith('_'): # note: this scheme doesn't yet handle special vals on "helper prefixes" such as the following: for helper_prefix in ('_CK_', '_TYPE_'): ## assert not attr.startswith(helper_prefix), "special val not yet supported for %r: %r" % (attr, val) if attr.startswith(helper_prefix): print "WARNING: special val not yet supported for %r: %r" % (attr, val) # this one we need to support: # _DEFAULT_height = _self.width [now it's in prefix_map] # this one is a bug in my condition for detecting a formula: # _TYPE_thing = <class 'exprs.widget2d.Widget2D'> ok = False break continue ## if prefix == '_DEFAULT_': ## printnim("_DEFAULT_ needs to be handled differently before it will let named options override it")###@@@ ## # _DEFAULT_ needs to declare attr0 as an option, ie let it be overridden by named options ## ### how we'll do this: leave it sitting there in the namespace, DON'T COPY IT TO ATTR (that's WRONG), ## # instead make the DEFAULT thing a rule of its own, but also do the decl ## # and also set up a rule on attr which grabs it from options and DEFAULT in the proper way. if ok: lis = data_for_attr.setdefault(attr0, []) lis.append((prefix, val)) pass continue del attr, val # extract from each lis its sole (prefix, val), element (could be removed if we cleaned up code to not need lis at all), # and prepare those for sorting by expr_serno(val) # [needed so we process val1 before val2 if val1 is included in val2 -- assumed by FormulaScanner] newitems = [] for attr0, lis in data_for_attr.iteritems(): assert len(lis) == 1, "error: can't define %r and %r in the same class %r (when ExprsMeta is its metaclass); ns contained %r" % \ ( lis[0][0] + attr0, lis[1][0] + attr0, name, orig_ns_keys ) #e change that to a less harmful warning? prefix, val = lis[0] if 'kluge061103': # we have to make sure canon_expr happens before sorting, not in the processor after the sort, # or the sort is in the wrong order: if prefix == '_DEFAULT_': printnim("should de-kluge061103: val = canon_expr(val) for _DEFAULT_ before sorting") val = canon_expr(val) newitems.append( (expr_serno(val), prefix, attr0, val) ) del prefix, val, attr0, lis del data_for_attr # sort vals by their expr_serno [motivation [IIRC, 061201 ##k]: if expr1 contains expr2, make sure expr1 comes first] # (I don't think we have to give properties (like State_helper) a serno -- canon_expr will make an expr wrapper which gets one. # What we might need to do is make them act symbolic re getattr... before they get processed at all. # Hmm, how does that work for whatever Arg turns into?? 061201 Q # A: it turns into an expr; then that gets turned into a descriptor by our prefix-map, # but as an expr, it's easily extendible into other exprs, including by getattr, when used during the class def. # Can a descriptor work like that? ONLY IF IT STARTS ALL ITS OWN ATTRNAMES BY _e_ or so!!!! Hmm, do I want that? # It would end up simplifying things... maybe it would already be an expr with no wrapping, unlike a plain property.... # OTOH besides the work, it makes these objects bugprone to handle, since they don't complain about missing attrs. # So what about the old way -- let them be exprs when created, maybe even symbolic ones (perhaps unlike Arg/Option), # but not descriptors yet, and turn them into descriptors in this scanner. # But maybe in a simpler way than we do now? Or maybe have a kind of expr that is easy to make into a descriptor -- # maybe it's enough to set a flag in it to tell it "don't be symbolic anymore". Is doing that dynamically ok, # which means, once the class it's in is defined, are you done with that way of using it? Guess: yes. If so, # this would increase safety. But it still means writing the descriptor-content-methods with all-_e_ attrs, # even if the descriptors themselves are separate objects. Or just using current system, with DescriptorForState, like C_rule. ####) newitems.sort() ## print "newitems for class %s:" % name, newitems # this can print a lot, since single Expr vals can have long reprs ## if 'debugging' 'kluge061103': ## print "newitems for class %s:" % name ## for junk, prefix, attr0, val in newitems: ## print prefix, attr0, expr_serno(val), val.__class__ # process the vals assigned to certain attrs, and assign them to the correct attrs even if they were prefixed scanner = FormulaScanner( debug_name = name) #070321 added debug_name # this processes formulas by fixing them up where their source refers directly to an attr # defined by another (earlier) formula in the same class, or (#nim, maybe) in a superclass (by supername.attr). # It replaces a direct ref to attr (which it sees as a ref to its assigned formula value, in unprocessed form, # since python eval turns it into that before we see it) with the formula _self.attr (which can also be used directly). # Maybe it will replace supername.attr as described in a comment inside FormulaScanner. #e for junk, prefix, attr0, val in newitems: del junk # prefix might be anything in prefix_map (including ''), and should control how val gets processed for assignment to attr0. processor = prefix_map[prefix] val0 = processor(name, attr0, val, formula_scanner = scanner) # note, this creates a C_rule (or the like) for each formula ns[attr0] = val0 # new feature 070316: if this assignment looks exactly like attr = _self.attr (before processor runs), # then don't store it in ns. This permits "inheritance of formulae from superclass" # but with the use of attr (not _self.attr) in subsequent formulae. Seems to work (testexpr_36). # update 070321: see another comment of this date, about a conflict we should make legal between this and def _C_attr. # update 070324: this needs to be done earlier, and now it is. Just assert that worked. ##e refile these comments? # assert not is_attr_equals_self_attr_assignment(attr0, val) # remove when works # old code said, when that assert cond failed: ## assert val0 == val # should be ok, but there is not yet an __eq__ method on OpExpr!!! ## print "skipping ns[attr0] = val for attr0 = %r, val = %r" % (attr0, val) # works ## del ns[attr0] processed_vals.append(val0) # (for use with __set_cls below) del prefix, attr0, val del newitems # create the new class object res = super(ExprsMeta, cls).__new__(cls, name, bases, ns) assert res.__name__ == name #k # tell the processed vals what class object they're in for thing in processed_vals: try: if hasattr(thing, '_ExprsMeta__set_cls'): # (note: that's a tolerable test, since name is owned by this class, but not sure if this scheme is best -- # could we test for it at the time of processing, and only append to processed_vals then?? # OTOH, what better way to indicate the desire for this info at this time, than to have this method? #k) thing._ExprsMeta__set_cls(res) # style point: __set_cls is name-mangled manually, since the method defs are all outside this class except: print "data for following exception: res,thing =",res,thing # fixed by testing for __set_cls presence: ## res,thing = <class 'exprs.Rect.Rect'> (0.5, 0.5, 0.5) ## AttributeError: 'tuple' object has no attribute 'set_cls' [when it had a different name, non-private] raise return res # from __new__ in ExprsMeta pass # end of class ExprsMeta class FormulaScanner: #061101 ##e should it also add the attr to the arglist of Arg and Option if it finds them? [061101] def __init__(self, debug_name = ""): self.debug_name = debug_name self.replacements = {} self.seen_order = -1 # this class knows about retvals of expr_serno (possible ones, possible non-unique ones) self.linecounter = 0 # this must be unique for each separate formula we scan, and be defined while we scan it self.argposns = {} # attr -> arg position ##e fix for superclass args self.next_argpos = 0 # next arg position to allocate ##e fix for superclass args self.saw_arglist = False # whether an ArgList was declared (if so, it used up all remaining arg positions) [070321 new feature] self.saw_non_required_arg = False # whether an Arg decl for a non-required Arg was seen [070321 new feature] # WARNING: saw_arglist and saw_non_required_arg are used only for error messages, and thus are affected by kluges # which reset them to False after one error message is emitted, to prevent them from issuing redundant ones. # Therefore they are NOT permanent records of those errors. If that is needed, replace the kluges with two different # attrs for each, one for whether the condition was seen and one for whether it led to an error message being printed. def __repr__(self): #070321 debug_name = self.debug_name return "<%s at %#x%s>" % (self.__class__.__name__, id(self), debug_name and (" (%s)" % debug_name) or "") def scan(self, formula, attr): """ Scan the given formula (which might be or contain a C_rule object from a superclass) .... #doc Return a modified copy in which replacements were done, .... #doc """ self.linecounter += 1 printnim("several serious issues remain about C_rules from superclasses in ExprsMeta; see code comment") ####@@@@ # namely: if a C_rule (the value of a superclass attrname) is seen in place of a formula in ExprsMeta: # - will it notice it as needs_wrap_by_ExprsMeta? # - will it do the right thing when using it (same as it does when making one for a subclass)? # - does C_rule need OpExpr methods for letting source code say e.g. thing.width on it? # - if so, does it need renaming of its own methods and attrs (especially args/kws) to start with _e_? # Idea to help with these: like a function making an unbound method, C_rule can modify its retval when # accessed from its class, not only when accessed from its instance. Can it actually return a "formula in _self" # for accessing its attr? This would do our replacement for us in the present context, but I'm not sure its good # if some *other* code accesses an attr in the class. OTOH, I can't think of any other code needing to do that, # unless it thinks it'll get an unbound method that way -- but for instance var attrs, it won't think that -- # if anything it'll think it should get a "default value". (Or perhaps it might want the formula passed into the C_rule.) # Note, the C_rule remains available in the class's __dict__ if needed. # Related Qs: what if a class formula accidentally passes a superclass attrname directly to a Python function? # If it does this for one in the same class, it passes the formula or expr assigned to that one in the source code, # before processing by FormulaScanner. This will generally fail... and needn't be specifically supported, I think. # A test shows that I was wrong: you can't access superclass namespace directly, in the first place! # You have to say superclassname.attr (like for using unbound methods in Python, even as rhs of an assignment # directly in subclass, not in a def in there, I now realize). If someone said this in our system, they would NOT # want _self.attr, if they had redefined (or were going to redefine) attr! They'd want either the formula assigned # to attr in the superclass, or something like _self._superclassname__attr with that formula assigned forever to that attr # (in the superclass). BTW, they'd probably want the processed formula, that is, if the formula they got had source # saying "attr2" (which had evalled to some unprocessed formula assigned to attr2) they'd want that to become _self.attr2. # Does access from a class happen when a subclass internally caches things? Does subclass __dict__ have everything? # Should find out... for now, just print_compact_stack whenever access from class happens, in a def __get__ far above. # Guess: best soln is for class access to return either _self.attr or (much better, semantically) the processed formula; # I think that solves all issues listed above, except that it would be supoptimal (maybe very) if the same super formula # was used multiple times (since no sharing of cached recompute results). If that matters, return _self._class__attr # and plop that formula on _class__attr in that class. BUT I haven't designed how Arg or Option work # or thought this through at all re them; maybe this scanner handles them too... s##e # [061101] #e if not a formula or C_rule, asfail or do nothing error_if_Arg_or_Option = False if 1: new_order = expr_serno(formula) assert new_order >= self.seen_order, 'you have to sort vals before calling me, but I got order %r, then %r in %r' % \ (self.seen_order, new_order, formula) #### this is failing, so print the exprs it gets: ## print "fyi here is a formula for worrying about that sort order bug: %r" % formula ## # the bug is that we sort it as 10, but see it here as constant_Expr(10) -- but who does that? ## # Turns out it was done in prefix_DEFAULT_, so in 'kluge061103' we predo that before sorting. if new_order == self.seen_order > 0: error_if_Arg_or_Option = True #doc ###IMPLEM its effect; is it really just an error about _E_ATTR?? not sure. self.seen_order = new_order pass self.replacements[_E_ATTR] = constant_Expr(attr) # this allows formulas created by Option to find out the attr they're on printnim("we need some scheme to detect two attrs with the same val, if that val contains an Arg or Option subexpr") # once vals are sorted, these are easy to see (they're successive)... we exploit that above, to set error_if_Arg_or_Option if error_if_Arg_or_Option: del self.replacements[_E_ATTR] ###KLUGE -- at least this ought to cause an error, eventually & hard to understand # but under the right conditions... #e instead we need to put in a "replacement it's an error to use". ###WRONG since Arg doesn't put in the symbol _E_ATTR, I think... what's ambiguous for it is, ref same arg, or another Arg? ##e to fix, use a scheme we need anyway -- a thing in the expr which runs code when we scan it, to get its replace-val. # (Can that be an effect of doing constant-folding if replace-vals are constants, incl funcs being called on args??) printnim("should test that above kluge (del at _E_ATTR) detects thing = thing2 = Option(...) even if not Arg()")##e # current status by test 061103 8pm - for bright = width, and bheight = top, that warning gets printed, # but nothing else seems to detect the error (if it is an error, I forget, but I think it is). #####@@@@@ res = self.replacement_subexpr(formula) # register formula to be replaced if found later in the same class definition [#e only if it's the right type??] if formula in self.replacements: print "warning: formula %r already in replacements -- error?? its rhs is %r; new rhs would be for attr %r" % \ (formula, self.replacements[formula], attr) # maybe not error (tho if smth uses it after this, that might deserve a warning) -- # in any case, don't replace it with a new replacement else: self.replacements[formula] = getattr(_self, attr) # this creates a getattr_Expr [#e clearer to just use that directly?] # don't do this before calling self.replacement_subexpr above, or it'll find this replacement immediately! return res def replacement_subexpr(self, subexpr): ###e arg to preclude replacing entire thing, to help detect a1=a2=Arg() error """ Map a subexpr found in a formula (perhaps a C_rule from a superclass, if that can happen and is supported) into its replacement, which is usually the same subexpr. """ assert not isinstance(subexpr, ClassAttrSpecific_NonDataDescriptor), "formula containing super C_rule is nim" #e more info if subexpr in self.replacements: # looked up by id(), I hope ###k res = self.replacements[subexpr] ## print "replacing %r by %r" % (subexpr,res) return res elif hasattr(subexpr, '_e_override_replace') and is_Expr_pyinstance(subexpr): # It wants to do it itself, perhaps using private knowledge about the methods & internal attrs in this scanner. # (This is used by special subexprs which call self.argpos in order to allocate argument positions.) return subexpr._e_override_replace( self ) ###e can we find an Instance here?? assume no, for now. assert not expr_is_Instance(subexpr) printnim("I bet InstanceOrExpr is going to need arb getattr when Expr, and _e_ before all methodnames.... see code cmt") #### PROBLEM re that printnim: # attr1 = Rect(...); attr2 = attr1.width -- this does a getattr that will fail in current code -- # or might return something like a bound method (or C_rule or whatever it returns). # [###e C_rule better detect this error, when _e_is_instance false in it -- i bet it does... # yes, it does it inside _e_compute_method.] # BUT it might be illegal anyway, if we needed to say instead attr1 = Instance(Rect(...)) for that to work, # with Instance (or Arg or Option) effectively returning something like a Symbol # (representing a _self-specific instance, like _self does) -- in fact [061101], # Instance(expr) might immediately return something like # _self._i_instance( expr, relindex-incl-attr-and-formula-subexpr-index ) # or maybe that relindex can itself just be a symbol, so it can be put in easily and replaced later in a simple way. # otherwise assume it's a formula ###e special case for a formula headed by Arg or Option etc? just ask the expr if it wants to know attr, # ie if it's a macro which wants that, and if so, copy it with a new keyword or so, before replacing it as below. printnim("need special replacement for Arg etc which needs to know attr and formula-subexpr-index?") # do replacements in the parts if is_Expr_pyclass(subexpr): # it's a python class -- has no replaceable parts return subexpr return subexpr._e_replace_using_subexpr_filter( self.replacement_subexpr ) ###IMPLEM in Expr #k does API survive lexscoping?? def argpos(self, attr, required, arglist = False): """ An Arg or ArgOrOption macro has just been seen for attr, in the source line identified by self.linecounter. (It is a required arg iff required is true. It is an ArgList iff arglist is true [new feature 070321].) (In the future, if a superclass defines args, this might be one of those or a new one.) What argument position (numbered 0, 1, 2, etc) does this arg correspond to? Return the answer, and record it. NIM: ASSUME NO ARGUMENTS COME FROM THE SUPERCLASSES. To fix that, we'll need to find out what they were, then see if these are in that list (if so return old number), or not (and start new numbers after end of that list). Behavior when superclass has optional args and this class then defines required ones is not decided (might be an error). NIM: any decl to override this, like _args. """ try: res = self.argposns[attr] ## print "fyi: scanner argpos returned an already-known pos %d for %r; other data:" % (res, attr), self, self.argposns # Note: this shows that finding the attr already recorded here is very common -- I guess since the thing that # gets replaced with the argpos occurs twice in every expanded Arg macro, or in lots of them anyway. # (It might also happen in a more unavoidable way, if we implemented inheritance of argpos from superclass someday, # tho the need for the recent kluge to permit attr = _self.attr (elsewhere in this file) suggests that might # not be possible after all -- allocated argpos could be inherited, but probably not the initial defns desired # in the class namespace, unless we added some sort of kluge to bring them in, which seems like a bad idea.) [070321] return res except KeyError: # new argument -- allocate an arglist position for it if self.saw_arglist: print "error (ignoring it): another arg is declared after an arglist was seen",\ self,attr,required,arglist,self.argposns ###e improve message self.saw_arglist = False # kluge: don't keep complaining about this for more args after the same ArgList if arglist: self.saw_arglist = True ##e also record this for this arg? # no need for now, but in future, recording all arg/opt decls in one list (of all kinds) # for processing once by the class (or customized expr) will permit better error checking of passed args/opts. # [070321 comment] pos = self.next_argpos self.next_argpos += 1 self.argposns[attr] = pos ###e also record whether it's required, and assert that once they stop being required, new ones are also not required if self.saw_non_required_arg and required: print "warning: required arg decl for %r comes after non-required arg decl -- it won't do what you want" % attr, self ###e improve msg self.saw_non_required_arg = False # kluge: don't keep complaining about this for the same non-required arg if not required: self.saw_non_required_arg = True # (do we also need to record their names? well, we're doing that. Do we need to record whether their names are public? #e) return pos pass # end of class FormulaScanner # == # helpers for CV_rule # (generally useful, but placed here since this module is very fundamental so should be mostly self-contained; # we might relax this later #e, but files helping implement this need to say so, like lvals.py does, # since most files in this module assume they can depend on this one.) class ConstantComputeMethodMixin: # use this when defining things used inside ExprsMeta [is this necessary?? maybe it's lazy enough to not need it? I doubt it. #k] # only ok when they don't need any recomputes after the first compute. # (maybe just use python properties instead? #e) def __getattr__(self, attr): # in class ConstantComputeMethodMixin # return quickly for attrs that can't have compute rules if attr.startswith('__') or attr.startswith('_C'): raise AttributeError, attr # must be fast for __repr__, __eq__, __add__, etc try: cmethod = getattr(self, '_C_' + attr) except AttributeError: raise AttributeError, attr try: val = cmethod() except: print_compact_traceback("bla: ") ###e val = None setattr(self, attr, val) return val pass class DictFromKeysAndFunction(ConstantComputeMethodMixin): """ Act like a read-only dict with a fixed set of keys (computed from a supplied function when first needed; if that func is not supplied, all keys are permitted and iteration over this dict is not supported), and with all values computed by another supplied function (not necessarily constant, thus not cached). """ def __init__(self, compute_value_at_key, compute_key_sequence = None, validate_keys = False): self.compute_value_at_key = compute_value_at_key self.compute_key_sequence = compute_key_sequence # warning: might be None self.validate_keys = validate_keys def _C_key_sequence(self): # called at most once, when self.key_sequence is first accessed assert self.compute_key_sequence, "iteration not supported in %r, since compute_key_sequence was not supplied" % self return self.compute_key_sequence() def _C_key_set(self): return dict([(key,key) for key in self.key_sequence]) def __getitem__(self, key): if self.validate_keys: #e [if this is usually False, it'd be possible to optim by skipping this check somehow] if not key in self.key_set: raise KeyError, key return self.compute_value_at_key(key) # not cached in self # dict methods, only supported when compute_key_sequence was supplied def keys(self): """ @note: unlike for an ordinary dict, this is ordered, if compute_key_sequence retval is ordered """ return self.key_sequence iterkeys = keys def values(self): """ @note: unlike for an ordinary dict, this is ordered, if compute_key_sequence retval is ordered """ compval = self.compute_value_at_key return map( compval, self.key_sequence ) itervalues = values def items(self): """ @note: unlike for an ordinary dict, this is ordered, if compute_key_sequence retval is ordered """ compval = self.compute_value_at_key return [(key, compval(key)) for key in self.key_sequence] iteritems = items pass # end of class DictFromKeysAndFunction class RecomputableDict(Delegator): """ Act like a read-only dict with variable (invalidatable/recomputable) values, and a fixed key sequence used only to support iteration (with iteration not supported if the key sequence compute function is not supplied). If validate_keys is True, every __getitem__ verifies the supplied key is in the specified key sequence. #e Someday, self.lvaldict might be a public attr -- not sure if this is needed; main use is "iterate over values defined so far". [This class is used by ExprsMeta to help implement _CV_ dict-item compute methods.] """ def __init__(self, compute_methodV, compute_methodK = None, validate_keys = False): self.lvaldict = LvalDict2(compute_methodV) Delegator.__init__( self, DictFromKeysAndFunction( self.compute_value_at_key, compute_methodK, validate_keys = validate_keys ) ) return def compute_value_at_key(self, key): #e should rename to be private? return self.lvaldict[key].get_value() def inval_at_key(self, key):#070207 """ [public method, on a dictlike object whose other client code might treat it much like an ordinary dict] Invalidate our lval at the given key. This has two effects: - force it to be recomputed when next asked for; - propogate this inval to anything which tracked a use of the value. Note that __delitem__, if we implemented it, would only do the first of these effects. That would probably be a bug, so for now, we're not implementing it (exception if you try to del an item). """ self.lvaldict[key].inval() pass ###e tests needed: # - make sure customization of attr formulas doesn't work unless they were defined using _DEFAULT_ # end
NanoCAD-master
cad/src/exprs/ExprsMeta.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Boxed.py -- example of high-level layout expr @author: bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. See also: DraggablyBoxed """ from utilities.constants import white from exprs.Rect import RectFrame from exprs.Overlay import Overlay from exprs.transforms import Translate from exprs.Exprs import V_expr from exprs.widget2d import Widget2D from exprs.instance_helpers import InstanceMacro from exprs.attr_decl_macros import Arg, Option from exprs.ExprsConstants import Width, PIXELS, Color class Boxed(InstanceMacro): # 070316 slightly revised """ Boxed(widget) is a boxed version of widget -- it looks like widget, centered inside a rectangular frame. Default options are pixelgap = 4 (in pixels), borderwidth = 4 (in pixels), bordercolor = white. [#e These can be changed in the env in the usual way. [nim]] @warning: some deprecated but commonly used options are given in model units, not in pixels (probably a design flaw). """ #e (Does Boxed want a clipped option, like DraggablyBoxed has? What about just Rect?) # WARNING: would not work if it inherited from Widget2D, # since it would pick up Widget2D default values for lbox attrs like btop. [unconfirmed but likely; 061127 comment] # args thing = Arg(Widget2D) # options borderwidth = Option(int, 4) # 070305 new feature -- specified in pixels borderthickness = Option(Width, borderwidth * PIXELS) # old alternative (worse since caller has to multiply by PIXELS); commonly used, but deprecated as of 070305 # (warning: borderthickness is still used as an internal formula when not supplied) # (WARNING: supplying both forms is an error, but is not detected; # this might cause bugs that are hard for the user to figure out # if the different option forms were used in successive customizations of the same expr) pixelgap = Option(int, 4) # 070305 new feature [#e rename gap? bordergap? (change all gap options to being in pixels?)] # (maybe not yet tested with nonzero passed-in values) gap = Option(Width, pixelgap * PIXELS) # old alternative (worse since caller has to multiply by PIXELS), commonly used, but deprecated as of 070305 # (see also the comments for borderthickness) # (warning: gap is still used as an internal formula when not supplied) bordercolor = Option(Color, white) # internal formulae extra1 = gap + borderthickness ww = thing.width + 2 * extra1 #k I'm not sure that all Widget2Ds have width -- if not, make it so ##e [061114] hh = thing.height + 2 * extra1 rectframe = RectFrame( ww, hh, thickness = borderthickness, color = bordercolor) # appearance -- note, rectframe appearing first is significant, since lbox attrs are delegated to it. _value = Overlay( Translate( rectframe, - V_expr( thing.bleft + extra1, thing.bbottom + extra1) ), #e can't we clarify this somehow? thing) pass # end
NanoCAD-master
cad/src/exprs/Boxed.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ geometry_exprs.py -- time-varying geometric primitives that can know their units & coordinate system. $Id$ About this module's filename: I might have just called it geometry.py, but that name is taken in cad/src (though perhaps that file deserves to be relegated to a more specific name). == About data representation: raw data is represented using Numeric Python arrays of convenient shape, containing floats, or ints or longs treated the same as floats, the same as would be commonly used in cad/src files. But I might decide to represent some points/vectors/matrices as 4d, so that translation can be matrix multiplication too (as in OpenGL, for example). Perhaps routines for asking for coords (or, coord systems themselves) will come in 3d and 4d forms. == About style and conventions of this code: Simpler method and attr names should access and accept self-describing objects (e.g. Points which know their space & coordsystem, not just 3-tuples), but for convenience should also accept raw objects (unless asked not to), interpreting them in a coordsystem that's an attr of the base object. Fancier method and attr names should be used to ask for raw coordinates, either in any specified coordsystem, or by default in one known to the object (as an attr or in its env). These objects have mutable public attrs in general, but when their attr values are arrays of high-level objects, elementwise-mutability of those arrays (with change tracking) may not be universal -- but it is encouraged and should be assumed unless documented otherwise. But individual raw coordinates (e.g. x,y, and z in a Point's coords) are *never* individually mutable or tracked. Methods that accept numbers should always accept either floats or ints or longs, treating ints or longs as if they were converted to floats, but not guaranteeing to actually convert them unless necessary for correctness of arithmetic in this module. That is, raw data saved or computed here and passed outside might in principle still contain int coordinates. On the other hand, it's not guaranteed to, even if all inputs were ints and all computed values could have been correctly represented as ints. Any issue about whether mutable arrays are shared or not needs to be documented in each case, until a general pattern emerges and can become the standard- unless-otherwise-specified. Watch out for the Numeric Array == bug, and for Numeric arrays being shared with other ones (even if they are "extracted elements" from larger arrays). All methods which accept or return Numeric arrays should try to protect naive callers from these bugs. == About optimization: One useful geometric primitive is a collection of little prims of a variety of types (points, vecs, unit vecs, dual vecs, matrices, quats, etc) (or of a single type?) all in the same coordinate system. E.g. a point & vec array object... then its coordinate-system-checking overhead can be handled once for the whole collection, so it can be reasonably efficient w/o compiling. (For more general compiling, see below.) Then any HL geometric object can be expressed as something that owns some of these geom-prim-arrays, and maybe knows about special subsets of indices of its elements. This is sort of like a GeometricArray or GeometricStateArray -- unless the element coords are formulas... ##e == About this code's future relation to externally written geometric utility libraries (e.g. constructive solid geometry code, or Oleksander's code, or that trimesh-generating package that Huaicai once interfaced to), and/or about expressing some of this in C, or Pyrex, or even in Numeric Python or numarray: - There is none of that now [070313], but someday there should be, as an important optimization. - But the classes here are probably higher-level than will be found in any external code -- maybe in handling units & coord systems, and certainly in their Expr aspects. - So the most basic ones might deserve direct translation into C/Pyrex, but that will require translating an Expr framework (e.g. for inval/update)... - And most of them should be viewed as examples of what glue code to external library functions ought to look like, much like drawing exprs can be thought of as glue code to OpenGL. == About compiling as the ultimate optimization: [###e maybe refile some of this comment into a new file about compiling or optim, even if it's a stub file] - We're likely someday to implement compiling features which let the application programmer use exprs to designate connected networks of objects/methods/attrs to be compiled, and which reexpress them as glue code exprs to automatically generated C or Pyrex code, which implements the understood subset of their state & methods in a very efficient way. In practice, many of the primitives involved would need special purpose "compiling instructions", but the higher-level objects (defined in terms of those primitives) often would not, nor would we need the C code we made to be itself optimized in order to see a huge speedup from doing this. If we taught the basic OpenGL, State/StateArray, formula OpExpr, internal Expr, instantiation, and geometric primitives how to be compiled, that would cover most code that needs to be fast. - That means we can think of these high-level geometric formula-bundles as if they will become compiling instructions for geometric calculations, rather than as ever-present overhead -- since someday they will. """ from Numeric import dot from geometry.VQT import planeXline from geometry.VQT import norm from geometry.VQT import cross from geometry.VQT import vlen # == # See also: # demo-polygon.py # ../VQT.py # ../geometry.py # ../*bond*.py has some vector math utils too # == #e refile into a non-expr geom utils file? maybe even cad/src/geometry.py? #k also I was pretty sure I already wrote this under some other name... def project_onto_unit_vector(vec, unit): ###UNTESTED "project vec onto a unit-length vector unit" return dot(vec, unit) * unit # == # line_closest_pt_to_line( p1, v1, p2, v2) -> point on line1 # line_closest_pt_params_to_line -> params of that point using p1,v1 (a single number) class Ray: ##e (InstanceOrExpr): #k revise super to something about 3d geom. #e add coordsys/units features # not fully tested """Represent an infinite line, and a map from real numbers to points on it, by a point and vector (of any length), so that 0 and 1 map to p and p+v respectively. WARNING: in this initial kluge implem, p and v themselves are passed as bare 3-tuples. WARNING: should be an expr, but isn't yet! """ #e should it be drawable? if so, is there a synonym for a non-ray line which is identical except for the draw method? #e and, how would its draw method know how far to draw, anyway? it might need an estimate of viewing volume... def __init__(self, p, v): self.p = p #### note: p and v themselves are stored as 3-tuples, and in this initial kluge implem, are also passed that way!! # OTOH in future we might *permit* passing them as that, even if we also permit passing fancier objects for them. #e But then we'll have to decide, for example, whether they can be time-varying (meaning this class is really an Instance). # Answer: they can be, and what we store should ultimately be able to include optimizedly-chosen methods # for recomputing them in our local coords! Unless that's relegated entirely to "compiling code" separate from this code... self.v = v self.params = (p, v) ##e change to a property so mutability works as expected def closest_pt_params_to_ray(self, ray): "" p2, v2 = ray.params # note: at first I wrote self.params() (using method not attr) p1, v1 = self.params # do some math, solve for k in p1 + k * v1 = that point (remember that the vecs can be of any length): # way 1: express p2-p1 as a weighted sum of v1, v2, cross(v1,v2), then take the v1 term in that sum and add it to p1. # way 2: There must be a NumPy function that would just do this in about one step... # way 3: or maybe we can mess around with dot(v1,v2) sort of like in corner_analyzer in demo_polygon... # way 4: or we could google for "closest points on two lines" or so... # way 5: or we could call it the intersection of self with the plane containing p2, and directions v2 and the cross prod, # and use a formula in VQT. Yes, that may not be self-contained but it's fastest to code! v1n = norm(v1) v2n = norm(v2) perp0 = cross(v1n, v2n) if vlen(perp0) < 0.01: ##k btw what if the lines are parallel, in what way should we fail? # and for that matter what if they are *almost* parallel so that we're too sensitive -- do we use an env param # to decide whether to fail in that case too? If we're an Instance we could do that from self.env... #e print "closest_pt_params_to_ray: too sensitive, returning None" ###### teach caller to handle this; let 0.01 be option return None perpn = norm(perp0) perpperp = cross(perpn,v2n) inter = planeXline(p2, perpperp, p1, v1n) # intersect plane (as plane point and normal) with line (as point and vector) if inter is None: print "inter is None (unexpected); data:",p1,v1,p2,v2,perp0 return None # inter is the retval for a variant which just wants the closest point itself, i.e. closest_pt_to_ray return dot(inter - p1, v1n) / vlen(v1) def posn_from_params(self, k): "" # return a point on self whose param is k -- as a Point or a 3-tuple? how does method name say, if both can be done? # best answer someday: just return a Point and let it be asked for raw data if needed. Its default coordsys can be ours. # or maybe can be specified by self.env. ###k does the method name 'posn' imply we return a 3-tuple not a Point? if k is None: return None p1, v1 = self.params return p1 + k * v1 def closest_pt_to_ray(self, ray): ### NOT USED "" k = self.closest_pt_params_to_ray(ray) return self.posn_from_params(k) def __add__(self, other): ##### assume other is a Numeric array vector 3-tuple -- should verify! and someday permit a Vector object too. p1, v1 = self.params return self.__class__(p1 + other, v1) ###REVIEW: will this work once we're an InstanceOrExpr? (p1 and/or other might be an expr then) pass
NanoCAD-master
cad/src/exprs/geometry_exprs.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ ToggleShow.py $Id$ #e needs cleanup """ ##nim: [obs? maybe not] ## StateRef, syntax and implem ## see comments from 061121 # ##e see also old code in ToggleShow-outtakes.py # Hmm, I discovered by accident 061203 1007p that the following were not being processed by ExprsMeta: ##weird val (('open_icon', 'ToggleShow')): an Expr that is not free in _self <Overlay#3945(a)> ##weird val (('closed_icon', 'ToggleShow')): an Expr that is not free in _self <Overlay#3952(a)> ##weird val (('openclose', 'ToggleShow')): an Expr that is not free in _self <Highlightable#3959(a)> # so I will make them processed by it, by removing the free in _self condition (needed for State too), # but I wonder if that will break this, or maybe fix some of its occasional problems... from exprs.Highlightable import Highlightable from exprs.Rect import Rect from exprs.TextRect import TextRect from exprs.Column import SimpleRow, SimpleColumn from exprs.Overlay import Overlay from exprs.If_expr import If_kluge from exprs.instance_helpers import InstanceMacro, _this from exprs.attr_decl_macros import Arg from exprs.widget2d import Widget2D from exprs.StatePlace import set_default_attrs from exprs.py_utils import printnim from exprs.__Symbols__ import _self ## Set - not yet needed # [see controls.py [moved to Set.py] for a prototype, 061130, which takes a stateref rather than an lval as arg1 -- might be wrong -- # update 061204 -- yes, was wrong, revising, see Set.py ] ##e should try using State here once it's tested # == StateRef = Automatic = State = 'needs import' _my_node = 'needs implem' class ToggleShow(InstanceMacro): # args thing = Arg(Widget2D) label = Arg(Widget2D, TextRect("label")) #e or coerce text into a 1-line TextRect -- how do we declare that intent?? if 0: # first make it work with a self-made stateref only, imitating Highlightable, using transient state stateref = Arg(StateRef, Automatic) ###k assumes the dflt can be a way to make one, not a literal one ## Q: how does each stateref we have, e.g. the one here meant for 'open', relate to StatePlace args # we might make or get from a superclass? (like the ones now in Highlightable.py but to be moved to a super of it) # if caller passes one, no need for our own, but to make our own, we'd make it in a StatePlace of our own, I think. ##e 061117 if 0 and 'maybe': ##e might need to also say it's supposed to be boolean # note, on 070115 I revised StateRef (still a stub) but might have broken it due to the arg being passed here (not tested) stateref = Arg(StateRef(bool), Automatic) ##e and also spell out the default location -- assume ipath itself can be coerced into the full stateref stateref = Arg(StateRef(bool), _self.ipath) ####k is ipath local to something like _self, or only rel to the entire model?? his matters if we name the statepath here! stateref = Arg(StateRef(bool), _my_node.open) ###k assumes _my_node.open can be an lval even after _my_node is bound! ####k ##e or we could spell out the default stateref as _self.ipath, assuming that can be coerced into one -- # of course it can't, we also need to say it's boolean (openQ: open is true, closed is false) and with what encoding. # but come to think of it, that is not part of the arg, right? the arg is "some boolean state"... hmm, i guess it is. # but the arg can also be "where to store the state, of whatever kind you want". And we say the type and encoding # if the arg doesn't -- as if the caller can supply partial info in the arg, and we supply defaults rather than # making them get made up by the bare argtype -- which could work by just using a fancified argtype created here. # which the Arg macro could make for us somehow... but that can all wait for later. For now, # we can detect the boolean type by how we try to use the arg, i guess... not sure, maybe just say it right here. # and the default encoding for bools (known to the bool type, not custom to us) is fine. if 1: # works fine, but as of 061126 late, comment out the remaining stmt, since done in InstanceOrExpr superclass rather than here pass ## transient_state = StatePlace('transient') #e move into super along with the ones in Highlightable of which this is a copy #e rename stateref to be specific for open, maybe open_stateref, in that if 0 code above # devel scratch: transient_state is an attr_accessor, which lets you do getattr and setattr. # but what we want it to do for us is tell us an lval for the attr 'open' # so we can retain that, attached to self.open somehow -- as its actual lval, maybe? not sure. # but much like that, since get or set self.open should work that way. # so a stateref (instance of StateRef) is basically an instance which acts as an lval... and can be attached to an attr. # But ExprsMeta right now insists on making its own lval, being passed a formula. Should we kluge-adapt to that or change it? # Guess: better & maybe easier to change it. So we have a new kind of object, not a formula (or a special kind of one), # to use as an rhs and process by ExprsMeta. It's not an lval, that's per-Instance. Is it a formula for making an lval?### # But it might be semantically different, since we don't store the lval as the value for self.open, # but as the value for its lval. hmm.... can we tell ExprsMeta to do this by an assignment to open # of a wrapped formula? it means, get the lval not by making one whose vals come from this formula # but make a property whose lvals come from this formula (which should be per-instance but time-constant, maybe, # tho if not time constant, it might be ok -- not sure ##e). ## open = State('transient','open') ### hmm... maybe 'open' needn't be passed if it gets it like Arg or Option does... maybe the kind is also default something? # so: open = State()? bt say the type and dfault val -- like I did in this: # staterefs.py: 181: LocalState( lambda x = State(int, 1): body(x.value, x.value = 1) ) # # see if this gets the expected asfail: it does! [061121 late] ## set_default_attrs( transient_state, open = True) if 0: # this will be real code someday when no longer nim, but use an easier way first. open = State(bool, True) # default 'kind' of state depends on which layer this object is in, or something else about its class # but for now make it always transient_state # this is a macro like Option # it takes exprs for type & initial val # but those are only evalled in _init_instance or so -- not yet well defined what happens if they time-vary # and note, that form doesn't yet let you point the state into a storage place other than _self.ipath... should it?? # but the importance is, now in python you use self.open for get and set, just as you'd expect for an instance var. else: def get_open(self): #k return self.transient_state.open def set_open(self, val): #k self.transient_state.open = val return open = property(get_open, set_open) pass def _init_instance(self): super(ToggleShow, self)._init_instance() set_default_attrs( self.transient_state, open = True) # constants # Note, + means openable (ie closed), - means closable (ie open) -- this is the Windows convention (I guess; not sure about Linux) # and until now I had them reversed. This is defined in two files and in more than one place in one of them. [bruce 070123] open_icon = Overlay(Rect(0.4), TextRect('-',1,1)) closed_icon = Overlay(Rect(0.4), TextRect('+',1,1)) if 0: open_icon = TextRect('-',1,1) #stub closed_icon = TextRect('+',1,1) #stub else: ####@@@@ I vaguely recall that Highlightable didn't work on text! # and indeed, highlighting doesn't seem to be working on those. # if so, the above'll need revision until that's fixed. # BUT, with these grays anyway, clicks on the text are working. But it might be because the grays are behind them. ###k if 0 and 'varying rect sizes': # how it was during debugging open_icon = Overlay(Rect(0.5,1), TextRect('-',1,1)) # added 0.5 061120 1018p temp debug kluge closed_icon = Overlay(Rect(1,0.5), TextRect('+',1,1)) #061120 changed impicit 1 -> 0.5 else: # easier on the mouse-hand and eye open_icon = Overlay(Rect(0.4), TextRect('-',1,1)) # added 0.5 061120 1018p temp debug kluge closed_icon = Overlay(Rect(0.4), TextRect('+',1,1)) #061120 changed impicit 1 -> 0.5 # _value, and helper formulae ## open = stateref.value # can we make it work to say Set(open, newval) after this?? ####k # the hard part would be: eval arg1, but not quite all the way. we'd need a special eval mode for lvals. # it'd be related to the one for simplify, but different, since for (most) subexprs it'd go all the way. ## openclose = If( open, open_icon, closed_icon ) # Status as of 061121 421p: both if 0 and if 1 cases seem to work fine, provided you restart when changing between them. # (Testing was not extensive, so it might turn out that avoiding other reloads is also needed.) # The known bugfixes that led to this: # - selobj = None in some places (not sure which are needed). # - no usage/change tracking by stateplaces that get set during draw (or that contain glname -- don't know if that matters). # - no usage/change tracking by set_default_attrs. # And other changes that might be helping: # - don't recycle glnames. # - some others I forget, which are marked by 061120 (or maybe 061121) # in comments or stringlits (in this or other files). # - don't track_use on exception in Lval get_value (BUT, i suspect it's actually wrong not to; see cmt there 061121) # - more conservative selobj_still_ok # - mode.update_selobj(event) in leftClick and ReleasedOn # - self.inval(mode) #k needed? (done in two places per method, guess is neither is needed) # # Soon, the needed or not of the above workarounds should be sorted out, # and most of the following debugging-log commentary should be removed. #e if 1: openclose = Highlightable( If_kluge( open, open_icon, closed_icon ), on_press = _self.toggle_open, sbar_text = _this(Highlightable).ipath # this line just for debugging ) ##e we should optim Highlightable's gl_update eagerness # for when some of its states look the same as others! # (no gl_update needed then, at least not just for that change -- # note, this is a special case of the inval optim for when something was changed to an equal value) #e someday be able to say: # on_press = Set( open, not_Expr(open) ) ## silly: on_press = lambda open = open: open = not open # no, open = not open can't work # in fact, you can't use "lambda open = open", since open has to be replaced by ExprsMeta ##k can on_press be an expr to eval, instead of a (constant expr for a) func to call?? ####k ## on_press = call_Expr( lambda xxx: self.open = not self.open, xxx) # no, no assignment in lambda pass else: # so try this form 155p - bug of not working is gone, but now, it always draws the + form! Is it drawing the old one # due to same glname? no (I guess), they should have different names! # is it drawing old one due to not realizing that one is obs? ######where i am # is it failing to invalidate the drawing effect of this instance? (after all, who is it that sees the usage of open? # it must be glpane as if we were using a prefs variable here! is that sufficient?? does it work ok re selobj system???###) # IS THE CHOICE OF DELEGATE being invalled? I think so, since I see the alignment calcs get updated, # or is that just the live gltranslate inside the draw method? # HEY, when I covered up the glpane with this app, then uncovered it, suddenly I see the new selobj, # then the conjunction of both! how can that be? thes are similar to whgat I sawe earlier. conclusion: weird update bugs # in selobj/highlight system, i guess. (maybe it does the main draw and highlight draw on different objects? # try altering color, or using 4 images not 2. ###) # now it sems that mouse around on the closed that looks like open is what makes it look like clsed, or like both. # yes, repeatable, for either change of state. Ok, try that in 'if 1' case of this. ### siilar but not identical # and that time is again does get stuck into the closed state, with the grayrect no longer optiming redraws re stencil buffer. # .. reviewing code in Highlightable, I see some things to try -- see its 061120 comments. # ... I did all that, and the 'gray becomes inactive bug' in 'if 1 openclose case' is still there. howbout the if 0 case? # [later: i think that still had some bad bugs too, not much changed.] # for more, see string lits containing 061120, and for a log see big cmt just below here. openclose = If_kluge( open, ## Highlightable(open_icon, on_press = _self.toggle_open, sbar_text = _self.ipath), ## Highlightable(closed_icon, on_press = _self.toggle_open, sbar_text = _self.ipath), ###BUG - same ipaths? NO, I USED _self BUT MEANT _this(Highlightable)!!! AAArgh! ##k works now?? yes Highlightable(open_icon, on_press = _self.toggle_open, sbar_text = _this(Highlightable).ipath), Highlightable(closed_icon, on_press = _self.toggle_open, sbar_text = _this(Highlightable).ipath), ) pass def toggle_open(self): if 'yet another shot in the dark 061120 1001p': self.env.glpane.selobj = None ##### THIS SEEMS TO FIX THE BUG, at least together with other potshots and if 0 openclose. # theory: old selobjs are being drawn highlighted even when not drawn normally. they mask the real stuff. # but with if 1 openclose it doesn't fix the different bug (gets wedged into closed state). why not??? # this is with no recycling of names, and also selobj=None in recycler. # guess: in if 1, the same glname is used... but it's same literal selobj too, right? and remaking is turned off. # I don't have a theory for 'if 1' bug cause, or for why it only affects the inner thing, not outer one. # Does it only affect that after it's once been hidden? ### if so, is it "you were selobj and then not drawn" that makes it # happen? that might fit the data but I don't see how that could work. # So I added a 2nd 0.5 so neither gray rect form covers the other. but first inner close hits the bug of making it # inactive and act non-highlighted. so i wondered if the glname really only covers the openclose? code says so. # I added a try/except to be sure the PopName occurs; not triggered during this if 1 bug. # # Stopping for night 061120 1027p, summary: I understand some bug causes but not all; wish I could see inside the glselect # reasoning, so plan to add debug prints to glpane. Need to think thru its assumptions re chaotic glname/selobj/size/ # whether-drawn situation, see which are wrong, which might cause the bug. Also - can event processing occur during # paintGL? I hope not, but verify. Also maybe GLPane needs to track frame numbers for selobjs being drawn, # stencil bits being made, vs selobj state mods as tracked by inval.... # # update 061121 953a, where I am: after basic fixes elsewhere [some stateplaces not tracked, some usage tracking disallowed], # and still using all kluge/workarounds from 061120, bug seems totally fixed for if 0 case, all or most for if 1 ##k. # IIRC it was slightly remaining before some usage tracking disallowed, but that is not complaining, which is suspicious. # Anyway, if if 1 works too, plan is to gradually remove the kluges and clean up and keep it working. # BUT it looks like if 1 (using reloaded code) has a bug of some disallowed usage... details to follow. # BUT after restart I don't see it. BTW I recently reenabled reloading -- could that have fixed some bugs (how???), # or could it be that they now occur after reloading but not before it?? indeed, this is after changing if 1->0 and reload, # and looks like it might relate to old state being there, and ###### WHAT IF RELOADED CODE USES THE SAME STATE DIFFERENTLY AND HAS A BUG? ##### # [but, that bug aside, there is still a real problem with whatever usage tracking this # set_default_attrs is doing. [fixed now]] if 0: #061121 822p i've been using if 1 forever, let's see if if 0 works here: it does! either is ok, given the open property. old = self.transient_state.open self.transient_state.open = new = not old ## print "toggle_open changed self.transient_state.open from %r to %r" % (old, new,) else: old = self.open self.open = new = not old ## print "toggle_open changed self.open from %r to %r" % (old, new,) # [obs cmt re open property, but was it talking about that or a partly working State decl? as of 061121 I can't remember:] # should work but doesn't, see bug in notesfile, it delegates self.open eval to _value: 061118 late # (or is it just because the val was not initialized? GUESS, YES ###k) ## self.open = not self.open ### can this work??? it will call set of self.open -- what does the descriptor do for that? # (asfail, or not have __set__ at all?? FIND OUT. the notesfile says the same thing but for a different Q, what was it?) ## WE SHOULD MAKE THIS WORK even if we also make on_press = Set( open, not_Expr(open) ) work, since it's so natural. ### BTW what is it that will notice the inval, and the usage of this when we drew, and know that gl_update is needed? # the same thing that would know a display list content was invalid -- but where is it in our current code (if anywhere)? # I vaguely recall a discussion of that issue, in the displist chunk code or notesfile, weeks ago. # some way to have lvals representing displist contents or frame buffer contents, whose inval means an update is needed. printnim("toggle_open might do a setattr which is not legal yet, and (once that's fixed) might not properly gl_update yet") return _value = SimpleRow( openclose, SimpleColumn( label, If_kluge( open, thing, TextRect("<closed>") #####BUG: I wanted None here, but it exposes a logic bug, # not trivial to fix, discuss in If or Column [see also a discussion in demo_MT.py, 070302]; ##e Spacer(0) can also be tried here [##e should what to show here be an arg??] ) ) ) ## if 0: # if 0 for now, since this happens, as semiexpected: ## ## AssertionError: compute method asked for on non-Instance <SimpleRow#3566(a) at 0xe708cb0> ## ## ##e do we want to make the height always act as if it's open? I think not... but having a public open_height attr ## # (and another one for closed_height) might be useful for some callers (e.g. to draw a fixed-sized box that can hold either state). ## # Would the following defns work:? ## ## # (They might not work if SimpleRow(...).attr fails to create a getattr_Expr! I suspect it doesn't. ####k ) ## ## # [WARNING: too inefficient even if they work, due to extra instance of thing -- see comment for a fix] ## open_height = SimpleRow( ## open_icon, ## SimpleColumn( ## label, ## thing ## )).height ##k if this works, it must mean the SimpleRow gets instantiated, or (unlikely) ## # can report its height even without that. As of 061116 I think it *will* get instantiated from this defn, ## # but I was recently doubting whether it *should* (see recent discussions of TestIterator etc). ## # If it won't, I think wrapping it with Instance() should solve the problem (assuming height is deterministic). ## # If height is not deterministic, the soln is to make open_instance and closed_instance (sharing instances ## # of label), then display one of them, report height of both. (More efficient, too -- only one instance of thing.) ## # (Will the shared instance of label have an ipath taken from one of its uses, or something else? ## # Guess: from the code that creates it separately.) ## ## closed_height = SimpleRow( ## closed_icon, ## SimpleColumn( # this entire subexpr is probably equivalent to label, but using this form makes it more clearly correct ## label, ## None ## )).height pass # end of class ToggleShow # end
NanoCAD-master
cad/src/exprs/ToggleShow.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ demo_drag.py @author: bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. demo not only some drag actions, but some ways of setting up new model types and their edit tools and behaviors. [Eventually.] [for current status see comments just before GraphDrawDemo_FixedToolOnArg1] 070105 moved the pseudocode for Command & DragCommand class etc into new file Command_scratch_1.py -- see it for ideas about Command, DragCommand, _PERMIT_SETS_INSIDE_, DragANode, ClickDragCommand, MakeANode. (But some comments below still discuss Command and MakeANode in important ways.) Notable bug (really in check_target_depth in GLPane, not this file): highlighted-object-finder can be fooled by nearby depths due to check_target_depth_fudge_factor of 0.0001. This caused a bug here, which is so far only worked around (by increasing DZFUZZ), not really fixed. [070115 comment] == See also: * demo_drag_2_scratch.py * dna_ribbon_view.py * world.py * rules.py """ from OpenGL.GL import GL_LINE_LOOP from OpenGL.GL import glBegin from OpenGL.GL import GL_LINE_STRIP from OpenGL.GL import glVertex3fv from OpenGL.GL import glEnd from exprs.Overlay import Overlay from exprs.transforms import Translate from exprs.Rect import Rect ##, Sphere from exprs.Center import Center from exprs.Highlightable import Highlightable, BackgroundObject ##, Button, print_Expr from exprs.controls import checkbox_pref, ActionButton from exprs.Column import SimpleColumn ##, SimpleRow from exprs.DisplayListChunk import DisplayListChunk from exprs.world import World from utilities.constants import black, noop from utilities.constants import red from utilities.constants import blue from utilities.constants import green from utilities.constants import white from utilities.constants import yellow from exprs.Exprs import list_Expr, eval_Expr, call_Expr from exprs.Exprs import mod_Expr from exprs.Exprs import tuple_Expr from exprs.Exprs import getattr_Expr from exprs.If_expr import If from exprs.If_expr import If_kluge from exprs.widget2d import Stub, Widget2D from exprs.instance_helpers import ModelObject, InstanceOrExpr, DelegatingInstanceOrExpr, InstanceMacro, _this from exprs.attr_decl_macros import Arg, State, ArgOrOption, Option from exprs.ExprsConstants import PIXELS, Position, Color, StubType, ORIGIN, DZ from exprs.py_utils import printfyi from exprs.__Symbols__ import Anything, _self # == ## _viewer_for_object, etc, moved to rules.py on 070123 DZFUZZ = PIXELS * 3.0 # replacing 1, 2, 2.5 in different places, to work around bug reported in BUGS as: # 070115 "highlightable-finder can be fooled due to check_target_depth_fudge_factor of 0.0001" # (see also the assignment of check_target_depth_fudge_factor in testmode.py, and the discussion in BUGS.txt of better fixes ###e) # WARNING: It's possible that the value of DZFUZZ needed to work around this bug depends # on the GLPane size, or on user prefs settings, or on Ortho vs Perspective! (all speculations) ## DZFUZZ = PIXELS * 0.5 # this also works, given the change in testmode.py to check_target_depth_fudge_factor = 0.00001 [070116], # reducing it by 10x, but I will leave it this way (>10x margin of safety) to make it unlikely the bug will show up with # other GLPane sizes, zoom factors, etc. Sometime it needs one of the better fixes discussed in BUGS.txt. class Vertex(ModelObject): # renamed Node -> Vertex, to avoid confusion (tho it added some too, since localvars not all changed, # and since the world ought to contain model objs anyway, in general, of which Vertex is only one type, and current implem # also has its own graphics code)... # see below about better ways to rename it... """It has a position, initializable from arg1 but also settable as state under name pos, and an arb appearance. Position is relative to whatever coords it's drawn in. When you drag it, it chooses depth just nearer than hitpoint -- which means if you wiggle it over itself, it gets nearer and nearer (design flaw). [see comment for possible fix] """ # 070223 possible fix to seeing depth of self: during a drag, tell glpane not to draw dragobj into depth or during glselect # mode... so it finds some other selobj besides dragobj. means it should draw dragobj last i guess... maybe transparent # so you can see selobj behind it, or diff color when there is a selobj... ###e about what to rename it... Hmm, is it a general "Draggable"? .lookslike arg2 -> .islike or .thing arg1? # BTW, the highlightability is not yet specified here ###nim; it relates to the fact that we can bind commands to it # (as opposed to things it contains or is contained in, tho that should be permitted at the same time, # tho implem requires nested glnames to sometimes ignore inner ones, when those are inactive); # but we might add it in a wrapper which makes it into a view of it that lets commands be bound to it, # except that World.draw assumes we draw the actual model objs, not wraps of them - also an issue if env says they # look different -- so maybe World needs to wrap all it draws with glue to add looks and behavior to it, in fact. # [update much later 070201: or maybe ModelObject knows about this and asks env whether to override default drawing code.] # but for now, can we do this here? pos0 = Arg(Position) pos = State(Position, pos0) ###BUG -- does this work -- is pos0 set in time for this? not sure it's working... 061205 1009p #e we probably want to combine pos0/pos into one StateArg so it's obvious how they relate, # and only one gets saved in file, and only one self.attr name is used up and accessible # the rest of this class is for drawing it and interacting with it. # Can we move that code into e.g. VertexDrawable or VertexView # and have Vertex itself just delegate (for sake of draw, lbox, etc) to some rule in the env for getting a Drawable for it, # probably looking it up in a dynamic memoizing mapping in the env? ####e [070105] # I think YES. # - a main difference between a model & view object -- a view obj knows how to draw itself, a model obj asks the env. # (and the answer is quite different in different envs, e.g. 3d area vs MT. but what if we mix those?) # related notes: # - it might want a different delegate for drawing purposes (draw, lbox) and sim purposes (or others). # - does it also have an attr corresponding to its index/address/id in the model world? # - and maybe some for relations to other model objs, eg MT-parent, tags, name, etc? # - and maybe some graphics prefs like color or whatever, even if it's up to the drawing rule whether/how to use these? # - and for that matter some arbitrary other data (named attrs), as we'll let any model object have? # simplest thing that could work -- # - make some sort of MemoDict for model-view and put it into the env, even if we kluge how to set it up for now. # how does demo_MT do it? With a hardcoded helper function using a MemoDict in a simple way -- no involvement of env. # So see above for copied code from that... ###e #e so now what we want is for this (in super modelobject) to delegate to a computed viewer from the helper func above #e but also to have more args that can be used to set the color [do this only in Vertex_new, below] ## color = Option(Color, color) ## pass ## class VertexView(xx): -- SOMETHING LIKE THIS IS THE INTENT #### #e and then we want this new class to have the hardcoded appearance & behavior which the code below now passes in lookslike arg lookslike = ArgOrOption(Anything) # OrOption is so it's customizable ###BAD for lookslike to be an attr of the Vertex, at least if this should be a good example of editing a sketch. [070105] # (a fancy sketch might have custom point types, but they'd have tags or typenames, with rules to control what they look like) cmenu_maker = State(Anything, None) # meant to be set from outside; let's hope None is a legal value [070223 HACK] ## delegate = _self.lookslike #k delegate = Highlightable( Translate( lookslike, pos ), ## eval_Expr( call_Expr(lookslike.copy,)( color = yellow) ), #####?? weird exc don't know why - reload? ## AssertionError: _this failed to find referent for '_this_Vertex' on_drag = _self.on_drag, # 070103 kluge experiment, works (eg in _19d) cmenu_maker = cmenu_maker #070223 HACK [#e rename cmenu_maker to cmenu_obj as I guessed it was named??] ) #e actions? or do this in a per-tool wrapper which knows the actions? # or, do this here and make the actions delegate to the current tool for the current parent? guess: the latter. ##e digr: will we want to rename delegate so it's only for appearance? *is it*? does it sim like this too? # Guess: it's for everything -- looks, sim qualities, etc -- except what we override or grab from special members. # [if so, no need to rename, except to clarify, leaving it general.] #e might need something for how to save it in a file, Undo policy, etc def on_drag(self): # 070103 kluge experiment, copied/modified from on_drag_bg in bigger class below # Note: this bug reported in BUGS breaks dragging of these nodes; worked around by increasing DZFUZZ: # 070115 "highlightable-finder can be fooled due to check_target_depth_fudge_factor of 0.0001" # where i am 070103 447p (one of two places with that comment) # - sort of sometimes works, but posns are sometimes same as bg, not sure why that DZ would be needed, # oh i guess the mousepos comes from the gray bg rect not the self unless we drag very slow... point = self.current_event_mousepoint() ### MIGHT BE WRONG COORDS? guess: no #k guess: will have snap-to-fixed-point bug for generic drag code newpos = point + DZ * DZFUZZ # used for different things, depending #### DZ needed but might cause trouble too self.pos = newpos ## print "in-node action set %r.pos = %r" % (self, newpos) # sometimes works self.KLUGE_gl_update() #k needed? return pass # end of class Vertex # == # Summary of this and Vertex_new -- make use_VertexView work -- # [long comment added 070111; devel on this code has been inactive for a few days] # # it's an example of dynamically mapping selobj thru toolstate to get looks & behavior, # so the model object itself can be split out and needs no graphics/interaction code of its own. # My general sense in hindsight is that it's too low-level -- I need to figure out how all this could/should look as toplevel exprs. # # See a new file rules.py for more on that. class Vertex_new(ModelObject): #070105 ###e maybe it also needs an official type or typename for use in rules and files? pos0 = Arg(Position) pos = State(Position, pos0) color = Option(Color, black) pass class Viewer(InstanceOrExpr): "superclass for viewers of model objs given as arg1" modelobj = Arg(ModelObject) #k can subclass refer to this?? pass class VertexViewer(DelegatingInstanceOrExpr, Viewer): ###k ok supers? delegate = Rect(1, color = _self.modelobj.color) ###WRONG details, also assumes _self.modelobj has a color, but some don't. ###e do we wrap it in a provider of new default options?? ###e also needs behaviors... ## viewerfunc = identity # stub - might better be that hardcoded helper func above ####e def viewerfunc(x): printfyi("viewerfunc is being used but is a stub") return x WithViewerFunc = Stub # see rules.py, to which I moved the more expansive stub of this, 070123 # === # 070223 new hack ##class polyline_handle(DelegatingInstanceOrExpr): ## delegate = Draggable(Rect(0.3,green)) class polyline(InstanceOrExpr): # WARNING [070319]: duplicated code, demo_drag.py and demo_draw_on_surface.py [modified a bit] """A graphical object with an extendable (or resettable from outside I guess) list of points, and a kid (end1) (supplied, but optional (leaving it out is ###UNTESTED)) that can serve as a drag handle by default. (And which also picks up a cmenu from self. (kluge!)) Also some Options, see the code. """ # Note [070307]: this class will be superceded by class Polyline in demo_polyline.py, # and the code that uses it below (eg the add_point call) will be superseded by other code in that file. # ###BUGS: doesn't set color, depends on luck. end1 is not fully part of it so putting cmenu on it will be hard. # could use cmenu to set the options. # end1 might be in MT directly and also be our kid (not necessarily wrong, caller needn't add it to MT). # when drawing on sphere, long line segs can go inside it and not be seen. points = State(list_Expr, []) ###k probably wrong way to say the value should be a list ## end1arg = Arg(StubType,None) ## end1 = Instance(eval_Expr( call_Expr(end1arg.copy,)( color = green) ))###HACK - works except color is ignored and orig obscures copy end1 = Arg(StubType, None, doc = "KLUGE arg: optional externally supplied drag-handle, also is given our cmenu by direct mod") closed = Option(bool, False, doc = "whether to draw it as a closed loop") _closed_state = State(bool, closed) ####KLUGE, needs OptionState relative = Option(bool, True, doc = "whether to position it relative to the center of self.end1 (if it has one)") def _init_instance(self): end1 = self.end1 if end1: end1.cmenu_maker = self def _C__use_relative(self): "compute self._use_relative (whether to use the relative option)" if self.relative: try: center = self.end1.center return True except: #e print? return False return False def _C_origin(self): #070307 renamed this to origin from center if self._use_relative: return self.end1.center # this can vary! return ORIGIN ## center = _self.origin #k might not be needed -- guessing it's not, 070307 def add_point(self, pos): "add a point at the given 3d position" pos = pos - self.origin self.points = self.points + [pos] ### INEFFICIENT, but need to use '+' for now to make sure it's change-tracked def draw(self): ###k is it wrong to draw both a kid and some opengl stuff?? not really, just suboptimal if opengl stuff takes long (re rendering.py) self.drawkid(self.end1) # end1 node if self._closed_state: glBegin(GL_LINE_LOOP) # note: nothing sets color. see drawline for how. # in practice it's thin and dark gray - just by luck. else: glBegin(GL_LINE_STRIP) if self._use_relative: # general case - but also include origin (end1.center) as first point! origin = self.origin glVertex3fv(origin) for pos in self.points: glVertex3fv(pos + origin) else: # optim - but not equivalent since don't include origin! for pos in self.points: glVertex3fv(pos) glEnd() #e option to also draw dots on the points [useful if we're made differently, one click per point; and they might be draggable #e] return def make_selobj_cmenu_items(self, menu_spec, highlightable): """Add self-specific context menu items to <menu_spec> list when self is the selobj (or its delegate(?)... ###doc better). Only works if this obj (self) gets passed to Highlightable's cmenu_maker option (which DraggableObject(self) will do). [For more examples, see this method as implemented in chem.py, jigs*.py in cad/src.] """ menu_spec.extend([ ("polyline", noop, 'disabled'), # or 'checked' or 'unchecked'; item = None for separator; submenu possible ]) pass # === ## class World(ModelObject) -- moved to world.py, 070201 # ok, now how do we bind a click on empty space to class MakeANode ? # note, someday we might just as easily bind a click on some guide surface # (onto which we've applied an active tool to interpret clicks) # to that command, as binding a click on empty space to it. The point is, we have tools, with cmds in them, # and we bind tools to objects or to pieces of space (see scratch6 and recent notesfiles). # # so we can separate this: #####IMPLEM all these # - put this command and others (for other modkeys) into a tool, and # - make a button for a pallette which can (when run on a selected space or surface, or on the current space) # - bind that tool to empty space or to a guide surface. # - make a pallette with that button # - show this pallette. # - make a space object... is it that World object above, or only sometimes, or only temporarily? # well, the tool can change for the same world, the world concerns itself only with what kind of data it can hold # (and it may offer a set of tools, or have a default one, or have implems of std-named ones...) # but for an initial test, we can always be in this kind of world, have one tool implicitly, on entire space -- # but this does require changing the click-action. OR we could create a big image as a guide shape, and put click action on that. # Hmm, I think that's easier, I'll try that first. # Let's do it with a DNA origami image... but first, just a rect. So, we want a modifier for a thing (the rect) # which gives it the event bindings implied by this tool. I.e. a macro based on Highlightable. # status 061205 1022p: works (in this initial klugy form, not using Command classes above) except for recording points in abs coords # (wrong) but drawing them in arb rel coords (wrong), when both need to be in a specified coord sys, namely that of the bg rect object. # status 061207 ~9am: coords were fixed last night, and drag now works as of thismorning. simple demo draws blue nodes along the drag. # In theory it's using depth found at each point, so it could draw on a 3d curved surface -- but that's not tested. [later, it is.] # 061213 bug report, trivial: draws just in front, but in model coords, not screen coords. For trackball and then draw on back or # other side, screen coords would work better -- or maybe object-surface-coords (as some comment suggests) would be better still, # but for non-enclosed objs like planes, note that that depends on screen coords to know which face is facing the user. class GraphDrawDemo_FixedToolOnArg1(InstanceMacro): # see also class World_dna_holder -- need to unify them as a ui-provider framework # args background = Arg(Widget2D, Rect(10) ) # testexpr_19a, 061207 morn -- see if arb objects work here, and try drawing on a curved surface -- # works! (when the surface was the default here -- now also tested/works when it's the arg supplied by that testexpr) # # ... except for desirable improvements: # - we should replace DZ with "local perp to surface" to make the drawn things more visible. # - And we *might* want to replace depth with "computed true depth", since for a sphere, as we rotate the view # the drawn radius slightly changes due to where the triangle faces are located, and this can bury the drawing of marks # if they are really close to the sphere -- # - either that, or record their posns relative to the sphere surface, # which might be most correct anyway -- and especially useful if we change the radius of the sphere! (making it balloon-like) # - Also those things are oriented in global coords rather than coords based on the clicked surface. # Fixing that would also make them "look oriented" and help you perceive their depth when they're over a curved surface. # # Note that all these ideas would require asking the object for the surface orientation, and for how to store coords (relative # to what), and in the given eg, getting quite different answers (incl about how to transform coords for storage, re scaling) # depending on whether the rect or sphere was clicked -- # which the current code does not even detect, since it gives them the same glname. ###e # options highlight_color = Option(Color, None) # suggest: ave_colors(0.9,gray,white)) # use this only if background takes a color option use_VertexView = Option(bool, False) # 070105 so I can try out new code w/o breaking old code #### TRYIT world = Option(World, World(), doc = "the set of model objects") # revised 070228 for use in _19j test_background_object = Option(bool, False, doc = "test the new testmode._background_object feature") #070322 hide_background_object = Option(bool, False) # internals highlightable_background = \ Highlightable( background, ####### WAIT A MINUTE, how can we do that -- background is already an instance?!? ######@@@@@@ ## background(color=green),####KLUGE, causes various bugs or weirdnesses... not yet fully understood, ## e.g. AssertionError: compute method asked for on non-Instance <Rect#10415(a)> ## [GLPane_overrider.py:455] [Highlightable.py:275] [Rect.py:52] ##Rect(5,5,green),###KLUGE2 - works now that highlightable is not broken by projection=True [also works 061213] ## background.copy(color=green), # oops i mean: ## call_Expr(background.copy,)( color=green), # oops, i have to include eval_Expr: If( highlight_color, eval_Expr( call_Expr(background.copy,)( color = highlight_color) ), # can't work unless background is simple like a Rect, # but does work then! (edit _19d to include _19 not _19b) background ## None -- I hoped None would be equivalent, noticed in HL and replaced, but that would be hard, # would require it to notice each time whether the opt was suppied or not, do default each time # rather than per-time, also require supplying None to be same as not supplying the arg (not true now) # (maybe passing some other symbol should be same as that?? and permitted each time? But If->None is so # easy, by leaving out the arg... ###e decide) ), #e want this to work too: call_Expr(background.copy, color=green), # -- just let copy take **kws and pass them on, or let it call a customize helper # review of the kluges: # - the explicit call_Expr remains annoying but the lack of simple fix still seems true; not sure; # could we experiment by turning off that check within certain classes? not sure if that's possible # since it happens during expr-building. ##k # - the need for eval_Expr seems wrong somehow, in fact i'm not sure I understand why we need it. # Will it go away in new planned eval/instantiation scheme? not sure. I think so. # - copy needs **kws. # - does the .copy itself need to be explicit? that is, could supplying args/opts to an instance copy it implicitly?? # this might fit with other instances doing other stuff when those were supplied.... ###e # - should Overlay take color option and pass it on into leaves (subexprs)? what if some leaves won't take it? # that has been discussed elsewhere... i forget if dynenv or _optional_options = dict() seemed best. on_press = _self.on_press_bg, on_drag = _self.on_drag_bg, on_release = _self.on_release_bg, sbar_text = "gray bg" ) use_highlightable_background = If( test_background_object, BackgroundObject( highlightable_background, hide = hide_background_object), DisplayListChunk( # new feature as of 070103; works, and seems to be faster (hard to be sure) highlightable_background ) ) ## world = Instance( World() ) # maintains the set of objects in the model _value = Overlay( use_highlightable_background, If( _self.use_VertexView, DisplayListChunk( WithViewerFunc(world, viewerfunc) ), # try DisplayListChunk, 070103 later -- works, doesn't break dragging of contained old nodes. DisplayListChunk( world) ##, debug_prints = "World") ## world # zap DisplayListChunk to see if it fixes new 070115 bug about dragging old nodes -- nope ) ) newnode = None # note: name conflict(?) with one of those not yet used Command classes def on_press_bg(self): if 0: print "compare:" print self, self.delegate, self.delegate.delegate, self.delegate.delegate.plain # the background print self.background print "hl.highlighted =",self.delegate.delegate.highlighted # self.background is the same as the .plain printed above, which means, as of 061208 941pm anyway, # instantiating an instance gives exactly that instance. (Reasonable for now...) point = self.current_event_mousepoint() #e note: current_event_mousepoint is defined only on Highlightable, for now (see comments there for how we need to fix that), # but works here because we delegate ultimately to a Highlightable, without changing local coords as we do. # note: lots of devel scratch & debug comments removed 061207; see cvs rev 1.5 for them. # for initial test, don't use those Command classes above, just do a side effect right here ###kluge newpos = point + DZ * DZFUZZ # kluge: move it slightly closer so we can see it in spite of bg ###e needs more principled fix -- not yet sure what that should be -- is it to *draw* closer? (in a perp dir from surface) #e or just to create spheres (or anything else with thickness in Z) instead? (that should not always be required) ###BUG: DZ is not always the right direction! [more comment on that in demo_draw_on_surface.py] if not self.use_VertexView: # old code ## print "make node in old way (not using VertexView)" # still running as of 070115 at least in testexpr_19f node_expr = Vertex(newpos, Center(Rect(0.2,0.2, ## 'green', -- now we cycle through several colors: (colors,...)[counter % 6] ## tuple_Expr(green,yellow,red,blue,white,black)[mod_Expr(_this(Vertex).ipath[0],6)] red # the above worked ok until tested 070121 morn -- ipath now starts with string. # it was a kluge anyway, so disable it until we can rework it to be sensible. ))) else: # new code, being written 070105, just getting started -- mostly nim node_expr = Vertex_new(newpos, # cycle through several colors: (colors,...)[counter % 6] color = tuple_Expr(green,yellow,red,blue,white,black)[mod_Expr(_this(Vertex).ipath[0],6)] ) pass ## draggable_node_expr = Highlightable(node_expr, on_drag = _self.on_drag_node, sbar_text = "dne") ###BUG: this breaks dragging of the new node; it fails to print the call message from on_drag_node; # if you try to drag an old node made this way, it doesn't work but says # debug fyi: len(names) == 2 (names = (268L, 269L)) # Guess: limitation in current rendering code makes it not work for any nested glnames, but just print this instead... # (note: even after reload, the node objects in the world have their old Vertex class, and the old expr used to make them) # # [later 061213:] IIRC the status was: I made GLPane_overrider so I could fix that 2-glname issue in it, # but never got to that yet. Meanwhile I commented out the use of this expr, and thus on_drag_node is never used... # and Vertexes dragged directly do nothing -- they're highlightable but with no actions. # And World could probably draw them highlightable even if they weren't, but it doesn't. # BTW the disabled nonworking draggable_node_expr is not well-designed -- it does not add a Vertex to World, it adds a # draggable one -- but even World is not perfect, since it contains Vertexes (not just their data) # and they inherently have (a lack of) action bindings since they are Highlightable. # Probably better would be if World contained data-nodes and had access to (or had its own) display rules for them # which added commands/actions based on the currently active tools. That would help with tool-code-reloading too. # Probably some other comments here say this too. # # So does a World need a formula or function arg for how to map its data objects to display objects, at the moment? # Or is there some scheme of a global map for that, to be applied when "drawing" any data object? # And do some data objs have their own positions, or is that always supplied by the world or other data obj they're in? # In theory, we might display atoms at posns unrelated to atom.pos, e.g. as a row in a table which includes their coords. # So it's more like we have ways of "drawing a set of things" which can say "at posns given by func(thing)" # or "at successive posns in a column", corresponding to two display forms with different exprs, # with the map from thing to individual display form also needing to be specified. # So a World is more like a set of things, and it can have a display mode (or more than one), given a thing-display-function. # We can ask it or anything else how it recommends displaying itself given display style options, # but we can choose to use that display function (from it to a more directly displayable object) or use another one. # Or we can probably just "draw it" and have it pick up the current display style from the env (including the # currently active tools). Is there any reason not to permit both? (draw using current style, draw using given style, # give me function from you to drawables using given style, use specific function and draw the results -- all possible.) # # If a thing in a world has standard mouse actions of its own, can it also have "grabbable areas" for use in dragging it # when it has a posn as displayed in some world? Or did that world have to explicitly turn it into a draggable thing? # Answer: both. The world turns it into that by adding a drag binding for those "overall handles" the thing has. # It might draw them with glnames in some set it knows... ie as named subobjs of itself. The overall thing might also # have a single name. Then we have a sequence of two glnames meaning obj/subobj which we want to use to determine the action. # For some subobjs that's within the object and supplied by it (perhaps depending on tool); for others, # it's supplied by the World it's in (also dep on a tool) and handled by it (eg move the obj, select the obj). # # For the simple things we have there, there are no subobjects, and no actions except drag or later select the whole thing. # A simple model is "one thing was hit, but some things are specified by a specific series of two or more glnames". # In general the outer name decides how to interpret (or whether to ignore) the inner names. # It can map the inner ones somehow... not sure how. This will relate a lot to DisplayListChunk when we have that. # Mere nested Highlightables might push two names but both would be unique. Outer name might just defer to inner one then. if 0: ## MAKE THIS WORK: draggable_node_expr = 'define this' newnode = self.world.make_and_add( draggable_node_expr, type = "Vertex") else: newnode = self.world.make_and_add( node_expr, type = "Vertex") #070206 added type = "Vertex" self.newnode = newnode ###KLUGE that we store it directly in self; might work tho; we store it only for use by on_drag_bg return # from on_press_bg ## def on_drag_node(self): ## print "on_drag_node called -- how can we know *which* node it was called on??" ## # 070103 status guess: this is not called; old cmts above seem to say that the only problem with it working is nested glnames. ## return def on_drag_bg(self): # note: so far, anyway, called only for drag after click on empty space, not from drag after click on existing node point = self.current_event_mousepoint() lastnode = self.newnode # btw nothing clears this on mouseup, so in theory it could be left from a prior drag ## try: ## lastipath = lastnode.ipath[0] ## except: ## lastipath = -1 ## # print "on_drag_bg %d" % lastipath, point### # this shows no error in retaining correct lastnode -- that's not the bug ## print "on_drag_bg" newpos = point + DZ * DZFUZZ # used for different things, depending what = kluge_dragtool_state() ###IMPLEM better if what == 'draw': # make a blue dot showing the drag path, without moving the main new node (from the click) node_expr = Vertex(newpos, Center(Rect(0.1,0.1,blue))) self.world.make_and_add(node_expr, type = "dot") #070206 added type = "dot" -- note, not deducible from the expr!! elif what == 'polyline': if not lastnode: print "bug: no self.newnode!!!" else: if not isinstance(lastnode, polyline): lastnode = self.newnode = self.world.make_and_add( polyline(lastnode), type = "polyline" ) lastnode.add_point(newpos) elif what == 'drag': # drag the new node made by the click if not lastnode: print "bug: no self.newnode!!!" else: lastnode.pos = newpos pass return def on_release_bg(self):#070223 new hack import foundation.env as env #FIX if isinstance(self.newnode, polyline) and env.prefs.get(kluge_dragtool_state_prefs_key + "bla2", False): self.newnode._closed_state = True ####KLUGE, I'd rather say .closed but that won't work until I have OptionState return # == methods make, make_and_add have been moved from here into class World [070202] pass # end of class GraphDrawDemo_FixedToolOnArg1 kluge_dragtool_state_prefs_key = "A9 devel/kluge_dragtool_state_bool" kluge_dragtool_state_prefs_default = False ## False = 'draw', True = 'drag' (since our only prefs control yet is a boolean checkbox) def kluge_dragtool_state(): # it's like a user pref or transient state for the *toolset* of which the tools choosable here are a part. # (typically you have one instance of each toolset in your app, not one per editable thing for each kind of toolset, # though if you ask, there might be a way to customize those settings for what you edit -- but by default they're general.) # so for now we can approximate this using either transient state or prefs state for the toolset object, # or a prefs key if we don't have that kind of state. (Note: currently no stateplace is stored in prefs, but one could be.) # # related digr: if code uses prefs, those prefs might as well be readily available when that code's in use, # so automatically we can get code-specific control panels just to control display & behavior that affects what's now on screen, # organized in std hierarchy but filtered for whether they are "in use". For now do this by hand, but later we'll want some way # to find out what's in use in that sense, and usage-tracking might be enough unless prefs get bundled into single tracked objs # of which then only some parts get used. We can probably avoid that well enough by convention. import foundation.env as env polyline = env.prefs.get(kluge_dragtool_state_prefs_key + "bla", False)#070223 new hack if polyline: return "polyline" # for this kluge, let the stored value be False or True for whether it's drag drag = env.prefs.get(kluge_dragtool_state_prefs_key, kluge_dragtool_state_prefs_default) return drag and 'drag' or 'draw' kluge_dragtool_state() # set the default val kluge_dragtool_state_checkbox_expr = SimpleColumn( # note, on 061215 late, checkbox_pref was replaced with a better version, same name checkbox_pref(kluge_dragtool_state_prefs_key, "drag new nodes?", dflt = kluge_dragtool_state_prefs_default), checkbox_pref(kluge_dragtool_state_prefs_key + "bla", "some other pref"), ) def demo_drag_toolcorner_expr_maker(world): #070106 improving the above # given an instance of World, return an expr for the "toolcorner" for use along with GraphDrawDemo_FixedToolOnArg1 (on the same World) expr = SimpleColumn( checkbox_pref(kluge_dragtool_state_prefs_key, "drag new nodes?", dflt = kluge_dragtool_state_prefs_default), checkbox_pref(kluge_dragtool_state_prefs_key + "bla", "make polyline?", dflt = False), checkbox_pref(kluge_dragtool_state_prefs_key + "bla2", "(make it closed?)", dflt = False), ## ActionButton( world._cmd_Clear, "button: clear") # works # 070108: try this variant which uses _cmd_Clear_nontrivial: will the If work as an Expr?? If_kluge should tell us #####k ####k also will the type tests inside ActionButton work with an If? Probably not -- that's a ###BUG but I'll put it off. ## 1. make this work later: ActionButton( world._cmd_Clear, If_kluge( world._cmd_Clear_nontrivial, "button: clear", "button (disabled): clear")) ## 2. this too: If_kluge( world._cmd_Clear_nontrivial, ## ActionButton( world._cmd_Clear, "button: clear"), ## ActionButton( world._cmd_Clear, "button (disabled): clear") ## ) If_kluge( getattr_Expr( world, '_cmd_Clear_nontrivial'), ActionButton( world._cmd_Clear, "button: clear"), ActionButton( world._cmd_Clear, "button (disabled): clear", enabled = False) ) # works, though text change is so slow I suspect there's actually a highlighting or update bug making it appear even slower... # update 070109: the bug seems to be that as long as the mouse stays on the button, it remains highlighted with the old highlight form. ) return expr # end
NanoCAD-master
cad/src/exprs/demo_drag.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ testmode.py -- Command/GraphicsMode for testing graphical exprs (implemented in the exprs module). @author: Bruce @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. How to use: [see also exprs/README.txt, which is more up to date] [this symlink is no longer needed as of 061207:] make a symlink from ~/Nanorex/Modes/testmode.py to this file, i.e. % cd ~/Nanorex/Modes % ln -s /.../cad/src/exprs/testmode.py . then find testmode in the debug menu's custom modes submenu. It reloads testdraw.py on every click on empty space, so new drawing code can be tried by editing that file and clicking. (It also hides most of your toolbars, but you can get them back using the context menu on the Qt dock, or by changing to another mode, or customize this feature by editing the "annoyers" list below to leave out the toolbars you want to have remain.) WARNING: some of the code in here might not be needed; conversely, some of it might depend on code or data files bruce has at home. Much of it depends on the "cad/src/exprs" module, and some of that used to depend on the "cad/src/experimental/textures" directory. As of 070604 that's being changed to depend on a new subdirectory of cad/src/ui named exprs (so it will be supported in built releases). """ import time from geometry.VQT import V, Q ## from commands.BuildAtoms.depositMode import depositMode from utilities.debug import print_compact_traceback from utilities.debug_prefs import Choice_boolean_True from utilities.debug_prefs import Choice_boolean_False from utilities.debug_prefs import debug_pref annoyers = ['editToolbar', 'fileToolbar', 'helpToolbar', 'modifyToolbar', 'molecularDispToolbar', 'selectToolbar', 'simToolbar', ## 'toolsToolbar', # not sure why this is removed, maybe it no longer exists ## 'viewToolbar', # I often want this one ## one for modes too -- not sure of its name, but I guess I'll let it keep showing too ] ## superclass = depositMode from commands.SelectAtoms.SelectAtoms_Command import SelectAtoms_Command # [bruce 080825 split testmode into C & GM] _superclass_C = SelectAtoms_Command _superclass_for_GM = _superclass_C.GraphicsMode_class class testmode_GM(_superclass_for_GM): """ GraphicsMode for testing graphical exprs """ # class constants for GraphicsMode ## check_target_depth_fudge_factor = 0.0001 # same as GLPane, tho it caused a demo_drag bug 070115 -- try lower val sometime ###e if 0: check_target_depth_fudge_factor = 0.00001 # (in 'if 0'?) # this gives us another 10x safety factor in demo_drag [070116] # Unfortunately, this change helps *cause* a bug in which highlighting # "flickers" (works only on alternate frames) whenever renderText is # used (e.g. by View -> Rulers) in testmode. So I'm disabling it now. # For more info see the related change in exprs/test.py. # [bruce 081211] # unclassified (Command vs GraphicsMode) [guessing for GraphicsMode -- bruce 080825] backgroundColor = 103/256.0, 124/256.0, 53/256.0 compass_moved_in_from_corner = True # only works when compassPosition == UPPER_RIGHT; should set False in basicMode [revised 070110] _defeat_update_selobj_MMB_specialcase = True # 070224; overridden at runtime in some methods below ## UNKNOWN_SELOBJ = something... this is actually not set here (necessary for now) but a bit later in exprs/test.py [061218 kluge] ## # work around some of our superclass depositMode's dependence on having its particular PM ## # [now taken care of in depositMode itself] ## ## def pastable_element(self): # bruce 070921 ## "[overrides superclass method]" ## ## return self.propMgr.elementChooser.getElement() ## from elements import Carbon ## return Carbon # == def render_scene(self, glpane): # This is always called, and modifying it would let us revise the entire rendering algorithm however needed. # This encompasses almost everything done within a single paintGL call -- even the framebuffer clear! # For what it doesn't include, see GLPane.paintGL, which gets to its call of this quickly. if 0: glpane.render_scene() else: import exprs.testdraw as testdraw try: testdraw.render_scene(self, glpane) except: print_compact_traceback("exception in testdraw.render_scene ignored: ") return def Draw_preparation(self): self.command._background_object = None # Note: by resetting this at the start of Draw (by "Draw" I mean # the sequence of Draw_* methods into which the old Draw method # was split on 090310), we make sure that a new _background_object # set during Draw is only active for event handlers # when it was set during the most recent call of Draw # before they run. [bruce 090310 clarified old comment] import exprs.testdraw as testdraw try: testdraw.Draw_preparation(self, self.o, _superclass_for_GM) except: #e history message? print_compact_traceback("exception in testdraw.Draw_preparation ignored: ") return def Draw_model(self): import exprs.testdraw as testdraw try: testdraw.Draw_model(self, self.o, _superclass_for_GM) except: #e history message? print_compact_traceback("exception in testdraw.Draw_model ignored: ") return def Draw_other(self): import exprs.testdraw as testdraw try: testdraw.Draw_other(self, self.o, _superclass_for_GM) except: #e history message? print_compact_traceback("exception in testdraw.Draw_other ignored: ") return def Draw_after_highlighting(self, pickCheckOnly = False): #bruce 050610 # I'm very suspicious of this pickCheckOnly arg in the API... it's not even acceptable to some modes, # it's not clear whether they'll be called with it, it's not documented what it should do, # and there seems to be a return value when it's used, but not all methods provide one. # [update: I subsequently rationalized it, so it's now ok and explained in a comment somewhere] """ Do more drawing, after the main drawing code has completed its highlighting/stenciling for selobj. Caller will leave glstate in standard form for Draw. Implems are free to turn off depth buffer read or write. @warning: anything implems do to depth or stencil buffers will affect the standard selobj-check in bareMotion. """ ## _superclass_for_GM.Draw_after_highlighting(self, pickCheckOnly) # let testdraw do this if if wants to import exprs.testdraw as testdraw try: return testdraw.Draw_after_highlighting(self, pickCheckOnly, self.o, _superclass_for_GM) except: #e history message? print_compact_traceback("exception in testdraw.Draw_after_highlighting ignored: ") return def leftDown(self, event): import exprs.testdraw as testdraw try: testdraw.leftDown(self, event, self.o, _superclass_for_GM) # note: if _superclass_for_GM.leftDown and/or gl_update should be called now, this must do it. # note: this might reload testdraw (inside self.emptySpaceLeftDown). except: #e history message? print_compact_traceback("exception in testdraw.leftDown ignored: ") def leftDouble(self, event): # Note: added to testmode 070324. (See also selectMode.dragHandlerLeftDouble, which is never called -- # either it's obsolete, or this should be merged into selectMode.leftDouble and it should call that # and let that do the rest of what this does now.) # # Some issues: # - depositMode version deposits when in empty space; ours must not do that if there's a background object # (unless that object says to, somehow), but should otherwise. # - depositMode version sets "self.ignore_next_leftUp_event = True # Fixes bug 1467", # which I guess we should always set (even if not depositing) -- not sure. In theory, bg object should decide. # Also in theory, good code would never need this, since leftUp would only do things its leftDown asked it to do. # Guess: depositMode.leftUp doesn't follow that principle, and this flag works around that flaw by # "turning off an assumption about what leftDown did". # (For example (speculation), that it reset certain variables left over from prior drag??) self.ignore_next_leftUp_event = True # I'm guessing this is always necessary, though I'm not sure. # Note that it will prevent the call of drag_handler.ReleasedOn -- this seems desirable, # since the press method (leftClick) was not called either, for the 2nd click of a double click -- # and it's also the same behavior as before we added this implem of leftDouble. # However, minor ###BUG: the superclasses only reset it in leftUp -- if they were more cautious # they'd also do so in leftDown, in case of a missing (or buggily overidden) leftUp call. # (Or GLPane would, so not every mode class has to. Or it'd just call leftDoubleUp or so.) if self.drag_handler is not None: print "fyi: testmode passing leftDouble to drag_handler = %r" % (self.drag_handler,) #### # This works: it's a highlightable or a _background_object if we double-clicked on one, # and otherwise false (presumably None). # So when it's there, let's pass this event to it for handling, and not to the superclass. # (Note: most of the DragHandler interface is implemented in selectMode (see also DragHandler.py), # but this new method in it ('leftDouble') is implemented only in testmode.) method = getattr( self.drag_handler, 'leftDouble', None) if method is not None: method(event, self) #e protect from exceptions? else: print "fyi: testmode passing leftDouble to superclass (since no drag_handler)" #### _superclass_for_GM.leftDouble(self, event) return def get_obj_under_cursor(self, event): #070322 [assume part of GraphicsMode even though not in all subclasses of that] """ this is called in *some cases* by various event handler methods to find out what object the cursor is over """ # The kinds of calls of this method (whose interface assumptions we need to be sensitive to): # - depositMode.singletLeftUp indirectly calls it and checks whether the return value is an instance of Atom, # handling it specially if so. # - similarly, selectMode.atomLeftUp can indirectly call it and check whether it returns a non-singlet instance of Atom. # - its main call is in selectMode.leftDown to decide (based on the kind of object returned -- None, or anything which # hasattr 'leftClick', or being an instance of Atom or Bond or Jig) # which kind of more specialized leftDown method to call. # Note that this method is only called for leftDown or leftUp, never during a drag or baremotion, # so its speed is not all-important. That means it might be fast enough, even if it creates new Instances # (of exprs module classes) on each call. # WARNING: overriding this method doesn't override the lower-level determination of glpane.selobj, # which is also used directly by mode event-handling methods in a similar way as they use this method, # and is used in GLPane to determine hover-highlighting behavior (both between and within drags -- in fact, # there is not yet a good-enough way for hover-highlighting behavior to be different during a drag). # For some purposes, overriding the determination of selobj in GLPane would be more useful and more flexible # than overriding this method; to affect highlighting behavior, it would be essential. [070323 comment] res = _superclass_for_GM.get_obj_under_cursor(self, event) #e here is where we might let some other mode attr replace or wrap objects in specified classes. [070323 comment] if res is None: res = self.command._background_object # usually None, sometimes set during draw to something else [070322] if res is not None: if not hasattr(res, 'leftClick'): print "bug: testmode._background_object %r has no leftClick, will be ineffective" % (res,) return res def emptySpaceLeftDown(self, event): #e note: if we override self.get_obj_under_cursor(event) to return a bg object rather than None, # i.e. if something sets self.command._background_object to something other than None, # then this won't be called by selectMode.leftDown. emptySpace_reload = debug_pref("testmode: reload on empty space leftDown?", Choice_boolean_True, prefs_key = "A9 devel/testmode/reload on empty space leftDown" ) #070312, also in exprs/test.py if emptySpace_reload: self.command.reload() _superclass_for_GM.emptySpaceLeftDown(self, event) #e does testdraw need to intercept this? no... instead we override get_obj_under_cursor # let superclass do these -- no need to define them here and let testdraw intercept them: ## def leftDrag(self, event): ## pass ## ## def leftUp(self, event): ## pass # middle* event methods, defined here to permit "New motion UI" to be prototyped in testmode [bruce 070224]. # # Notes: there are 12 "middle" methods in all (4 key combos, and Down Drag Up), # tho for left & right buttons there are only 9 (since there is no ShiftCntl combo). # That doesn't bother selectMode since it ignores the ShiftCntl part of the methodname, # channelling them all together and later using glpane.modkeys to sort them out # (which does define a separate state for 'Shift+Control'). # But for capturing these middle # methods (i.e. Alt/Option button) for the "New motion UI", it's tougher -- we want to use # selectMode's ability to count a tiny drag as not a drag, to dispatch on selobj type # (Atom, Bond, Jig, DragHandler_API), and maybe more, so we need to turn these into left methods here, # but we need to add something like glpane.altkey to not forget they were really middle, # and then we need to modify selectMode to not think they are really left if this would mess it up # (which may only matter for Atom Bond Jig being visible in testmode) -- only for DragHandler would # it pass the event inside (and then we'd detect glpane.altkey inside Highlightable). # Either that, or we could actually implement the "New motion UI" directly inside selectMode, # for all objects. # Either way, we need extensive mods to selectMode, but that's just been split into new files # in Qt4 branch but not Qt3 branch, so it might be better to not do that now, either splitting it # in Qt3 the same way, or holding off until Qt4 is standard. # I guess there is one simpler way: ignore the issue of Atom Bond Jig being visible in testmode # (the bug will be that middle clicks on them act like left clicks) -- just turn middle into left, # don't tell selectMode, and worry only about the empty space or DragHandler cases. We can also # forget the ShiftCntl part at the same time. Ok, I'll try it! (It required a minor change in # selectMode, to notice a new attr _defeat_update_selobj_MMB_specialcase defined above.) # It was simpler before I added the debug_pref to turn it off! 3 distinct methods before, all 12 needed now. def _update_MMB_policy(self): "[private helper for middle* methods]" capture_MMB = debug_pref("testmode capture MMB", Choice_boolean_False, prefs_key = "A9 devel/testmode/testmode capture MMB") self._capture_MMB = self._defeat_update_selobj_MMB_specialcase = capture_MMB return def _middle_anything(self, event, methodname): "[private helper for middle* methods]" # glpane = self.o # print "%s: glpane.button = %r" % (methodname, glpane.button,) # 'MMB' for Down and Drag, None for Up, in singlet middleClick; when it's None, # Highlightable will just have to remember it from the middleDown or middleDrag [and now it does] self._update_MMB_policy() if self._capture_MMB: if methodname.endswith('Down'): _superclass_for_GM.leftDown(self, event) # don't go through self.leftDown for now -- it's only used for reload, gl_update, etc elif methodname.endswith('Drag'): _superclass_for_GM.leftDrag(self, event) elif methodname.endswith('Up'): _superclass_for_GM.leftUp(self, event) else: assert 0, "bad methodname %r" % (methodname,) else: method = getattr(_superclass_for_GM, methodname) method(self, event) return def middleDown(self, event): self._middle_anything( event, 'middleDown') def middleShiftDown(self, event): self._middle_anything( event, 'middleShiftDown') def middleCntlDown(self, event): self._middle_anything( event, 'middleCntlDown') def middleShiftCntlDown(self, event): self._middle_anything( event, 'middleShiftCntlDown') def middleDrag(self, event): self._middle_anything( event, 'middleDrag') def middleShiftDrag(self, event): self._middle_anything( event, 'middleShiftDrag') def middleCntlDrag(self, event): self._middle_anything( event, 'middleCntlDrag') def middleShiftCntlDrag(self, event): self._middle_anything( event, 'middleShiftCntlDrag') def middleUp(self, event): self._middle_anything( event, 'middleUp') def middleShiftUp(self, event): self._middle_anything( event, 'middleShiftUp') def middleCntlUp(self, event): self._middle_anything( event, 'middleCntlUp') def middleShiftCntlUp(self, event): self._middle_anything( event, 'middleShiftCntlUp') def keyPressEvent(self, event): try: key = event.key() except: # no one reported a problem with this, but we might as well be paranoid about it [bruce 070122] key = -1 if key == 32: pass ## self._please_exit_loop = True else: _superclass_for_GM.keyPressEvent(self, event) #060429 try to get ',' and '.' binding #bruce 070122 basicMode->superclass return def keyReleaseEvent(self, event): _superclass_for_GM.keyReleaseEvent(self, event) #bruce 070122 new feature (probably fixes some bugs), and basicMode->superclass ## # probably unused, but mentioned in real code, and might be added back (related to self.myloop): ## _please_exit_loop = False ## _in_loop = False ## _loop_start_time = 0 pass # end of class testmode_GM # == class testmode(_superclass_C): """ Command for testing graphical exprs """ # class constants for Command GraphicsMode_class = testmode_GM commandName = 'testmode' # must be same as module basename, for 'custom mode' featurename = "Test Command: Exprs Package" from utilities.constants import CL_ENVIRONMENT_PROVIDING command_level = CL_ENVIRONMENT_PROVIDING def reload(self): import exprs.testdraw as testdraw #bruce 070611 bugfix for release builds: add try/except try: reload(testdraw) except ImportError: pass # print "testdraw reload ImportError, ignoring" return _background_object = None #070322 new feature: can be set during Draw # to something to handle clicks on background # Note: this is stored in the Command instance, but usually accessed # from the GraphicsMode instance using .command._background_object. # [bruce 071010] if 0: ### TODO: port these methods to new command API! # the code works without it, but presumably some of these side effects # were desirable. [bruce 080929 comment, and 'if 0'] def Enter(self): print print "entering testmode again", time.asctime() self.reload() ## self.assy = self.w.assy # [now done by basicCommand] self.o.pov = V(0,0,0) self.o.quat = Q(1,0,0,0) res = _superclass_C.Enter(self) if 1: # new 070103; needs reload?? import exprs.testdraw as testdraw testdraw.end_of_Enter(self.o) return res def init_gui(self): #050528; revised 070123 ## self.w.modifyToolbar.hide() self.hidethese = hidethese = [] win = self.w for tbname in annoyers: try: try: tb = getattr(win, tbname) except AttributeError: # someone might rename one of them ## import __main__ if 0: ## __main__.USING_Qt3: # most of them are not defined in Qt4 so don't bother printing this then [bruce 070123] print "testmode: fyi: toolbar missing: %s" % tbname # someone might rename one of them else: if tb.isVisible(): # someone might make one not visible by default tb.hide() hidethese.append(tb) # only if hiding it was needed and claims it worked except: # bug print_compact_traceback("bug in hiding toolbar %r in testmode init_gui: " % tbname) continue return def restore_gui(self): #050528 ## self.w.modifyToolbar.show() for tb in self.hidethese: tb.show() def makeMenus(self): ### WARNING: this copies and slightly modifies selectMode.makeMenus (not those of our superclass, depositMode!); # with slightly more work, we could instead just decide when to call the superclass one here # vs. when not to, rather than duplicating the menu items it produces. # But we can't do that for now, since we want to ditch its general items # whenever there is a selobj which defines make_selobj_cmenu_items, # even when we add atom-specific ones it also hardcodes, # and later we may also decide to not ditch them if the selobj's make_selobj_cmenu_items returns nothing. # DANGER: if this copied code got changed for Qt4, we're introducing a Qt4 porting problem into testmode. # [bruce 070228] selatom, selobj = self.graphicsMode.update_selatom_and_selobj( None) # not doing: ## superclass.makeMenus(self) # this makes standard items for selobj if it's atom or bond or Highlightable, and a few more self.Menu_spec = [] # Local minimize [now called Adjust Atoms in history/Undo, Adjust <what> here and in selectMode -- mark & bruce 060705] # WARNING: This code is duplicated in depositMode.makeMenus(). mark 060314. if selatom is not None and not selatom.is_singlet() and self.w.simSetupAction.isEnabled(): # see comments in depositMode version self.Menu_spec.append(( 'Adjust atom %s' % selatom, lambda e1 = None, a = selatom: self.localmin(a,0) )) self.Menu_spec.append(( 'Adjust 1 layer', lambda e1 = None, a = selatom: self.localmin(a,1) )) self.Menu_spec.append(( 'Adjust 2 layers', lambda e1 = None, a = selatom: self.localmin(a,2) )) # selobj-specific menu items. [revised by bruce 060405; for more info see the same code in depositMode] if selobj is not None and hasattr(selobj, 'make_selobj_cmenu_items'): try: selobj.make_selobj_cmenu_items(self.Menu_spec) except: print_compact_traceback("bug: exception (ignored) in make_selobj_cmenu_items for %r: " % selobj) return # from makeMenus pass # end of class testmode # end
NanoCAD-master
cad/src/exprs/testmode.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ test_statearray.py @author: bruce @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. """ from exprs.Column import SimpleRow from exprs.Rect import Rect from exprs.Highlightable import Highlightable from exprs.Boxed import Boxed from exprs.Set import Set from utilities.constants import black, pink from exprs.Exprs import call_Expr from exprs.statearray import StateArrayRefs, StateArrayRefs_getitem_as_stateref from exprs.iterator_exprs import MapListToExpr, KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.attr_decl_macros import Arg from exprs.ExprsConstants import StateRef, Color from exprs.__Symbols__ import _self # == example 1 class _color_toggler(DelegatingInstanceOrExpr): ###WRONGnesses: # - Q: shouldn't we be toggling a flag or enum or int, and separately mapping that to a color to show? # A: Yes, unless we're for general raw color images -- but as a StateArray test this doesn't matter. # args color_ref = Arg(StateRef, doc = "stateref to a color variable") ###e can we tell StateRef what the value type should be? # appearance/behavior delegate = Boxed( Highlightable( Rect(1, 1, color_ref.value), on_press = Set( color_ref.value, call_Expr( _self.toggle_color, color_ref.value) ), sbar_text = "click to change color" #e give index in StateArray, let that be an arg? (if so, is it a fancy stateref option?) ), pixelgap = 0, #e rename -- but to what? bordergap? just gap? (change all gap options to being in pixels?) borderwidth = 1, ###BUG: some of these border edges are 2 pixels, depending on pixel alignment with actual screen bordercolor = black ) def toggle_color(self, color): r,g,b = color return (b,r,g) # this permits toggling through the cyclic color sequence red, green, blue in that order #e or we could rotate that color-cube on the same diagonal axis but less than 1/3 turn, # to get more colors, if we didn't mind renormalizing them etc... pass class test_StateArrayRefs(DelegatingInstanceOrExpr): ### has some WRONGnesses indices = range(10) colors = StateArrayRefs(Color, pink) #e i want an arg for the index set... maybe even the initial set, or total set, so i can iter over it... # NOTE: at least one dictlike class has that feature - review the ones in py_utils, see what _CK_ uses def _color_toggler_for_index(self, index):#e should we use _CV_ for this?? if not, it must be too hard to use!!! #k or is it that it defines a dict rather than a func, but we need a func in MapListToExpr? stateref = StateArrayRefs_getitem_as_stateref( self.colors, index ) newindex = ('_color_toggler_for_index', index) return self.Instance( _color_toggler( stateref), newindex ) delegate = MapListToExpr( _self._color_toggler_for_index, ###k _self needed?? indices, KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr(SimpleRow) ) pass # end
NanoCAD-master
cad/src/exprs/test_statearray.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ demo_MT.py - demo of "model tree in GLPane" (primitive, but works) @author: bruce @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. ### WARNING: the rest of this docstring has not been reviewed since before MT_try2 was implemented and MT_try1 was moved into an outtakes file, demo_MT_try1_obs.py. Some of the comments in this file may belong in that outtakes file rather than here. [070210] works in testexpr_18 warning: *not* being used in test.py's top_left_corner [as of 070105 anyway], that's something else that looks the same -- but on 070206 it is now being used there... bugs to fix: - overlay highlight bug (gray hides plus sign -- for best way to fix, see notesfile 070105) - updating - see "nim issues" comment below nfrs: - use DisplayListChunk - see "needed polish" comment below, etc [renamed from MT_demo.py, 070106] """ #todo 070208: # cleanup: # - move the new one to top left (try2 on new model) (depends on particular testexpr to find model) # - move deprecated MT_try1 into an outtakes file to avoid confusion (maybe a loadable one so testexpr_18 & _30h still works) # - start out being open at the top # +? turn off debug prints # - reorder args to _try2 helper classes # - make helper classes attrs of main MT_try2 (rather than globals) # demo: # - cross-highlighting # polish: # - alignment bug (openclose vs other parts of row in item) # - type icons # - openclose needs a triangle too, so mac ppl can understand it # someday: # - implem type coercion and use it to let anything work as a node # - move Interface to its own file # - make ModelTreeNodeInterface real and use it for that # - autoupdate for legacy nodes # - permit_expr_to_vary inval during recompute logic bug: (in instance_helpers, but made use of here) # - verify it by test (maybe no bug in MT_try2, so the test is a new class designed to hit the bug) # - fix it -- see comments where it's defined #e stub, but works in test.py: ## # demo_MT ## ###e need better error message when I accidently pass _self rather than _my] ## testexpr_18 = MT_try1( _my.env.glpane.assy.part.topnode ) # works! except for ugliness, slowness, and need for manual update by reloading. # biggest nim issues [some marked with ####]: [solved just barely enough for testexpr_18] # - where to put a caching map from kidnode, args to MT(kidnode, args) # - note, that's a general issue for any "external data editor" # where the node is the external data and MT is our preferred-edit-method # - does the scheme used for _texture_holder make sense? ###k # - should the usual place for maps like this be explicit MemoDicts located in self.env?? ###k # by "like this" I mean, maps from objects to fancier things used to interface to them, potentially shared. # - how similar is this to the map by a ColumnList from a kid fixed_type_instance to CLE(that instance)? # - guess: it can be identical if we specify what ought to be included in the map-key, i.e. when to share. # If that includes "my ipath" or "my serno" (my = the instance), it can act like a local dict (except for weakref issues). # - where & how to register class MT as the "default ModelTree viewer for Node", # [note 070206: that class MT is not MT_try1 -- that's a helper expr for a whole-MT exprhead, which is nim] # where 'ModelTree' is basically a general style or place of viewing, and Node is a type of data the user might need to view that way? # And in viewing a kid (inside this class), do we go through that central system to create the viewer for it, passing it enough env # that it's likely to choose the same MT class to view a kid of a node and that node, but not making this unavoidable? [guess: yes. ##k] # Note: if so, this has a lot to say about the viewer-caching question mentioned above. # Note: one benefit of that central system is to help with handling other requests for an "obj -> open view of it" map, # like for cross-highlighting, or to implem "get me either an existing or new ModelTree viewer for this obj, existing preferred". # These need a more explicit ref from any obj to its open viewers than just their presumed observer-dependency provides. # Note that the key might be more general for some purposes than others, e.g. I'll take an existing viewer even if it was opened # using prefs different than I'd use to make a new one. I'm not sure if any one cache needs more than one key-scheme applicable to # one value-slot. Let's try to avoid that for now, except for not excluding it in the general architecture of the APIs. # - arg semantics for Node # - or for time-varying node.MT_kids() (can be ignored for now) # complicated details: # - usage/mod tracking of node.open, node.MT_kids() # [maybe best to redo node, or use a proxy... in future all model objs need this natively] # - for an initial demo, do it read-only, i.e. don't bother tracking changes by others to external state # needed polish: # - better fonts - from screenshots of NE1 or Safari? # - appearing selected # - italic, for disabled # - current-part indicator # - transparency # opportunities for new features: # - cross-highlighting -- mouseover an atom, chunk, jig, or MT chunk or jig, highlights the others too, differently # - does require realtime changetracking, *but* could be demoed on entirely new data rather than Node, # *or* could justify adding new specialcase tracking code into Node, Atom, Bond. # small nims: # - map_Expr # - mt_instance = MT_try1(obj) # with arg1 being already instantiated, this should make an instance ###IMPLEM that #k first be sure it's right # #e more?? # === ### WARNING: the comments above this line have not been reviewed since before MT_try2 was implemented # and MT_try1 was moved into an outtakes file, demo_MT_try1_obs.py. Some of them # may belong in that outtakes file rather than here, or maybe be entirely obs even there. [070210] ### # == imports from utilities.constants import blue, green, ave_colors, white from utilities.debug import print_compact_traceback from utilities.debug import safe_repr from exprs.Highlightable import Highlightable from exprs.TextRect import TextRect from exprs.Column import SimpleRow, SimpleColumn from exprs.Overlay import Overlay from exprs.Set import Set from exprs.Rect import Rect, Spacer from exprs.images import Image from exprs.Center import CenterY, Center from exprs.transforms import Translate from exprs.projection import DrawInCenter #e but what we need is not those, but DrawInAbsCoords or DrawInThingsCoords # or really, just get the place (or places) a thing will draw in, in local coords (see projection.py for more discussion) from exprs.DisplayListChunk import DisplayListChunk from exprs.Exprs import call_Expr, list_Expr, getattr_Expr, not_Expr, format_Expr from exprs.Exprs import is_expr_Instance from exprs.Exprs import is_Expr from exprs.If_expr import If from exprs.widget2d import Stub from exprs.iterator_exprs import MapListToExpr from exprs.iterator_exprs import KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr from exprs.attr_decl_macros import Option, State, Arg from exprs.instance_helpers import DelegatingInstanceOrExpr, ModelObject, InstanceMacro from exprs.ExprsConstants import StubType from exprs.py_utils import identity from exprs.__Symbols__ import Anything, _self # == ##e prototype, experimental definition of an Interface # (all use of which nim, and it's a stub anyway -- but intended to become real). [070207] class Interface: """ ###doc Note: most InstanceOrExpr interfaces (e.g. ModelTreeNodeInterface) consists of attrs (recomputable, tracked), not methods, to make it easier and more concise to give formulae for them when defining how some IorE subclass should satisfy the interface. If you want to define them with methods in a particular case, use the standard compute method prefix _C_, e.g. def _C_mt_kids(self): return a sequence of the MT_kids (which the caller promises it will not try to modify). or mt_kids = formulae for sequence of MT_kids This means that to tell if a node follows this interface, until we introduce a new formalism for that [#e as we should], or a way to ask whether a given attr is available (perhaps for recomputation) without getting its value [#e as we should], you may not be able to avoid getting the current value of at least one attr unique to the interface. ### DESIGN FLAW It also means that a text search for all implems of the interface attr should search for _C_attr as well as attr (if it's a whole-word search). Attr names: the interface attrnames in ModelTreeNodeInterface all start with mt_ as a convention, for several reasons: - less chance of interference with attrs in other interfaces supported by the same objects, or with attrs already present locally in some class; - less chance of accidental reuse in a subclass of a class that inherits the interface; - more specific name for text search; - to make it more obvious that their defs might be part of a definite interface (and give a hint about finding it). """ pass ###e STUB Attr = Option ###e STUB -- an attr the interface client can ask for (with its type, default value or formula, docstring) StateAttr = State ###e STUB -- implies that the interface client can set the attr as well as getting it, # and type coercion to the interface might create state as needed to support that (if it's clear how to do that correctly) Id = StubType class ModelTreeNodeInterface(Interface): """ Interface for a model tree node (something which can show up in a model tree view). Includes default compute method implems for use by type-coercion [which is nim] [see also ModelTreeNode_trivial_glue, and the node_xxx helper functions far below, for related code]. WARNING: this class, itself, is not yet used except as a place to put this docstring. But the interface it describes is already in use, as a protocol involving the attrs described here. """ _object = Arg(Anything, doc = "an object we want to coerce into supporting this interface") ###k?? #e does it have to sound so nasty? # the recompute attrs in the interface, declared using Attr [nim] so they can include types and docstrings mt_node_id = Attr( Id, call_Expr( id, _object), doc = "a unique nonrecyclable id for the node that object represents") ###BUG: id is wrong -- ipath would be closer (but is not really correct, see comments in def mt_node_id) mt_name = StateAttr( str, "", doc = "the name of a node in the MT; settable by the MT view (since editable in that UI)") mt_kids = Attr( list_Expr, (), doc = "the list of visible kids, of all types, in order (client MT view will filter them)") mt_openable = Attr( bool, False, doc = "whether this node should be shown as openable; if False, mt_kids is not asked for") ##e (consider varying mt_openable default if node defines mt_kids, even if the sequence is empty) # (##e nothing here yet for type icons) pass # some existing interfaces we might like to clean up and formalize: # - "selobj interface" (from GLPane to a hover-highlighted object; provided by Highlightable) # - "DragHandler interface (from selectMode to an object that handles its own mouse clicks/drags; see class DragHandler_API) # # some new interfaces we'd like: # - many of the types used in Arg(type, x) are really interfaces, e.g. ModelObject # (which may have variants. eg movable or not, geometric or not, 3d or not -- some of these are like orthogonal interfaces # since graphical decorating wrappers (eg Overlay, Column) might provide them too) # - Draggable (something that provides _cmd_drag_from_to) # - ModelTreeNodeInterface # - whatever is needed to be dragged by DraggableObject # - Drawable (whatever is needed to be drawn -- may have variants, may apply to POV-Ray too) # == # the following ModelTreeNode_trivial_glue example is not yet used, but it points out that default formula for interface attrs # would often like to refer to the object they're trying to type-coerce (in this case, to use its classname to init new state). class ModelTreeNode_trivial_glue(DelegatingInstanceOrExpr): #070206, 070207 # args delegate = Arg(ModelObject) # default formulae for ModelTreeNodeInterface -- including one which supplies new state mt_name = State(str, getattr_Expr(getattr_Expr(delegate, '__class__'), '__name__')) ###k #e type - grab it from object, or related to role in parent... mt_kids = () mt_openable = False ###e something for mt_node_id pass # == # define some helper functions which can apply either the new ModelTreeNodeInterface or the legacy Utility.Node interface # to node, or supply defaults permitting any object to show up in the MT. # ###BUG: they decide which interface to use for each attr independently, but the correct way is to decide for all attrs at once. # shouldn't matter for now, though it means defining mt_kids is not enough, you need mt_openable too # (note that no automatic type coercion is yet implemented, so nothing ever yet uses # the default formulae in class ModelTreeNodeInterface). def node_kids(node): # revised 070207 # REVIEW: rename to something like node_MT_kids? [bruce 080108 comment] """ return the kid list of the node, regardless of which model tree node interface it's trying to use [slight kluge] """ try: node.mt_kids # look for (value computed by) ModelTreeNodeInterface method except AttributeError: pass else: return node.mt_kids try: node.MT_kids # look for legacy Node method except AttributeError: pass else: return node.MT_kids() return () # give up and assume it has no MT_kids def node_openable(node): # revised 070207 """ return the openable property of the node, regardless of which model tree node interface it's trying to use [slight kluge] """ try: node.mt_openable # look for (value computed by) ModelTreeNodeInterface method except AttributeError: pass else: return node.mt_openable try: node.openable # look for legacy Node method except AttributeError: pass else: return node.openable() ###k return False # give up and assume it's not openable (as the default formula for mt_openable would have us do) ##e (consider varying this if node defines mt_kids or kids, even if they are empty) def node_name(node): # revised 070207 """ return the name property of the node, regardless of which model tree node interface it's trying to use [slight kluge] """ try: node.mt_name # look for (value computed by) ModelTreeNodeInterface method except AttributeError: pass else: return node.mt_name try: node.name # look for legacy Node variable except AttributeError: pass else: return node.name try: return "%s" % node except: last_resort = safe_repr(node, maxlen = 20) ### FIX: Undefined variable safe_repr, print_compact_traceback print_compact_traceback("node_name fails when trying %%s on node %s: " % last_resort ) return last_resort pass print_mt_node_id = False # set True for debugging (or remove in a few days [070218]) def mt_node_id(node): # 070207; the name 'node_id' itself conflicts with a function in Utility.py (which we import and use here, btw) """ return the mt_node_id property of the node, regardless of which model tree node interface it's trying to use [slight kluge] """ # look for value of ModelTreeNodeInterface attr try: node.mt_node_id except AttributeError: pass else: if print_mt_node_id: print "this node %r has mt_node_id %r" % (node,node.mt_node_id) # old Q: where do our Rects get it? # A: they don't -- the bug fixed by bugfix070218 meant this was never called except for World!! # [note: on 070302 the comments about bugfix070218, and the code affected by it, was rewritten and removed # (becoming MapListToExpr). # it might still be in an outtakes file not in cvs on bruce's g5 -- or in cvs rev 1.21 or earlier of this file.] # btw, we want it to be for the # underlying model object... sort of like how we ask for name or type... [bug noticed 070218 late; see below comment] return node.mt_node_id ## assert not is_expr_Instance(node), "what node is this? %r" % (node,) # most to the point if is_expr_Instance(node): # All Instances ought to have that, or delegate to something which does -- which ought to be their contained ModelObject. ####FIX SOMETIME (implem that properly) # Until that's implemented properly (hard now -- see _e_model_type_you_make for the hoops you have to jump thru now), # use the ipath (non-ideal, since captures wrappers like Draggable etc, but tolerable, # esp since this effectively means use the world-index, which will work ok for now [070218 late]) return node.ipath ###e should intern it as optim assert not is_Expr(node), "pure exprs like %r don't belong as nodes in the model tree" % (node,) # look for legacy Node property from foundation.Utility import node_id res = node_id(node) # not sure what to do if this fails -- let it be an error for now -- consider using id(node) if we need to if print_mt_node_id: print "legacy node %r has effective mt_node_id %r" % (node,res) return res def mt_node_selected(node): #070216 experiment """ #doc """ # look for value of ModelTreeNodeInterface attr (note: lots of objs don't have this; it's also #WRONG(?), should ask the env) try: node.selected except AttributeError: pass else: return node.selected # look for legacy Node property try: node.picked except AttributeError: pass else: return node.picked return False # === ModelNode = ModelObject ###stub -- should mean "something that satisfies (aka supports) ModelNodeInterface" class MT_try2(DelegatingInstanceOrExpr): # works on assy.part.topnode in testexpr_18i, and on World in testexpr_30i """ Model Tree view, using the argument as the top node. Has its own openclose state independent of other instances of MT_try2, MT_try1, or the nodes themselves. Works on IorE subclasses which support ModelTreeNodeInterface, or on legacy nodes (assy.part.topnode), but as of 070208 has no way to be notified of changes to legacy nodes (e.g. openclose state or MT_kids or name). Has minor issues listed in "todo" comment [070208] at top of source file. [This is the official version of a "model tree view" in the exprs package as of 070208; replaces deprecated MT_try1.] """ arg = Arg(ModelNode, doc = "the toplevel node of this MT view (fixed; no provision yet for a toplevel *list* of nodes #e)") #e could let creator supply a nonstandard way to get mt-items (mt node views) for nodes shown in this MT def _C__delegate(self): # apply our node viewer to our arg return self.MT_item_for_object(self.arg, initial_open = True) # note: this option to self.MT_item_for_object also works here, if desired: name_suffix = " (MT_try2)" ## no longer needed after bugfix070218: name_suffix = " (slow when open!)" def MT_item_for_object(self, object, name_suffix = "", initial_open = False): "find or make a viewer for object in the form of an MT item for use in self" ###e optim: avoid redoing some of the following when we already have a viewer for this object -- # but to find out if we have one, we probably can't avoid getting far enough in the following to get mt_node_id(object) # to use as index (since even id(object) being the same as one we know, does not guarantee mt_node_id(object) is the same -- # unless we keep a reference to object, which I suppose we could do -- hmm... #k #e), # which means coercing object enough into ModelNodeInterface to tell us its mt_node_id. # Maybe try to make that fast by making most of it lazily done? # #e coerce object into supporting ModelNodeInterface object = identity(object) ###e STUB: just assume it already does support it index = ('MT_item_for_object', mt_node_id(object)) # note: the constant string in the index is to avoid confusion with Arg & Instance indices; # it would be supplied automatically if we made this using InstanceDict [nim] #e ###e if nodes could have >1 parent, we'd need to include parent node in index -- only sufficient if some # nodes have to be closed under some conds not spelled out here (I think: at most one MT item for a given node # is open at a time ###k) -- otherwise the entire root-parents-node path might be needed in the index, # at least to permit nonshared openness bit of each separately drawn mt item, which is strongly desired # (since we might like them to interact, but not by being shared -- rather, by opening one view of a node closing # its other views) expr = _MT_try2_node_helper(object, self, name_suffix = name_suffix, initial_open = initial_open) ###BUG: if object differs but its mt_node_id is the same, the Instance expr sameness check might complain!!! # Can this happen?? (or does it only happen when self is also not the same, so it's not a problem?) #k ##e optim: have variant of Instance in which we pass a constant expr-maker, only used if index is new # WARNING: if we do that, it would remove the errorcheck of whether this expr is the same as any prior one at same index return self.Instance( expr, index) ###k arg order -- def Instance pass # end of class MT_try2 class _MT_try2_kids_helper(DelegatingInstanceOrExpr): # rewrote this 070302 (splitting out older one's alg as MapListToExpr) -- works! """ [private helper expr class for MT_try2] One MT item kidlist view -- specific to one instance of _MT_try2_node_helper. [#e if we generalize MT_try2 to support a time-varying list of toplevel nodes, then we might use one of these at the top, instead of using a single node at the top -- but more likely a variant of this (at least passing it an option), to turn off anything it might display in the left which only makes sense when it's elts are under a common parent node.] """ # args kids = Arg( list_Expr, doc = "the sequence of 0 or more kid nodes to show (after filtering, reordering, etc, by _self.mt)") mt = Arg( MT_try2, doc = "the whole MT view (for central storage and prefs)") ###e let this be first arg, like self is for methods?? parent_item = Arg( mt._MT_try2_node_helper, None, doc = "the parent node item for these kid nodes") #k needed?? # formulae delegate = MapListToExpr( mt.MT_item_for_object, kids, KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr(SimpleColumn) ) pass class _MT_try2_node_helper(DelegatingInstanceOrExpr): """ [private helper expr class for MT_try2] One MT item view -- specific to one node, one whole MT, and one (possibly time-varying) position with it. """ # args ####e REORDER THEM node = Arg(ModelNode, doc = "any node that needs to be displayed in this MT") ###e NOTE: type coercion to this is nim; while that's true, we use helper functions like node_name(node) below; # once type coercion is implemented # (or simulated by hand by wrapping this arg with a helper expr like ModelTreeNode_trivial_glue), # we could instead use node.mt_name, etc.) mt = Arg(MT_try2, doc = "the whole MT view, in which we store MT items for nodes, and keep other central state or prefs if needed") name_suffix = Option(str, "") initial_open = Option(bool, False, doc = "initial value of boolean state 'open'; only used when this item is first created") ##e should ask the node itself for the initial value of open (e.g. so new groups, trying to start open, can do so), # and also advise it when we open/close it, in case it wants to make that state persistent in some manner # WARNING: compare to MT_try1 -- lots of copied code after this point # WARNING: the comments are also copied, and not yet reviewed much for their new context! (so they could be wrong or obs) ###k # state refs open = State(bool, initial_open) # other formulae ###e optim: some of these could have shared instances over this class, since they don't depend on _self; should autodetect this # Note, + means openable (ie closed), - means closable (ie open) -- this is the Windows convention (I guess; not sure about Linux) # and until now I had them reversed. This is defined in two files and in more than one place in one of them. [bruce 070123] open_icon = Overlay(Rect(0.4), TextRect('-',1,1)) closed_icon = Overlay(Rect(0.4), TextRect('+',1,1)) openclose_spacer = Spacer(0.4) #e or Invisible(open_icon); otoh that's no simpler, since open_icon & closed_icon have to be same size anyway # the openclose icon, when open or close is visible (i.e. for openable nodes) openclose_visible = Highlightable( If( open, open_icon, closed_icon ), on_press = Set(open, not_Expr(open)), sbar_text = getattr_Expr( _self, '_e_serno') #070301 this permits finding out how often MT gets remade/shared # (results as of 070301: remade when main instance is, even if going back to a prior testexpr, out of _19i & _30i) ) openclose_slot = If( call_Expr(node_openable, node), openclose_visible, openclose_spacer ) if 0: # cross-highlighting experiment, 070210, but disabled since approach seems wrong (as explained in comment) yellow = DZ = 'need to import these' indicator_over_obj_center = Center(Rect(0.4, 0.4, yellow)) position_over_obj_center = node.center + DZ * 3 ###BUG: DZ does not point towards screen if trackballing was done ###STUB: # - should be drawn in a fixed close-to-screen plane, or cov plane (if obscuring is not an issue), # - so indicator size is constant in pixels, even in perspective view (I guess), # - also so it's not obscured (especially by node itself) -- or, draw it in a way visible behind obscuring things (might be a better feature) # - what we draw here should depend on what node is # - we also want to draw a line from type icon to node indicator (requires transforming coords differently) # - needs to work if node.center is not defined (use getattr_Expr - but what dflt? or use some Ifs about it) pointer_to_obj = DrawInCenter( Translate( indicator_over_obj_center, position_over_obj_center)) #bug: Translate gets neutralized by DrawInCorner [fixed now] ###BUG: fundamentally wrong -- wrong coord system. We wanted DrawInAbsCoords or really DrawInThingsCoords, # but this is not well-defined (if thing drawn multiply) or easy (see comments about the idea in projection.py). else: # What we want instead is to set a variable which affects how the obj is drawn. # If this was something all objs compared themselves to, then all objs would track its use (when they compared) # and therefore want to redraw when we changed it! Instead we need only the involved objs (old & new value) to redraw, # so we need a dict from obj to this flag (drawing prefs set by this MT). Maybe the app would pass this dict to MT_try2 # as an argument. It would be a dict of individually trackable state elements. (Key could be node_id, I guess.) # ### TRY IT SOMETIME -- for now, cross-highlighting experiment is disabled. pointer_to_obj = None # selection indications can use this node_is_selected = call_Expr( mt_node_selected, node) kluge_icon_color = If( node_is_selected, blue, green) sbar_format_for_name = If( node_is_selected, "%s (selected)", "%s") ###STUB for the type_icon ##e the Highlightable would be useful on the label too icon = Highlightable( Rect(0.4, 0.4, kluge_icon_color), ##stub; btw, would be easy to make color show hiddenness or type, bfr real icons work Overlay( Rect(0.4, 0.4, ave_colors(0.1, white, kluge_icon_color)), #070216 mix white into the color like DraggableObject does pointer_to_obj ), sbar_text = format_Expr( sbar_format_for_name, call_Expr(node_name, node) ) ) ##e selection behavior too label = DisplayListChunk( # added DisplayListChunk 070213 late -- does it speed it up? not much; big new-item slowness bug remains. retain, since doesn't hurt. TextRect( call_Expr(node_name, node) + name_suffix ) ) ###e will need revision to Node or proxy for it, so node.name is usage/mod-tracked ##e selection behavior too -- #e probably not in these items but in the surrounding Row (incl invis bg? maybe not, in case model appears behind it!) ##e italic for disabled nodes ##e support cmenu delegate = SimpleRow( CenterY(openclose_slot), SimpleColumn( SimpleRow(CenterY(icon), CenterY(label)), #070124 added CenterY, hoping to improve text pixel alignment (after drawfont2 improvements) -- doesn't work If( open, _MT_try2_kids_helper( call_Expr(node_kids, node) , _self.mt ), # 070218 added _self.mt -- always intended, first used now None # Note: this None used to be Spacer(0), due to a bug mentioned in a comment in ToggleShow.py # (but unfortunately not explained there -- it just says "I wanted None here, but it exposes a logic bug, # not trivial to fix, discuss in If or Column" -- my recollected bug-theory is described just below). # On 070302 I confirmed that None seems to work (even in testexpr_18i with a group of 2 chunks, plus two more below). # I don't fully know why it works, since I thought the bug was that SimpleColumn's None specialcase # didn't run, since the element was not None but the If, and then delegating lbox attrs to None didn't work. # (Fixable by using the newer If that evals, but for some reason that's not yet standard, I guess just because # I didn't have time to test it enough or think it through fully re ipath or instance caching or something.) # But as long as it works, use it -- ask Qs later. A recent perhaps-related change: None is allowed in drawkid. # (A memory scrap -- does instantiating None conceivably produce a spacer?? ###k) ) ) ) pass # end of class _MT_try2_node_helper # == # note: this predates MT_try2, but it's not moved into demo_MT_try1_obs.py since it might still be used someday. [070210] Node = Stub # [later note 061215: this is probably the same as Utility.Node; # it's NOT the same as that's new subclass, ModelNode in ModelNode.py.] class test_drag_pixmap(InstanceMacro): mt = Arg(Anything) # pass _my.env.glpane.assy.w.mt node = Arg(Node) # pass the topnode def _C__value(self): mt = self.mt # fails, recursion in self.delegate computation -- why? related to parent AttributeError: win? must be. ###e NEED BETTER ERROR MESSAGE from exception when computing self.mt by formula from caller. # It did have the attrerror, but buried under (and then followed by) too much other stuff (not stopping) to notice. node = self.node pixmap = mt.get_pixmap_for_dragging_nodes('move', [node]) # (drag_type, nodes); method defined in TreeWidget.py #e includes "moving n items", need to make it leave that out if I pass None for drag_type print pixmap # <constants.qt.QPixmap object at 0x10fbc2a0> #e make Image (texture) from pixmap -- how? # - pass the pixmap into ImageUtils somehow (won't be hard, could go in in place of the filename) # - worry about how it works in our texture-caching key (won't be hard) # - teach ImageUtils how to get a PIL image or equivalent data from it -- requires learning about QPixmap, image formats # MAYBE NOT WORTH IT FOR NOW, since I can get the icons anyway, and for text I'd rather have a Qt-independent path anyway, # if I can find one -- tho I predict I'll eventually want this one too, so we can make GL text look the same as Qt text. # Note: PixelGrabber shows how to go in the reverse direction, from GL to Qt image. # Guess: QPixmap or QImage docs will tell me a solution to this. So when I want nice text it might be the quickest way. # (Also worth trying PIL's builtin text-image makers, but I'm not sure if we have them in NE1 even tho we have PIL.) # The other way is to grab actual screenshots (of whatever) and make my own font-like images. Not ideal, re user-reconfig # of font or its size! # # Here are hints towards using Qt: turn it into QImage, which boasts # "The QImage class provides a hardware-independent pixmap representation with direct access to the pixel data." # and then extract the data -- not yet known how much of this PyQt can do. # # - QImage QPixmap::convertToImage () const # ##uchar * QImage::scanLine ( int i ) const ## ##Returns a pointer to the pixel data at the scanline with index i. The first ##scanline is at index 0. ## ##The scanline data is aligned on a 32-bit boundary. ## ##Warning: If you are accessing 32-bpp image data, cast the returned pointer ##to QRgb* (QRgb has a 32-bit size) and use it to read/write the pixel value. ##You cannot use the uchar* pointer directly, because the pixel format depends ##on the byte order on the underlying platform. Hint: use qRed(), qGreen() and ##qBlue(), etc. (qcolor.h) to access the pixels. image = pixmap.convertToImage() print image # <constants.qt.QImage object at 0x10fe1900> print "scanlines 0 and 1 are", image.scanLine(0), image.scanLine(1) # <sip.voidptr object at 0x5f130> <sip.voidptr object at 0x5f130> -- hmm, same address print "image.bits() is",image.bits() # image.bits() is <sip.voidptr object at 0x5f130> -- also same address print "\n*** still same address when all collected at once?:" # no. good. objs = [image.scanLine(0), image.scanLine(1), image.bits()] for obj in objs: print obj print # but what can i do with a <sip.voidptr object>? Can Python buffers help?? Can PIL use it somehow?? # Or do I have to write a C routine? Or can I pass it directly to OpenGL as texture data, if I get the format right? # Hmm, maybe look for Qt/OpenGL example code doing this, even if in C. ##e _value = Image( "notfound") env = self.env ipath = self.ipath return _value._e_eval( env, ('v', ipath)) # 'v' is wrong, self.env is guess ## AssertionError: recursion in self.delegate computation in <test_drag_pixmap#15786(i)> -- in pixmap set above pass # end
NanoCAD-master
cad/src/exprs/demo_MT.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Overlay.py @author: bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. """ from exprs.TextRect import TextRect from exprs.Rect import Spacer from exprs.attr_decl_macros import Arg from exprs.instance_helpers import InstanceOrExpr, DelegatingMixin from exprs.widget2d import Widget2D from exprs.Exprs import list_Expr, and_Expr, or_Expr class Overlay(InstanceOrExpr, DelegatingMixin): "Overlay has the size of its first arg, but draws all its args in the same place, with the same origin." # Note: we can't inherit from Widget2D, or we'd fail to delegate # e.g. bright to self.delegate, and pick up the default value instead! # I'm not yet sure whether the proper fix is to handle those defaults in some other way # (e.g. as a last-resort delegate of some sort -- maybe we could say right here (to a fancier # version of DelegatingMixin), if you don't find the attr in self.delegate, look in Widget2D). # See also comments in InstanceMacro, about the same issue for it. # [061210 grabbing SimpleColumn's scheme for permitting up to 10 args, though ArgList is nim] a0 = Arg(Widget2D, None) # so it's not a bug to call it with no args, as when applying it to a list of no elts [061205] a1 = Arg(Widget2D, None) a2 = Arg(Widget2D, None) a3 = Arg(Widget2D, None) a4 = Arg(Widget2D, None) a5 = Arg(Widget2D, None) a6 = Arg(Widget2D, None) a7 = Arg(Widget2D, None) a8 = Arg(Widget2D, None) a9 = Arg(Widget2D, None) a10 = Arg(Widget2D, None) a11 = Arg(Widget2D, None) args = list_Expr(a0,a1,a2,a3,a4,a5, a6,a7,a8,a9,a10, # could say or_Expr(a0, Spacer(0)) but here is not where it matters and_Expr(a11, TextRect("too many args in Overlay")) ) delegate = or_Expr(a0, Spacer(0)) ## _self.a0 # needed by DelegatingMixin ## args = list_Expr(arg0, arg1) # not sure if [arg0, arg1] would work, but I doubt it -- ###e should make it work sometime, if possible (e.g. by delving inside all literal list ns-values in ExprsMeta) #e add an option to make each element slightly closer, maybe just as a depth increment? makes hover highlighting more complicated... def draw(self): args = self.args # this order is correct since we set glDepthFunc to GL_LEQUAL (not GL_LESS) for a in args: self.drawkid( a) #e We'd like this to work properly for little filled polys drawn over big ones. # We might need something like z translation or depth offset or "decal mode"(??). # [later 070404: "decal mode" is probably unrelated -- GL_DECAL is for combining a texture with a non-textured color/alpha, # not related to using depth buffer when resulting textured object is drawn. Is "decal" used to mean anything else?? #k] # Different depth test would be best [done now -- GL_LEQUAL], but roundoff error might make it wrong... # This is definitely needed for overdrawing like that to work, but it's low priority for now. # Callers can kluge it using Closer, though that's imperfect in perspective mode (or when viewpoint is rotated). # [Or glDepthRange, now used for highlight drawing in GLPane as of 070921.] pass # Overlay # obs cmt from when we mistakenly inherited from Widget2D: # #e remove '2D' so it can work in 3D too? if so, need type inference that also delegates?? #e see also FilledSquare # end
NanoCAD-master
cad/src/exprs/Overlay.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ transforms.py - provide Translate [and more later] @author: Bruce @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. Translate was developed in Center.py, split out of that 061115 plan: include things like Rotate and Closer see also Rotated and Closer in testdraw1, for sample opengl code, showing how simple it ought to be (except that makes no provision for highlighting, which i need to do using move methods or the equiv) """ ##k [obs cmt? strongly guess yes 061115, but need to test:] # it doesn't work yet to actually delegate, eg for lbox attrs, # so I don't think using an Overlay inside another one would work right now from math import pi from OpenGL.GL import glTranslatef, glPushMatrix, glRotatef, glPopMatrix from exprs.attr_decl_macros import Arg from exprs.instance_helpers import InstanceOrExpr, DelegatingMixin, DelegatingInstanceOrExpr from exprs.widget2d import Widget from exprs.Exprs import call_Expr from exprs.ExprsConstants import Vector, Quat, ORIGIN from exprs.__Symbols__ import _self ###e [semiobs cmt:] # these vec routines are not best.. what's best is to turn into (not away from) numeric arrays, for their convenience. # guess: convention should be to always pass 3dim numeric arrays, and keep 3dim bboxes. # let 2d routines not use z but still have it, that way same code can do 2d & 3d stuff, no constant checks for len 2 vecs, etc. # but the above is nim in this code. def tuple3_from_vec(vec): #stub, but might be enough for awhile "turn all kinds of 2D or 3D vecs (tuples or Numeric arrays of ints or floats) into 3-tuples (of ints or floats)" try: x,y,z = vec except: x,y = vec z = 0 return x,y,z def tuple2_from_vec(vec): x,y,z = tuple3_from_vec(vec) return x,y def weighted_ave(t, t0, t1): #e refile to py_utils? # not presently used, but useful and tested (was used in debug code) """return the weighted average of t0 and t1 using t (i.e. t0 * (1-t) + t1 * t), which is t0 for t == 0, and t1 for t == 1. No requirement that 0 <= t <= 1, though that's typically true. """ return t0 * (1-t) + t1 * t class Translate(InstanceOrExpr, DelegatingMixin): "Translate(thing, vec) translates thing (and its bounding box, 2D or 3D) by vec (2 or 3 components). [3D aspect is nim]" # 3D aspect might be nim #061127 fixed unnoticed bug, Widget -> IorE, to avoid failing to delegate fix_color etc in Widget thing = Arg(Widget) delegate = _self.thing vec = Arg(Vector) # translation of layout box # [#e This should be handled differently later, since the current approach requires knowing # all attrs/methods that take or return geometric info in the object's local coords! # A better way might be to have object-local methods to turn number-coords into Points etc, and vice versa, # with Points knowing their coords and their coord-frame identifier. Subtleties include the semantics # of time-variable coord-frames -- it matters which frame a Point is understood to be relative to, # to know whether it moves or not when it doesn't change in value. # If that's too hard to work out, another better way might be to query the object, or our # understanding of its API-type, for type-signatures of methods/attrs needing geometric transformations, # and setting those up here, perhaps in _init_instance (tho this scheme would need optims to move it # at least as far (in being shared between instances) as into _init_expr). # ] ## for useful debug/example code, _C_debugfactor and call_Expr(_self._C_debugfactor), see rev 1.6: ## "_C_debugfactor - temporary eg of debug code, counter-dependent drawing, mixing _C_ and formulae" dx = vec[0] dy = vec[1] #k Interesting Q: would it work here to say dx, dy = vec? I doubt it, since len(vec) (an expr) is not defined. # (Besides (an academic point), its length when defined is 3, so we'd need to include dz even if we don't use it.) bleft = thing.bleft - dx # might become negative; probably ok, but origin outside lbox will affect Column layout, etc ##e ok? bright = thing.bright + dx bbottom = thing.bbottom - dy # might become negative; see comment above btop = thing.btop + dy motion = call_Expr( tuple3_from_vec, vec) #070209 late -- works center = delegate.center + motion #070209 late -- moved from draggable to here -- works ###e the following move method will probably need to go (not hard since not in any non-obs api), # to make room for a move method which alters the posn of a model object. [070209 comment about old code] # methods needed by all layout primitives: move & draw (see Column) & maybe kid (needed for highlighting, maybe not yet called) def move(self, i, j): # note: this separate move/draw API is obsolete, but still used, tho only locally (see paper notes circa 091113) "move from i to j, where both indices are encoded as None = self and 0 = self.thing" #e we might decide to only bother defining the i is None cases, in the API for this, only required for highlighting; # OTOH if we use it internally we might need both cases here assert self._e_is_instance x,y,z = tuple3_from_vec(self.vec) if i is None and j == 0: glTranslatef(x,y,z) ##e we should inline this method (leaving only this statement) into draw, before thing.draw ... elif i == 0 and j is None: glTranslatef(-x, -y, -z) ##e ... and leaving only this statement, after thing.draw return def kid(self, i): # never called, but (for nim hover highlighting) i forget whether it's obs (see paper notes circa 091113) assert i == 0 return self.thing ###e note: as said in notesfile, the indices for these drawn kids *could differ* from these arg indices if I wanted... # or I could instead define a dict... def draw(self): ## print "start drawing in %r, ipath %r" % (self, self.ipath,) assert self._e_is_instance self.move(None, 0) self.drawkid( self.thing) ## self.thing.draw() # draw kid number 0 -- ##k but how did we at some point tell that kid that it's number 0, so it knows its ipath?? ##k is it worth adding index or ipath as a draw-arg? (I doubt it, seems inefficient for repeated drawing) self.move(0, None) ## print "done drawing in %r, ipath %r" % (self, self.ipath,) return pass # end of class Translate def Closer(expr, amount = 0.1): #061208 #e should be a class i guess, if anyone wants to use _this on it -- unlikely return Translate(expr, (0,0,amount)) class RotateTranslate(DelegatingInstanceOrExpr):#070225 """ RotateTranslate(thing, quat, vector) draws as thing, rotated around its center by quat, then translated by vector. ###e other options for other kinds of motion? e.g. a different center of rotation? ###e lbox transforms? """ # args delegate = Arg(Widget) quat = Arg(Quat) ###e also permit 2-arg form like glRotate itself does? or only when we're called Rotate? #e also permit named options (rotation or quat? angle, amount? degrees or radians or turns?? various arg formats like Q takes?) vector = Arg(Vector, ORIGIN) # formulae motion = call_Expr( tuple3_from_vec, vector) center = delegate.center + motion ###e lbox transforms? could just use the same ones as Translate, but do we need them at all? # (bounding radius around center might be more useful -- it needs no transform beyond what we just did for center.) def draw(self): self.pushMatrix() self.drawkid(self.delegate) # has exception protection (#e#k or will soon) self.popMatrix() return def pushMatrix(self): # [modified from same method in class Chunk] """ Do glPushMatrix(), and then transform from external to local coordsys. """ # do most of the things that might cause exceptions before doing any OpenGL calls. x,y,z = self.motion cx,cy,cz = self.delegate.center q = self.quat try: a,b,c,d = q.angle*180.0/pi, q.x, q.y, q.z except: ###UNTESTED print "exception in a,b,c,d = q.angle*180.0/pi, q.x, q.y, q.z for q == %r" % (q,) # does my quat bug print this? no, it happily permits a quat to become Q(nan, nan, nan, nan) with no exception... a,b,c,d = 0,1,0,0 glPushMatrix() glTranslatef(x+cx,y+cy,z+cz) glRotatef(a,b,c,d) glTranslatef(-cx,-cy,-cz) return def popMatrix(self): # [copied from same method in class Chunk] """ Undo the effect of self.pushMatrix(). """ glPopMatrix() pass # end
NanoCAD-master
cad/src/exprs/transforms.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ world.py -- prototype Model Data Set owning/storing object, not yet very general. $Id$ 070201 Moved here from demo_drag.py. Class & file likely to be renamed -- but not to DataSet since that's different -- it's a subset of refs to data already in the model. Some relevant discussion remains in demo_drag.py. Note: for our use in dna_ribbon_view.py we said: #e generalize World to the DataSet variant that owns the data, # maybe ModelData (not sure which file discusses all that about DataSet), refile it... it supports ops, helps make tool ui ###e 070205 replacing world.nodelist with some more controlled access methods: - world.list_all_objects_of_type(DNA_Cylinder) - world.number_of_objects (of all types) """ from exprs.Exprs import getattr_Expr, not_Expr from exprs.instance_helpers import InstanceOrExpr from exprs.attr_decl_macros import State, Instance from exprs.__Symbols__ import Anything, _self from exprs.StatePlace import set_default_attrs from exprs.py_utils import sorted_by from exprs.Highlightable import SavedCoordsys #070401 # I'm not sure whether this unfinished new code should be finished and used -- for now, comment it out [070206] #####e redesign and refile this type stuff (it's wrong in basic nature, terminology, rep, version control; undecided re pure exprs) ## ##def obj_i_type(obj): #070205 late ## """For an arbitrary Python object, but especially an Instance, return a representation of its type ## (known as an Instance Type or i_type, even if it doesn't come from an Instance), ## as a model object or part of one (not necessarily closely related to Python's concept of its type). ## WARNING: it's not yet clear whether an Instance's type can vary with time. ###k ## WARNING: it's not yet clear what this should return for a pure expr. Maybe just 'Expr'?? ## But that's not good enough, since we'll need to understand types of exprs in relation to what instances they'd make... ## Note: the returned type-representation's own python type is not publicly defined, ## but the returned objects can be compared with our associated helper functions, or with python == and !=, ## and printed, and stored as pure python data, and hashed (so they're useable as dict keys). ## """ ## try: ## #e should first verify it's an Instance, to be safe; then we could also use .type instead ## res = obj._i_type # works for Instances [nim right now] ## # (so might .type, but we're not free to use an attrname like that on arbitrary objects) ## # Note: many InstanceMacros and similar wrappers delegate this to the object they wrap. This is essential. ## assert _possible_true_Instance_type(res) ## except AttributeError: ## res = type(obj) ####k ??? ## assert not _possible_true_Instance_type(res) ## return res ## ##def _possible_true_Instance_type( i_type): ## """[private] ## classify all objects into whether they might be types of actual Instances (return True) ## or types of other things (return False). ## """ ## return not callable(i_type) ###k ## ##def i_type_predicate(i_type): ## """Given an Instance Type [bad term -- ambiguous -- ###FIX], ## turn it into a predicate which is true for objects of that type and false otherwise ## """ ## if _possible_true_Instance_type( i_type): ## def pred(thing, i_type = i_type): #k I'm guessing this i_type = i_type kluge is still needed, at least in Python 2.3 ## return getattr(thing, '_i_type', None) == i_type # from inner func ## ##### WRONG as soon as we recognize type inclusion (model obj subclassing) ## else: ## def pred(thing, i_type = i_type): ## return isinstance(thing, i_type) ###k REVIEW ## return pred ## ##nim _i_type in IorE - justuse classname for now, but only if not delegating, i guess... ######NIM ## ###BUG: mere name is too loose, someday def model_type_predicate( model_type): #070206 "#doc" if type(model_type) == type(""): # assume it should exactly match the string passed to World.make_and_add and stored in thing.model_type by a kluge [070206] def pred(thing, model_type = model_type): # assume thing is an Instance, thus has the attr _i_model_type res = (thing._i_model_type == model_type) # print "model_type_predicate(%r)(%r) = %r" % (model_type, thing, res) return res pass else: # assume model_type is an IorE subclass; use the last component of its name, by convention name = model_type.__name__ # note: not self.__class__.__name__ -- that would be about the class's class, ExprsMeta! name = name.split('.')[-1] assert type(name) == type("") # otherwise we might have infrecur of this case pred = model_type_predicate( name) return pred # == class World(InstanceOrExpr): #070205 revised, public nodelist -> private _nodeset """maintains the set of objects in the model; provides general operations on them """ #k is this 070401 change ok: ModelObject -> InstanceOrExpr? At least it doesn't seem to have caused trouble. ###e Q: Is it ok for this to inherit _CoordsysHolder and have .draw save the coords? Or to own one of those to hold them? # The goal is for some external thing to be able to copy the coords we will draw a newly made thing under. # that's partly misguided given that we might in theory draw things in more than one place # and/or in a different place than in the prior frame. The external thing that wants to do this # is self._newobj.copy_saved_coordsys_from( self.world) in class PalletteWell.on_press as of 070401. # It wants to use the right coordsys to turn a mouseray into that obj's initial position in the World. Hmm. # A: In principle, if we're drawing the world twice (eg in stereo), we'd better be able to tell from a mouseray # used to put something into it, which world-instance we're putting it into! and each of those needs to know # where mouse events would drop things (based on where it was last drawn -- no ambiguity there). # So it's correct for something to save that and reveal it -- it just needs to be a world-drawn-instance # which would somehow show up (as selobj?) when interpreting that mouseray. For now, it's ok to kluge this # by assuming this class is taking the role of world-drawn-instance and being drawn only once. Alternatively, # we could say that the recipient of the mouseray should also be told what background it's over (whether or not it # hit the background or some object drawn over it) (this might be "one of several background objects" for stereo) # so it would know how to find "absolute model coords" in a canonical way. Or a third way is for the World client code # to include an invisible object drawn just to capture the coords. In the multi-world-drawn-instance case, we'd have to combine # this object with our knowledge of which worldinstance was drawn, by storing the drawn coords under the crossproduct # of that and the object... # ... Trying one of these solutions with self._coordsys_holder below. Seems to work & fix the pallette bug. Comment needs cleanup. # [070401] # ###FLAW: logically, this should store exprs needed to remake its instances, merely caching the instances, # but in fact, stores the instances themselves. This will make save/load harder, and means instances survive code-reloading. # Probably it should be fixed before trying to do save/load. [070206 comment] _nodeset = State(Anything, {}) # self._nodeset is private; it's changetracked but only when entirely replaced (not just modified!) # (###e optim: can that be fixed? we need a way to access the LvalForState and inval it) ###e we'll need to put that State on a different state-layer (i.e. kind of StatePlace) when we start saving/loading this _coordsys_holder = Instance(SavedCoordsys()) #070401 -- see long comment above, about _CoordsysHolder def _init_instance(self): super(World, self)._init_instance() set_default_attrs( self.untracked_model_state, _index_counter = 4000) #070213; could State() do this for us instead? #e def _C_number_of_objects(self): """Compute self.number_of_objects, defined as the total number of objects explicitly stored in self, of all types, in all Parts and configurations (but not including objects removed by Undo but present in Undo history). WARNING: Parts, configurations, and Undo are nim for this class as of 070206. Note: probably not very useful, due to that lack of qualification by anything. Perhaps useful to know whether self is entirely empty, or as a ballpark estimate of how much data it might contain. """ return len(self._nodeset) def list_all_objects_of_type(self, model_type): """Return a nominally read-only list of all objects in self of the given model_type (or IorE class, as a special case), in a deterministic order not yet decided on (might be creation order, world-index order, MT order). [Current implem uses creation order as an Instance, as told by _e_serno; this order will become unideal as new kinds of object ops are added, like potential objs or moving them from other worlds (if possible). ##e 070206] ##e needs options for "not just this config", "not just this Part" (and revised implem, once we support configs or Parts) #e optim: extend API to be able to specify ordering -- otherwise it has to be sorted twice (here, and often in caller). """ type_predicate = model_type_predicate( model_type) # this permits model_type to be an IorE subclass (or its name) ###BAD: not enough kinds of type exprs can be passed, and error checking on model_type (not being garbage) is nim return filter( type_predicate, self._sorted_objects ) ##e optim: filter first (or keep them already type-separated), then sort def _append_node(self, index, node):#070201 new feature ###e SHOULD RENAME [070205] "not sure if this should be private... API revised 070205, ought to rename it more (and #doc it)" ## self._nodeset = dict(self._nodeset) ## ###KLUGE: copy it first, to make sure it gets change-tracked. Inefficient when long! ###BUG in the above: # doesn't work, since the change to it is not tracked, since the old and new values compare equal! (guess) #k note that LvalForState may also not keep a deep enough copy of the old value in doing the compare, # to not be fooled by the direct modification of the dict (in the sense of that mod escaping its notice, even later)! # (i'm not sure -- needs review, e.g. about whether bugs of this kind will go undetected and be too hard to catch) ## self._nodeset[index] = node newset = dict(self._nodeset) newset[index] = node self._nodeset = newset # this ought to compare different and cause changetracking (assuming the index was in fact new) ###e OPTIM IDEA: can we modify it, then set it to itself? No, because LvalForState will compare saved & new value -- # the same mutable object! We need to fix that, but a workaround is to set it to None and then set it to itself again. # That ought to work fine. ####TRYIT but then fix LvalForState so we can tell it we modified its mutable contents. [070228] return def _C__sorted_objects(self): """compute private self._sorted_objects (a list, ordered by something not yet decided, probably creation time; probably should be the same order used by list_all_objects_of_type) """ res = self._nodeset.values() res = sorted_by( res, lambda obj: obj._e_serno ) ###KLUGE: use _e_serno in place of .creation_order, not yet defined -- # works now, but wrong in general due to potential objects or moved-from-elsewhere objects. # (Q: Would index-in-world be ordered the same way? A: Yes for now, but not good to require this in the future.) return res def draw(self): # draw all the nodes [#e 070228 ###e in future we're more likely to draw X(node) for X supplied from caller & subset of nodes] # [optim idea 070103 late: have caller put this in a DisplayListChunk; will it actually work? # the hope is, yes for animating rotation, with proper inval when nodelist changes. It ought to work! Try it. It works!] self._coordsys_holder.save_coords_if_safe() #070401 for node in self._sorted_objects: # print "%r is drawing %r at %r" % (self, node, node.pos) # suspicious: all have same pos ... didn't stay true, nevermind self.drawkid( node) ## node.draw() # this assumes the items in the list track their own posns, which might not make perfect sense; # otoh if they didn't we'd probably replace them with container objs for our view of them, which did track their pos; # so it doesn't make much difference in our code. we can always have a type "Vertex for us" to coerce them to # which if necessary adds the pos which only we see -- we'd want this if one Vertex could be in two Worlds at diff posns. # (Which is likely, due to Configuration Management.) if 0 and node is self._sorted_objects[-1]: print "drew last node in list, %r, ipath[0] %r, pos %r" % (node, node.ipath[0], node.pos) ###e see comment above: "maybe World needs to wrap all it draws with glue to add looks and behavior to it" return def make_and_add(self, expr, type = None): #070206 added type option -- required for now (temporary); semantics not fully defined """Make a new model object instance from expr, add it to the world at a local index we choose, and return it. This is the main public method for making new model objects. [As a temporary ###KLUGE (070206), the type needs to be passed, for purposes of methods like self.list_all_objects_of_type. This will no longer be needed once we can reliably infer the type (including supertypes) from the made instance of expr. But that probably requires altering delegation to specify which attrs to delegate (based on which interface they're part of), including a new attr for model object type. ###e Even once that's done, the caller may want to pass type-like info, perhaps "tags" -- e.g. one current caller passes type = "dot" which could not be inferred from expr it passes. ###e Callers may also want to pass desired relations, like a parent object, for convenience, or to influence details of how we make and index the new instance. ##e callers will also want to wrap objects with type-nicknames (see code comment for details). [WARNING: the API may be revised to also return the index. Or, we might store that in object, or store a back-dict here.] """ index, node = self._make(expr) # that picks a unique index (using a counter in transient_state); I think that's ok # (but its change/usage tracking needs review ####k) self._append_node(index, node) # revised 070205 if 'model_type_on_object_kluge_070206': ###KLUGE -- store type on object (simulates later inferring it from object) # update 070213: the right thing to do is probably not this, but to wrap the object itself with a type-nickname # (before passing it to us), so not only this world (self), but everything that sees it (MT default label, commands/ops, # selobj checks, etc), can react to its type-nickname. if type is not None: # node._i_model_type is defined on all Instances, and node should be one ## if not hasattr(node, '_i_model_type'): ## node._i_model_type = None # this is how much of a kluge it is -- we're not even sure which classes need this attr if node._i_model_type is not None: assert node._i_model_type == type, "make_and_add type %r inconsistent with existing type %r on %r" % \ (type, node._i_model_type, node) node._i_model_type = type pass return node def _make(self, expr): # moved here from demo_drag 070202 """[private] Allocate a new index, use it as the localmost component of ipath while making [or finding?? I THINK NOT ####k] expr, and return (index, new-expr-instance). Note that it's up to expr whether to actually make use of the suggested ipath in the new instance. The case of one instance stored with different indices in World is not reviewed, and not recommended until it is, but it's up to the caller to worry about. I don't know it's wrong, just never thought about it and assumed it would not happen when analyzing the code. """ index = None #e rename? #e move to some superclass #e worry about lexenv, eg _self in the expr, _this or _my in it... is expr hardcoded or from an arg? #e revise implem in other ways eg eval vs instantiate #e default unique index?? (unique in the saved stateplace, not just here) # (in fact, is reuse of index going to occur from a Command and be a problem? note *we* are acting as command... #e use in other recent commits that inlined it if index is None: # usual case I hope (due to issues mentioned above [maybe here or maybe in demo_drag.py]): allocate one index = self.untracked_model_state._index_counter if 'index should be modified [070203]': # see comments above dated 070203 index = index + 1 self.untracked_model_state._index_counter = index # 070213 changed implem of _index_counter to make sure it's not change/usage-tracked. # (Fyi, I don't know whether or not it was before (using State()), in a way that mattered. # The tracking danger would be that whenever you make any new object, # the old objects see that the index they used is different # and think they too need remaking, or something like that! This needs thinking through # since it probably covers all make-data, not just the index. All make-data is being snapshotted. # For that matter, things used by "commands" are in general different than things used to recompute. # Maybe entire commands need to have tracked usage discarded or kept in a new kind of place. #####FIGURE OUT) # # Note (language design flaw): to set this attr (using current code), # you have to refer to it directly in the stateplace, # rather than using the kind of abbrev that (in Highlightable glname) seems to work for get: # _index_counter = _self.untracked_model_state._index_counter # This could possibly be fixed in C_rule_for_formula (not sure), or by making the abbrev in a fancier manner. # (If you try to set the abbrev, you get # "AssertionError: subclass [C_rule_for_formula] ... should implement set_for_our_cls".) # ###BUG: even for get, the abbreviated form (self._index_counter) is not updated when the spelled out form is!! # See this debug print from when we tried that here: ## print "after set to %r, self._index_counter = %r, self.untracked_model_state._index_counter = %r" % \ ## (index, self._index_counter, self.untracked_model_state._index_counter ) ## # it prints: after set to 4002, self._index_counter = 4001, self.untracked_model_state._index_counter = 4002 # This is weird, since Highlightable seems to succeed using a similar glname abbrev for get. # (Unless it doesn't, and I never noticed?? To check, I just added debug code for that -- so far untriggered.) pass ###e LOGIC ISSUE: should assert the resulting ipath has never been used, # or have a more fundamental mechanism to guarantee that env = self.env # maybe wrong, esp re _self ipath = (index, self.ipath) return index, env.make(expr, ipath) # note: does eval before actual make # == def _C_mt_kids(self): # 070206 experiment related to ModelTreeNodeInterface (sp?) ###e how do we depend on the mt display prefs? note we need to be drawn twice, once in graphics area using .draw # and once in MT using the mt_* methods, but with independent envs provided! Self.env might have room in attr namespace, # but it has a single origin. Besides there might be two indep MT views or graphics views -- each of those also needs # separate envs (of the same kind). But that makes us two instances! I guess we need separate World data obj vs World viewer, # to handle that! I'm not even sure it makes sense to put the viewing methods in the same object... but maybe it does # with this concept of partial instantiation [nim], in which we could instantiate the viewing layer(?) (interface??) twice, # and the data layer just once, letting it (an instance) serve as the expr for instantiating the viewing layer in two places. # (But this makes it clear that the env would need to be split into separate parts, one for each partially instantiable # layer -- hopefully these parts would correspond to interfaces (or sets of them), i.e. an interface's attrs would # have to all be instantiated at the same time, and decls would control which ones were instantiated together in which # partial-instantiation layers.) # # So for now let's pretend self.env can tell us... tho as initial kluge, the global env.prefs (get_pref?) could tell us. # But even sooner, just pretend we don't care and always show all the kids. return self._sorted_objects mt_name = "testmode" #e or maybe something like State(str, "Untitled"), or a stateref # or "Untitled" as it was before 070208 mt_openable = True ## mt_node_id = getattr_Expr( _self, '_e_serno') mt_node_id = getattr_Expr( _self, 'ipath') #e optim: should intern the ipath ###e move this to IorE? btw redundant w/ def mt_node_id # 070218 -- by test, using ipath (a bugfix) makes world.open persistent (as hoped/predicted); # probably doesn't affect open-MT newnode slowness (but now that's fixed in different way in demo_MT) # == def _cmd_Clear(self): #070106 experimental naming convention for a "cmd method" -- a command on this object (requiring no args/opts, by default) if self._nodeset: # avoid gratuitous change-track by only doing it if it does something (see also _cmd_Clear_nontrivial) # NOTE: this cond is probably not needed, since (IIRC) LvalForState only invalidates if a same_vals comparison fails. ###k self._nodeset = {} return # related formulae for that command # (names are related by convention, only used in this file, so far; prototype for wider convention, but not yet well thought through) _cmd_Clear_nontrivial = not_Expr( not_Expr( _nodeset)) #KLUGE: need a more direct boolean coercion (not that it's really needed at all) # can be used to enable (vs disable) a button or menu item for this command on this object _cmd_Clear_legal = True # whether giving the command to this object from a script would be an error _cmd_Clear_tooltip = "clear all objects" # a command button or menu item could use this as its tooltip ###e is this client-specific?? def _cmd_Make(self): print "world make is nim" ### _cmd_Make_tooltip = "make something [nim]" ###e when we know the source of what to make, it can also tell us this tooltip pass # end of class World # == comments from class World's original context # for a quick implem, how does making a new node actually work? Let's assume the instance gets made normally, # and then a side effect adds it to a list (leaving it the same instance). Ignore issues of "whether it knows its MT-parent" for now. # We know it won't get modified after made, since the thing that modifies it (the command) is not active and not reused. # (It might still exist enough to be revivable if we Undoed to the point where it was active, if it was a wizard... that's good! # I think that should work fine even if one command makes it, some later ones modify it, etc...) # so we need a world object whose state contains a list of Vertex objects. And a non-stub Vertex object (see above I hope). # end
NanoCAD-master
cad/src/exprs/world.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ DisplayListChunk.py @author: Bruce @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. History: 061231 prototyped this code in NewInval.py 070102 moved it here 1-2 days ago, and revised it to seem correct; imports/reloads ok, but otherwise untested 070103 works, with important caveats re Highlightable (described below) 080215 renamed from DisplistChunk to DisplayListChunk == Still needed: - maybe: some renamings, as commented - provisions for highlighting (see just below in this docstring) - include texture/image contents in the same scheme -- analogous to displist contents. Requires giving them compatible owner objects and treating those like we treat the ones for directly called display lists, aka sublists. == caveats re Highlightable [as of 070103]: a Highlightable inside a DisplayListChunk only works properly (without highlight-position errors) if no coord transform occurs from the DisplayListChunk to the Highlightable, and no trackballing or other motion of whole thing from the last time the instance was made. The second condition is impossible to guarantee, so in practice, you should not use a Highlightable inside a DisplayListChunk until this is fixed. Theory: the gl matrix is saved only once and only as it was when the displist was compiled. Note, the rules would be even weirder (I predict) if nested display lists were involved -- then we'd need no transforms in any of them, re their calls of the next, for current code to work. The best fix is the one planned on paper a few weeks ago -- have ExprsMeta decorate draw methods with something that can call only the needed ones in a special scan for implementing draw_in_abs_coords. (Idea now: the tree whose paths from root need to be marked, to implem that, is the tree of original calls of draw methods. This was supposed to equal the ipath-suffix tree. Hopefully it does. If not, the decorated draw methods themselves could generate ipath-like things for this purpose -- or really, just pointers to the draw-method-owning parents in each one, to be stored in the objects with the draw methods.) Update, 081202: If you suspect this bug causes some unwanted behavior, you can test that by temporarily setting the debug_pref "disable DisplayListChunk?" and seeing if that fixes the unwanted behavior. (But it might also cause a large slowdown.) But if there are bugs from the other nesting order of interaction, i.e. a DisplayListChunk inside a Highlightable, that would fix those too. I'm not sure whether there are. For example, as of 081202 morning, disabling DisplayListChunks fixes the following bug: mousewheel zoom makes checkboxes inside DrawInCorner (and perhaps other checkboxes) either not highlight, or if they are close enough to the center of the screen (I guess), highlight in the wrong size and place (only where the highlight image overlaps the original image, which happens for the top two checkboxes when you zoom in by one wheel click). The bug is "reset" by "clear state and reload" even if the zoom is still in effect, but additional zoom causes the bug again. But panning or rotating the view does not cause the bug (for reasons I don't fully understand, except that it must be related to the fact that those don't alter the projection matrix but zoom does). But I don't fully understand what causes this bug, and I don't know for sure in which order the nesting is or whether being inside DrawInCorner is part of the bug's cause. I do know it's alternatively fixable by using projection = True in the Highlightable, so I'm going to change that to default True (see comments there for reasoning and related plans). As for the cause, it's probably related that only zoom, not pan or trackball, caused the bug, and only zoom modifies the projection matrix. But I don't have a complete explanation of either the bug or the fix. *If* this bug comes from Highlightable inside DisplayListChunk, maybe it could be fixed more optimally by detecting when that happens at runtime, and setting projection = True only then? Maybe try this someday. """ from OpenGL.GL import GL_COMPILE from utilities.debug_prefs import Choice_boolean_False from utilities.debug_prefs import debug_pref from utilities.debug import print_compact_traceback from foundation.changes import SelfUsageTrackingMixin # defines track_use, track_inval; maintains a private __subslist on self from foundation.changes import SubUsageTrackingMixin # defines begin_tracking_usage, end_tracking_usage; doesn't use self from exprs.attr_decl_macros import Arg, ArgOrOption from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.widget2d import Widget from exprs.py_utils import printfyi ##e comment during devel -- see also some comments in lvals-outtakes.py and DisplayListChunk-outtakes.py (in cvs, only during devel) # (including long docstrings/comments that might be correct, but are unreviewed and partly redundant now) # == # moved class GLPane_mixin_for_DisplayListChunk from here into GLPane.py, bruce 070110 # == ###@@@ Q: do we separate the object to own a displist, below, and the one to represent various Instances, # like one for DisplayListChunk and one for defining a displist-subroutine? # (Do these even differ? [062023 addendum: One way they differ: whether highlighting treats their instances as separate objects. # But it might turn out this is just a matter of whether we use a DisplayListChunk inside something for highlighting # which pushes its own glname for everything inside it, crossing it with whatever ones are inside it rather than being # overridden by them (just a flag on the name which matters when it's interpreted).]) # If we do, is the class below even an Instance with a draw method? (I doubt it. I bet it's an internal displist-owner helper object.) #e digr: someday: it might be good for glpane to have a dict from allocated dlist names to their owning objects. # Could we use displist names as keys, for that purpose? class DisplayListChunk( DelegatingInstanceOrExpr, SelfUsageTrackingMixin, SubUsageTrackingMixin ): """ #doc [Note: the implicit value for SelfUsageTrackingMixin is the total drawing effect of calling our displist in immediate mode. This has an inval flag and invalidator, but we also have another pair of those for our display list's OpenGL contents, making this more complicated a use of that mixin than class Lval or its other uses.] [old long docstring and comment moved to outtakes file since unreviewed and partly redundant, 070102] """ # default values of instance variables _direct_sublists_dict = 2 # intentional error if this default value is taken seriously contents_valid = False drawing_effects_valid = False # we don't yet have a specific flag for validity of sublist drawing effects (unknown when not contents_valid); # that doesn't matter for now; a useful optim someday would be a dict of all invalid-effects direct sublists #e # args delegate = Arg(Widget) # options debug_prints = ArgOrOption(str, None) # flag to do debug prints, and (unless a boolean) name for doing them def _C__debug_print_name(self): # compute self._debug_print_name """ return False (meaning don't do debug prints), or a name string to prefix them with """ # use this to say when we emit a calllist (and if so, immediate or into what other displist), and/or recompile our list #e and use in repr if self.debug_prints: if self.debug_prints == True: return "%r" % self ###BUG (suspected): this looks like an infrecur. Not sure if ever tested. [070110 comment] return str(self.debug_prints) return False def _init_instance(self): self._key = id(self) # set attribute to use as dict key (could probably use display list name, but it's not allocated yet) self.glpane = self.env.glpane #e refile into superclass?? self._disabled = not hasattr(self.glpane, 'glGenLists') if self._disabled: # this should never happen after the merge of GLPane_overrider into GLPane done today [070110] print "bug: %r is disabled since its GLPane is missing required methods" % self return def _C_displist(self): # compute method for self.displist ### WARNING: this doesn't recycle displists when instances are remade at same ipath (but it probably should), # and it never frees them. To recycle them, just change it to use transient_state. # When we start using more than one GL Context which share display lists, we'll have to revise this somehow. # ### NOTE: usage tracking should turn up nothing -- we use nothing """ allocate a new display list name (a 32-bit int) in our GL context """ if self.displist_disabled(): # revised this cond (true more often), 070215 printfyi("bug: why does .displist get requested in a disabled DisplayListChunk??") # (i never saw this) return 0 self.glpane.makeCurrent() # not sure when this compute method might get called, so make sure our GL context is current displist = self.glpane.glGenLists(1) # allocate the display list name [#k does this do makeCurrent??] # make sure it's a nonzero int or long assert type(displist) in (type(1), type(1L)) assert displist, "error: allocated displist was zero" if self._debug_print_name: print "%s: allocated display list name %r" % (self._debug_print_name, displist) return displist def __repr__(self): try: if not self._e_is_instance: return super(DisplayListChunk, self).__repr__() _debug_print_name = self._debug_print_name # only legal on an instance except: print "exception in self._debug_print_name discarded" #e print more, at least id(self), maybe traceback, if this happens # (but don't print self or you might infrecur!!) ##e can we print self.displist and/or self.delegate? return "<%s at %#x>" % (self.__class__.__name__, id(self)) else: return "<%s(%s) at %#x>" % (self.__class__.__name__, _debug_print_name or "<no name>", id(self)) pass def displist_disabled(self): #070215 split this out, modified it to notice _exprs__warpfuncs """ Is the use of our displist (or of all displists) disabled at the moment? """ return self._disabled or \ debug_pref("disable DisplayListChunk?", Choice_boolean_False, prefs_key = True) or \ getattr(self.env.glpane, '_exprs__warpfuncs', None) ###BUG: this will be too inefficient a response for nice dragging. def draw(self): """ Basically, we draw by emitting glCallList, whether our caller is currently compiling another display list or executing OpenGL in immediate mode. But if our total drawing effects are invalid (i.e. our own list and/or some list it calls has invalid contents), we must do some extra things, and do them differently in those two cases. In immediate mode, if our own display list contents are invalid, we have to recompile it (without executing it) and only later emit the call, since compiling it is the only way to find out what other display lists it currently calls (when using the current widget expr .draw() API). Further, whether or not we recompiled it, we have to make sure any other lists it calls are valid, recompiling them if not, even though they too might call other lists we can't discover until we recompile them. Since OpenGL doesn't permit nested compiles of display lists, we use a helper function: given a set of display lists, make sure all of them are ok to call (by compiling zero or more of them, one at a time), extending this set recursively to all lists they indirectly call, as found out when recompiling them. This involves calling .draw methods of arbitrary widgets, with a glpane flag telling them we're compiling a display list. (In fact, we tell them its controller object, e.g. self, so they can record info that helps with later redrawing them for highlighting or transparency.) When not in immediate mode, it means we're inside the recursive algorithm described above, which is compiling some other display list that calls us. We can safely emit our glCallList before or after our other effects (since it's not executed immediately), but we also have to add ourselves to the set of displists directly called by whatever list is being compiled. (Doing that allows the recursive algorithm to add those to the set it needs to check for validity. That alg can optim by only doing that to the ones we know might be invalid, but it has to record them as sublists of the list being compiled whether or not we're valid now, since it might use that later when we're no longer valid.) We do all that via methods and/or private dynamic vars in self.glpane. ###doc which Note that the recursive algorithm may call us more than once. We should, of course, emit a glCallList every time, but get recompiled by the recursive algorithm at most once, whether that happens due to side effects here or in the algorithm or both. (Both might be possible, depending on what optims are implemented. ###k) Note that recursive display list calls are possible (due to bugs in client code), even though they are OpenGL errors if present when executed. (BTW, it's possible for cycles to exist transiently in display list contents without an error, if this only happens when some but not all display lists have been updated after a change. This needs no noticing or handling in the code.) """ # docstring revised 070102. _debug_print_name = self._debug_print_name if self.displist_disabled(): self.drawkid( self.delegate) ## self.delegate.draw() # I hope it's ok that this has no explicit effect on usage tracking or inval propogation... I think so. # It's equivalent to wrapping the whole thing in an If on this cond, so it must be ok. return self.displist # make sure we have a display list allocated # (this calls the compute method to allocate one if necessary) # [probably not needed explicitly, but might as well get it over with at the beginning] ###e NOTE: if someday we keep more than one displist, compiled under different drawing conditions in dynenv # (e.g. different effective values of glpane._exprs__warpfuncs), # then some or all of our attrs need splitting by the case of which displist to use, # and we also have to avoid usage-tracking the attrs that eval that case in the same way # as those we use when compiling displists. (As if we're If(cond, displistchunk1, displistchunk2), # but also making sure nothing in displistchunk1 tracks those same attrs in a way we see as our own usage, # or if it does, making sure we don't subscribe inval of a displist to that, by adding new code # to end_tracking_usage to handle those usages specially, having known what they were by tracking cond, perhaps -- # or by explicit description, in case cond also tracks other stuff which doesn't show up in its value. # Or another way, if the cond-value-attrs are special (e.g. glpane._exprs__warpfuncs), # is for them to not be natively usage-tracked, but only when we eval cond (not sure this is ok re outsider tracking # of them -- maybe better to track them except when we set a specialcase dynenv flag next to them, # which they notice to decide whether to track uses, which we set when inside the specific case for the cond-value.) # [070215] # are we being compiled into another display list? parent_dlist = self.glpane.compiling_displist_owned_by # note: a dlist owner or None, not a dlist name if parent_dlist: # We're being compiled into a display list (owned by parent_dlist); tell parent that its list calls ours. # (Note: even if we're fully valid now, we have to tell it, # since it uses this info not only now if we're invalid, but later, # when we might have become invalid. If we ever have a concept of # our content and/or drawing effects being "finalized", we can optim # in that case, by reducing what we report here.) if _debug_print_name: print "%s: compiling glCallList into parent list %r" % (_debug_print_name, parent_dlist) parent_dlist.__you_called_dlist( self) #e optim: inline this # (note: this will also make sure the alg recompiles us and whatever lists we turn out to call, # before calling any list that calls us, if our drawing effects are not valid now.) elif self.glpane.compiling_displist: print "warning: compiling dlist %r with no owner" % self.glpane.compiling_displist #e If this ever happens, decide then whether anything but glCallList is needed. # (Can it happen when compiling a "fixed display list"? Not likely if we define that using a widget expr.) else: # immediate mode -- do all needed recompiles before emitting the glCallList, # and make sure glpane will be updated if anything used by our total drawing effect changes. if _debug_print_name: print "%s: prepare to emit glCallList in immediate mode" % (_debug_print_name, ) self.glpane.ensure_dlist_ready_to_call( self) # (this might print "compiling glCallList" for sublists) # note: does transclose starting with self, calls _recompile_if_needed_and_return_sublists_dict self.track_use() # defined in SelfUsageTrackingMixin; compare to class Lval # This makes sure the GLPane itself (or whatever GL context we're drawing into, if it has proper usage tracking) # knows it needs to redraw if our drawing effects change. # Note: this draw method only does track_use in immediate mode (since it would be wrong otherwise), # but when compiling displists, it can be done by the external recursive algorithm via track_use_of_drawing_effects. if _debug_print_name: print "%s: emit glCallList(%r)" % (_debug_print_name, self.displist) self.do_glCallList() #e optim: inline this return # from draw # some old comments which might still be useful: # 061023 comments: analogous to Lval.get_value, both in .draw always being such, and in what's happening in following code. # Another issue - intermediate levels in a formula might need no lval objs, only ordinary compute calls, # unless they have something to memoize or inval at that level... do ordinary draw methods, when shared, # need this (their own capturing of inval flag, one for opengl and one for total effect, # and their own pair of usage lists too, one of called lists which can be scanned)?? # this doesn't work due to quirks of Python: ## track_use_of_drawing_effects = track_use # this is semipublic; track_use itself (defined in SelfUsageTrackingMixin) is private # so rather than slow it down by a def, # I'll just rename the calls track_use but comment them as really track_use_of_drawing_effects def _your_drawing_effects_are_valid(self): ##e should inline as optim """ """ assert self.contents_valid # this failed 070104 with the exception shown in long string below, when I used clear "button" (070103 kluge) on one node... # theory: the world.nodelist change (by clear button run inside draw method, which is illegal -- that's the kluge) # invalidated it right when it was being recompiled (or just after, but before the overall recomp alg sent this call). # So that kluge has to go [later: it's gone], # and the underlying error of changing an input to an ongoing recompute has to be better detected. ####e self.drawing_effects_valid = True return # the exception mentioned above: """ atom_debug: fyi: <OneTimeSubsList(<LvalForState(<World#16291(i)>|transient.nodelist|('world', (0, (0, 'NullIpath')))) at 0x101a7b98>) at 0x10583850>'s event already occurred, fulfilling new subs <bound method usage_tracker_obj.standard_inval of <usage_tracker_obj(<DisplayListChunk(<no name>) at 0x111b7670>) at 0x112086e8>> immediately: [atom.py:414] [GLPane.py:1847] [GLPane.py:1884] [testmode.py:67] [testdraw.py:251] [GLPane_overrider.py:127] [GLPane_overrider.py:138] [GLPane_overrider.py:298] [testmode.py:75] [testdraw.py:275] [testdraw.py:385] [testdraw.py:350] [testdraw.py:384] [testdraw.py:530] [test.py:1231] [Overlay.py:57] [Overlay.py:57] [Overlay.py:57] [DisplayListChunk.py:286] [DisplayListChunk.py:124] [state_utils.py:156] [DisplayListChunk.py:116] [DisplayListChunk.py:358] [changes.py:352] [changes.py:421] [changes.py:72] exception in testdraw.py's drawfunc call ignored: exceptions.AssertionError: [testdraw.py:350] [testdraw.py:384] [testdraw.py:530] [test.py:1231] [Overlay.py:57] [Overlay.py:57] [Overlay.py:57] [DisplayListChunk.py:286] [DisplayListChunk.py:127] [DisplayListChunk.py:314] """ def __you_called_dlist(self, dlist): self.__new_sublists_dict[ dlist._key ] = dlist # note: this will intentionally fail if called at wrong time, since self.__new_sublists_dict won't be a dict then return def _recompile_if_needed_and_return_sublists_dict(self): """ [private helper method for glpane.ensure_dlist_ready_to_call()] Ensure updatedness of our displist's contents (i.e. the OpenGL instructions last emitted for it) and of our record of its direct sublists (a dict of owners of other displists it directly calls). Return the dict of direct sublists. As an optim [mostly nim], it's ok to return a subset of that, which includes all direct sublists whose drawing effects might be invalid. (In particular, if our own drawing effects are valid, except perhaps for our own displist's contents, it's ok to return {}. [That's the part of this optim we do.]) """ # doc revised 070102 if not self.contents_valid: # we need to recompile our own displist. if self._debug_print_name: print "%s: compiling our displist(%r)" % (self._debug_print_name, self.displist) self._direct_sublists_dict = 3 # intentional error if this temporary value is used as a dict # (note: this might detect the error of a recursive direct or indirect call -- untested ##k) self.__new_sublists_dict = new_sublists_dict = {} # this is added to by draw methods of owners of display lists we call mc = self.begin_tracking_usage() # Note: we use this twice here, for different implicit values, which is ok since it doesn't store anything on self. # [#e i should make these non-methods to clarify that.] # This begin/end pair is to track whatever affects the OpenGL commands we compile; # the one below is to track the total drawing effects of the display lists called during that # (or more generally, any other drawing effects not included in that, but tracking for any other # kinds of effects, like contents of textures we draw to the screen ### WHICH MIGHT MATTER, is nim). # # Note that track_use and track_inval do NOT have that property -- they store self.__subslist. try: self.recompile_our_displist() # render our contents into our displist using glNewList, self.drawkid( self.delegate), glEndList # note: has try/except so always does endlist ##e make it tell us if error but no exception?? finally: self.contents_valid = True # Q: is it ok that we do this now but caller might look at it? # A: yes, since caller never needs to see it -- it's effectively private. self.end_tracking_usage( mc, self.invalidate_contents) # same invalidator even if exception during recompile or its draw self._direct_sublists_dict = dict(new_sublists_dict) #e optim: this copy is only for bug-safety in case something kept a ref and modifies it later self.__new_sublists_dict = 4 # illegal dict value mc2 = self.begin_tracking_usage() # this tracks how our drawing effects depend on those of the sublists we call try: for sublist in self._direct_sublists_dict.itervalues(): sublist.track_use() # really track_use_of_drawing_effects (note: that's tracked into the global env, as always for track_use) finally: self.end_tracking_usage( mc2, self.invalidate_drawing_effects ) # this subscribes invalidate_drawing_effects to inval of total effects of all sublists # (effectively including indirectly called ones too); # the only thing it doesn't cover is subscribing it to inval of our own displist's contents, # so we manually call it in invalidate_contents. if self.drawing_effects_valid: if debug_pref("DisplayListChunk: permit optim 070204?", Choice_boolean_False): ###BUG: this old optim seems to cause the bug 070203 -- I don't know why, but disabling it seems to fix the bug ###k print "doing optim 070204"#e and listnames [#e only print if the optim makes a difference?] return {} # optim; only possible when self.contents_valid, # tho if we had a separate flag for sublist contents alone, # we could correctly use that here as a better optim #e else: pass ## print "not doing optim 070204"#e and listnames return self._direct_sublists_dict def invalidate_contents(self): """ [private] called when something changes which might affect the sequence of OpenGL commands that should be compiled into self.displist """ if self.contents_valid: self.contents_valid = False self.invalidate_drawing_effects() else: # this clause would not be needed except for fear of bugs; it detects/complains/works around certain bugs. if self.drawing_effects_valid: print "bug: self.drawing_effects_valid when not self.contents_valid. Error, but invalidate_drawing_effects anyway." self.invalidate_drawing_effects() pass return def invalidate_drawing_effects(self): # note: compare to class Lval if self.drawing_effects_valid: self.drawing_effects_valid = False # propogate inval to whoever used our drawing effects self.track_inval() # (defined in SelfUsageTrackingMixin) return def recompile_our_displist(self): """ [private] call glNewList/draw/glEndList in the appropriate way, but do no usage tracking or valid-setting """ glpane = self.glpane displist = self.displist glpane.glNewList(displist, GL_COMPILE, owner = self) # note: not normally a glpane method, but we'll turn all gl calls into methods so that glpane can intercept # the ones it wants to (e.g. in this case, so it can update glpane.compiling_displist) # note: we have no correct way to use GL_COMPILE_AND_EXECUTE, as explained in draw docstring try: self.drawkid( self.delegate) ## self.delegate.draw() except: print_compact_traceback("exception while compiling display list for %r ignored, but terminates the list: " % self ) ###e should restore both stack depths and as much gl state as we can # (but what if the list contents are not *supposed* to preserve stack depth? then it'd be better to imitate their intent re depths) pass glpane.glEndList(displist) # note: glEndList doesn't normally have an arg, but this arg lets glpane version of that method do more error-checking return def do_glCallList(self): """ emit a call of our display list, whether or not we're called in immediate mode """ self.glpane.glCallList( self.displist) return pass # end of class DisplayListChunk # end
NanoCAD-master
cad/src/exprs/DisplayListChunk.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ controls.py - some simple controls, like ChoiceButton, ChoiceColumn/Row, checkbox_v3 @author: Bruce @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. TODO: - also has some general things we need to refile See also: toolbars.py """ #e stub, nim; implem requires StateRef, some better type conversion (& filling it out below), Set action, on_press accepting that import time from exprs.Rect import Rect, Spacer, SpacerFor from exprs.Center import CenterY from exprs.Column import SimpleColumn, SimpleRow from exprs.Boxed import Boxed from exprs.TextRect import TextRect from exprs.Highlightable import Highlightable, print_Expr from exprs.Overlay import Overlay from exprs.images import IconImage from exprs.staterefs import PrefsKey_StateRef from exprs.DisplayListChunk import DisplayListChunk from exprs.If_expr import If_kluge If = If_kluge # until debugged # stub types from exprs.ExprsConstants import StubType stubtype = StubType from exprs.Set import Set from exprs.staterefs import LocalVariable_StateRef ###e move to basic, if it doesn't become obs, but it probably will, once State works ##from exprs.debug_exprs import debug_evals_of_Expr from utilities.constants import gray, blue, yellow, orange from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice_boolean_False from exprs.widget2d import Widget2D from exprs.Exprs import format_Expr, eq_Expr, not_Expr, call_Expr, or_Expr from exprs.instance_helpers import InstanceMacro, InstanceOrExpr from exprs.instance_helpers import DelegatingMixin, DelegatingInstanceOrExpr from exprs.attr_decl_macros import Arg, Option, ArgOrOption, State, Instance from exprs.ExprsConstants import StateRef, lightblue, PIXELS from exprs.Set import Action from exprs.__Symbols__ import Anything, _self class ChoiceButton(InstanceMacro): """ChoiceButton(choiceval, choiceref, content, background, background_off) [most args optional] displays and permits control of a choice variable stored externally in choiceref, looking like Overlay(background, content) or Overlay(background_off, content) when its own choice value is chosen or unchosen (ie equal or unequal to the stored one), respectively. Most args are optional with useful defaults, or can be given as simpler convenience types (eg colors or text); all args but choiceval can be given as named options, which is useful for customization. (Example: it's useful to put several of these with the same choiceref but different choicevals into a Column. This can be done by mapping one customized variant over a list of choicevals.) The choosing-action occurs on_press of entire thing -- this is not yet changeable (to other kinds of button actions), but should be. #e """ # args choiceval = Arg(Anything) #e declare it as having to be constant per-Instance? Or can it legally vary?? I guess it could; # and I guess it's no error, just weird, for two of these (eg in a column) to share the same choiceval; # in fact, if they're physically separated it's not even weird. sbar_text = Option(str, format_Expr("%s", _self.choiceval)) # mouseover text for statusbar choiceref = ArgOrOption(StateRef) ###k need value-type?? content = ArgOrOption(stubtype, TextRect(format_Expr("%s", _self.choiceval)) ) # Widget2D or something "displayable" in one (eg text or color); defaults to displayed choiceval; # can caller pass a formula in terms of the other options to _self? # Maybe, but not by saying _self! _this(ChoiceButton) == _my? [yes -- _my is now implemented, 061205] background = ArgOrOption(stubtype, Rect(_self.width, _self.height, lightblue) ) # Widget2D, or color (used in Rect a bit larger than content) background_off = ArgOrOption(stubtype, Spacer(_self.width, _self.height)) # ditto, defaults to transparent ##k problem: what we want is to compute an lbox and then use this here in the spacer... or align the content... or .... ##e note that a lot of people find it more convenient to pass around a size, or even pass around a rect, # than to always work with 4 or 6 rect-related attrs... # formulae chosen = eq_Expr( choiceref.value, choiceval) #k ## print "chosen is",chosen ###k assume useful conversions of named options happened already ###e use _value; is it as simple as renaming it delegate and using DelegatingMixin?? Can InstanceMacro do it for us?? # [if we use one of those, be careful not to inherit from Widget2D here, due to its lbox defaults!] _value = Highlightable( Overlay( SpacerFor(Boxed(content)), # kluge to make room around content in _self.width and _self.height, # and make those non-circular; WRONG because won't be properly aligned with backgrounds, # even if content itself would be; # could fix by shifting, but better to figure out how to have better rectlike size options ###e Overlay( ###KLUGE since "Overlay is a stub which only works with exactly two args" If(chosen, background, background_off), content ), ), ## old code: on_press = SetStateRefValue(choiceref, choiceval), # try this code 061211 1113a -- it works, use it: on_press = Set(choiceref.value, choiceval), ##e probably best to say Set(choiceref.value, choiceval), but I think that's nim -- not sure -- # should retest it after Set is revised later today to work with arg1 being lval eg getattr_Expr [061204] sbar_text = sbar_text ) pass # end of class ChoiceButton # == ####e refile these: ##class Apply(InstanceMacro): # guess, 061130 ## func = Arg(Function) ## arg = Arg(Anything) # exactly 1 arg for now ## if 1: # init instance? no, init_expr i think? but self.func is not defined by then, is it? it is, but self is not special... ## func_expr = self.func( _self.arg) ## _value = call_Expr()#... ## pass def Apply(func, arg1_expr): # exactly 1 arg for now arg1sym = _self._arg1 # make a symbol based on _self (not affected by arg1_expr in any way) func_expr = func(arg1sym) # feed it to the lambda to get the expr we want, relative to _self return _Apply_helper(func_expr, arg1_expr) ##e or could pass a list of args... and exprs like _self._args[i] # an expr which instantiates arg1_expr, # then acts as if its ._value = func_expr (with _self in func_expr captured by that instance), used by InstanceMacro(??), # and its ._arg1 = arg1_expr (but WAIT, how would that end up being visible to _self._arg1? Ah, by _self replacement...) class _Apply_helper(InstanceOrExpr, DelegatingMixin): delegate = Arg(Anything) ### but unlike usual, _self in the arg passed in refers to the same as _self inside, so gets replaced... _arg1 = Arg(Anything) #e something to affect _self replacement def _i_grabarg_0( self, attr, argpos, dflt_expr): external_flag, res0 = super(_Apply_helper, self)._i_grabarg_0( attr, argpos, dflt_expr) if argpos == 0: ## print "using False for extflag in %r from _i_grabarg_0%r" % ( (external_flag, res0), (self, attr, argpos, dflt_expr) ) external_flag = False # special case for arg[0]: treat _self as internal, so it refers to our instance, not caller's return external_flag, res0 pass # == # test status 061130: works, except that a click is only noticed (or a mouseover sbar msg given) for the one that's currently chosen, # so you can't change the current choice. hmm. ## def make_testexpr_for_ChoiceButton(): #e call me from test.py to make a [#e list of named?] testexprs for this def ChoiceColumn( nchoices, dflt = 0, **kws): ##e should be an InstanceMacro, not a def! doesn't work to be customized this way. "#doc" #e nim: Column -- esp on list like this -- Column( map(...)) -- so use SimpleColumn return Apply( lambda stateref_expr, nchoices = nchoices, dflt = dflt, kws = kws: SimpleRow( # stateref_expr will be a Symbol when this lambda is run, to produce an expr, once only SimpleColumn( * map( ChoiceButton(choiceref = stateref_expr, **kws), range(nchoices) ) ), # choose TextRect( format_Expr( "choice is %%r (default %s)" % dflt, stateref_expr.value ), 1, 30) # show choice ), LocalVariable_StateRef(int, dflt) # LocalState, combining this and the Apply? # or, just a stateref to some fixed state somewhere... whose instance has .value I can get or set? use that for now. ##k is there any way to use the new-061203 State macro for this? ) def ChoiceRow( nchoices, dflt = 0, **kws): ##e should be an InstanceMacro, not a def! doesn't work to be customized this way. "#doc" #e nim: Row -- esp on list like this -- Row( map(...)) -- so use SimpleRow return Apply( lambda stateref_expr, nchoices = nchoices, dflt = dflt, kws = kws: SimpleRow( # stateref_expr will be a Symbol when this lambda is run, to produce an expr, once only SimpleRow( * map( ChoiceButton(choiceref = stateref_expr, **kws), range(nchoices) ) ), # choose TextRect( format_Expr( "choice is %%r (default %s)" % dflt, stateref_expr.value ), 1, 30) # show choice ), LocalVariable_StateRef(int, dflt) # LocalState, combining this and the Apply? # or, just a stateref to some fixed state somewhere... whose instance has .value I can get or set? use that for now. ##k is there any way to use the new-061203 State macro for this? ) # == # how far are we from doing ChoiceRow as a class, nicely expressed? [061214 Q/exper] # in light of the attempt below: # - biggest need is dealings with iterated args of several kinds: # - OptionsDict # - Row over made list of things # - making those things, by iterating a ChoiceButton expr # - we might also need a way to turn _self.var into a stateref we can pass into ChoiceButton as its choiceref ###e conclusion: too far to be held up by doing it, but worth thinking about, since we *DO* need to solve all those Qs pretty soon. # One approach is to say # - "assume we want *-expr and map-Expr for use in SimpleRow( * map( expr, varying args/opts for expr ))" # - and come up with simplest syntax for that we can. # - then we'd probably need to resolve "iterator expr" (eval/instantiate) issues too. # - Another is to say "do that iteration in python methods or lambdas", # but make it easier to integrate those with toplevel formula exprs. # (An argument for this is that people already know how -- no need to learn new syntax. # A disadvantage is that the iteration won't be incrementally updated, only the whole thing at once will update.) # So the Apply above happens in some method of the class -- perhaps _C__value -- not sure that works if nchoices can vary, # but they can't vary anyway in the current def. def OptionsDict(type = Anything): return Option(type) ###STUB just so parsing works, totally wrong in effect class ChoiceRow_class(InstanceMacro): # stub, nim nchoices = Arg(int) dflt = Arg(int, 0) kws = OptionsDict() ###IMPLEM #e see if name is correct re other proposals, eg Options not Option? #e renamekws tosay what they are for -- the ChoiceButton --- note that we could ditch the OptionsDict and ask for # an explicit dict of them, but then they would not be indivly customizable. Should a new sub-option cust scheme be made? #e var = State(int, _self.dflt) ###k does _self.dflt work? Is this equiv to the above? NO, it's an lval not a stateref! _value = SimpleRow( 0 ###stub -- the next hard thing is to apply this to a variable number of exprs or insts created by map over range(nchoices) ) pass # == checkbox_image = IconImage(ideal_width = 25, ideal_height = 21, size = Rect(25 * PIXELS, 21 * PIXELS)) # a pure expr # WARNING: dup code & comment with tests.py, WHICH PROBABLY IMPORTS * from here # note, IconImage ought to use orig size in pixels but uses 22x22, # and ought to display with orig size but doesn't -- all those image options need reform, as its comments already know ###e #e see also checkbox_v2 in tests.py for use in testexpr_16b class checkbox_v3(InstanceMacro): ##e rename # note: this can do something checkbox_pref can't yet do -- take an external stateref stateref = Arg(StateRef, None) ### default? might not work with a default val yet ### IMPLEM: specify what external state to use, eg a prefs variable, PrefsKey_StateRef(displayOriginAxis_prefs_key) defaultValue = Option(bool, False) ###BUG -- not used! [noticed 061215] ## var = State(bool, defaultValue) var = stateref.value ## # print "var = %r" % (var,) # TypeError: 'module' object is not callable - on line that says on_press = Set(var, not_Expr(var) ) ## # solved: it's probably from above: import Set; from Set import something else but not Set _value = Highlightable( If( var, checkbox_image('mac_checkbox_on.png'), checkbox_image('mac_checkbox_off.png'), ), ## on_press = Set(var, not_Expr(var) ) # wanted (sort of), but doesn't work yet, as explained here: ## AssertionError:... <C_rule_for_formula at 0xff2de10 for 'var' in 'checkbox_v3'> should implement set_for_our_cls # ah, I was assuming "var = stateref.value" would alias var to obj.attr permitting set of obj.attr by set of var, # but of course, that should probably never be permitted to work, since it looks like we're changing self.var instead! # Unless, I either: # - implem a variant of "var = stateref.value" # - decide that since var would normally be unsettable when defined by a formula, that always aliasing it like that # would be ok (often wanted, not too confusing). # PROBLEM WITH PERMITTING IT: you might start out var = State(), and it works to change self.var, # then change var to a formula, and forget you were directly setting it... causing an unwanted actual working set # of other state which you thought you were not touching or even able to touch. # SOLUTION: # - implem a variant of "var = stateref.value, sort of a "state alias" # - have a clear error message from this Set, suggesting to change that assignment to that alias form. # as of 061204 418p: tentatively decided I like that, but the alias variant syntax is not yet designed. # Maybe: ####@@@@ # - var = Alias(stateref.value) ?? [sounds good] # - or just var = State(stateref.value), or is that too confusing? # [yes, too confusing, that arg is for the type, and State is for new state, not an alias... latter is lesser problem] # - or var = StateRef(stateref.value)? no, it's an lval, not a stateref. on_press = Set(stateref.value, not_Expr(var) ) # kluge: see if this works (I predict it will) -- workaround of not yet having that alias form of "var = stateref.value" ) pass # end of class checkbox_v3 def checkbox_pref_OLDER(prefs_key, label, dflt = False): # renamed 061215 late, since newer one is better "#doc" if type(label) == type(""): label = TextRect(label,1,20) return SimpleRow(CenterY(checkbox_v3(PrefsKey_StateRef(prefs_key, dflt))), CenterY(label)) # align = CenterY is nim # note: adding CenterY also (probably coincidentally) improved the pixel-alignment (on g5 at least), so the label is no longer fuzzy. # [see also testexpr_16c, similar to this] class checkbox_pref(InstanceMacro): #e rename -- Checkbox(...), with various kinds of args to say what state it uses in different ways? #e make it one of several prefs controls for other types of pref and control #e generalize to all named state -- e.g. see also LocalVariable_StateRef -- permit passing in the stateref? #e get dflt label from stateref?? # note: this was split out of kluge_dragtool_state_checkbox_expr 061214, # extended here into a def (later renamed checkbox_pref_OLDER), then a class prefs_key = Arg(str) label = Arg(Anything) # string or Widget2D dflt = ArgOrOption(bool, False) sbar_text = Option(str, '') use_label = If( call_Expr(lambda label: type(label) == type(""), label), TextRect(label), label ) ## was TextRect(label,1,20) use_sbar_text = or_Expr( sbar_text, If( call_Expr(lambda label: type(label) == type(""), label), label, "" )) stateref = Instance(PrefsKey_StateRef(prefs_key, dflt)) # note: without Instance here, next line stateref.value says (correctly): ## AssertionError: compute method asked for on non-Instance <PrefsKey_StateRef#47221(a)> var = stateref.value checkbox = If( var, checkbox_image('mac_checkbox_on.png'), checkbox_image('mac_checkbox_off.png'), ) _value = DisplayListChunk( Highlightable( SimpleRow( CenterY(checkbox), CenterY(use_label)), # align = CenterY is nim ## on_press = Set(debug_evals_of_Expr(stateref.value), not_Expr(var) ), #070119 debug_evals_of_Expr - worked on_press = _self.on_press, # the following works too, but I wanted to intercept it to add some py code [070305]: ## Set( stateref.value, not_Expr(var) ), sbar_text = use_sbar_text) ) # note: using DisplayListChunk in _value works & is faster [070103] #070124 comment: the order DisplayListChunk( Highlightable( )) presumably means that the selobj # (which draws the highlightable's delegate) doesn't include the displist; doesn't matter much; # that CenterY(use_label) inside might be ok, or might be a bug which is made up for by the +0.5 I'm adding to drawfont2 # in testdraw.py today -- not sure. incr_drawable = Instance( Boxed( CenterY(checkbox), pixelgap = 0, bordercolor = gray, borderwidth = 2 )) # I tried orange as a warning color -- means the checkbox reflects an intention but not yet the reality. # But it was annoyingly too visible. So I'll try gray. # If all colorboxeds are unpopular, then try an image that has a little spray of lines coming from the center, instead. def on_press(self): self.stateref.value = not self.stateref.value # was, in the expr: Set( stateref.value, not_Expr(var) ) ###e revise this code to use self.draw_incrementally once that's refiled into Highlightable ###e def func(self = self): self.incr_drawable.draw() ## self.draw() # includes the label - probably a waste but who cares self.env.glpane.swapBuffers() # update display [needed] ran_already_flag, funcres = self.run_OpenGL_in_local_coords( func) # this method runs in the Highlightable made in _value assert ran_already_flag return pass # end of class checkbox_pref ###BUG: whatever I do, I can't get reloading of controls.py (this file) and test.py to cause code changes in on_press above # to take effect -- not even modifying the _value expr before the reload, changing the current test by cmenu, # or by editing testexpr assignment in test.py. sanity check -- try rerunning NE1 app - yep, that works. repeatable. # So far it's a complete ###MYSTERY. I was wondering if the Instance that makes value hangs onto it, but altering expr # ought to have either fixed that or warned me that it changed -- I hope. Nonetheless that's my best guess so far. # Note (prob not related): recent NE1 startup times have sometimes been very long -- is it checking for sponsors??? [070305] class ActionButton(DelegatingInstanceOrExpr): # 070104 quick prototype "ActionButton(command, text) is something the user can press to run command, which looks like a button." # args/options command = Arg(Action) #e default which prints? text = Arg(str, "<do it>") #e default text should be extracted from the command somehow button = Arg(Widget2D, Rect(15.*PIXELS)) # can it be left out so only text label is used? ideally we'd have text with special border... enabled = Option(bool, True) # whether the button should look enabled, and whether the command will run when the button is operated # formulae use_label = TextRect(text) ## TextRect(text,1,20)###e revise plain_button = CenterY(button) highlighted_button = Boxed( plain_button, # note: despite the name, this is only shown as the highlighted form when enabled is true bordercolor = blue, # should color adapt to bg? is it a bad idea to put this over bg rather than over button? borderthickness = 1.5 * PIXELS, gap = 1 * PIXELS, ) ###k ???? -- note, this doesn't include the label -- ok? plain = DisplayListChunk( SimpleRow( plain_button, CenterY(use_label))) # align = CenterY is nim highlighted = DisplayListChunk( SimpleRow( highlighted_button, CenterY(use_label), pixelgap = 0.5)) #k ok to wrap with DisplayListChunk? [seems so] ### KLUGE: without the pixelgap adjustment (to this particular weird-looking value, i guess), # the label moves to the right when highlighted, due to the Boxed being used to position it in the row. ### BUG: CenterY is not perfectly working. Guess -- lbox for TextRect is slightly wrong. ### IDEA: make the borderthickness for Boxed negative so the border is over the edge of the plain button. Might look better. ##e Note: we have no "pressed" appearance, since by the next time we get drawn, the command is already drawn and we ought to be # back to normal. Someday we should do a transient incremental redraw of just this button, with a "pressed and acting" appearance, # which can then go back to normal when the operation completes and does a regular full redraw. # Alternatively, we could switch to using buttons with an on_release_in action only, # and then have ordinarily-drawn pressed etc looks. [070227 comment] # update 070305: let's try to fix that: # appearances for optional willdoit-flicker (confirms unambiguously that the button was hit and will do something) [070307] # [ideally the computation & side effects could overlap the willdoit flicker in time, # but they don't now, which is one reason the flicker is optional] incr_drawable_willdo1 = Instance( SimpleRow( highlighted_button( bordercolor = yellow), pixelgap = 0.5)) # label not needed here incr_drawable_willdo2 = Instance( SimpleRow( highlighted_button( bordercolor = blue ), pixelgap = 0.5)) # note: yellow/blue (matching the usual ending & starting colors which bracket the flicker) looks much better than black/white # what it looks like while we're computing/doing its effects: incr_drawable_doing = Instance( SimpleRow( highlighted_button( bordercolor = orange), ## CenterY(use_label), [removed -- see comment for why -- might be added back] pixelgap = 0.5)) # orange warns you that it's not yet done, is also bright & active for action; ### UI FLAW: the orange/yellow distinction is annoying, so it's really only desirable for debugging, # since it shows that the instantiation time is significant but only happens on the first use of a button. # Probably the distinction (and its redraw happening at all) should be a debug_pref or so. ###FIX # (But if there is no distinction, we may want to be sure to redraw the label now if there is any chance it can be different -- # but in current code there's not, since we haven't changed state it might depend on by the time we draw it. # BTW I wonder if redrawing the label (i.e. instantiating this instance of it) ever takes significant time itself?? #k) # what it looks like while we're redrawing (after finishing its internal effects): incr_drawable_done = Instance( SimpleRow( highlighted_button( bordercolor = yellow), pixelgap = 0.5)) # label not needed here # yellow means done -- not sure makes sense -- note green means "can do" in some controls def doit(self): """This runs when the user clicks on the button. WARNING: it's NOT just self.do_action() (the public method self's clients, like scripts, can call to do the same action) -- it calls that, but it also has graphical effects. [It may or may not be public (in the Action interface) in the end. If it is, it'll be renamed. #e] """ if self.enabled: # do some incremental drawing [new feature 070305, revised 070307] ###BUG (in some client code of this class): # this won't be able to make clear button quickly show it's disabled until client code is revised and maybe selobj-bugfixed ###DOIT if debug_pref("testmode: ActionButton willdoit-flicker?", # When set, this flickers the button, like how the mac confirms a menu item choice. # Conclusion after testing: it works fine, and usually looks ok, # but is redundant with "yellow during redraw", # so as long as that's slow enough to see, this has no point and is also making it even slower, # so leave it turned off by default. Choice_boolean_False, prefs_key = 'A9 devel/exprs/action flicker' ): # works [retest###], but I won't make it True by default [070307] ##e someday do this in a way that does not tie up the thread during this, e.g. by letting paintGL do it; # for now it's just experimental for its graphics effects and as a speed test, # and will probably be turned off after testing for i in range(4): if i % 2 == 0: self.draw_incrementally( self.incr_drawable_willdo1 ) else: self.draw_incrementally( self.incr_drawable_willdo2 ) # print i, # very fast # todo: delay, if needed to make this visible -- using time.time to delay only if draw timing was not long enough # (with no delay it's almost too fast too see -- sometime I should write the code to measure the actual speed) # (for now assume it's always very fast, so just delay a fixed amount using time.sleep) time.sleep(1.0/3/4) # 1/3 sec, spread over 4 sleeps self.draw_incrementally( self.incr_drawable_doing ) # this method runs in the Highlightable made in delegate print "ActionButton: doing %r for %r" % (self.text, self) ### remove self? ##e optim note: this shows self is a different obj each time (at least for make dna cyl button)... # I guess this is due to dna_ribbon_view_toolcorner_expr_maker being a function that makes an expr # which runs again at least on every use of the button (maybe more -- not sure exactly how often). # Should fix that (and it's not this file's fault -- just that the print stmt above reveals the problem). self.do_action() self.draw_incrementally( self.incr_drawable_done ) pass else: print "ActionButton: not enabled, so not doing %r for %r" % (self.text, self) # remove when works [reenabled 070307 ####] pass return def do_action(self): "#doc -- public, also used internally; see doit comment for doc, for now" res = self.command() if res is not None: print "unexpected: %r cmd %r retval was not None: %r" % (self, self.text, res,) #e remove if happens legitimately return ###e refile these: def draw_incrementally( self, thing):#070307 #e refile (as for next method below) "#doc" self._incrementally_draw_OpenGL( thing.draw ) #e or call a variant method of thing, which defaults to thing.draw?? nah, use an env var? def _incrementally_draw_OpenGL( self, func): #070307 #e rename ###e refile into IorE someday, and into Highlightable for now, i think """helper method for incremental drawing by user event handling methods (not part of self.draw called by paintGL). [#doc better] func should contain OpenGL commands for incrementally drawing, in self's coords (but not the swapbuffers at the end). Guess at a requirement within func: [which should be removed and is prob not real now, see below] # don't use drawkid! (because we're not inside a draw method) # (but will this cause trouble for draw methods inside this?? ### NEEDS REVIEW) [but instead we might as well make sure that drawkid's parent-seeing alg will not be messed up, since it'll be used inside whatever subthing draws we call, anyway] """ ###e undefined in API so far: what if func says "draw later" (eg for transparency) -- do we do all that too, before we return?? # guess: yes, but we'll need special drawing-env settings to tell primitives inside func that we're doing incremental drawing, # since it'll affect things like whether it's ok to write into the depth buffer for transparent objs obscuring visible ones # (useful for glselect code but would mess up subsequent incr drawing). def func1(self = self, func = func): res = func() self.env.glpane.swapBuffers() # update display [needed] return res ran_already_flag, funcres = self.run_OpenGL_in_local_coords( func1 ) # note: this runs in self or first delegate that's a Highlightable, for now; that determines its gl state & coordsys assert ran_already_flag return funcres #e should we change to doing the action on_release_in, rather than on_press? delegate = Highlightable( plain, ##e should this depend on enabled? probably yes, but probably the caller has to pass in the disabled form. ###e at least for the Mac, maybe it also ought to depend on whether the application is active (frontmost) and will respond to clicks. If( enabled, highlighted, plain), # revised 070109 to depend on enabled [#k does this cause the delegate expr itself to be remade??] on_press = _self.doit, # note: there was a bug in the prior form of this, "on_press = command" -- command to do should depend on enabled -- ##e but i'm not sure if If(enabled,command,None) will work properly ###k TRY IT -- nevermind, using _self.doit now [070208] sbar_text = text #e should sbar_text depend on enabled?? yes, but need to revise callers then too -- some of which make the text depend on it ) pass # end of class ActionButton PrintAction = print_Expr ###e refile (both names if kept) into an actions file """ 1. Subject: where i am g5 504p; highlight/text debug ideas the choicebutton bug might be entirely in highlightable vs textrect and not in anything else, based on what it acts like and my guesses in test.py comments about it. next up: did i learn anything from the mess of lambda and localvar and state related kluges in controls.py? (and also debug this bug, or work around it more permanently, eg always draw a rect just behind text, or a same-rect into the depth buffer) (also test this bug for images, since they are drawn the same way as text is) (also scan the code for drawing text or both for an accidental explan like a depth shift, or some disable or mask i forgot about) (also put in some closers into the overlays to see if it's a bug caused by all the things being drawn at the same depth) 2. Subject: BAD CHOICE BUG - wrong one if you move mouse quickly! if you move mouse from top to bot one or vice versa, fast, then click at end w/o slowing down, it can pick 2nd to last one sometimes, as if it uses an old mouse pos without noticing it, or uses an old stencil buffer contents or selobj or something like that. how can it not correctly confirm the one under the click? I'd think it'd update_selobj and find out if it's wrong. does it do that and then see None for selobj and somehow revert back to thinking about the prior value of selobj??? mitigation: make these things hover-highlight, then you'll probably see if you're going too fast; it might help me debug it too. """ # end
NanoCAD-master
cad/src/exprs/controls.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ demo_draw_on_surface.py @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. 070319 a standalone version of the so-called polyline example in demo_drag.py (testexpr_19g) See also: - demo_polyline.py (and the other files it refers to, like demo_ui.py) - TODO comments below - our_testexpr at bottom (substitute for demo_ui until it's ready) """ from OpenGL.GL import GL_LINE_LOOP from OpenGL.GL import glBegin from OpenGL.GL import GL_LINE_STRIP from OpenGL.GL import glVertex3fv from OpenGL.GL import glEnd from utilities.constants import yellow, purple, red, noop from widgets.simple_dialogs import grab_text_using_dialog from exprs.Exprs import list_Expr from exprs.If_expr import If from exprs.Column import SimpleColumn, SimpleRow from exprs.Boxed import Boxed from exprs.TextRect import TextRect from exprs.Rect import Rect from exprs.world import World from exprs.Highlightable import Highlightable, BackgroundObject from exprs.Overlay import Overlay from exprs.controls import checkbox_pref, ActionButton from exprs.draggable import DraggableObject from exprs.projection import DrawInCorner from exprs.Center import Left, Top, Center from exprs.transforms import Translate from exprs.iterator_exprs import MapListToExpr, KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr from exprs.demo_drag import Vertex, kluge_dragtool_state_prefs_key, DZFUZZ from exprs.command_registry import auto_register from exprs.instance_helpers import InstanceOrExpr, DelegatingInstanceOrExpr from exprs.attr_decl_macros import State, Arg, Option, ArgOrOption, Instance from exprs.ExprsConstants import StubType, Width, Color, Point, PM_CORNER, ORIGIN, DZ from exprs.widget2d import Stub from exprs.__Symbols__ import _self, Anything # == ###e plan: make it a demo command file alongside demo_polyline.py. ## Q: needs to run in a highlightable object so self.current_event_mousepoint() is defined -- tho empty space works ok in some manner.... ##just not sure where we get a coordsys for that -- maybe just make a Coordsys object then? ## ##we might rather use abs coords even if we're on an object with local ones!!! #e change class polyline3d to not show the red thing until you're done, and let the red thing be a kid of the polyline3d #e and maybe to always draw closer to screen, but store coords identical to model object -- # use a displist (not yet defined) for translating closer to user # also in the command class define a PM... or is that really part of the object defn? or one of each? # probably the command can override the one for the obj, and say whether to show it also... # what about an "edit obj" command... doesn't that one's PM come from the obj itself? not necessarily... # tho we can hope it's created from the obj. # for the create or edit polyline3d, the only PM need so far is the checkbox for closed. # (initial value from a pref - maybe changing it also changes the pref, when creating one, but when editing one # it connects to the specific one only, not to the pref. So the PMs differ at least in that case.) # so the making of PM needs to be able to differ, for create vs edit. # OTOH we might ask model objs for PM fields, and model objs knowing they were being made could give different kinds... # and have attrs that affected how mod ops to them (done as they are made) are interpreted... # and if this info is on the object itself, the incomplete obj can be saved, which might be good... # so let's put code here which asks the incomplete polyline3d for a list of editable fields, and makes a PM for them. # Can it include the points too? why not? later we'd know to suppress that from the PM unless you open the advanced/complete one... # or we might decl it like that from the start -- a decl on the attribute in the model object. # == ##class polyline_handle(DelegatingInstanceOrExpr): ## delegate = Draggable(Rect(0.3,green)) ###e change super: ModelObject or ModelObject3D or so ###e rename class polyline3d(InstanceOrExpr): # WARNING [070319]: duplicated code, demo_drag.py and demo_draw_on_surface.py [modified a bit] """A graphical object with an extendable (or resettable from outside I guess) list of points, and a kid (end1) (supplied, but optional (leaving it out is ###UNTESTED)) that can serve as a drag handle by default. (And which also picks up a cmenu from self. (kluge!)) Also some Options, see the code. """ # Note [070307]: this class will be superceded by class Polyline in demo_polyline.py, # and the code that uses it below (eg the add_point call) will be superseded by other code in that file. # ###BUGS: doesn't set color, depends on luck. end1 is not fully part of it so putting cmenu on it will be hard. # could use cmenu to set the options. # end1 might be in MT directly and also be our kid (not necessarily wrong, caller needn't add it to MT). # when drawing on sphere, long line segs can go inside it and not be seen. points = State(list_Expr, []) ###k probably wrong way to say the value should be a list ## end1arg = Arg(StubType,None) ## end1 = Instance(eval_Expr( call_Expr(end1arg.copy,)( color = green) ))###HACK - works except color is ignored and orig obscures copy end1 = Arg(StubType, None, doc = "KLUGE arg: optional externally supplied drag-handle, also is given our cmenu by direct mod") closed = Option(bool, False, doc = "whether to draw it as a closed loop") _closed_state = State(bool, closed) ####KLUGE, needs OptionState relative = Option(bool, True, doc = "whether to position it relative to the center of self.end1 (if it has one)") def _init_instance(self): end1 = self.end1 if end1: end1.cmenu_maker = self def _C__use_relative(self): "compute self._use_relative (whether to use the relative option)" if self.relative: try: center = self.end1.center return True except: #e print? return False return False def _C_origin(self): #070307 renamed this to origin from center if self._use_relative: return self.end1.center # this can vary! return ORIGIN ## center = _self.origin #k might not be needed -- guessing it's not, 070307 def add_point(self, pos): "add a point at the given 3d position" pos = pos - self.origin self.points = self.points + [pos] ### INEFFICIENT, but need to use '+' for now to make sure it's change-tracked def draw(self): ###k is it wrong to draw both a kid and some opengl stuff?? not really, just suboptimal if opengl stuff takes long (re rendering.py) self.drawkid(self.end1) # end1 node if self._closed_state: glBegin(GL_LINE_LOOP) # note: nothing sets color. see drawline for how. # in practice it's thin and dark gray - just by luck. else: glBegin(GL_LINE_STRIP) if self._use_relative: # general case - but also include origin (end1.center) as first point! origin = self.origin glVertex3fv(origin) for pos in self.points: glVertex3fv(pos + origin) else: # optim - but not equivalent since don't include origin! for pos in self.points: glVertex3fv(pos) glEnd() #e option to also draw dots on the points [useful if we're made differently, one click per point; and they might be draggable #e] return def make_selobj_cmenu_items(self, menu_spec, highlightable): """Add self-specific context menu items to <menu_spec> list when self is the selobj (or its delegate(?)... ###doc better). Only works if this obj (self) gets passed to Highlightable's cmenu_maker option (which DraggableObject(self) will do). [For more examples, see this method as implemented in chem.py, jigs*.py in cad/src.] """ menu_spec.extend([ ("polyline3d", noop, 'disabled'), # or 'checked' or 'unchecked'; item = None for separator; submenu possible ]) pass # end of class polyline3d # == PropertyGroup = DelegatingInstanceOrExpr class make_polyline3d_PG(PropertyGroup):###e call me ###e revise -- not clear it should refer to a pref #e rename? this name means "PG for the command make_<class>" ###e who supplies this? the command? i guess so. is it a local class inside it? or at least the value of an attr inside it? "contents of property manager group for a polyline3d which is being made" ###e needs some args that let it find that polyline3d or the making-command! ## arg = Arg() #e someday be able to automake this from higher-level contents... but returning a widget is always going to be a possibility # (see also comments in PM_from_groups about this) title = "Polyline Properties" ###e USE ME in PM_from_groups delegate = SimpleColumn( checkbox_pref( kluge_dragtool_state_prefs_key + "bla2", "closed loop?", dflt = False), # only gets closed when done -- ok?? ) pass class PM_from_groups(DelegatingInstanceOrExpr): ###e refile into demo_ui or so, and call it on [make_polyline3d_PG(somearg)] "Make a Property Manager UI from a list of groupbox content widgets (eg columns of field editors) and other info." # args groups = Arg(list_Expr) #e in future these groups need to come with more attrs, like group titles # (WAIT, they already do have a title attr which we don't use here!), # whether they're closable and if so whether initially closed... # and they might include their own Boxed already... # the type decl might say we want a list of PropertyGroupBoxes, # with autoconversion of ParameterGroups to those... message = Option(str, "(PM message goes here)") # this has to be already split into lines, for now; all indentation is stripped # formulae def _C_use_message(self): lines = self.message.split('\n') lines = [line.strip() for line in lines] lines = filter(None, lines) return '\n'.join(lines) use_message = _self.use_message # appearance message_box = Boxed(TextRect(use_message), gap = 0, bordercolor = yellow) group_box_column = MapListToExpr( KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr(Boxed), ###e change to a GroupBox, with a title from the group... groups, KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr(SimpleColumn) ) delegate = SimpleColumn( Left(message_box), Left(group_box_column), ) pass # == class PM_Command(DelegatingInstanceOrExpr): #e review name, etc ##e delegating?? ###k hmm, is it a command, or a CommandRun? can those be same class? "superclass for commands with their own property managers" # default ways to get the PM property_manager_groups = () # typically overridden by a subclass property_manager_message = _self.__class__.__name__ #e improve, use _C_ if needed # typically overridden by a subclass property_manager = Instance( PM_from_groups( _self.property_manager_groups, message = _self.property_manager_message )) # find the world -- maybe this belongs in a yet higher Command superclass? ###e world = Option(World) pass # === class _cmd_DrawOnSurface_BG(Highlightable): "[private helper] background drag event bindings for cmd_DrawOnSurface; intended for use inside BackgroundObject()" # args [needed for sharing state with something] world = Option(World) #e code for event handlers during the drag, eg on_drag def on_press(self): point = self.current_event_mousepoint() newpos = point + DZ * DZFUZZ # kluge: move it slightly closer so we can see it in spite of bg ###e needs more principled fix -- not yet sure what that should be -- is it to *draw* closer? (in a perp dir from surface) #e or just to create spheres (or anything else with thickness in Z) instead? (that should not always be required) ###BUG: DZ is not always the right direction! #e maybe scrap it here, and instead change class polyline3d to always draw itself closer to the screen # than its stored coords, but store coords identical to those of the underlying model object -- # use a globally available displist (nim) for translating closer to the user -- hmm, that has to be different # for each rotational environment you might be inside! So only the graphical env knows its name... node_expr = Vertex(newpos, Center(Rect(0.2,0.2, red ))) newnode = self.world.make_and_add( node_expr, type = "Vertex") #070206 added type = "Vertex" ###e may want to make, but not add... let it be a kid of the polyline3d self.newnode = newnode return def on_drag(self): point = self.current_event_mousepoint() lastnode = self.newnode # btw nothing clears this on mouseup, so in theory it could be left from a prior drag newpos = point + DZ * DZFUZZ # inside a drawable, this is where we'd let the current tool decide what to do, # but in this polyline3d-making command we already know what to do: if not lastnode: print "bug: no self.newnode!!!" else: if not isinstance(lastnode, polyline3d): lastnode = self.newnode = self.world.make_and_add( polyline3d(lastnode), type = "polyline3d" ) ###e should we make and add this polyline3d, but get world to put it inside DraggableObject or so? lastnode.add_point(newpos) return def on_release(self):#070223 new hack import foundation.env as env #FIX - make this unnecessary if isinstance(self.newnode, polyline3d) and env.prefs.get(kluge_dragtool_state_prefs_key + "bla2", False): self.newnode._closed_state = True ####KLUGE, I'd rather say .closed but that won't work until I have OptionState return pass # end of class _cmd_DrawOnSurface_BG class cmd_DrawOnSurface(PM_Command): """A command for creating a new object, a 3d polyline, by drawing it over any visible surface (but the resulting object is in absolute model coords, in this version). To use the command, some UI invokes it, one-time or as a mode, and an object of this class gets created and stored in some global place; then the next mousedown (on_press) on a tool-sensitive object of a kind this command's mousedown filter thinks it's applicable to (perhaps including empty space, though it's unclear which object that corresponds to -- but that doesn't concern this command) calls a method in this command for creating and returning an object to handle the drag (which can be self or some other recycled object, I suppose -- much like how Highlightable returns itself as the DragHandler, I guess). The drag event calls turn into the new object, and something in the end tells the outer stuff whether the new object gets really added or discarded (but it's probably present in the set of model objects from the start, even if it's only provisional -- outer code can decide if it shows up in the MT in that case, and if so, in what way). """ # class constants, presumed to be part of a "registerable command API" # name and description cmd_name = "DrawOnSurface" cmd_desc = "draw 3D polyline over surface" cmd_desc_long = "draw a dense 3D polyline over a 3D surface, following its contours" #e categorization info, so a UI-builder knows where to include this command, how to classify it for browsing -- # this includes what it needs to run, what it creates or modifies #e info about when this command can sensibly be offered, about what kind of command it is in terms of event-capturing # (one drag, many drags, uses selection, etc)... #e for when the command is "active": #e a display style (or mod of one?) to use -- filter what is shown, how its shown -- # or maybe it's one of a family of commands that use the same display style -- then it needs to specify an interface # that it expects drawables to follow, while it's in effect -- and some overlying system has to decide whether to make # a new instance of a model-view and in what style... or maybe this command inserts itself into a tree of commands # and a higher node in the tree (a family of commands, maybe a main command of which this is a subcommand) # supplies the display style (incl filter) for all its subcommands... # ... ultimately this ensures that the drawables know enough for this command # to know how to highlight them, select them (if that can occur while it's active), which ones to operate on # (so it supplies its own selobj or glname filter)... # a property manager ## property_manager_groups = [make_polyline3d_PG] # functions to apply to an arg (which arg? ####), or exprheads, to get PM groups ##### why not just say make_polyline3d_PG(_self)??? property_manager_groups = list_Expr( make_polyline3d_PG(_self) ) property_manager_message = """ Sketch a 3D polyline on any model surface or in free space. [Note: model surface is NIM for click, but works for drag-over.] """ # super should make property_manager from the groups, if we don't make a whole one ourselves [might be already stub-coded] # appearance of world while we're active, including code for click/drag event handlers for objects or bg #e (someday we might need to separate the bg and the rest, so an outer rendering loop can handle them separately) delegate = Overlay( _self.world, # draw whatever is in there ###BUG: actual objects are not yet drawn in a way that lets them delegate drags to us -- only the BG does that yet. # Possible fixes: # 1. One is discussed below -- get the objects to delegate their drag event calls to us, # also passing self for coordsys, altered behavior, etc. Do this by drawing a wrapped version of them that # looks in graphics env for what to do. # 2. Another way might be simpler: in testmode.get_obj_under_cursor, which replaces None with our BackgroundObject, # also replace *other* objects with it, if they are a kind we wish to draw on or cause to be ignored (except for their # pixel depth)! Or, replace them with a wrapped version of themselves, created dynamically... [##k fast enough??] # In general a command may well want to be involved in those highlighting decisions, and that's one way. # (Though we do have to worry about effects on highlighting, between and within drags.) BackgroundObject( _cmd_DrawOnSurface_BG(world = _self.world)), ) pass # end of class cmd_DrawOnSurface #####e TODO: ####@@@@ # Q: how do we get the things in _self.world to draw in the way we want them to? (style, filtering, highlighting) # A: provide them advice on that in our graphics dynenv, which we set up in a wrapper around the above delegation, # which is a drawing-interface (graphics interface) delegation. [or see another easier way, in a comment just above] # # Q: when they get activated, how do they send events to us? # A: put ourself (as CommandRun with event interface they expect, e.g. on_press) into some dynenv var they can find. # # So I need a wrapper sort of like DraggableObject but different, and a scheme for World to draw things # with the right wrapper around them, and the right set of things, based on what the current command/mode favors. # WAIT -- should World do that at all? Maybe it just holds the objs and lets the mode map them into drawables? # Yes, that sounds better. # # For empty space events, when I draw the model through my filter, also draw BackgroundObject(thing to handle them). # [done] # Someday: measure the pixel depth to affect this drawing, after drawing the model, but before drawing the # "front plane of 2d control widgets", # or hover-highlights, or whatever object you're creating based on the depth (eg a polyline3d in this code). # Right now it's measured after all drawing, so it's often too near to the user -- especially bad if you wiggle # the mouse around in one place and go over what you just drew -- because of our drawing it closer by DZFUZZ # (or even storing it closer, as now -- worse in other ways but both are bad in this way). # If you detected what objects owned the pixels, you could leave out the ones # you don't want after the fact, interpolating depths for those points -- imperfect, but better than now, # and no need for measuring intermediate depths or controlling rendering order. Or, you could ask model objs # to compute their ideal depth rather than relying on pixeldepth. When we want to store intrinsic coords rel to them, # we'll need related abilities anyway. It'd have ambiguities for surfaces right on the near clipping plane, though, # unless you could tell the pixels you touched came from specific objects. # === class TextEditField(DelegatingInstanceOrExpr): text = State(str, "(empty)") #e dflt should be an arg, or more to the point, the text should come from a stateref ###DOIT label = Option(str, "(field label)") dialog_title = Option(str, "(title)") dflt_dialog_label = "enter some text; use @@@ for \\n" # a public class attr (for clients to use in longer labels) dialog_label = Option(str, dflt_dialog_label) delegate = Highlightable( SimpleRow(Top(TextRect(label)), Top(TextRect(text))), #e long enough? too long? nlines ok? # Top is for when >1 line in text #e highlight form with blue border? on_doubleclick = _self.on_doubleclick, # on_press -> on_doubleclick -- probably better sbar_text = "double-click to edit textfield", #e cmenu binding too? ) def on_doubleclick(self): ok, text = grab_text_using_dialog( default = self.text, title = self.dialog_title, label = self.dialog_label ) if ok: #e unicode?? (see cad/src MT Node renaming code, or Node.name mmp code, or the Comment Node, # for example code that can handle it) #e filter through a func about what's acceptable? # if it fails, repeat dialog with more specific label? # strip whitespace? etc # eventually customize all that, for now just do what's most useful right here text = text.strip() self.text = text # changes state else: print "cancelled text edit, old text remains: %r" % (self.text,) #e some other place to put a message in the UI? return pass # === # how short can another command be? # ... looks like its UI needs to be thought through, or the longest part will be the scratch comments! #e ColorEdit = TextEditField ###WRONG ARGS color_ref = label = "stubs" ###BTW, StateRefs must not be designed well yet, since I'm always reluctant to use one and/or I forget how. # also I need new HL helpers for them, eg to turn one (eg for Color) into another (for text) using state transforms -- # that latter one needs to be able to reject some sets since they don't meet its conds, noticably by the setting code. # (by raising ValueError??) # Digr: actually, if user can enter color using text, the state should include the text, not only the color derived from it!! # So that helper function might be misguided in this context. Movable = Stub class StatefulRect(DelegatingInstanceOrExpr): ###UNFINISHED but works for now # args rect = ArgOrOption(Movable(Rect), Rect(1,1,yellow), doc = "copy state from a snapshot of this guy's state") ###k not sure of Movable; for now, we ignore it and just grab out the state attrs we happen to know about as Rect attrs # state (maybe stateargs?) width = State(Width, rect.width) height = State(Width, rect.height) color = State(Color, rect.color) # appearance ###k missing the Movable -- does that belong in here, anyway?? delegate = Rect(width, height, color) pass class _cmd_MakeRect_BG(Highlightable): """Background event bindings for dragging out new Rects. (Not involved with selecting/moving/editing/resizing rects after they're made, even if that happens immediately to a rect this code makes from a single drag.) """ # args [needed for sharing state with something] world = Option(World) #e something to share state with a control panel in the PM - unless we just use prefs for that # The drag event handlers modify the following state and/or derived objects (some documented with their defs): # self.rubber_rect = None or a newly made Rect we're dragging out right now # (implemented as a rubberband-object drawable -- NOT a model object -- since it has formulae to our state, not its own state) # # nim: self.newnode = None or a Model Object version of the Rect we're dragging out now, or last dragged out... # in general this may be redundant with "the selection", if dragging out a rect selects it, or shift-dragging it adds it to sel... # note, which of these are change-tracked? the ones used in drawing. that means all of them i guess. startpoint = State(Point, None, doc = "mousedown position; one corner of the rect") #e (or its center, for variants of this cmd) curpoint = State(Point, None, doc = "last mouse position used for the other corner of the rect") making_a_rect_now = State(bool, False, doc = "whether we're making a rect right now, using the current drag") # formulae whj = curpoint - startpoint # contains dims of current rect; only valid while we're making one, or after it's done before next press w = whj[0] ###k what if negative?? evidently we make a neg-width Rect and nothing complains and it draws properly... ###REVIEW h = whj[1] # ditto color = purple # for now -- will be a pref or PM control for the color to use for new rects rubber_rect = Instance( If( making_a_rect_now, Translate(Rect(w,h,color),startpoint)) ) # this Instance is needed, at least by Highlightable # appearance -- note, for superclass Highlightable, this is plain, not delegate, and must be an Instance. # This means it's not good to subclass Highlightable rather than delegating to it. (Especially in example code!) ###FIX ## delegate = _self.rubber_rect plain = _self.rubber_rect # code for event handlers during the drag. def on_press(self): self.startpoint = self.current_event_mousepoint() self.making_a_rect_now = False #k probably not needed # don't make until we drag! self.curpoint = None #k probably not needed, but might help to catch bugs where whj is used when it shouldn't be #e change cursor, someday; sooner, change state to name the desired cursor, and display that cursorname in the PM return def on_drag(self): self.curpoint = self.current_event_mousepoint( plane = self.startpoint ) self.making_a_rect_now = True return def on_release(self): ##e decide whether to really make one... here, assume we do, as long as we started one: if self.making_a_rect_now: node_expr = DraggableObject(StatefulRect(self.rubber_rect)) #e StatefulMovableRect? StatefulSnapshot(self.rubber_rect)?? ###k can we just pass the rubber rect and assume StatefulRect can grab its state from it by taking a snapshot?? ###WRONG for DraggableObject to be here, I think -- it's how we display it -- not sure, at least movability might be here... ### the posn is in the rubber_rect since it has Translate... this seems potentially bad/klugy tho... # older cmts, related: ... also its state needs to include abs posn... # maybe this means, split DraggableObject into event binding part (for this UI) and Movable part (for abs posn state). #k self.newnode = self.world.make_and_add( node_expr, type = "Rect") ###BUG (understood): type = "Rect" is not affecting sbar_text in DraggableObject. Need to add it in StatefulRect itself. self.newnode.motion = self.startpoint ###KLUGE self.making_a_rect_now = False # hide the rubber rect now that the real one is there else: print "fyi: click with no drag did nothing" ##e remove after debug return pass # end of class _cmd_MakeRect_BG class make_Rect_PG(PropertyGroup): "property group contents for making a Rect" # note: classname includes make_Rect rather than MakeRect, # since it might not be the *only* PG for cmd_MakeRect, and it might be shared by other commands' PMs. # (not sure this is sensible) title = "Rect properties" delegate = SimpleColumn( ColorEdit( color_ref, label ), ##e [could put color name into prefs, for now...] #e dimensions? (numeric textfields) co-update with its draggability? yes... #e someday: units, gridding, ref plane, ... ) pass class cmd_MakeRect(PM_Command): """#doc """ # name and description cmd_name = "MakeRect" cmd_desc = "make a screen-aligned rectangle" # in abs coords, with choosable fill color # property manager property_manager_groups = list_Expr( make_Rect_PG(_self) ) property_manager_message = """ Drag out a purple Rect. """ # appearance of world while we're active, including code for click/drag event handlers for objects or bg background = Instance( _cmd_MakeRect_BG(world = _self.world) ) #k might not need to be split out, once bugs are fixed delegate = Overlay( _self.world, background, ####e SHOULD NOT BE NEEDED, but doesn't work anyway BackgroundObject( background ), ) pass # end of class cmd_MakeRect # cmd_MakeRect status as of 070326 mon morn: # - ###TODO: need some visual indication after click, that drag would now make a rect... not sure what it can be... a tiny but toobig one?? # of course the best one is a cursor... how hard can it be to make a cursor? we have tons of example code for it... # and for now, just pick an existing one that looks ok here. # - kluges about copying state, especially abs position # - lots of nfrs, esp color # - don't know why neg widths are working, but my guess is, Rect allows them and doesn't cull when drawing #k; needs cleanup # # mainly, i need to integrate all this with demo_ui.py. # === # short term -- until demo_ui.py works, # make a testexpr which keeps us in the state in which this command is active and its PM is showing. # But the TODO items above are still needed to make this do anything. class whatever(DelegatingInstanceOrExpr): ###e rename # simulates the env that demo_ui will provide (stub version, evolving to be more like it) ui_and_world = Instance(World())##### ###e following needs to permit cmd_DrawOnSurface to vary # (at least let it also be cmd_MakeRect; use a menu of options? or use one ActionButton per command, since more like a toolbar?) # -- but with Instance inside the variation, I think -- # ie it should be a map from the desired cmd expr to the cmd instance -- or, make a new one each time, so it's a cmdrun... # maybe see how demo_ui/toolbar was planning to do it... ###e toolbar = SimpleColumn( ActionButton( _self.do_cmd_DrawOnSurface, "button: cmd_DrawOnSurface"), #e make the text from the command #e the running one should look pressed ActionButton( _self.do_cmd_MakeRect, "button: cmd_MakeRect"), ) ###e show it where? above PM for now? current_cmdrun = State(Anything, None) # what is actually in here? an Instance of a "command run", [btw is None needed??] # or of a command obj that handles multiple runs (ie a command_runner?)... up to it to not get messed up if that happens # (and for now, unfortunately, not remaking it is probably a significant speed optim) # (so should we let an outer command handler have the PM and get reused, but an inner CommandRun get remade? why bother?) def do_cmd_DrawOnSurface(self): #e which name is better: do_cmd or set_cmd? depends on type of command! self._do_cmd( cmd_DrawOnSurface) def do_cmd_MakeRect(self): self._do_cmd( cmd_MakeRect) def _do_cmd( self, cmd): "set self.current_cmdrun, etc..." # do we make a new one if button pressed when one already running?? yes for now. self.current_cmdrun = self.Instance( cmd(world = self.ui_and_world), id(cmd) ) #e cache that expr? index ok? why cache instance? #old cmt: #e args? world? new object? does its super handle some? Command vs CommandRun? pm = current_cmdrun.property_manager corner_stuff = SimpleColumn( toolbar, pm) delegate = Overlay( current_cmdrun, DrawInCorner( corner_stuff, corner = PM_CORNER), ) def _init_instance(self): super(whatever, self)._init_instance() self.do_cmd_MakeRect() # or at least set some command, preferably a "null" or "default" one # note that this resets the current tool state on reload -- not really desirable; # how was demo_ui planning to handle that? ###k pass our_testexpr = whatever() # == ## __register__ = ['cmd_DrawOnSurface'] #e or could be filter(func, dir()) ... ###e is calling a global function clearer? yes. auto_register( globals()) #e or list the objects? # end
NanoCAD-master
cad/src/exprs/demo_draw_on_surface.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ draw_utils.py $Id$ Note: this module does not really belong in the exprs package -- that's its main client, but it contains only pure OpenGL utilities. """ from OpenGL.GL import GL_TEXTURE_2D from OpenGL.GL import glTexCoord2fv from OpenGL.GL import glColor4fv from OpenGL.GL import GL_QUADS from OpenGL.GL import glColor3fv from OpenGL.GL import GL_LIGHTING from OpenGL.GL import glDisable from OpenGL.GL import GL_TRIANGLES from OpenGL.GL import glBegin from OpenGL.GL import glVertex3fv from OpenGL.GL import glEnd from OpenGL.GL import glEnable from OpenGL.GL import GL_QUAD_STRIP from OpenGL.GLU import gluUnProject from geometry.VQT import norm, A from Numeric import dot from array import array # == def mymousepoints(glpane, x, y): #bruce 071017 moved this here from testdraw.py ### TODO: rename, docstring # modified from GLPane.mousepoints; x and y are window coords (except y is 0 at bottom, positive as you go up [guess 070124]) self = glpane just_beyond = 0.0 p1 = A(gluUnProject(x, y, just_beyond)) p2 = A(gluUnProject(x, y, 1.0)) los = self.lineOfSight # isn't this just norm(p2 - p1)?? Probably not, if we're in perspective mode! [bruce Q 061206] # note: this might be in abs coords (not sure!) even though p1 and p2 would be in local coords. # I need to review that in GLPane.__getattr__. ###k k = dot(los, -self.pov - p1) / dot(los, p2 - p1) p2 = p1 + k*(p2-p1) return (p1, p2) # == new LL drawing helpers def draw_textured_rect(origin, dx, dy, tex_origin, tex_dx, tex_dy): """ Fill a spatial rect defined by the 3d points (origin, dx, dy) with the 2d-texture subrect defined by the 2d points (tex_origin, tex_dx, tex_dy) in the currently bound texture object. """ glEnable(GL_TEXTURE_2D) glBegin(GL_QUADS) glTexCoord2fv(tex_origin) # tex coords have to come before vertices, I think! ###k glVertex3fv(origin) glTexCoord2fv(tex_origin + tex_dx) glVertex3fv(origin + dx) glTexCoord2fv(tex_origin + tex_dx + tex_dy) glVertex3fv(origin + dx + dy) glTexCoord2fv(tex_origin + tex_dy) glVertex3fv(origin + dy) glEnd() glDisable(GL_TEXTURE_2D) def draw_textured_rect_subtriangle(origin, dx, dy, tex_origin, tex_dx, tex_dy, points): #070404 modified from draw_textured_rect """ Like draw_textured_rect, but draw only the sub-triangle of the same rect (textured in the same way), where the subtriangle has relative 2d vertices as specified inside that rect (treating its own coords as each in [0.0, 1.0]). WARNING: depending on the glEnables set up by the caller, the sub-triangle coords might need to be in CCW winding order for the triangle to be visible from the front. """ #e could easily generalize API to polygon, and this implem to convex polygon, if desired ##e WARNING: this function's name and api are likely to be revised; # or we might just replace the whole scheme, using things like Textured(Triangle(...),...) instead, # perhaps implemented by telling OpenGL how to compute the texture coords in a wrapper, then just drawing the triangle. assert len(points) == 3 # and each point should be a V of length 2, or a 2-tuple, with elements convertible to floats -- this is assumed below glEnable(GL_TEXTURE_2D) glBegin(GL_TRIANGLES) for px, py in points: px = float(px) py = float(py) glTexCoord2fv((tex_origin + px * tex_dx + py * tex_dy).tolist()) # glVertex3fv(origin + px * dx + py * dy) glEnd() glDisable(GL_TEXTURE_2D) # Ideally we'd modularize the following to separate the fill/color info from the shape-info. (And optimize them.) # For now they're just demos that might be useful. def draw_filled_rect(origin, dx, dy, color): ## print 'draw_filled_rect',(origin, dx, dy, color) #####@@@@@ glDisable(GL_LIGHTING) # this allows the specified color to work. Otherwise it doesn't work (I always get dark blue). Why??? # guess: if i want lighting, i have to specify a materialcolor, not just a regular color. (and vertex normals) try: len(color) except: print "following exception in len(color) for color = %r" % (color,) # 061212 -- why didn't caller's fix_color catch it? ##k raise if len(color) == 4: glColor4fv(color) if 0 and color[3] != 1.0: print "color has alpha",color ####@@@@ else: glColor3fv(color) ## glRectfv(origin, origin + dx + dy) # won't work for most coords! also, ignores Z. color still not working. glBegin(GL_QUADS) glVertex3fv(origin) #glColor3fv(white)# glVertex3fv(origin + dx) # glColor3fv(white) # hack, see if works - yes! #glColor3fv(color)# glVertex3fv(origin + dx + dy) #glColor3fv(white)# glVertex3fv(origin + dy) glEnd() glEnable(GL_LIGHTING) # should be outside of glEnd! when inside, i got infloop! (not sure that was why; quit/reran after that) def draw_filled_triangle(origin, dx, dy, color): glColor3fv(color) glDisable(GL_LIGHTING) glBegin(GL_TRIANGLES) glVertex3fv(origin) glVertex3fv(origin + dx) glVertex3fv(origin + dy) glEnd() glEnable(GL_LIGHTING) def draw_filled_rect_frame(origin, dx, dy, thickness, color): """ draw something that looks like a picture frame of a single filled color. """ tx = thickness * norm(dx) ty = thickness * norm(dy) ## glColor3fv(color) ### this has an exception (wants 3 elts, gets 4) in Mac A9.1-rc1 # (i.e. in the Mac "Gold" PyOpenGL for A9.1), so instead, do the following: [bruce 070703] glColor3fv(color[:3]) glDisable(GL_LIGHTING) glBegin(GL_QUAD_STRIP) glVertex3fv(origin) glVertex3fv(origin + tx + ty) glVertex3fv(origin + dx) glVertex3fv(origin + dx - tx + ty) glVertex3fv(origin + dx + dy) glVertex3fv(origin + dx + dy - tx - ty) glVertex3fv(origin + dy) glVertex3fv(origin + dy + tx - ty) glVertex3fv(origin) glVertex3fv(origin + tx + ty) glEnd() glEnable(GL_LIGHTING) # end
NanoCAD-master
cad/src/exprs/draw_utils.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ State_preMixin.py - help classes define change-tracked attributes using the State macro @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: 080910 bruce split this out of test_connectWithState.py, since it's been used in real code for some time """ from exprs.ExprsMeta import ExprsMeta from exprs.IorE_guest_mixin import IorE_guest_mixin class State_preMixin( IorE_guest_mixin): # TODO: refile (alongside IorE_guest_mixin ? in its own file?), once cleaned up & bugfixed -- # note, as of 080128 or so, this is used in real code. """ Use this as the *first* superclass (thus the _preMixin in the name) in order to permit use of the State macro in the class assignments which set up instance variable defaults in a given class. The glpane (*not* the commandSequencer!) must be passed as the first argument to __init__. """ # the following are needed for now in order to use the State macro, # along with the IorE_guest_mixin superclass; this may be cleaned up: __metaclass__ = ExprsMeta _e_is_instance = True ### REVIEW: can the superclass define this, since to work as a noninstance you need a special subclass? _e_has_args = True # not needed -- only purpose is to remove "w/o a" from repr(self) def __init__(self, glpane, *args, **kws): DEBUG_INIT = False # if True, enables some debug prints in console if DEBUG_INIT: print "State_preMixin.__init__", glpane, args, kws IorE_guest_mixin.__init__(self, glpane) # REVIEW: should callers do the following, not us? if DEBUG_INIT: print " State_preMixin.__init__ will call", super(State_preMixin, self).__init__ ## <bound method test_connectWithState.__init__ of <test_connectWithState#4789(i w/o a)>> # note: the following debug output suggests that this would cause # infinite recursion, but something prevents it from happening at all # (it seems likely that no call at all is happening, but this is not yet # fully tested -- maybe something different is called from what's printed) # ##debug fyi: starting DnaSegment_EditCommand.__init__ ##State_preMixin.__init__ <GLPane 0> () {} ## State_preMixin.__init__ will call <bound method DnaSegment_EditCommand.__init__ of <DnaSegment_EditCommand#6986(i)>> ## State_preMixin.__init__ returned from calling <bound method DnaSegment_EditCommand.__init__ of <DnaSegment_EditCommand#6987(i)>> ##debug fyi: inside DnaSegment_EditCommand.__init__, returned from State_preMixin.__init__ super(State_preMixin, self).__init__(glpane, *args, **kws) # this is not calling ExampleCommand.__init__ as I hoped it would. I don't know why. ###BUG # (but is it calling anything? i forget. clarify!) if DEBUG_INIT: print " State_preMixin.__init__ returned from calling", super(State_preMixin, self).__init__ pass # end
NanoCAD-master
cad/src/exprs/State_preMixin.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ StatePlace.py - help InstanceOrExpr or its subclasses define and store state, in layers [#redoc that] $Id$ note: this used to be part of staterefs.py; split it out on 061203 """ from exprs.__Symbols__ import _self from exprs.Exprs import call_Expr from exprs.py_utils import attrholder from exprs.lvals import LvalDict2, LvalForState, LvalError_ValueIsUnset from utilities import debug_flags # == def StatePlace(kind, ipath_expr = _self.ipath, tracked = True): # revised 061117 # experimental, but used and working in Highlightable [that use moved to InstanceOrExpr 061126]; related to Arg/Option/Instance """In a class definition for an InstanceOrExpr subclass, use the assignment <kind>_state = StatePlace(<kind>, <ipath_expr>) (for a short string <kind>, usually one of a small set of conventional kinds of storage) to cause self.<kind>_state in each Instance to refer to external state specific to <ipath_expr> as evaluated in that Instance (by default, _self.ipath, meaning specific to that Instance, though usually more persistent than it, perhaps depending on <kind>). By default, that state is fully usage-tracked and change-tracked; it should only be changed when processing a mouse click or keystroke or similar user action, and changing it will invalidate any model variables or drawing side effects that used the prior value of the same state. (Changing it *during* model computations or drawing code can cause undetected errors and/or detected bad bugs.) If tracked = False, then that state is not usage-tracked or change-tracked at all. This is appropriate for certain "kinds" of state, e.g. temporary per-frame variables used for drawing code. (Some such state could probably just be stored in each Instance, but this is not yet clear. #k) It's usually necessary to initialize the contents of the declared stateplaces using set_default_attrs in _init_instance, or the like. (Note that the stateplace is often found rather than created, and the same sometimes goes for individual attrs within it. Both this StatePlace declaration and set_default_attrs take this into account by only initializing what's not already there.) See also the [nim] State declaration for use with individual attrs. """ # Implem notes: # # StatePlace() works by turning into a formula which will eval to a permanent reference # to a (found or created) attrholder for storing state of the given kind, at the given ipath # (value of ipath_expr), relative to the env of the Instance this is used in (i.e. to _self.env). # [revision 061117: the persistent state itself needs usage and change tracking. The attrholder # could be permanent and own that state (and do that tracking), or be a transient accessor to it [did it that way].] # # WARNING/BTW: when I reload, the data should be persistent, but the subscriptions to it probably shouldn't be. # But that's really up to each subs -- clearing all of them would be wrong. So ignore it for now. # (It means old objects will get invalidated, but that loses them their subs, and nothing recomputes their attrs # and resubs them, so it actually doesn't end up causing a lasting performance problem, I think. Review sometime. #k) assert isinstance(tracked, bool) or tracked in (0,1) assert isinstance(kind, str) res_expr = call_Expr( _StatePlace_helper, _self, kind, ipath_expr, tracked ) return res_expr # from StatePlace def _StatePlace_helper( self, kind, ipath, tracked): # could become a method in InstanceOrExpr, if we revise StatePlace macro accordingly """Create or find, and return, a permanent attrholder for access to all attrs with the given ipath, which are usage-and-change-tracked iff tracked is true. """ # [revision 061117: the persistent state itself needs usage and change tracking. The attrholder # can be permanent and own that state (and do that tracking), or be a transient accessor to it [done here]. # [061121 added back the tracked=False possibility.] # # implem scratch 061117: # what needs permanence is the lvals themselves. They will someday be in arrays (one attr, many objects), # but the attrholders are one object, many attrs, so let's keep the lvals outside the attrholders, # so they are not holders but just accessors. Let's simplify for now, by not keeping persistent attrholders at all, # making them nothing but access-translators (knowing kind & ipath to combine with each attr) # into one big persistent LvalDict. Or maybe one per kind, if we feel like it, and to get practice # with letting the LvalDict to use vary. Hmm, might as well make it one per kind/attr pair, then -- # but that means all the work is in the attraccessors (since we don't even know the key to identify # the LvalDict until we know the attr) -- ok. if not tracked: # [devel note: this is just the old code for _StatePlace_helper from before it supported "tracked".] state = self.env.staterefs key = (kind,0,ipath) #e someday, kind should change which state subobj we access, not just be in the key # Note: this needs to be not interfere with _attr_accessor, whose key is (kind,attr) -- thus the extra 0 res = state.setdefault(key, None) # I wanted to use {} as default and wrap it with attr interface before returning, e.g. return AttrDict(res), # but I can't find code for AttrDict right now, and I worry its __setattr__ is inefficient, so this is easier: if res is None: res = attrholder() state[key] = res return res res = _attr_accessor( self.env.staterefs, kind, ipath, debug_name = debug_flags.atom_debug and ("%r|%s" % (self,kind))) # we leave ipath out of the debug_name, since the accessor's LvalDict2 will add it in in the form of its key return res # from _StatePlace_helper class _attr_accessor: """[private helper for _StatePlace_helper]""" ##e optim: someday we should rewrite in C both this class, # and its storage & usage-tracking classes (LvalDict2, Lval, etc), # for speed & RAM usage] ##e NIM: doesn't yet let something sign up to recompute one attr's values; only lets them be individually set. # This might be a problem. BTW to do that well it might need to also be told a model-class-name; # we can probably let that be part of "kind" (or a new sibling to it) when the time comes to put it in. def __init__( self, staterefs, kind, ipath, debug_name = None): self.__dict__['__staterefs'] = staterefs self.__dict__['__kind'] = kind self.__dict__['__ipath'] = ipath self.__dict__['__debug_name'] = debug_name ## self.__dict__['__tables'] = {} def __get_table(self, attr): kind = self.__dict__['__kind'] whichtable = (kind,attr) # WARNING: this key is assumed in _StatePlace_helper, since it needs to not interfere with it ## tables = self.__dict__['__tables'] # WRONG, store them in staterefs staterefs = self.__dict__['__staterefs'] tables = staterefs try: res = tables[whichtable] except KeyError: # (valfunc computes values from keys; it's used to make the lval formulas; but they have to be resettable) valfunc = self.valfunc ###e should use an initval_expr to make this debug_name = self.__dict__['__debug_name'] if debug_name: debug_name = "%s.%s" % (debug_name, attr) tables[whichtable] = res = LvalDict2(valfunc, LvalForState, debug_name = debug_name) # note: we pass our own lvalclass, which permits set_constant_value return res def valfunc(self, key): # note: as of 061215 this is never overridden, so the usage-tracking LvalDict2's lvals do for it never tracks usage, # but we still need to use Lvals there so we can reset their value. In theory we could use a special kind # which didn't have recomputation-usage-tracking code at all. [i guess, as of 061215] raise LvalError_ValueIsUnset, "access to key %r in some lvaldict in %r, before that value was set" % (key,self) #k [061117 late] use this exception in hopes that it makes hasattr just say an attr is not yet there ##e needs more info, so probably make a lambda above to use as valfunc # [Update 070109: a certain order of file mods (triggering reload_once, each followed by remaking main instance) # can cause a bug of unknown cause which leads to this error. I found it only once, but repeatably, # using the demo_drag example and doing this order of touches: test.py lvals.py demo_drag.py test.py. # The messages mentioned Highlightable#0 -- not sure if that was an inner or outer expr. # Since it only happens in certain reloads, it may not be a "real bug".] pass def __repr__(self):#070109 return "<%s(%s,%s) at %#x>" % (self.__class__.__name__, self.__dict__['__kind'], self.__dict__['__debug_name'] or '', id(self)) def __get_lval(self, attr): # WARNING: in spite of the very private name, this is accessed externally due to a kluge. [070815] table = self.__get_table(attr) # an LvalDict2 object ipath = self.__dict__['__ipath'] dictkey = ipath lval = table[dictkey] # lval might be created at this time (only in one of our two calls) ##k let's hope this doesn't internally ask for its value -- error if it does return lval def __getattr__(self, attr): # in class _attr_accessor return self.__get_lval(attr).get_value() # error if the value was not yet set; maybe we need an initval_expr like the State macro is about to be given ###e def __setattr__(self, attr, val): "WARNING: this runs on ALL attribute sets -- do real ones using self.__dict__" self.__get_lval(attr).set_constant_value(val) ###e probably set_constant_value should be renamed set_value, to fit with StateRefInterface [070312] # note: this optims by noticing if the value differs from last time; that ought to be a per-attr decl #e return def __setattr_default__(self, attr, default): # note: this method name is not special to Python """If attr is not set, set it to default, without doing any usage or change tracking. [Note: This method name and its meaning is a custom extension to Python's general attribute interface consisting of the __getattr__/__setattr__ (and maybe __delattr__?) special methods. This method name is not special to Python itself.] """ self.__get_lval(attr)._set_defaultValue( default) pass # end of class _attr_accessor # == def set_default_attrs(obj, **kws): #e if this was general, we could refile into py_utils, but it turns out it's not general enough """For each attr=val pair in **kws, if attr is not set in obj, set it, without doing usage or change tracking. If obj supports __setattr_default__ (not a special name to Python itself), use that, otherwise use hasattr and setattr (with a temporary dynamic suppression of usage or change tracking, if possible -- nim for now except as an assertion). Note: this is not very efficient (or self-contained) for general use, for which pure hasattr/setattr would be sufficient. """ # Note about why we disable tracking: hasattr itself does legitimately track use of the attr, # since testing thereness does use its "value" in a general sense (as if value was _UNSET_ when not there). # But, in this specific code, we don't want client (caller) to see us using attr, # since from client POV, all we're doing is changing _UNSET_ to v, which are equivalent values # (as client is declaring by calling us). # So we need to discard tracked usage of attr here. # We also need to discard any change from the set to default value, # except that we can probably ignore that issue for now (due to an accident of how current code uses this), # since if the attr is unset, it was never yet used, so invalidating it should have no effect. if 1: from exprs.Exprs import is_pure_expr if is_pure_expr(obj): assert 0, "set_default_attrs called on pure_expr %r is almost surely a bug; normally do it in _init_instance" % (obj,) import foundation.changes as changes try: method = obj.__setattr_default__ except AttributeError: ## print "fyi: set_default_attrs using general case for",obj,kws.keys() # this happens for all non-tracked StatePlaces # general case - let's hope the object doesn't have tracked attrs; the temporary assertion here might not catch this ###e instead, we should actively suppress usage/change tracking, so we can permit it in obj # (tho careless uses of that would lead to bugs) mc = changes.begin_disallowing_usage_tracking('set_default_attrs (hasattr/setattr) for %r' % obj) # note: the argument is just an explanation for use in error messages ##e OPTIM: don't precompute that arg try: for k, v in kws.iteritems(): if not hasattr(obj, k): setattr(obj, k, v) finally: changes.end_disallowing_usage_tracking(mc) else: # use the special method mc = changes.begin_disallowing_usage_tracking('set_default_attrs (__setattr_default__) for %r' % obj) #e optim: remove this check; it only catches usage tracking, not change tracking (ie inval of something by this), anyway try: for k, v in kws.iteritems(): method(k, v) # does its own usage/change-tracking suppression (we assume); this is partially checked (for now) finally: changes.end_disallowing_usage_tracking(mc) return # from set_default_attrs #e useful improvements to set_default_attrs (as used in InstanceOrExpr class defs) might be: [061116] # - shorter name # - able to create new objs of a desired type # (perhaps by using a kw prefix: _type_attr = type, or _init_attr = (type, dfltval aka initarg)) # - or to check the type if the obj is found (same args and call, but ask the type if it agrees that obj is one of its type) # - if obj is wrong type, we might even coerce it, eg add glue code to improve the api, make it relative to our own coords, etc, # if we can do this in our local proxy for the state rather than in the external state. BUT, if we're creating the object too, # we'd better make it clear what type to create it as externally (for others to also see) # vs what type to coerce/glue that too locally (for private use). So we really have to say both the external & local types, # or the external type & local mapping from that, or something like that. # In fact -- maybe even give the two versions different names; which probably implies, # set up a dependency between different external data. # - be able to initialize subattrs, like self.state.x.y -- do by creating x of desired type, then doing x.y inside x -- # but Q, do you do this if x.y is not there in x, but x is already there, or only if even x is not already there? # usually the first, meaning, use two separate calls of this, but can one notation do it all? (and do we need that?) # - we might want a toplevel (expr syntax) version of all this, for use in pure-expr-notation programs; related to LocalState # (see notesfile), esp if that really sets up a local *ref* to perhaps-external state. # In the future, it might work differently -- maybe we won't want attrs with default values to use up space, # when possible (not possible for the ones stored in allocated slots in arrays), so this will be replaced with # some sort of per-class per-kind attr decl, which includes the type & default value. (For that, see the [nim] State decl.) # end
NanoCAD-master
cad/src/exprs/StatePlace.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ DragBehavior_AlongLine.py @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. the DragBehavior in this file improves on the one in test_statearray_2.py: - uses its own coordsys, not the one in the Highlightable - computes the translation from the height (for internal and external use) - has a range limit TODO: needs a refactoring; see comments herein about "refactoring" [following comment came from DragBehavior.py, guessing it was about this class:] maybe revise how it works for off-line points -- not closest in space but closest within a plane perp to screen and -- what? ### """ from exprs.Highlightable import SavedCoordsys from exprs.geometry_exprs import Ray from exprs.Exprs import tuple_Expr from exprs.attr_decl_macros import Arg, Option, Instance from exprs.ExprsConstants import StateRef, ORIGIN from exprs.__Symbols__ import Anything from exprs.DragBehavior import DragBehavior class DragBehavior_AlongLine(DragBehavior): #070318 (compare to SimpleDragBehavior) """ A drag behavior which moves the original hitpoint along a line, storing only its 1d-position-offset along the line's direction [noting that the hitpoint is not necessarily equal to the moved object's origin] [#doc better] """ # args [#e replace 'height' with 'posn_parameter' or 'posn_param' in these comments & docstrings] highlightable = Arg(Anything) ###e is there a way we can require that we're passed an Instance rather than making it ourselves? # I suspect that violating that caused the bug in example 2. # (A way that would work: a specialcase check in _init_instance. # But I'd rather have an option on Arg to do that. require_already_instance?? Or ArgInstance? that latter invites confusion # since it's not analogous to ArgExpr.) posn_parameter_ref = Arg(StateRef, doc = "where the variable height is stored") constrain_to_line = Arg(Ray, doc = "the line/ray on which the height is interpreted as a position") ###e rename: constraint_line? line_to_constrain_to? constrain_to_this_line? # note: the position of the height on this line is typically used as the position of the drawn movable object's origin; # we shouldn't assume the drag startpoint is on the line, since the drawn movable object might be touched at any of its points. ##e rename Ray -> MarkedLine? (a line, with real number markings on it) ParametricLine? (no, suggests they can be distorted/curved) range = Option(tuple_Expr, None, doc = "range limit of height")#nim ##e drag event object can be passed to us... as a delegate! [In recent code, it seems like the Highlightable is taking this role.] # (if this delegates or supers to something that knows all about the drag in a lower level way, # then maybe it's not so bad to be getting dragevent info from self rather than a dragevent arg... hmm. # An argument in favor of that: self is storing state related to one drag anyway, so nothing is lost # by assuming some other level of self stores some other level of that state. So maybe we create a standard # DragHandling object, then create a behavior-specific delegate to it, to which *it* delegates on_press etc; # and we also get it to delegate state-modifying calls to some external object -- or maybe that's not needed # if things like this one's stateref are enough. ##k) # # related: Maybe DraggableObject gets split into the MovableObject and the DragBehavior... # same as in SimpleDragBehavior: saved_coordsys & current_event_mousepoint # state: saved_coordsys = Instance( SavedCoordsys() ) # provides transient state for saving a fixed coordsys to use throughout a drag # helper methods (these probably belong in a superclass): def current_event_mousepoint(self, *args, **kws): #e zap this and inline it, for clarity? or move it into DragBehavior superclass?? return self.saved_coordsys.current_event_mousepoint(*args, **kws) def current_event_mouseray(self): p0 = self.current_event_mousepoint(depth = 0.0) # nearest depth ###k p1 = self.current_event_mousepoint(depth = 1.0) # farthest depth ###k return Ray(p0, p1 - p0) #e passing just p1 should be ok too, but both forms can't work unless p0,p1 are typed objects... # specific methods def _C__translation(self): ### WARNING: used externally too -- rename to be not private if we decide that's ok ###e """ compute self._translation from the externally stored height """ k = self.posn_parameter_ref.value return self.constrain_to_line.posn_from_params(k) #e review renaming, since we are asking it for a 3-tuple def on_press(self): self.saved_coordsys.copy_from( self.highlightable) # needed before using current_event_mousepoint or current_event_mouseray # (since self.highlightable's coordsys changes during the drag) self.startpoint = self.current_event_mousepoint() # the touched point on the visible object (hitpoint) self.offset = self.startpoint - (ORIGIN + self._translation) #k maybe ok for now, but check whether sensible in long run self.line = self.constrain_to_line + self.offset # the line the hitpoint is on (and constrained to, if handle is rigid) # (this is parallel to self.constrain_to_line and intersects the hitpoint) def on_drag(self): # Note: we can assume this is a "real drag" (not one which is too short to count), due to how we are called. mouseray = self.current_event_mouseray() k = self.line.closest_pt_params_to_ray(mouseray) # # BUG: for lines with a lot of Z direction, in perspective view, # this is wrong -- we want the closest point on the screen, # not in space. The current code (closest point in space) # would tend to come up with a point too near the screen, # if the constraint line and the mouseray are diverging away # from each other (in model space) with depth. # # TODO: fix this. Possible fixes include: # - common code, using a projection matrix & its inverse (seems hard) # - separate code for Ortho vs Perspective case (needs eyepoint) # (might be clearest & simplest; it might turn out we'd want other # behavior tweaks which differed in these cases -- for example, # stop dragging and turn the handle red when it gets so far away # in model space (near the "point at infinity" visible on the screen # for an infinite line -- aka the "point of convergence" for a family # of parallel lines) that its motion would be too sensitive, since # the constraint line is too close to perpendicular to the screen) # - save the initial mouseray too, since it gives us enough info # (along with current one) to know the entire projection # (except when they coincide, in which case no motion is needed). # Alg for this is not yet worked out. Q: is an ortho projection # along initial mouseray a good approximation? Probably not, # if we approach the "point at infinity". # # Also we need a refactoring, so that one external object can store # both the geometric info about the constraint, and the state of the # dragpoint along it, accessible as parameter-along-line or point or both, # with either being the underlying state. (Unless nothing less than a # DragBehavior can actually do all those things, in which case, # we need variants depending on whether the point or the parameter # is the underlying state. But more likely, we want a DragState which # knows how to make the underlying state convenient, and a DragBehavior # which knows how to connect that to mouse gestures, so these can vary # separately.) # # [bruce 070913 comment] # if k is not None: # store k, after range-limiting range = self.range # don't use the python builtin of the same name, #in this method! (#e or rename the option?) if range is not None: low, high = range if low is not None and k < low: k = low if high is not None and k > high: k = high self.posn_parameter_ref.value = k ##e by analogy with DraggableObject, should we perhaps save this ##side effect until the end? return def on_release(self): pass pass # end of class DragBehavior_AlongLine # end
NanoCAD-master
cad/src/exprs/DragBehavior_AlongLine.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ ExprsConstants.py -- define constants and simple functions used by many files in this package @author: bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. """ # Note: most or all of the imports from cad/src are no longer needed here, # since the exprs modules that want them import them directly. from geometry.VQT import V # compass positions, also usable for DrawInCorner from utilities.prefs_constants import UPPER_RIGHT from utilities.prefs_constants import UPPER_LEFT from utilities.prefs_constants import LOWER_LEFT from utilities.prefs_constants import LOWER_RIGHT # note: their values are ints -- perhaps hard to change since they might correspond to Qt radiobutton indices (guess) # tell pylint we don't want unused import warnings about those: UPPER_RIGHT from exprs.py_utils import identity # standard corners for various UI elements [070326, but some will be revised soon] WORLD_MT_CORNER = UPPER_LEFT ##PM_CORNER = LOWER_RIGHT #e revise ##DEBUG_CORNER = LOWER_LEFT #e revise PM_CORNER = LOWER_LEFT DEBUG_CORNER = LOWER_RIGHT # == other generally useful constants # (but color constants are imported lower down) # geometric (moved here from draw_utils.py, 070130) ORIGIN = V(0,0,0) DX = V(1,0,0) DY = V(0,1,0) DZ = V(0,0,1) ORIGIN2 = V(0.0, 0.0) D2X = V(1.0, 0.0) ##e rename to DX2? D2Y = V(0.0, 1.0) # type aliases (tentative; see canon_type [070131]) Int = int # warning: not the same as Numeric.Int, which equals 'l' Float = float # warning: not the same as Numeric.Float, which equals 'd' String = str # warning: not the same as parse_utils.String Boolean = bool # == Python and debug utilities, and low-level local defs nevermind = lambda func: identity # == colors (constants and simple functions; import them everywhere to discourage name conflicts that show up only later) #e maybe import the following from a different file, but for now we need to define some here #k need to make sure none of these are defined elsewhere in this module from utilities.constants import red, green, blue, white ##from constants import black, purple, magenta, violet, yellow, orange, pink, gray # note: various defs of purple I've seen: # ave_colors( 0.5, red, blue), or (0.5, 0.0, 0.5), or (0.7,0.0,0.7), or (0.6, 0.1, 0.9) == violet in constants.py ##from constants import aqua, darkgreen, navy, darkred, lightblue from utilities.constants import ave_colors ###e what does this do to alpha? A: uses zip, which means, weight it if present in both colors, discard it otherwise. ###k What *should* it do? Not that, but that is at least not going to cause "crashes" in non-alpha-using code. def normalize_color(color): #070215; might be too slow; so far only used by fix_color method """ Make sure color is a 4-tuple of floats. (Not a numeric array -- too likely to hit the == bug for those.) """ if len(color) == 3: r,g,b = color a = 1.0 elif len(color) == 4: r,g,b,a = color else: assert len(color) in (3,4) return ( float(r), float(g), float(b), float(a)) # alpha will get discarded by ave_colors for now, but shouldn't crash [070215] #e define brown somewhere, and new funcs to lighten or darken a color lightblue = ave_colors( 0.2, blue, white) # WARNING: differs from at least one version of this in constants.py halfblue = ave_colors( 0.5, blue, white) def translucent_color(color, opacity = 0.5): #e refile with ave_colors """ Make color (a 3- or 4-tuple of floats) have the given opacity (default 0.5, might be revised); if it was already translucent, this multiplies the opacity it had. """ if len(color) == 3: c1, c2, c3 = color c4 = 1.0 else: c1, c2, c3, c4 = color return (c1, c2, c3, c4 * opacity) trans_blue = translucent_color(halfblue) trans_red = translucent_color(red) trans_green = translucent_color(green) # == other constants PIXELS = 0.035 ###WRONG: rough approximation; true value depends on depth (in perspective view), glpane size, and zoomfactor! ###e A useful temporary kluge might be to compute the correct value for the cov plane, and change this constant to match # whenever entering testmode (or perhaps when resizing glpane), much like drawfont2 or mymousepoints does internally. # But if we do that, then rather than pretending it's a constant, we should rename it and make it an appropriate function # or method, e.g. glpane.cov_PIXELS for the correct value at the cov, updated as needed. # We might also replace some uses of PIXELS # with fancier functions that compute this for some model object point... but the main use of it is for 2d widget display, # for which a single value ought to be correct anyway. (We could even artificially set the transformation matrices so that # this value happened to be the correct one -- in fact, we already do that in DrawInCorner, used for most 2d widgets! # To fully review that I'd need to include what's done in drawfont2 or mymousepoints via TextRect, too.) # For model objects (at least in perspective view), there are big issues about what this really means, or should mean -- # e.g. if you use it in making a displist and then the model object depth changes (in perspective view), or the glpane size # changes, or the zoom factor changes. Similar issues arise for "billboarding" (screen-parallel alignment) and x/y-alignment # to pixel boundaries. Ultimately we need a variety of new Drawable-interface features for this purpose. # We also need to start using glDrawPixels instead of textures for 2d widgets, at some point. [comment revised 070304] # == lower-level stubs -- these will probably be refiled when they are no longer stubs ###@@@ NullIpath = '.' ##k ok that it's not None? maybe not, we might test for None... seems to work for now tho. #e make it different per reload? [070121 changed from 'NullIpath' to '.' to shorten debug prints] from exprs.__Symbols__ import Anything ## TODO: remove this, # since it's our only remaining import of __Symbols__ # and it causes a runtime import loop with Exprs.py StubType = Anything # use this for stub Type symbols [new symbol and policy, 070115] # stub types Width = StubType Color = StubType Vector = StubType Quat = StubType Position = StubType Point = StubType StateRef = StubType Function = StubType Drawable = StubType # warning: also defined as DelegatingInstanceOrExpr in one file # note: class Action in Set.py is not in this list since it's not entirely a stub. Type = Anything # end
NanoCAD-master
cad/src/exprs/ExprsConstants.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ clipping_planes.py -- support OpenGL clipping planes. @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from OpenGL.GL import glEnable from OpenGL.GL import glClipPlane from OpenGL.GL import glDisable from OpenGL.GL import GL_CLIP_PLANE1 from OpenGL.GL import GL_CLIP_PLANE2 from OpenGL.GL import GL_CLIP_PLANE3 from OpenGL.GL import GL_CLIP_PLANE4 from geometry.VQT import V from exprs.Exprs import list_Expr from exprs.widget2d import Widget2D from exprs.attr_decl_macros import Arg, ArgOrOption from exprs.instance_helpers import InstanceOrExpr from exprs.__Symbols__ import Anything def clip_below_y0(y0): #070322 #e refile #e someday make it return a smarter object (ClippingPlane) than just a 4-tuple or Numeric array """ return a 4-coefficient OpenGL clipping plane (red book p.144) which displays the half-space defined by y >= y0. """ # Return V(A,B,C,D) where Ax + By + Cz + D >= 0 defines the visible volume. # In this case we want y - y0 >= 0 to be visible. y0 = float(y0) # mainly to verify the type is ok; # also to force it to be a pure number, if someday it could have units or be a time-dependent expr or whatever return V(0,1,0,-y0) def clip_to_right_of_x0(x0): """ return a 4-coefficient OpenGL clipping plane (red book p.144) which displays the half-space defined by x <= x0. """ # We want x <= x0 to be visible, i.e. x - x0 <= 0, or -x + x0 >= 0. x0 = float(x0) return V(-1,0,0,+x0) ClippingPlane = Anything # stub # GL_CLIP_PLANE_table lists the OpenGL clipping plane objects we are allowed to use, in the order # in which we should allocate them for our own use. They're in backwards order in this table, # since other code (in cad/src) tends to use lower numbered planes first, though only plane 0 is # excluded completely, since only it appears to be used incompatibly (modes.py sometimes enables it # while drawing the entire model, in jigGLSelect, for motivations that are not clear to me # [later, 080917: probably to make GL_SELECT more likely to return only the correct object, # which matters since it uses the first one rather than figuring out which one to use]). # [070322; policy subject to revision] GL_CLIP_PLANE_table = ( ## GL_CLIP_PLANE5, # update: now used in stereo mode, so exclude it here. [bruce 080917] UNTESTED GL_CLIP_PLANE4, GL_CLIP_PLANE3, GL_CLIP_PLANE2, GL_CLIP_PLANE1, # used in class ThumbView -- see above ## GL_CLIP_PLANE0, # excluded, as explained above ) class Clipped(InstanceOrExpr): """ #doc """ # note: we're not delegating anything. # e.g. the best lbox attrs for this are specified by the caller and relate to the planes passed to us. thing = Arg(Widget2D) planes = ArgOrOption(list_Expr(ClippingPlane)) def draw(self): planes = self.planes assert len(planes) <= len(GL_CLIP_PLANE_table), \ "no more than %d clipping planes are permitted" % \ len(GL_CLIP_PLANE_table) # even if your OpenGL driver supports more -- no sense writing an expr that not everyone can draw! # WARNING: this ignores the issue of nested Clipped constructs! # In fact, it assumes nothing in thing or above self uses any clipping planes. # (Not merely "assumes no more than 6 in all", because we hardcode which specific planes to use!) # Worse, we don't even detect the error. Fixing the behavior is just as easy # (let graphical dynenv (self.env) know which planes are still available to any drawing-kid), so do that instead. ##e # Note that we might need to work inside a display list, and therefore we'd need to get the "next plane to use" # from an env which stays fixed (or from an env var which is changedtracked), not just from each draw call's caller # (i.e. a glpane attr). # enable the planes for i, plane in zip(range(len(planes)), planes): assert len(plane) == 4 glEnable( GL_CLIP_PLANE_table[i] ) glClipPlane( GL_CLIP_PLANE_table[i], plane) # draw thing self.drawkid( self.thing) # disable the planes for i in range(len(planes)): glDisable( GL_CLIP_PLANE_table[i] ) return pass #e Maybe add something to easily clip to an lbox or Rect, like we do in DraggablyBoxed. #e Maybe add options to not cull faces in spheres (and other objects), and to draw both sides of the faces. # These could be turned on here for what we draw (using graphical dynenv). # # Even better, if we wanted spheres to look "filled with a solid color" # (rather than hollow) when they were clipped, we could probably do it like this: # - draw the regular model, clipped in the usual way # - for each face of the clip volume (presumed brick-shaped) exposed to the user, draw some of the model again, # only including the spheres that intersect the clipping plane, # clipping to include only what's outside that face (and "above it" -- i.e. in another brick-shaped region), # but in a squished form so that all drawn surfaces are effectively squished almost totally onto the clipping plane. # (I'm not sure this works perfectly for all ways spheres can intersect. In fact, I doubt it. It would be more correct # to just draw filled circles, but to make them match up at the edges, they need to depend on the exac polyhedron used # for the sphere, so they're complicated to compute.) # end
NanoCAD-master
cad/src/exprs/clipping_planes.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ reload.py -- handle dynamic reloading of code for developers $Id$ Note: as of 070921 reload_once is no longer called except in testdraw.py. """ from utilities import debug_flags import utilities.EndUser as EndUser from utilities.debug import reload_once_per_event ENABLE_RELOAD = True and debug_flags.atom_debug # WARNING: the reload feature implemented herein has become broken, probably # ever since the confirmation corner started importing exprs modules without # using reload_once. Its calls were then significantly modified when import * # was removed from exprs, which may have further broken it, but this is # unknown. It should be considered dead until it can be analyzed and fixed, # or preferably, replaced with a better feature. The above init of ENABLE_RELOAD # is safe enough for now, since it only sets it when ATOM_DEBUG is turned on # before this module is first imported (probably at startup due to confirmation # corner imports of other exprs modules -- not sure). [bruce 070829 comment] # == #bruce 071102 moved vv from testdraw and renamed it vv -> exprs_globals, # to avoid an import cycle. class _attrholder: pass try: # see whether this module was loaded before; if so, don't disturb # these globals unless we've modified this code by adding globals exprs_globals exprs_globals.reload_counter # note: this is public, used by other modules exprs_globals.start_time ## exprs_globals.state ## exprs_globals.havelist except: # the module wasn't loaded before, or we added globals -- # reinitialize all these globals exprs_globals = _attrholder() exprs_globals.reload_counter = -1 exprs_globals.start_time = -1 ## exprs_globals.state = {} # prototype of a place to store persistent state (presuming some persistent way of allocating keys, eg hardcoding) ## ##e should modify to make it easier to set up defaults; sort of like a debug_pref? ## exprs_globals.havelist = False # == def reload_once(module): """ This function is used to support automatic runtime reloading of modules within this package, for developer convenience. To use it, add this code before any import of symbols from a module (or use this code in place of any direct import of a module): # import module # reload_once(module) Warning: not all modules support runtime reload. Those that don't should say so in their docstrings. Warning: this system does not yet properly handle indirect imports, when only the inner module has been modified. See code comments for details, especially the docstring of debug.reload_once_per_event(). As a workaround, if A imports B and you edit B.py, also edit A.py in order to trigger the desired runtime reload of B.py. """ # this comment become obsolete when exprs.basic was split into separate files: ##Note: this function's module (exprs.basic itself) is fast and harmless enough to reload that it can be ##reloaded on every use, without bothering to use reload_once. Therefore, external callers of anything ##in the exprs package can always "import basic;reload(basic)" first, and if they do, all modules within ##exprs can just start with "from basic import *". But for clarity, some of them call reload_once on basic too. if (not EndUser.enableDeveloperFeatures()): #070627 precaution; should improve by making this only affect default value of a debug_pref ###TODO return if not ENABLE_RELOAD: def printfyi(msg): # WARNING: dup code, inlining py_utils version since not yet imported msg = "fyi (printonce): " + msg from foundation.env import seen_before if not seen_before(msg): print msg if 1: ## printfyi( "exprs modules won't be reloaded during this session" ) # 070627 removed this return reload_once_per_event(module, always_print = True, never_again = False, counter = exprs_globals.reload_counter, check_modtime = True) return # end
NanoCAD-master
cad/src/exprs/reload.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ ColorCube.py -- a cube of all RGB colors (though only the surface is visible) @author: Bruce @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from geometry.VQT import V from OpenGL.GL import GL_QUADS from OpenGL.GL import glBegin from OpenGL.GL import glColor3f from OpenGL.GL import glColor3fv from OpenGL.GL import glVertex from OpenGL.GL import glVertex3f from OpenGL.GL import glVertex3fv from OpenGL.GL import glNormal3fv from OpenGL.GL import glEnd from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import GL_LIGHTING from exprs.widget2d import Widget2D # some data for a cube: # (todo: rename these to show they are mostly constants, and private) # axes to use X = V(1,0,0) Y = V(0,1,0) Z = V(0,0,1) # faces are an axis and a sign, and orientation directions # (pay attention to positive area in direction of normal) faces = [(X, 1, Y, Z), (X, -1, -Y, Z), (Y, 1, Z, X), (Y, -1, -Z, X), (Z, 1, X, Y), (Z, -1, -X, Y) ] def facenormal(face): return face[0] * face[1] def faceverts(face): perp1, perp2 = face[2], face[3] for signs in [(-1, -1), (1, -1), (1, 1), (-1, 1)]: yield signs[0] * perp1 + signs[1] * perp2 + facenormal(face) return def fix(coord): """ turn a sign into a color component; -1 -> 0, 1 -> 1 """ return coord * 0.5 + 0.5 class ColorCube(Widget2D): def draw(self): glDisable(GL_LIGHTING) # note: the colors here don't work without this glBegin(GL_QUADS) for face in faces: face_normal = facenormal(face) for vert in faceverts(face): color = (fix(vert[0]), fix(vert[1]), fix(vert[2])) glColor3fv(color) glNormal3fv(face_normal) glVertex3fv(vert) glEnd() glEnable(GL_LIGHTING) pass # end
NanoCAD-master
cad/src/exprs/ColorCube.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ dna_ribbon_view.py @author: bruce @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. 070125: started this from a copy of demo_dna-outtakes.py. [Since then, that file has been cvs-removed -- see 070201 comment below.] Eventually this will have some display styles for DNA double helix segments, with the model aspects of those defined in separate files, but to get started, we might make self-contained exprs which handle two parts of this that ought to be separated: - think of some external "control point" state as "state describing a DNA double helix segment"; - draw a "DNA double helix segment" in various ways. We'll break it down into separate expr classes for the operations: - make dna seg params from control points, - generate various useful geometric objects from those and from simpler or higherlevel ones, - draw those individually, - put that together to draw a DNA segment. Then it can all be put together into a demo in which the control points are draggable. In the future we can let a "dna model object" know how to get its params from a variety of input types in different ways, and know how to display itself or make it work to find the display rules externally and apply them to it. To some extend we can prefigure that now if we break things down in the right way. 070130: the tension between arrays of unlabeled numbers (efficiency, LL code convenience) and typesafe geometric objects (points, knowing their coords intrinsicness & coordsys & space, etc) is a problem, but the best-guess resolution is to make "rich objects" available (with all such type info, metainfo, extra info -- e.g. normal and surface (incl its own local coordsys vectors within the tangent plane, or enough info to derive them) and object-we-mark for points), but also make coords available, in standard coordsystems, informal at first, later available as metainfo for specific attrs; and someday to bridge the gap by working primarily with rich *arrays* of data, so the number ops can be done by Numeric or the like, expressing the HL ops with exprs. In the meantime it's a continual hassle, seen in the present Qs about types like Cylinder and Cylinder_HelicalPath. 070131/070201: for now, coordinates are handled by using all the same ones (same as drawing coords) in any given object. The object is responsible for knowing what coords it uses in kids it makes (and the ones here just use the same ones in kids and in themselves). This means a cylinder with markings, to be efficient re display lists when moved/rotated [which is nim], should have that move/rotate done outside it (not modifying anything it stores), in a manner not yet worked out. Maybe the easiest way is for it to make an exception and contain an outer repositioner wrapping everything else it draws... tho if that repositioner could be entirely outside it, that might be better -- but only if not having one is an option; especially useful if there can be different kinds, e.g. for gridded drags. The outer repositioner could also be temporary, with coord changes reflected inside the object eventually (similar to chunks, which often reset their base coords to abs coords or a translated version of them). This is all TBD. ###e 070201: for now, length units will be handled by using nm everywhere. This is a kluge for the lack of an adjustable relation between NE1 model-drawing-coords and physical distance; it will make DNA look the right size on screen. But it's incompatible with drawing atoms (assuming you want them to look in the same scale as the DNA -- not clear, if they are in a different model that happens to be shown at the same time!) Later we'll have to coexist better with atoms using angstroms, perhaps by making physical & drawing units explicit for each object -- or for individual numbers and numeric arrays if we can do that efficiently (which probably means, if we implement the unit/coord compatibility checks and wrapping/unwrapping in C). 070201: moved still-useful scraps we're not using now to another file, dna_ribbon_view_scraps.py, including most of what remains from demo_dna-outtakes.py, which I'm cvs-removing. (The only reason I might want to look it up in cvs would be for help making the OpenGL do what it used to do, if that's ever needed.) """ from math import pi from Numeric import dot, cos, sin from OpenGL.GL import GL_LIGHTING from OpenGL.GL import glDisable from OpenGL.GL import glColor3fv from OpenGL.GL import GL_LINE_STRIP from OpenGL.GL import glBegin from OpenGL.GL import glVertex3fv from OpenGL.GL import glEnd from OpenGL.GL import glEnable from OpenGL.GL import GL_CULL_FACE from OpenGL.GL import GL_LIGHT_MODEL_TWO_SIDE from OpenGL.GL import GL_TRUE from OpenGL.GL import glLightModelfv from OpenGL.GL import GL_QUAD_STRIP from OpenGL.GL import glNormal3fv from OpenGL.GL import GL_FALSE from exprs.Overlay import Overlay 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.gl_lighting import apply_material from exprs.world import World from exprs.Rect import Rect, Spacer, Sphere, Line from exprs.Column import SimpleColumn, SimpleRow from exprs.DisplayListChunk import DisplayListChunk from exprs.Highlightable import Highlightable from exprs.transforms import Translate from exprs.Center import Center from exprs.TextRect import TextRect from exprs.controls import checkbox_pref, ActionButton from exprs.draggable import DraggableObject from exprs.projection import DrawInCenter from exprs.pallettes import PalletteWell from geometry.VQT import norm from utilities.constants import gray, black, red, blue, purple, white from utilities.constants import ave_colors, noop from utilities.constants import green from utilities.constants import yellow from exprs.widget2d import Widget, Stub from exprs.Exprs import norm_Expr, vlen_Expr, int_Expr, call_Expr, getattr_Expr, format_Expr from exprs.Exprs import eq_Expr from exprs.If_expr import If from exprs.instance_helpers import ModelObject, InstanceMacro, DelegatingInstanceOrExpr from exprs.instance_helpers import WithAttributes from exprs.attr_decl_macros import Arg, ArgOrOption, Option, State, StateOption, StateArg from exprs.ExprsConstants import Width, ORIGIN, DX, DY, DZ, Color, Point, Vector from exprs.__Symbols__ import _self # undefined symbols: object_id, nim, ditto # temporary kluge: excerpt from cad/src/DnaGenerator.py; this copy used locally for constants [values not reviewed]: class B_Dna: geometry = "B-DNA" TWIST_PER_BASE = -36 * pi / 180 # radians [this value is not used here since it differs from Paul's Origami values] BASE_SPACING = 3.391 # angstroms # stubs: Radians = Width Rotations = Degrees = Width Angstroms = Nanometers = Width ModelObject3D = ModelObject ### might be wrong -- might not have fix_color -- unless it can delegate it -- usually it can, not always -- # can default delegate have that, until we clean up delegation system? or just move that into glpane? yes for now. # we'll do that soon, but not in present commit which moves some code around. this vers does have a bug re that, # expressed as AssertionError: DelegatingMixin refuses to delegate self.delegate (which would infrecur) in <Cylinder#16801(i)> ###e ## ModelObject3D = Widget ###e remove soon -- see fix_color comment above; and probably buggy by its defaults hiding the delegate's Geom3D = ModelObject3D # how would ModelObject3D & Geom3D differ? something about physicality? PathOnSurface = Geom3D LineSegment = Geom3D ## StateFormulaArg = StateArg # utilities to refile (or redo) def remove_unit_component(vec1, unitvec2): #e rename, or maybe just replace by remove_component or perp_component (no unit assumption) """Return the component of vec1 perp to unitvec2, by removing the component parallel to it. Requires, but does not verify, that vlen(unitvec2) == 1.0. """ return vec1 - dot(vec1, unitvec2) * unitvec2 class Cylinder(Geom3D): #e super? ####IMPLEM - and answer the design Qs herein about state decls and model objs... #e refile """Be a cylinder, including as a surface... given the needed params... ###doc """ ###e someday accept a variety of arg-sequences -- maybe this has to be done by naming them: # - line segment plus radius # - center plus orientation plus length plus radius # - circle (in space) plus length # But for now accept a linesegment or pair of endpoints, radius, color; let them all be mutable? or argformulae? or both??#### # StateFormulaArg? ##e # OR, let creator say if they want to make it from state? hmm... ##### pro of that: in here we say Arg not StateFormulaArg. # If we do that, is there any easy way for creator to say "make all the args turn into state"? Or to let dflt_exprs be state?? # Or let the model state be effectively an expr? but then how could someone assign to cyl attrs as if mutable? #### # args axis = Arg( LineSegment, (ORIGIN, ORIGIN + DX) ) #e let a pair of points coerce into a LineSegment, and let seq assign work from it radius = ArgOrOption( Nanometers, 1.0) color = ArgOrOption( Color, gray) capped = Option( bool, True) #e best default?? #e should capped affect whether interior is made visible? (yes but as dflt for separate option) #e also provide exprs/opts for use in the caps, incl some way to be capped on one end, different colors, etc #e color for marks/sketch elements: point, line & fill & text -- maybe inherit defaults & option-decls for this #e surface texture/coordsys options opacity = Option(float, 1.0) #ninad 2008-06-25 See also self.draw. # formulae ## dx = norm_Expr(axis) # ValueError: matrices are not aligned -- probably means we passed an array of V's to norm end2 = axis[1] #e or we might have to say axis.ends[1] etc end1 = axis[0] axisvector = end2 - end1 #e should also be axis.vector or so dx = norm_Expr(axisvector) #e axis.direction def _C__dy_dz(self): #e if axis has a dy, use that (some lines might come with one) # otherwise get an arb perp to our dx from model.pi_bond_sp_chain import arb_ortho_pair # "Given a nonzero vector, return an arbitrary pair of unit vectors perpendicular to it and to each other." #e refile that into geometry.py in cad/src, or use smth else in there, and grab these from a more central source in exprs return arb_ortho_pair(self.dx) dy = _self._dy_dz[0] dz = _self._dy_dz[1] length = vlen_Expr(axisvector) center = (end1 + end2) / 2.0 def draw(self): #@ATTENTION: The new attr 'self.opacity' was added on 2008-06-26. But #call to self.fix_color doesn't set the opacity (transparency) properly. #Also, based on test, not 'fixing the color' and directly using #self.color works. So, defining the following condition. (use of #self.fix_color may be unnecessary even for opaque objects but it is #untested -- Ninad 2008-06-26 if self.opacity == 1.0: color = self.fix_color(self.color) else: color = self.color end1, end2 = self.axis ##### radius = self.radius capped = self.capped drawcylinder(color, end1, end2, radius, capped = capped, opacity = self.opacity ) ###coordsys? return def perpvec_at_surfacepoint(self, point): #e rename? """Given a point on or near my surface (actually, on the surface of any coaxial cylinder), return a normal (unit length) vector to the surface at that point (pointing outward). Ignores end-caps or cylinder length -- treats length as infinite. Works in same coords as all points of self, such as self.end1, end2. """ return norm( remove_unit_component( point - self.end1, self.dx)) ##e rename: norm -> normalize? unitvector? normal? #e bbox or the like (maybe this shape is basic enough to be an available primitive bounding shape?) pass class Cylinder_HelicalPath(Geom3D): #e super? """Given a cylinder (cyl), produce a helical path on its surface (of given params) as a series of points (at given resolution -- but specifying resolution is #NIM except as part of path spec) starting at the left end (on an end-circle centered at cyl.end1), expressing the path in the same coordsys as the cylinder points (like end1) are in. Usage note: callers desiring path points invariant to rotations or translations of cyl should express cyl itself in a local coordsys which is rotated or translated, so that cyl.end1 and end2 are also invariant. """ # args #e need docstrings, defaults, some should be Option or ArgOrOption #e terms need correction, even tho not meant to be dna-specific here, necessarily (tho they could be): turn, rise, n, theta_offset cyl = Arg(Cylinder) n = Option(int, 100) # number of segments in path (one less than number of points) turn = Option( Rotations, 1.0 / 10.5) # number of rotations of vector around axis, in every path segment ###e MISNAMED?? rise = Option( Nanometers, 0.34) ###k default theta_offset = Option( Radians, 0.0) # rotates entire path around cyl.axis color = Option(Color, black) # only needed for drawing it -- not part of Geom3D -- add a super to indicate another interface??##e ##e dflt should be cyl.attr for some attr related to lines on this cyl -- same with other line-drawing attrs for it ## start_offset = Arg( Nanometers) radius_ratio = Option(float, 1.1) ###e def _C_points(self): cyl = self.cyl theta_offset = self.theta_offset n = int(self.n) #k type coercion won't be needed once Arg & Option does it radius = cyl.radius * self.radius_ratio rise = self.rise turn = self.turn end1 = self.cyl.end1 axial_offset = cyl.dx * rise # note: cyl.dx == norm(cyl.axisvector) cY = cyl.dy # perp coords to cyl axisvector (which is always along cyl.dx) [#e is it misleading to use x,y,z for these??] cZ = cyl.dz points = [] turn_angle = 2 * pi * turn p0 = end1 #e plus an optional offset along cyl.axisvector? for i in range(n+1): theta = turn_angle * i + theta_offset # in radians y = cos(theta) * radius # y and z are Widths (numbers) z = sin(theta) * radius vx = i * axial_offset # a Vector p = p0 + vx + y * cY + z * cZ points.append(p) return points # temporarily remove these just to make sure i don't use them anymore for phosphates -- # they work fine and can be brought back anytime after the next commit. [070204 late] ## def _C_segments(self): ## "compute self.segments, a list of pairs of successive path points [###e maybe they ought to be made into LineSegments]" ## p = self.points ## return zip(p[:-1], p[1:]) ## def _C_segment_centers(self): ## "compute self.segment_centers [obs example use: draw base attach points (phosphates) in DNA; not presently used 070204]" ## return [(p0 + p1)/2.0 for p0,p1 in self.segments] def draw(self): color = self.fix_color(self.color) points = self.points glDisable(GL_LIGHTING) ### not doing this makes it take the color from the prior object glColor3fv(color) ##k may not be enough, not sure glBegin(GL_LINE_STRIP) for p in points: ##glNormal3fv(-DX) #####WRONG? with lighting: doesn't help, anyway. probably we have to draw ribbon edges as tiny rects. # without lighting, probably has no effect. glVertex3fv(p) glEnd() glEnable(GL_LIGHTING) return pass class Cylinder_Ribbon(Widget): #070129 #e rename?? #e super? """Given a cylinder and a path on its surface, draw a ribbon made from that path using an OpenGL quad strip (whose edges are path +- cyl.axisvector * axialwidth/2). Current implem uses one quad per path segment. Note: the way this is specific to Cylinder (rather than for path on any surface) is in how axialwidth is used, and that quad alignment and normals use cyl.axisvector. Note: present implem uses geom datatypes with bare coordinate vectors (ie containing no indication of their coordsys); it assumes all coords are in the current drawing coordsys (and has no way to check this assumption). """ #args cyl = Arg(Cylinder) path = Arg(PathOnSurface) ###e on that cyl (or a coaxial one) color = ArgOrOption(Color, cyl.dflt_color_for_sketch_faces) axialwidth = ArgOrOption(Width, 1.0, doc = "distance across ribbon along cylinder axis (actual width is presumably shorter since it's diagonal)" ) #e rename showballs = Option(bool, False) # show balls at points [before 070204 late, at segment centers instead] ###KLUGE: hardcoded size showlines = Option(bool, False) # show lines from points to helix axis (almost) [before 070204 late, at segment centers] # (note: the lines from paired bases don't quite meet, and form an angle) def draw(self): self.draw_some(None) # None means draw all segments def draw_some(self, some = None): "#doc; some can be (i,j) to draw only points[i:j], or (i,None) to draw only points[i:]" # tested with (2,-2) and (2,None) cyl = self.cyl path = self.path axialwidth = self.axialwidth points = path.points #e supply the desired resolution? if some: i,j = some points = points[i:j] normals = map( cyl.perpvec_at_surfacepoint, points) ####IMPLEM perpvec_at_surfacepoint for any Surface, e.g. Cylinder (treat as infinite length; ignore end-caps) ####e points on it might want to keep their intrinsic coords around, to make this kind of thing efficient & well defined, # esp for a cyl with caps, whose caps also counted as part of the surface! (unlike in present defn of cyl.perpvec_at_surfacepoint) offset2 = axialwidth * cyl.dx * 0.5 # assumes Width units are 1.0 in model coords offset1 = - offset2 offsets = (offset1, offset2) color = self.fix_color(self.color) interior_color = ave_colors(0.8, color, white) ### remove sometime? self.draw_quad_strip( interior_color, offsets, points, normals) if self.showballs: #070202 kluge_hardcoded_size = 0.2 for c in points: ##e It might be interesting to set a clipping plane to cut off the sphere inside the ribbon-quad; # but that kind of fanciness belongs in the caller, passing us something to draw for each base # (in a base-relative coordsys), presumably a DisplayListChunk instance. (Or a set of things to draw, # for different kinds of bases, in the form of a "base view" base->expr function.) drawsphere(color, c, kluge_hardcoded_size, 2) if self.showlines: for c, n in zip(points, normals): nout, nin = n * 0.2, n * 1.0 # hardcoded numbers -- not too bad since there are canonical choices drawline(color, c + nout, c - nin) ##k lighting?? # draw edges? see Ribbon_oldcode_for_edges return def draw_quad_strip(self, color, offsets, points, normals): #e refile into draw_utils -- doesn't use self """draw a constant-color quad strip whose "ladder-rung" (inter-quad) edges (all parallel, by the following construction) are centered at the given points, lit using the given normals, and have width defined by offsets (each ladder-rung going from point + offsets[1] to point + offsets[0]). """ offset1, offset2 = offsets ## glColor3fv(color) # actually I want a different color on the back, can I get that? ###k glDisable(GL_CULL_FACE) apply_material(color) ## glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color) # gl args partly guessed #e should add specularity, shininess... glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE) glBegin(GL_QUAD_STRIP) # old cmts, obs??: # this uses CULL_FACE so it only colors the back ones... but why gray not pink? # the answer - see draw_vane() -- I have to do a lot of stuff to get this right: # - set some gl state, use apply_material, get CCW ordering right, and calculate normals. ## glColor3fv(color) ## print "draw_quad_strip",color, offsets, points, normals ###BUG: points are 0 in y and z, normals are entirely 0 (as if radius was 0?) for p, n in zip( points, normals): glNormal3fv( n) glVertex3fv( p + offset2) glVertex3fv( p + offset1) glEnd() glEnable(GL_CULL_FACE) glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE) return pass # == ###e need to look up the proper parameter names -- meanwhile use fake ones that don't overlap the real ones -- # easy, just use the geometric ones in Cylinder_HelicalPath. Later we'll have our own terminology & defaults for those here. ## pitch # rise per turn ## rise kluge_dna_ribbon_view_prefs_key_prefix = "A9 devel/kluge_dna_ribbon_view_prefs_key_prefix" def dna_pref(subkey): return kluge_dna_ribbon_view_prefs_key_prefix + '/' + subkey from foundation.preferences import _NOT_PASSED ###k def get_pref(key, dflt = _NOT_PASSED): #e see also... some stateref-maker I forget ####DUP CODE with test.py, should refile """Return a prefs value. Fully usage-tracked. [Kluge until we have better direct access from an expr to env.prefs. Suggest: use in call_Expr.] """ import foundation.env as env return env.prefs.get(key, dflt) def get_dna_pref(subkey, **kws): ###DESIGN FLAW: lack of central decl means no warning for misspelling one ref out of several return get_pref( dna_pref(subkey), **kws) class DNA_Cylinder(ModelObject): #070215 DIorE -> ModelObject (affects _e_model_type_you_make) #070213 started revising this to store state in self (not cyl) and know about seam... # [done? I guess yes, but a newer thing is not -- the strand1_theta stuff (needed for origami grid support), # while partly done, is not yet used for real (tho maybe called) and not fully implem in this class either. #####e ] """A guide object for creating a cylindrical double-helical or "duplex" domain of DNA (with fully stacked bases, but not usually with fully connected backbone -- that is, strands can enter and leave its two helices). [#e may be renamed to something mentioning duplex or double helix, especially once it no longer needs to remain straight] ### doc this better -- needs intro/context: We think of a symmetric cylinder as having a central inter-base segment, with the same number of bases on either side. But there is no requirement that a specific cylinder be symmetric. (It will be if n_turns_left == n_turns_right in its state.) The central segment (not really central if it's not symmetric) is thought of as the seam (for origami) and is used as an origin for the indexing of inter-base segments and bases, as follows: - base-position indices are 0,1,2 to the right of (after) this origin, and -1, -2, etc to the left. - inter-base segments are numbered 0 at this origin (and in general, by the following base). This means the order is ... base(-1) -- segment(0)(== origin) -- base(0) -- ... (Note: this is subject to revision if it turns out some other scheme is standard or much better. ###e) Note that ficticious segment numbers at the ends, which have only one endpoint that's a real base index, might be useful in some places, but won't be included by default when iterating over inter-base helix segments. That is, by default (when accessing related attrs), there will be one fewer inter-base segment than base. """ color_cyl = Option(Color, gray, doc = "color of inner solid cylinder (when shown)") #e default should be transparent/hidden color1 = Option(Color, red, doc = "default color of helix 1 of this cylinder (overridable by strand colors #nim)") color2 = Option(Color, blue, doc = "default color of helix 2 of this cylinder (overridable by strand colors #nim)") n_turns_left = State(float, 1.5, doc = "number of turns before seam or interbase-index-origin") n_turns_right = State(float, 2.5, doc = "number of turns after seam or interbase-index-origin") bpt = StateOption(float, 10.5, doc = "bases per turn") ###e default will depend on origami raster style #e rename: bases_per_turn? n_bases_left = int_Expr( n_turns_left * bpt) ###IMPLEM int_Expr; make it round or truncate? If round, rename it? n_bases_right = int_Expr( n_turns_right * bpt) ### PROBLEM: base indices will change if bpt is revised -- what if crossovers were chosen first? do crossovers need to be # turn-indexed instead? Or something weirder, like "this turn, then this many bases away in this direction"?? # (Does this ever happen in Paul's UI stages? #k) [mentioned in 2/19 meeting agenda] n_bases = n_bases_left + n_bases_right # this determines length ###e need options strand1_theta, strand2_theta -- one defaults to modified other, i guess... NOT SO SIMPLE -- # each one has to do that, but not be circular -- it's our first unavoidably needed ability # to specify constrained dofs in more than one way. hmm. #####DECIDE HOW # idea, not sure if kluge: a circular spec would eval to None, and you could then say spec1 or spec2, # so if spec1 was circular when evalled, you'd get spec2. # - would it work in this case? # - is it a kluge in general, or well-defined and safe and reasonable? # - what if a legitimate value could be boolean-false? is a modified or_Expr ok? rather than None, use Circular (which is false)?? # # strand1_theta = Option( Degrees, FIRST_NON_CIRCULAR( _self.strand2_theta + offset, 0 ) ) # # catches CircularDefinitionError (only if this lval is mentioned in the cycle?), tries the next choice # # or -- strand1_theta = Option( Degrees, first_non_circular_choice_among = ( _self.strand2_theta + offset, 0 ) ) # # strand2_theta = Option( Degrees, _self.strand1_theta - offset ) # raises CircularDefinitionError (saying the cycle it found?) # # PROBLEM: I suspect the behavior depends on the order of eval of the defs, at least if cycles break in more than one place. # PROBLEM: you have to manually create the proper inverse formulas -- nothing catches mistake if they're not inverses. # PROBLEM: the above might work for initial sets (from being unset) -- # but if they are State, what about how they respond to modification-sets? # this requires "set all at once" and know what to keep fixed; discussed elsewhere (where? corner situations??); # one way is "fix up inconsistencies later" (or on request); all ways require knowing the set of related variables. # (In general, you have to be able to do that -- but for simple affine cases, system ought to do it for you. # So for these simple affine constraints, shouldn't we use a specialized mechanism instead? # like state aliases with ops in lvals...) # ##e then use them below to make path1 and path2 # # here is an ad-hoc method for now: strand1_theta = Option( Degrees, None) strand2_theta = Option( Degrees, None) def _C_use_strand12_theta(self): s1 = self.strand1_theta s2 = self.strand2_theta offset = 150 ### guess if s1 is None and s2 is None: s1 = 0 # not both undefined if s1 is None: s1 = s2 + offset if s2 is None: s2 = s1 - offset s1 %= 360.0 s2 %= 360.0 return s1, s2 use_strand1_theta = _self.use_strand12_theta[0] ### USE ME -- note, in degrees, not necessary limited to [0,360] use_strand2_theta = _self.use_strand12_theta[1] center = State(Point, ORIGIN) ###e make these StateArgs... #e put them in the model_state layer #e rename to position?? def move(self, motion): ###CALL ME self.center = self.center + motion return direction = State(Vector, DX) # must be unit length! #e make center & direction get changed when we move or rotate [entirely nim, but someday soon to be called by DraggableObject] #e make the theta_offset (or whatever) also get changed then (the rotation around cyl axis) ###e should we revise direction/theta_offset to a local coordsys?? in fact, should we include center in that too? ###e should we define ourselves so locally that we don't bother to even store this center/direction/axisrotation at all? # (quite possibly, that would simplify the code greatly... otoh, we may need to get revised abs posns inside our bases somehow...) ###e correct the figures and terminology: rise, turn, pitch rise = StateOption(Angstroms, B_Dna.BASE_SPACING, doc = "distance along helix axis from one basepair to the next") #k can you say units that way? not yet, so we have a kluge to turn them into nm below. rise_nm = rise / 10.0 #e is the attr_nm suffix idea a generally useful one?? [070213] pitch = rise_nm * bpt ##k #e and make it settable? [not yet used] length_left = rise_nm * n_bases_left length_right = rise_nm * n_bases_right length = length_left + length_right end1 = center - direction * length_left end2 = center + direction * length_right cyl = Cylinder( (end1, end2), color = color_cyl, radius = 1.0, # cyl is a public attr for get doc = "cylindrical surface of double helix" ) ###k ###e bring in more from the comments in cyl_OBS below?? ##e also tell cyl how much it's rotated on its axis, in case it has a texture?? what if that's a helical texture, like dna? cyl_OBS = StateArg( Cylinder(color = color_cyl, radius = 1.0), ###IMPLEM this way of giving dflts for attrs added by type coercion #k radius and its units #e put it into model_state ##e make this work: Automatic, #e can this be given as a default to type coercion, to make it "just create one"? Cylinder(color = color_cyl, radius = 1.0)((ORIGIN-6*DX, ORIGIN+10*DX)), ###e silly defaults, change back to ORIGIN end1 soon ###k why did that () not fix this warning: "warning: this expr will get 0 arguments supplied implicitly" ?? ###e can we make it ok to pass length and let end1 be default ORIGIN and dx be default DX? doc = "cylindrical surface of double helix" ) ###e add dflt args in case we typecoerce it from a line ###e or maybe even bring in a line and make the cyl ourselves with dflt radius? somewhere we should say dflt radius & length. # ah, the right place is probably in the type expr: Cylinder(radius = xxx, length = xxx) #e do we want to let a directly passed cyl determine color, as the above code implies it would? # if not, how do we express that: StateArg(...)(color = color_cyl)?? # what if color was not passed to self, *then* do we want it fom cyl? same Q for radius. path1 = Cylinder_HelicalPath( cyl, rise = rise_nm, turn = 1/bpt, n = n_bases, theta_offset = - n_bases_left / bpt * 2*pi ) ## should be: path2 = Rotate(path1, 150.0, cyl.axis) #e note, this seems to be "rotate around a line" (not just a vector), which implies translating so line goes thru origin; # or it might be able to be a vector, if we store a relative path... get this straight! ###e (for now assume axis could be either) ## here's an easier way, and better anyway (since the path's state (when it has any) should be separate): path2 = path1(theta_offset = 150*2*pi/360 - n_bases_left / bpt * 2*pi) # optional extender drag handles [070418] -- # doesn't yet work, apparently *not* due to nested HL issue, but due to coordsys being wrong for it due to outer Draggable # (presumed, but output from debug_pref: preDraw_glselect_dict failure consistent...) # If that's fixed, it might still fail if big object that includes us is drawn first as a candidate! # To fix that, change stencil ref value from 1 to 0 (see glpane.py for how) while drawing nested glnamed obj, # when inside another one drawing with stencil on (in draw_in_abs_coords, knowable by drawing_phase == 'selobj'). handle = Highlightable(Center(Rect(0.3, 2.0, purple)), Center(Rect(0.3, 2.0, white))) drag_handles = Overlay( Translate(handle, end1 - direction), Translate(handle, end2)) # prefs values used in appearance [##e in future, we'll also use these to index a set of display lists, or so] show_phosphates = call_Expr( get_dna_pref, 'show phosphates', dflt = False) ###e phosphates -> sugars show_lines = call_Expr( get_dna_pref, 'show lines', dflt = False) ##e lines -> bases, or base_lines (since other ways to show bases) # appearance (stub -- add handles/actions, more options) delegate = Overlay( If( call_Expr( get_dna_pref, 'show central cyl', dflt = False), cyl ), If( call_Expr( get_dna_pref, 'show drag handles', dflt = True), drag_handles ), #e has no checkbox yet Cylinder_Ribbon(cyl, path1, color1, showballs = show_phosphates, showlines = show_lines ), Cylinder_Ribbon(cyl, path2, color2, showballs = show_phosphates, showlines = show_lines ) ) # geometric attrs should delegate to the cylinder -- until we can say that directly, do the ones we need individually [070208] # (for more comments about a fancier case of this, see attr center comments in draggable.py) ## center = cyl.center #e actually the origami center might be the seam, not the geometric center -- worry about that later # revision 070213: center is now directly set State (type Point) def make_selobj_cmenu_items(self, menu_spec, highlightable): #070204 new feature, experimental #070205 revised api """Add self-specific context menu items to <menu_spec> list when self is the selobj (or its delegate(?)... ###doc better). Only works if this obj (self) gets passed to Highlightable's cmenu_maker option (which DraggableObject(self) will do). [For more examples, see this method as implemented in chem.py, jigs*.py in cad/src.] """ menu_spec.extend([ ("DNA Cylinder", noop, 'disabled'), # or 'checked' or 'unchecked'; item = None for separator; submenu possible ("show potential crossovers", self._cmd_show_potential_crossovers), #e disable if none (or all are already shown or real) ("change length", [ ("left extend by 1 base", lambda self = self, left = 1, right = 0: self.extend(left, right)), ("left shrink by 1 base", lambda self = self, left = -1, right = 0: self.extend(left, right)), ("right extend by 1 base", lambda self = self, left = 0, right = 1: self.extend(left, right)), ("right shrink by 1 base", lambda self = self, left = 0, right = -1: self.extend(left, right)), ("both extend by 1 base", lambda self = self, left = 1, right = 1: self.extend(left, right)), ("both shrink by 1 base", lambda self = self, left = -1, right = -1: self.extend(left, right)), ] ), ]) # print "make_selobj_cmenu_items sees mousepoint:", highlightable.current_event_mousepoint() ###BUG: exception for this event # # That happens because glpane._leftClick_gl_event_info is not defined for this kind of event, nor are some other attrs # defined (in exprs module) for a drag event that comes right after a leftclick. # # That could be fixed... in a few different ways: # - Support general posn-specific selobj behavior (highlight image, sbar text, cmenu): # That would require the baremotion-on-one-selobj optim # to notice a per-selobj flag "I want baremotion calls" (a new method in selobj interface), # and call it for all baremotion, with either side effects or retval saying whether new highlight image, # sbar text, or cmenu point is needed. (Totally doable, but not completely trivial.) # - Or, have intra-selobj different 2nd glnames, and when they change, act like it is (or might be) a new selobj. # This is not a lot different from just splitting things into separate selobjs (tho it might be more efficient # in some cases, esp. if you wanted to use weird gl modes for highlighting, like xormode drawing; alternatively # it might be simpler in some cases). # - Or, just support posn-specific selobj cmenu (but not sbar or highlight image changes): # that could be simpler: just save the point (etc) somewhere # (as computed in baremotion to choose the selobj), and have it seen by current_event_mousepoint in place of # glpane._leftClick_gl_event_info (or rename that and use the same attr). # But customizing only the cmenu is not really enough. So: maybe we'll need this someday, and we'll use # one of the fancier ways when we do, but for now, do other things, so this improvement to selobj API is being put off. # (Except for this unused arg in the API, which can remain for now; for some of these methods maybe it could be removed.) return def extend(self, left, right): "change the length of this duplex on either or both ends, by the specified numbers of new bases on each end respectively" ###e need to improve the UI for this -- eg minibuttons to extend by 1.5 turn, or drag end to desired length ## self.n_bases_left += left # ... oops, this is not even a state variable!! ## self.n_bases_right += right self.n_turns_left += (left / self.bpt) ###BUG: rotates it too -- need to compensate theta_offset self.n_turns_right += (right / self.bpt) self.KLUGE_gl_update() ###BUG: without this, doesn't do gl_update until selobj changes, or at least until mouse moves, or so def _cmd_show_potential_crossovers(self): print "_cmd_show_potential_crossovers is NIM" # ModelTreeNodeInterface formulae mt_node_id = getattr_Expr( _self, '_e_serno') # ipath might be more correct, but this also doesn't change upon reload in practice, # i guess since World objects are not remade [070218 late comment] ###REVIEW for possibly being ###WRONG or ###BUG # in fact it is surely a bug (tho harmless now); see comments re bugfix070218 and in def mt_node_id mt_name = State(str, format_Expr("DNA Cylinder #n (%r)", mt_node_id)) # mt_node_id is only included in name for debugging (does it change?) ###e make it unique somehow #e make it editable #e put this state variable into model_state layer mt_kids = () #e add our crossovers, our yellow rect demos mt_openable = False #e pass # end of class DNA_Cylinder # == def dna_ribbon_view_toolcorner_expr_maker(world_holder): #070201 modified from demo_drag_toolcorner_expr_maker -- not yet modified enough ###e """given an instance of World_dna_holder (??), return an expr for the "toolcorner" for use along with whatever is analogous to GraphDrawDemo_FixedToolOnArg1 (on the world of the same World_dna_holder) """ world = world_holder.world number_of_objs = getattr_Expr(world, 'number_of_objects') ## WARNING: when that said world.number_of_objects instead, it turned into a number not an expr, and got usage-tracked, # and that meant this expr-maker had to get called again (and the result presumably remade again) # every time world.number_of_objects changed. [For more details, see comments here in cvs rev 1.40. 070209] # (This would not have happened if this was an expr rather than a def, since then, # world would be _self.attr (symbolic) rather than an Instance.) ###BUG: Are there other cases throughout our code of debug prints asking for usage-tracked things, causing spurious invals?? expr = SimpleColumn( checkbox_pref( dna_pref('show central cyl'), "show central cyl?", dflt = False), checkbox_pref( dna_pref('show phosphates'), "show base sugars?", dflt = False), #070213 phosphates -> sugars [###k] ###e if indeed those balls show sugars, with phosphates lying between them (and btwn cyls, in a crossover), # then I need to revise some other pref keys, varnames, optnames accordingly. [070213] checkbox_pref( dna_pref('show lines'), "show lines?", dflt = False), # temporary ActionButton( world_holder._cmd_Make_DNA_Cylinder, "button: make dna cyl"), ActionButton( world_holder._cmd_Make_some_rects, "button: make rects over cyls"), ActionButton( world_holder._cmd_Make_red_dot, "button: make red dot"), SimpleRow( PalletteWell( ## Center(Rect(0.4, 0.4, green))(mt_name = "green rect"), # customization of mt_name has no effect (since no Option decl for mt_name inside) -- need WithAttributes WithAttributes( Center(Rect(0.4, 0.4, green)), mt_name = "green rect #n" ), world = world, type = "green rect" # design flaw: type is needed in spite of WithAttributes mt_name, since that only affects Instances -- # and anyway, this is a type name, not an individual name. For replacing this we'd want WithModelType # and I guess we want a combined thing that does both, also filling in the #n with an instance number. ), PalletteWell( WithAttributes( Overlay(Center(Spacer(0.6)), Cylinder((ORIGIN, ORIGIN+DZ*0.01), capped = True, radius = 0.3, color = yellow)), mt_name = "yellow circle #n" ), # first try at that failed, due to no attr bleft on Cylinder (tho the exception is incomprehensible ###FIX): ## Cylinder((ORIGIN, ORIGIN+DZ*0.01), capped = True, radius = 0.3, color = green), # a green dot world = world, type = "yellow circle" ), PalletteWell( WithAttributes( Sphere(0.2, blue), mt_name = "blue sphere #n"), world = world, type = "blue sphere" ), ), If( getattr_Expr( world, '_cmd_Clear_nontrivial'), ActionButton( world._cmd_Clear, "button: clear"), ActionButton( world._cmd_Clear, "button (disabled): clear", enabled = False) ), Overlay( DisplayListChunk(TextRect( format_Expr( "(%d objects in world)" , number_of_objs ))), If( eq_Expr( number_of_objs, 0), DrawInCenter(corner = (0,0))( TextRect("(empty model)") ), Spacer() ), ), ) return expr object_id = 'needs import or implem' ##### TODO class World_dna_holder(InstanceMacro): #070201 modified from GraphDrawDemo_FixedToolOnArg1; need to unify them as a ui-provider framework # args # options world = Option(World, World(), doc = "the set of model objects") # revised 070228 for use in _30j # internals ## world = Instance( World() ) # maintains the set of objects in the model _value = DisplayListChunk( world) _cmd_Make_DNA_Cylinder_tooltip = "make a DNA_Cylinder" ###e or parse it out of method docstring, marked by special syntax?? def _cmd_Make_DNA_Cylinder(self): ###e ideally this would be a command defined on a "dna origami raster", and would show up as a command in a workspace UI # only if there was a current raster or a tendency to automake one or to ask which one during or after a make cyl cmd... world = self.world expr = DNA_Cylinder() # Note: ideally, only that much (expr, at this point) would be stored as world's state, with the following wrappers # added on more dynamically as part of finding the viewer for the model objects in world. ###e # (Nice side effect: then code-reloading of the viewer would not require clearing and remaking the model objs.) expr = DisplayListChunk( expr) # displist around cylinder itself -- speeds(unverified) redraw of cyl while it's dragged, or anywhen [070203] ###BUG (though this being the cause is only suspected): prefs changes remake the displist only the first time in a series of them, # until the next time the object is highlighted or certain other things happen (exact conditions not yet clear); not yet diagnosed; # might relate to nested displists, since this is apparently the first time we've used them. # This is now in BUGS.txt as "070203 DisplayListChunk update bug: series of prefs checkbox changes (eg show central cyl, # testexpr_30g) fails to remake the displist after the first change", along with suggestions for investigating it. #####TRYTHEM expr = DraggableObject( expr) ## expr = DisplayListChunk( expr) # displist around drag-repositioned cyl -- prevents drag of this cyl from recompiling world's dlist ###BUG: seems to be messed up by highlighting/displist known bug, enough that I can't tell if it's working in other ways -- # the printed recompile graph makes sense, but the number of recomps (re changetrack prediction as I drag more) # seems wrong (it only recompiles when the drag first starts, but I think every motion ought to do it), # but maybe the highlight/displist bug is preventing the drag events from working properly before they get that far. # So try it again after fixing that old issue (not simple). [070203 9pm] newcyl = world.make_and_add( expr, type = "DNA_Cylinder") #070206 added type = "DNA_Cylinder" if 'kluge070205-v2' and world.number_of_objects > 1: # note: does not imply number of Cylinders > 1! ### KLUGE: move newcyl, in an incorrect klugy way -- works fine in current code, # but won't work if we wrap expr more above, and won't be needed once .move works. ### DESIGN FLAW: moving this cyl is not our business to do in the first place, # until we become part of a "raster guide shape's" make-new-cyl-inside-yourself command. cyls = world.list_all_objects_of_type(DNA_Cylinder) # a nominally read-only list of all cylinders in the world, in order of _e_serno (i.e. creation order as Instances) # (WARNING: this order might be changed in the API of list_all_objects_of_type). ###KLUGE -- this list should be taken only from a single raster if len(cyls) > 1: if newcyl is cyls[-1]: newcyl.motion = cyls[-2].motion - DY * 2.7 ###KLUGE: assumes current alignment # Note: chosen distance 2.7 nm includes "exploded view" effect (I think). else: print "added in unexpected order" ###should never happen as long as _e_serno is ordered like cyl creation order return def _cmd_Make_some_rects(self): #070206 just to show we can make something else and not mess up adding/moving the next cyl world = self.world expr = Center(Rect(0.5, 1, yellow)) expr = DraggableObject(expr) # note: formally these rects are not connected to their cyls (e.g. won't move with them) cyls = world.list_all_objects_of_type(DNA_Cylinder) #e could remove the ones that already have rects, but that requires storing the association -- doesn't matter for this tests rects = [] for cyl in cyls: posn = cyl.center # includes effect of its DraggableObject motion ### is this being usage tracked? guess yes... what are the effects of that?? guess: too much inval!! ####k ###e need debug code to wra this with "show me the inval-and-recompute-causing-fate of whatever usage is tracked here" ## print "cyl.center was %r" % (posn,) where = posn + DZ * 1.5 ###KLUGE: assumes current alignment newrect = world.make_and_add(expr, type = "rect") newrect.motion = where ###KLUGE, I think, but works for now rects.append(newrect) #070211 hack experiment for r1,r2 in zip(rects[1:], rects[:-1]): junk = world.make_and_add( Line( getattr_Expr(r1,'center'), getattr_Expr(r2,'center'), red), type = "line") return def _cmd_Make_red_dot(self):#070212, so we have a fast-running 'make' command for an empty model (#e should add a posn cursor) expr = Cylinder((ORIGIN, ORIGIN+DZ*0.01), capped = True, radius = 0.3, color = red) # a red dot [#e implem Circle or Disk] expr = DraggableObject(expr) self.world.make_and_add(expr, type = "circle") def _cmd_Show_potential_crossovers(self): #070208 experimental stub prototype """for all pairs of cyls adjacent in a raster (more or less), perhaps assuming aligned as desired for now (tho for future general use this would be bad to assume), come up with suggested crossovers, and create them as potential model objs, which shows them (not if the "same ones" are already shown, not any overlapping ones -- but shown ones can also be moved slightly as well as being made real) [later they can be selected and made real, or mad real using indiv cmenu ops; being real affects them and their cyls but is not an irreversible op! it affects the strand paths...] """ world = self.world cyls = world.list_all_objects_of_type(DNA_Cylinder) cylpairs = [] for cyl1 in cyls: for cyl2 in cyls: if id(cyl1) < id(cyl2): #e no, use the order in the list, use indices in this loop, loop over i and j in range... cylpairs.append((cyl1,cyl2)) ##e make this a py_utils subroutine: unordered_pairs(cyls) ?? for cyl1, cyl2 in cylpairs: # create an object (if there is not one already -- else make it visible again?) # which continuously shows potential crossovers between these cyls. # STUB: create one anew. # STUB: let it be a single connecting line. ###BUG: cyl1.center evals to current value -- but what we want here is an expr to eval later. ###FIX: use getattr_Expr # What do we do? Someday we'll rewrite this loop as an iterator expr in which cyl1 will be a Symbol or so, # so simulate that now by making it one. #####e DECIDE HOW, DO IT, IMPLEM ### [BUT, note, it's an academic Q once we use a new macro instead, since we pass it the cyls, not their attrs.] expr = Line(cyl1.center, cyl2.center, blue, thickness = 2) #e thickness or width?? ###IMPLEM Line and refile this design note: ###e design note: it's a line segment, but LineSegment is too long & nonstd a name, # and you need endpoints anyway to conveniently specify even a ray or line, # so have options to make it ray or line. if you want to use end1 and direction/length or vector, do so, # but you could want that too for any of segment, ray, or line (except you'd like option to leave out length for some). index = ( object_id(cyl1), object_id(cyl2) ) ### IMPLEM object_id #e rename it? make it an attr of object? #### design note: this is the index for the new instance (find or make; if find, maybe make visible or update prefs). # (or maybe just discard/replace the old one? NO, see below for why) # We also need an InstanceDict index, and to implem InstanceDict and use it # for this. These objects would be children of the common parent of the cyls (found dynamically so they go inside # groups etc when possible, i think, at least by default -- but if user moves them in MT, that should stick, # WHICH IS A BIG REASON TO FIND AND REUSE rather than replacing -- user might have done all kinds of per-obj edits). ## # older cmt: ## # ok, who has this op: one of the cyls, or some helper func, or *this command*? ## # find backbone segs on cyl1 that are facing cyl2 and close enough to it, and see if cyl2 backbone is ok ## # *or*, just find all pairs of close enough backbone segs -- seems too slow and forces us to judge lots of near ones - nah ## # (what if the cyls actually intersect? just ignore this issue, or warn about it and refuse to find any??) ## # (in real life, any cyl that overlaps another in some region should probably refuse to suggest any mods in that region -- ## # but we can ignore that issue for now! but it's not too different than refusing to re-suggest the same crossover -- ## # certain features on a cyl region (crossovers, overlaps) mean don't find new potential crossovers in that region.) ## for seg in cyl1.backbone_segments: ###IMPLEM; note, requires coord translation into abs coords -- kluge: flush motion first?? ## pass##stub ######e more return pass # end of class World_dna_holder [a command-making object, I guess ###k] # == #070214 stub/experiment on higher-level Origami objects ##e refile into an Origami file, once the World_dna_holder can also be refiled class OrigamiDomain(DelegatingInstanceOrExpr): """An OrigamiDomain is a guide object which organizes a geometrically coherent bunch of DNA guide objects (with the kind of geometric organization depending on the specific subclass of OrigamiDomain), in a way that facilitates their scaffolding/stapling as part of a DNA Origami design. The prototypical kind of OrigamiDomain is an OrigamiGrid. Other kinds will include things like polyhedral edge networks, single DNA duplex domains, and perhaps unstructured single strands. """ pass OrigamiScaffoldedRegion = Stub class OrigamiGrid(OrigamiDomain): """An OrigamiGrid holds several pairs of DNA_Cylinders in a rasterlike pattern (perhaps with ragged edges and holes) and provides operations and displays useful for designing raster-style DNA Origami in them. An OrigamiGrid is one kind of OrigamiDomain. Note that an OrigamiScaffoldedRegion can in general cover all or part of one or more OrigamiDomains, even though it often covers exactly one OrigamiGrid. """ def add_cyl_pair(self, cyl_pair, above = None, below = None): """Add the given cyl_pair (or perhaps list of cyl_pairs? #e) into self, at the end or at the specified relative position. Set both cyls' position appropriately (perhaps unless some option or cyl propert prevents that #e). #k Not sure whether we'd reset other properties of the cyls appropriately if they were not yet set... or even if they *can be* not yet set. #obs cmt after this?: #k Not sure if this is the bulk of the op for adding a new cyl created by self, or not -- probably not -- let's say this does minimal common denominator for "add a cyl", and other ops decide what those cyls should be like. But this does have to renumber the existing cyls... Q: should we force adding them in pairs, so this op doesn't need to change which kind of cyl (a or b in pairing scheme) an existing cyl is? yes. """ assert 0 # nim def make_and_add_cyl_pair(self, cyl_options = {}, cyl_class = DNA_Cylinder): #e rename cyl_class -> cyl_expr?? """Make and add to self a new cyl pair (based on the given class or expr, and customization options), at the end of self (or at a specified position within self #e), and return the pair. """ #### Q: at what point to cyl exprs get instantiated? and various indices chosen? note we should return Instances not exprs ## cyl_expr = cyl_class(**cyl_options) ### DESIGN FLAW: cyl_class(**cyl_options) would add args if there were no options given! ###e to fix, use an explicit "expr-customize method", e.g. # cyl_expr = cyl_class._e_customize(**cyl_options) # works with cyl_class = actual python class, or pure expr -- # not sure how to implem that (might need a special descriptor to act like either a class or instance method) # or as initial kluge, make it require an instance... but that means, only pass an expr into here cyl_expr = cyl_options and cyl_class(**cyl_options) or cyl_class cyl1_expr = cyl_expr(strand1_theta = 180) # change the options for how to align it at the seam: strand 1 at bottom ###e Q: should we say pi, or 180? # A: guess: 180 -- discuss with others, see what's said in the origami figures/literature, namot2, etc cyl2_expr = cyl_expr(strand2_theta = 0) #e ditto: strand 2 at top cyl1 = self.make_and_add_to_world(cyl1_expr) ###k guess ##e need any options for this call? eg does index or type relate to self?? need to also add a relation, self to it? #e and/or is that added implicitly by this call? (only if we rename the call to say "make child obj" or whatever it is) # # note: cyl1 starts out as a child node of self in MT, a child object for delete, etc, # but it *can* be moved out of self and still exist in the model. Thus it really lives in the world # (or model -- #e rename method? worry about which config or part?) more fundamentally than in self. cyl2 = 'ditto...' pair = (cyl1, cyl2) #e does it need its own cyl-pair object wrapper, being a conceptual unit of some sort? guess: yes, someday self.add_cyl_pair(self, pair) # that sets cyl posns (and corrects existing posns if needed) # and (implicitly due to recomputes) modifies summary objects (grid drawing, potential crossover perceptors) as needed return pair pass # end of class OrigamiGrid # end
NanoCAD-master
cad/src/exprs/dna_ribbon_view.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ toolbars.py - OpenGL toolbars, basically serving as "working mockups" for Qt toolbars (but someday we should be able to turn the same toolbar configuration code into actual working Qt toolbars) @author: bruce @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. """ from exprs.Column import SimpleRow from exprs.Highlightable import Highlightable from exprs.TextRect import TextRect from exprs.Boxed import Boxed from exprs.command_registry import CommandRegistry from utilities.constants import gray, white, blue, green from exprs.Exprs import list_Expr, format_Expr from exprs.If_expr import If from exprs.iterator_exprs import MapListToExpr, KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr from exprs.attr_decl_macros import Arg, State from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.ExprsConstants import StubType, StateRef from exprs.__Symbols__ import _self class Toolbar(DelegatingInstanceOrExpr): pass Command = StubType # might be a class in other files class MainCommandToolButton(DelegatingInstanceOrExpr): #e rename? "Toolbutton for one of the main tools like Features, Build, Sketch -- class hierarchy subject to revision" # args toolbar = Arg(Toolbar) # our parent - #e rename parent_toolbar? to distinguish from our flyout_toolbar. toolname = Arg(str) #e.g. "Build" command = Arg(Command, doc = "the command invoked by pressing this toolbutton (might be transient or long lasting)") ###k type ok? subtools = Arg(list_Expr) # list of subtools (for cmenu or flyout), with None as a separator -- or as an ignored missing elt?? # like menu_spec items? # Q: can they contain their own conditions, or just let the list be made using Ifs or filters? # A: subtools can contain their own conditions, for being shown, enabled, etc. they are ui elements, not just operations. #e also one for its toolbar, esp if it's a mutually exclusive pressed choice -- and ways to cause related cmd/propmgr to be entered # state pressed = State(bool, False, doc = "whether this button should appear pressed right now") # formulae plain_bordercolor = If(pressed, gray, white) highlighted_bordercolor = If(pressed, gray, blue) pressed_in_bordercolor = If(pressed, gray, green) # green = going to do something on_release_in pressed_out_bordercolor = If(pressed, gray, white) # white = not going to do anything on_release_out # appearance delegate = Highlightable( plain = Boxed(TextRect(toolname), bordercolor = plain_bordercolor), highlighted = Boxed(TextRect(toolname), bordercolor = highlighted_bordercolor), #e submenu is nim pressed_in = Boxed(TextRect(toolname), bordercolor = pressed_in_bordercolor), pressed_out = Boxed(TextRect(toolname), bordercolor = pressed_out_bordercolor), sbar_text = format_Expr( "%s (click for flyout [nim]; submenu is nim)", toolname ), on_release_in = _self.on_release_in, cmenu_obj = _self ###IMPLEM cmenu_obj option alias or renaming; or call it cmenu_maker?? ) # repr? with self.toolname. Need to recall how best to fit in -- repr_info? ##e # actions def on_release_in(self): if not self.pressed: print "on_release_in %s" % self.toolname self.pressed = True #e for now -- later we might let main toolbar decide if this is ok #e incremental redraw to look pressed right away? or let toolbar decide? self.toolbar._advise_got_pressed(self) else: #### WRONG but not yet another way to unpress: self.pressed = False print "unpressed -- not normal in real life!"### return #e stub def cmenu_spec(self, highlightable): ###IMPLEM this simpler cmenu API (if it still seems good) return map( self.menuitem_for_subtool, self.subtools ) ###e how can that func tell us to leave out one, or incl a sequence? def menuitem_for_subtool(self, subtool): # stub, assume not None etc return ( subtool.name, subtool.cmd_invoke ) pass class MainToolbar(Toolbar): ###e how is the Main one different from any other one??? not in any way I yet thought of... # unless its flyout feature is unique... or maybe it has the behavior of deciding what to look like, inside it?? # Nah, its client needs to provide the spec that, even if MainToolbar then does the work... but if it *can* do the work, # that might count... maybe it's just that it has no parent toolbar? #e rename """The main toolbar that contains (for example) Features, Build, Sketch, Dimension (tool names passed as an arg), with their associated flyout toolbars, and maintains the state (passed as a stateref) of what tool/subtool is active. """ # args registry = Arg( CommandRegistry, doc = "the place in which tool name -> tool code mapping is registered, and in which subtools are found") #e the app object in which the tools operate? #e the world which they affect? toolnames = Arg(list_Expr, doc = "list of names of main tools") toolstack_ref = Arg(StateRef, doc = "external state which should be maintained to show what tool & subtool is active now") # formulae # appearance delegate = SimpleRow( MapListToExpr( _self.toolbutton_for_toolname, toolnames, KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr(SimpleRow) ), TextRect("flyout goes here") ) def toolbutton_for_toolname(self, toolname): assert type(toolname) == type("") registry = self.registry ## expr = Boxed(TextRect(toolname)) # stub #e look up commands from registry ### LOGIC BUG: don't we get the toolname/cmd pair from the reg? if so, # then at this stage, just look up cmd from a local cache we made of cmds that go with our names for them. # But in current code, toolnames were passed in. Nevermind. command = registry.command_for_toolname(toolname) ###STUB - at least since retval might be None # [also, terms are messed up -- straighten out cmd vs tool, use same for main and sub] # [maybe: a command is something you do, and a command is "invoke a tool", ie start it (does not imply finishing it) -- # but i don't like that much -- what i look up here is the longlived-thing-maker (toolrun maker), # not a subr that invokes it. otoh what abt toolbuttons that have immediate effect, no longlived thing created? # their presence means i *do* have to look up a command, which when run *might* change toolstack state.] subtools = registry.subtools_for_command(command) ###STUB?? expr = MainCommandToolButton( self, toolname, command, subtools) #e is it ok about MapListToExpr that it makes us instantiate this ourselves? Can't it guess a cache index on its own? #e related Q: can we make it easier, eg using nim InstanceDict or (working) _CV_ rule? instance = self.Instance( expr, "#" + toolname) return instance def _advise_got_pressed(self, button): print "my button %r with toolname %r says it got pressed" % (button, button.toolname) ###STUB - do the following: #e decide if legal at this time #e set it as the next running button #e unpress other buttons (and finish or cancel their runs if needed) (maybe only if their actions are incompat in parallel??) # e.g. something like: ## while toolstack_ref.get_value()[-1].is_incompatible_with(something): ## didit = toolstack_ref.get_value()[-1].force_finish(something) ## if not didit: ## # oops, still in some prior command (and what about some we already popped out of? restore them? ## # no, don't pop out yet, unless we want that...) #e start a new ToolRun of this button's command #e put it on the stack we were passed (that way its flyout gets displayed, and its pm gets displayed) #e update our flyout and PM if needed (for example, by figuring out what subcommands have been registered with this name) #e update other stuff not yet used, like a display/edit style, various filters... return pass # end
NanoCAD-master
cad/src/exprs/toolbars.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ widget2d.py $Id$ """ ###e rename module, to same caps? hmm, maybe just to widget, since it has that class too? or move that class? from OpenGL.GL import GL_FALSE from OpenGL.GL import glColorMask from OpenGL.GL import GL_TRUE from OpenGL.GL import glPushName from OpenGL.GL import glPopName from exprs.instance_helpers import InstanceOrExpr from exprs.py_utils import printnim from exprs.__Symbols__ import _self from exprs.Exprs import V_expr class Widget(InstanceOrExpr): # Widget can also be used as a typename -- ok?? # I guess that just means it can be used to coerce things... see docstring-comment in Widget2D. #####@@@@@ """Class whose Instances will be drawable. [#doc more]""" ## methods moved into superclass 070201 pass # end of class Widget # == class Widget2D(Widget): """1. superclass for widget instances with 2D layout boxes (with default layout-box formulas). Also an expr-forming helper class, in this role (as is any InstanceOrExpr). 2. can coerce most drawable instances into (1). WARNING: I DON'T YET KNOW IF THOSE TWO ROLES ARE COMPATIBLE. """ # default layout-box formulas # bright is bbox size on right, bleft on left (both positive or zero) #e rename, bright is a word printnim("lbox defaults are not customizable -- wrong??") #k is this still true?? if so, is it wrong? IIRC old cmts suggest a fix... [070121] bright = 0 btop = 0 bleft = 0 bbottom = 0 ## width = bleft + bright # this would be ok if bleft etc were exprs; since they're constants we have to say _self explicitly ## height = bbottom + btop width = _self.bleft + _self.bright height = _self.bbottom + _self.btop center = V_expr( (_self.bright - _self.bleft) / 2.0, (_self.btop - _self.bbottom) / 2.0, 0.0) # 070227 moved here from Rect pass # end of class Widget2D # == class _misc_old_code: # not used now, maybe useful someday # helper methods (some really belong on other objects) def disable_color(self): ### really should be a glpane method "don't draw color pixels (but keep drawing depth pixels, if you were)" glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE) pass def enable_color(self): # nested ones would break, due to this in the inner one -- could be fixed by a counter, if we used them in matched pairs glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) pass def push_saved_names(self): # truer args would be: both glpane and transient_state object for glname in self.saved_glnames: glPushName(glname) def pop_saved_names(self): for glname in self.saved_glnames: # wrong order, but only the total number matters glPopName() pass # lowercase stub doesn't work for the following, since they get called during import, so use uppercase Stub # need InstanceOrExpr defined for this one: Stub = Widget2D # use this for stub InstanceOrExpr subclasses # end
NanoCAD-master
cad/src/exprs/widget2d.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ draggable.py @author: bruce @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. 070203 status: DraggableObject works, except: - move/flush untested, and if it works, will require objs already with posn state - moved/rotated coordsys untested See also the future usage comments in DraggableObject's docstring. 070203 Design discussion (scratch): Draggable( thing): - have own state which is drag pos - have a command which pushes that state into the object by calling a move method on it - run that command on mouseup, for now, so highlighting can work inside the object - temporary solution, since external bonds would need abs coords even during the drag - better soln is for inner thing to be drawable in more than one coordsys! its own, or abs. and for points in it to reveal coords in more than one. coordsys to draw in is passed how: - parameter in dynenv in glpane? problem is, changetracking of drawing effects. they can change in one coordsys indeply of changing in another one!!! ### that is, there is a coordsys of least change, and this varies by part and by time! but if ever nonconstant, it's "none" (not counting objects with symmetries for it, like spheres, dots, infinite lines). so for a given object that changed, either it changed in all coordsystems, or in all but a specific one... but that one is not a fixed property of that object. But our code should always be able to produce a good guess about what system that is. BTW it might really be more than one system, since they can equal each other for awhile and then not! This happens for the above Draggable idea, between an object's native system (used in its own displist) and the one maintained by Draggable during a drag. Note, that's for a Draggable wrapper, but there is also a Draggable interface (in comments and stub code), which is for any object that can accept standard drag events, regardless of what it uses them for (which could be anything that varies with mousepos while it's down). In theory wrapper and interface are implementationally independent namespaces (AFAIK so far) so this overloading would be tolerable. But would it be misleading? Would all methods of the wrapper be assumed to be part of the interface? Quite possibly. So one of them should be renamed. Note that Draggability of a visible object will tend to go along with selectability... For now, just use a temp name, fix it later. Avoid overloading -- call it DraggableObject. It assumes its arg has move method, etc. """ from math import pi from exprs.Overlay import Overlay from exprs.Rect import Rect from exprs.transforms import Translate, RotateTranslate from exprs.Highlightable import Highlightable from exprs.DisplayListChunk import DisplayListChunk from exprs.demo_MT import node_name #e really this belongs in a file which defines ModelTreeNodeInterface from geometry.VQT import V, Q from geometry.VQT import norm from geometry.VQT import cross from geometry.VQT import vlen from utilities.constants import blue, white, ave_colors from exprs.Exprs import call_Expr, LvalueFromObjAndAttr, format_Expr, V_expr, neg_Expr from exprs.Boxed import Boxed from exprs.If_expr import If from exprs.Center import TopLeft, Center from exprs.clipping_planes import Clipped, clip_to_right_of_x0, clip_below_y0 from exprs.ExprsConstants import StubType, StateRef, Vector, Quat, ORIGIN from exprs.widget2d import Widget from exprs.instance_helpers import DelegatingInstanceOrExpr, ModelObject from exprs.attr_decl_macros import Arg, Option, State, Instance from exprs.__Symbols__ import Anything, _self, _my from exprs.DragBehavior import SimpleDragBehavior debug070209 = True # turn on debug prints related to drags and clicks, and "click to toggle self.selected" test-kluge # == ###e refile WarpColors etc ColorFunction = StubType class WarpColors(DelegatingInstanceOrExpr): """#doc""" delegate = Arg(Widget) #e really Drawable or so warpfunc = Arg(ColorFunction) #e also might need hashable data specifying what it does, as an attr of it or another arg def draw(self): #e temporarily push warpfunc onto the front of a sequence of functions in a composition # which forms the glpane's overall color-warping function # (front means first run by fix_color, when it turns specified colors into drawn colors) # # (this assumes there are no GL state variables that do good-enough color-warping -- # if there are, it would be much better & more efficient to use them -- # but other things will end up needing this scheme) glpane = self.env.glpane old_warpfuncs = getattr(glpane, '_exprs__warpfuncs', None) # note: attr also used in DisplayListChunk and fix_color method glpane._exprs__warpfuncs = (self.warpfunc, old_warpfuncs) # temporary #e also modify a similar sequence of hashable func-effect data -- unless presence of any funcs turns off all displists # (we'll do that to start with, since simplest) try: self.drawkid( self.delegate) finally: glpane._exprs__warpfuncs = old_warpfuncs return pass # == # [old cmt:] ### TODO: DraggableObject should ask the obj when it prefers to be moved (eg so other objs know its abs location) -- # never; only at file save or some other kind of update; at end of drag; continuously. # ('m not sure things in that scheme are divided up quite right -- its model coords may need to update continuously regardless... # or at least that may be a different Q than whether a graphical delegate inside DraggableObj wants that.) #### NOTE [070318]: DraggableObject will be refactored soon. Its drag event handling methods (on_*) need to be moved into # separate DragBehaviors, one for translate (i.e. SimpleDragBehavior) and one for rotate, # or maybe into a fancier DragBehavior which delegates to one or the other of those, # and also lets us know whether any on_drags occurred so we can do selection behavior in on_release if not. # See also: other uses of any DragBehavior. class DraggableObject(DelegatingInstanceOrExpr): """DraggableObject(obj) is a wrapper which makes any model object draggable (###doc the details), and also helps provides a context menu specific to obj. [##e It may be extended to make obj click-selectable or even region-selectable, at the proper times, too.] WARNING: Experimental -- API/organization will surely change, integrating not only rotation, but click to select, etc. The resulting wrapper will typically be applied by model->view macros. In fact, it's more complicated than that: the selection-click controller will wrap single objects, but the draggability wrapper is more likely to be organized something like this, where the named localvars refer to sets whose membership depends on selection: visibles = DisplayListChunk(fixed_stuff) + distortedly_moving_stuff + DraggableObject(DisplayListChunk(dragging_as_a_unit_stuff)). The distortedly_moving_stuff includes things like external bonds between fixed and being-dragged atoms, which have to stretch in individual ways during the drag. """ # args obj = Arg(ModelObject) # options #e selectable = Option(bool, True, doc = "whether to let this object be click-selectable in the standard way") [see selected] rotatable = Option(bool, True, doc = "whether to let this object rotate about its center using MMB/Alt/Option drags") # This is intended to implement an initial subset of the "New motion UI" [070225 new feature] # [###e default will change to False after testing] # WARNING: as an optim, we might require that this be True initially, or even always (i.e. be a constant), # if it will ever be True during the Instance's lifetime -- not sure. If so, this requirement must at least be documented, # and preferably error-detected. ###FIX (if we do require that) # experimental kluge 070314 _kluge_drag_handler = Option(Anything, _self, doc = "object to receive our on_press/on_drag/on_release events, in place of _self") # state selected = State(bool, False) ###KLUGE test stub, only set when debug070209 translation = Option(Vector, V(0,0,0), #070404 doc = "initial translation [WARNING: might merge with misnamed self.motion (a State attr) to make a StateOption]") motion = State(Vector, _self.translation) # publicly visible and settable (but only with =, not +=). ##e rename to translation? (by making it a StateOption) ##e (or deprecate the concept of StateOption but make any State settable initially by a special option not just with same name? ## eg either initial_attr or initial_data = [something with dict or attr access to the data] ??) ##e NOTE [070404]: I miscoded translation as Arg rather than Option, and said StateArg rather than StateOption in docstring, # though intending only named uses of it -- is this evidence that Arg / Option / Parameter should be the same, # that Option should be the default meaning, and positional arglists should be handled differently and as an extra thing # (eg like the old _args feature -- which leads to clearer code when subclassing)?? Guess: quite possibly, but needs more thought. # WARNING: use of += has two distinct bugs, neither error directly detectable: # - changes due to += (or the like) would not be change tracked. # (But all changes to this need to be tracked, so our drawing effects are invalidated when it changes.) # - value might be a shared Numeric array -- right now use of = to set this doesn't copy the array to make us own it. rotation = State(Quat, Q(1,0,0,0)) #070225 new feature -- applied around object center # experiment 070312: works (see test_StateArrayRefs_2) ###doc ##e clean up ##k is it making the usual case slow in a significant way?? delta_stateref = Option(StateRef, call_Expr( LvalueFromObjAndAttr, _self, 'motion'), doc = "#doc") use_motion = delta_stateref.value # geometric attrs should delegate to obj, but be translated by motion as appropriate. ##e Someday we need to say that in two ways: # - the attrs in the "geometric object interface" delegate as a group (rather than listing each one of them here) # - but when they do, they get passed through a change-of-coords boundary, and they know their own coordsystems, # so the right thing happens. # But for now we have no way to say either thing, so we'll add specific formulas for specific attrs as needed. [070208] ##e Note that before the obj types know how to translate due to type, the interface (which knows the attrs indivly) # could know it. So, delegation of all attrs in an interface can be done by special glue code which also knows # how to transform them in useful ways, by knowing about those attrs and what transforms are useful. # This is useful enough to keep, even once its default transforms can come from declared attr types & # values knowing their coordsys. It adds value to that since interfaces can always know special cases about specific attrs. if 0: # update 070209 late: try doing this in Translate below, with the other involved exprs delegating as usual... ####k center = obj.center + motion # following comments are from when the above was 'if 1' a day or two ago -- still relevant since general [##e refile??]: # Problem: won't work for objs with no center! Solution for now: don't try to eval the self attr then. # Not perfect, since what ought to be AttributeError will turn into some other exception. ##e One better solution would involve declared interfaces for obj, and delegation of all attrs in interfaces # of a certain kind (geometric), so if obj met more interfaces and had more attrs, those would be included, # but if not, we would not have them either. ##e Or alternatively, we could provide an easy way to modify the above formula # to specify a condition under which center should seem to exist here, with that cond being whether it exists on obj. ### A potential problem with both solutions: misleasing AttributeError messages, referring to self rather than obj, # would hurt debugging. So we probably want to reraise the original AttributeError in cases like that, whatever # the way in which we ask for that behavior. That means one construct for "passing along attr missingness", # but *not* a composition of one construct for saying when this attr is there, and one for asking whether another is. # Note: can't we delegate center (& other geometry) through the display delegate below, if Highlightable passes it through # and Translate does the coordinate transformation? ###e # appearance obj_name = call_Expr( node_name, obj) #070216 # Note: node_name is used in MT_try2; it's better than using _e_model_type_you_make (for our use in sbar_text, below). # BTW, node_name is a helper function associated with ModelTreeNodeInterface (informal so far). # # If you want to wrap an object with extra info which specifies its node_name, use ... what? ###k hmm, I forget if there # is a way partway through being implemented... # maybe WithAttributes( Center(Rect(0.4, 0.4, green)), mt_name = "green rect #n" )... i guess yes, ### TRY IT # should clean this situation up, use Adaptor term for that pattern # of interface conversion, etc... [070404 updated comment] # (Note [070216]: I had a bug when I had a comma after the above def. This made obj_name, included directly in another expr, # turn into a singleton tuple of the call_Expr value, but when included as _self.obj_name (normally equivalent to obj_name), # turn into something else (since eval of a tuple must not descend inside it -- guess, might have been a tuple_Expr). # I'm not sure how to detect this error except to stop permitting tuple(expr) to be allowed as abbrev for a tuple_Expr -- # which seems too inconvenient -- or to figure out a way for the formula scanner to detect it (and make it illegal as the # rhs of an assignment into a class namespace -- probably ok to make illegal). ##DOIT sometime) obj_drawn = If( selected, Overlay( obj, Rect(1,1,blue)), ##### WRONG LOOK for selected, but should work [070209] #BUG: Rect(1,lightblue) is gray, not light blue -- oh, it's that failure to use type to guess which arg it is! obj ) sbar_text_for_maybe_selected = If( selected, " (selected)", "") delegate = Highlightable( # Note 070317: since Highlightable is outside of RotateTranslate, its coordsys doesn't change during a drag, # thus avoiding, here in DraggableObject, the bug that came up in the first implem of DraggablyBoxed, # whose highlightable rectframe was moving during the drag, but was also being used to supply the coordsys # for the drag events. This bug is actually in SimpleDragBehavior above, and the fix will be confined to that class. # # plain appearance RotateTranslate( obj_drawn, rotation, use_motion), # hover-highlighted appearance (also used when dragging, below) highlighted = RotateTranslate( DisplayListChunk( # This inner DisplayListChunk, in theory, might help make up for current implem of disabling them inside WarpColors... # in my tests, it didn't make a noticeable difference (probably since obj is fast to draw). [070216 2pm] # # Note: if obj has its own DisplayListChunk, does that notice the value of whatever dynenv var is altered by WarpColors?? # We'll have to make it do so somehow -- perhaps by altering the displist name by that, or turning off displists due to it. # For this initial implem [070215 4pm], we did the latter. ## WarpColors( obj_drawn, lambda color: ave_colors( 0.3, white, color ) ), # whiten the color -- ugly ## WarpColors( obj_drawn, lambda color: yellow ), # "ignore color, use yellow" -- even uglier ## WarpColors( obj_drawn, lambda color: ave_colors( 0.2, white, color ) ), # whiten, but not as much -- less ugly WarpColors( obj_drawn, lambda color: ave_colors( 0.1, white, color ) ), # whiten, even less -- even less ugly [best so far] ## WarpColors( obj_drawn, lambda color: ave_colors( 0.2, gray, color ) ), # gray-end instead of whiten -- not quite as good ## WarpColors( obj_drawn, lambda color: (color[1],color[2],color[0]) ), # permute the hues... ), rotation, use_motion ), pressed = _my.highlighted, # pressed_in and pressed_out appearance ###BUG (when we gave pressed_in and pressed_out separately -- ###UNTESTED since then): # this pressed_out appearance seems to work for DNA cyls but not for draggable PalletteWell items! [070215 4pm] ## sbar_text = format_Expr( "Draggable %r", obj ), ##e should use %s on obj.name or obj.name_for_sbar, and add those attrs to ModelObject interface # (they would delegate through viewing wrappers on obj, if any, and get to the MT-visible name of the model object itself) ##e [Can we implem something like try_Expr( try1, try2, try3) which evals to the first one evalling without an exception?? # But that doesn't seem safe unless you have to list the permissible exceptions (like in Python try/except). # The use of this here (temporary) would be to look for obj.name, then try a different format_Expr if that fails. # getattr(obj, 'name', dflt) would get us by, but would not as easily permit alternate format_Exprs in the two cases.] ## # older highlighted or pressed_in appearance (not sure which it was before I inserted the args above this) -- zapping it 070216 late ## If( eval_Expr(constant_Expr(constant_Expr(debug070209))), ## ###e need option or variant of If to turn off warning that cond is a constant: warn_if_constant = False?? ## # also make the printed warning give a clue who we are -- even if we have to pass an option with the text of the clue?? ## Translate( Boxed(obj), motion), ## #######070209 TEST THIS KLUGE -- note it does not include selected appearance ## # (but HL might incl it anyway? sometimes yes sometimes no, not sure why that would be -- ah, it depends on whether ## # mouse is over the moved object (which is silly but i recall it as happening in regular ne1 too -- ###BUG) ## #e not good highlight form ## ####BUG: the layout attrs (lbox attrs, eg bleft) are apparently not delegated, so the box is small and mostly obscured ## Translate( obj, motion) ## ), ## _obj_name = call_Expr(node_name, obj), #070216 # that can't work yet -- it tries to define a new attr in an object (this Highlightable) from outside, # accessible in other option formulae as _this(Highlightable)._obj_name... # instead, I moved this def into _self (far above) for now. sbar_text = format_Expr( "%s%s (can be dragged)", obj_name, sbar_text_for_maybe_selected ), # revised 070216 # This adds some info to sbar_text about what we can do with obj (drag, select, etc)... #e someday, maybe the dynenv wants to control how info of several kinds turns into actual sbar_text. ## on_press = _self.on_press, ## on_drag = _self.on_drag, ## on_release = _self.on_release, on_press = _kluge_drag_handler.on_press, on_drag = _kluge_drag_handler.on_drag, on_release = _kluge_drag_handler.on_release, cmenu_maker = obj ###e 070204 experimental, API very likely to be revised; makes Highlightable look for obj.make_selobj_cmenu_items ) ### DESIGN Q: do we also include the actual event binding (on_press and on_drag) -- for now, we do -- # or just supply the Draggable interface for moving self.obj # and let the caller supply the binding to our internal "cmd" drag_from_to?? ###e # has Draggable interface (see demo_polygon.py for explan) for changing self.motion def _cmd_drag_from_to( self, p1, p2): #e rename drag_hitpoint_from_to? (in the Draggable Interface) """[part of the Draggable Interface; but this interface is not general enough if it only has this method -- some objects need more info eg a moving mouseray, screenrect, etc. Either this gets passed more info (eg a dragevent obj), or we keep the kluge of separate self dynenv queries (like for mousepoint and screenrect), or we provide glue code to look for this method but use more general ones if it's not there. ###e BTW, that interface is a myth at present; all actual dragging so far is done using on_press/on_drag/on_release, with this method at best used internally on some objs, like this one. [as of 070313]] """ if self._delegate.altkey: assert 0, "should no longer be called" ## ###KLUGE, just a hack for testing Highlightable.altkey [070224]; later, do rotation instead (per "New motion UI") ## # (Is it also a ###KLUGE to detect altkey within this method, rather than caller detecting it and passing a flag ## # or calling a different method? YES.) ## ## self.motion = self.motion + (p2 - p1) * -1 ## # change self.rotation... by a quat which depends on p2 - p1 projected onto the screen... or the similar mouse x,y delta... ## ###KLUGE: assume DZ is toward screen and scale is standard.... ## # wait, ###BUG, we don't even have enough info to do this right, or not simply, starting from p1, rather than startpoint... ## dx,dy,dz = p2 - p1 ## rotby = Q(p1,p2) ###WRONG but ought to be legal and visible and might even pretend to be a trackball in some cases and ways ## self.rotation = self.rotation + rotby ## # print "%r motion = %r rotation = %r" % (self, self.motion, self.rotation) else: ## self.motion = self.motion + (p2 - p1) self.delta_stateref.value = self.delta_stateref.value + (p2 - p1) return ##e something to start & end the drag? that could include flush if desired... # can push changes into the object def flush(self, newmotion = V(0,0,0)): self.delegate.move(self.use_motion + newmotion) ###k ASSUMES ModelObject always supports move (even if it's a noop) ###IMPLEM # note, nothing wrong with modelobjects usually having one coordsys state which this affects # and storing the rest of their data relative to that, if they want to -- but only some do. ## self.motion = V(0,0,0) self.delta_stateref.value = V(0,0,0) # if told to move, flush at the same time def move(self, motion): self.flush(motion) return # on_press etc methods are modified from demo_polygon.py class typical_DragCommand #e note: it may happen that we add an option to pass something other than self to supply these methods. # then these methods would be just the default for when that was not passed # (or we might move them into a helper class, one of which can be made to delegate to self and be the default obj). [070313] def on_press(self): point = self.current_event_mousepoint() # the touched point on the visible object (hitpoint) # (this method is defined in the Highlightable which is self.delegate) self.oldpoint = self.startpoint = point # decide type of drag now, so it's clearly constant during drag, and so decision code is only in one place. # (but note that some modkey meanings might require that changes to them during the same drag are detected [nim].) if self._delegate.altkey: self._this_drag = 'free x-y rotate' #e more options later, and/or more flags like this (maybe some should be booleans) ###e or better, set up a function or object which turns later points into their effects... hmm, a DragCommand instance! ##e or should that be renamed DragOperation?? self._screenrect = (ll, lr, ur, ul) = self.screenrect( self.startpoint) # these points should be valid in our delegate's coords == self's coords self._dx = _dx = norm(lr - ll) self._dy = _dy = norm(ur - lr) self._dz = cross(_dx, _dy) # towards the eye (if view is ortho) (but alg is correct whether or not it is, i think) ###k check cross direction sign self._scale = min(vlen(lr - ll), vlen(ur - lr)) * 0.4 # New motion UI suggests that 40% of that distance means 180 degrees of rotation. # We'll draw an axis whose length is chosen so that dragging on a sphere of that size # would have the same effect. (Maybe.) self._objcenter = self._delegate.center self.startrot = + self.rotation else: self._this_drag = 'free x-y translate' if debug070209: self.ndrags = 0 return def on_drag(self): # Note: we can assume this is a "real drag", since the caller (ultimately a selectMode method in testmode, as of 070209) # is tracking mouse motion and not calling this until it becomes large enough, as the debug070209 prints show. oldpoint = self.oldpoint # was saved by prior on_drag or by on_press point = self.current_event_mousepoint(plane = self.startpoint) if debug070209: self.ndrags += 1 ## if (self.ndrags == 1) or 1: ## print "drag event %d, model distance = %r, pixel dist not computed" % (self.ndrags, vlen(oldpoint - point),) if self._this_drag == 'free x-y rotate': # rotate using New motion UI # [probably works for this specific kind of rotation, one of 4 that UI proposes; # doesn't yet have fancy cursors or during-rotation graphics; add those only after it's a DragCommand] # two implem choices: # 1. know the eye direction and the screen dims in plane of startpoint, in model coords; compute in model coords # 2. get the mouse positions (startpoint and point) and screen dims in window x,y coords, compute rotation in eye coords, # but remember to reorient it to correspond with model if model coords are rotated already. # Not sure which one is better. # In general, placing user into model coords (or more precisely, into object local coords) seems more general -- # for example, what if there were several interacting users, each visible to the others? # We'd want each user's eye & screen to be visible! (Maybe even an image of their face & screen, properly scaled and aligned?) # And we'd want their posns to be used in the computations here, all in model coords. # (Even if zoom had occurred, which means, even the user's *size* is quite variable!) # I need "user in model coords" for other reasons too, so ok, I'll do it that way. # # [Hey, I might as well fix the bug in current_event_mousepoint which fakes the center of view, at the same time. # (I can't remember its details right now, but I think it assumed the local origin was the cov, which is obviously wrong.) # (But I didn't look at that code or fix that bug now.)] vec = point - self.startpoint uvec = norm(vec) #k needed?? axisvec = cross(self._dz, uvec) # unit length (suitable for glRotate -- but we need to use it to make a quat!) axisvec = norm(axisvec) # just to be sure (or to reduce numerical errors) scale = self._scale draw_axisvec = axisvec * scale #e times some other length constant too? center = self._objcenter self.axisends = (center - axisvec, center + axisvec) # draw a rotation axis here ###e self.degrees = degrees = vlen(vec) / scale * 180.0 # draw a textual indicator with degrees (and axisvec angle too) ###e ###e or print that info into sbar? or somewhere fixed in glpane? or in glpane near mouse? # now set self.rotation to a quat made from axisvec and degrees theta = degrees / 360.0 * 2 * pi # print "axisvec %r, degrees %r, theta %r" % (axisvec ,degrees,theta) rot = Q(axisvec, theta) self.rotation = self.startrot + rot # note use of self.startrot rather than self.rotation on rhs # avoid += to make sure it gets changed-tracked -- and since it would be the wrong op! elif self._this_drag == 'free x-y translate': self._cmd_drag_from_to( oldpoint, point) # use Draggable interface cmd on self else: assert 0 self.oldpoint = point return def on_release(self): #e here is where we'd decide if this was really just a "click", and if so, do something like select the object, # if we are generalized to become the wrapper which handles that too. if debug070209: if not self.ndrags: # print "release (no drags)" # ie a click self.selected = not self.selected ###KLUGE test stub else: pass # print "release after %d drags" % self.ndrags self.ndrags = 0 pass pass # end of class DraggableObject class DraggablyBoxed(Boxed): # 070316; works 070317 [testexpr_36] before ww,hh State or resizable, and again (_36b) after them # inherit args, options, formulae from Boxed thing = _self.thing ###k WONT WORK unless we kluge ExprsMeta to remove this assignment from the namespace -- which we did. ###e not sure this is best syntax though. attr = _super.attr implies it'd work inside larger formulae, but it can't; # attr = Boxed.attr might be ok, whether it can work is not reviewed; it too might imply what _super does, falsely I think. extra1 = _self.extra1 borderthickness = _self.borderthickness rectframe = _self.rectframe # a pure expr # new options resizable = Option(bool, False, doc = "whether to make it resizable at lower right") # works 070317 10pm (testexpr_36b) except for a few ###BUGS [updated info 070318 7pm]: # + [fixed] the wrong corner resizes (top right) (logic bug) # + [fixed] resizer doesn't move (understood -- wrong expr for its posn; commented below) # - negative sizes allowed (missing feature - limit the drag - need new DragBehavior feature) # - no clipping to interior of rectframe (missing feature - draw something clipped) # - perspective view ought to work, but entirely ###UNTESTED. # also, cosmetic bugs: # - resizer doesn't follow mouse in rotated coordsys, even in ortho view (though it's still useable). # (This is not surprising -- we're using the wrong kind of DragBehavior as a simple kluge.) # - the resizer is ugly, in shape & color. clipped = Option(bool, False, doc = "###doc") #070322 new feature ### make True default after testing? # state # WARNING: due to ipath persistence, if you revise dflt_expr you apparently need to restart ne1 to see the change. ## ww = State(Width, thing.width + 2 * extra1) # replaces non-state formula in superclass -- seems to work ## hh = State(Width, thing.height + 2 * extra1) ## # now we just need a way to get a stateref to, effectively, the 3-tuple (ww,hh,set-value-discarder) ... instead, use whj: whj = State(Vector, V_expr(thing.width + 2 * extra1, - thing.height - 2 * extra1, 0)) #e not sure this is sound in rotated coordsys translation = State(Vector, ORIGIN) # override super formulae ww = whj[0] # seems to work hh = neg_Expr(whj[1]) # negative is needed since drag down (negative Y direction) needs to increase height # (guess: neg_Expr wouldn't be needed if we used an appropriate new DragBehavior in resizer, # rather than our current klugy use of SimpleDragBehavior) # appearance rectframe_h = Instance( Highlightable( ## rectframe(bordercolor=green),####### cust is just to see if it works -- it doesn't, i guess i sort of know why ##bug: __call__ of <getattr_Expr#8243: (S._self, <constant_Expr#8242: 'rectframe'>)> with: () {'bordercolor': (0.0, 1.0, 0.0)} ##AssertionError: getattr exprs are not callable TopLeft(rectframe), #e different colored hover-highlighted version?? for now, just use sbar_text to know you're there. sbar_text = "draggable box frame", # this disappears on press -- is that intended? ###k behavior = SimpleDragBehavior( # arg1: the highlightable _self.rectframe_h, # arg2: a write-capable reference to _self.translation ## fails - evalled at compile time, not an expr: LvalueFromObjAndAttr( _self, 'translation'), ###BUG: why didn't anything complain when that bug caused the state value to be an add_Expr, not a number-array? call_Expr( LvalueFromObjAndAttr, _self, 'translation'), #e alternate forms for this that we might want to make work: # - getattr_StateRef(_self, 'translation') # simple def of the above # - StateRef_for( _self.translation ) # turns any lvalue into a stateref! Name is not good enough, though. ) )) resizer = Instance( Highlightable( Center(Rect(extra1, extra1)), #e also try BottomRight highlighted = Center(Rect(extra1, extra1, white)), pressed = _my.highlighted, sbar_text = "resize the box frame", behavior = SimpleDragBehavior( _self.resizer, call_Expr( LvalueFromObjAndAttr, _self, 'whj') ) )) ###BUG: in Boxed, rectframe comes first, so lbox attrs are delegated to it. We should do that too -- # but right now we draw it later in order to obscure the thing if they overlap. With clipping we won't need that -- # but without clipping we will. If the latter still matters, we need a version of Overlay with delegation != drawing order, # or, to delegate appearance and layout to different instances ourselves. (Or just to define new formulae for lbox -- easiest.) #e drawme = Instance( Overlay( If( clipped, Clipped(thing, planes = [call_Expr(clip_to_right_of_x0, - thing.bleft - extra1 + ww - borderthickness ), # note: the (- borderthickness) term makes the clipping reach exactly # to the inner rectframe edge. Without it, clipping would reach to the outer edge, # which for 3d objects inside the frame can cause them to obscure it. # (Other interesting values are (- extra1) and (- borderthickness/2.0), # but they both look worse, IMHO.) call_Expr(clip_below_y0, thing.btop + extra1 - hh + borderthickness ) ]), thing, ), Translate( rectframe_h, V_expr( - thing.bleft - extra1, thing.btop + extra1) ), If( resizable, ## Translate( resizer, V_expr( thing.bright + extra1, - thing.bbottom - extra1)) ###WRONG - this posn is fixed by thing's lbox dims, not affected by ww, hh; # will the fix be clearer if we use a TopLeft alignment expr? # It'd be hard to use it while maintaining thing's origin for use by external alignment -- # but maybe there's no point in doing that. Translate( resizer, V_expr( - thing.bleft - extra1 + ww, thing.btop + extra1 - hh)) ) )) _value = Translate( drawme, ## DisplayListChunk( drawme), ###k this DisplayListChunk might break the Highlightable in rectframe_h ##### translation ) pass # end of class DraggablyBoxed # examples ## testexpr_31 = DraggableObject(Rect()) # end
NanoCAD-master
cad/src/exprs/draggable.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ If_expr.py - provide the expr (or macro) If(cond, _then, _else) and related functions/classes $Id$ Note: the current implem can't reside in Exprs.py since it uses higher-level features. It's likely that this will be replaced someday with a lower-level implem, but for now, it has to be in this separate file (maybe that's best anyway). Note: file needs cleanup, and code needs reimplem. """ from utilities.debug import print_compact_stack from exprs.Exprs import OpExpr, canon_expr, expr_constant_value from exprs.instance_helpers import InstanceMacro from exprs.attr_decl_macros import Arg from exprs.__Symbols__ import Anything # == # If -- refiled from ToggleShow.py, 061128 ## If [needs +testing, and [still] review of old code for it vs this new code, esp re OpExpr, and refiling] #e If_expr is probably wrongly implemed too ### see also class If_ in testdraw.py #e for If, see also: # Exprs.py: 565: class If_expr(OpExpr): # so we can use If in formulas # testdraw1_cannib.py: 1054: def If(cond, then, else_ = None): # usage in ToggleShow-outtakes.py # == class If_expr(InstanceMacro): #e refile ### WAIT A MINUTE, why does Exprs.py think it needs to be an OpExpr? for getattr & call? #### NOT YET REVIEWED FOR EVAL_REFORM 070117 cond = Arg(bool) # WARNING: this is effectively a public attr; none of these argnames will be delegated to the value (I think) _then = Arg(Anything) _else = Arg(Anything, None) # note: the None default probably won't work here; the callers presently pass a TextRect # update 070914: I added a kluge in _e_argval_If_expr to try to make this default work # (not using the fact that it's declared here except to permit expr init when it's not passed) def _C__value(self): if self.cond: # digr: I mistakenly thought _then & _else ipaths were same, in some debugging e.g. printing _self.ipath, # since I said _self where I meant _this(Highlightable). # THAT'S GOING TO BE A COMMON PROBLEM -- need to rethink the jargon... # maybe let _this.attr work (find innermost Instance with capitalized classname??) [061121] return self._then else: return self._else pass # addendum 061212: # The above is enough for If(cond, InstanceOrExpr1(), InstanceOrExpr2()), since it delegates to one of them as needed. # but it's not enough for use an as OpExpr that needs to eval, as in # testexpr_9fx2 = Rect(color = If_expr(_my.env.glpane.in_drag, blue, lightblue))() (or the same with color as arg3). # For that, I think we need an eval method which returns a different value in each case... OTOH that might cause trouble # when it's used to instantiate. Which calls which, of _e_eval and _e_make_in and things that call either one? # The one that can say "REJECTED using _e_make_in case" is _CV__i_instance_CVdict -- only happens on toplevel exprs in class attr # assignments I think, maybe only when Instance/Arg/Option is involved. In the IorE class, _e_make_in is primitive # and _e_eval calls it -- after saying printnim("Instance eval doesn't yet handle If"). So that's what we want to fix here: # (439p: This affected many or all uses of If, but note that _e_make_in is probably never or almost never called, # so that is not surprising in hindsight.) def _e_eval(self, env, ipath): # added 061212 ## super method: return self._e_make_in(env, ipath) # note, this might be WRONG if the toplevel assignment of a class formula is an If. # We might want to permit it and change _i_instance or _CV__i_instance_CVdict to do usage-tracking of this eval... ###e # otoh this might all be superceded by the "planned new eval/instantiate code", for which this change of today # is a related pre-experiment. [061212] ## res = self._value ##k? this fails because self is an expr, and env probably contains _self to help that (in which to eval cond), # but we're not doing it right... #### LOGIC BUG -- enough pain to do that to call into Q this method of doing it.... # or can be easy if we do what OpExpr._e_eval would do? condval = self._e_argval_If_expr(0,env,ipath) if condval: res = self._e_argval_If_expr(1,env,ipath) else: res = self._e_argval_If_expr(2,env,ipath) ## print "is this right?: %r gets cond %r, evals to %r" % (self, condval, res) # This happens in a lot of existing If-examples, but seems ok, for reasons not fully understood. (But see comment above 439p.) # For test results & discussion see comments in '061127 coding log' (bruce's g5) dated 061212 410p. return res def _e_argval_If_expr(self, i, env, ipath): # modified from OpExpr (I don't want to try making OpExpr a superclass right now) # _e_argval is not normally defined in InstanceOrExpr, which is important -- # we don't want to override anything in there unwittingly. To be safe, I renamed it. ## args = self._e_args args = self._e_args # I guess this is correct -- self.cond etc would prematurely eval or instantiate them i think (#k not sure!) if i == 2 and len(args) == 2: # KLUGE: special case to make default _else clause work return None res = args[i]._e_eval(env, (i,ipath)) return res pass def If_kluge(*args):###e zap or rename """Use this in place of If when you know you want If to mean If_expr but you worry that the If code might not give it to you yet; this always does give it to you, but warns you if If would not have done so. [probably not needed anymore] """ res1 = res = If(*args) if not isinstance(res, If_expr): res2 = res = If_expr(*args) assert isinstance(res, If_expr) msg = "bug: If() gave you %r instead of this If_expr %r I think you wanted (which I'll use)" % (res1, res2) print msg assert 0, msg #061121 return res def If(cond, _then, _else = None): # note: the default value None for _else doesn't yet work in most uses, due to a nontrivial logic bug # mentioned in ToggleShow.py (I think) and discussed in a notesfile (not in cvs). [IIRC 061128] cond = canon_expr(cond) # (but not on _then or _else to make this work better for immediate use. (might be deprecated, not sure)) constflag, condval = expr_constant_value(cond) if not constflag: return If_expr(cond, _then, _else) #e maybe this will typecheck cond someday (in a way that would complain if it was a pyclass) elif condval: print "using then immediately"### leave these in awhile, since they're rare and might indicate a bug return _then ##k whether or not it's an expr?? (I think so... this is then a primitive form of expr-simplification, I guess) else: print "using else immediately; it's", _else ### print_compact_stack()? yes for temporarily### print_compact_stack("using else immediately: ") return _else pass # Q: If cond is an Instance, do we want to check whether it says it's legal to get its boolean value? # A: We don't need to -- if it cares, let it define __bool__ (or whatever it's called, maybe __nonzero__) and raise an exception. # I think that would be ok, since even if we knew that would happen, what else would we want to do? # And besides, we could always catch the exception. (Or add a prior type-query to cond, if one is defined someday.) # == class If_OpExpr(OpExpr): # 070125 experiment -- can If work as an OpExpr, now that we've done EVAL_REFORM? # evalling both _then and _else might not be *needed* but it might not cause *harm* -- or if it doesm # at least that harm won't be *instantiation*. Guess: it will cause harm, so this implem is not viable, # but it can still be tested and tell me whether it works re instantiation. Test it in analog of testexpr_29a and _29ax. # Note this variant also always requires 3 args (no default _else clause). # # results: it works (see testexpr_29ao*). To become real, it needs: # - default else clause # - refrain from even evalling (not just from instantiating) unused clauses # - repr # advantages once it can become real: # - more optimal when result of eval is passed on to inner iterators, or other expr building / instance building # - problem of customizing an If_expr (testexpr_29) is different in implem -- not sure in what way or which is easier, tho! # (digr re that: we might want to wrap the opts with Optional() in such cases... maybe user should do that explicitly.... # where should I refile that comment? as it says near testexpr_29 about customization outside of If_expr: # the desire came up in Ribbon2_try1 in new file dna_ribbon_view.py, but devel comments might as well be in If_expr.py [here].) def _e_init(self):pass # ok for a stub _e_eval_function = staticmethod( lambda c,t,e: (c and (1,t) or (1,e))[1] ) pass # end
NanoCAD-master
cad/src/exprs/If_expr.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ staterefs.py - facilities for defining and referencing state, in widget exprs which display it, edit it, operate on it, produce it ###e MIGHT RENAME, since widget_env has an attr or arg named this. state.py? might be confusing re State macro. @author: bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. note: this used to define StatePlace and associated things, but those are now in StatePlace.py [as of 061203]; most things remaining here are nim see also: class Set, and State macro, in other files """ from exprs.StatePlace import set_default_attrs from exprs.instance_helpers import InstanceOrExpr from exprs.attr_decl_macros import Arg, ArgOrOption from exprs.ExprsConstants import Type from exprs.py_utils import printnim, stub from exprs.__Symbols__ import Anything from utilities import debug_flags # == class LocalVariable_StateRef(InstanceOrExpr): # guess, 061130 # [moved here from controls.py, 061203; will probably become obs once State works] """ return something which instantiates to something with .value which is settable state... """ #e older name: StateRefFromIpath; is this almost the same as the proposed State() thing? it may differ in how to alter ipath # or some other arg saying where to store the ref, or in not letting you change how to store it (value encoding), # and worst, in whether it's an lval or not -- I think State is an lval (no need for .value) and this is a stateref. type = Arg(Type, Anything) defaultValue = ArgOrOption(Anything, None) ##e default of this should depend on type, in same way it does for Arg or Option # see comments in about problems if this is a formula which uses anything usage-tracked -- same probably applies here. def get_value(self): #e should coerce this to self.type before returning it -- or add glue code wrt actual type, or.... return self.transient_state.value ###e let transient_state not be the only option? does the stateplace even matter?? def set_value(self, val): self.transient_state.value = val #e should coerce that to self.type, or add glue code... return value = property(get_value, set_value) def _init_instance(self): super(LocalVariable_StateRef, self)._init_instance() set_default_attrs( self.transient_state, value = self.defaultValue) #e should coerce that to self.type pass class PrefsKey_StateRef(InstanceOrExpr): # guess, 061204 """ return something which instantiates to something with .value which is settable state, shared with env.prefs[key], properly usage-tracked in a compatible way with the rest of NE1 """ prefs_key = Arg(str) # note: it's probably ok if this is a time-varying formula, tho I don't know why it would be useful. defaultValue = ArgOrOption(Anything, None) ##e default of this should depend on type, in same way it does for Arg or Option -- # nonetheless it's so much more common to specify a default value than a type, that I decided to put default value first. # ##BUG (optimization issue only, and not yet important in practice): # [re-noticed 070228 -- also the topic of the printnim and older comment just below!] # this defaultValue should be evaluated with usage tracking discarded, unless prefs_key changes, # in which case it should be reevalled once (doable if its eval pretends to use prefs_key) -- except ideally the value # for older prefs_keys being reused again would be cached (eg using MemoDict) (not important in practice). # This bug is not yet serious since the actual args so far are constants [as of 070228]. # It's purely an optimization issue; but the worst-case effects are that the default value changes a lot more # often than the prefs value itself, causing needless inval propogation into the get_value caller, # and thus needless recomputation of an arbitrary amount of memoized results which care about the prefs value. # (But for all I know, the usual constant case would slow down due to the overhead of discarding usage tracking. # Actually that's not an issue since we'd also rarely recompute it, not nearly on every get_value.) printnim("need a way to declare that this arg should not be usage-tracked, or have its use as default val do that for that use") # [older version of the comment above; contains still-useful suggestions:] ###e we need a way to declare that this arg should not be usage-tracked re time-variation!!! or to assert it uses nothing. # right now, if it uses something that will silently cause bugs, probably just invisible performance bugs from extra invals. # CAN THERE BE A GENERAL SOLN based on what we use this for (default vals of things that don't care about updates)? # that is more correct in principle, since that's what matters -- eg what if someone added another use of the same arg. ###e type = ArgOrOption(Type, Anything) # this arg is not yet passed by anything, or used in this implem; # moved type from arg2->arg3, and Arg -> ArgOrOption (as being after ArgOrOption arg2 ought to force anyway), 061211 night def get_value(self): #e should coerce this to self.type before returning it -- or add glue code wrt actual type, or.... prefs_key = self.prefs_key assert type(prefs_key) == type("") #k redundant? import foundation.env as env return env.prefs.get( prefs_key, self.defaultValue ) # note: this computes defaultValue at least once, even if not needed. def set_value(self, val): #e should coerce that to self.type, or add glue code... prefs_key = self.prefs_key assert type(prefs_key) == type("") #k redundant? import foundation.env as env env.prefs[prefs_key] = val if 0 and debug_flags.atom_debug: print "fyi: %r set env.prefs[%r] = %r" % (self, prefs_key, val) return value = property(get_value, set_value) def _init_instance(self): super(PrefsKey_StateRef, self)._init_instance() # also set default value of this prefs key (noting that it may or may not already have a saved value) -- # i think this (since it does .get with default arg) is the official way: self.get_value() pass # == end of current code class InstanceOrExpr_Stub: pass ### kluge, permit early import of this file [061126 late] -- ##e probably need to move LocalState into another file class LocalState(InstanceOrExpr_Stub): #e stub, just reserve the name and let searches find where to add code for it """ Permit body exprs to reference specific external state using local names (and perhaps using specified proxy-wrappers, so the state is seen using locally desired types & in local coordinate systems). Usage: - if x is already defined as a Symbol, e.g. by from __Symbols__ import x : maybe: LocalState( (x,type/location/etc), body(x) ) - otherwise: maybe: LocalState( lambda x = XXX(type/location/etc): body(x) ) # might work if we never modify x directly, only use it or set attrs in it """ _init_instance = stub # asfail if used pass """ # e.g. code, scratch area [bruce 070817 made this a string, since as 'if 0' it was causing # a traceback in pychecker, according to Eric M mail to cad list.] LocalState( lambda x = State(int, 1): body(x.value, x.value = 1) ) # note, x.value = 1 is not allowed in a lambda anyway! # in a class: def body(self, x): x.value x.value = 1 """ #e see also ToggleShow.py # end
NanoCAD-master
cad/src/exprs/staterefs.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ test_statearray_2.py @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. test code for one kind of constrained dragging used in testexpr_35a in exprs/test.py DEPRECATED -- replaced by test_statearray_3.py """ # maybe some of these imports are not needed from exprs.Column import SimpleColumn, SimpleRow from exprs.draggable import DraggableObject from exprs.images import Image from exprs.controls import ActionButton ##, PrintAction from exprs.geometry_exprs import Ray from exprs.statearray import StateArrayRefs, StateArrayRefs_getitem_as_stateref from exprs.iterator_exprs import MapListToExpr, KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.attr_decl_macros import Arg, Instance from exprs.ExprsConstants import StateRef, ORIGIN, DY, DX, Width from exprs.py_utils import sorted_items from exprs.__Symbols__ import _self from exprs.DragBehavior import DragBehavior # == example 2 -- full of kluges, but may finally work now; abandoned 070318 in favor of example 3 # maybe-partly-obs cmt: ###UNFINISHED in 3 ways (besides the same kluges as in example 1): # - stores vectors not heights # - constrain_delta nim, so they'll be dragged in all directions # + [works now] delta_stateref nim, # so dragging these won't actually affect the elements of the StateArray yet, which pretty much bypasses the point. # ... done, works, and printit verifies that the statearray values actually change. # even so, it runs (testexpr_35a). # UNFINISHED aspects of xxx_drag_behavior: # - its name # + implem posn_from_params [done now] # - the logic bug about self.motion -- ignoring for initial kluge test # + closest_pt_params_to_ray [coded now] # - how it fits into anything else -- not using DraggableObject is going to be best in the end, # but as initial kluge, just pass it in (wrapping DO as a delegator), and it might work. # Now [cvs rev 1.15 & 1.16, sometime before 070318] it is supposedly coded enough to work using initial kluge test, but it doesn't work, # but is making 2 highlightables and showing one and trying to drag the other (and failing). No idea why. [fixed now, see below] # evidence is "saved modelview_matrix is None, not using it" and the reprs in that debug print and in the cmenu. Hmm. #BUG # [note, an earlier version (not preserved except in earlier cvs revs of these same classes) # did partly work, which stored vectors and had no working constraint on the dragging.] # Now I fixed that bug by passing _delegate not delegate to drag_handler; see code comment. class xxx_drag_behavior(DragBehavior): # revised 070316; on 070318 removed comments that were copied into version _3 """a drag behavior which moves the original hitpoint along a line, storing only its 1d-position-offset along the line's direction [noting that the hitpoint is not necessarily equal to the moved object's origin] [#doc better] """ # args highlightable = Arg(DraggableObject) # kluge; revised 070316, delegate -> highlightable [works no worse than before [same bug as before]] # [but it's misnamed -- it has to be a DraggableObject since we modify its .motion] ###e rename, but what is it for? posn_parameter_ref = Arg(StateRef, doc = "where the variable height is stored") ###e rename constrain_to_line = Arg(Ray, Ray(ORIGIN, DY), doc = "the line/ray on which the height is interpreted as a position") ###e rename: constraint_line? line_to_constrain_to? constrain_to_this_line? # dflt_expr is just for testing #e remove it def current_event_mouseray(self): p0 = self.highlightable.current_event_mousepoint(depth = 0.0) # nearest depth ###k p1 = self.highlightable.current_event_mousepoint(depth = 1.0) # farthest depth ###k return Ray(p0, p1 - p0) #e passing just p1 should be ok too, but both forms can't work unless p0,p1 are typed objects... def on_press(self): self.startpoint = self.highlightable.current_event_mousepoint() # the touched point on the visible object (hitpoint) self.offset = self.startpoint - (ORIGIN + self.highlightable.motion) #k maybe ok for now, but check whether sensible in long run self.line = self.constrain_to_line + self.offset # the line the hitpoint is on (assuming self.motion already obeyed the constraint) def on_drag(self): # Note: we can assume this is a "real drag" (not one which is too short to count), due to how we are called. mouseray = self.current_event_mouseray() ## self._cmd_drag_from_to( oldpoint, point) # use Draggable interface cmd on self # ie self.delta_stateref.value = self.delta_stateref.value + (p2 - p1) ## def drag_mouseray_from_to(self, oldray, newray): # sort of like _cmd_from_to (sp?) in other eg code ## "[part of an interface XXX related to drag behaviors]" k = self.line.closest_pt_params_to_ray(mouseray) if k is not None: # store k self.posn_parameter_ref.value = k ####e by analogy with DraggableObject, should we perhaps save this side effect until the end? # compute new posn from k self.highlightable.motion = self.constrain_to_line.posn_from_params(k) #e review renaming, since we are asking it for a 3-tuple ####### LOGIC BUG: what causes self.motion to initially come from this formula, not from our own state? # maybe don't use DraggableObject at all? [or as initial kluge, just let initial motion and initial height both be 0] return def on_release(self): pass pass # end of class xxx_drag_behavior class _height_dragger(DelegatingInstanceOrExpr): # args #e coordsystem? for now let x/y be the way it spreads, z be the height height_ref = Arg(StateRef, doc = "stateref to a height variable") # appearance/behavior #e should draw some "walls" too, and maybe limit the height # note: the following sets up a cyclic inter-Instance ref ( drag_handler -> delegate -> drag_handler); # it works since the actual refs are symbolic (getattr_Expr(_self, 'attr'), not evalled except when used). drag_handler = Instance( xxx_drag_behavior( _self._delegate, height_ref, Ray(ORIGIN, DX) )) ### DX for initial test, then DZ # note: passing _self._delegate (not _self.delegate) fixed my "undiagnosed bug". delegate = DraggableObject( Image("blueflake.png"), ###e needs an option to be visible from both sides (default True, probably) ## constrain_delta = _self.constrain_delta, ###IMPLEM constrain_delta in DraggableObject ## delta_stateref = height_ref ###IMPLEM delta_stateref [done] (and rename it); and change this to make height_ref a number not vector; ##e and maybe include the constraint in that transform, since it seems implicit in it anyway. ####HOW in semantics? # ... = PropertyRef(DZ * height_ref.value, Set( height_ref.value, project_onto_unit_vector( _something, DZ )) # ... = TransformStateRef( height_ref, ... ) # funcs? or formula in terms of 1 or 2 vars? with a chance at solving it?? ##e _kluge_drag_handler = drag_handler ) ## def constrain_delta(self, delta): ## not yet - called ## return project_onto_unit_vector( delta, DZ) pass class test_StateArrayRefs_2(DelegatingInstanceOrExpr): # testexpr_35a indices = range(4) ## heights = StateArrayRefs(Width, ORIGIN) ###KLUGE for now: this contains heights * DZ as Vectors, not just heights heights = StateArrayRefs(Width, 0.0) def _height_dragger_for_index(self, index): stateref = StateArrayRefs_getitem_as_stateref( self.heights, index ) #e change to self.heights.getitem_as_stateref(index)? self.heights._staterefs[index]?? self.heights[index]??? newindex = ('_height_dragger_for_index', index) return self.Instance( _height_dragger( stateref), newindex ) delegate = SimpleRow( MapListToExpr( _self._height_dragger_for_index, ###k _self needed?? indices, KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr(SimpleColumn) ), #e SimpleGrid? 2d form of MapListToExpr? ActionButton( _self.printit, "button: print state") ###e idea: define on special attr, let UI assemble debug info viewer ) def printit(self): #e can PrintAction do this for us? print [h.value for i,h in sorted_items(self.heights)] ###KLUGE, assumes they're StateRefs -- maybe just rename StateArray -> StateArrayRefs pass # end
NanoCAD-master
cad/src/exprs/test_statearray_2.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Center.py - alignment primitives $Id$ might be renamed or merged note: transforms.py was split out of here, 061115 """ from exprs.transforms import Translate from exprs.Exprs import V_expr from exprs.attr_decl_macros import Arg from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.widget2d import Widget2D from exprs.__Symbols__ import _self # There are 15 non-noop combos of dx & dy formulae, but only 13 have simple names, due to X/Y ambiguity of Center... # even so, I spell them out like this, partly since the resulting classes are more efficient # than the easy implems of a general version which takes args for what to do with x & y independently. # Maybe the missing ones could be called CenterX and CenterY? (They do nothing to the not-named coordinate.) Done. # See testexpr_21e for a table of all of them. # BTW they need docstrings; here is an old one for Center: "Center(thing) draws as thing (a Widget2D [#e should make work for 3D too]), but is centered on the origin" class TopRight(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dx = - thing.bright dy = - thing.btop delegate = Translate(thing, V_expr(dx,dy,0)) class CenterRight(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dx = - thing.bright dy = (thing.bbottom - thing.btop)/2.0 delegate = Translate(thing, V_expr(dx,dy,0)) class BottomRight(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dx = - thing.bright dy = + thing.bbottom delegate = Translate(thing, V_expr(dx,dy,0)) class TopLeft(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dx = + thing.bleft dy = - thing.btop delegate = Translate(thing, V_expr(dx,dy,0)) class CenterLeft(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dx = + thing.bleft dy = (thing.bbottom - thing.btop)/2.0 delegate = Translate(thing, V_expr(dx,dy,0)) class BottomLeft(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dx = + thing.bleft dy = + thing.bbottom delegate = Translate(thing, V_expr(dx,dy,0)) class TopCenter(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dx = (thing.bleft - thing.bright)/2.0 dy = - thing.btop delegate = Translate(thing, V_expr(dx,dy,0)) class Center(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dx = (thing.bleft - thing.bright)/2.0 dy = (thing.bbottom - thing.btop)/2.0 delegate = Translate(thing, V_expr(dx,dy,0)) class BottomCenter(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dx = (thing.bleft - thing.bright)/2.0 dy = + thing.bbottom delegate = Translate(thing, V_expr(dx,dy,0)) class Left(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dx = + thing.bleft delegate = Translate(thing, V_expr(dx,0,0)) class Right(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dx = - thing.bright delegate = Translate(thing, V_expr(dx,0,0)) class Top(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dy = - thing.btop delegate = Translate(thing, V_expr(0,dy,0)) class Bottom(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dy = + thing.bbottom delegate = Translate(thing, V_expr(0,dy,0)) class CenterX(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dx = (thing.bleft - thing.bright)/2.0 delegate = Translate(thing, V_expr(dx,0,0)) class CenterY(DelegatingInstanceOrExpr): thing = Arg(Widget2D) dy = (thing.bbottom - thing.btop)/2.0 delegate = Translate(thing, V_expr(0,dy,0)) # == not yet working: a form with less duplicated code class AlignmentExpr(DelegatingInstanceOrExpr): # doesn't work yet, see below thing = Arg(Widget2D) dx = 0 # override in some subclasses dy = 0 delegate = Translate(thing, V_expr(dx,dy,0)) pass class TopRight_buggy(AlignmentExpr): # with AlignmentExpr -- doesn't work yet dx = - _self.thing.bright dy = - _self.thing.btop ###BUG [061211] -- for some reason these don't seem to be inherited into the formula for delegate. # guess: ExprsMeta stores it, then stores these new ones, but doesn't know it needs to "revisit" that one (for delegate) # and remake it for subclass with revised dx/dy. (Ideally it would remake it afresh for each subclass, I guess... how hard??) # conclusion: debug that, but for now, don't use the AlignmentExpr superclass, just spell out each subclass. # update, 080514: obvious in hindsight: when the delegate formula in AlignmentExpr is executed by Python, # dx is 0 so it might as well be defining delegate = Translate(thing, V_expr(0,0,0)). # So there is no fix without revising that definition or the defs of dx, dy. # pre-061211 version of Center, also worked fine: ##class Center(InstanceMacro): ## "Center(thing) draws as thing (a Widget2D [#e should make work for 3D too]), but is centered on the origin" ## # args ## thing = Arg(Widget2D) ## # internal formulas - decide how much to translate thing ## dx = (thing.bleft - thing.bright)/2.0 ## dy = (thing.bbottom - thing.btop)/2.0 ## # value ## ###k for now, use V_expr instead of V when it has expr args... not sure we can get around this (maybe redef of V will be ok??) ## _value = Translate(thing, V_expr(dx,dy,0)) # this translates both thing and its layout box ###k might not work with V(expr...) ## pass # end
NanoCAD-master
cad/src/exprs/Center.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ IorE_guest_mixin.py -- WILL BE RENAMED to fit class, when class is renamed @author: Bruce @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. 070815 split IorE_guest_mixin superclass out of InstanceOrExpr and moved it into this new file """ from exprs.lvals import call_but_discard_tracked_usage from exprs.widget_env import thisname_of_class, widget_env from utilities.debug import safe_repr from utilities.debug import print_compact_stack from exprs.Exprs import Expr from exprs.Exprs import is_pure_expr from exprs.Exprs import is_constant_for_instantiation from exprs.Exprs import is_Expr from exprs.Exprs import is_Expr_pyinstance from exprs.Exprs import lexenv_Expr from exprs.Exprs import tuple_Expr from exprs.Exprs import canon_expr from exprs.Exprs import EVAL_REFORM from exprs.ExprsMeta import ExprsMeta from exprs.StatePlace import StatePlace from exprs.py_utils import printnim from exprs.__Symbols__ import _E_REQUIRED_ARG_ kluge070119 = True # this is permanent for now, but don't clean up the associated code yet, since it'll soon be replaced # by a better centralized instantiator. [070120] # # history: # True used to cause infrecur in delegate in testexpr_10a, not yet diagnosed; caused wrong _self for .ww in _5x, # which as of 070120 944p is understood and fixed. The _10a bug is also fixed (by the same fix in the code -- # a more-correct _self assignment), but I don't know why there was infrecur before (and I guess I never will). #### Where i am 070120 1023p as I stop -- ... # I should still test more egs, and test non-EVAL_REFORM cases of all these egs to make sure that's ok too # (its code was also changed by these fixes). #### Then I should remove dprints and tons of comments and unused code cases from the # files modified today. Then fix the need for manual Instance in delegates. #### debug070120 = False # some debug prints, useful if bugs come up again in stuff related to the above class IorE_guest_mixin(Expr): #bruce 070815 split this out of its InstanceOrExpr subclass """ @note: This class will be renamed and probably further split. For most doc, see our InstanceOrExpr subclass. This is the part of InstanceOrExpr which supports sub-instance making (requiring self.env and self.ipath i think), and formula/Arg/Option/State eval in attr decl formulae in a subclass, and some standard stateplaces for use by State then; but not expr customization by __init__ or __call__, or _e_make_in, or drawing-specific things -- for those see InstanceOrExpr. """ __metaclass__ = ExprsMeta transient_state = StatePlace('transient') # state which matters during a drag; scroll-position state; etc def __init__(self, _e_glpane = None, _e_env = None, _e_ipath = None, _e_state = None ): """ [needs doc] Note: If we're born an Instance, then either _e_env or _e_glpane must be passed. (The keyword args are not meant to be passed from IorE itself, or its subclasses.) _e_glpane can be passed as a positional argument. We might rename these w/o _e_. """ self._e_init_e_serno() #k needed? if self._e_is_instance: # This only happens for classes which set this class constant to indicate # their pyinstances should be born as Instances from the start. # They need to pass either _e_env or (_e_glpane and optionally _e_state). if _e_env is None: # make a widget_env if _e_state is None: _e_state = {} assert _e_glpane _e_env = widget_env( _e_glpane, _e_state) if _e_ipath is None: _e_ipath = str(id(self)) #k?? self._init_self_as_Instance( _e_env, _e_ipath) else: assert _e_env is None and _e_ipath is None # other values not yet supported; i doubt these make sense before we have an Instance return # no __call__ in this class def _init_self_as_Instance(self, env, ipath): #bruce 070815 split this out of IorE._destructive_make_in """ (in principle, only needed if self should support formulae or subinstances) """ assert self._e_is_instance self.env = env #k ok, or does it need modification of some kind? #e in fact we mod it every time with _self, in _e_compute_method -- can we cache that? # [much later: now we do, in env_for_formulae] ####@@@@ self.ipath = ipath ###e does this need mixing into self.env somehow? ## print "assigned %r.ipath = %r" % (self,ipath) #061114 -- note, repr looks funny since fields it prints are not yet inited #e also set self.index?? ## print "fyi my metaclass is",self.__metaclass__ # <class 'exprs.ExprsMeta.ExprsMeta'> # set up state refs ## printnim("instance_helpers needs setup state refs") [not necessarily implemented, but don't spend runtime to print that] self._i_instance_decl_data = {} # private storage for self._i_instance method [renamed from _i_instance_exprs, 061204] self._i_instance_decl_env = {} # ditto, only for EVAL_REFORM kluge070119 # call subclass-specific instantiation code (it should make kids, perhaps lazily, if above didn't; anything else?? ###@@@) self._init_instance() self._debug_init_instance() return # from _init_self_as_Instance def _init_instance(self): #e let it be name-mangled, and call in mro order? """ called once per python instance, but only when it represents a semantic Instance ###doc -- explain better [some subclasses should extend this, starting their versions with super(TheirName, self)._init_instance()] """ def _debug_init_instance(self): if debug070120: #070120 debug code for _5x ER kluge070119 bug env = self.env print "%r.env has _self %r" % (self, getattr(env, '_self', '<none>')) assert self.env_for_formulae._self is self # remove when works -- inefficient (forces it to be made even if not needed) pass # might need to move the method custom_compute_method here, from our subclass IorE ###REVIEW # kid-instantiation support, to support use of the macros Arg, Option, Instance, etc #k (not sure this is not needed in some other classes too, but all known needs are here) def _i_env_ipath_for_formula_at_index( self, index, env = None): # split out of Expr._e_compute_method 070117; revised 070120 """ #doc; semi-private helper method for Expr._e_compute_method and (after EVAL_REFORM) self._i_instance """ ###e needs cleanup, once recent changes are tested and stable [070120] instance = self assert instance._e_is_instance if env is None: ## env0 = instance.env # fyi: AttributeError for a pure expr (ie a non-instance) env0 = instance.env_for_formulae # this change is related to bugfix [070120 935p (untested)] for bug in kluge070119 in testexpr_5x (wrong _self for ww), # but this is not the bugfix (since this case never happens when EVAL_REFORM), # but rather, compensates for not doing _self = instance below; the bugfix is to do it earlier when ER kluge070119. else: env0 = env # new feature for EVAL_REFORM for use by kluge070119 ## env = env0.with_literal_lexmods(_self = instance) ###e could be memoized in instance, except for cyclic ref issue # this is done in the wrong place (here), as explained elsewhere re bug in kluge070119 [070120 924p, see 844p comment] env = env0 assert env #061110 ipath0 = instance.ipath ipath = (index, ipath0) return env, ipath def Instance(self, expr, index = None, permit_expr_to_vary = False, skip_expr_compare = False): #070207 added permit_expr_to_vary """ toplevel interface (public for use in exprs) to self._i_instance; needs ##doc; similar to Instance macro for use in class assignments; except where that uses ipaths relative to _self, this uses them relative to self. @warning: Index arg is required for now, and matters a lot (unintended nonuniqueness is allowed but causes bugs). """ #070122; works, official for now; note relationship to Instance macro (also "def Instance") # allocating an index might be nice, but I don't see how we can do it yet # (the issue is when it changes due to history of prior allocs) # (wait, can we use the id of the child? not with this API since we have to pass it before making the child. # Isn't using a unique value here equiv to that? Yes, if it's unique forever even when we're remade at same ipath -- # meaning it's either allocated globally, or contains our _e_serno -- no, that might get reset, not sure. Ok, globally. nim.) if index is None: ## index = self._i_allocate_unique_kid_index(...) assert index is not None, "error: %r.Instance(%r) requires explicit index (automatic unique index is nim)" % (self, expr) return self._i_instance( expr, index, permit_expr_to_vary = permit_expr_to_vary, skip_expr_compare = skip_expr_compare) def _i_instance( self, expr, index, _lvalue_flag = False, permit_expr_to_vary = False, skip_expr_compare = False ): # see also def Instance (the method, just above, not the macro) """ [semi-private; used by macros like Instance, Arg, Option] Find or create (or perhaps recompute if invalid, but only the latest version is memoized) (and return) an Instance of expr, contained in self, at the given relative index, and in the same env [#e generalize env later?]. Error (perhaps not detected) if called with same index and different other args; when a cached instance is returned, the other args are not used except perhaps to check for this error. (When an instance is recomputed, if this error happens, are new args used? undefined.) (#e Should we change this to make the expr effectively part of the index, for caching? Probably not; not sure.) (#e Should we change this to make it legal to pass a new expr? Probably not... hard for subsequent callers to be consistent...) WARNING: this docstring is probably out of date regarding whether expr can change and what happens if it does. [070301 comment] """ # Note: Before EVAL_REFORM, this is used to do all evals, including instantiations (treated as how IorE evals). # It also does "eval to lval" when _lvalue_flag is true (passed only from LvalueArg, so far used only in Set). # After EVAL_REFORM, instantiation can't be done by eval (evals of IorE exprs return them unchanged); # evals are done before this is called, then this either returns constants (numbers, Instances) unchanged, # or instantiates exprs. It can no longer be called with _lvalue_flag when EVAL_REFORM (as of late 070119). def __debug_frame_repr__(locals): """ return a string for inclusion in some calls of print_compact_stack """ return "_i_instance(index = %r, expr = %r), self = %r" % (index,expr,self) assert self._e_is_instance if not EVAL_REFORM: # this is redundant with a later assert in _i_instance_CVdict in all cases (EVAL_REFORM or not), # and it causes trouble in the EVAL_REFORM case. To be conservative I'll only disable it in that case # (so I'll leave it untouched in this case). 070117 assert is_pure_expr(expr), "who passed non-pure-expr %r to _i_instance? index %r, self %r, _e_args %r" % \ (expr, index, self, self._e_args) #k guess 061105 else: if _lvalue_flag: print "SHOULD NEVER HAPPEN: saw _lvalue_flag: _i_instance(index = %r, expr = %r), self = %r" % (index,expr,self) # new behavior 070118; might be needed to fix "bug: expr or lvalflag for instance changed" in testexpr_9fx4 click, # or might just be hiding an underlying bug which will show up for pure exprs in If clauses -- not yet sure. #####k # (Note that its only effects are an optim and to remove some error messages -- what's unknown is whether the detected # "errors" were real errors or not, in this case. # Guess: we'll still have a ###BUG when exprs are involved, which to fix # will require noticing local ipath modifiers (lexenv_ipath_Expr's ipath) not only in _e_make_in but in the upcoming # determination of index; the best fix will be to dispense with the local cache of exprs per-index in favor of a global one # indexed by ipath, after those local ipath mods are included -- the same one needed for the "find" in the find or make # of instantiation (this find presently being nim, as mentioned somewhere else in this file in the last day or two), # meaning that it takes into account everything needed to create the ipath to find or make at (local mods, # state-sharing transforms, maybe more).) if is_constant_for_instantiation(expr): #revised 070131 self._debug_i_instance_retval(expr) #070212 return expr # [#k review whether this comment is still needed/correct; 061204 semiobs due to newdata change below; even more obs other ways] # hmm, calling Instance macro evals the expr first... can't it turn out that it changes over time? # I think yes... not only that, a lot of change in it should be buried inside the instance! (if it's in an arg formula) # as if we need to "instantiate the expr" before actually passing it... hmm, if so this is a SERIOUS LOGIC BUG. ####@@@@ # WAIT -- can it be that the expr never changes? only its value does? and that we should pass the unevaluated expr? YES. # But i forgot, eval of an expr is that expr! I get confused since _e_eval evals an implicit instance -- rename it soon! ###@@@ # [addendum 061212: see also the comments in the new overriding method If_expr._e_eval.] # 070119 Q: what if, right here, we burrowed into expr, and used a cvdict on a central object? as a kluge? # just since fast to code vs a central instantiator obj? # or at *least* we could do it locally -- no sharing but should fix bugs? if EVAL_REFORM and kluge070119: assert not _lvalue_flag # don't know how otherwise ## env = self.env # like in _i_env_ipath_for_formula_at_index [like in the old wrong version, that is] env = self.env_for_formulae # like in _i_env_ipath_for_formula_at_index [like in the new corrected version, 070120 940p] expr, env, ipath = expr, env, index oldstuff = expr, env, ipath expr, env, ipath = expr._e_burrow_for_find_or_make(env, ipath) if debug070120 and (expr, env, ipath) != oldstuff: print "fyi EVAL_REFORM kluge070119: worked, %r => %r" % (oldstuff, (expr, env, ipath)) index = ipath del ipath self._i_instance_decl_env[index] = env del env pass newdata = (expr, _lvalue_flag) # revised 061204, was just expr, also renamed; cmt above is semiobs due to this olddata = self._i_instance_decl_data.get(index, None) # see above comment if skip_expr_compare: #070411 new optim option (public) ###UNTESTED; might or might not use in confirmation corner ###e should use in Arg, Option -- might be a big speedup -- but is it safe?? maybe only with IorE If, not eval If!! ###k expr_is_new = (olddata is None) else: expr_is_new = (olddata != newdata) if expr_is_new: if olddata is not None: if permit_expr_to_vary: # new feature 070207 ### how do we remove the old instance so it gets remade? ## del self._i_instance_CVdict[index] ##k guess at how -- but del might be nim in this object -- # good thing it was, since inval_at_key [new feature] is what we need -- del would fail to propogate invals # to prior usage trackers of this now-obsolete instance! ###BUG: changes to the info used to compute expr, by whatever decides to call this method (_i_instance), # are usage tracked into that caller, not into our lval in our lvaldict. We depend on the caller # someday getting recomputed before it will realize it wants to pass us a new expr and cause this inval. # (Example of this use: a kid-column delegate in MT_try2.) # THIS LATE PROPOGATION OF INVAL MIGHT LEAD TO BUGS -- not reviewed in detail. # Much better would be for the callers "usage tracked so far" to somehow get subscribed to (for invals) # by the thing we manually inval here. The potential bugs in the current scheme include: # - inval during recompute can make more pieces of it need recompute than did when it started # - if the caller's recompute never happens, the invals that need to propogate never occur at all, # though they need to. # I am not sure if this can cause bugs in MT_try2 -- maybe not -- but surely it can in general! ###FIX SOMEHOW (maybe as suggested above, by stealing or copying usage tracking info from caller -- # but it's not enough, we'd need our lval's recompute to get the caller to re-decide to call us # so we'd know the new expr to recompute with! So, details of any fix are unclear.) self._i_instance_CVdict.inval_at_key(index) # print "fyi: made use of permit_expr_to_vary for index = %r, expr = %r" % (index, expr) # remove when works else: print "bug: expr or lvalflag for instance changed: self = %r, index = %r, new data = %r, old data = %r" % \ (self,index,newdata,olddata) #e more info? i think this is an error and should not happen normally # update 070122: it usually indicates an error, but it's a false alarm in the latest bugfixed testexpr_21g, # since pure-expr equality should be based on formal structure, not pyobj identity. ###e ####e need to print a diff of the exprs, so we see what the problem is... [070321 comment; happens with ArgList] #e if it does happen, should we inval that instance? yes, if this ever happens without error. # [addendum 061212: see also the comments in the new overriding method If_expr._e_eval.] # [one way to do that: have _i_instance_decl_data contain changetracked state vars, changed above, # usage-tracked by _CV__i_instance_CVdict. But the env matters too, so we might want to compare it too, # or compare the expr before burrowing into it, and do the # burrowing later then?? But we can't, due to the index... ###e 070122] self._i_instance_decl_data[index] = newdata else: # they're equal (or we were told not to bother comparing them, in which case, use the old one) if 0 and (not skip_expr_compare) and olddata[0] is not expr: # this print worked, but it's not usually useful (not enough is printed) so I disabled it # they're only equal because __eq__ is working on non-identical exprs [implemented in Expr late 070122] print "fyi: non-identical exprs compared equal (did we get it right?): %r and %r" % (olddata[0], expr) ### remove sometime pass res = self._i_instance_CVdict[index] # takes care of invals in making process? or are they impossible? ##k [see above] self._debug_i_instance_retval( res) #070212 return res def _debug_i_instance_retval(self, res): #070212 """ [private] res is about to be returned from self._i_instance; perform debug checks [#e someday maybe do other things] """ ## NumericArrayType = type(ORIGIN) ## if isinstance(res, NumericArrayType): ## return res # has no __class__, but legitimate try: ## assert res.__class__.__name__ != 'lexenv_ipath_Expr', "should not be returned from _i_instance: %r" % (res,) assert not is_pure_expr(res), "pure exprs should not be returned from _i_instance: %r" % (res,) except: print "bug: exception in _debug_i_instance_retval for this res (reraising): %s" % safe_repr(res) raise return def _CV__i_instance_CVdict(self, index): """ [private] value-recomputing function for self._i_instance_CVdict. Before calling this, the caller must store an expr for this instance into self._i_instance_decl_data[index] (an ordinary dict). If it's permitted for that expr to change with time (which I doubt, but don't know yet for sure #k), then whenever the caller changes it (other than when initially setting it), the caller must invalidate the entry with the same key (our index arg) in the LvalDict2 that implements self._i_instance_CVdict (but the API for the caller to do that is not yet worked out #e). (Implem note: _CV_ stands for "compute value" to ExprsMeta, which implements the LvalDict2 associated with this. This method needs no corresponding _CK_ keylist function, since any key (instance index) asked for is assumed valid.) """ assert self._e_is_instance # This method needs to create a new instance, by instantiating expr and giving it index. # Implem notes: # - the glue code added by _CV_ from self._i_instance_CVdict to this method (by ExprsMeta) uses LvalDict2 # to cache values computed by this method, and recompute them if needed (which may never happen, I'm not sure). # - the access to self._i_instance_decl_data[index] is not usage tracked; # thus if we change it above w/o error, an inval is needed. data = self._i_instance_decl_data[index] expr, lvalflag = data # 061204 ## print "fyi, using kid expr %r" % expr # (these tend to be longish, and start with eval_Expr -- what we'd rather print is the result of the first eval it does) # Note, this expr can be very simplifiable, if it came from an Arg macro, # but present code [061105] reevals the full macro expansion each time -- suboptimal. # To fix, we'd need an "expr simplify", whether we used it only once or not... # the reason to use it more than once is if it becomes partly final at some later point than when it starts out. # The simplify implem would need decls about finality of, e.g., getting of some bound methods and (determinism of) # their retvals -- namely (for Arg macro etc) for _i_instance and _i_grabarg and maybe more. # Feasible but not simple; worthwhile optim someday but not right away. ##e if not EVAL_REFORM: # three increasingly strict asserts: assert expr is not None assert is_Expr(expr), "not is_Expr: %r" % (expr,) assert is_pure_expr(expr) ###k?? what if someone passes an instance -- is that permitted, but a noop for instantiation?? assert is_Expr_pyinstance(expr), "can't instantiate a class: %r" % (expr,) # new, 070117, untested### -- i'm not even sure it's correct # also assume expr is "canonicalized" and even "understood" -- not sure if this is justified printnim("don't we need understand_expr somewhere in here? (before kidmaking in IorE)") ###@@@ else: # EVAL_REFORM case 070117 if not (is_pure_expr(expr) and is_Expr_pyinstance(expr)): print "this should never happen as of 070118 since we handle it above: non pure expr %r in _CV__i_instance_CVdict" % (expr,) ## print "FYI: EVAL_REFORM: _CV__i_instance_CVdict is identity on %r" % (expr,) # this is routine on e.g. None, small ints, colors, other tuples... and presumably Instances (not tested) assert not lvalflag # see comments at start of _i_instance return expr pass ####e: [061105] is _e_eval actually needing to be different from _e_make_in?? yes, _e_eval needs to be told _self # and the other needs to make one... no wait, wrong, different selves -- # the _self told to eval is the one _make_in *should make something inside of*! (ie should make a kid of) # So it may be that these are actually the same thing. (See paper notes from today for more about this.) # For now, tho, we'll define _e_make_in on OpExpr to use eval. [not done, where i am] # actually this is even faster -- review sometime (note, in constant_Expr they're both there & equiv #k): ###@@@ ## this is just the kid expr: print "_CV__i_instance_CVdict needs to make expr %r" % (expr,) ## if hasattr(expr, '_e_make_in'): ## print("REJECTED using _e_make_in case, on a pyinstance of class %s" % expr.__class__.__name__)###was printfyi til 061208 921p ## ## res = expr._e_make_in(env, index_path) ## #k we might have to fix bugs caused by not using this case, by defining (or modifying?) defs of _e_eval on some classes; ## # addendum 061212, we now do that on If_expr. if not EVAL_REFORM: # WARNING: following code is very similar to _i_eval_dfltval_expr as of 061203 # printfyi("used _e_eval case (via _e_compute_method)") # this case is usually used, as of 061108 -- now always, 061110 # note: this (used-to-be-redundantly) grabs env from self try: res = expr._e_compute_method(self, index, _lvalue_flag = lvalflag)() ##e optim someday: inline this # 061105 bug3, if bug2 was in held_dflt_expr and bug1 was 'dflt 10' except: # we expect caller to exit now, so we might as well print this first: [061114] print "following exception concerns self = %r, index = %r in _CV__i_instance_CVdict calling _e_compute_method" % \ (self, index) raise else: # EVAL_REFORM case, 070117 if kluge070119: # also pass an env retrieved from... env = self._i_instance_decl_env[index] env, ipath = self._i_env_ipath_for_formula_at_index( index, env) # note: retval's env is modified from the one passed # THIS MUST BE WHERE THE INCORRECT BINDING _self = self gets added, in the kluge070119 ###BUG in _5x! [070120 844p] # GUESS at basic bug: an Instance self really needs to know two envs: the one for its args (_self refers to # whoeever lexically created the expr they were made from), and the one for their internal formulae (_self = self). # self.env is the one for the args (since it's thought of as "self's (outer) environment"), # and the one for internal formulae has (until now -- this should change #e) been recreated as needed in # _e_compute_method and now in _i_env_ipath_for_formula_at_index, by extending self.env by _self = self. # But to be correct, this should be done BEFORE the burrowing and env-extension done by the kluge070119, # but in this wrong current code it's done after it. The old code also had wrongness of order, in principle # (doing this _self addition here rather than in env_for_args, with env_for_args done first when it should # be done 2nd), but it didn't matter since env_for_args only added _this_xxx and _my. WAIT, THAT'S WRONG -- # env_for_args is for external (in lexenv) args, so it should have SAME _self as self.env, so it's correct now, # and never gets or needs _self = self, either before or after its _my and _this_xxx bindings. # What we need here is NOT env_for_args but env_for_internal_formulae. It should be used for dflt exprs in Arg, # and for all exprs sitting on class assignments. We've been making it before *using* those formulae # (probably getting it onto dflt exprs only because they end up being *used* in the right place for that). # We've been making it in each call of _i_env_ipath_for_formula_at_index or _e_compute_method, but we ought to # make it once and let those use it, and make sure that happens before the env mods from the burrowing done by # kluge070119. (We can't make it in the class (eg ExprsMeta) -- we have to wait until _init_instance or so, # because it depends on self which is only known around then.) # # SUGGESTED FIX ###e: make self.env_for_internal_formulae (#e shorter name -- env_for_formulae?) # before (??) calling _init_instance [or after if _init_instance can modify self.env ##k]; # use it in _i_env_ipath_for_formula_at_index and some of our uses of _e_compute_method; # and review all uses of self.env for whether they ought to be env_for_formulae. # Doing it 070120 circa 942p -- I made _C_env_for_formulae instead of setting it in _init_instance # (optim, since some Instances never need it (I hope -- not sure) and since it creates a cyclic ref. else: env, ipath = self._i_env_ipath_for_formula_at_index( index) # equivalent to how above other case computes them assert not lvalflag # see comments at start of _i_instance res = expr._e_make_in(env,ipath) # only pure IorE exprs have this method; should be ok since only they are returned from expr evals return res # from _CV__i_instance_CVdict def _i_eval_dfltval_expr(self, expr, index): ##e maybe unify with above, but unclear when we soon split eval from instantiate """ evaluate a dfltval expr as used in State macro of 061203; using similar code as _CV__i_instance_CVdict for Instance... """ # WARNING: similar code to end of _CV__i_instance_CVdict # note: this (used-to-be-redundantly) grabs env from self # Note about EVAL_REFORM: I think this needs no change, since these exprs can now be evalled to pure exprs, # then if desired passed through instantiation. try: computer = expr._e_compute_method(self, index) ##e optim someday: inline this # 061105 bug3, if bug2 was in held_dflt_expr and bug1 was 'dflt 10' res = call_but_discard_tracked_usage( computer) # see also docstring of eval_and_discard_tracked_usage # res is the same as if we did res = computer(), but that would track usage into caller which it doesn't want invals from except: print "following exception concerns self = %r, index = %r in *** _i_eval_dfltval_expr *** calling _e_compute_method" % \ (self, index) raise return res def _i_grabarg( self, attr, argpos, dflt_expr, _arglist = False): """ #doc, especially the special values for some of these args """ debug = False ## _arglist if debug: print_compact_stack( "_i_grabarg called with ( self %r, attr %r, argpos %r, dflt_expr %r, _arglist %r): " % \ (self, attr, argpos, dflt_expr, _arglist) ) print " and the data it grabs from is _e_kws = %r, _e_args = %r" % (self._e_kws, self._e_args) #k below should not _e_eval or canon_expr without review -- should return an arg expr or dflt expr, not its value # (tho for now it also can return None on error -- probably causing bugs in callers) assert is_pure_expr(dflt_expr), "_i_grabarg dflt_expr should be an expr, not %r" % (dflt_expr,) #061105 - or use canon_expr? assert self._e_is_instance if not self._e_has_args: print "warning: possible bug: not self._e_has_args in _i_grabarg%r in %r" % ((attr, argpos), self) assert attr is None or isinstance(attr, str) assert argpos is None or (isinstance(argpos, int) and argpos >= 0) assert _arglist in (False, True) external_flag, res0 = self._i_grabarg_0(attr, argpos, dflt_expr, _arglist = _arglist) if external_flag: # flag and this condition added 061116 443p to try to fix '_self dflt_expr bug'; seems to work in testexpr_9a; # I'm guessing type_expr doesn't have a similar bug since it's applied outside this call. #k index = attr or argpos #k I guess, for now [070105 stub -- not always equal to index in ipath, esp for ArgOrOption] env_for_arg = self.env_for_arg(index) # revised 070105 if debug070120: print "grabarg %r in %r is wrapping %r with %r containing _self %r" % \ ((attr, argpos), self, res0, env_for_arg, getattr(env_for_arg,'_self','<none>')) res = lexenv_Expr(env_for_arg, res0) ##k lexenv_Expr is guess, 061110 late, seems confirmed; env_for_args 061114 #e possible good optim: use self.env instead, unless res0 contains a use of _this; # or we could get a similar effect (slower when this runs, but better when the arg instance is used) by simplifying res, # so that only the used parts of the env provided by lexenv_Expr remained (better due to other effects of simplify) else: res = res0 #k (I *think* it's right to not even add self.env here, tho I recall I had lexenv_Expr(self.env, res0) at first -- # because the self.env was for changing _self, which we want to avoid here, and the _for_args is for supporting _this.) # Note: there was a '_self dflt_expr bug' in the above, until i added 'if external_flag:'] [diagnosed & fixed 061116]: # it's wrong for the parts of this expr res0 that came from our class, i.e. dflt_expr and type_expr. # That is hard to fix here, since they're mixed into other parts of the same expr, # but nontrivial to fix where we supply them, since when we do, the specific env needed is not known -- # we'd have to save it up or push it here, then access it there (or just say "escape from the most local lexenv_Expr" # if that's well-defined & possible & safe -- maybe the most local one of a certain type is better). # We also want whatever we do to be robust, and to not make it too hard to someday simplify the expr. # So why not fix it by wrapping only the parts that actually come from _e_args and _e_kws, right when we access them? # I guess that is done inside _i_grabarg_0... ok, it's easy to add external_flag to its retval to tell us what to do. [done] ###k ARE THERE any other accesses of _e_args or _e_kws that need similar protection? Worry about this if I add # support for iterating specific args (tho that might just end up calling _i_grabarg and being fine). if debug: print "_i_grabarg returns %r" % (res,) return res def env_for_arg(self, index): # 070105 experiment -- for now, it only exists so we can override it in certain primitive subclasses """ Return the env to use for the arg (or kid?) at the given index (attr or argpos, I guess, for now #k). By default this is just self.env_for_args. Certain subclasses [intended to be dynenv-modifying primitives, not user macros] can override this (for specific indices) to supply other envs based on self.env_for_args or self.env, using .with_lexmods(dict) to alter one of those envs. They should use self.env_for_args if they want to lexically bind _this(theirname) and _my, not otherwise. For OpExpr-like primitives it might be best to use self.env. Note that overriding this method in a user-level macro (e.g. one based on DelegatingInstanceOrExpr) may not work as expected, since this is only used to alter the env for exprs that come from outside as actual args, not those that are defined internally by formulae (not even the default value formula for an arg). """ return self.env_for_args def _C_env_for_args(self):###NAMECONFLICT? i.e. an attr whose name doesn't start with _ (let alone __ _i_ or _e_) in some exprs """ #doc """ lexmods = {} # lexmods for the args, relative to our env thisname = thisname_of_class(self.__class__) ##e someday make it safe for duplicate-named classes # (Direct use of Symbol('_this_Xxx') will work now, but is pretty useless since those symbols need to be created/imported. # The preferred way to do the same is _this(class), which for now [061114] evals to the same thing that symbol would, # namely, to what we store here in lexmods for thisname. See "class _this".) lexmods[thisname] = self # WARNING: this creates a cyclic ref, from each child whose env contains lexmods, to self, to each child self still knows. # In fact, it also creates a cyclic ref from self to self, since the result (which contains lexmods) is memoized in self. lexmods['_my'] = self #061205 return self.env.with_lexmods(lexmods) def _C_env_for_formulae(self):#070120 for fixing bug in kluge070119 """ compute method for self.env_for_formulae -- memoized environment for use by our internal formulae (class-assigned exprs) """ res = self.env.with_literal_lexmods( _self = self) # This used to be done (each time needed) in _e_compute_method and _i_env_ipath_for_formula_at_index -- # doing it there was wrong since it sometimes did it after env mods by kluge070119 that needed to be done after it # (in order to mask its effect). # WARNING: doing it here creates a cyclic ref from self to self, since the result is memoized in self. return res def _i_grabarg_0( self, attr, argpos, dflt_expr, _arglist = False): """ [private helper for _i_grabarg] return the pair (external-flag, expr to use for this arg) """ # i think dflt_expr can be _E_REQUIRED_ARG_, or any (other) expr if dflt_expr is _E_REQUIRED_ARG_: required = True else: required = False if isinstance(dflt_expr, _E_REQUIRED_ARG_.__class__) and dflt_expr._e_name.startswith("_E_"): print "possible bug: dflt_expr for arg %r in %r is a Symbol %r named _E_* (suspicious internal symbol??)" % \ ( (attr, argpos), self, dflt_expr ) # kluge sanity check for _E_ATTR or other internal symbols [revised 070131] if attr is not None and argpos is not None: printnim("should assert that no expr gets same arg twice (positionally and as named option)")###e if attr is not None: # try to find it in _e_kws; I suppose the cond is an optim or for clarity, since None won't be a key of _e_kws try: return True, self._e_kws[attr] except KeyError: pass if argpos is not None: try: res = self._e_args[argpos] except IndexError: # "tuple index out of range" pass else: # res was the arg provided at argpos if _arglist: res = tuple_Expr(* self._e_args[argpos:]) return True, res # no arg was provided at argpos if _arglist: # [_arglist supports ArgList, a new feature 070321] # no args were provided for an ArgList -- use dflt_expr, or tuple_Expr(). # (Note: we don't use list_Expr. See comments near def of ArgList.) if required: return False, tuple_Expr() #k probably equiv to canon_expr(()) ##k optim-related Q: what should external_flag be in this case? [070321 Q] else: return False, dflt_expr # note: nothing fundamental requires that dflt_expr evals/instantiates to a list or tuple, # though it would usually be an error if it doesn't (depending on how the class body formulae were written). # It's not an error per se, just likely to be one given how ArgList is conventionally used. else: # ordinary arg was not provided -- error or use dflt_expr if required: print "error: required arg %r or %r not provided to %r. [#e Instance-maker should have complained!] Using None." % \ (attr, argpos, self) # Note: older code returned literally None, not an expr, which caused a bug in caller which tried to _e_eval the result. # Once we've printed the above, we might as well be easier to debug and not cause that bug right now, # so we'll return a legal expr -- in some few cases this will not cause an error, making this effectively a warning, # "missing args are interpreted as None". Review this later. [061118] printnim("a better error retval might be a visible error indicator, if the type happens to be a widget")###e #e I think we don't know the type here -- but we can return a general error-meaning-thing (incl error msg text) # and let the type-coercers do with it what they will. Or we could return something equivalent to an exception # (in our interpreted language) and revise our eval semantics to handle that kind of thing. [061118] return False, canon_expr(None) ##k optim-related Q: what should external_flag be in this case? [070321 Q] else: return False, dflt_expr pass # above should not _e_eval or canon_expr without review -- should return an arg or dflt expr, not its value def _StateRef__attr_ref(self, attr): #bruce 070815 experimental """ Return a stateref for our attr of the given name, or None if we can't do that. (#e option for error if we can't?) Part of an API for objects which can return StateRefs for some of their attrs. See StateRef_API for more info. """ descriptor = getattr( self.__class__, attr, None) # for devel, assume it should work, fail if not. ###FIX or REDOC # print "got descriptor: %r" % (descriptor,) assert descriptor is not None ## assert isinstance( descriptor, ClassAttrSpecific_DataDescriptor ) ###k??? in fact assume it is a subclass which can do following: ## return None if following method is not there return descriptor._StateRef__your_attr_in_obj_ref( self) pass # end of class IorE_guest_mixin # end
NanoCAD-master
cad/src/exprs/IorE_guest_mixin.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ exprs.Arrow.py @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: 2008-03-02: Created """ from exprs.widget2d import Widget2D from exprs.attr_decl_macros import ArgOrOption from exprs.attr_decl_macros import Option from exprs.ExprsConstants import Color, Position, ORIGIN, DX from utilities.constants import gray from exprs.__Symbols__ import Anything from graphics.drawing.CS_draw_primitives import drawDirectionArrow class Arrow(Widget2D): """ Arrow class provides a 3D arrow with a 'tail' and an arrow head. @see: B{DnaSegment_ResizeHandle} where this is used to draw a resize handle while editing a DnaSegment. @see: exprs.Rect.py which defines some other 3 D objects. @see: DirectionArrow.py -- Don't confuse it with this class. """ color = ArgOrOption(Color, gray) tailPoint = ArgOrOption(Position, ORIGIN) arrowBasePoint = ArgOrOption(Position, ORIGIN + 2*DX) scale = ArgOrOption(float, 10.0) tailRadius = ArgOrOption(float, 0.4) #tailRadiusLimits ensure a min and max size for the arrow (including arrow #tail and arrow head. drawDirectionArrow method uses tailRadius as a reference #to derive other params such as arrowhead base radius etc. Thats why this arg #is named this way. #@See DnaSegment_ResizeHandle to see how these limits are defined. tailRadiusLimits = ArgOrOption(tuple, ()) glpane = ArgOrOption(Anything, None) scale_to_glpane = Option(bool, False) def draw(self): drawDirectionArrow( self.color, self.tailPoint, self.arrowBasePoint, self.tailRadius, self.scale, tailRadiusLimits = self.tailRadiusLimits, numberOfSides = 6, glpane = self.glpane, scale_to_glpane = self.scale_to_glpane )
NanoCAD-master
cad/src/exprs/Arrow.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ testdraw.py -- drawing code for testmode, which tests the exprs package. [for doc, see testmode.py] @author: Bruce @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. BUGS: - 081204: testmode messes up ruler text and clipboard part text: mouse motion over a highlightable alternately turns highlighting and text colors on and off; with highlight on, text fg is white and bg clear (wrong but readable); with highlight off (a bug in itself), text fg and bg are both the same as whatever i set for text fg bfr renderText; there are two redraws per mouse motion (normal for motion over a *non*-highlighted object) when rulers are on; rulers *or* clipboard text also messes up some of the highlightable behavior in testmode, making it alternate (as described above). guesses as to the cause: - could it be related to calling qglClearColor with the text color, in the text rendering code? - could renderText mess up something else related to highlighting, like stencil buffer? mostly it's a mystery. ### WARNING: most of the rest of this docstring is obs: known bugs: + slowness of redraw, and redraw happens whenever i go on or off a highlighted thing, or on or move around on something else. this is much worse on my iMacG4 than my iMac G5, but not because of redraw speed, but because on the G4, the mouse cursor stops following the mouse during the redraw!!! Possible fixes: different hit test alg, C-coded redraw or hit test, use of display list or saved color/depth buffer for nonhighlighted stuff. ... i put in a display list, which fixed it, but it's not invalled enough. (it also needs inval by trackball, unlike a chunk's.) - highlight orange is slightly wider on right than nonhighlight pink (guess: glpane translates in model space, not just depth space) - see the exception from the selobj alive test, which happens on clicks (left or cmenu) and on highlight not covering selobj, described below (in class Highlightable) [fixed now?] - DraggedOn and ReleasedOn are nim (and need renaming) [no longer true, as of very long before 061120] - region selection - works to select atoms in a rect, but the rect for it is not being drawn [even w/o displist optim] - is it a failure to delegate some method to superclass, maybe emptySpaceLeftDown? - is it related to the reload that happens on that leftDown? (not sure why it would be) solved: it was failure to call super.Draw! Tested, but fix reverted, since i wanted to test the old way again. ###@@@ - singlet-drag to bond - also works but lacks rubberband line [even w/o displist optim] [might be fixed now??] - draw_later doesn't make thing highlightable even when i don't touch color enablement and do it not much later, so how can I test the real thing? [relates to Invisible] [would it work better as Transparent? Probably not yet...] [###@@@ maybe fixed now] - TextRect: - size is wrong - origin is wrong [probably fixed] + if too few lines, testchars at top rather than blanklines at bottom [fixed] - sometimes fuzzy (should fix several of these by using pixmap/displist text, or the bitmap text in pyrex_atoms) - fails to notice hits, in Button... no idea why. interesting Q - does it draw into depth buffer at all? yes it does; also, if i slide off black rect onto text, it works fine, only if i slide onto text does it fail. AHA, i bet it does something funny with size/pos, which messes up rendering by draw_in_abs_coords. == todo: - try a display list optim in main draw function, for keeping non-highlighted stuff in one; might work almost as well as a color/depth buffer, for this code; but this requires knowing when it changed. One advantage: works across rotations (as long as we keep any billboarded stuff out of it). Note: some text rendering here shrinks when it gets nonparallel, but that's a bug, not a form of billboarding. - more & better-organized widget exprs. - widget exprs that map from external state (such as that in Nodes), and let us edit it. - i'm suspecting that one widget expr should often be used to draw all the things that use the same formulas it was set up with, so it would never carry per-object state -- it would be more like code. (But right now, Highlightable does carry some.) - for this to work, but fit with simple compounds like Row, the widget-subexprs need to get their own sub-state; this (as func of main state) could either be a code-id from their instance, or a posn from their caller, and done at compile time (their __init__ time) or draw time -- but it needs to work when they get reloaded/remade, suggesting that (for these simple compound -- not for iteratives used to describe rules) it's mainly positional, or "positional but sorted by type" so that a few kinds of code-changes don't destroy data. (But with optional explicit ids per instance, so that old data *can* be destroyed if you want, or preserved more readily. The auto ids are really only needed for transient things like glnames and saved modelview matrices, which any highlightable needs, and maybe for saved display lists, inval data, etc; so maybe it doesn't matter if those change on reload. And for anything referring to user-editable data, you need explicit ids anyway so you can recode and not obsolete your data.) - likely state implem (if we ignore letting it be "externally storable"): linked dicts; any convenient pyobj-constant keys, or maybe string keys. Possible convention (not thought through): the ids usable as attrs are the ones whose chars work in a py identifier. - more todos findable by searching for "todo", "Drawable", and (older ones) "next up", "wishlist", and (implicit ones) "kluge". """ __author__ = "bruce" import time from OpenGL.GL import glPushMatrix from OpenGL.GL import glPopMatrix from OpenGL.GL import glTranslate import foundation.env as env from utilities import debug_flags from utilities.debug import print_compact_traceback from utilities.constants import ave_colors from utilities.constants import blue from utilities.constants import white from utilities.constants import green from utilities.constants import red from exprs.reload import exprs_globals #bruce 071102 renamed vv -> exprs_globals and moved it out of this file, # to avoid import cycle exprs_globals.reload_counter += 1 # the first time we load testdraw, this changes that counter # from -1 to 0; when we reload it, it changes it to 1, 2, etc; # thus the counter counts the number of reloads of testdraw. ### a lot of the following constants are probably obs here, redundant with ones now defined in exprs module [070408 comment] printdraw = False # debug flag from graphics.drawing.texture_fonts import ensure_courierfile_loaded ##lightblue = ave_colors( 0.2, blue, white) halfblue = ave_colors( 0.5, blue, white) ##purple = ave_colors(0.5, red, blue) def translucent_color(color, opacity = 0.5): #e refile with ave_colors """Make color (a 3- or 4-tuple of floats) have the given opacity (default 0.5, might be revised); if it was already translucent, this multiplies the opacity it had. """ if len(color) == 3: c1, c2, c3 = color c4 = 1.0 else: c1, c2, c3, c4 = color return (c1, c2, c3, c4 * opacity) trans_blue = translucent_color(halfblue) trans_red = translucent_color(red) trans_green = translucent_color(green) # == # note: class avoidHighlightSlowness was defined here in rev. 1.6, but didn't work and probably can't work, so I zapped it. # Its goal was to avoid the redraws on every mouseover motion of drawing that doesn't use glname to make itself highlightable. # Instead, just get all drawing to be inside a highlightable object. (It's ok if the highlighting is not visible. # It just needs to get into the stencil and depth buffers like the plain object, so we don't worry whether we're over other objects # during the mouseover.) # == if debug_flags.atom_debug: print "\ntestdraw: %d reloads" % exprs_globals.reload_counter def end_of_Enter(glpane): # called by testmode.Enter after it does everything else including super Enter; was never called before 070103 ## glpane.win.setViewHome() # not tested, might be wrong; redundant now (if home view is the default) init_glpane_vars(glpane) # print "did end_of_Enter on",glpane # works def init_glpane_vars(glpane): # print "init_glpane_vars on glpane %r" % glpane # called by Draw and by end_of_Enter (as of 070103) glpane._glnames = [] glpane._testmode_stuff = [] glpane._testmode_stuff_2 = [] glpane._testmode_stuff_3 = [] glpane._alpha = 1.0 def leftDown(mode, event, glpane, superclass): # called from testmode.leftDown "[mode is needed to call superclass.leftDown]" ####@@@@ LOGIC BUG: when we reload, we replace one highlightable with a new one in the same place -- # but don't replace selobj with the new one! So we predict not selobj_still_ok -- should print that from there ###@@@ # [fixed now? note, reload is not right here, but in superclass.leftDown when it calls testmode.emptySpaceLeftDown] if printdraw: print "\ntestdraw leftDown" ###@@@ superclass.leftDown(mode, event) # this might call testmode.emptySpaceLeftDown (or other class-specific leftDown methods in it) glpane.gl_update() # always, for now [might be redundant with superclass.leftDown, too] def render_scene(mode, glpane): # called by testmode.render_scene # 061208 # print "calling glpane.render_scene from testdraw.render_scene" -- works glpane.render_scene() return def Draw_preparation(mode, glpane, superclass): # called by testmode.Draw_preparation init_glpane_vars(glpane) return # no need so far for Draw_other_before_model def Draw_model(mode, glpane, superclass): # called by testmode.Draw_model if env.prefs.get("A9 devel/testdraw/super.Draw first?", True): #070404 glPushMatrix() #k needed?? superclass.Draw_model(mode) glPopMatrix() # glpane.part.draw(glpane) # this doesn't draw the model in any different place as when done below... [061211] return def Draw_other(mode, glpane, superclass): # called by testmode.Draw_other glPushMatrix() try: drawtest0(glpane) # this does all our special drawing, and sometimes puts some of it into a display list # [no point in putting the main model drawing into it, for now -- but when we can know when to inval, there might be] except: print_compact_traceback("exc ignored: ") glPopMatrix() # it turns out this is needed, if drawtest0 does glTranslate, or our coords are messed up when glselect code # [not sure what this next comment is about:] # makes us draw twice! noticed on g4, should happen on g5 too, did it happen but less?? if env.prefs.get("A9 devel/testdraw/super.Draw last?", False): # revised prefs key and default, 070404 # NOTE: after 090310 refactoring of Draw API, this is happening at the wrong time # (in Draw_other rather than in Draw_model) which may make it slower and/or have bugs. # [bruce 090310 comment] glPushMatrix() if 1: superclass.Draw_model(mode) # needed for region selection's separate xor-drawing; # I suspect this is slower than the other case. Does it draw more than once (for glselect) or something like that? ####@@@@ else: # region selection's drawing [later: xor mode, i guess] won't work in this case, though its selection op itself will work glpane.part.draw(glpane) # highlighting works fine on this copy... if 0 and 'draw copy2 of model': glTranslate(5,0,0) glpane.part.draw(glpane) # but not on this one - i see why it doesn't draw it there, but why not complain about not finding it? glPopMatrix() # draw invisible stuff #e (we'll want to split this into stages for more than one kind of such stuff; # later, to go through a "rendering pass widget expr") for func in glpane._testmode_stuff_2: # colors, for translucent stuff func() for func in glpane._testmode_stuff_3: # depths, for translucent stuff (matters if they are highlightable) func() for func in glpane._testmode_stuff: # depths, for invisible stuff func() return def Draw_after_highlighting(mode, pickCheckOnly, glpane, superclass): ## print "testdraw.Draw_after_highlighting(pickCheckOnly = %r)" % (pickCheckOnly,) # pickCheckOnly is True once when I click return superclass.Draw_after_highlighting(mode, pickCheckOnly) # == def drawtest0(glpane): """ run drawtest1, protected from exceptions, after setting up some of its environment """ # load the texture for the courier bitmap font; params incl tex_name are in private texture_fonts.vv object ensure_courierfile_loaded() # used to be done inside drawtest1 glpane.kluge_reset_texture_mode_to_work_around_renderText_bug() #bruce 081205; ok this soon? exprs_globals.start_time = time.time() # anything that gets drawn can compare this with realtime # to get time so far in this frame, but it's up to it to be drawn # near the end of what we draw in the frame try: if printdraw: print "drawfunc (redraw %d)" % env.redraw_counter drawtest1(glpane) except: # this happens sometimes print_compact_traceback("exception in testdraw.py's drawfunc call ignored: ") return def drawtest1(glpane): # main special drawing -- let the exprs module do it _reload_exprs_test() from exprs.test import drawtest1_innards drawtest1_innards(glpane) return def _reload_exprs_test(): # will need REVIEW when we have a new reloading system to replace heavy manual use of reload_once from exprs.reload import reload_once from exprs import test reload_once(test) return # == # (some outtakes removed to bruceG5 testdraw-outtakes.py, last here in rev 1.11) # (lots more removed 070408 over several commits, last here in rev 1.55) # end
NanoCAD-master
cad/src/exprs/testdraw.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ __init__.py -- control initial import order and side effects, whenever any submodule of this exprs package is used. @author: Bruce @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. """ # Note: I don't know whether the following imports need to be relative # to this package (as they are now). Until I know this, I will leave # them relative. [bruce 080130] # print "fyi: start of exprs.__init__.py" # control initial import order: import Exprs # probably not needed at present, but might be needed # if we revise __Symbols__.py to not import Exprs, or vice versa # try to tell Pylint that we needed to do that import: [bruce 071023] Exprs # initialize some symbols using side effects # [moved here from ExprsConstants.py, bruce 070914] from __Symbols__ import Anything #070115 from __Symbols__ import Automatic, Something #070131 # Symbol docstrings -- for now, just tack them on (not yet used AFAIK): Anything.__doc__ = """Anything is a legitimate type to coerce to which means 'don't change the value at all'. """ Anything._e_sym_constant = True Automatic.__doc__ = """Automatic [###NIM] can be coerced to most types to produce a default value. By convention, when constructing certain classes of exprs, it can be passed as an arg or option value to specify that a reasonable value should be chosen which might depend on the values provided for other args or options. """ ###e implem of that: # probably the type should say "or Automatic" if it wants to let a later stage use other args to interpret it, # or maybe the typedecl could give the specific rule for replacing Automatic, using a syntax not specific to Automatic. Automatic._e_sym_constant = True Something.__doc__ = """Something is a stub for when we don't yet know a type or value or formula, but plan to replace it with something specific (by editing the source code later). """ Something._e_eval_forward_to = Anything # print "fyi: end of exprs.__init__.py" # end
NanoCAD-master
cad/src/exprs/__init__.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ test_statearray_3.py @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. test code for one kind of constrained dragging used in testexpr_35b thru 35d in exprs/test.py the DragBehavior in this file [now in its own file, DragBehavior_AlongLine] improves on the one in test_statearray_2.py: - uses its own coordsys, not the one in the Highlightable - computes the translation from the height (for internal and external use) - has a range limit But it needs a refactoring; see comments herein about "refactoring". """ from exprs.Column import SimpleColumn, SimpleRow from exprs.Rect import Rect, Line from exprs.Highlightable import Highlightable from exprs.images import Image from exprs.controls import ActionButton ##, PrintAction from exprs.geometry_exprs import Ray from exprs.transforms import Translate from exprs.Overlay import Overlay from utilities.constants import white from exprs.Exprs import call_Expr, tuple_Expr from exprs.statearray import StateArrayRefs, StateArrayRefs_getitem_as_stateref from exprs.iterator_exprs import MapListToExpr, KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.attr_decl_macros import Arg, Option, Instance from exprs.ExprsConstants import StateRef, ORIGIN, DX, Width, Vector from exprs.py_utils import sorted_items from exprs.__Symbols__ import _self from exprs.DragBehavior_AlongLine import DragBehavior_AlongLine # == example 3 # 070318: now that DraggablyBoxed resizer works, I'll revise example 2 in some related ways, # including using a saved_coordsys as in SimpleDragBehavior. This new example has the same intent # as example 2, but cleaner code, and could entirely replace it once it works -- # but now they both work (except for different lbox effects) so for now I'll keep them both around. # [note, that comment is partly about DragBehavior_AlongLine, now in its own file] class _height_dragger_3(DelegatingInstanceOrExpr): # args height_ref = Arg(StateRef, doc = "stateref to a height variable") direction = Arg(Vector) sbar_text = Option(str, "_height_dragger_3") range = Option(tuple_Expr, None, doc = "range limit of height") # appearance/behavior #e should draw some "walls" too, and maybe limit the height drag_handler = Instance( DragBehavior_AlongLine( _self._delegate, height_ref, ## Ray(ORIGIN, DX) # works ## Ray(ORIGIN, DZ) # works, but only if you trackball it (as expected)... ## Ray(ORIGIN, direction) # fails -- Ray is an ordinary class, not an expr! ###FIX call_Expr(Ray, ORIGIN, direction), # this workaround fixes it for now. # (in prior commit it didn't fix it, but only because of a typo in the testexpr defs # in tests.py, which meant I passed DZ when I thought I passed DX.) range = range )) ### NOTE: drag_handler is also being used to compute the translation from the height, even between drags. delegate = Overlay( Highlightable( Translate( Image("blueflake.png"), ###e needs an option to be visible from both sides (default True, probably) drag_handler._translation ###k ok?? only if that thing hangs around even in between drags, i guess! #e #k not sure if this code-commoning is good, but it's tempting. hmm. ), sbar_text = sbar_text, behavior = drag_handler ), Translate(Rect(2), direction * -0.01), Line(ORIGIN, ORIGIN + direction * height_ref.value, white) ) pass class test_StateArrayRefs_3( DelegatingInstanceOrExpr): # testexpr_35b, _35c indices = range(3) heights = StateArrayRefs(Width, 0.0) direction = Arg(Vector, DX, "direction of permitted motion -- DZ is the goal but DX is easier for testing") ### DX for initial test (testexpr_35b), then DZ (testexpr_35c) range = Option(tuple_Expr, None, doc = "range limit of height") msg = Option(str, "drag along a line") def _height_dragger_for_index(self, index): stateref = StateArrayRefs_getitem_as_stateref( self.heights, index ) #e change to self.heights.getitem_as_stateref(index)? self.heights._staterefs[index]?? self.heights[index]??? newindex = ('_height_dragger_3_for_index', index) return self.Instance( _height_dragger_3( stateref, self.direction, sbar_text = "%s (#%r)" % (self.msg, index,), range = self.range ), newindex ) delegate = SimpleRow( MapListToExpr( _self._height_dragger_for_index, ###k _self needed?? indices, KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr(SimpleColumn) ), #e SimpleGrid? 2d form of MapListToExpr? ActionButton( _self.printit, "button: print state") ###e idea: define on special attr, let UI assemble debug info viewer ) def printit(self): #e can PrintAction do this for us? print [h.value for i,h in sorted_items(self.heights)] ###KLUGE, assumes they're StateRefs -- maybe just rename StateArray -> StateArrayRefs pass # end
NanoCAD-master
cad/src/exprs/test_statearray_3.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ exprs/test.py - tests of exprs package, accessible from testmode UI; also some exprs/testmode support code (which ought to be refiled) @author: Bruce @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. """ #e during devel, see drawtest1_innards for main entry point from testdraw.py # and old todo-list, still perhaps useful: # # Would it be useful to try to define several simple things all at once? # Boxed, Rect, Cube, ToggleShow, Column/Row # classify them: # - 2d layout: # - Column/Row, Boxed, Checkerboard # - has kids: # - Column # - all macros (since _value is a kid, perhaps of null or constant index) # - If [and its kids have to be lazy] # - Cube, Checkerboard # - macro: # - ToggleShow, Boxed, MT # - has state: # - ToggleShow # - simple leaf: # - Rect # - complicated options: # - Grid # - complicated visible structure # - Cube, Grid, Checkerboard, MT # - 3d layout # - Cube # - iterator # - Cube, Checkerboard (and fancier: Table) # first: Column, Boxed, Rect, If import os import sys import time from PyQt4.Qt import QInputDialog # == imports from parent directory import foundation.changes as changes changes._debug_standard_inval_nottwice_stack = False changes._debug_standard_inval_twice = False # WARNING: this hides the pseudobug [061207] changes._debug_standard_inval_twice_stack = False # == local imports with reload from exprs.Rect import Rect, RectFrame, IsocelesTriangle, Spacer, SpacerFor from exprs.Rect import Sphere, PartialDisk from exprs.ColorCube import ColorCube from exprs.Column import SimpleColumn, SimpleRow # no longer includes still-nim Column itself [070129] from exprs.Overlay import Overlay from exprs.Boxed import Boxed from exprs.draggable import DraggablyBoxed from exprs.transforms import Translate, Closer from exprs.TestIterator import TestIterator, TestIterator_wrong_to_compare from exprs.TextRect import TextRect from exprs.Highlightable import Highlightable from exprs.Highlightable import Button from exprs.Highlightable import print_Expr from exprs.Highlightable import _setup_UNKNOWN_SELOBJ_on_graphicsMode from exprs.Highlightable import BackgroundObject from exprs.ToggleShow import ToggleShow from exprs.images import Image, IconImage, NativeImage, PixelGrabber from exprs.controls import ChoiceButton, ChoiceColumn, ChoiceRow, checkbox_v3, checkbox_pref, ActionButton, PrintAction #e rename some of these? from exprs.staterefs import PrefsKey_StateRef from exprs.Set import Set ##e move to basic from exprs.demo_MT import test_drag_pixmap, MT_try2 from exprs.widget2d import Stub # MT_try1 was moved to this outtakes file 070210; it's still importable from there and works in testexpr_18 # (verified in test.py cvs rev 1.224), but since it's obs, we'll no longer import it (thus breaking all tests # using MT_try1 unless you reenable this import). #if 0: # from exprs.demo_MT_try1_obs import MT_try1 #else: MT_try1 = Stub from exprs.demo_drag import GraphDrawDemo_FixedToolOnArg1, kluge_dragtool_state_checkbox_expr, demo_drag_toolcorner_expr_maker from exprs.projection import DrawInCorner_projection, DrawInCorner ##from exprs.ModelNode import Sphere_ExampleModelNode ###stub or wrong, not yet used [061215] from exprs.DisplayListChunk import DisplayListChunk ##import demo_polygon # stub 070103 # commented out 070117 since it's a scratch file with syntax errors # [and it was renamed 070125 from demo_dna.py] ##from demo_polygon import newerBoxed, resizablyBoxed ##from lvals import Lval_which_recomputes_every_time ##e and more? refile in basic?? from exprs.widget_env import widget_env from exprs.debug_exprs import DebugPrintAttrs from exprs.dna_ribbon_view import DNA_Cylinder, dna_ribbon_view_toolcorner_expr_maker, World_dna_holder, Cylinder from exprs.draggable import DraggableObject ##from exprs.world import World ##import exprs.demo_polyline from exprs.test_statearray import test_StateArrayRefs from exprs.test_statearray_2 import test_StateArrayRefs_2 from exprs.test_statearray_3 import test_StateArrayRefs_3 from geometry.VQT import V from utilities.Comparison import same_vals from utilities.constants import purple, white, blue, red, orange, green, lightgreen from utilities.constants import gray, pink, yellow, black from utilities.constants import ave_colors, noop # more colors imported below, from ExprsConstants from utilities.prefs_constants import displayOriginAxis_prefs_key from graphics.drawing.texture_fonts import courierfile from graphics.drawing.CS_draw_primitives import drawline from exprs.reload import exprs_globals from exprs.Exprs import format_Expr, getattr_Expr, list_Expr, mod_Expr, not_Expr, eval_Expr, call_Expr, is_Expr from exprs.Exprs import local_ipath_Expr from exprs.If_expr import If_expr, If, If_OpExpr import exprs.Center as Center_module from exprs.Center import Left, Center, Right, TopRight, CenterRight, BottomRight, TopLeft, CenterY, BottomLeft from exprs.py_utils import printnim, identity from exprs.widget2d import Widget2D from exprs.instance_helpers import WithAttributes, InstanceMacro, _this, DelegatingInstanceOrExpr from exprs.attr_decl_macros import State, Option, Instance, Arg from exprs.ExprsConstants import trans_red from exprs.ExprsConstants import PIXELS from exprs.ExprsConstants import lightblue from exprs.ExprsConstants import ORIGIN, DX, DZ ##, DY from exprs.ExprsConstants import nevermind from exprs.ExprsConstants import PM_CORNER from exprs.ExprsConstants import WORLD_MT_CORNER from exprs.ExprsConstants import DEBUG_CORNER from exprs.ExprsConstants import NullIpath from exprs.__Symbols__ import _self, _my, _app, Anything ### WARNING: more imports far below! (of files that used to get lazy and do "from test import *", e.g. demo_ui; # now that import * is banned, maybe they could be moved up here? I don't know.) # == # == make some "persistent state" try: _state except: _state = {} ###e Note: this is used for env.staterefs as of bfr 061120; see also session_state, not yet used, probably should merge # == testexprs # === test basic leaf primitives ## testexpr_1 = Rect_old(7,5, color = green) # works 061030; removed 061113 since obs (tho only test of obs _DEFAULT_ and _args) testexpr_2 = Rect(8,6, color = purple) # works as of 061106 testexpr_2a = Rect(8,5, color = trans_red) # fails, since appears fully red ###BUG in translucent color support # test not supplying all the args testexpr_2b = Rect(4, color = purple) # works [061109] testexpr_2c = Rect(color = purple) # works; had warning from no explicit args until 070121 (still warns minimally for now) testexpr_2d = Rect() # works, except default size is too big, since 10 makes sense for pixels but current units are more like "little" testexpr_2e = Rect(4, 5, white) # works # test non-int args testexpr_2f = Rect(4, 2.6, blue) # works #e test some error detection (nonunderstood option name, color supplied in two ways -- problem is, detecting those is nim) #e test some formulas? e.g. a rect whose width depends on redraw_counter?? testexpr_3 = RectFrame(6,4) # works testexpr_3a = RectFrame(6,4,color=blue) # works testexpr_3b = RectFrame(6,4,thickness=5*PIXELS) # works testexpr_3c = RectFrame(6,4,5*PIXELS,red) # works # test DebugPrintAttrs (and thereby DelegatingMixin) testexpr_3x = DebugPrintAttrs(Rect(4,7,blue), 'color') # works now! late 061109 (won't yet work with more than one attrname) def FilledSquare(fillcolor, bordercolor, size = 0.5, thickness_ratio = 0.05): # 061115 direct copy from cad/src/testdraw.py return Overlay( Rect(size, size, fillcolor), RectFrame(size, size, size * thickness_ratio, bordercolor) ) testexpr_3y = FilledSquare(purple, blue) # works, except top border quantized to 0 pixels thick, others to 1 (not surprising) # === test more complex things # Overlay (as of 061110 only implemented with exactly two args) # these all work as expected, now that I know why Rect(1, white) doesn't work. After the commit I can clean it up. #e testexpr_4 = Overlay( Rect(2), Rect(1, white) ) # might work since exactly two args; requires ArgList for more ###k test 061110 # appears to work except that the white rect does not show; that's a bug, but for now, try a less ambiguous test: testexpr_4a = Overlay( Rect(2,1), Rect(1, 2, white) ) # works; white rect is in front, but that didn't happen in test 4!! ####??? testexpr_4b = Rect(1.5, white) # could this be the problem? white is probably interpreted as a Width! (as 1) why no error?? ###e printnim("the error of Color as Width in Rect(1.5, white) ought to be detected in draw_utils even before type coercion works") testexpr_4c = Rect(1.5, color = white) # works testexpr_4d = Overlay( Rect(2), Rect(1, color = white) ) # works! # Boxed # obs tests of Boxed_old*, CenterBoxedKluge* removed 070317: testexpr_5, _5x, _5a, _5b, _5c_exits [last present in cvs rev 1.263] testexpr_5d = Boxed( Rect(2,3.5,purple)) # 061113 morn - works; this should become the official Boxed, tho its internal code is unclear # TextRect, and _this testexpr_6a = TextRect("line 1\nline 2", 2,8) # works # note, nlines/ncols seems like the right order, even though height/width goes the other way testexpr_6b = TextRect("line 3\netc", 2) # works except for wrong default ncols testexpr_6c = TextRect("line 4\n...") # works except for wrong defaults -- now nlines default is fixed, 061116 testexpr_6d = TextRect("%r" % _self.ipath) # bug: Expr doesn't intercept __mod__(sp?) -- can it?? should it?? not for strings. ###### testexpr_6e = TextRect(format_Expr("%r", _self.ipath),4,60) # incorrect test: _self is not valid unless we're assigned in some pyclass # (so what it does is just print the expr's repr text -- we can consider it a test for that behavior) # (note: it tells us there's a problem by printing "warning: Symbol('_self') evals to itself") # Update 070118: in EVAL_REFORM, this has an exception, AttributeError: 'lexenv_Expr' object has no attribute 'ipath', # about the bare symbol _self wrapped with a lexenv_Expr. I think that's ok, since it's an error in the first place. # Maybe the error behavior could be improved, but we can ignore that for now. testexpr_6f = TextRect(format_Expr( "%r", _this(TextRect).ipath ),4,60) # printed ipath is probably right: 'NullIPath' ###k verify # obs cmt (correct but old, pre-061114): # PRETENDS TO WORK but it must be the wrong thing's ipath, # since we didn't yet implem finding the right thing in _this!! [061113 934p] # Guess at the cause: I wanted this to be delegated, but that won't work since it's defined in the proxy (the _this object) # so __getattr__ will never run, and will never look for the delegate. This problem exists for any attr normally found # in an InstanceOrExpr. Solution: make it instantiate/eval to some other class, not cluttered with attrs. [done now, 061114] # # update 061114: now it works differently and does find right thing, but the printed ipath looks wrong [WRONG - it's not wrong] # Is it ipath of the pure expr (evalled too soon), # or is the ipath (of the right instance) wrong? Or are we asking too early, before the right one is set? # How can I find out? [061114 152p] # A: it wasn't wrong, it was the top expr so of course it was None -- now I redefined it to 'NullIPath'. # But a good test is for an expr in which it's not None, so try this, which will also verify ipaths are different: testexpr_6f2 = Overlay(testexpr_6f, Translate(testexpr_6f, (0,-2))) # works! testexpr_6g = TextRect(format_Expr( "%r", _this(TextRect) ),4,60) # seems to work, 061114 testexpr_6g2 = TextRect(format_Expr( "%r", (_this(TextRect),_this(TextRect)) ),4,60) # should be the same instance - works (best test) testexpr_6h = TextRect(format_Expr( "%r", _this(TextRect)._e_is_instance ),4,60) # unsupported. # prints False; wrong but not a bug -- ._e_* is unsupportable on any symbolic expr. # Reason (not confirmed by test, but sound): # it never even forms a getattr_Expr, rather it evals to False immediately during expr parsing. testexpr_6h2 = TextRect(format_Expr( "%r", getattr_Expr(_this(TextRect),'_e_is_instance') ),4,60) # works (prints True) ## testexpr_6i = TextRect(format_Expr( "%r", _this(TextRect).delegate ),4,60) # attrerror, not a bug since TextRects don't have it testexpr_6j = TextRect(format_Expr( "%r", (_this(TextRect),_this(TextRect).ncols) ),4,60) # works: prints (<textrect...>, 60) #e more kinds of useful TextRect msg-formulae we'd like to know how to do: #e how to access id(something), or env.redraw_counter, or in general a lambda of _self # Boxed (_7 and _7a were TestIterator, now deferred) testexpr_7b = Boxed(testexpr_6f) # works (and led to an adjustment of PIXELS to 0.035 -- still not precisely right -- not important) testexpr_7c = Boxed(testexpr_7b) # works as of 061114 noon or so. (2 nested Boxeds) testexpr_7d = Boxed(testexpr_7c) # works (3 nested Boxeds) # SimpleColumn & SimpleRow [tho out of testexpr_7*, TestIterator doesn't work yet, only nested Boxed does] testexpr_8 = SimpleColumn( testexpr_7c, testexpr_7b ) # works (gap is ok after Translate lbox fixed) testexpr_8a = SimpleColumn( testexpr_7c, testexpr_7c, pixelgap = 0 ) # works (gap is ok after Translate lbox fixed) testexpr_8b = SimpleColumn( Rect(1,1,blue), Rect(1,1,red), pixelgap = 1 ) # works (with pixelgap 2,1,0,-1) testexpr_8c = SimpleColumn( Rect(1,1,blue), None, Rect(1,1,orange), pixelgap = 1 ) # None-removal works, gap is not fooled testexpr_8d = SimpleRow( Rect(1,1,blue), None, Rect(1,1,orange), pixelgap = 1 ) # works testexpr_8e = SimpleRow( Rect(1,1,blue), Rect(2,2,orange), pixelgap = 1 ) # works testexpr_8f = SimpleRow(SimpleColumn(testexpr_8e, testexpr_8e, Rect(1,1,green)),Rect(1,1,gray)) # works # [don't forget that we skipped TestIterator above -- I think I can safely leave iterators unsolved, and fancy Column unfinished, # while I work on state, highlighting, etc, as needed for ToggleShow and MT-in-GLPane [061115]] # [warning: some commits today in various files probably say 061114 but mean 061115] # Highlightable, primitive version [some egs are copied from cad/src/testdraw.py, BUT NOT YET ALL THE PRIMS THEY REQUIRE ##e] testexpr_9a = Highlightable( Rect(2, 3, pink), # this form of highlight (same shape and depth) works from either front or back view Rect(2, 3, orange), # comment this out to have no highlight color, but still sbar_text # example of complex highlighting: # Row(Rect(1,3,blue),Rect(1,3,green)), # example of bigger highlighting (could be used to define a nearby mouseover-tooltip as well): # Row(Rect(1,3,blue),Rect(2,3,green)), sbar_text = "big pink rect" ) # works for highlighting, incl sbar text, 061116; # works for click and release in or out too, after fixing of '_self dflt_expr bug', 061116. if 'stubs 061115': Translucent = identity testexpr_9b = Button( ## Invisible(Rect(1.5, 1, blue)), # works Translucent(Rect(1.5, 1, blue)), # has bug in Translucent ## IsocelesTriangle(1.6, 1.1, orange), # oops, I thought there was an expanding-highlight-bug-due-to-depthshift-and-perspective, # but it was only caused by this saying 1.6, 1.1 rather than 1.5, 1! Rect(1.5, 1, orange), ## Overlay( Rect(1.5, 1, lightgreen) and None, (IsocelesTriangle(1.6, 1.1, orange))), ###@@@ where do I say this? sbar_text = "button, unpressed" ##e maybe I include it with the rect itself? (as an extra drawn thing, as if drawn in a global place?) IsocelesTriangle(1.5, 1, green), IsocelesTriangle(1.5, 1, yellow),#e lightgreen better than yellow, once debugging sees the difference ###@@@ sbar_text = "button, pressed", # actions (other ones we don't have include baremotion_in, baremotion_out (rare I hope) and drag) on_press = print_Expr('pressed'), on_release_in = print_Expr('release in'), # had a bug (did release_out instead), fixed by 'KLUGE 061116' on_release_out = print_Expr('release out') ) # using 'stubs 061115': # - highlighting works # - button aspect (on_* actions) was not yet tested on first commit; now it is, # and each action does something, but on_release_in acted like on_release_out, # but I fixed that bug. ###e should replace colors by text, like enter/leave/pressed_in/pressed_out or so # update 070118, with no testbed and EVAL_REFORM turned off: still works, but prints # debug_pref: preDraw_glselect_dict failure ... whenever mouse goes off or on while it's pressed. # That's probably not a bug, but it might be worth understanding re other bugs in highlighting system. # Guess: the selobj is out of date but still used in some way. # update 070212: still works after unstubbing IsocelesTriangle (before now it was equal to Rect). testexpr_9c = SimpleColumn(testexpr_9a, testexpr_9b) # works (only highlighting tested; using 'stubs 061115') testexpr_9d = testexpr_9b( on_release_in = print_Expr('release in, customized')) # works # test customization of option after args supplied testexpr_9e = testexpr_9b( on_release_in = None) # works # test an action of None (should be same as a missing one) (also supplied by customization after args) testexpr_9cx = SimpleColumn(testexpr_9a, testexpr_9b(projection = True)) # works 070118?? [verified still works 070405] testexpr_9cy = DrawInCorner_projection(Highlightable(Rect(1,1,black),Rect(1,1,green),projection=True)) # 070405, works! # So, projection matrix changes are now ok re Highlightable if you tell it projection=True. See comments therein for more. testexpr_9f = Highlightable( Rect(color = If_expr(_this(Highlightable).env.glpane.in_drag, blue, lightblue))) # fails, silly reason ## AssertionError: this expr needs its arguments supplied: <Rect#0(i w/o a)> # I turned that into a warning, but it fails later (ends up trying to draw_filled_rect with color = If_expr(...)), # perhaps because destructive_supply_args never ran -- just a speculation, but I can't see anything else that could differ. # Hmm, maybe the bug will occur even if I supply the args?!? Try that now: testexpr_9fx1 = Rect(color = If_expr(_my.env.glpane.in_drag, blue, lightblue)) # still fails (expected) # _my is ok since everyone's glpane is the same! # This has the same ###BUG!!! Hmm, why doesn't that expr get evalled? Oh, duh, I forgot to supply the args. Ok, this is the control experiment. testexpr_9fx2 = Rect(color = If_expr(_my.env.glpane.in_drag, blue, lightblue))() # still fails # This has the same bug, and does have args and no longer complains it doesn't! So some code to eval If_expr or _my is missing. testexpr_9fx3 = Rect(1, 1, If_expr(_my.env.glpane.in_drag, blue, lightblue)) # try it with args supplied at same time, and color not an option -- still fails; # after I overrode _e_eval in If_expr it sort of works but gets stuck at true state, but maybe in_drag itself gets stuck (in rubberband selrect)?? # hard to say; double-click makes it 0, using atoms makes it 1 again... # note that I was wrong that glpane.in_drag would be ok for this application instead of something about _this(Highlightable) -- # it's true about *any* drag, not only about a drag of that object -- not what I intended. Even so it ought to work. # It might be failing due to lack of inval when in_drag changes, of course. Try adding another draggable somewhere? # No, dragging around on a TextRect causes lots of redraws, but no reprints of "<If_expr#19096(a)> gets cond 1"! Why? # Because something contains its value and didn't usage-track anything which we're invalidating here! AHA. ######BUG # That can be fixed by referring to trackable state, provided it's not _i_instance_dict or whatever which fails to track this eval anyway. Try it. testexpr_9fx4 = Highlightable( Rect(1, 1, If_expr(_this(Highlightable).transient_state.in_drag, blue, lightblue))) # works, if I # remember to click rather than just to mouseover -- the code says in_drag, not in_bareMotion! ##e should make an abbrev for that attr as HL.in_drag -- maybe use State macro for it? read only is ok, maybe good. ##e should add an accessible attr for detecting whether we're over it [aka in_bareMotion -- not a serious name-suggestion]. # What to call it? # Q, 070118: Does that mean all the comments in _9f thru _9f3 are mistaken, as if mouseover == drag??? # Or did I click in those tests? # 070122 update: I don't know if it means that, but recently they failed in EVAL_REFORM but this is probably expected. # This one, testexpr_9fx4, had a bug in ER, apparently due to no local ipath mod, fixed some days ago by adding one. So it works now. testexpr_9fx5 = Highlightable( Rect(color = If_expr(_this(Highlightable).transient_state.in_drag, blue, lightblue))) # works with warning # so it turns out the If_expr was a total red herring -- once fixed, the no-args form now warns us, but works anyway. testexpr_9fx6 = Highlightable( Rect(color = If_expr(_this(Highlightable).transient_state.in_drag, purple, lightblue))() ) # works # ToggleShow testexpr_10a = ToggleShow( Rect(2,3,lightgreen) ) # test use of Rules, If, toggling... works testexpr_10b = ToggleShow( Highlightable(Rect(2,3,green)) ) # use Highlightable on rect - avoid redraw per mousemotion on it - works testexpr_10c = ToggleShow(ToggleShow( Highlightable(Rect(2,3,green)) )) # works testexpr_10d = ToggleShow(ToggleShow( Rect(2,3,yellow) )) # works # [all still work [on g4] after StatePlace move, 061126 late; _10c also tested on g5, works] # [also ok on g4: all of _11 & _12 which I retried] # Image blueflake = "blueflake.png" testexpr_11a = Image(courierfile) # works testexpr_11a1 = Image("courier-128.png") # works (note: same image) testexpr_11a2 = Image(blueflake) # works [and no longer messes up text as a side effect, now that drawfont2 binds its own texture] # WARNING: might only work due to tex size accident -- need to try other sizes testexpr_11b = SimpleRow( Image(blueflake), Image(courierfile) ) # works (same caveat about tex size accidents applies, re lbox dims) testexpr_11c = SimpleColumn( Image(courierfile), Image(blueflake), pixelgap=1 ) # works testexpr_11d = SimpleRow( SimpleColumn( Image(courierfile), Image(blueflake), pixelgap=1 ), SimpleColumn( Image(blueflake), Image(courierfile), pixelgap=1 ), pixelgap=1 ) # works testexpr_11d2 = SimpleColumn( SimpleColumn( Image(courierfile), Image(blueflake), pixelgap=1 ), SimpleColumn( Image(blueflake), Image(courierfile), pixelgap=1 ), ) # works testexpr_11d3 = SimpleColumn( SimpleRow( Image(courierfile), Image(blueflake), pixelgap=1 ), SimpleRow( Image(blueflake), Image(courierfile), pixelgap=1 ), ) # works; but suffers continuous redraw as mouse moves over image # (as expected; presumably happens for the others too, and for all other tests, not just images; seen also for Rect) ##e we need a general fix for that -- should all these leafnodes allocate a glname if nothing in their surroundings did?? testexpr_11d4 = SimpleRow( SimpleRow( Image(courierfile), Image(blueflake), pixelgap=1 ), SimpleRow( Image(blueflake), Image(courierfile), pixelgap=1 ), ) # works testexpr_11e = ToggleShow( testexpr_11a2) # works; continuous redraw as mouse moves over image (as expected) testexpr_11f = ToggleShow( Highlightable( testexpr_11a)) # works; no continuous redraw (as expected) testexpr_11g = Image(blueflake, nreps = 2) # works; this series is best viewed at zoom of 3 or so [061126] testexpr_11h = Image(blueflake, clamp = True, nreps = 3, use_mipmaps = True) # works (clamping means only one corner has the image) testexpr_11i = testexpr_11h(pixmap = True) # works (reduced fuzziness) [note: this customizes an option after args supplied] # note: there is probably a bug in what Image texture options do to subsequent drawfont2 calls. [as of 061126 noon; not confirmed] # note: defaults are clamp = False, use_mipmaps = True, decal = False [was True before 070404], pixmap = False; # the options not tried above, or tried only with their defaults, are not yet tested -- namely, # untested settings include use_mipmaps = False, decal = False [nim before 070403]. testexpr_11j = testexpr_11h(use_mipmaps = False) # DOESN'T WORK -- no visible difference from _11i. #####BUG ??? testexpr_11k = testexpr_11h(tex_origin = (-1,-1)) # works; latest stable test in _11 (the rest fail, or are bruce-g4-specific, or ugly) # try other sizes of image files ## testexpr_11l_asfails = testexpr_11k(courierfile) # can I re-supply args? I doubt it. indeed, this asfails as expected. # note, it asfails when parsed (pyevalled), so I have to comment out the test -- that behavior should perhaps be changed. imagetest = Image(tex_origin = (-1,-1), clamp = True, nreps = 3, use_mipmaps = True) # customized [see also IconImage, imagetest_x2] testexpr_11m = imagetest(courierfile) # works # [but weirdly, on bruce's g5 061128 212p as first test, clamped part is blue! ###BUG?? # screenshot on g5 is in /Nanorex/bug notes/clamped is blue.jpg # It turns out it is a different color depending on what's been displayed before! # If i have some atoms, at least with testexpr_11pcy2, and highlight them etc, it affects this color. # Must be something in the texture or its border looking at current color, # or some GL state that affects drawing that border region. But it affects color all around the triangle icon in the file, # not just around the square pasted area, so it must have something to do with the alpha value, or some sort of background.] testexpr_11n = imagetest("stopsign.png") # fails; guess, our code doesn't support enough in-file image formats; ###BUG # exception is SystemError: unknown raw mode, [images.py:73] [testdraw.py:663] [ImageUtils.py:69] [Image.py:439] [Image.py:323] ##e need to improve gracefulness of response to this error # PIL reports: (22, 22), 'RGBA' testexpr_11nc = imagetest("stopsign.png", convert = True) # [061128, does convert = True help? partly...] # this lets us read it and display it, but we get "IOError: cannot write mode RGBX as PNG" # when we try to write it out to update it. # (But why does it try to write it into a PNG file, not some other format of its choice? ###k Specify or hardcode an update format?) # What's better is to just use RGBA in the texture, if we can... I need to look at the texture making code re this. ###e testexpr_11ncx2 = imagetest("stopsign.png", convert = True, _tmpmode = 'TIFF') # works, see 11pc-variant comments for details testexpr_11ncy2 = imagetest("stopsign.png", convert = 'RGBA', _tmpmode = 'TIFF') # ditto testexpr_11o = imagetest("RotateCursor.bmp") # fails, unknown raw mode ###BUG # PIL reports: (32, 32), '1' # "1-bit bilevel, stored with the leftmost pixel in the most significant bit. 0 means black, 1 means white." testexpr_11oc = imagetest("RotateCursor.bmp", convert = True) # works but with exception, like _11nc testexpr_11ocx = imagetest("RotateCursor.bmp", convert = True, _tmpmode = 'JPEG') # see if this fixes exception -- well, not quite: ## debug warning: oldmode != newmode ('RGBX' != 'CMYK') in ## <nEImageOps at 0xf029d28 for '/Nanorex/Working/cad/images/RotateCursor.bmp'>.update ##fyi: following exception relates to <JpegImagePlugin.JpegImageFile instance at 0xf029cb0> with mode 'CMYK' ##exception in <Lval at 0xf037e18>._compute_method NO LONGER ignored: exceptions.SystemError: unknown raw mode testexpr_11ocx2 = imagetest("RotateCursor.bmp", convert = True, _tmpmode = 'TIFF') # works! testexpr_11ocy = imagetest("RotateCursor.bmp", convert = 'RGBA') # IOError: cannot write mode RGBA as BMP testexpr_11ocy2 = imagetest("RotateCursor.bmp", convert = 'RGBA', _tmpmode = 'TIFF') # works, looks same as ocx2 testexpr_11p = imagetest("win_collapse_icon.png") # fails, unknown raw mode ###BUG # PIL reports: (16, 8), 'RGBA' testexpr_11pc = imagetest("win_collapse_icon.png", convert = True) # works but with exception, like _11nc testexpr_11pcx = imagetest("win_collapse_icon.png", convert = True, _tmpmode = 'JPEG') # see if this fixes exception -- no, like ocx testexpr_11pcx2 = imagetest("win_collapse_icon.png", convert = True, _tmpmode = 'TIFF') # works, looks better than some others testexpr_11pcy = imagetest("win_collapse_icon.png", convert = 'RGBA') # partly works, no exception, but alpha not yet "active" -- # it's probably not processed properly by neImageOps paste (see comments there), and also not drawn properly. testexpr_11pcy2 = imagetest("win_collapse_icon.png", convert = 'RGBA', _tmpmode = 'TIFF') # works, looks worse than pcx2, improper alpha ###e conclusion: we need to improve image loading / texture making code, so icon/cursor images can work [cmt says how - im.convert] # note: mac shell command 'file' reveals image file format details, e.g. ## % file stopsign.png ## stopsign.png: PNG image data, 22 x 22, 8-bit/color RGBA, non-interlaced # however, on some images it's clearly incorrect (at least on bruce's g4): ## /Nanorex/bug notes/1059 files/IMG_1615.JPG: JPEG image data, EXIF standard 0.73, 10752 x 2048 # obviously too large; PIL says (1704, 2272), 'RGB' when ne1 reads it ## blueflake.jpg: JPEG image data, JFIF standard 1.01, aspect ratio, 1 x 1 # actually (268, 282), 'RGB' [acc'd to PIL] ## courier-128.png: PNG image data, 128 x 128, 8-bit/color RGB, non-interlaced # actually (128, 128), 'RGB' ## redblue-34x66.jpg: JPEG image data, JFIF standard 1.01, resolution (DPCM), 0 x 0 # actually (34, 66), 'RGB' # more conclusions, 061128: Image defaults should be convert = True, _tmpmode = 'TIFF' for now, until Alpha handled properly. # eventually the options should depend on the image type so as not to waste texture ram when used for cursors. #e still need to test more images below with those options. plus the ones that work without them. #e should retest _tmpmode = JPEG since I altered code for that. # more translucent image tests inserted (& finally working after new options added) - 070403; 070404 works with decal = False default testexpr_11pd1 = Overlay( Closer(DraggableObject(Image("win_collapse_icon.png", convert = 'RGBA', decal = True))), DraggableObject(Image("blueflake.png")) ) # works, but closer image has no transparency (as expected with decal = True) testexpr_11pd2 = Overlay( Closer(DraggableObject(Image("win_collapse_icon.png", convert = 'RGBA', decal = False))), DraggableObject(Image("blueflake.png")) ) # works, but without blend option being set, still no transparency (expected) # (but does change image bg color from blue (prior test, might be an accident of color setting leakage) to black) testexpr_11pd3 = Overlay( Closer(DraggableObject(Image("win_collapse_icon.png", convert = 'RGBA', decal = False, blend = True))), DraggableObject(Image("blueflake.png")) ) # works, incl transparency after 070403-late changes in image.py, # but translucent image obscures the other one (expected, since drawn first, with depthwrite on) # (fyi, screenshot in 'translucent first+depthwrite.jpg', not in cvs) testexpr_11pd4 = Overlay( DraggableObject(Image("blueflake.png")), Closer(DraggableObject(Image("win_collapse_icon.png", convert = 'RGBA', decal = False, blend = True))), ) # works, including proper translucency, and (after GL_ALPHA_TEST added) properly not highlightable in fully transparent pixels ###e should add option to turn off depth buffer writing trans_image = Image(convert = 'RGBA', decal = False, blend = True, ## alpha_test = False, # see if this makes OK_Cancel_TrianglesOutline_100x100.png grabbable in blank areas -- works, # and indeed makes all of them grabbable in the entire square. Move to separate test, try again with shape option # to limit to a triangle. [did this below, see testexpr_11pd6 etc] clamp = True, # this removes the artifacts that show the edges of the whole square of the image file ideal_width = 100, ideal_height = 100, size = Rect(100*PIXELS)) _files1 = """Cancel_100x100_translucent.png Cancel_100x100.png OK_Cancel_100x100_translucent.png OK_Cancel_100x100.png OK_Cancel_Triangles_100x100_translucent.png OK_Cancel_Triangles_100x100.png OK_Cancel_TrianglesOutline_100x100.png""".split() _dir1 = "/Nanorex/confirmation-corner/" # not in cvs def test_translucent_icons(_files, _dir = ""): #e refile into images.py? (along with trans_image?) if type(_files) == type(""): # permit single file arg [untested, as is _dir = "" with os.path.join] _files = [_files] _tmp = DraggableObject(SimpleColumn(Image("blueflake.png", size = Rect(5)), TextRect("drag blueflake under icons to see\n" "their translucency over it")), translation = (0,0,0)) for _file, _i in zip(_files, range(len(_files))): _translation = (_i - 4) * 2.5 * DX # de-overlap them _tmp = Overlay( _tmp, Closer(DraggableObject( WithAttributes( trans_image( os.path.join( _dir, _file) ), mt_name = _file ), #e rename mt_name in this interface? (used by DraggableObject) translation = _translation)) ) _tmp = Overlay(_tmp, DraggableObject(SimpleColumn(Rect(5,5,red), TextRect("drag red rect under icons to see which\n" "pixels are highlightable/draggable\n" "(it's drawn so they'll obscure it fully)")), translation = (-6,-8,-10))) return _tmp testexpr_11pd5 = test_translucent_icons(_files1, _dir1) # works; only looks good over atoms ("the model") if you hack testdraw to draw the model before this expr, # rather than after it (now there is a checkbox_pref for that, and it has the right default, 070404) ##_files2 = """BigCancel.png ##BigCancel_pressed.png ##BigOK.png ##BigOK_pressed.png ##Cancel_pressed.png ##OK_Cancel.png ##OK_pressed.png""".split() _files2 = """CancelBig.png CancelBig_Pressed.png DoneBig.png DoneBig_Pressed.png DoneSmall_Cancel_Pressed.png DoneSmall.png DoneSmall_Pressed.png """.split() ## _dir2 = "/Nanorex/confirmation-corner/new-icons/" # not in cvs _dir2 = "ui/confcorner" #070621 [now that cad/src/ui/confcorner is in cvs] testexpr_11pd5a = test_translucent_icons(_files2, _dir2) # test Mark's latest images -- they work ok_image = trans_image( shape = 'upper-left-half') # further customization ok_image_2 = trans_image( shape = [(1,1),(0,1),(0.5,0.75)]) # upper quarter, but only upper half of that again, just for testing cancel_image = trans_image( shape = 'lower-right-half') testexpr_11pd6 = DraggableObject( ok_image( _dir1 + "OK_Cancel_TrianglesOutline_100x100.png", alpha_test = False )) # works (grabs in too many places) # also confirms that the sharp edge is a bit too close for antialiasing, at least on the border with the other button (but that's ok on that edge) testexpr_11pd7 = DraggableObject( ok_image( _dir1 + "OK_Cancel_TrianglesOutline_100x100.png", alpha_test = True )) # works (grabs in too few places) #e to grab in best set of places (i mean, let best set of pixels cause highlight, sbar text, and be potential drag-grip-points), # but not mess up antialiasing of the visible edge, pass in a custom subtriangle shape... # but we probably won't need this in practice, since the real images will not have fully transparent holes, # so it'll be enough to use alpha_test = True (the default, given blend = true) for them. testexpr_11pd8 = DraggableObject( ok_image_2( _dir1 + "OK_Cancel_TrianglesOutline_100x100.png", alpha_test = False )) # works testexpr_11pd9 = DraggableObject( cancel_image( _dir1 + "OK_Cancel_TrianglesOutline_100x100.png", alpha_test = True )) # works (expected grab caveats) testexpr_11pd10 = DraggableObject( ok_image( "blueflake.png", alpha_test = True, convert = False )) # works (subtri of opaque image) # [comment from when this was blueflake.jpg:] # tests different native size, jpg not png, perhaps different native format (RGB vs RGBA, don't know), tri coords ok for diff native size, # and finding filename in usual way. BTW, with convert = RGBA or RGB has SystemError: unknown raw mode (and message mentions CMYK). testexpr_11pd10a = DraggableObject( ok_image( "blueflake.png", blend = False, convert = False )) # works (tests tri not needing blend) # try some images only available on bruce's g4 testexpr_11q1 = imagetest("/Nanorex/bug notes/1059 files/IMG_1615.JPG") # works testexpr_11q1b = Image("/Nanorex/bug notes/1059 files/IMG_1615.JPG", ideal_width = 1704, ideal_height = 2272) # works [070223] testexpr_11q2 = imagetest("/Nanorex/bug notes/bounding poly bug.jpg") # works testexpr_11q3 = imagetest("/Nanorex/bug notes/1059 files/peter-easter-512.png") # works testexpr_11q4 = imagetest("/Nanorex/bug notes/1059 files/IMG_1631.JPG alias") # (mac alias) fails ## IOError: cannot identify image file [images.py:56] [testdraw.py:658] [ImageUtils.py:28] [Image.py:1571] testexpr_11q5 = imagetest("/Nanorex/DNA/paul notebook pages/stages1-4.jpg") # fails, unknown raw mode, ###BUG [try converting it. ###e] # fyi, PIL reports size & mode as (1275, 1647), 'L' # which means "8-bit greyscale. 0 means black, 255 means white." # accd to http://www.pythonware.com/library/pil/handbook/decoder.htm # so converting it is likely to work, but generalizing the retval of getTextureData would be more efficient, # but it's too large anyway so we need to support getting subrect textures from it. #e imagetest_x2 = imagetest(convert = True, _tmpmode = 'TIFF') # [works on some files here; not verified recently[070304] whether needed] imagetest_y2 = imagetest(convert = 'RGBA', _tmpmode = 'TIFF') # [not used here as of 070304; i don't recall its status] testexpr_11q5cx2_g4 = imagetest_x2("/Nanorex/DNA/paul notebook pages/stages1-4.jpg") # shows the "last resort" file. ## ## for the record, at first I didn't guess why it showed courier font file, so I thought the following: ## ##print "testexpr_11q5cx2 _e_args are",testexpr_11q5cx2._e_args # args correct... ## ## guess: too big to resize or load or paste(?), error not reported, ## ## but new texture did not get bound properly. ## ## could confirm theory by putting it in a column, predict we'd show prior one in its place. ##e ## ## WAIT, WRONG, it's just the lastresort file, since this one is only found under that name on g4!!! # That lastresort file needs to look different and/or print error message when found! Ok, now it prints error msg at least. testexpr_11q5cx2_g5 = imagetest_x2("/Nanorex/DNA/pwkr-user-story/notebook page images/stages1-4.jpg") # works, but poor resolution testexpr_11q5cx2_g5_bigbad = imagetest_x2("/Nanorex/DNA/pwkr-user-story/notebook page images/stages1-4.jpg", ideal_width = 1275, ideal_height = 1647) # try huge texture, non2pow size -- actually works! [bruce's g5] [g4 too] #e also try bigger ideal sizes for that one, or try loading a subregion of the image. # but for now, if we need it, just grab smaller images out of it using an external program. testexpr_11q6 = imagetest("/Users/bruce/untitled.jpg") # glpane screenshot saved by NE1, jpg # works (note clamping artifact -- it's ok) testexpr_11q7 = imagetest("/Users/bruce/untitled.png") # glpane screenshot saved by NE1, png # works # note: those are saved by a specific filetype option in "File -> Save As..." testexpr_11q8 = imagetest("/Users/bruce/PythonModules/data/idlewin.tiff") # try tiff -- works testexpr_11q9 = imagetest("/Users/bruce/PythonModules/data/glass.bmp") # bmp from NeHe tutorials -- works testexpr_11q10 = imagetest("/Users/bruce/PythonModules/data/kp3.png") # png from KidPix [also on g5] -- fails, unknown raw mode ###BUG # fyi, PIL reports (512, 512), 'RGBA'; converting it is likely to work; generalizing to use 'A' in texture would be better. #e testexpr_11q10x2 = imagetest_x2("/Users/bruce/PythonModules/data/kp3.png") # works testexpr_11q11 = imagetest("/Users/bruce/PythonModules/data/textil03.jpg") # a tiling texture from the web -- works testexpr_11q11a = imagetest("/Users/bruce/PythonModules/data/textil03.jpg", clamp=False) # try that with tiling effect -- works! testexpr_11q12 = imagetest("/Users/bruce/PythonModules/data/dock+term-text.png") # a screenshot containing dock icons -- works # try differently-resized images [using new features 061127, Image options rescale = False, ideal_width = 128, ideal_height = 128] ###e rename ideal_width -> tex_width?? not sure. decide later. poss name conflict. # [note, the texture size used in the above tests used to depend on a debug pref, default 256 but 512 on g4; # it is now 256 by default but can be passed as option to Image; RETEST (for that and for revised implem)] testexpr_11r1 = Image(blueflake, rescale = False) # works; I can't really tell whether I can detect smaller texture size (256 not 512) testexpr_11r1b = Image(blueflake, rescale = False, ideal_width = 512, ideal_height = 512) # works, but note unexpected black border on left testexpr_11r1c = SimpleRow(testexpr_11r1, testexpr_11r1b) # works (but not aligned or even at same scale -- hard to compare) testexpr_11r2 = Image("redblue-34x66.png", rescale = False) # works, except the desired image is in upper left corner of black padding, # not lower left as expected, and maybe some filtering happened when it pasted, # and the black padding itself is destined to be undrawn ###BUG that some of that is nim ##e testexpr_11r2b = Image("redblue-34x66.png") # works (rescaled to wider aspect ratio, like before) testexpr_11s = Translate(Image("blueflake.png",size=Rect(7,0.4)),(1,0)) # try the new size option [061130] -- works [broken] [works again] testexpr_11s1 = Highlightable(Image("blueflake.png",size=Rect(7,0.4))) # make sure this fixes mouseover stickiness and sbar text -- works [broken] [works again] testexpr_11s2 = Boxed(Image("blueflake.png",size=Rect(7,0.4))) # test its lbox -- won't work? coded a fix, but that broke the use of size entirely!! [fixed, works] testexpr_11t = imagetest("storyV3-p31.tiff") # 070222; local to bruce G5 (not in cvs); -- fails, IOError: cannot identify image file testexpr_11tx = imagetest("storyV3-p31x.tiff") # different error -- that means _11t finds the file and can't load it -- why? testexpr_11t_png = imagetest("storyV3-p31.png") # 070228 -- tryit -- fails: ###BUG: ##fyi: following exception relates to <PngImagePlugin.PngImageFile instance at 0xf799648> with mode 'RGBA' ##(exception in <Lval at 0xf7992b0>._compute_method being reraised) ##bug: exception in <Overlay#18217(i)>.drawkid(<Image#18220(i)>): exceptions.SystemError: unknown raw mode ## [instance_helpers.py:949] [images.py:283] [images.py:273] [images.py:109] [ExprsMeta.py:272] [ExprsMeta.py:382] ## [lvals.py:170] [lvals.py:210] [images.py:91] [testdraw.py:743] [ImageUtils.py:151] [Image.py:439] [Image.py:323] #e try jpg too? testexpr_11u = imagetest("storyV4b-p15.png") #070304 -- works, poor res -- see also imagetest_x2, IconImage testexpr_11u2 = Image("storyV4b-p15.png", rescale = False, use_mipmaps = True) # works, poor res # are their opts to use the real sizes or must i always do it manually? testexpr_11u3 = Image("storyV4b-p15.png", use_mipmaps = True) # works, poor res testexpr_11u4 = Image("storyV4b-p15.png", use_mipmaps = True, ideal_width = -1, ideal_height = -1) # works, but aspect ratio wrong # fyi: before the new feature letting -1 mean native size [kluge070304, ###UNTESTED] it failed like this: ## bug: exception in <Overlay#31692(i)>.drawkid(<Image#31695(i)>): exceptions.MemoryError: ## [instance_helpers.py:949] [images.py:283] [images.py:273] [images.py:109] [ExprsMeta.py:272] [ExprsMeta.py:382] ## [lvals.py:170] [lvals.py:210] [images.py:91] [testdraw.py:743] [ImageUtils.py:142] [ImageUtils.py:182] [Image.py:1051] ## .*** malloc_zone_calloc[2545]: arguments too large: 4294967295,4 testexpr_11u5 = Image("storyV4b-p15.png", use_mipmaps = True, ideal_width = -1, ideal_height = -1, rescale = False) # same # rescale would only affect how it got fit into the ideal tex size -- so with native size used, it makes no difference. # what we need is to make the displayed size fit the native size. # we can grab the native size once we have this image... let's define NativeImage in images.py to do this. testexpr_11u6 = NativeImage("storyV4b-p15.png") # works! except fuzzier than expected (maybe PIXELS is wrong?), # and alignment is not as I expected # (topright of image is at origin, as if I said TopRight instead of Center for the Image size option inside NativeImage). #e see also testexpr_13z2 etc ##e want to try: gif; pdf; afm image, paul notebook page (converted); # something with transparency (full in some pixels, or partial) # ####e We could also try different code to read the ones that fail, namely, QImage or QPixmap rather than PIL. ## try it # test Spacer [circa 061126] testexpr_12 = SimpleRow( Rect(4, 2.6, blue), Spacer(4, 2.6, blue), Rect(4, 2.6, blue)) # works testexpr_12a = SimpleColumn( testexpr_12, Spacer(4, 2.6, blue), Rect(4, 2.6, blue)) # works testexpr_12b = SimpleColumn( testexpr_12, Spacer(0), Rect(4, 2.6, green), pixelgap = 0) # works # test PixelGrabber -- not fully implemented yet (inefficient, saves on every draw), and requires nonrotated view, all on screen, etc testexpr_13 = PixelGrabber(testexpr_12b, "/tmp/pgtest_13.jpg") # lbox bug... [fixed now] # worked, when it was a partial implem that saved entire glpane [061126 830p] testexpr_13x1 = Boxed(testexpr_12b) # ... but this works, as if lbox is correct! hmm... testexpr_13x2 = PixelGrabber(testexpr_13x1, "/tmp/pgtest_13x2.jpg") # works the same (except for hitting left margin of glpane) [fixed now] testexpr_13x3 = Boxed(Translate(testexpr_12b, (1,1))) # works testexpr_13x4 = Boxed(Translate(Translate(testexpr_12b, (1,1)), (1,1))) # works testexpr_13x5 = Boxed(Boxed(Translate(Translate(testexpr_12b, (1,1)), (1,1)))) # works -- not sure how! [because Boxed is not Widget2D] testexpr_13x6 = Boxed(PixelGrabber(testexpr_12b)) # predict PixelGrabber lbox will be wrong, w/ shrunken Boxed -- it is... fixed now. testexpr_13x7 = Boxed(PixelGrabber(Rect(1,1,red))) # simpler test -- works, saves correct image! no bbottom bug here... testexpr_13x8 = Boxed(PixelGrabber(SimpleColumn(Rect(1,1,red),Rect(1,1,blue)))) # this also had lbox bug, now i fixed it, now works. # It was a simple lbox misunderstanding in PixelGrabber code. [###e maybe it means lbox attr signs are wrongly designed?] savedimage = "redblue-34x66.png" ## was "/tmp/PixelGrabber-test.jpg" - use that too but not as a "test" since it's not deterministic; ## it'd actually be a "command to see the last PixelGrabber test which saved into the default file" testexpr_13z = Boxed(bordercolor=purple)(Image(savedimage)) # works, but aspect ratio wrong -- that's a feature for now... testexpr_13z2 = Boxed(color=purple)(Image(savedimage, rescale = False)) # works (with padding etc for now) ####e make this the default? testexpr_13z3 = Boxed(color=purple)(Image(savedimage, rescale = False, ideal_width = 128, ideal_height = 128)) # works testexpr_13z4 = Boxed(color=purple)(Image(savedimage, rescale = False, ideal_width = 64, ideal_height = 64)) # will rescale... yes. # note that it prints a debug warning that it can't do as asked # try non-power-of-2 texture sizes (not confirmed that's what's actually being given to us; should get ImageUtils to tell us ####e) testexpr_13z5 = Boxed(color=purple)(Image(savedimage, rescale = False, ideal_width = 36, ideal_height = 68)) # works on g4: non-2pow sizes -- but aspect ratio is wrong ###BUG?? testexpr_13z6 = Boxed(color=purple)(Image(savedimage, rescale = False, ideal_width = 34, ideal_height = 66)) # ditto -- ###BUG?? ###BUG - in some above, purple is showing as white. ah, option name is wrong. revise it in Boxed?? probably, or add warning. ##e # try out a table of icons (notation is not very nice though...) # [note: this code to setup testexpr_14 all runs even if we don't display that test, # but the images won't load [that's verified] so it shouldn't be too slow] hide_icons = """ anchor-hide.png gamess-hide.png measuredihedral-hide.png moltubes-hide.png atomset-hide.png gridplane-hide.png measuredistance-hide.png molvdw-hide.png displayCylinder-hide.png ground-hide.png molcpk-hide.png rmotor-hide.png displaySurface-hide.png linearmotor-hide.png moldefault-hide.png stat-hide.png espimage-hide.png lmotor-hide.png molinvisible-hide.png thermo-hide.png espwindow-hide.png measureangle-hide.png mollines-hide.png """.split() # 23 icons if 1: # test the corresponding non-hidden icons instead -- works hide_icons = map(lambda name: name.replace("-hide",""), hide_icons) for another in "clipboard-empty.png clipboard-full.png clipboard-gray.png".split(): hide_icons.append(another) pass # how do you take 4 groups of 6 of those? we need a utility function, or use Numeric reshape, but for now do this: res = [] ## moved into images.py: ## IconImage = Image(ideal_width = 22, ideal_height = 22, convert = True, _tmpmode = 'TIFF') # size 22 MIGHT FAIL on some OpenGL drivers # now in basic: nevermind = lambda func: identity for i in range(5): # 4 is enough unless you set 'if 1' above res.append([]) for j in range(6): res[i].append(None) # otherwise, IndexError: list assignment index out of range try: res[i][j] = hide_icons[i * 6 + j] res[i][j] = IconImage(res[i][j]) if not ((i + j ) % 3): # with 3 -> 2 they line up vertically, but that's only a coincidence -- this is not a real Table. pass ## res[i][j] = Boxed(res[i][j]) except IndexError: res[i][j] = nevermind(Boxed)(Spacer(1 * PIXELS)) ## None ###e Spacer should not need any args to be size 0 continue continue testexpr_14 = SimpleColumn( * map(lambda row: nevermind(Boxed)(SimpleRow(*row)), res) ) # works! testexpr_14 = Translate(testexpr_14, V(-1,1,0) * 2) testexpr_14x = SimpleColumn(*[Rect(2 * i * PIXELS, 10 * PIXELS) for i in range(13)]) # works (so to speak) -- 11th elt is TextRect("too many columns") ####e i need that general warning when there are too many args!! testexpr_14x2 = SimpleRow(*[Rect(2 * i * PIXELS, 10 * PIXELS) for i in range(13)]) # works -- TextRect("too many rows") # ChoiceButton (via ChoiceColumn, a convenience function to call it, which ought to be redesigned and made an official expr too #e) # summary, 061130 1015p: mostly works, except for bugs which are not its fault, namely TextRect hit test, # speed/sync of selobj update (guess at cause of sometimes picking wrong one after fast motion), # selobj-changeover effects (guess at cause of sbar_text not working after a click and no motion off the object) testexpr_15 = ChoiceColumn(6,2) # doesn't work - click on choice only works if it's the one that's already set (also color is wrong) ## ( nchoices, dflt = 0, **kws), kws can be content, background, background_off ## make_testexpr_for_ChoiceButton() testexpr_15a = ChoiceColumn(6,2, background = Rect(3,1,green), background_off = Rect(2,1,gray)) # almost works -- you can click on any choice, but only for click over area of gray rect, # including the part behind the text, but not for click over other part of text # (and maybe this is the text click bug i recalled before, didn't resee in toggleshow, but there the text is over the grayrect??) # possible clue: for mouseover sbar msg, there is hysteresis, you see it in text not over rect iff you were seeing it before # (from being over rect), not if you come directly from blank area. #k is same true of whether click works? yes! # another clue: if you move mouse too fast from blank to rect to text not over rect, you don't get sbar msg. # you have to hover over the good place and wait for redraw and see it, only then move out over the "suspended" part # (text not over rect, hanging instead over infinite depth empty space). # see also bug comments in controls.py. testexpr_15b = ChoiceColumn(6,2, background = Rect(3,1,green), background_off = IconImage("espwindow-hide.png")) ##e ChoiceColumn should be an InstanceMacro, not a def! doesn't work to be customized this way. ## testexpr_15cx = testexpr_15b(background = Rect(3,1,red)) -- ###BUG? missing errmsg? somehow it silently doesn't work. ##niceargs = ChoiceColumn(background = Rect(3,1,green), background_off = IconImage("espwindow-hide.png")) # error, not enough args ##testexpr_15cy = niceargs(6,2) niceargs = dict(background = Rect(3,1,green), background_off = IconImage("espwindow-hide.png")) testexpr_15c = ChoiceColumn(6,2, content = TextRect("zz",1,30), **niceargs) # bug more likely at far right end of text, but not consistent testexpr_15d = ChoiceColumn(6,2, content = Rect(7,0.3,white), **niceargs) # compare Rect here -- works, reliable except right after click [which is a ###BUG] testexpr_15e = ChoiceColumn(6,2, content = Translate(Image("blueflake.png",size=Rect(7,0.4)),(1,0)), **niceargs) # compare Image -- works # see also _22 # State [061203] class toggler(InstanceMacro): var = State(int, 0) _value = Highlightable( list_Expr( # if you use [] directly, you get TypeError: list indices must be integers (of course) Rect(1,1,red), Rect(1,1,green), Rect(1,1,blue), )[ mod_Expr(var,3) ], #e do we want a nicer syntax for this, as simple as If which you can only use when 3 is 2? Case or Switch? on_press = Set(var, var+1) ) pass testexpr_16 = SimpleRow(toggler(), toggler()) # works # as of 061204 this works, even tho State & Set are not completely implemented (and I predict bugs in some uses) checkbox_image = IconImage(ideal_width = 25, ideal_height = 21, size = Rect(25 * PIXELS, 21 * PIXELS)) # note, IconImage ought to use orig size in pixels but uses 22x22, # and ought to display with orig size but doesn't -- all those image options need reform, as its comments already know ###e class checkbox_v1(InstanceMacro): var = State(int, 0) #e bool, False? _value = Highlightable( list_Expr( checkbox_image('mac_checkbox_off.png'), checkbox_image('mac_checkbox_on.png'), )[ mod_Expr(var,2) ], #e or use If on_press = Set(var, mod_Expr(var+1,2) ) #e or use not_Expr ) pass testexpr_16a = SimpleColumn( SimpleRow(checkbox_v1(), TextRect("option 1",1,10)), SimpleRow(checkbox_v1(), TextRect("option 2",1,10)), ) # works class checkbox_v2(InstanceMacro): # this is now copied into controls.py, but it's probably to be renamed and revised there, so leave this test here defaultValue = Option(bool, False) var = State(bool, defaultValue) #e need to be able to specify what external state to use, eg a prefs variable # (but i don't know if the arg or option decl can be part of the same decl, unless it's renamed, e.g. StateArg) _value = Highlightable( If( var, checkbox_image('mac_checkbox_on.png'), checkbox_image('mac_checkbox_off.png'), ), on_press = Set(var, not_Expr(var) ) ) pass testexpr_16b = SimpleColumn( SimpleRow(checkbox_v2(), TextRect("option 1a",1,10)), #e need to be able to specify specific external state, eg a prefs variable SimpleRow(checkbox_v2(defaultValue = True)(), TextRect("option 2a",1,10)), # that 2nd () is to tell it "yes, we supplied args" ) # works testexpr_16c = SimpleColumn( # [later: see also kluge_dragtool_state_checkbox_expr, similar to this with different prefs_key] SimpleRow(checkbox_v3(PrefsKey_StateRef(displayOriginAxis_prefs_key)), # test: specify external state, eg a prefs variable ###e would this look better? checkbox_v3(prefs_key = displayOriginAxis_prefs_key) TextRect("display origin axis",1,20)), ) # works! (changes the axis display) # an older implem doesn't work yet, see comments in controls.py # note: if prior verson of _16c diff implem of _v3) failed first in same session, then in this good test or a prior good test # being retried, we'd see a double-inval warning for glpane (something called standard_inval twice). But if no error in same session # then I never saw this. # == dragging (e.g. on_drag) testexpr_17 = Highlightable(Rect(), on_drag = print_Expr("on_drag happened")) # works, but trivial (only prints) # testexpr_17a was moved below and renamed to testexpr_19 # == demo_MT testexpr_18 = MT_try1( _my.env.glpane.assy.part.topnode ) # works! except for ugliness, slowness, and need for manual update by reloading. #e Still need to test: changing the current Part. Should work, tho manual update will make that painful. ###e need better error message when I accidently pass _self rather than _my] testexpr_18a = test_drag_pixmap( _my.env.glpane.assy.w.mt, _my.env.glpane.assy.part.topnode ) # nim, otherwise works -- debug prints testexpr_18i = MT_try2( _my.env.glpane.assy.part.topnode ) #070207 # == more dragging testexpr_19 = GraphDrawDemo_FixedToolOnArg1(Rect(10)) # works ## testexpr_17a = testexpr_19 # alias, remove soon # [for current status see comments just before GraphDrawDemo_FixedToolOnArg1] testexpr_19a = GraphDrawDemo_FixedToolOnArg1(Overlay(Rect(10),Sphere(1.5))) # works testexpr_19b = GraphDrawDemo_FixedToolOnArg1(Overlay(Rect(10),SimpleRow(Sphere(1.5),Sphere(2)))) # works # note that you can interchange the guide shapes at runtime, and retain the drawing which was done with their aid. # (just by editing this file's choice of testexpr, and clicking to reload it) testexpr_19c = Overlay( testexpr_19b, # edit this one by hand if you want Translate( kluge_dragtool_state_checkbox_expr, (6,-4) ) ###e need to wrap this with "draw at the edge, untrackballed" ) # later 061213: # [070326 adding PM_CORNER w/o retesting most of them -- note, since PM_CORNER is variable, this is not a test of DrawInCorner, # but a test of other things which assumes that DrawInCorner works well enough that the corner choice can't affect the testing.] testexpr_19d = Overlay( testexpr_19b, DrawInCorner(Boxed(kluge_dragtool_state_checkbox_expr), PM_CORNER) ) # (works but highlight-sync bug is annoying) -- after some changes inside 061214, still works testexpr_19e = Overlay( GraphDrawDemo_FixedToolOnArg1( Rect(9), highlight_color = green), # this is the new (and only current) test of background.copy(color=green) experiment [061214] DrawInCorner(Boxed(kluge_dragtool_state_checkbox_expr)), PM_CORNER ) # ugly color, but works # later 070106: (syntax is a kluge; see also testexpr_26) testexpr_19f = eval_Expr( call_Expr( lambda thing: Overlay( thing, DrawInCorner( Boxed( eval_Expr( call_Expr( demo_drag_toolcorner_expr_maker, thing.world )) ), PM_CORNER ) ), testexpr_19b )) # This is not a valid example for EVAL_REFORM (and indeed it fails then): # testexpr_19b is not instantiated (when we eval the call_Expr and ask for thing.world) but needs to be. # Since this whole syntax was a kluge, I should not worry much about making it or something similar still work, # but should instead make a better toplevel syntax for the desired effect, and make *that* work... for that, see lambda_Expr.py. ###e # So for the time being I won't try to fix this for EVAL_REFORM. # (At one time it didn't work without EVAL_REFORM unless testbed was enabled. I'm guessing that was an old bug (predating EVAL_REFORM) # and I fixed it -- for details see cvs revs prior to 1.202 (Qt3 branch).) # hmm, what would happen if we just tried to tell it to instantiate, in the simplest way we might think of? # It may not work but it just might -- at least it'll be interesting to know why it fails... [070122 945a] # fails because Instance wants to make one using _self._i_instance, but _self has no binding here, evals to itself. testexpr_19g_try1_fails = eval_Expr( call_Expr( lambda thing: Overlay( thing, DrawInCorner( Boxed( eval_Expr( call_Expr( demo_drag_toolcorner_expr_maker, thing.world )) ), PM_CORNER ) ), Instance(testexpr_19b) )) # Is there a sensible default binding for _self? In this lexical place it might be "the _app, found dynamically"... # but to be less klugy we want to make Instance work differently here... or use a different thing to make one... # or make Instance an expr. Or at least give it a helper func to have a backup for _self._i_instance failing or _self having no value. # But as a test I can just manually insert whatever would work for that... hmm, how about this: [later: see also testexpr_30g] testexpr_19g = eval_Expr( call_Expr( lambda thing: Overlay( thing, DrawInCorner( Boxed( eval_Expr( call_Expr( demo_drag_toolcorner_expr_maker, thing.world )) ), PM_CORNER ) ), ## _app._i_instance(testexpr_19b) # safety rule: automatic formation of getattr_Expr not allowed for attrs starting _i_ call_Expr( _app.Instance, testexpr_19b, "#19b") )) # works now, after some bugfixes [070122] testexpr_19haux = GraphDrawDemo_FixedToolOnArg1(Overlay(testexpr_11q1b(size = Rect(10)), SimpleRow(Sphere(2),Sphere(1),Sphere(0.5),Sphere(0.25)))) testexpr_19h = eval_Expr( call_Expr( lambda thing: Overlay( thing, DrawInCorner( Boxed( eval_Expr( call_Expr( demo_drag_toolcorner_expr_maker, thing.world )) ), PM_CORNER ) ), call_Expr( _app.Instance, testexpr_19haux, "#19h") )) # 070223 -- works testexpr_19i = eval_Expr( call_Expr( lambda world_ui: Overlay( world_ui, DrawInCorner( Boxed( eval_Expr( call_Expr( demo_drag_toolcorner_expr_maker, world_ui.world )) ), PM_CORNER ), DrawInCorner( MT_try2(getattr_Expr(world_ui, 'world')), WORLD_MT_CORNER ), ), call_Expr( _app.Instance, testexpr_19haux, "#19h") )) # 070227 # note, this is now the same as _30i except for demo_drag_toolcorner_expr_maker and the fact that it wants .world of its arg -- # AND for the type of object it needs as the world_ui! (that's the worst difference, since the ops it needs are different.) # See also testexpr_19j, once imported far below, now removed. But don't reuse the name. # == test testmode._background_object [070322] testexpr_19Qaux = GraphDrawDemo_FixedToolOnArg1( Rect(10), test_background_object = True) testexpr_19Q = eval_Expr( call_Expr( lambda world_ui: Overlay( world_ui, DrawInCorner( Boxed( eval_Expr( call_Expr( demo_drag_toolcorner_expr_maker, world_ui.world )) ), PM_CORNER ), DrawInCorner( MT_try2(getattr_Expr(world_ui, 'world')), WORLD_MT_CORNER ), ), call_Expr( _app.Instance, testexpr_19Qaux, "#19Q") )) # works! (you can draw polylines on empty space just as well as on the gray rect) testexpr_19Q2 = BackgroundObject( DraggableObject(Rect()) ) # works. (drag in empty space moves it; click selects it; no sbar text tho) testexpr_19Q3aux = GraphDrawDemo_FixedToolOnArg1( Rect(10), test_background_object = True, hide_background_object = True) testexpr_19Q3 = eval_Expr( call_Expr( lambda world_ui: Overlay( world_ui, DrawInCorner( Boxed( eval_Expr( call_Expr( demo_drag_toolcorner_expr_maker, world_ui.world )) ), PM_CORNER ), DrawInCorner( MT_try2(getattr_Expr(world_ui, 'world')), WORLD_MT_CORNER ), ), call_Expr( _app.Instance, testexpr_19Q3aux, "#19Q3") )) # works (like _19Q but no gray rect) # == DrawInCorner def func(text, color, corner): color1 = ave_colors(0.6,white,color) color2 = ave_colors(0.1,white,color) return DrawInCorner( Boxed( SimpleColumn( TextRect(text,1,11), Highlightable(Rect(1,1,color1),Rect(1,1,color2)))) , corner) testexpr_20 = Overlay( Rect(1,1,purple), func('lower left', red, (-1,-1)), func('upper left', green, (-1,1)), func('lower right', black, (1,-1)), func('upper right', blue, (1,1))) # works -- except for textrect size when I rotate the trackball, and it's intolerably slow to highlight. # (why slow? chopping out TextRect speeds it somewhat, but it's still slow. ###e SHOULD COMPARE to same stuff drawn in center.) testexpr_20a = Overlay( ##Rect(1,1,purple), func('lower left', red, (-1,-1)), func('upper left', green, (-1,1)), func('lower right', black, (1,-1)), func('upper right', blue, (1,1))) # == alignment exprs [061211] def wrap1(alignfunc): return Boxed(alignfunc(Rect())) testexpr_21 = Boxed(SimpleColumn(wrap1(Left), wrap1(Center), wrap1(Right))) # works testexpr_21a = Boxed(SimpleRow(wrap1(Left), wrap1(Center), wrap1(Right))) # works testexpr_21b = Boxed(SimpleColumn(wrap1(TopRight), wrap1(CenterRight), wrap1(BottomRight))) # might work but hard to interpret testexpr_21c = Boxed(SimpleRow(wrap1(TopRight), wrap1(CenterRight), wrap1(BottomRight))) # ditto # the following testexpr_21d & _especially _21e are examples of toplevel code we need to figure out how to simplify. #### def aligntest(af): """ [af should be an alignment func (class) like Center] """ try: def doit(n): return af(Translate(Rect(n),(-n/3.0,-n/3.0))) return Overlay(BottomRight(TextRect(af.__name__)), BottomLeft(Boxed(SimpleRow(doit(0.4), doit(0.6), doit(0.9) ))), TopRight(Boxed(SimpleColumn(doit(0.45), doit(0.65), doit(0.95) ))) ) except: print sys.exc_info() ##k return BottomRight(TextRect('exception discarded') )#e find a way to include the text? def aligntest_by_name(afname): try: af = getattr(Center_module, afname) res = aligntest(af) worked = True #e or a version counter?? to be correct, i think it needs one [070122] except: res = BottomRight(TextRect("didn't work: %r" % afname,1,30)) worked = False ## return res return local_ipath_Expr( (worked,afname), res) # try local_ipath_Expr as a bugfix for _21e/_21g in EVAL_REFORM, 070122 -- partly works (fully after we have Expr.__eq__); # for details see long comment in _21g. testexpr_21d = aligntest(Center) colwords = ('Left', 'Center', 'Right', '') rowwords = ('Top', 'Center', 'Bottom', '') ## choiceref_21e = LocalVariable_StateRef(str, "") ###k ok outside anything? it's just an expr, why not? but what's it rel to? var name??? # answer: each instance has its own state, so it won't work unless shared, e.g. in InstanceMacro or if we specify sharing somehow. choiceref_21e = PrefsKey_StateRef("A9 devel scratch/testexpr_21e alignfunc5", 'Center') # need a non-persistent variant of this... ###e # later note: choiceref_21e (constructed by PrefsKey_StateRef) is an expr, not yet an instance. def mybutton(xword, yword, choiceref): # later note: choiceref is really choiceref_expr, not yet an instance. word = yword + xword if word == 'CenterCenter': word = 'Center' elif word == 'Center': ## word = (xword or 'Y') + (yword or 'X') -- oops, wrong order (YCenter) if not xword: word = yword + 'Y' # i.e. CenterY elif not yword: word = xword + 'X' # CenterX if not word: return Spacer() return ChoiceButton(word, choiceref, content = TextRect( format_Expr("%s", _this(ChoiceButton).choiceval), 1,12 ) ) table_21e = SimpleColumn(* [SimpleRow(* [mybutton(colword, rowword, choiceref_21e) for colword in colwords]) for rowword in rowwords]) testexpr_21e = Translate( Overlay( eval_Expr( call_Expr( aligntest_by_name, getattr_Expr( ## choiceref_21e, ###BUG in EVAL_REFORM noticed 070122 -- see below for fix-attempt call_Expr( _app.Instance, choiceref_21e, 'testexpr_21e.choiceref_21e'), # try this 070122 -- fixes it except for "bug: expr or lvalflag for instance changed", same as same change # does for testexpr_21g, so for now I'm only doing further work in testexpr_21g. [fully fixed there & here, eventually] 'value'))) , TopLeft( Boxed(table_21e)) ), (-6,0) ) # non-EVAL_REFORM: works, IIRC. # EVAL_REFORM [070122]: mostly works after bugfixes, same as _21g (which see). # Later, works fully now, due to new Expr.__eq__, same as _21g. At all bugfix-stages (3 fixes I think) these egs behaved the same, # tho in some cases they needed different variants of the same bugfix-change. [070122 late] # all 15 primitives in the table are defined and working as of 061211 eve testexpr_21f = Boxed( identity(Center)( Rect(2,3.5,purple))) # test lbox translation by Center -- works # (implem of lbox shift is in Translate, so no need to test all alignment prims if this works) class class_21g(DelegatingInstanceOrExpr): # see how far I can simplify testexpr_21e using an expr class [061212] choiceref_21g = Instance( PrefsKey_StateRef("A9 devel scratch/testexpr_21g alignfunc", 'Center') ) #070122 bugfix for EVAL_REFORM # note: this is an expr. In current code [061212]: it's implicitly instantiated, i think. # In planned newer code [i think]: you'd have to explicitly instantiate it if it mattered, # but it doesn't matter in this case, since this expr has no instance-specific data or state. # update 070122 -- indeed, it fails in EVAL_REFORM. Partly fixed by Instance above (the "it doesn't matter" above is nim ###e). # For more of the fix see comments of this date below. [fully fixed now] colwords = ('Left', 'Center', 'Right', '') rowwords = ('Top', 'Center', 'Bottom', '') ## xxx = TextRect( format_Expr("%s", _this(ChoiceButton).choiceval), 1,12 ) #k is _this ok, tho it requires piecing together to work? # no, see comment "IT WILL FAIL" -- and indeed it does: ## AssertionError: _this failed to find referent for '_this_ChoiceButton' (at runtime) def mybutton_CANTWORK(self, xword, yword): # an ordinary method -- return an expr when asked for one - but does require self to run, THOUGH IT OUGHT NOT TO #k (should we make it into a classmethod or staticmethod? yes, see below) word = yword + xword if word == 'CenterCenter': word = 'Center' elif word == 'Center': if not xword: word = yword + 'Y' # i.e. CenterY elif not yword: word = xword + 'X' # CenterX if not word: return Spacer() ###k is it ok that this returns something that was constructed around self.choiceref_21g, # a saved choiceref instance, the same instance each time this runs (for different args)? # reiterating the above comment about the choiceref_21g attr def: # current code: yes, sharing that instance is ok # planned new code: it will be including an expr anyway, tho hopefully one with the optim-power # to cache instantiated versions on self if it so desires... this might mean self.choiceref_21g # is a "sharable partly-instantiated-as-appropriate-for-self thing", able to be anything in # between instance and expr. (But what if it was a number vs a number-producer?? #k) ###k what about for self.xxx? # In planned new code, it's just an expr, so we're fine (given that we're returning "just an expr"). # In current code, it will eval to an instance... # _this might fail now, fail later (my guess), or work later. # But the instance is the same for each button, which is definitely wrong. SO IT WILL FAIL.###BUG return ChoiceButton(word, self.choiceref_21g, content = self.xxx ) # this next is supposed to be an expr dependent only on this class... but it can't be if mybutton gets choiceref_21g via self. # so fix that: def mybutton(xword, yword, choiceref): ## , xxx): # staticmethod, but only after direct use as function word = yword + xword if word == 'CenterCenter': word = 'Center' elif word == 'Center': if not xword: word = yword + 'Y' # i.e. CenterY elif not yword: word = xword + 'X' # CenterX if not word: return Spacer() ## return ChoiceButton(word, choiceref, content = xxx ) return ChoiceButton(word, choiceref, content = TextRect( format_Expr("%s", _this(ChoiceButton).choiceval), 1,12 ) ) # now pass what we need to mybutton, direct from the class namespace -- will this work now, or do we need to do it before the staticmethod call?? # yes, we got TypeError: 'staticmethod' object is not callable until we did that table_21g = SimpleColumn(* [SimpleRow(* [mybutton(colword, rowword, choiceref_21g) for colword in colwords]) for rowword in rowwords]) mybutton = staticmethod(mybutton) # this statement could just as well be 'del mybutton', i think del mybutton #k ok? # the following required compromises with current code: # getattr_Expr, eval_Expr, no xxx in mybutton call above (due to _this vs autoinstantiation). delegate = Overlay( eval_Expr( call_Expr( aligntest_by_name, getattr_Expr(choiceref_21g, 'value') )) , ###BUG in EVAL_REFORM noticed 070122: theory: this expr gets recomputed when the getattr_Expr's someobj.value is changed (correct), # but the index assigned to it does not change (even though it includes components from the changed expr, which would change # if it was due to an If that the expr changed). Symptom: "bug: expr or lvalflag for instance changed", and no update of the # alignment demo display (both behaviors same as for _21e -- after both of them got a new manual Instance to fix a worse bug). # This bug was predicted by a comment in class eval_Expr regarding changes in its argval (in this case, an expr constructed # and returned by our ad-hoc external function, aligntest_by_name). # # Maybe refile these comments into class eval_Expr: ##e # # The best fix would probably be to invalidate the instance at that fixed index, letting the index stay fixed, saying it's ok # for the expr there to change. This requires inval access to the LvalDict2 used by _CV__i_instance_CVdict. # It's best because it'll take care of all cases of "bug: expr or lvalflag for instance changed", # albeit sometimes inefficiently. The details of how to best do this inval (by usage/change tracking of the expr) # are not trivial... not yet worked out. ###e # # Another fix might be to wrap a varying part of this expr with some fixed Instance which absorbs the change. # (That wrapper might need the previous fix internally, but it might be more efficient if the varying part # was smaller than it is now.) Not worked out. ###e # # Another fix might be to add something unique to the local ipath mods from this retval. I'm not sure this can work, # since the innermost differing retval is not a pure expr -- unless I add it in an ad-hoc way to something outside that -- # which is a useful thing to be able to do, even if not the best general fix for this example. It could be done by a # toplevel use of something like lexenv_ipath_Expr (perhaps inside aligntest func itself), or by an option to eval_Expr. # Note that if the goal is indeed to memoize any variants of this varying expr, but to be conservative about how much # gets memoized, then this is the only principled fix. So on those grounds I'll try it by using the new local_ipath_Expr # in aligntest_by_name. # This fix works fine in both _21e and this _21g, except that "bug: expr or lvalflag for instance changed" # is still printed when equal but not identical exprs are seen at the same index (i.e. whenever we try any choice for the 2nd # time (since remaking the main instance). In this case it doesn't indicate a real bug -- except that pure-expr equality should # be based on formal structure, not pyobj identity. Now that's fixed by a new Expr.__eq__ (except for loose ends documented # in a comment there), and testexpr_21g seems to work fully now. # [older comments, not reviewed on 070122:] # predict failure here in .value, until I re-add getattr_Expr [and then? works] # yes, it failed, but I didn't predict the exact manner: AssertionError: compute method asked for on non-Instance <PrefsKey_StateRef#105377(a)> # and i'm unsure if it's equiv to what i predicted... ##k # I think ExprsMeta scanner makes choiceref_21g symbolic -- but, too late to help? YES, ###BUG, unless we wrap the def above with something # to make it symbolic, even if we needn't wrap it with something to instantiate it. # And I think the eval_Expr requirement isn't affected by being in a class. And I think the next line TopLeft( Boxed(table_21g)) will still work, # UNLESS replacement of table_21g with _self.table_21g causes trouble (not sure). #k likely BUG -- but seems to work ok for some reason... aha, # it's because _self.table_21g evals to what's already an instance, since all exprs as class attrs become instances as self attrs in current code. # In planned new code it will also work, with table_21g staying an expr until used (or explicitly type-coerced or instantiated). TopLeft( Boxed(table_21g)) ) pass testexpr_21g = Translate( class_21g(), (-6,0) ) # works [061212 154p]; works in EVAL_REFORM [after 3 bugfixes, 070122] # == ##niceargs = dict(background = Rect(3,1,green), background_off = IconImage("espwindow-hide.png")) ##testexpr_15c = ChoiceColumn(6,2, content = TextRect("zz",1,30), **niceargs) # bug more likely at far right end of text, but not consistent ##testexpr_15d = ChoiceColumn(6,2, content = Rect(7,0.3,white), **niceargs) # compare Rect here -- works, reliable except right after click [which is a ###BUG] ##testexpr_15e = ChoiceColumn(6,2, content = Translate(Image("blueflake.png",size=Rect(7,0.4)),(1,0)), **niceargs) # compare Image -- works testexpr_22 = DrawInCorner(ChoiceRow(6,2), (1,-1)) # works! (though default options are far from perfect) # see also kluge_dragtool_state_prefs_default and _19* # == test DisplayListChunk ##BUG in general when not wrapped directly around translated Highlightable, or when an HL is trackballed. # Most of these are not marked as indiv ##BUGs. testexpr_23 = DisplayListChunk(Rect(1,green)) # might work testexpr_23x = DisplayListChunk(Rect(1,green), debug_prints = "dlc1") # might work # try to detect the speedup of trackball or animated rotation. some of these may fail immediately due to highlighting issue. # (remember to turn off testbed for speed tests.) testexpr_23a1 = TextRect("hjfdfhjksdhfkjafhjksdhfkafdftftytudyufdyufua\n" * 26, max_lines = 100, max_cols = 100) # works testexpr_23a2 = DisplayListChunk(testexpr_23a1) # works -- *much* faster (as eyeballed using rotate view 90) # WHY does this not fail due to highlighting issue? Maybe TextRect is not natively highlightable. Ah, that must be it. testexpr_23a1h = Highlightable(testexpr_23a1) # works testexpr_23a2h = DisplayListChunk(testexpr_23a1h) # doesn't crash, and even its highlighting sbar msg works! WHY??? #### # At least it does have a bug -- the highlight is drawn in the home position of the main thing, ignoring trackball rot/shift. # Guess: loading the matrix doesn't fail while compiling a displist, it just loads the wrong matrix. # If so (and if indep of opengl driver), I can leave this unfixed until I need highlighting behavior inside one of these. # (It also suggests a kluge fix: load the matrix for real, by disabling displist, once each time the local coords change! # Some experiments suggest this might work. Hmm. ##### THINK WHETHER THIS COULD WORK -- no, inefficient, needed for all objs. # Or is it only needed for "candidates found by glselect"?? Hmm.... #####) # This may also mean it can work fine for exprs that are shown in fixed places, like widgets in our testbed. # I suspect it may have another highlighting bug besides coords, namely, in use of a different appearance for highlighting. # But it turns out it doesn't. Later: I guess that's because in DisplayListChunk(Highlightable(...)), the draw_in_abs_coords # is called directly on the inner Highlightable, so the displist is only used when running the usual draw on the whole thing. testexpr_23b = testexpr_9c(fakeoption=0) # customize it just to make it nonequal - works testexpr_23bh = DisplayListChunk(testexpr_9c) # sort of works - top rect works except for coords, bottom rect doesn't work at all, # maybe [wrong] since not moused until after trackball, or trackball too far for it?? # or [right i think] since not drawn at origin? # if the latter, it probably breaks the hopes of making this work trivially for testbed widgets. # ... maybe it would turn out differently if the DisplayListChunk was embedded deeper inside them: testexpr_23bh2 = SimpleColumn( DisplayListChunk(testexpr_9a), DisplayListChunk(testexpr_9b)) # works. # so I put it in checkbox_pref, and this sped up the testbed expr with 5 of them, so I adopted it in there as standard. # I also retested demo_drag (_19d) re that; it works. testexpr_23ch = Highlightable(testexpr_10c) # works, but prints debug fyi: len(names) == 2 (names = (429L, 439L)) due to glname nesting testexpr_23cd = DisplayListChunk(testexpr_10c) # has expected coord ##BUG -- outermost toggle works, inner one as if not highlightable # probably a bit faster (smoother rot90) than bare testexpr_10c, tho hard to be sure. ###e sometime try improving demo_MT to use DisplayListChunk inside -- should not be hard -- but not right now. # but I did improve demo_drag inside... testexpr_19d still works, and seems to be faster (hard to be sure) # == demo_polygon.py (stub) # commented out 070117, see comment after "import demo_polygon" ##testexpr_24 = newerBoxed(Boxed(Rect(1))) # works ##testexpr_24a = newerBoxed(Boxed(Highlightable(Rect(1)))) # works ##testexpr_24b = resizablyBoxed(Boxed(Rect(1))) # works with action being incrs of state # now modifying _19d to let me drag existing nodes... sort of working, see comments there... # will use this in _24b or so to let me define corner resizers -- as long as their local coords are right, they # are just like any other draggable things in local coords. that is where i am 070103 447p (one of two places with that comment) # == ActionButton testexpr_25 = ActionButton( PrintAction("pressed me"), "test button") # == demo of shared instance, drawn in two places (syntax is a kluge, and perhaps won't even keep working after eval/instantiate fix ) testexpr_26 = eval_Expr( call_Expr( lambda shared: SimpleRow(shared, shared) , testexpr_10c )) # no longer a correct test [070122] # pre-EVAL_REFORM status: works, except for highlighting bug -- # when you draw one instance twice, Highlightables only work within the last-drawn copy. See BUGS file for cause and fix. # EVAL_REFORM status 070122: this no longer makes a shared instance -- it shows different instances of the same expr. # So use _26g instead. # try the same fix for EVAL_REFORM as we're trying in _19g [070122 1017a]: testexpr_26g = eval_Expr( call_Expr( lambda shared: SimpleRow(shared, shared) , call_Expr( _app.Instance, testexpr_10c, "_26g") )) # works, after some bugfixes (but highlight only works on right, as explained above) # == TestIterator [070122] testexpr_27preq = SimpleColumn(testexpr_6f, testexpr_6f) # works (two different ipaths) testexpr_27 = TestIterator(testexpr_6f) # works [shows that ipaths differ] testexpr_27w = TestIterator_wrong_to_compare(testexpr_6f) # works -- ipaths are the same, since it makes one instance, draws it twice # == # this demos a bug, not yet diagnosed: testexpr_28 = eval_Expr( call_Expr( lambda shared: SimpleRow(shared, shared) , call_Expr( _app.Instance_misspelled, testexpr_10c, "_28") )) # this has "infrecur in delegate" bug, don't know cause yet ###BUG # == # test customization outside of If_expr -- unanticipated, probably won't work, but how exactly will it fail? [070125 Q] # (the desire came up in Ribbon2_try1 in new file dna_ribbon_view.py, but devel comments might as well be in If_expr.py) testexpr_29 = If( mod_Expr( _app.redraw_counter, 2), Rect(1, 1.5), Rect(1.5, 1) ) (color = red) # partly works -- # it just ignores the customization. (How, exactly??? see below for theory #k) # it doesn't fail to build the expr, or to run it -- it just ignores the customization opts. # I think If is actually an IorE macro which takes opts, fails to complain about not recognizing them, # and has no way to make them available to what's inside it. ###WAIT, does If_expr have a bug that makes it instantiate its args?? # test this now: # does If_expr have a bug that makes it instantiate its args?? # if yes bug, these ipaths might be same -- not sure -- so I won't know for sure it's ok even if they differ. # if no bug, they'll definitely differ. testexpr_29ax = TestIterator(If_expr(False, testexpr_6f)) ###BUG: note that I failed to pass an arg for the else clause... still a bug: ## IndexError: tuple index out of range ## [lvals.py:210] [Exprs.py:254] [Exprs.py:1043] [Exprs.py:1023] [Exprs.py:952] [Exprs.py:918] [If_expr.py:71] [If_expr.py:81] testexpr_29a = TestIterator(If_expr(True, testexpr_6f)) # ipaths differ -- this test works, but I'm not sure if this means If_expr is ok # (i.e. doesn't have the bug mentioned). But I guess it does... since I can't think of a more definitive test... # wait, maybe it's *not a bug* for If_expr to instantiate its args when it itself is *instantiated* -- tho it would be # if it did that when it was *evalled*. But right now it's not an OpExpr anyway, so it doesn't even *simplify* when evalled! # Which is a lack of optim, but not a bug. I suppose it means it never returns a local-ipath-mod... if it did I'd have seen # _then and _else in ipaths (before interning them). # See if If_OpExpr works at all, and if so, works in that example. First see what it does when given too few args. testexpr_29aox = TestIterator(If_OpExpr(True, testexpr_6f)) # TypeError: <lambda>() takes exactly 3 arguments (2 given) -- tolerable for now testexpr_29ao = TestIterator(If_OpExpr(True, testexpr_6f, TextRect("bug_else"))) # works, different ipaths testexpr_29aox2 = TestIterator(If_OpExpr(False, testexpr_6f, TextRect("bug_else"))) # works, shows "bug_else" twice testexpr_29aox3 = If_OpExpr(False, TextRect("True"), TextRect("False")) # -- works, shows "False" # note, we predict the old If used local ipath strings _then and _else, and the new one uses argnumbers supplied by OpExpr method. # This could be seen in the tests if we'd turn off ipath interning -- I ought to add an option for that, general # or for use when making kids of a specific instance (which would work now, since lexenv_ipath_Expr or whatever doesn't # intern it until it combines it with another ipath -- and could work later if it took an arg then for whether to intern it). # (this would take 5-10 minutes, so do it if I suspect any bugs in this ####e) # Q: should I switch over from If_expr to If_OpExpr (in implems, the name would be If_expr)?? #####e DECIDE -- note it's not done # in terms of a real implem, re default else clause, or refraining from even evalling (not just from instantiating) unused clauses # == test dna_ribbon_view.py testexpr_30 = DNA_Cylinder() # works 070131 (has no DisplayListChunk inside it) testexpr_30a = DisplayListChunk(DNA_Cylinder()) # works 070131 # (but it'd be more sensible to include DisplayListChunk inside it instead, so it can have one per display style pref setting) # try modifying testexpr_19g to put in some controls testexpr_30b = World_dna_holder() testexpr_30g = eval_Expr( call_Expr( lambda world_ui: Overlay( world_ui, DrawInCorner( Boxed( eval_Expr( call_Expr( dna_ribbon_view_toolcorner_expr_maker, world_ui )) ), PM_CORNER ) ), ## _app._i_instance(testexpr_30b) call_Expr( _app.Instance, testexpr_30b, "#30b") )) testexpr_30h = eval_Expr( call_Expr( lambda world_ui: #070206 Overlay( world_ui, DrawInCorner( Boxed( eval_Expr( call_Expr( dna_ribbon_view_toolcorner_expr_maker, world_ui )) ), PM_CORNER ), ## DrawInCorner( testexpr_18, (1,1) ), # works ## DrawInCorner( MT_try1(world_ui.world), (1,1) ), # semi-works -- autoupdate fails, # and it prints "bug: expr or lvalflag for instance changed", # and I know why -- see ###BUG comments 070206 in demo_MT.py. # How to fix it is also described in there, but not yet attempted. DrawInCorner( MT_try1(getattr_Expr(world_ui, 'world')), (1,1) ), # predict same bug - yes. ), ## _app._i_instance(testexpr_30b) call_Expr( _app.Instance, testexpr_30b, "#30bh") )) testexpr_30i = eval_Expr( call_Expr( lambda world_ui: #070207 -- just like 30h except MT_try1 -> MT_try2 Overlay( world_ui, DrawInCorner( Boxed( eval_Expr( call_Expr( dna_ribbon_view_toolcorner_expr_maker, world_ui )) ), PM_CORNER ), DrawInCorner( MT_try2(getattr_Expr(world_ui, 'world')), WORLD_MT_CORNER ), ), call_Expr( _app.Instance, testexpr_30b, "#30bi") )) # see also _30j far below -- don't reuse the name #070208 -- _30ix is like _30i except includes exprs_globals.reload_counter in world_ui make-index. # No effect except when instance remade after modifying test.py (thus reloading it). # Then, it remakes the world_ui (desired effect) but also the world itself (undesired effect, makes it lose its objects). # Could be fixed by making the world separately; ultimately we want buttons for remaking various obj layers (incl model and ui); # for now just live with it, meaning this _30ix is only useful rarely, for debugging. testexpr_30ix = eval_Expr( call_Expr( lambda world_ui: Overlay( world_ui, DrawInCorner( Boxed( eval_Expr( call_Expr( dna_ribbon_view_toolcorner_expr_maker, world_ui )) ), PM_CORNER ), DrawInCorner( MT_try2(getattr_Expr(world_ui, 'world')), WORLD_MT_CORNER ), ), call_Expr( _app.Instance, testexpr_30b, "#30bi(%d)" % exprs_globals.reload_counter) )) # == DraggableObject testexpr_31 = DraggableObject(Rect(1,0.5,yellow)) # works [but see caveats in draggable.py] # [note: this can work even though Rect() has no .move (and no state of its own, so far), since we never try to flush motion; # eventually what's needed is for Rect(), when coerced to ModelObject, to acquire enough position state to be moved ###e] # == IsocelesTriangle testexpr_32 = IsocelesTriangle(1.5, 1, green) # works [after unstubbing of IsocelesTriangle from being equal to Rect, 070212] # fyi: so does _9b, which contains IsocelesTriangle # == Highlightable.screenrect() class _testexpr_33(DelegatingInstanceOrExpr):#070226 """ test Highlightable.screenrect() """ delegate = Highlightable( Rect(1.5, 1, orange), sbar_text = "press orange rect to draw two diagonals across screen") def draw(self): if self._delegate.transient_state.in_drag: # (requires mouse click!) # other tests here say glpane.in_drag ll, lr, ur, ul = self.screenrect() # these points should be valid in the HL's coords == self's coords drawline(blue,ll,ur) # at first I tried putting color last, and it seemed to work but with the wrong coords... ugh. drawline(red,lr,ul) self.drawkid(self._delegate) pass testexpr_33 = _testexpr_33() # works now testexpr_33x = Translate(_testexpr_33(), (2,-2)) # works now # == # 070228 # How can we get the functions of both _19i and _30i in one integrated setup? from exprs.demo_ui import testexpr_34, testexpr_34a # not *, or it grabs old values of the testexprs it imported earlier from here! # note: this used to define testexpr_19j, testexpr_30j (obs, never worked); now it only defines testexpr_34* # try to tell pylint that these are used (if someone types them in) testexpr_34 testexpr_34a # == StateArrayRefs testexpr_35 = test_StateArrayRefs() # works testexpr_35a = test_StateArrayRefs_2() # works (after undiagnosed bug finally fixed, 070318), but superceded. testexpr_35b = test_StateArrayRefs_3() # works, 070318 [default direction arg is DX] testexpr_35c = test_StateArrayRefs_3(DZ) # works, 070318 [but only if you rotate view so DZ is not directly towards screen -- expected] testexpr_35d = test_StateArrayRefs_3(range = (-2,4), msg = "drag along line segment") # works (note, default Image size is 2) # == DraggablyBoxed testexpr_36 = DraggablyBoxed(Rect()) # works 070317 testexpr_36a = DraggablyBoxed(Rect(), bordercolor = red, pixelgap = 6, borderwidth = 2) # works testexpr_36b = testexpr_36(resizable = True) # partly works 070317 10pm -- see bug comments in the code testexpr_36c = testexpr_36(resizable = True) # do all testexprs share the same state for the same State attrs?? yes! ###PROBLEM. # all 4 of these (36, 36a, 36b, 36c) share the same ww and hh state, though only 2 can change that state. # a mitigation would be a testbed button to clear all state. # a fix might be to include testexpr name in the toplevel ipath used by the testbed (when one is used) # or the main instance maker (otherwise). ### SOLVE THIS SOMEHOW # update 070322: trying to solve it via testname_for_testexpr -- # ###BUG: changing to _36c from _36b or back, using cmenu of testname text, with ArgList in SimpleColumn FYI, # has delayed effect in a buggy-seeming way. It claims to have remade the instance at a recent redraw, # and shows the new testname, but the instance itself (in the main graphics area) is using old state # (don't know which testexpr it's using for sure). Could it be something about "ipath for App as opposed to test itself"?? # That is, are we using the new testexpr as desired, but not using the new ipath until an explicit reload makes us remake testbed? # To find out, turn off testbed -- NO, then I can't use testname cmenu. Ok, to find out, display ipath? trying this: testexpr_36fa = testexpr_6f(fake = 1) testexpr_36fb = testexpr_6f(fake = 2) # this works, but I can see the problem: it remakes the instance only because the exprs differ! # (find_or_make_main_instance compares the exprs to decide whether to remake.) # Trying again with _36{b,c}, the console output says it's not remaking it! # I guess it's not obvious whether that's a bug -- tho since the testname is known in those cases (by user choice in menu), # it could be considered part of the test... ah, another effect is that testname_for_testexpr[testexpr] will be the same # (in its current implem) even if the explicit testname is not. # What to do is not clear, and it relates to a current topic about ipath reform, but I think this at least explains it all. testexpr_36d = DraggablyBoxed(Image("courier-128.png", size = Rect(4)), resizable = True, clipped = True) # works, 070322 testexpr_36e = DraggablyBoxed(Sphere(2), resizable = True, clipped = True) # works [use trackball -- shows limits/benefits of implem] class Kluge_DrawTheModel(Widget2D): #070414 #e refile along with the "app object" (AppOuterLayer) """ Draw the (old legacy code) model. Kluge in many ways: - *what* model? - answer is not well defined in a more general context - and even current answer is grabbed thru env in a way that can't easily be modified by a wrapper - highlighting on this model may not work, or may mess up highlighting on the main model or some other call of this - it will matter which copy of the model is drawn last - if that's this one, and if it's not drawn in absolute coords, highlighting won't work at all - the model's drawing code might mess up gl state (when changing/restoring it) if we draw inside any nonstd state (thought to be not yet possible in practice as of 070414) - the model is not change-tracked (except by gl_update calls from high-level legacy code ops that change it). If this is inside a displist, it won't update often enough. """ #e highlightable option not yet supportable; see docstring; the last-drawn model will highlight, *iff* drawn in abs coords. def draw(self): self.env.glpane.part.draw( self.env.glpane) #k or try part.topnode.draw? maybe it doesn't matter pass testexpr_36f = DraggablyBoxed( Kluge_DrawTheModel( highlightable = False), resizable = True, clipped = True) # 070414 try to draw the model in a clipped way. sort of works, but has ###BUGS: # - only clips on bottom and right, not on top and left. # - starts out very small and not around model, since Kluge_DrawTheModel has no lbox. # (could it get one somehow from model's bbox??) # - drawing model in abs coords (maybe good for highlighting, but not for convenience), but starting out at origin... # - then if you drag the box frame, the model is no longer drawn in abs coords (it moves with the box), which means: # - so highlighting won't work (verified) (even tho no displist is involved), # - and no way to position box relative to model -- you have to position the model in space, instead. # - OTOH, highlighting works fine if you trackball entire viewing space (no displist, so no need even to remake instance). # - highlighting (yellow atom with blue wireframe, as selobj) is not clipped. (conceivably that counts as a feature, sometimes.) # Fixing highlighting in general (rendering.py) would fix the highlight-clip and permit us to draw in different coords. # The other problems could then be fixed in some straightforward way. # Even now, this could probably be used to get a screenshot of a specific clipped model. # (So it might even be useful sometimes, if it was user-accessible, but it can't be until some of those bugs are fixed.) # == demo_draw_on_surface.py from exprs.demo_draw_on_surface import our_testexpr testexpr_37 = our_testexpr # == misc testexpr_38 = PartialDisk() # works 070401, in stub form with no settable parameters testexpr_39 = ColorCube() # takes about 10-12 msec to draw [bruce 090102] testexpr_39a = DisplayListChunk(ColorCube()) # takes (very roughly) 0.5 msec to draw [bruce 090102] # === set the testexpr to use right now -- note, the testbed might modify this and add exprs of its own @@@@ #e see also the _recent_tests system... should we use the most recent test instead? or have a setting for this var which means that? enable_testbed = True testexpr = testexpr_39a ## testexpr_35b ### testexpr_11pd5a # testexpr_36f # testexpr_38 # testexpr_30i # testexpr_37 # testexpr_37 - demo_draw_on_surface # testexpr_36e - clipped sphere # testexpr_34a - unfinished demo_ui # testexpr_30i - make dna cyls # testexpr_29aox3 # testexpr_9fx4 # _26g _28 # testexpr_19Q3 - _19g (demo_drag) with drawing on background, no rect # testexpr_19i - demo_drag # testexpr_8b (tests ArgList in SimpleColumn, when that version of SimpleColumn is enabled) # as of 070121 at least these work ok in EVAL_REFORM with now-semipermanent kluge070119: # _2, _3a, _4a, _5, _5a, _10a, _10c, _9c, _9d, _9cx, # and finally _19d (bugfixed for non-ER case re ipath[0], and for ER case re delegate autoInstance). # The delegate autoInstance takes care of the last known bug in ER (IIRC, which is far from certain), # but a lot of tests have never been done in it. # Later: also _21g, _14, others. ## testexpr_24b ## testexpr_10c ## testexpr_9c ## testexpr_19d ## testexpr_9f ## testexpr_21g ## testexpr_20 ## Rect() # or _19c with the spheres ## testexpr_2 - a simple Rect ## testexpr_7c nested Boxed ## testexpr_9c column of two highlightables # testexpr_9cx has a bug, in highlightable with projection = True... the current_glselect cond fix attempt didn't fix it. # status 061209 eve: has debug prints, debug ideas are on paper, but for now I'll use a different method (not projection matrix) # for doing things like DrawInCorner_projection. [not using overrider doesn't fix it.] # status 070122: seemed to work recently in ER, don't know why, details commented next to the test. # # BUG in testexpr_9c (later: and all other highlightables), noticed 061210 morn g4: # a rapid motion onto the Highlightable doesn't highlight it, tho it does update sbar text. # Only the next motion highlights it. I wonder if it's related to gl_update and usage-tracking sync issues. # ... discussion is in BUGS file. Might be fixed now. ## testexpr_9fx4 - use of _this(Highlightable).attr to determine Rect color; _9fx6 with missing args (warning but works) ## testexpr_10c double-nested toggleshow of highlightable rect ## testexpr_11r1b image with black padding; _11s1 highlightable stretched image ## testexpr_13z4 red/blue image ## testexpr_14 array of hidden-state icons for MT (from cad/images) (change if 0 to if 1 to see non-hidden icons) [retested 070122] ## testexpr_15d ChoiceColumn [briefly retested 070122] ## testexpr_16 state test (testexpr_16c for controlling origin axes) ## testexpr_18 model tree demo using MT_try1 ## testexpr_19g GraphDrawDemo_FixedToolOnArg1 -- works [070122]; for non-ER the last tested was _19f; older _19d lacks clear button ## testexpr_20 four DrawInCorners (works but highlighting is slow) ## testexpr_21e table of alignment testers; _21g same in class form -- update 070122: works in EVAL_REFORM too -- # after I fixed 3 bugs, including adding a mostly-complete pure-expr __eq__ (which has loose ends in Expr.__eq__ comments, # which don't affect testexpr_21g/_21e). ## testexpr_22 ChoiceRow (in corner) ## testexpr_23bh2 DisplayListChunk # works: _11i, k, l_asfails, m; doesn't work: _11j, _11n ## stable: testexpr_11k, testexpr_11q11a [g4], # testexpr_11ncy2 [stopsign], testexpr_11q5cx2_g5_bigbad [paul notebook, g5, huge non2pow size] testexpr_14 [hide_icons] # latest stable tests: _11k, _10c # testexpr_5d, and testexpr_6f2, and Boxed tests in _7*, and all of _8*, and testexpr_9c, and _10d I think, and _11d3 etc # currently under devel [061126]: demo_MT, and need to revamp instantiation, but first make test framework, thus finish PixelGrabber # some history: # ... after extensive changes for _this [061113 932p], should retest all -- for now did _3x, _5d, _6a thru _6e, and 061114 6g*, 6h* # == def get_redraw_counter(): #070108 """ #doc [WARNING: this is not a usage/change-tracked attribute!] """ import foundation.env as env return env.redraw_counter ##_lval_for_redraw_counter = Lval_which_recomputes_every_time( get_redraw_counter) #070108; SEVERELY DEPRECATED ## ##def get_redraw_counter_ALWAYSCHANGES(): #070108 experiment -- useless, since it correctly causes an unwanted gl_update after every redraw! ## "like get_redraw_counter() but act as if we use something which changes every time (usage/change tracked the max legal amount)" ## return _lval_for_redraw_counter.get_value() from foundation.preferences import _NOT_PASSED ###k def get_pref(key, dflt = _NOT_PASSED): #e see also... some stateref-maker I forget """ Return a prefs value. Fully usage-tracked. [Kluge until we have better direct access from an expr to env.prefs. Suggest: use in call_Expr.] """ import foundation.env as env return env.prefs.get(key, dflt) debug_prints_prefs_key = "A9 devel/debug prints for my bug?" # also defined in GLPane.py class AppOuterLayer(DelegatingInstanceOrExpr): #e refile when works [070108 experiment] """ helper class for use in testbed, to provide glue code between testexpr and the rest of NE1 """ redraw_counter = State(int) testname = State(str)#070122 delegate = Arg(Anything) # might need to delegate lbox attrs (or might not, not sure, but no harm in doing it) def draw(self): import foundation.env as env ## print "changes._print_all_subs = True" ## changes._print_all_subs = True #### self.redraw_counter = env.redraw_counter # assume this set is subject to LvalForState's same_vals->noinval optimization #k verify ## changes._print_all_subs = False ## print "changes._print_all_subs = False" ## (note: that set caused no warning, even when done twice. Why not, since it's during recomputation that used it?? #k) # THEORY OF CONTIN REDRAW BUG WHEN THIS IS USED IN DRAWING: # the use last time means the set above does gl_update during this repaint. ... but the details of how & why are elusive... # (Would a separate lval for each draw fix it? would some kind of clear or ignore of invals at the right time fix it? # the right time for the inval from this set right now is *now* in terms of changing what the redraw will do, # but *never* in terms of causing the gl_update from our caller's use of this here. Not sure how to fix that. ####k 070109) self.testname = ', '.join(testnames) if get_pref(debug_prints_prefs_key): print "AppOuterLayer: before delegate draw", env.redraw_counter### self.drawkid( self.delegate) ## self.delegate.draw() if get_pref(debug_prints_prefs_key): print "AppOuterLayer: after delegate draw", env.redraw_counter### ###e need an env for args which binds some varname to self (dynamically), so the args have some way to access our state def env_for_arg(self, index): env = self.env_for_args #e or could use super of this method [better #e] if index == 0: #KLUGE that we know index for that arg (delegate, arg1) env = env.with_lexmods(dict(_app = self)) # something to provide access to self under the name _app (for now) # NOTE: this is meant to be a dynamic binding. # It might work anyway, given how it's used (inside & outside this expr) -- not sure. ##k # See comments in widget_env.py about needed lexical/dynamic cleanup. return env pass def testbed(expr): """ this turns the current testexpr into the actual expr to render """ ## return Overlay(expr, Closer(Rect(1,1,black), 3.4)) #stub ## return Overlay(expr, If(1,DrawInCorner_projection,Closer)(Highlightable(Rect(1,1,black),Rect(1,1,green),projection=True))) ## return Overlay(expr, DrawInCorner(Highlightable(Rect(1,1,black),Rect(1,1,green)) )) return AppOuterLayer( # [note: defines _app in dynenv] Overlay( expr, ## ## or maybe: WithEnv(expr, _env = access to app state, env module, etc ...) or, intercept .draw and run special code... ## ## _WrapDrawMethod(expr, ...)... with code to copy app state into instance State -- of what instance? smth in env... DrawInCorner( top_left_corner, (-1,1)), # some sort of MT on top left ## testexpr_20a, DrawInCorner( debug_corner_stuff, DEBUG_CORNER), # redraw counter, etc [note: contains _app as ref to dynenv] ) ) if not enable_testbed: testbed = identity #e what next, planned optims, nim tests -- see below testnames = [] # note: we show this in the testbed via _app, like we show current redraw [070122] print "using testexpr %r" % testexpr for name in dir(): if name.startswith('testexpr') and name != 'testexpr' and eval(name) is testexpr: print "(which is probably %s)" % name testnames.append(name) # (see below for our required call of _testexpr_and_testnames_were_changed() ) # == recent tests feature [070227] recent_tests_prefs_key = 'A9 devel/exprs/recent tests' def _save_recent_tests(): global _recent_tests #fyi import foundation.env as env env.prefs[recent_tests_prefs_key] = _recent_tests return def _load_recent_tests(): import foundation.env as env return env.prefs.get(recent_tests_prefs_key, []) def _add_recent_test( _recent_tests, this_test): #e should be a method of a class RecentTestsList # (note: class RecentFilesList exists in NE1 and/or IDLE -- I don't know if either is appropriate) _recent_tests = filter( lambda test1: test1 != this_test , _recent_tests) _recent_tests.append(this_test) # most recent last _recent_tests = _recent_tests[-10:] # length limit return _recent_tests _favorite_tests = ['DraggableObject(Cylinder((ORIGIN,ORIGIN+DX),1,pink))', # note: this one has state which persists during session 'Rect(3,3,purple)', 'testexpr_19i', # and so does this one (have state), of course... but that is less surprising for some reason 'testexpr_30i' ] # most favorite last; come before the ones in prefs _favorite_test_exprs = [ # this is to make sure we import the symbols needed for the above text versions [bruce 071023] # TODO: clean this up somehow DraggableObject(Cylinder((ORIGIN,ORIGIN+DX),1,pink)), Rect(3,3,purple), testexpr_19i, testexpr_30i ] try: _recent_tests except: _recent_tests = [] # most recent last _recent_tests.extend(_favorite_tests) for test in _load_recent_tests()[len(_favorite_tests):]: # (zap the first few so they don't swamp the favorites) _recent_tests = _add_recent_test( _recent_tests, test) #e would be simpler if it was a method _save_recent_tests() pass try: testname_for_testexpr except: testname_for_testexpr = {} pass def _testexpr_and_testnames_were_changed(): """ call this when you change those (which you must do in sync); the two callers (reload and _set_test) need to set them in different ways but must call this to make sure _app knows about the change and will update _app.testname """ assert type(testnames) == type([]) assert is_Expr(testexpr) global _recent_tests if testnames: this_test = testnames[-1] # just a local var _recent_tests = _add_recent_test( _recent_tests, this_test) _save_recent_tests() testname_for_testexpr[testexpr] = ",".join(testnames) #070322 new feature return _testexpr_and_testnames_were_changed() def _set_test(test): global testexpr, testnames print "\n_set_test(%r):" % (test,) testexpr = eval(test) # this is already enough to cause "remake main instance", since testexpr is compared on every draw ###BUG: this can fail if you eval a new testname after handediting this file (to add that name) # but not reloading it before doing this cmenu command. Maybe catch NameError and try reloading then?? ##e # Also, when that happens the test does not get saved in _recent_tests -- good and bad, but more bad than good # if it was hard to type (tho main importance only comes after we add editing of the text in _recent_files entries). testnames = [test] print "set testexpr to %r" % (testexpr,) _testexpr_and_testnames_were_changed() ##e need to print "doing it" or so into sbar, too, since redraw can take so long return def _set_test_from_dialog( ): # see also grab_text_using_dialog in another file; TODO: rewrite this to call that (easy) """ #doc """ # modified from debug_runpycode_from_a_dialog, which does the "run py code" debug menu command title = "title" label = "testexpr_xxx, or any 1-line expr\n(or use @@@ to fake \\n for more lines)" ## not applicable i think: \n(or use execfile) # Qt4 version [070329; similar code in another exprs-module file] parent = None text, ok = QInputDialog.getText(parent, title, label) # parent arg needed only in Qt4 if ok: # fyi: type(text) == <class '__main__.qt.QString'> command = str(text) command = command.replace("@@@",'\n') _set_test(command) # this even works for general exprs -- e.g. you can just type in Rect(3,3,purple)! else: print "_set_test_from_dialog: cancelled" return def _delete_current_test(): global _recent_tests current_test = testnames[-1] _recent_tests = filter( lambda test: test != current_test, _recent_tests) _save_recent_tests() _set_test(_recent_tests[-1]) #k bug: could be empty return class _test_show_and_choose(DelegatingInstanceOrExpr): delegate = Highlightable( DisplayListChunk( CenterY( TextRect( format_Expr("testname: %r", _app.testname)))), sbar_text = "current test (has recent tests context menu)", cmenu_maker = _self ) def make_selobj_cmenu_items(self, menu_spec, highlightable): """ Add self-specific context menu items to <menu_spec> list when self is the selobj (or its delegate(?)... ###doc better). Only works if this obj (self) gets passed to Highlightable's cmenu_maker option... """ ## menu_spec.clear() # is this a kluge, or ok? hmm, list doesn't have this method. ## del menu_spec[0:len(menu_spec)] # is this a kluge, or ok? ###BUG: this del is not enough to prevent those unwanted general items!!! I guess they're added later. ###FIX (how?) global _recent_tests # fyi for test in _recent_tests[::-1]: menu_spec.append( (test, lambda test = test: self.set_test(test)) ) if not menu_spec: menu_spec.append( ('(bug: no recent tests)', noop, 'disabled') ) # special items at the end menu_spec.append( ('other...', self.set_test_from_dialog) ) menu_spec.append( ('(delete current test)', self.delete_current_test) ) #e should include its name return def set_test(self, test): global _set_test # fyi _set_test(test) self.KLUGE_gl_update() # Note: this KLUGE_gl_update is needed [verified by test], I guess because it takes a call of _app.draw # to set any tracked state from the changed globals. #BUG: at least when KLUGE_gl_update was not here, # if redraw was triggered by mouseover of a Highlightable from before the # cmenu was used to change testexpr, then the text would be fuzzy until the inst was remade (not sure of exact cond # of how it can be fixed). Guess: the first redraw, in that case, is in the wrong coords... def set_test_from_dialog(self): _set_test_from_dialog() self.KLUGE_gl_update() def delete_current_test(self): _delete_current_test() self.KLUGE_gl_update() pass # == def _clear_state(): #070318; doesn't crash, but has bugs -- see comments where it's called just below. """ clear state, then reload (without reload, gets exception) """ print "clearing _state (len %d), then reloading" % len(_state) _state.clear() import foundation.env as env win = env.mainwindow() command = win.commandSequencer.currentCommand command.reload() return debug_corner_stuff = Boxed(SimpleColumn( # 070326 renamed bottom_left_corner -> debug_corner_stuff ## checkbox_pref("A9 devel/testdraw/drawtest in old way?", "drawtest in old way?", dflt = False), ## checkbox_pref("A9 devel/testdraw/use GLPane_Overrider?", "use GLPane_Overrider? (after reload)", dflt = True), # works (moves compass) checkbox_pref("A9 devel/testdraw/super.Draw first?", "draw model & lasso first?", dflt = True), # revised 070404 checkbox_pref("A9 devel/testdraw/super.Draw last?", "draw model & lasso last?", dflt = False), # revised 070404 # these next 4 work fine, but are not worth the screen space for now ... # when this turns into a browsable control they can be added back but not shown by default. [070227] ## checkbox_pref("A9 devel/testdraw/show old timing data?", "show old timing data?", dflt = False), # works (side effect on text in next one) ## checkbox_pref("A9 devel/testdraw/show old use displist?", "show old use displist?", dflt = False), # works ## checkbox_pref("A9 devel/testdraw/draw test graphics?", "draw old test graphics?", dflt = False), # works, but turns off above two too (ignore) ## checkbox_pref(debug_prints_prefs_key, "debug prints for redraw?", dflt = False), # note prefs_key text != checkbox label text checkbox_pref("A9 devel/testmode/testmode capture MMB", "testmode capture MMB?", dflt = False), #070228 alias for a debug_pref ## checkbox_pref("A9 devel/GLPane: zoom out same as zoom in?", "zoom out around mouse?", dflt = False), #obs key; disabled 081203 #070402 alias for new debug_pref also used in cad/src/modes.py (affects a change to mousewheel bindings added today) ActionButton(_app.env.glpane.assy.commandSequencer.currentCommand.reload, "btn: testmode.reload()"), #070227; seems faster than true empty space click! ##k #e perhaps useful: text display of len(_state), or better, inspector of _state ActionButton( _clear_state, "btn: clear _state and reload"), #070318; ###BUG: not all label chars visible. ###BUG: this failed to cause a code change in testexpr_36c to take effect, tho ne1 restart did -- I don't know why. # WARNING: It's not yet verified that _clear_state makes any difference compared to reload alone. SimpleRow( SpacerFor(Rect(15*PIXELS)), # same size as the rect button in ActionButton checkbox_pref("A9 devel/testmode/reload on empty space leftDown", #070312, also in testmode.py "reload on empty space leftDown?", dflt = True) ), checkbox_pref("A9 devel/exprs/show redraw_counter?", "show redraw_counter? (slows redraw)", dflt = True), # works [new dflt & prefs key 070227] Highlightable(DisplayListChunk( CenterY(TextRect( format_Expr("instance remade at redraw %r", call_Expr(get_redraw_counter)))) )), # NOTE: not usage/change tracked, thus not updated every redraw, which we depend on here If( call_Expr(get_pref, "A9 devel/exprs/show redraw_counter?", True), # 070124 disabled both orders of Highlightable(DisplayListChunk(, since fuzzy during highlighting after my testdraw.py fixes ##Highlightable(DisplayListChunk( CenterY(TextRect( format_Expr("current redraw %r", _app.redraw_counter))) )), ## DisplayListChunk (Highlightable( CenterY(TextRect( format_Expr("current redraw %r", _app.redraw_counter))) )), # 070124 just don't use a displist, since it'd be remade on every draw anyway (except for glselect and main in same-counted one) ## Highlightable( CenterY(TextRect( format_Expr("current redraw %r", _app.redraw_counter))) ), # 090102 split into pieces to optimize, since old form is very slow -- about 100 msec extra per frame!!! (143 msec vs 36.5 msec for entire frame) # (perhaps it got slower on my current Mac, though most things got faster there?) # Just removing outer CenterY sped it up to about 117 msec for entire frame, i.e. removed 26 msec from this! # Then splitting it into two TextRects in a Row, one in a DisplayListChunk, changed it to total 107, i.e. removed 10 more msec. # (So either the CenterY was the slowness not the TextRect, or, the extra SimpleRow computations use up most of the savings.) # But it still costs (107 - 36.5 == 70.5) msec per frame to turn this on!! Highlightable( SimpleRow(DisplayListChunk(TextRect("current redraw ")), TextRect( format_Expr("%r", _app.redraw_counter)) ) ), # should be properly usage/change tracked # note: used to have continuous redraw bug, never yet fully understood... # after checking the checkbox above, the bug showed up only after the selobj changes away from that checkbox. # update 070110 1040p: the bug is fixed in GLPane.py/changes.py; still not fully understood; more info to follow. ###e Highlightable(DisplayListChunk(TextRect("current redraw: checkbox shows counter"))) #### ), ## # this old form is redundant now, but was useful for debugging the failure of the new one to update: ## Highlightable(DisplayListChunk( CenterY(TextRect(max_cols = 100)( format_Expr("testname: %r (_app %r)", _app.testname, _app))) ), ## sbar_text = "current test" #e give it a cmenu? we need an obj to make the menu from a list of recent tests... ## ), _test_show_and_choose(), #070227 - like "testname: %r" % _app.testname, but has cmenu with list of recent tests )) # cosmetic bugs in this: mouse stickiness on text label (worse on g4?) [fixed], and label not active for click [fixed], # but now that those are fixed, highlighting of text changes pixel alignment with screen, # and Boxed not resizable, and labels wouldn't grow if it was (and they're not long enough, tho that'd be ok if they'd grow), # and reload is pretty slow since we're not caching all this testbed stuff (at least I guess that's why) top_left_corner = None # testexpr_18i # testexpr_10c # nested ToggleShow. -- works, usual # testexpr_18 # (MT_try1) also works, and has indep node.open state, i think (limited autoupdate makes it hard to be sure). # update 070206: testexpr_18 mostly works, but has a funny alignment issue. ###BUG (but can ignore for now) # == @@@ #e what next? [where i am, or should be; updated 061126 late] # - some boolean controls? # eg ChoiceButton in controls.py -- requires StateRef (does a property count as one?), maybe LocalState to use nicely # - framework to let me start setting up the dna ui? # - just do a test framework first (simpler, needed soon); described in PixelGrabber # - working MT in glpane? yes, demo_MT.py; seems to require revamp of instantiation (separate it from IorE-expr eval) # == nim tests # Column, fancy version ## testexpr_xxx = Column( Rect(4, 5, white), Rect(1.5, color = blue)) # doesn't work yet (finishing touches in Column, instantiation) # @@@ # BTW, all this highlighting response (e.g. testexpr_9c) is incredibly slow. # Maybe it's even slower the first time I mouseover the 2nd one, suggesting that instantiation time is slow, # but this doesn't make sense since I reinstantiate everything on each draw in the current code. hmm. # PLANNED OPTIMS (after each, i need to redo lots of tests): # - don't always gl_update when highlighting -- requires some code review (or experiment, make it turnable off/on) # - retain the widget_env and the made testexpr between drawings, if no inputs changed (but not between reloads) # - display lists (I don't yet know which of the above two will matter more) # - simplify exprs, like the grabarg one # - related (maybe needed as part of that): know which attrvals are "final", and which methods are deterministic (by attrname). # - some optims mentioned in StatePlace - faster & denser storage, and kinds of state with no usage/mod tracking. # - in Lval: self.track_use() # (defined in SelfUsageTrackingMixin) ###e note: this will need optimization # but first, make a state-editing example using Button. # "intentional deferred loose ends" # - iterators, and separation of expreval/instantiation (same thing? not sure) # - geom data types (eg Point) with relative coords; good system for transforms in things like Translate # - highlighting that works in displists # - povray # == per-frame drawing code _kluge_current_testexpr_instance = None # new feature 070106 for use by other modules such as demo_drag, but it's deprecated at birth and may never be used. # WARNING: if enable_testbed is set, this is actually an instance of testbed(testexpr), not of testexpr alone, # and there's no simple way to find the instance of testexpr inside it (even assuming there's exactly one instance, # which is only a convention). def drawtest1_innards(glpane): """ entry point from ../testdraw.py (called once per mode.Draw call) """ graphicsMode = glpane.graphicsMode # assume this is always testmode's graphicsMode if 0: _setup_UNKNOWN_SELOBJ_on_graphicsMode(graphicsMode) # (in 'if 0'?) # note, bruce 061218, clarified 081211: use of UNKNOWN_SELOBJ is a KLUGE # (multiple places, some in cad/src, e.g. SelectAtoms_GraphicsMode / # SelectChunks_GraphicsMode); it fixes a "highlight sync bug" in which # click on checkbox, then rapid motion away from it, then click again, # could falsely click the same checkbox twice. # # update: Unfortunately, UNKNOWN_SELOBJ also helps *cause* a bug # in which highlighting "flickers" (works only on alternate frames) # whenever renderText is used (e.g. by View -> Rulers) in testmode. # That bug is not yet understood, but it can be fixed by changing this # and the assignment of check_target_depth_fudge_factor in testmode, # and it may relate to a similar bug for Russ even when renderText # is not used. So I am changing those things now to fix it, # even though it may reactivate the older bug mentioned above. # [bruce 081211] staterefs = _state ##e is this really a stateplace? or do we need a few, named by layers for state? #e it has: place to store transient state, [nim] ref to model state inst = find_or_make_main_instance(glpane, staterefs, testexpr, testbed) # for testbed changes to have desired effect, we'll need to switch them among __eq__-comparable choices (like exprs) # rather than among defs, or editing one def, like we do now... not sure it's easy to make it an expr though; # but when it is, change to that to improve this. ##e global _kluge_current_testexpr_instance _kluge_current_testexpr_instance = inst # no longer needed, 070408 ## if 'kluge': ## #### KLUGE: get back to the standard drawing coords ## # (only works since exactly one level of this is pushed since graphicsMode.Draw is entered, and we control all that code) ## glPopMatrix() ## glPushMatrix() inst.draw() # can't use self.drawkid -- we're not an IorE instance (just a function) if not glpane.is_animating: # cond added 061121, but will probably need mod so we print the first & last ones or so... #e if not glpane.in_drag: # subcond added 061208; should be easily controllable; # might be problematic if *all* drag-caused redraws are not printed, but I'm guessing the last one will be [##k]. # it turns out, it is in some cases and not others. # if this is a problem, or if in_drag redraws matter, also consider printing ".", for them. In fact, try this now. ##import foundation.env as env ##print "drew", env.redraw_counter ##e or print_compact_stack ### TODO: also let glpane.drawing_phase and .current_glselect affect the character _print_redraw_character(';') else: _print_redraw_character('.') # Note: this shows it often draws one frame twice, not at the same moment, presumably due to GLPane highlighting alg's # glselect redraw. That is, it draws a frame, then on mouseover of something, draws it glselect, then immediately # draws the *next* frame which differs in having one object highlighted. (Whereas on mouse-leave of that something, # it only redraws once, presumably since it sees the infinite depth behind the mousepos, so it doesn't need the glselect draw.) # That behavior (drawing a new frame with a highlighted object) sounds wrong to me, since I thought it # would manage in that case to only draw the highlighted object (and to do it in the same paintGL call as the glselect), # but it's been awhile since I analyzed that code. Or maybe it has a bug that makes it do an extra gl_update, or maybe our # own code does one for some reason, or maybe it's code I added to selectMode for drag_handler support that does it. # (That last seems likely, since that code has a comment saying it's conservative and might often be doing an extra one; # it also lets the drag_handler turn that off, which might be an easy optim to try sometime. ####) # When the time comes (eg to optim it), just use print_compact_stack here. [061116 comment] printnim("see code for how to optim by replacing two redraws with one, when mouse goes over an object") # see comment above return _last_redraw_counter = -1 def _print_redraw_character(char): global _last_redraw_counter import foundation.env as env if _last_redraw_counter != env.redraw_counter: sys.stdout.write(' ') # group characters from the same redraw [081203] _last_redraw_counter = env.redraw_counter sys.stdout.write(char) sys.stdout.flush() return # == MEMOIZE_MAIN_INSTANCE = True # whether to memoize it across redraws, without reloads MEMOIZE_ACROSS_RELOADS = False # whether to memoize it across reloads ###BUG: False seems to not be working for demo_MT, 061205... ah, the intent might have been "printed reloads of testdraw" # but the code looks for reloads of this module test.py! Which often correspond but not always! # Solution: include testdraw.exprs_globals.reload_counter in the data, when this is false. try: _last_main_instance_data except: # WARNING: duplicated code, a few lines away _last_main_instance_data = (None, None, None, None, None) _last_main_instance = None else: # reloading if not MEMOIZE_ACROSS_RELOADS: # WARNING: duplicated code, a few lines away _last_main_instance_data = (None, None, None, None, None) _last_main_instance = None pass def find_or_make_main_instance(glpane, staterefs, testexpr, testbed): #061120; got testbed 061208 if not MEMOIZE_MAIN_INSTANCE: return make_main_instance(glpane, staterefs, testexpr, testbed) global _last_main_instance_data, _last_main_instance new_data = (glpane, staterefs, testexpr, testbed, MEMOIZE_ACROSS_RELOADS or exprs_globals.reload_counter ) # revised as bugfix, 061205 # note: comparison data doesn't include funcs & classes changed by reload & used to make old inst, # including widget_env, Lval classes, etc, so when memoizing, reload won't serve to try new code from those defs if new_data != _last_main_instance_data: old = _last_main_instance_data _last_main_instance_data = new_data res = _last_main_instance = make_main_instance(glpane, staterefs, testexpr, testbed) print "\n**** MADE NEW MAIN INSTANCE %s ****\n" % time.asctime(), res, \ "(glpane %s, staterefs %s, testexpr %s, testbed %s, reloads %s)" % _cmpmsgs(old, new_data) else: res = _last_main_instance ## print "reusing main instance", res return res def _cmpmsgs(d1, d2): """ return e.g. ("same", "DIFFERENT", "same") to show how d1 and d2 compare using == at corresponding elts """ assert len(d1) == len(d2) res = [_cmpmsg(d1[i], d2[i]) for i in range(len(d1))] return tuple(res) # tuple is required for this to work properly with print formatting def _cmpmsg(e1,e2): return (e1 == e2) and "same" or "DIFFERENT" def make_main_instance(glpane, staterefs, testexpr, testbed): some_env = widget_env(glpane, staterefs) try: testname = testname_for_testexpr[testexpr] # new feature 070322 except KeyError: print "no saved testname_for_testexpr" testname = "?" pass ipath = (testname, NullIpath) inst = some_env.make(testbed(testexpr), ipath) return inst class _find_or_make: #061217 from find_or_make_main_instance etc #e refile ### NOT YET USED """ Helper class for caching made things when the input data hasn't changed. (Note that it is up to you to not accidentally discard and remake instances of this class itself, e.g. upon module reload... Or maybe we'll let you do it, and have this class store its data elsewhere... that might be more convenient, especially during development of this class. ###doc better) If you want a "remake button" for such a thing, let the button increment a counter which is part of the input data. If you want an "always remake" button, let it control whether an always- changing counter gets included in the data or not. If the data is positional, then include a constant in place of anything you sometimes leave out. """ def __init__(self, printname = None): #e makefunc? cacheplace? self.old_data = None self.printname = printname def find_or_make(self, *data_args, **data_kws): if 0: ## not MEMOIZE_MAIN_INSTANCE: return self.make(*data_args, **data_kws) #e store in self.res? for i in range(len(data_args)): data_kws[i] = data_args[i] ###k only safe if passing a dict via ** always copies it! new_data = data_kws #k ok since dict.__eq__ does what i want if not same_vals( new_data, self.old_data): # use same_vals to avoid the bug in != for "Numeric array in tuple" # remake, but first explain why old_data = self.old_data self.old_data = new_data if self.printname: print "remaking %r, because", if old_data is None: print "not made before" else: # make sure keys are the same k1 = old_data.keys() k2 = new_data.keys() k1.sort() k2.sort() if k1 != k2: print "data keys changed (bug?)" else: for k in k1: if not same_vals(old_data[k], new_data[k]): print "%s DIFFERENT" % k, else: print "%s same" % k, print pass pass res = self.res = self.make(*data_args, **data_kws) ## print "\n**** MADE NEW MAIN INSTANCE %s ****\n" % time.asctime(), res, \ ## "(glpane %s, staterefs %s, testexpr %s, testbed %s, reloads %s)" % _cmpmsgs(old, new_data) else: res = self.res ## print "reusing %s" % self.printname, res return res def make(self): assert 0, "subclass should implement" ### or use a self.func pass # == # old comments: # upon reload, we'll make a new env (someday we'll find it, it only depends on glpane & staterefs), # make an instance of testexpr in it, set up to draw that instance. # this is like making a kid, where testexpr is the code for it. # when we draw, we'll use that instance. # problem: draw is passed glpane, outer inst doesn't have one... but needs it... # what's justified here? do we store anything on glpane except during one user-event? # well, our knowledge of displists is on it... lots of cached objs are on it... # OTOH, that might mean we should find our own stores on it, with it passed into draw -- # since in theory, we could have instances, drawable on several different renderers, passed in each time, # some being povray files. these instances would have their own state.... # OTOH we need to find persistent state anyway (not destroyed by reload, that's too often) # some state is in env.prefs, some in a persistent per-session object, some per-reload or per-glpane... try: session_state # assert it's the right type; used for storing per-session transient state which should survive reload except: session_state = {} ### NOT YET USED as of 061120 per_reload_state = {} ### NOT YET USED as of 061120 # also per_frame_state, per_drag_state ... maybe state.per_frame.xxx, state.per_drag.xxx... # == # one-time tests: to do them, change if 0 to if 1: from exprs.instance_helpers import InstanceOrExpr if 0: class something(InstanceOrExpr):#070123 attr1 = Arg(int) attr2 = attr1 # do we get a warning? yes (but it's not understandable -- that could be fixed). ## formula <...> already in replacements -- error?? its rhs is <..._self.attr1...>; new rhs would be for attr 'attr2' pass if 0: # above warning mentions in order attr1, attr2. does that depend on this order here? let's find out in this next test: class something(InstanceOrExpr): attr2 = Arg(int) attr1 = attr2 # in what order does the warning mention these attrs? same order as before: attr1 then attr2. if 0: # what if I ask Arg() to record locals().keys() when it runs? Won't help, even if it works -- when it runs, *neither* # of these attrs will be defined in locals. Even so, does it work at all?? Yes. class something(InstanceOrExpr): print locals().keys() # ['__module__'] attr2 = 0 print locals().keys() # ['__module__', 'attr2'] attr1 = 0 print locals().keys() # ['__module__', 'attr2', 'attr1'] pass # end
NanoCAD-master
cad/src/exprs/test.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ py_utils.py $Id$ simple utility functions for python built-in types """ # note: the module basic.py imports * from this module. class attrholder: pass def identity(arg): return arg def interleave(elts, gaps): """Return an interleaved list of the given elements and gaps -- e.g. elt[0] gap[0] elt[1] gap[1] elt[2], for 3 elts and 2 gaps. (Error if input list lengths are not properly related; special case for no elts.) """ if len(elts) <= 1: # btw, code below would also work for len(elts) == 1 assert not gaps return elts assert len(gaps) + 1 == len(elts) def elt_or_gap(i): if i % 2 == 0: return elts[i / 2] else: return gaps[int(i / 2)] return map(elt_or_gap, range(len(elts) + len(gaps))) def interleave_by_func(elts, gapfunc): gaps = [gapfunc(e1,e2) for e1,e2 in zip(elts[:-1],elts[0:])] return interleave(elts, gaps) def dict_ordered_values(d1): ##e rename (this name 'dict_ordered_values' is completely unrecallable) #e see also sorted_items "Return the values of the given dict, sorted by their key in the dict. [see also sorted_items]" items = d1.items() items.sort() return [v for (k,v) in items] def sorted_items(d1): #070312 "Return a list of all (key, value) pairs in the given dict, sorted by dict key. [see also dict_ordered_values]" items = d1.items() items.sort() return items def sorted_by(seq, func): #070206 ##e do I have this under some other name, somewhere? "return the elements of the given sequence, sorted by func(element)" items = [(func(elt), elt) for elt in seq] items.sort() return [elt for (f, elt) in items] from foundation.env import seen_before # public in this module def printonce(msg, constpart = None): """print msg (which should be a constant), but only once per session. If msg is *not* a constant, pass its constant part (a nonempty string -- not checked, bad errors if violated) in constpart. WARNING: If you pass nonconstant msg and forget to pass constpart, or if constpart is nonconstant or false, this might print msg on every call! WARNING: Nonconstant args can be a slowdown, due to the time to evaluate them before every call. Passing constpart can't help with this (of course), since all args are always evaluated. Consider direct use of env.seen_before instead. """ constpart = constpart or msg if not seen_before(constpart): print msg return printnim_enabled = False # 061114 -> False; turn on again when I feel like cleaning a lot of them up def printnim(msg, constpart = None): if printnim_enabled: printonce("nim reminder: " + msg, constpart) return def printfyi(msg, constpart = None): printonce("fyi (printonce): " + msg, constpart) return def stub(*args, **kws): #e rename to stubfunc (too hard to search for 'stub', common in comments) assert 0, "stub called" class MemoDict(dict): #k will inherit from dict work? ###e rename to extensibledict?? -- it doesn't have to memoize exactly... """Act like a transparently extensible dict, given a way to compute a new element (which we'll memoize) from the dict key; this way MUST NOT USE USAGE-TRACKED LVALS (WARNING: this error is not yet detected [actually I think it is, now]). (If you wish there was usage-tracking and update, see LvalDict2, or a proposed RecomputingMemoDict, in other files.) WARNING: typical uses are likely to involve cyclic refs, causing memory leaks. """ ###e should provide an optional argfunc to canonicalize the key before using it to look up or call the wayfunc # (for use in texture_holder_for_filename in images.py) [061125 comment] def __init__(self, way): self._way = way dict.__init__(self) def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: import foundation.changes as changes mc = changes.begin_disallowing_usage_tracking(self) # note: argument is just explanation for use in error messages try: val = self._way(key) # note, it needs to be legal for something during this to reallow using tracking for itself, locally except: # try not to hurt this object for use at other keys, but good to reraise exception to whoever accessed this key # (maybe something's wrong with this key, but good even if not, i think [061121]) # Note: the exception might be an error being reported by begin_disallowing_usage_tracking! # So we should do the ending of that disallowing -- the initial raising of that exception should not do it. changes.end_disallowing_usage_tracking(mc) raise else: changes.end_disallowing_usage_tracking(mc) dict.__setitem__(self, key, val) return val pass pass # end of class MemoDict def union(A,B): #k does this override anything that's standard in python? if so, rename it, perhaps to dict_union #note: presumably useful, but not yet used; may never end up being used. """Union, for sets represented as dicts from k to k, or (if you prefer) from k to f(k), for any pure function f (which need not be deterministic, and can even be entirely arbitrary). For even more general uses, we guarantee: when k occurs in both inputs, the value f(k) comes from B. But we might remove this guarantee as an optim, someday, so uses should comment if they depend on it (or should use an alias to this function, which carries a permanent guarantee #e). [It would be good if we could use some form of hashable (finalized or immutable) dict... #e] """ # note: we might use this for tracking sets of free variables in exprs. if A: if B: #e is it worth optimizing for both len 1 and same key? note, it reduces memory usage w/o interning. #e relatedly: we could order them by len, check for subsetness. res = dict(A) res.update(B) #e intern res? this could help in making these sets hashable (usable as dict keys), # esp. if the result of interning was just a number, able to be looked up to get the dict... # it could be a serno, or actually a bitmap of the elements, permitting bitwise Or as union # (for uses in which the universe of all elements used in any set is very small, # as will often be true for "free variables in exprs"). return res else: return A else: return B pass class delegated_state_attr(object): # 070103, moved from GLPane_overrider.py 070104 """A descriptor (like a property) which delegates get and set of an attr into another object found at a specified attrpath. For example, to delegate self.quat to self.delegate.quat (for get and set), use quat = delegated_state_attr('delegate', 'quat') """ def __init__(self, *attrpath): self.path_to_obj = tuple(attrpath[0:-1]) self.attr = attrpath[-1] assert self.path_to_obj + (self.attr,) == attrpath def find_obj(self, obj): assert obj is not None for attr in self.path_to_obj: obj = getattr(obj, attr) return obj def __get__(self, obj, cls): if obj is None: return self obj = self.find_obj(obj) attr = self.attr return getattr(obj, attr) def __set__(self, obj, val): if obj is None: return obj = self.find_obj(obj) attr = self.attr setattr(obj, attr, val) return pass # end
NanoCAD-master
cad/src/exprs/py_utils.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ widget_env.py -- an environment for the instantiation and use of widget exprs @author: bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. The environment is used for lexical replacement & instantiation, and then for "use/residence" (running & drawing & holding state). Maybe someday we'll split these parts. The ipath is already passed separately for efficiency. [#doc -- this comment is not clear enough.] 070106 discussion of lexical/dynamic confusion: the env is mainly dynamic, but also holds lexical bindings. At present, it holds both kinds as attributes (distinguishing them only by convention), and also has class attrs and an instance variable (delegate and whatever else Delegator has), with no means of distinguishing them from variable bindings (which would lead to bugs if symbolnames overlapped class attrs -- so far that can't happen, since nothing creates arbitrary symbolnames and the fixed ones don't overlap them). Finally, the implementation of lexical vs dynamic inheritance is incorrect, since lexenv_Expr should grab only lexical vars from its contained env, but grabs all vars from it -- this too has not yet led to bugs, since there is no provision for overriding dynamic variables, so each one is the same in both envs seen by lexenv_Expr. But all the confusions mentioned above will soon turn into real bugs, since we'll introduce ways to declare and override both lexical and dynamic symbols of non-hardcoded names. So we have to clean up the situation somehow. First, a survey of existing symbolnames in use: Lexical: _self [note: the _e_eval* methods on Expr act as operations on implicit instances of the Expr self owned by the real instance env._self; AFAIK this is an orthogonal issue to _self being lexical in formulae] _this_<classname> _my Dynamic: glpane staterefs (rarely used directly) And proposed names: _the_<classname> (dynamic) _env (unclear -- the intent is for _env.sym to be used in formulas to refer to dynamic sym, but it's probably short for _my.env.sym, thus _env is itself lexical.) With the exception of the proposed dynamic variable _the_<classname>, note that the lexical names start with one '_' and the dynamic ones start with no '_'. Of these, the only ones often accessed as env attrs by client code are _self and glpane. If we changed how all env vars should be accessed, only those would lead to large numbers of client code changes.Nothing is wrong with a fixed set of vars being accessible as env attrs, so we might let those continue to be accessed that way even if general vars can't be. We also may want formulas to access env vars of some object using <object>.env.<var>, which is a harder issue since the vars could be arbitrary. I don't yet know if we want to enforce a naming convention about which vars are dynamic vs lexical, and/or a fancier required syntax for accessing non-hardcoded env var names. The likely uses for dynamic variables are to refer to important GUI framework objects surrounding specific drawables, including singleton model objects like the model or the current selection, to display styles, to "the model object" being shown in drawables serving as its view, and probably various containing or otherwise-related model objects of given types, and to the presence of specific user-defined "tags" on those objects. The likely uses for lexical variables are in user-defined rules, and the hardcoded _self, _this_X, _my. """ #e rename module?? possible names: expr_env, instance_env, widget_env, drawing_env -- or something plural? from idlelib.Delegator import Delegator ###e we should use our own delegation code, since we don't need the key cache so it can be more efficient from exprs.Exprs import canon_expr from exprs.py_utils import printnim ##from exprs.py_utils import printfyi class widget_env(Delegator): "represent an environment for the instantiation and use of widget exprs (with rules and staterefs)" # I intend to add this soon here (default value): _self = None printnim("SOON I need to add _self = None to class widget_env")#####@@@@@ def __init__(self, glpane, staterefs, delegate = None, lexmods = {}): #e rename glpane? #e type of staterefs? [just an external dict, as of 061116 calling code; the 'refs' in the name is to remind you it's not owned] #e rules/lexenv too? #e ipath? [061116: no, that's separate, tho if we end up splitting it by state-layer, # we might have to change that, or let env have ipaths per layer with the separately-passed one relative to all those ] self.glpane = glpane self.staterefs = staterefs ###k ###KLUGES, explained below [061028]: Delegator.__init__(self, delegate) # this will be None or the parent env for k,v in lexmods.iteritems(): setattr(self, k,v) # worst part of the kluge -- dangerous if symnames overlap method names # next worst part: special methods like __repr__ end up delegating pass def __repr__(self): # without this, Delegator delegates __repr__ ultimately to None, so "%r" % self == "None"!!! return "<widget_env at %#x (_self = %r)>" % (id(self), getattr(self, '_self', '<none>')) # revised 070120 __str__ = __repr__ #k guess: might be needed for same reason as __repr__ def understand_expr(self, expr, lexmods = None): print "understand_expr ran"###070112 -- never happens "#doc; retval contains env + lexmods, and can be trusted to understand itself." # only the "rules" in self are needed for this, not the glpane & staterefs! so put this method in a subobject! #e assert not lexmods, "lexmods are nim" ###@@@ return expr ####@@@@ STUB but might sometimes work #e [if we ever need this, can we just use something like lexenv_Expr?? but with dynenv bindings too? 070112 guess comment] def make(self, expr, ipath, eval = True): #k args?? ####@@@@ """Make and return an instance of the given expr (understood or not) in self. The instance should store its state under the index-path ipath [#doc format]. """ # print "make ran (eval = %r)" % eval # happens before you make a new main instance... 070121 or when demo_drag makes a node #e ipath guess: a list of 2 or 3 elts, linked list inner first, maybe append an interning of it #e look for rules; check if understood; #e Q: is this memoized? does it allocate anything like a state obj ref, or was that already done by customizing this env? ## print "making",expr,ipath # assume it's an understood expr at this point # # update 070117 re EVAL_REFORM: maybe we'll need to be an explicit noop for numbers or Instances (non-pure-exprs) -- # we will if some calls to _e_make_in are changed into calls to this, which seems likely. #k # The way to do that is to do what _i_instance does -- it calls some helper function to decide what's idempotent for make. if eval: # new feature 070118 -- fixes testexpr_19f when no testbed and when not EVAL_REFORM # (guess, unconfirmed: its failure then is an old bug predating EVAL_REFORM, not a new bug) eval_ipath = ('!env-eval', ipath) # I'm guessing this had better differ from the one passed to _e_make_in -- not sure expr = expr._e_eval(self, eval_ipath) #e it'd be nice to print a notice if this changed it, but it surely will by wrapping a new lexenv_Expr if nothing else, # so it's too hard to tell if it *really* did. try: res = expr._e_make_in(self, ipath) except:#070118 print "following exception in env.make's _e_make_in call concerns expr %r and ipath %r: " % (expr, ipath) raise return res def with_literal_lexmods(self, **lexmods): "Return a new rule-env inheriting from this one, different in the lexmods expressed as keyword arguments" return self.with_lexmods(lexmods) def with_lexmods(self, lexmods): "Return a new rule-env inheriting from this one, different in the given lexmods (a dict from symbolnames to values)" ###e need to know if env vars are accessed by attr, key, or private access function only, like lexval_of_symbol; # and whether glpane is a lexvar like the rest (and if so, its toplevel symbol name); # and about staterefs. # For now, to make tests work, it's enough if there's some way to grab syms with inheritance... # use Delegator? it caches, that's undesirable, and it uses attr not key, which seems wrong... otoh it's easy to try. # So I'll try it temporarily, but not depend on attr access to syms externally. [061028] return self.__class__(self.glpane, self.staterefs, delegate = self, lexmods = lexmods) def lexval_of_symbol(self, sym): # renamed _e_eval_symbol -> lexval_of_symbol # but I'm not sure it's really more lexenv than dynenv, at least as seen w/in env... [061028] ####@@@@ # btw, so far this is probably only used for _self. # As of 061114, also for _this_whatever -- no, that uses our helper lexval_of_symbolname. name = sym._e_name return self.lexval_of_symbolname(name, sym) def lexval_of_symbolname(self, name, dflt): #e default for dflt? used to be the sym, even now could be an imported (so identical) sym # removed printfyi warning, 070131: ## if name not in ('_self','_app') and not name.startswith('_this_'): ## printfyi("lexval_of_symbolname other than _self, _app, or _this_xxx: %s" % (name,) ) # kluge: return getattr(self, name, dflt) ## newenv = dynenv.dynenv_with_lexenv(lexenv) #e might be renamed; might be turned into a helper function rather than a method def dynenv_with_lexenv(self, lexenv): "#doc" return lexenv ##### 070109 is _app bug fixed even w/ this? yes, it was unrelated. WE STILL NEED NEW CODE HERE. ####BUG # kluge 070109: do just enough to see if using this fixes the bug i suspect it might -- ###WRONG IN GENERAL (and disabled too) if getattr(self, '_app', None) is not getattr(lexenv, '_app', None): print "fyi: dynenv_with_lexenv makes a difference for _app: %r vs %r" % \ ( getattr(self, '_app', None) , getattr(lexenv, '_app', None) ) ### remove when works if not hasattr(self, '_app'): return lexenv return lexenv.with_literal_lexmods(_app = self._app) # really this is a "dynamic mod" as hardcoded in the name _app (w/in current kluge) def _e_eval(self, expr, ipath):#070131 "evaluate an expr (or constant) in this env, with given ipath" return canon_expr(expr)._e_eval( self, ipath) pass def thisname_of_class(clas): thisname = "_this_%s" % clas.__name__ ##e [comment also in our caller:] someday make it safe for duplicate-named classes # (Direct use of Symbol('_this_Xxx') will work now, but is pretty useless since those symbols need to be created/imported. # The preferred way to do the same is _this(class), which for now [061114] evals to the same thing that symbol would, # namely, to what we store here in lexmods for thisname. See "class _this".) return thisname # == end, except for obs code and maybe-not-obs comments # things in the env: # - rules for understanding exprs (can be empty even in practice) # - they are lexical # - contains exprhead macro-replacements # - contains lexical replacements while we're expanding rules -- passed separately since changes separately, but might just inherit # - rules for instantiating # - a drawing env to attach the instance to # - glpane # - a model env in which the state resides, in layers # - staterefs # - rules/state for running/drawing # use GlueCodeMapper I mean GlueCodeMemoizer to map exprs to understood versions and then (with ipaths) to instances?? # but we already use it for finding kids, in some cases... maybe in all?? # - ipath is explicit so we can use it to make state in other layers, following structure of instances. # - so it has not only ints etc, but symbols corresponding to attrs... it should correspond to "find the instance using attr/index" path # - so we might want to make sure that always works... in fact we do. how? by a special member for storing kids or their defs... # self.kids.attr1[i] # we put compute rules in it, but also have a way to find attr/index paths in it... # end
NanoCAD-master
cad/src/exprs/widget_env.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ Rect.py -- provide Rect, RectFrame, and other simple 2d shapes @author: Bruce @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. These are prototypes with imperfect arg syntaxes. #e maybe rename this file to shapes.py? #e also have shapes3d.py, or even put both in one file, when simple. """ from OpenGL.GL import GL_CULL_FACE from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GLU import gluNewQuadric from OpenGL.GLU import GLU_SMOOTH from OpenGL.GLU import gluQuadricNormals from OpenGL.GLU import gluPartialDisk from utilities import debug_flags from utilities.constants import gray, white, black from exprs.widget2d import Widget2D from exprs.attr_decl_macros import Arg, ArgOrOption, Option from exprs.instance_helpers import InstanceOrExpr, DelegatingMixin from exprs.ExprsConstants import Width, Color, Position, ORIGIN, PIXELS, Point, DX, DY from exprs.draw_utils import draw_filled_rect from exprs.draw_utils import draw_filled_triangle from exprs.draw_utils import draw_filled_rect_frame from exprs.__Symbols__ import _self from exprs.py_utils import printnim, printfyi from graphics.drawing.CS_draw_primitives import drawsphere from graphics.drawing.CS_draw_primitives import drawline # == class Rect(Widget2D): # finally working as of 061106 """ Rect(width, height, color) renders as a filled x/y-aligned rectangle of the given dimensions and color, with the origin on bottomleft, and a layout box equal to its size (no margin). If color is not given, it will be gray [#e should be a default attrval from env]. If height is not given, it will be a square (even if width is a formula and/or random). See also: RectFrame, ... """ # args width = Arg(Width, 5) # changed 10 to 5 late on 061109 # Note: Widget2D defines width & height, making this seem circular, but it's ok (see comment in RectFrame) height = Arg(Width, width) color = ArgOrOption(Color, gray) # formulas if 0: # use this to test whatever scheme we use to detect this error, once we put one in [disabled 061105 until other things work] bright = width ######@@@@@ PROBLEM: in ns, width and bright will have same value, no ordering possible -- how can it tell # which one should be used to name the arg? It can't, so it'll need to detect this error and make you use _self. prefix. # (in theory, if it could scan source code, or turn on debugging during class imports, it could figure this out... # or you could put the argname in Arg or have an _args decl... but I think just using _self.attr in these cases is simpler.) printnim("make sure it complains about bright and width here") btop = height else: if debug_flags.atom_debug: printfyi("not yet trying to trigger the error warning for 'bright = width'") # (since it's nim, even as of 061114 i think) bright = _self.width btop = _self.height # bbottom and bleft are not needed (same as the defaults in Widget2D), except that we use them in the formula for center; # it would be more correct to say bleft = _self.bleft, but less efficient I think (not much), and hasn't been tested (should be #e). bbottom = 0 bleft = 0 ## center = V_expr( (bright - bleft) / 2.0, (btop - bbottom) / 2.0, 0.0) #070211 #e someday this could be deduced from lbox, generally ###e should move this def into Spacer, RectFrame, etc -- or arrange to deduce it from lbox on any Widget2D, somehow... # [070227] hmm, can't it just be moved from here into Widget2D itself? Yes, that works! def draw(self): glDisable(GL_CULL_FACE) draw_filled_rect(ORIGIN, DX * self.bright, DY * self.btop, self.fix_color(self.color)) #e move fix_color into draw_filled_rect? glEnable(GL_CULL_FACE) pass class Sphere(Widget2D): # the superclass is to give it a 2D lbox. We'll need to think about whether it needs renaming. # or maybe this super will be Widget3D and that will inherit Widget2D?? hmm... """ Sphere(radius, color, center) represents a spherical surface of the given radius (default 1), color (default gray), and center (default the local origin) [partly nim if not #e]. [There is also an undocumented option, detailLevel.] """ # args radius = ArgOrOption(Width, 1) color = ArgOrOption(Color, gray) center = ArgOrOption(Position, ORIGIN) # this is not yet supported in determining the layout box, # since I'm tempted to say, if this is supplied, turn into a macro, Translate(Sphere(...)) # so I won't need to uglify those calcs. Not yet sure quite how to most easily organize that -- # best would be a general way to make some options or uses of them "turn into macros", # sort of like in a math paper saying "w/o loss of generality, assume center == ORIGIN". ###e detailLevel = Option(int, 2) #k guess: 1 or 2 or 3, i think -- undocumented since needs a better name and maybe arg meaning # formulae bright = _self.radius bleft = _self.radius btop = _self.radius bbottom = _self.radius def draw(self): drawsphere(self.fix_color(self.color), self.center, self.radius, self.detailLevel) pass # == class Spacer_pre061205_obs(Rect): #061126 # slight kluge, since accepts color arg but ignores it (harmless, esp since nothing yet warns about extra args or opts) # (note: we might decide that accepting all the same args as Rect is actually a feature) #e #k might need enhancement to declare that instantiation does nothing, ie makes no diff whether you reref after it -- # but for that matter the same might be true of Rect itself, or anything that does pure drawing... #e see also: Invisible [nim], e.g. Invisible(Rect(...)) or Invisible(whatever) as a spacer sized to whatever you want ###e should change default dims to 0,0 -- now i did this by rewriting it below def draw(self): return pass class Spacer(Widget2D): # rewritten 061205 to not inherit from Rect, so arg defaults can change -- ###e it would be better if that was not the only safe way [tho I didn't even bother trying the simpler way, I admit] """ Accept same args as Rect, but draw as nothing. Equivalent to SpacerFor(Rect( same args)). """ width = Arg(Width, 0) # Note: Widget2D defines width & height, making this seem circular, but it's ok (see comment in RectFrame) height = Arg(Width, width) color = ArgOrOption(Color, gray) # not used, but should be accepted, since it's accepted as arg or public option name in Rect # formulas bright = _self.width btop = _self.height def draw(self): return pass class SpacerFor(InstanceOrExpr, DelegatingMixin): """ A spacer, the same size and position (ie same lbox) as its arg. ###e Should merge this with Spacer(dims), easier if dims can be a rect object which is also like a thing you could draw... maybe that's the same as a Rect object? #k See also Invisible, which unlike this will pick up mouseovers for highlighting. [##e And which is nim, in a cannib file.] """ delegate = Arg(Widget2D) def draw(self): return pass # == class IsocelesTriangle(Rect): """ IsocelesTriangle(width, height, color) renders as a filled upright isoceles triangle (symmetric around a vertical line, apex centered on top), with local origin on bottomleft vertex. """ def draw(self): glDisable(GL_CULL_FACE) draw_filled_triangle(ORIGIN, DX * self.bright, DY * self.btop + DX * self.bright * 0.5, self.fix_color(self.color)) glEnable(GL_CULL_FACE) pass # == class RectFrame(Widget2D): """ RectFrame(width, height, thickness, color) is an empty rect (of the given outer dims) with a filled border of the given thickness (like a picture frame with nothing inside). """ # args width = Arg(Width, 10) # NOTE: Widget2D now [061114] defines width from bright & bleft (risking circularity), & similarly height; # I think that's ok, since we zap that def here, so the set of active defs is not circular # (and they're consistent in relations they produce, too, as it happens); a test (_7b) shows no problem. height = Arg(Width, width) thickness = ArgOrOption(Width, 4 * PIXELS) color = ArgOrOption(Color, white) # layout formulas bright = _self.width btop = _self.height ## debug code from 061110 removed, see rev 1.25 for commented-out version: ## override _e_eval to print _self (in all envs from inner to outer) to see if lexenv_Expr is working def draw(self): glDisable(GL_CULL_FACE) draw_filled_rect_frame(ORIGIN, DX * self.width, DY * self.height, self.thickness, self.fix_color(self.color)) glEnable(GL_CULL_FACE) pass # == class Line(InstanceOrExpr): #070211; revised 070419 (Widget2D -> IorE, more options) end1 = Arg(Point) end2 = Arg(Point) color = ArgOrOption( Color, black) width = Option(int, 1) #e rename linewidth? dashed = Option(bool, False) def draw(self): color = self.fix_color(self.color) end1, end2 = self.end1, self.end2 width = self.width dashed = self.dashed drawline(color[:3], end1, end2, width = width, dashEnabled = dashed) ###k dashEnabled untested here pass # == class PartialDisk(Widget2D): # stub (no settable parameters), works (testexpr_38), 070401 def _C_quadric(self): """ set up self.quadric """ # see PyOpenGL Demo/NeHe/lesson18.py quadric = gluNewQuadric() #e it may be that this object could be shared by all instances, or even more globally -- not sure gluQuadricNormals(quadric, GLU_SMOOTH) # Create Smooth Normals ## gluQuadricTexture(quadric, GL_TRUE) # Create Texture Coords return quadric def draw(self): gluPartialDisk(self.quadric,0.5,1.5,32,32,0,300) #e stub - should use named options return pass # end
NanoCAD-master
cad/src/exprs/Rect.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ $Id$ """ # WARNING: there is an old version of this (same name TextRect) from cad/src/drawtest.py, still in use up there. # Note: this uses fixed size for text on screen, regardless of depth -- we'll need to revise this someday. #e # Plan: make this just good enough for use as a debugging tool -- e.g. to make instances that show their own ipath. # It still uses utility funcs and an assumed-bound-texture from cad/src/drawtest.py. from OpenGL.GL import glPushMatrix, glPopMatrix #e replace with glpane_proxy attrs from exprs.attr_decl_macros import Arg, Option from exprs.Exprs import min_Expr, call_Expr from exprs.widget2d import Widget2D from exprs.ExprsConstants import PIXELS from exprs.__Symbols__ import _self # TODO: see if our runtime imports from texture_fonts can be done at toplevel class TextRect(Widget2D): """TextRect(msg, nlines, ncols) renders as a rect of ncols by nlines chars, taken from str(msg) (typically a formula in _self or _this(something)), origin on bottomleft. Arg nlines defaults to lines in msg, limited by option max_lines, default 6; ncols defaults to cols in msg, limited by option max_cols, default 45. #doc textsize issues, lbox issues, arg order reason (some caller comment explains it, i think, maybe in test.py). """ from graphics.drawing.texture_fonts import tex_width, tex_height # constants (#e shouldn't be; see comments where they're defined) # args msg = Arg(str) nlines = Arg(int, min_Expr( _self.msg_lines, _self.max_lines) ) # related to height, but in chars ###e try default of _self.msg_lines, etc -- trying this 061116 ## ncols = Arg(int, 16) # related to width, but in chars ncols = Arg(int, min_Expr( _self.msg_cols, _self.max_cols) ) # related to width, but in chars # options max_lines = Option(int, 6) max_cols = Option(int, 45) # 16 -> 45 (guess), 061211, was never used before btw margin = Option(int, 2) # in pixels -- should this be said in the type? ###k # formulae for arg defaults, from other args and options (take care to not make them circular!) [061116] msg_lines = call_Expr( call_Expr(msg.rstrip).count, '\n') + 1 # i.e. msg.rstrip().count('\n') + 1, but x.y(z) syntax-combo is not allowed, as a safety feature -- # we'll need to find a way to sometimes allow it, I think. msg_cols = call_Expr( lambda msg: max(map(len, msg.split('\n'))) , msg ) # finally implemented 061211 # formulae ###e msg_lines, msg_cols, and make sure those can be used in the default formulae for the args # lbox attrs -- in the wrong units, not pixelwidth, so we need to kluge them for now margin1 = margin * PIXELS # bugs: option might want to know type PIXELS, and it all shows up on the right, none on the left bright = ncols * PIXELS * tex_width + 2 * margin1 btop = nlines * PIXELS * tex_height + 2 * margin1 def draw(self): assert self._e_is_instance, "draw called on non-Instance of TextRect" #061211 glpane = self.env.glpane msg = str(self.msg) #k str() won't always be needed, maybe isn't now ##e guess: need __mod__ in Expr width = self.ncols # in chars # WARNING: every Widget2D has self.width in native Width units; don't assign ncols to self.width or you'll mess that up. #e probably we should rename this localvar to ncols, same for height/nlines. height = self.nlines # in chars if 1: # until we have Arg type coercion, see if this detects caller errors -- it does: ## ValueError: invalid literal for int(): line 1 ## line 2 width = int(width) height = int(height) from graphics.drawing.texture_fonts import drawfont2 glPushMatrix() ####k guess, not sure needed #e translate by margin drawfont2(glpane, msg, width, height, pixelwidth = PIXELS) #061211 pass pixelwidth so rotation won't matter (warning: different value than before, even w/o rotation) glPopMatrix() return pass # TextRect # end
NanoCAD-master
cad/src/exprs/TextRect.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ lvals.py - various kinds of "lvalue" objects (slots for holding attribute values) with special behavior such as usage-tracking and invalidation/update. @author: bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. === Ways in which lval classes need to differ from each other: - how the value they represent is "delivered" (on request of a caller, calling a get_value method or the like): - (e.g. as a return value, or as an externally stored value, or as side effects) - (e.g. with or without a version-counter) - how the fact of their value's usage is recorded in the dynamic environment, and what kind of usage is recorded - kinds of usage: calls of display lists, uses of other external objects (qt widgets, opengl state), uses of ordinary usage-tracked variables (but if dynamic env wants to record usage in order of occurrence, I think it can do that without affecting the track_use API) - how the decision of what needs recomputing is made - e.g. what kinds of inval flags, whether to diff input values before deciding, whether to do partial or incremental recomputes - with what API the recomputing is accomplished (e.g. call a supplied function, perhaps with certain args) - how invals of the current value can/should be propogated to previous users of the current value Other differences, that should *not* be reflected directly in lval classes (but that might have specific helper functions in this module): - the specific formula being recomputed (whether expressed a python compute method, an interpreted HL math expr, or a draw method) - whether some of the storage implied above (eg value caches, usage lists and their subs records, inval flags and their user lists) is stored separately from formula instances (to permit sharing of formulas) -- because if it is, then just make an lval class that calls a different kind of formula (passing it more args when it runs), but let the lval class itself be per-storage-instance - whether the lvalues reside in a single object-attr, or a dict of them -- just make an attr or dict of lvals, and have the owning class access them differently. For examples, see the classes herein whose names contain Lval. """ # WARNING: the code in here needs to be safe for use in implementing ExprsMeta, which means it should not depend # on using that as a metaclass. # == imports import sys # from modules in cad/src from foundation.changes import SelfUsageTrackingMixin, SubUsageTrackingMixin import foundation.changes as changes from utilities.debug import print_compact_traceback from utilities.Comparison import same_vals ##from utilities import debug_flags from exprs.py_utils import MemoDict, printnim MemoDict class LvalError_ValueIsUnset(AttributeError): #061117 1030p not yet raised or caught in all places where it ought to be #####e """Exception for an lval whose value was never set (nor was a compute method or initval method set). This acts like AttributeError so (I hope) hasattr will treat it as an attr not being there. But it's our own subclass so we can catch it without catching other AttributeErrors caused by our own code's bugs. """ pass # == class Lval(SelfUsageTrackingMixin, SubUsageTrackingMixin): """One invalidatable value of the most standard kind, containing its own fully bound compute method, passed to the constructor. Get the current value using .get_value() (this tells the dynenv that this value was used). Contains inval flag, subs to what it used to compute, recomputes as needed on access, propogates invals, all in standard ways. [#doc better] Change the compute method using .set_compute_method, or (use our subclass which permits you to) set new constant values using set_constant_value. """ # Implem notes: # # - This object can't be a Python descriptor (in a useful way), because its storage has to be per-instance. # [I suppose we could separate it from its storage, and then that might not be true. # But it's simpler this way, especially since we sometimes store one in a visibly-indexed dict rather than an object-attr.] # - If a descriptor (which has to be per-class) uses one of these, it has to look up the one to use in each instance. # So the only reason not to provide this Lval with a bound recompute method would be to avoid cyclic references. # At the moment, that's not crucial. # - When we want that, this still has the storage, but it can be given an owner obj each time it runs. # It could just as well be given the compute method each time; for either one, the owner has to give the same one each time # or the inval flag etc won't be correct. # - The compute method it's given (once or each time) could be a bound instance method (from a _C_attr method), # or something created from a formula on _self, also bound to a value for _self. Whatever it is, we don't care how it's made, # so we might as well accept any callable. It might be made in various ways, by descriptors or helper functions like LvalDict. # # - The mixins provide these methods, for internal use: # - SelfUsageTrackingMixin: track_use, track_change == track_inval -- # for tracking how our value is used, is changed, is indirectly invalled. # - SubUsageTrackingMixin: begin_tracking_usage, end_tracking_usage -- for tracking which values we use when we recompute. # - They're the same mixins used for displists used by chunk/GLPane and defined in chunk, and for changes to env.prefs, # so these Lvals will work with those (except for chunk not yet propogating invals or tracking changes to its display list). # - See comments near those methods in changes.py for ways they'll someday need extension/optimization for this use. valid = False # public attribute # no need to have default values for _value, unless we add code to compare new values to old, # or for _compute_method, due to __init__ def __init__(self, compute_method = None, debug_name = None): #e rename compute_method -> recomputer?? prob not. """For now, compute_method is either None (meaning no compute_method is set yet -- error to try to use it until it's set), or any callable which computes a value when called with no args, which does usage-tracking of whatever it uses into its dynenv in the standard way (which depends mainly on what the callable uses, rather than on how the callable itself is constructed), and which returns its computed value (perhaps None or another callable, treated as any other value). Note that unlike the old InvalMixin's _recompute_ methods, compute_method is not allowed to use setattr (like the one we plan to imitate for it) instead of returning a value. (The error of it doing that is detected. ###k verify) In future, other special kinds of compute_methods might be permitted, and used differently, but for now, we assume that the caller will convert whatever it has into this simple kind of compute_method. [Note: if we try to generalize by letting compute_method be a python value used as a constant, we'll have an ambiguity if that value happens to be callable, so it's better to just make clients pass lambda:val instead.] """ ## optim of self.set_compute_method( compute_method), only ok in __init__: self._compute_method = compute_method self.debug_name = debug_name #061119 ## if debug_flags.atom_debug and not debug_name: #e can we use a scheme sort of like print_compact_stack to guess the object that is creating us, # since it'll have a localvar called self? I doubt it, since some helper objs are likely to be doing the work. # So just do the work myself of passing this in intelligently... return def __repr__(self): #061119 return "<%s%s at %#x>" % (self.__class__.__name__, self.debug_name and ("(%s)" % self.debug_name) or '', id(self)) def set_compute_method(self, compute_method): "#doc" # notes: # - this might be untested, since it might not be presently used # - note the different behavior of set_constant_value (in a variant subclass) -- it's not equivalent to using this method # on a constant function, but is closer (or equiv?) to doing that and then immediately evaluating # that new compute method. (It also diffs the values as opposed to the compute methods.) # - BUG: for this to be correct, we should also discard our usage-subscriptions stemming from the eval # of the prior compute method. Not doing this might be a severe performance hit or even a bug. # But it's not easy to do. Since this is never called, that's nim for now. assert 0, "if you call this, you better first implement discarding the prior usage-subscriptions" #e or modify this assert to not complain if there are none of them (eg if there is no prior compute method, or we're valid) old = self._compute_method self._compute_method = compute_method # always, even if equal, since different objects if old != compute_method: self.inval() def inval(self): """This can be called by the client, and is also subscribed internally to all invalidatable/usage-tracked lvalues we use to recompute our value (often not the same set of lvals each time, btw). Advise us (and whoever used our value) that our value might be different if it was recomputed now. Repeated redundant calls are ok, and are optimized to avoid redundantly advising whoever used our value about its invalidation. Note that this does not recompute the value, and it might even be called at a time when recomputing the value would be illegal. Therefore, users of the value should not (in general) recompute it in their own inval routines, but only when something next needs it. (This principle is not currently obeyed by the Formula object in changes.py. That object should probably be fixed (to register itself for a recompute later in the same user event handler) or deprecated. ###e) """ if self.valid: self.valid = False # propogate inval to whoever used our value self.track_inval() # (defined in SelfUsageTrackingMixin) def get_value(self): """This is the only public method for getting the current value; it always usage-tracks the access, and recomputes the value if necessary. """ if not self.valid: try: self._value = self._compute_value() # this USED TO catch exceptions in our compute_method; as of 061118 it reraises them except: # note: might be LvalError_ValueIsUnset, or any other exception -- likely that best responses should differ ###e printnim("I need to figure out what usage to track, in what object, when a tracked attr is unset") pass ## self.track_use() -- THIS IS PROBABLY NEEDED SOMEDAY, see below -- ###tryit # GUESS 061120 1112a [later suspected wrong, see below]: # this track_use causes the duplicate track_inval bug, because we track when invalid. # and (still guessing) we do this during hasattr seeing our value is unset. it's probably wrong, because when the # val becomes set, why should something be invalled, unless it turned exception into a real value? # what might be right is to merge all the usage at this point into whatever caller turns the exception # into a real value, rather than just discarding it. # surely we don't want to include it here, not only this one, but whatever was used before... but what # do i mean by "here"? The real error is not in our mentioning the use here, i think, but in what # the caller does with it... otoh our complaint stems entirely from what happens here, so that's wrong. # I don't understand this well yet, but let's see what happens if I comment that out. # ... status, 061121 late: it didn't fix the bug, later stuff did, and I suspect it's right in theory # to track the use here, but that it won't matter in the near future. So, at some point, put this back # and see if it works or breaks, but no hurry to put it back in general. But recall it as a possible bug cause, # and if it seems to not break anything, leave it in, unlike now. raise self.valid = True # do standard usage tracking into env (whether or not it was invalid & recomputed) -- API is compatible with env.prefs # [do it after recomputing, in case the tracking wants to record _value immediately(?)] self.track_use() # (defined in SelfUsageTrackingMixin) ###e note: this will need optimization return self._value def _compute_value(self): """[private] Compute (or recompute) our value, using our compute_method but protecting ourselves from exceptions in it, tracking what it uses, subscribing our inval method to that. NOTE: does not yet handle diffing of prior values of what was used, or the "tracking in order of use" needed for that. Maybe a sister class (another kind of Lval) will do that. """ #e future: _compute_value might also: # - do layer-prep things, like propogating inval signals from changedicts # - diff old & new if self._compute_method is None: raise LvalError_ValueIsUnset, "our compute_method is not yet set: %r" % self #k note: this is a subclass of AttributeError so hasattr can work in this case [061117 late] match_checking_code = self.begin_tracking_usage() try: val = self._compute_method() # [might raise LvalError_ValueIsUnset] # WARNING: lots of dup code in the except clauses. Should make them set flags to control common code afterwards. ##e except LvalError_ValueIsUnset: # might happen from some lower layer if we're virtual (e.g. if our value is stored in some external array or dict) ###k TOTAL GUESS that it's fully legit, 061118 156p [but without it we got missing end-tracks, naturally] # note: should we set val to None and say it's valid? NO -- then of two hasattrs in a row, 2nd would be wrong. # 061121: seems ok, always happens whether or not bugs do. # But don't zap this comment til it's fully analyzed as being legit in theory. self.end_tracking_usage( match_checking_code, self.inval ) raise # note 061205: delegation code should probably catch this specifically and not delegate, unlike for attrerror. # Coded it in DelegatingMixin, UNTESTED! #####TEST except AttributeError, e: # we don't want the caller to think this attr is entirely missing, and should be delegated! # So change this to another kind of exception. # [new feature 061205, works; see comment in Highlightable about a bug it helps catch] # Revised 070131 to try to preserve the inner traceback w/o printing it more than once. Doesn't yet work. ###fix # Until it does, print the inner traceback here. if 0: msg = "AttributeError in %r._compute_method turned into a RuntimeError: %s" % (self, exc_info_summary()) print msg, "(reraising)" #070131 no traceback, to reduce verbosity else: msg = "AttributeError in %r._compute_method turned into a RuntimeError" % self print_compact_traceback(msg + ": ") self.end_tracking_usage( match_checking_code, self.inval ) ## raise RuntimeError, msg ##e change to our own kind of exception, subclass of RuntimeError, NOT of AttributeError ## raise RuntimeError(e) # this fails to include the part of the traceback from e... that info is now lost. fix sometime. raise RuntimeError, e # try this version -- seems equivalent, also doesn't work except: ## print_compact_traceback("exception in %r._compute_method NO LONGER ignored: " % self) print("(exception in %r._compute_method being reraised)" % self) # revised to not print traceback 070131, since reraised ###e 061118 we still need to print more info from this; what to do to explain errors deep in evaling some expr? # catch them and turn them into std custom exceptions, then wrap with posn/val info on each step of going up? (maybe) self.end_tracking_usage( match_checking_code, self.inval ) # legitness is a guess, but seems to be ok when it occurs raise self.end_tracking_usage( match_checking_code, self.inval ) # that subscribes self.inval to lvals we used, and unsubs them before calling self.inval [###k verify that] #e optim (finalize) if set of used lvals is empty # (only if set_compute_method or direct inval won't be called; how do we know? we'd need client to "finalize" that for us.) # note: caller stores val and sets self.valid return val def can_get_value(self): """Ignoring the possibility of errors in any compute method we may have, can our get_value be expected to work right now? [WARNING: This also doesn't take into account the possibility (not an error) of the compute method raising LvalError_ValueIsUnset; this might happen if we're a virtual lval providing access to a real one known to the compute_method. If this matters, the only good test (at present) is to try the compute_method and see if it raises that exception. That is problematic in practice since it might track some usage if it doesn't!] """ return self.valid or (self._compute_method is not None) def have_already_computed_value(self): return self.valid # even tho it's a public attr pass # end of class Lval def exc_info_summary(): #070131 #e refile "return a 1-line summary of the current exception" type, value, traceback = sys.exc_info() del traceback # not needed now, but important to del it asap if we make this fancier return "%s: %s" % (type, value) ###k # == class Lval_which_recomputes_every_time(Lval): #070108; SEVERELY DEPRECATED (see docstring) """Lval_which_recomputes_every_time(recompute_func) is like Lval(recompute_func) but acts as if recompute_func uses something which changes immediately after the current (entire) usage-tracking-recomputation is complete. This class is DEPRECATED at birth, since using it anywhere in a computation causes the entire computation to be marked invalid as soon as it completes, which in most uses of this feature would cause excessive recomputation, mostly unneeded. (For example, if a widget expr draws anything computed by this class, then it issues a gl_update immediately after every redraw, causing continuous redraw and roughly 100% cpu usage.) So don't use it, But for the record, here are some details: An lval of this kind will call its recompute function exactly once in every entire usage-tracked computation which calls self.get_value one or more times. [Note that we might invalidate long before the next recomputation, so it would not be correct to recompute at that time, compare, and only inval if the value differs (as when setting a new value in LvalForState). For that behavior, something external would have to say when a recompute and compare should be done, most easily by just recomputing and setting an LvalForState. This class is not useful for that behavior.] """ def get_value(self): res = Lval.get_value(self) changes.after_current_tracked_usage_ends( self.inval ) return res pass # == def _std_frame_repr(frame): #e refile into debug.py? warning: dup code with lvals.py and changes.py "return a string for use in print_compact_stack" # older eg: frame_repr = lambda frame: " %s" % (frame.f_locals.keys(),), linesep = '\n' locals = frame.f_locals dfr = locals.get('__debug_frame_repr__') if dfr: return ' ' + dfr(locals) co_name = frame.f_code.co_name res = ' ' + co_name self = locals.get('self') if self is not None: res +=', self = %r' % (self,) return res # locals.keys() ##e sorted? limit to 25? include funcname of code object? (f_name?) # note: an example of dir(frame) is: # ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', # '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', # '__setattr__', '__str__', 'f_back', 'f_builtins', 'f_code', # 'f_exc_traceback', 'f_exc_type', 'f_exc_value', 'f_globals', 'f_lasti', # 'f_lineno', 'f_locals', 'f_restricted', 'f_trace'] # and of dir(frame.f_code) is: # ['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', # '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', # '__repr__', '__setattr__', '__str__', 'co_argcount', 'co_cellvars', # 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', # 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', # 'co_stacksize', 'co_varnames'] def call_but_discard_tracked_usage(compute_method): #061117 "#doc [see obs func eval_and_discard_tracked_usage for a docstring to cannibalize]" lval = Lval(compute_method) # lval's only purpose is to discard the tracked usage that is done by compute_method() res = lval.get_value() # this calls compute_method() #e destroy lval? #e future: option to tell caller whether or not we tracked any usage?? return res def make_compute_method_discard_usage_if_ever_called(compute_method): #061117 "change a compute_method into one which discards its tracked usage if it's ever called (but don't call it now!)" return lambda _guard = None, compute_method = compute_method: call_but_discard_tracked_usage(compute_method) #e and assert not _guard # == class StateRefInterface( object): #070312; experimental; see also staterefs.py """Anything with a .get_value and .set_value method, combined into a .value attribute (public for get and set), which act as accessors of the obvious (I hope) semantics for a definite piece of state, conforms to the "stateref interface". Inheriting this abstract class (StateRefInterface), by convention, indicates informally that something intends to conform to that interface. It would be nice if this class could also provide default methods for that interface, either get_value and set_value in terms of .value or value in terms of those (i.e. value = property(get_value, set_value)). But it doesn't, because providing both directions of default is not practical (for a superclass), and providing get_value and set_value in terms of .value is not very useful, and providing value = property(get_value, set_value) (with those methods coming from a subclass) doesn't seem to be possible in a straightforward way in Python. So, as a superclass it provides no default methods. [Maybe someday it can usefully provide them when used in some other way to "add glue code for an interface". #e] """ pass class LvalForState(Lval, StateRefInterface): #061117 -- NOT REVIEWED AS WELL AS I'D LIKE (esp since split out from its superclass, and initvals enabled) """A variant of Lval for containing mutable state. Can be given an initval compute method -- but that's required if and only if the first get comes before the first set; it's computed at most once, at the moment it's needed (even if it has a time-varying value). """ # This differs from Lval because it has to discard tracked usage from its compute_method, # which it uses only to initialize its value in the event it's gotten-from before being set. # That's a semantic difference which invites bugs unless we make it a different class. # #e optim note: we could specialize _compute_value to not bother doing usage tracking. def __init__(self, initval_compute_method = None, debug_name = None): # make sure our initval compute method will discard usage it tracks, so we'll call it at most once # (only if and when we're gotten-from before we're first set) if initval_compute_method is not None: compute_method = make_compute_method_discard_usage_if_ever_called( initval_compute_method) else: compute_method = None Lval.__init__(self, compute_method = compute_method, debug_name = debug_name) def set_compute_method(self, compute_method): assert 0, "not supported in this class" #e i.e., Lval and this class should really inherit from a common abstract class def set_constant_value(self, val): #061117, for use in StatePlace.py ###e probably set_constant_value should be renamed set_value, to fit with StateRefInterface [070312] """#doc [for now, using this is strictly an alternative to using compute_methods -- correctness of mixing them in one lval is not reviewed, and seems unlikely, with one exception: an initial compute_method can be provided for computing an initial value in case the value is asked for before being set, BUT IT'S AN ERROR IF THAT TRACKS ANY USAGE. So we enforce this by being in a variant subclass of Lval.] """ # note: this is inlined into _set_defaultValue ## if self.valid and self._value == val: # THIS HAS THE BUG of numeric arrays being == if any element is ==. ## if self.valid and not (self._value != val): # still not correct, but more often correct, and did fix my loss-of-drag bug... if self.valid and same_vals(self._value, val): pass # important optim, but in future, we might want to only sometimes do this # (eg have another variant class which doesn't do it) else: self._value = val # do this first, in case an outsider (violating conventions? At least for Lval, maybe not for us) # happens to notice self.valid being true during track_inval, so they won't be misled by an incorrect self._value if self.valid: self.track_inval() # (defined in SelfUsageTrackingMixin) # WARNING: self.valid is True for us during our call of track_inval, # but is False for Lval's call of it. # For our call, we only need to propogate invals if we were valid # (since if not, we propogated them when we became invalid, or # (more likely, assuming we're not mixing this with compute methods) [###k review re initial value compmethod] # we were never valid); but during that propogation, we'll remain valid # and have our new value available (permitting queries of it during inval propogation, # though that violates the convention used for the compute_method style). # [#e BTW isn't track_inval misnamed, since it's really to propogate or report our inval, not to track it?] else: self.valid = True pass return #070312 conform to StateRefInterface set_value = set_constant_value #e or just rename the latter? ## value = property(get_value, set_value) # NameError: name 'get_value' is not defined value = property(Lval.get_value, set_value) # -- ## value = property(Lval.__dict__['get_value'], set_value) #k I think the methods can_get_value and have_already_computed_value # are correct for us, as implemented in our superclass Lval. def _set_defaultValue(self, defaultValue): """If attr is not set, set it to defaultValue; never do any usage or change tracking. (WARNING: This will cause bugs unless all providers of access to a given attribute-instance use this consistently (same default value, and all of them using this rather than some of them providing access to the attr with no default value); they must all use it before providing access to that attr to any client object.) """ # see comments in set_default_attrs about why we need this to do no usage or change tracking if self.valid: return # easy case # Dilemma: we might have no value, or we might have one computable by an initial-value compute method... # or we might have such a method which will raise LvalError_ValueIsUnset when we try it # (e.g. valfunc method in some client code). The only way to find out is to use that method, # but what if doing so tracked some usage? I think it's normal for that to happen... # OTOH, it's not correct, I think, to have two inconsistent ways of setting a default value -- # code that calls this, vs. code that supplies an initial-value compute method that actually works. # So, maybe we should be able to ask the method which kind it is... but for now, assume it could # be either. If it computes a real value, we better not run it now, since usage would get tracked... # though that's an error... one way to detect is to return now and let it run, but that led to infrecur # in self.delegate in If.cond (don't know why). But setting defaultValue now risks hiding bugs. # That leaves: run it now, asserting no usage tracking. [Note: current calling code redundantly asserts the same thing. #e] # # One case which is not covered: something asked if we were set, was told "we're unset", and tracked its usage of us. # Ideally we'd assert right here that we have no current inval-subscribers. ####e DOIT # (For now, if we *do* have subscribers who learned we were unset, and if we leave them untouched, # it's indeed a bug that they asked that before we were initialized, but it's not so bad that they'll # get invalled when something changes us later.) printnim("assert no current inval-subscribers") mc = changes.begin_disallowing_usage_tracking('_set_defaultValue in %r' % self) # note: the argument is just an explanation for use in error messages ##e OPTIM: don't precompute that arg try: try: val = self._compute_value() # don't call get_value since it calls track_use except LvalError_ValueIsUnset: # this is the only non-error case! # (the following just inlines self.set_constant_value(defaultValue):) self._value = defaultValue self.valid = True ## print "_set_defaultValue returning after set" return except: # any other exception, including discovering usage tracking in that computation [once that works when it happens], # should be reported, but then (I think) needn't prevent this from working. print_compact_traceback("error: exception (ignored) in _set_defaultValue trying initval-computation in %r: " % self) self._value = defaultValue self.valid = True return else: # If a value was computed, that conflicts with using this method... report that error (even if the values agree), # but which value should we use? Let's use the computed one for now. # NOTE: In present code [061121], this can also happen if usage tracking occurred, since it's not detected # until the end_disallowing_usage_tracking call below (since begin_disallowing_usage_tracking is not fully # implemented). print "error: %r computed initial value %r (using it) but was also given an explicit _set_defaultValue(%r)" % \ (self, val, defaultValue) self._value = val self.valid = True return pass finally: changes.end_disallowing_usage_tracking(mc) pass # end of method _set_defaultValue def inval(self): msg = "inval in LvalForState is probably a bug indicator; not sure, remove this if needed" #061121 print msg assert 0, msg pass # end of class LvalForState # == ###@@@ class LvalForUsingASharedFormula(Lval): #stub -- do we need this? for a formula on _self shared among several instances """[pass _self to _compute_value?] """ pass # == def LvalDict1(wayfunc, lvalclass = Lval): #e option to not memoize for certain types of keys (like trivials or errors)?? this or Memo? """An extensible dict of lvals of the given lval class, whose memoized values will be recomputed from dict key using wayfunc(key)(). It's an error (reported [nim? not anymore i think] in MemoDict) for computation of wk = wayfunc(key) to use any external usage-tracked lvalues, but it's ok if wk() does; subsequent inval of those lvals causes the lval created here to recompute and memoize wk() on demand. This is more useful than if the entire dict had to be recomputed (i.e. if a _C_ rule told how to recompute the whole thing), since only the specific items that become invalid need to be recomputed. Design note: DO WE RETURN THE LVALS or their values?? For now, WE RETURN THE LVALS (partly since implem is easier, partly since it's more generally useful); this might be less convenient for the user. [But as of 061117, StatePlace.py will depend on this, in our variant LvalDict2.] Deprecation note: LvalDict2 is probably better to use. This LvalDict1 has not quite been deprecated in its favor, but almost. """ #k Note: # I'm only 90% sure the "wayfunc = wayfunc, lvalclass = lvalclass" lambda closure kluge is still needed in Python, in this case. # I know it's needed in some cases, but maybe only when they are variables?? # More likely, whenever the lambda is used outside their usual scope, as it is in this case. return MemoDict( lambda key, wayfunc = wayfunc, lvalclass = lvalclass: lvalclass( wayfunc(key)) ) def LvalDict2(valfunc, lvalclass = Lval, debug_name = None): """Like LvalDict1 but uses a different recompute-function API, which might be easier for most callers to supply; if it's always better, it'll replace LvalDict1. [not sure yet -- that has one semiobs use with a comment saying to try 2 instead] In this variant, just pass valfunc, which will be applied to key in order to recompute the value at key. """ return MemoDict( lambda key, valfunc = valfunc, lvalclass = lvalclass, debug_name = debug_name: lvalclass( lambda valfunc=valfunc, key=key: valfunc(key), debug_name = debug_name and ("%s|%s" % (debug_name,key)) ) ) class RecomputingMemoDict: # 061215 scratch, not yet used, might relate to comments in ModelNode.py """Like MemoDict, but permit usage-tracked recomputes by <way> (invalidating/recomputing our elements individually), which means the values we return for a given key might not be constant. [WARNING: we don't implement most dict-access methods, only __getitem__.] """ def __init__( self, way, lvalclass = Lval, debug_name = None): ##e and more options, if LvalDict2/MemoDict provides them, like canon_key?? self._lvals = LvalDict2( way, lvalclass = lvalclass, debug_name = debug_name) ## dict.__init__(self) #k will this mean that other dict-access methods (like len, keys, items) work property? no... # so what's the point?? no point, it'd just be promising what it can't deliver. Should create a value-filtered-dict or so... #e def __getitem__(self, key): lval = self._lvals[key] return lval.get_value() # might recompute (and track usage into lval), that's ok pass # end
NanoCAD-master
cad/src/exprs/lvals.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ __Symbols__.py -- support for "from __Symbols__ import xxx", to make a shared Symbol object within the exprs module. $Id$ NOTE: This module replaces its entry in sys.modules with a _FakeModule_for_Symbols object. That object probably doesn't support reload. So this module is effectively not reloadable. TODO: it might be possible to make this reloadable by passing in a new version of getattr_func, or if the reload would occur in here, passing in a source for new getattr_funcs. The Python 2.3 new import hooks might also help with this. Details not yet analyzed. """ __author__ = "bruce" # (but I took the idea of _FakeModule_for_Symbols # from Pmw == Python Megawidgets) from exprs.Exprs import Symbol ### TODO: remove this import cycle, here or (preferably?) in Exprs class _FakeModule_for_Symbols: """ An object which can take the place of a real module in sys.modules, for some purposes. Used as a singleton. Comments and messages assume it's used to create "Symbols". """ # make sure all of our private attrs or methods start with '__' __getattr_func = None # initial value of instance variable def __init__(self, name, getattr_func = None): self.__name__ = name # note: self.__file__ can be assigned by caller, if it wants self.__path__ = "fakepath/" + name #k ok? maybe not, it might be some sort of dotted import path -- # better look it up ####@@@@ self.__set_getattr_func(getattr_func) # might be None def __repr__(self): # only used in bug messages; UNTESTED return "<%s(%r) at %#x>" % (self.__class__.__name__, self.__name__, id(self)) def __set_getattr_func(self, getattr_func): assert self.__getattr_func is None self.__getattr_func = getattr_func def __clear_getattr_func(self): # not yet used self.__set_getattr_func(None) def __getattr__(self, attr): # in class _FakeModule_for_Symbols if attr.startswith('__'): raise AttributeError, attr assert self.__getattr_func, "bug: symbol source not yet set in %r" % (self,) res = self.__getattr_func(attr) setattr(self, attr, res) # cache the value of this attr for reuse return res pass import sys ## print "__name__ of exprs.__Symbols__ is %r" % (__name__,) # 'exprs.__Symbols__' ## print dir() # ['_FakeModule_for_Symbols', 'Symbol', '__author__', '__builtins__', ## # '__doc__', '__file__', '__name__', 'sys'] sys.modules[__name__] = fakemodule = _FakeModule_for_Symbols(__name__, Symbol) fakemodule.__file__ = __file__ # REVIEW: does __file__ work in a Windows release build? # Guess: yes, since this is also assumed in canon_image_filename (exprs/images.py) # which I think is always run due to confirmation corner. # It doesn't exist in __main__ (or didn't at one time anyway) # but I guess that's a special case. It would be good to confirm all this. # [bruce 080111 comment] fakemodule.__doc__ = __doc__ # note: __name__ and __path__ are set inside _FakeModule_for_Symbols.__init__ """ >>> print dir(fakemodule) fyi: fakemodule getattr got __members__ fyi: fakemodule getattr got __methods__ ['_FakeModule__getattr_func', '__doc__', '__file__', '__getattr__', '__init__', '__module__', '__name__', '__path__'] """ # end
NanoCAD-master
cad/src/exprs/__Symbols__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @version: $Id$ TODO: as of 2008-02-12 This is a non-working DragBehavior_AlongCircle class , not called anywhere. """ from exprs.Highlightable import SavedCoordsys from exprs.geometry_exprs import Ray from exprs.Exprs import tuple_Expr from exprs.attr_decl_macros import Arg, Option, Instance from exprs.ExprsConstants import StateRef ##, ORIGIN from exprs.__Symbols__ import Anything from exprs.DragBehavior import DragBehavior class DragBehavior_AlongCircle(DragBehavior): """ A drag behavior which moves the original hitpoint along a line, storing only its 1d-position-offset along the line's direction [noting that the hitpoint is not necessarily equal to the moved object's origin] [#doc better] """ highlightable = Arg(Anything) rotation_parameter_ref = Arg(StateRef, doc = "where anything proportional to angle is stored") #translation_parameter_ref = Arg(StateRef, #doc = "where translation is stored") origin = Arg(StateRef, doc = "handle base point") center = Arg(StateRef, doc = "center of the circle") axis = Arg(StateRef, doc = "circle axis") radiusVector = Arg(StateRef, doc = "radius of circle") locked_parameter = Option(tuple_Expr, None, doc = "locked parameter") range_for_rotation = Option(tuple_Expr, None, doc = "range limit of angle of rotation") range_for_translation = Option(tuple_Expr, None, doc = "range limit of translation") # provides transient state for saving a fixed coordsys to use throughout #a drag saved_coordsys = Instance( SavedCoordsys() ) # helper methods (these probably belong in a superclass): def current_event_mousepoint(self, *args, **kws): return self.saved_coordsys.current_event_mousepoint(*args, **kws) def current_event_mouseray(self): p0 = self.current_event_mousepoint(depth = 0.0) # nearest depth ###k p1 = self.current_event_mousepoint(depth = 1.0) # farthest depth ###k return Ray(p0, p1 - p0) # specific methods def _C__rotation(self): """ Compute self._rotation from the externally stored rotation paramater """ k = self.rotation_parameter_ref.value ##rotation = k*self.radiusVector #REVISE THIS from geometry.VQT import norm return self.origin#self.radiusVector + k*norm(self.radiusVector) def on_press(self): self.saved_coordsys.copy_from( self.highlightable) self.startpoint = self.current_event_mousepoint() #Formula needs to be revised. ##self.offset = self.startpoint - (ORIGIN + self._rotation) ##self.circularPath = self.constrain_to_circle + self.offset def on_drag(self): mouseray = self.current_event_mouseray() ##k = self.circularPath.closest_pt_params_to_ray(mouseray) k = None if k is not None: # store k, after range-limiting if self.range_for_rotation is not None: low, high = self.range_for_rotation if low is not None and k < low: k = low if high is not None and k > high: k = high self.rotation_parameter_ref.value = k ##e by analogy with DraggableObject, should we perhaps save this ##side effect until the end? return def on_release(self): pass
NanoCAD-master
cad/src/exprs/DragBehavior_AlongCircle.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ instance_helpers.py -- provides InstanceOrExpr and some related things @author: Bruce @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. History (partial): 070129 moved still-nim GlueCodeMemoizer into new file Column_old_nim.py 070815 split IorE_guest_mixin superclass out of InstanceOrExpr and moved it into a new file """ from exprs.lvals import LvalError_ValueIsUnset ## from lvals import LvalDict1 # only needed by obs code from exprs.widget_env import thisname_of_class, widget_env #e refile import?? or make it an env method?? from utilities.debug import print_compact_traceback from utilities.debug import print_compact_stack from exprs.Exprs import is_pure_expr from exprs.Exprs import is_expr_Instance from exprs.Exprs import SymbolicExpr, canon_expr from exprs.Exprs import expr_is_Instance from exprs.Exprs import expr_constant_value from exprs.Exprs import is_Expr_pyclass from exprs.Exprs import EVAL_REFORM from exprs.py_utils import printnim from exprs.py_utils import printfyi from exprs.IorE_guest_mixin import IorE_guest_mixin from exprs.StatePlace import StatePlace from exprs.attr_decl_macros import Instance, Arg from exprs.ExprsConstants import normalize_color from exprs.__Symbols__ import _self # == # maybe merge this into InstanceOrExpr docstring: """ Instances of subclasses of this can be unplaced or placed (aka "instantiated"); if placed, they might be formulas (dependent on aspects of drawing-env state) for appearance and behavior (justifying the name Drawable), or for some value used in that (e.g. a color, vector, string). Specific subclasses, e.g. Rect, contain code which will be used in placed instances (mainly drawing code) unless the env provided an overriding expansion for exprs headed by that subclass. If it did, the instance created by placing such an expr will (usually) have some other class. """ # note about nonexistent class IorE: IorE is a common abbreviation for class InstanceOrExpr. class InstanceOrExpr(IorE_guest_mixin): # see docstring for discussion of the basic kluge of using one class for both """ Main superclass for specific kinds of Instance classes whose python instances can be either Instances or Exprs, and (more importantly for the user) whose use as a constructor usually constructs an Expr. Used (for example) for Column, Rect, If, Widget2D, etc. See elsewhere for general explanation [#nim]. The rest of this docstring discusses some fine points of the class semantics and implementation, and possible changes to them. Kluge: the same class is used to represent both Exprs and Instances of the same type; the difference is encoded in self._e_is_instance, and is constant throughout one python-instance's lifetime (after it's fully constructed, which means, after __init__ and perhaps after immediately subsequent private methods in another Expr which created it). Many methods either assert a specific state for self._e_is_instance, or branch on it (or ought to #e). Pro: developer can create and use just one class, e.g. Rect, needing no other setup/registration except defining it, to both hold the Rect Instance methods, and serve as the Rect Expr constructor. The Instance methods can be written (after an initial assertion) as if self is the Instance (as opposed to self.instance, or some argument they receive), and (to avoid unpleasant surprises) that's actually true. And the class as constructor always constructs a Python instance of itself, as one would expect. Con: the Instance methods could be accidently requested in an Expr version, or vice versa; their very presence might mess up some semantics, since it's generally bad if expr.attr does anything except construct a getattr_Expr. The motivations above are not obviously good enough to justify the bug risk and internal-method unclarity. Possible issues in present implem: constant_Expr(10) is in some sense both an Expr *and* an Instance. The predicates don't yet account for this. And logic bugs in the whole scheme may yet show up. Possible alternative: these classes could represent only Instances, but still be usable as Expr constructors, by having __new__ create a separate (nim) ExprForInstanceOrExpr object which is not a subclass of this class, but which knows which subclass of this class to create when it needs to make Instances from itself. If this was done, much of the code in this specific class InstanceOrExpr would be moved to ExprForInstanceOrExpr, which might be renamed to be more general since it would really apply to any Expr which can be called, remaining an Expr but having its option formulas customized or its arg formulas supplied, and can then later be instantiated in an env to produce a specific Instance based on those formulas. """ #e rename to: ExprOrInstance? # [maybe, until i rename the term Instance, if i do... con side: most methods in each one are mainly for Instance, except arg decls, # and even they can be thought of mostly as per-instance-evalled formulas. So when coding it, think Instance first.] # PatternOrThing?[no] ### WARNING: instantiate normally lets parent env determine kid env... if arg is inst this seems reversed... # may only be ok if parent doesn't want to modify lexenv for kid. # standard stateplaces (other ones can be set up in more specific subclasses) # [following 3 StatePlaces moved here from Highlightable & ToggleShow, 061126 late; # these comments not yet reviewed for their new context: ###doc] # # refs to places to store state of different kinds, all of which is specific to this Instance (or more precisely to its ipath) ##e [these will probably turn out to be InstanceOrExpr default formulae] [note: their 2nd arg ipath defaults to _self.ipath] # OPTIM QUESTION: which of these actually need usage/mod tracking? They all have it at the moment [not anymore, 061121], # but my guess is, per_frame_state doesn't need it, and not providing it would be a big optim. [turned out to be a big bugfix too!] # (We might even decide we can store all per_frame_state in self, not needing a StatePlace at all -- bigger optim, I think. # That can be done once reloading or reinstancemaking is not possible during one frame. I'm not sure if it can happen then, # even now... so to be safe I want to store that state externally.) # transient_state moved to a superclass 070815 glpane_state = StatePlace('glpane', tracked = False) # state which is specific to a given glpane [#e will some need tracked=True?] per_frame_state = StatePlace('per_frame', tracked = False) # state which is only needed while drawing one frame (someday, cleared often) # (this is probably also specific to our glpane; note that a given Instance has only one glpane) model_state = StatePlace('model') # state that's part of the model (i.e. stored/copied with model objects) ### NOT YET USED [070213] untracked_model_state = StatePlace('untracked_model', tracked = False) # model state, not change/usage-tracked (e.g. counters for allocating unique index-components or name-components) [070213] # abbrevs for read-only state [#e should we make them a property or so, so we can set them too?] glname = glpane_state.glname # (note, most things don't have this) # instance variable defaults (names must start with _e_ or _i_, or they'll cause trouble for non-Instance getattr_Expr formation) _i_model_type = None # experimental, perhaps a kluge, 070206; WARNING: set externally on some specific Instances in world.py ## _e_model_type = None # 070215 (not sure if it supercedes the above) -- type of model obj an expr intends to construct (if known) # note: the value of _e_model_type can just be a string, or a fancier object (###NIM and probably not yet handled) # do we compute a type on exprs which can be _e_model_type or classname but only for ModelObjects? (else delegate to one?) # (or for pure graphicals can it be classname too? yes, they can be shapes in the model -- maybe their class needs to say so?) # do instances ever have a different model_type than their expr predicted? # (seems possible -- main use of expr one is for sbar_texts & cmenu item texts, ie UI predictions of what an expr can make) # sceptic: do exprs need this, or do we need special expr-like Instances to reside in eg PalletteWell, which have a special # interface "maker" and know the type of what they can make? But aren't exprs similar to makers anyway? # (even if so, must they be wrapped to be one? evidence for that might be if there are any params about how to make with them. # but i think not, since they're useable to make things "out of the box"... what if each thing wants params, do you want # to customize that beyond what the expr knows about args/state, and think of that as maker params??) # Is the real issue for determining the attrname/methodname not "model" or "expr" but "what you make vs what you are"?? ###k def _e_model_type_you_make(self): ###k 070215 very experimental #e move below init """ #doc; overridden on some subclasses, notably DelegatingInstanceOrExpr """ # but lots of specific DIorE don't delegate it... # model obj DIorE don't, but graphical ones do. For now assume we know by whether it's subclass of ModelObj. # This implem is meant for graphical prims like Rect. # ok for expr but wrong for instance! actually, not true - inst makes itself! so wrong for an explicit Maker I guess... return self.__class__.__name__.split('.')[-1] ##e see where else we have that code, maybe world.py; have classattr to override? def __init__(self, *args, **kws): # note: just before any return herein, we must call self._e_init_e_serno(), so it's called after any canon_expr we do; # also, the caller (if a private method in us) can then do one inside us; see comment where this is handled in __call__ ###e does place (instanceness) come in from kws or any args? # initialize attrs of self to an owned empty state for an expr self._e_kws = {} # need a fresh dict, since we own it and alter it during subsequent parts of init (??) # handle special keywords (assume they all want self to be initialized as we just did above) val = kws.pop('_copy_of', None) if val: assert not args and not kws self._destructive_copy(val) self._e_init_e_serno() return val = kws.pop('_make_in', None) if val: assert not args and not kws self._e_init_e_serno() #070121 moved this before _destructive_make_in, so it sees serno in prints, # and since AFAIK the desire to have later serno than our kids only applies to pure exprs, not Instances ##k self._destructive_make_in(val) return # assume no special keywords remain self._destructive_init(args, kws) IorE_guest_mixin.__init__(self) # must be done after _destructive_init return def __call__(self, *args, **kws): new = self._copy() new._destructive_init(args, kws) new._e_init_e_serno() # note, this "wastes a serno" by allocating a newer one that new.__init__ did; # this is necessary to make serno newer than any exprs produced by canon_expr during _destructive_init return new # I'm not sure whether this unfinished _i_type and _e_delegate_type code will be used -- for now, leave it but comment it out [070206] ## _e_delegate_type = False # subclass-specific constant -- whether Instance type determination should be delegated to self._delegate ## ## def _i_type(self): #070206 ## """Return something that represents the type of Instance or Expr we are. ## (This is not the same as Python type. For more info on what we return, see ###doc.) ## WARNING: preliminary implem, several implicit kluges. ## NOTE: _e_delegate_type should be True in any delegating subclass, *if* the delegate's type ## should be treated as self's type. This has to be determined by each specific subclass -- ## it's true for wrapper-like delegators (e.g. Translate) ## but not true for Macro-like ones, and there is not yet a formal distinction between those ## (though this makes it clear that there should be ###e). ## """ ## if self._e_is_instance: ## if self._e_delegate_type: ## return self._delegate._i_type() ## name = self.__class__.__name__ ## else: ## name = "Expr" ###e include something about the predicted instance type? what if it's condition- or time-varying? ## # maybe only include it if an outer level includes a type-coercer?? ## return name # deprecated public access to self._e_kws -- used by _DEFAULT_ decls def custom_compute_method(self, attr):###NAMECONFLICT? """ return a compute method using our custom formula for attr, or None if we don't have one """ try: formula = self._e_kws[attr] except KeyError: # caller will have to use the default case [#k i think] return None printnim("custom_compute_method likely BUG: uses wrong env for _self") # could fix by passing flag or env to _e_compute_method? printnim("assume it's a formula in _self; someday optim for when it's a constant, and/or support other symbols in it") #k guess: following printnim is wrong, should be in return None case -- verify then fix (or remove this entire feature) printfyi("something made use of deprecated _DEFAULT_ feature on attr %r" % (attr,)) ###e deprecated - remove uses, gradually # in fact, reviewing the uses 070120, there are none left, and the last ones in widget2d went away long ago. ###e ZAP IT return formula._e_compute_method(self, '@' + attr) #k index arg is a guess, 061110 # copy methods (used by __call__) def _copy(self, _instance_warning = True): ## assert not self._e_is_instance ## ??? [061019] if self._e_is_instance and _instance_warning: print "WARNING: copying an instance %r" % (self,) # this might be ok... return self.__class__(_copy_of = self) # this calls _destructive_copy on the new instance def copy(self):#061213 experiment, used in demo_drag.py, background.copy(color=green) ###k """ copy an expr or instance to make a new expr with the same formulas [experimental] """ return self._copy(_instance_warning = False) def _destructive_copy(self, old): """ [private] Modify self to be a copy of old, an expr of the same class. """ assert not self._e_is_instance # self has to own its own mutable copies of the expr data in old, or own objects which inherit from them on demand. self._e_kws = dict(old._e_kws) ###k too simple, but might work at first; make it a FormulaSet object?? self._e_args = old._e_args # not mutable, needn't copy; always present even if not self._e_has_args (for convenience, here & in replace) self._e_has_args = old._e_has_args return # common private submethods of __init__ and __call__ def _destructive_init(self, args, kws): """ [private, called by __init__ or indirectly by __call__] Modify self to give it optional args and optional ordinary keyword args. """ assert not self._e_is_instance if kws: self._destructive_customize(kws) if args or not kws: self._destructive_supply_args(args) return def _destructive_customize(self, kws): """ [private] Destructively modify self, an expr, customizing it with the formulas represented by the given keyword arguments. """ assert not self._e_is_instance # self._e_kws dict is owned by every non-instance customized expr (inefficient?) # but it's shared by Instances and their expr templates # don't do this, since we need canon_expr: ## self._e_kws.update(kws) for k,v in kws.iteritems(): self._e_kws[k] = canon_expr(v) return def _destructive_supply_args(self, args): """[private] Destructively modify self, an expr, supplying it with the given argument formulas. """ assert not self._e_is_instance assert not self._e_has_args, "not permitted to re-supply already supplied positional args, in %r" % self # added message 061126 self._e_has_args = True # needed in case args are supplied as () args = tuple(map(canon_expr, args)) self._e_args = args # also store the args in equivalent options, according to self._args declaration # Q: Should we do this on instantiation instead? # A: Probably not -- if you supply an option by positional arg, then later (i.e. in a later __call__) by named option, # maybe it should work (as it does now in the following code), or maybe it should be an error, # but it probably shouldn't be silently ignored. # Note: right now, since internal & public options are not distinguished, you could do funny things like # customize the value of _args itself! That might even make sense, if documented. _args = getattr(self, '_args', None) #e make a class attr default for _args if _args and 'kluge 061113': if self._e_is_symbolic: # as of 061113 late: happens to _this when constructing _this(class) (I think) -- # not yet sure whether/how to fix it in SymbolicExpr.__getattr__, # so fix it like this for now... # as of 061114 I think it will never happen, so also assert 0. printnim("better fix for _args when _e_is_symbolic??")##e assert 0 # see above comment _args = None if _args: printfyi( "_args is deprecated, but supported for now; in a pyinstance of %r it's %r" % (self.__class__, _args) )#061106 if type(_args) is type(""): # permit this special case for convenience _args = (_args,) if not (type(_args) is type(())): # note: printed only once per value of _args (which might be lots of times, but not as many as for each error) printnim( "_args should have type(()) but doesn't; its value is %r" % (_args,) ) # this once happened since I said ('thing') when I meant ('thing',). Should the first case be allowed, # as a special case for convenience? Probably yes, since the values have to be strings. # We could even canonicalize it here. ###e also extend the decl format for equiv of * or **, and rename it _argnames or something else (see small paper note) args = self._e_args argnames = _args for i in range(min(len(argnames), len(args))): name = argnames[i] val = args[i] assert type(name) is type("") self._e_kws[name] = val continue pass # Q. When do we fill in defaults for missing args? A. We don't -- the above code + options code effectively handles that, # PROVIDED we access them by name, not by position in self._e_args. (Is it reasonable to require that?? ###k) # Q. When do we type-coerce all args? For now, I guess we'll wait til instantiation. [And it's nim.] # [later 061106: handled by Arg macro.] printnim("type coercion of args & optvals") printnim("provision for multiple arglists,") printnim("* or ** argdecls,") printnim("checking for optnames being legal, or not internal attrnames") # Note: this scheme needs some modification once we have exprs that can accept multiple arglists... # one way would be for the above assert [which one? I guess the not self._e_has_args] # to change to an if, which stashed the old args somewhere else, # and made sure to ask instantiation if that was ok; but better is to have a typedecl, checked now, which knows if it is. ###@@@ return # from _destructive_supply_args # instantiation methods def _e_make_in(self, env, ipath): """ Instantiate self in env, at the given index-path [by default] [or return an existing instance at that ipath??]. [Note [semi-obs]: as of some time before 061110, this is usually called via _e_eval; and as of 061110 it's probably always called that way; probably they'll be merged at some point, unless some subtle difference is discovered (e.g. related to finding memoized instances).] [Later note, 070115: soon the "eval reform" will mean this is no longer called by _e_eval.] """ ##print "_e_make_in%r" % ((self, env, ipath),) #k is this ever called? [061215 Q] -- yes, lots of times in a single test. # of course it runs, _e_eval calls it... which will change when we do the eval/instantiate reform, maybe soon. [070112] assert env #061110 # no need to copy the formulas or args, since they're shared among all instances, so don't call self._copy. [###k still true?] # instead, make a new instance in a similar way. printnim("_e_make_in needs to replace _self with env._self in our externally-sourced formulas") #####@@@@@ 061110 # or could it do this when running them, eg by having a different env to run them in? not sure, they might get further # modified when we get customized... but my guess is this would work... come to think of it, the env they need is the # one passed here, and what goes wrong is that we run them in a modified env with new self stored as _self, # btu that's only appropriate for the built-in formulas, not the passed ones, for which the passed env is the best. # but we have some formulas that combine builtin & passed parts... # should we just wrap these outside formulas by something to drop one layer from env, # knowing we always modify it by adding _self? Better would just be something to replace env. # Note I could store them shared, and wrap them as I retrieve them, I think -- in _i_grabarg. # BTW is it desirable for everything in env, or just _self? what about ipath? #####@@@@@ ## assert not self._e_is_instance if self._e_is_instance: # new feature 070106, experimental but seems sensible/principled (since same as for constants like pyobjs) and desirable; # I'm sure about ignoring ipath but not completely sure about ignoring env, but it's my best guess, # and I don't know how *not* to ignore it. If you want a shared instance, this does it (see testexpr_26 for a demo # and some discussion); if you wanted mostly-shared but different instances, try something fancier. ## print "fyi: instantiating an instance returns it unchanged: %r" % self # works fine, no need to print for now # Q: Will we want to print this once per created main instance in which it happens, to warn about accidental use # of this new feature? # A: I doubt we need to, since in a long time when this was an assertfail, I never saw it until I wanted to # draw one instance twice (in testexpr_26). # [update 070117 re EVAL_REFORM -- we might do this in a caller, env.make, and perhaps make that the only caller, # so it has the same noop special case for "numbers used as exprs" too ####e] if EVAL_REFORM: print("_e_make_in called on Instance even after EVAL_REFORM -- shouldn't widget_env.make or _i_instance intercept that?") #### in fact, _i_instance should intercept it, so it ought to never happen, so use print not printfyi. 070117 return self else: return self ####e 070115: Here is where I think we need to ask self to decide what ipath a new instance should have, # and then if an old one is there and not out of date (which may involve comparing its init-expr to self??), return it. # (We may want to optimize the expr-compare by interning those exprs as we work. Maybe one could point to the other as equal? # Is there any way that can optim the discovery that they're *not* equal, as full interning can? #e) # Alternatively, maybe the caller should ask about this first (perhaps using a larger containing expr)? No, I doubt it. printnim("optim (important): decide what ipath a new instance should have, and if a valid old one is there, return it")#070115 return self.__class__(_make_in = (self,env,ipath)) # this calls _destructive_make_in on the new instance # note: if you accidentally define __init__ in your IorE subclass, instead of having it get its args using Arg etc, # you might get an exception here something like "TypeError: __init__ got an unexpected keyword argument _make_in". [070314] def _destructive_make_in(self, data): """ [private] This is the main internal instantiation-helper method. For expr, env, ipath = data, modify self (which initially knows nothing) to be an instance of expr, in the given env, at the given index-path. Called only from __init__, when self knows nothing except its class. """ ## printnim("make_in needs to replace _self in customization formulas with _self from env")#061110 313p # 061113 Q: what's the status of this? does _e_eval or _e_compute_method do it somehow, making this obs?? # or is it truly nim -- but if so, how does _self work in args inside _value in Boxed? oh, that's not customized, # rel to Boxed -- but it is, rel to the exprs in _value, which is what counts. hmm... # now I'm recalling something about lexenv_Expr fixing this (& it's dated later same day, 061110)... # yes, that fixes it inside grabarg; I am guessing it can be optimized to once per instance once we have # simplify to do that to most of grabarg; that scheme means instances of custom exprs can share formulas. # A: so I'll comment out this printnim. # Q: where & how should we replace _this(class) with the lexically innermost object of that class? ####@@@@ # Can it be computed at runtime, so we can turn it into a macro? Does the debug code to print selfs of outer envs # do the right thing, or would that be too dynamic? Do we *want* it to be dynamic, so we can use it when writing # display mode customizations to refer to things in which our instances will be contained? If so, do instances # know their parents? # For initial uses, we might not care about these "details"! Possible initial kluge implem: let _this(class) # turn into an instance itself, which figures out at runtime what to delegate to. Doing this below, "class _this". # WRONG, next day 061114 I'm doing it differently: _this(class) turns into an internal_Expr. Still found as "class _this". printnim("should make_in worry about finding an existing instance at the same index?") # guess: no, it'd be obsolete; not sure. #061110 313p # update 070120: our caller _make_in wants to handle this -- by this time, a new self exists so it's too late or wasteful. expr, env, ipath = data ###@@@ might want to split env into rules (incl lexenv) & place (incl staterefs, glpane) assert env #061110 assert not self._e_is_instance #e remove when works assert not expr._e_is_instance # copy all pure-expr things [order of several sections here revised, 070120] self._e_has_args = expr._e_has_args #k ?? # copy references to _e_args & _e_kws # note: exprs passed to specific args or kws can be lazily type-coerced and instantiated by Arg or Option decls in subclasses self._e_args = expr._e_args self._e_kws = expr._e_kws # replaces _e_formula_dict as of 061106; WARNING: shared and mutable; WE MUST NEVER MODIFY IT # do pure-expr things that could (in theory) still leave us a pure expr, but are needed before instantiation ## assert expr._e_has_args, "this expr needs its arguments supplied: %r" % self # we might allow exceptions to this later, based on type decl, especially if it has no declared args # (how can we tell, here?? ###e), # tho there is then an ambiguity about whether you're only customizing it or not, # but OTOH that is tolerable if it takes no args, actually that's unclear if instantiation does something like # make a random choice! So we might want to detect that, warn at compile time, or so.... if not expr._e_has_args: # try testexpr_9fx6. See comments near that test. ### update 070120: here is how I'd fix this, and propose to do it as soon as it won't confound other debugging/testing: # print "warning: this expr will get 0 arguments supplied implicitly: %r" % self ### remove when works [why no serno yet??] # 070323 -- removed the warning, since if it's ever an error, you'll find out when the missing args are accessed; # so far it's almost always been legit, so it's just been distracting. self._destructive_supply_args( () ) # supply a 0-tuple of args ##e in case having zero args is illegal and this [someday] detects it, # we should pass it a flag saying to use different error msgs in this "implicit supply args" case. (implicit = True) # WARNING: make sure we copied all expr stuff but set no Instance stuff before doing this! # And make sure the "destructive" here can't mess up expr._e_args which we share. # Maybe that flag we pass should also warn it not to destroy anything else (e.g. if it someday feels like # adding a generated keyword arg, it better copy _e_kws in this case). ##e assert self._e_has_args # set some Instance things self._e_class = expr # for access to _e_kws and args #k needed? #e rename: self._e_expr? not sure. #k not yet used printnim("instance_helpers needs init_class call, init_expr call") #e call _init_class and/or _init_expr if needed [here or more likely earlier] #semi-obs cmts: ### AND have some way to get defaults from env ### AND take care of rules in env -- now is the time to decide this is not the right implem class -- or did caller do that? ### and did caller perhaps also handle adding of type coercers, using our decl?? # 061020 hopes [rejargoned but not updated, 061106]: # maybe we can work for all, incl OpExprs & iterators, by only setting up RULES to instantiate, # which if not used, never happen. self.kids.<index/attr path> has to come from some self._e_args or self._e_kws member... # index always comes from <index/attr path> and *not* from which arg or opt, i think... sometimes they correspond, # and some predeclared members of kids could access those for you, e.g. self.kids.args or just self.args for short... # we could even say _e_args for the raw ones, .args for the cooked ones. self._e_is_instance = True self._init_self_as_Instance(env, ipath) return # from _destructive_make_in def _init_class(self): ###@@@ CALL ME """ called once per directly-instantiated python class, when its first python instance is created [subclasses should replace this] """ pass def _init_expr(self): ###@@@ CALL ME """ called once per Expr when it gets its args [details unclear, maybe not yet needed] [subclasses should replace this] """ pass def _e_eval(self, env, ipath): # implem/behavior totally revised, late-061109; works - not sure it always will tho... ###k # handling of If: As of 061212 If_expr (a subclass of this) overrides _e_eval and seems to work; see comments there. # handling of _value: done at a higher level only -- see InstanceMacro. if EVAL_REFORM: #070117 ## assert not self._e_is_instance, "EVAL_REFORM means we should not eval an instance: %r" % self if self._e_is_instance: # newly allowed 070122 for sake of _26g and _19g tests -- works # [guess: this would not be needed if canon_expr wrapped Instances; not confirmed, but why make it bother doing that?] # print "fyi: instance %r evals to itself after EVAL_REFORM" % self # remove if this is deemed fully ok and normal return self # exprs that need instantiation eval to themselves. ###k will there be exceptions that are subclasses of this? ## printfyi("probably normal: eval to self of a subclass of IorE: %s" % self.__class__.__name__) # find out which classes this happens to ### return self._e_eval_to_expr(env, ipath, self) ###e call from other _e_eval defs ?? # not just "return self", in case we need to wrap it with a local-ipath-modifying expr # Q: will the point of the local ipath be eval to any pure expr wanting instantiation in future, ie "free in ipath", # not just eval to self? A: I think so. else: return self._e_make_in(env, ipath) pass # == def _C__delegate(self): #070121 delegate = self.delegate if is_pure_expr(delegate): # instantiate it, as if it was wrapped with Instance -- do exactly what Instance would do delegate = self._i_instance( delegate, 'delegate') # is that the same index Instance would use? I think so (it gets passed _E_ATTR which should get replaced with this). return delegate # === def drawkid(self, kid): # note: supersedes nim _e_decorate_draw [070210] #e plans: debug_pref for no-net-coord-change enforcement (for testing), # and most importantly, make possible a drawing pass which draws only a specified subset of drawables # but in their coord- or glstate- transforming containers, e.g. for a highlight-drawing pass. # # Update 070414: # To accomplish that, we need to record a kid->parent map during draw (transient per-frame) or before it; # for kids with multiple parents, we hope (in evolving a simple API for this) that the parent-chains # have different glname-chains unless both kid copies can be co-highlighted; # for kids drawn twice by one parent (e.g. a stereo-viewer or a parent which does some sort of draw/overdraw scheme), # we'd probably like that parent to wrap each one differently, so no kid is really drawn twice by one parent, # and so the wrapper can give each one a different glname if necessary, or tell one not to record drawing-coords # (or equiv drawing-parent-chain info) for highlighting. # For a prototype of related code from 070219 or earlier, see a scratch file, rendering.py. if kid is not None: try: if is_expr_Instance(kid): kid.draw() else: print "***BUG: drawkid in %r sees non-Instance (skipping it): %r" % (self, kid,) #070226, worrying about self.delegate rather than self._delegate being passed -- # common but why does it work??####BUG?? in testexpr_33x I tried it and it fails here... # I predict there are a bunch of bugs like this, that some used to work, and others were not tested # since drawkid came in, and in others self.delegate happens to be an Instance (maybe not true bugs then, # but unclear). Hmm, if delegate = Arg() then it is always an Instance -- a style decision is needed for that -- # it should be "always use _delegate" even then I think, otherwise the code is a bad example. ###FIX all calls of drawkid except: print_compact_traceback("bug: exception in %r.drawkid(%r): " % (self, kid)) return # == methods moved from class Widget (which is being merged into this one for now -- merge is not complete, it exists as an # empty shell ###fix) [070201] # note: this is a method in case color is in local coords, BUT that won't work properly if subclass ought to delegate # this -- this def means it won't. Still, for now keep it here since implem never changes. Later clean up delegation for this # as discussed elsewhere. ###fix [070201] def fix_color(self, color): #e move to glpane?? """ Return the given color, suitably formatted for passing to low-level drawing code for the current drawing medium. The color is assumed to be evaluated (i.e. no longer a formula), but perhaps in some general data format and perhaps needing to be subjected to global color transformations stored transiently in the drawing medium object (e.g. a color warp or constant alpha, stored in the glpane). [#e If it proves unworkable for this method to know the current drawing medium, it will probably be replaced with more specific methods, eg fix_color_GL and fix_color_POVRay.] [#e Will we have to have variants of _GL for returning 3 tuples or 4 tuples as the color?] [#e Will we have to worry about material properties?] """ #e first decode it and normalize it as needed color_orig = color # for error messages color = normalize_color(color) warpfuncs = getattr(self.env.glpane, '_exprs__warpfuncs', None) #070215 new feature while warpfuncs: func, warpfuncs = warpfuncs # pop next func from nested list try: # do color = normalize_color(func(color)), but don't change color if anything goes wrong color0 = '?' # for error message in case of exception color0 = func(color) # don't alter color itself until we're sure we had no exception in this try clause color = normalize_color(color0) # do this here (not in next while loop body), since errors in it are func's fault except: print_compact_traceback("exception in %r.fix_color(%r) warping color %r with func %r (color0 = %r): " % \ ( self, color_orig, color, func, color0 ) ) pass continue return color ###e guess: it comes from the glpane as a method on it. the glpane is in our env. # self.env.glpane.fix_color ### fix_color is a method on self, I guess, or maybe on env (and env may either be self.env or an arg to this method -- guess, arg) # or maybe it has contribs from env, class, and glpane -- glpane to know what kind of color it needs, # env or glpane to know about warps or alphas to apply, class maybe, and something to know about resolving formulas (env?) ### we'll have fix_ for the dims too, handling their units, perhaps in a way specific to this class ### we'll have memoization code for all these attrs ### and we'll need better control of gl state like GL_CULL_FACE, if we can run this while it's already disabled # note: draw can't be defined here since it masks the one provided by the delegate, if the subclass delegates! [070201] ## def draw(self): ## "#doc" ## print "warning: no draw method in %r" % self # probably verbose enough to not be missed... ## return def KLUGE_gl_update(self): #070213 """ ###KLUGE: call our glpane.gl_update explicitly. Should never be needed (unless there are bugs), since any change that affects what we draw should be changed-tracked when made, and usage-tracked when some draw method (used directly or to make displist contents) uses it. But evidently there are such bugs [as of 070213], since some things apparently need to call this. Note: all calls of gl_update should go through this method, if possible, if they're needed due to changes in attrs of self. """ self.env.glpane.gl_update() return pass # end of class InstanceOrExpr # == class InstanceHolder: #070414 """ A self-contained place to make and hold Instances of exprs for use with a given glpane, which makes its own drawing env and (by default) its own state and initial ipath, and which caches the Instances at specified indices (using the API of InstanceOrExpr.Instance for details). """ def __init__(self, glpane, state = None, ipath = None): if state is None: state = {} if ipath is None: ipath = 'InstanceHolder-Null-ipath' self._autoindex = 0 self.ipath = ipath self.env = widget_env( glpane, state) self._thing = self.env.make( InstanceOrExpr(), self.ipath ) #k will this expr work? # make this exactly once; # its only purpose is to cache instances and provide the .Instance API def Instance(self, expr, index = None, **kws): """ make instances in self, using API similar to IorE.Instance. @index: if not provided or None, make up a new unique index for the expr; otherwise use the provided index (which if not unique will cause a prior returned Instance to be reused for a new expr or replaced with one made from it, depending on other options). """ if index is None: #bruce 080528 new feature self._autoindex += 1 index = ('__autoindex__', self._autoindex) # note (digression): index is not allowed to contain objects like Atoms, # due to restrictions in other code about ipath -- should be fixed. # [bruce 080528 comment] return self._thing.Instance(expr, index, **kws) pass def get_glpane_InstanceHolder(glpane): #070414 """ Find or make a central place to store cached expr Instances associated with a given glpane. @warning: there is one such place per glpane, with only one namespace for expr indices, effectively shared throughout the entire app. """ try: place = glpane._exprs__InstanceHolder #e could decide whether we need to remake it for some reason, e.g. code-reload except AttributeError: place = glpane._exprs__InstanceHolder = InstanceHolder(glpane) return place # === _DELEGATION_DEBUG_ATTR = '' # you can set this to an attrname of interest, at runtime, for debugging class DelegatingMixin(object): # 061109 # see also DelegatingInstanceOrExpr #070121 renamed delegate -> _delegate, let IorE relate them """ #doc: like Delegator, but only legal in subclasses which also inherit from InstanceOrExpr; other differences from Delegator: - we delegate to self._delegate rather than self.delegate - we don't delegate any attrs that start with '_' - no caching, in case the delegate varies over time - self._delegate should be defined by the subclass rather than being an instance variable of this class (e.g. it might be recomputable from a formula or _C__delegate compute method handled by ExprsMeta, or assigned in __init__) - we only support subclasses which also inherit from InstanceOrExpr - note: they should include InstanceOrExpr before DelegatingMixin in their list of base classes - note: InstanceOrExpr defines a compute method for self._delegate from self.delegate (which instantiates it if needed) - we don't start delegating until self is an Instance; before that we print a warning to say it was tried. (#k is it an error??) [##e This is why we don't support use by non-IorE subclasses. Maybe we could generalize this class to use a more general way of asking the pyinstance whether to delegate yet, like some other optional flag attr or method. (But probably not just by testing self._delegate is None, since the point is to avoid running a compute method for self._delegate too early -- in IorE subclasses this would cause an error when they're a pure expr.)] """ # Note: DelegatingMixin has always appeared after IorE (not before it) in the list of base classes. # I think this order can't matter, since it only defines __getattr__, which is not otherwise defined in any IorE # subclass or superclass, and DelegatingMixin is only legal in IorE (and I just now verified it's only used there, 070206). # The only "close calls" are that __getattr__ is defined in SymbolicExpr, and some obsolete code said # "class _this(SymbolicInstanceOrExpr, DelegatingMixin)". # So if we wanted to require DelegatingMixin to come first (so it could override things defined in IorE # or its subclasses (like the experimental _i_type, if it survives)), we could probably make that change. ##e optim: do this instead of the assert about attr: _delegate = None # safer default -- prevent infrecur def __getattr__(self, attr): # in class DelegatingMixin try: return super(DelegatingMixin,self).__getattr__(attr)###k need to verify super args in python docs, and lack of self in __getattr__ # note, _C__attr for _attr starting with _ is permitted, so we can't check whether attr starts '_' before doing this. except LvalError_ValueIsUnset: # 061205 new feature to prevent bugs: don't delegate in this case. UNTESTED! #####TEST print "fyi (maybe not always bug): " \ "don't delegate attr %r from %r when it raises LvalError_ValueIsUnset! reraising instead." % (attr, self) raise except AttributeError: if attr.startswith('_'): # useful debug code -- commented out, but keep around for now [061110]: ## if not attr.startswith('__'): ## # additional test hasattr(self._delegate, attr) doesn't work: AssertionError: compute method asked for on non-Instance ## # we need that test but I don't know how to add it easily. __dict__ won't work, the attr might be defined on any class. ## # maybe look in __dict__ of both self and its class?? #e ## print "warning: not delegating missing attr %r in %r (don't know if defined in delegate)" % \ ## (attr, self)#061110 - have to leave out ', tho it's defined in delegate %r' ## # before hasattr check, this happens for _args, _e_override_replace, _CK__i_instance_CVdict ## # (in notyetworking Boxed test, 061110 142p). ## #e could revise to only report if present in delegate... hard to do, see above. raise AttributeError, attr # not just an optim -- we don't want to delegate any attrs that start with '_'. ##k reviewing this 061109, I'm not sure this is viable; maybe we'll need to exclude only __ or _i_ or _e_, # or maybe even some of those need delegation sometimes -- we'll see. #e Maybe the subclass will need to declare what attrs we exclude, or what _attrs we include! assert attr != 'delegate', "DelegatingMixin refuses to delegate self.delegate (which would infrecur) in %r -- " \ "does its class lack a definition of delegate?" % self # that assert makes sense even though our low-level delegate is now self._delegate. [070121] if expr_is_Instance(self): recursing = self.__dict__.setdefault('__delegating_now', False) # note: would be name-mangled if set normally assert not recursing, "recursion in self._delegate computation in %r" % self #061121 self.__dict__['__delegating_now'] = True try: delegate = self._delegate finally: self.__dict__['__delegating_now'] = False #e or could del it, presumed less efficient, not sure ##e could check that delegate is not None, is an Instance (??), etc (could print it if not) #k Should it be silently tolerated if delegate is None? Probably no need -- None won't usually have the attr, # so it will raise the same exception we would. Are there confusing cases where None *does* have the attr?? # I doubt it (since we're excluding _attrs). But it's worth giving more info about likely errors, so I'm printing some. if delegate is None: raise AttributeError, attr # new feature 070121: this means there is no delegate (more useful than a delegate of None). if is_pure_expr(delegate): print_compact_stack( "likely-invalid _delegate %r for %r in self = %r: " % (delegate, attr, self)) #061114 if attr == _DELEGATION_DEBUG_ATTR: # you can set that to any attr of current interest, for debugging print "debug_attr: delegating %r from %r to %r" % (attr, self, delegate) try: res = getattr(delegate, attr) # here is where we delegate. It's normal for this to raise AttributeError (I think). except AttributeError: #### catching this is too expensive for routine use (since I think it's often legitimate and maybe common -- not sure), # but it's useful for debugging -- so leave it in for now. 061114 printnim("too expensive for routine use") msg = "no attr %r in delegate %r of self = %r" % (attr, delegate, self) if attr == _DELEGATION_DEBUG_ATTR: print "debug_attr:", msg raise AttributeError, msg else: if attr == _DELEGATION_DEBUG_ATTR: print "debug_attr: delegation of %r from %r is returning %r" % (attr, self, res) #070208 return res print "DelegatingMixin: too early to delegate %r from %r, which is still a pure Expr" % (attr, self) # it might be an error to try computing self._delegate this early, so don't print it even if you can compute it # (don't even try, in case it runs a compute method too early) raise AttributeError, attr pass pass # end of class DelegatingMixin # == # Implem notes for _value [061110, written when this was in Boxed.py]: # - Q: make it have an implicit Instance, I think -- or use a convention of adding one explicitly? # A: the convention, so it can work with other formulas too? no, they'd also need instantiation to work... not sure actually.###@@@ # - BTW that might mean we get in trouble trying to pure-eval (which is what?) an Expr made from InstanceOrExpr, e.g. for a formula # to figure an iterator-expr to use in something else! We'll have to try that, and understand the semantics more clearly... # could it be that we'll have to explicitly Hold the exprs assigned to class attrs in cases like that?!? # - where we use that _value is probably in _e_eval in InstanceOrExpr. (I still don't know if that and make_in are exactly the same.) # - so we could do the instantiation in the place where we use it... then (later) test what happens if it's a number or so. (##e) # - (or what if the entire macro with its value is supposed to come up with a pure expr? test that too. ##e) # So for now, just run the instantiation in the place we use it, in InstanceOrExpr._e_eval. # But worry about whether InstanceOrExpr._e_make_in sometimes gets called instead by the calling code. # Maybe better do it in whichever one has precedence when they both exist... that's _e_make_in (used in _CV__i_instance_CVdict). # _e_eval just calls it, so that way it'll work in both. Ok, do it. ### # WAIT, is it possible for the _value formula to vary with time, so that we want an outer instance, # delegating to a variable inner one? (Perhaps memoizing them all sort of like GlueCodeMemoizer would do... perhaps only last one.) # hmm... #### note that _make_in should pick up the same instance anyway, if it exists, but it looks to me like it might not!!! ###BUG # # let's try an explicit experiment, InstanceMacro: class InstanceMacro(InstanceOrExpr, DelegatingMixin): # ca. 061110; docstring revised 061127 & 070117; see also DelegatingInstanceOrExpr """ Superclass for "macros" -- they should define a formula for _value which they should always look like. # WARNING: a defect in InstanceMacro means that "default defs" in its client class (e.g. thing, ww in Boxed), # or in a superclass of that, will override their defs in _value rather than being delegated to _value # (since they are already defined, so they're never seen by DelegatingMixin.__getattr__); # so be careful what you name those local defs, and what default values are defined in a superclass! # This is also sometimes a feature, especially when the local defs occur in the same class that defines _value # (permitting you to override some of the otherwise-delegated attrs, e.g. bright or width), # tho at one time I thought delegate should let you do that, _value should not, # and this would be a useful distinction. I don't yet know how to make _value not do it, # nor whether that's desirable if possible, nor whether it's well-defined. ###@@@ [061114] # It means, for example, that the InstanceMacro Boxed would not work if it inherited from Widget2D, # since it would pick up Widget2D default values for lbox attrs like btop. [unconfirmed but likely; 061127 comment] """ #e might not work together with use by the macro of DelegatingMixin in its own way, if that's even possible [later: not sure what this comment means] if EVAL_REFORM: printnim("is this eval_Expr correct or not? does it even make any difference??") ## delegate = Instance( eval_Expr(_self._value), '!_value') #### guess about fixing testexpr_5 bug; didn't make any clear difference [070117] delegate = Instance( _self._value, '!_value') # innocent until proven guilty, even if suspected (more seriously, don't change what might not be wrong) # Note: as of 070121 late, due to changes in IorE, this explicit Instance() should no longer be needed (when EVAL_REFORM or not). # But that's only been tested in other classes and when EVAL_REFORM. else: # old code, worked for a long time delegate = Instance( _self._value, '!_value') #k guess: this might eval it once too many times... ####k # [later, as of 061113 -- it works, but this point of too many evals has never been fully understood, # so for all i now, it happens but causes no obvious harm in these examples -- should check sometime. ##e] # [much later, 061114: i think I know why it works -- Instance indeed does an eval, but it's the eval from _self._value # to what's stored in self._value, which is *already* an Instance because evaling the rule makes one! # see other comments about this in Boxed _init_instance dated today. as they say, it's all wrong and will probably change. # in fact, if I said here delegate = _self._value, I think it ought to work fine! Try it sometime. ######TRYIT] #k Note: I used '!_value' as index, because I worried that using '_value' itself could collide with an index used to eval the expr version of _value, # in future examples which do that (though varying expr is not presently supported by Instance, I think -- OTOH # there can be two evals inside _i_instance due to eval_Expr, so the problem might arise that way, dep on what it does with # indices itself). ##e could add sanity check that self.delegate and self._value are instances # (probably the same one, tho not intended by orig code, and won't remain true when Instance is fixed) [061114] def _e_model_type_you_make(self): ###k 070215 very experimental "#doc; overrides super version; see variant in DelegatingInstanceOrExpr" # assume we are a graphical DIorE (like a model obj decorator -- Overlay, Translate, DraggableObject...), so we do delegate it... # but wait, is code for this different if we're expr or instance? instance could go to _delegate, expr to _value if self._e_is_instance: return self._delegate._e_model_type_you_make() ###e check self._delegate not None?? else: assert is_pure_expr(self._value) return self._value._e_model_type_you_make() pass pass # end of class InstanceMacro # == class DelegatingInstanceOrExpr(InstanceOrExpr, DelegatingMixin): # moved here & basic 061211, created a few days before """ #doc """ #e this might replace most uses of DelegatingMixin and InstanceMacro, if I like it def _e_model_type_you_make(self): ###k 070215 very experimental "#doc; overrides super version; see variant in InstanceMacro" # assume we are a graphical DIorE (like a model obj decorator -- Overlay, Translate, DraggableObject...), so we do delegate it... # but wait, is code for this different if we're expr or instance? instance could go to _delegate, expr to delegate if self._e_is_instance: return self._delegate._e_model_type_you_make() ###e check self._delegate not None?? else: assert is_pure_expr(self.delegate) # can this fail for glue-code-objs or helper-objs like the ones MT_try2 makes? ##k return self.delegate._e_model_type_you_make() pass pass # new unfinished code, not sure useful, commented out, goes with other such code from today related to _i_type [070206] ##class InstanceWrapper(DelegatingInstanceOrExpr): #070206 ###e rename??? not yet used. see below for analysis of who should use this. ## """[proposed] The standard superclass for an InstanceOrExpr which delegates to another one ## (an instance of an expr defined by each subclass as self.delegate, which can be time-varying) ## in such a way as to "wrap" or "decorate" it without changing its type. ## (Note: It's possible that the implem of delegation in all such cases will be changed someday ## so that self and its delegate are the same object, only differing in unbound method functions. ###e) ## """ ## _e_delegate_type = True ## pass # Should the following delegating IorE subclasses delegate their type? [070206 survey] # Note, this only matters if they are fed into a model-object-container and wrapped around a model object -- # if that can ever happen legitimately, say yes -- or if they are used as model object even if they're a graphics primitive # like Cylinder (really a geometric object, not just a graphics prim). So for Overlay we'll say yes, in case it wraps # a model obj, even though that should probably not occur directly in a model obj container. Same with Highlighting, etc. # We'll only say no for things that might look like model objects themselves (whose type a user might want to see as the # type of object they put in the model). So far most of the code here is not a model obj, so maybe I should make the default yes... # # SpacerFor - no (it takes the size of a model object, but it surely does not take other aspects of its nature) # [###e this suggests that what's really going on is that we need to be saying what interfaces we do and don't delegate, # and SpacerFor is delegating layout but not other graphics and not model nature, which this "type" is part of -- # really it's not just plain type, but "model object type".] # Highlightable(image) - no # Highlightable(ModelObject) - maybe yes, but looks deprecated -- Highlightable should be used in a viewing macro. So no. # ImageChunk [not yet used] - like Highlightable? no... unclear. Maybe this model/graphics-object distinction needs formalization... # Overlay - # == class ModelObject(DelegatingInstanceOrExpr): #070201 moved here from demo_drag.py; see also ModelObject3D, Geom3D... ###WARNING: as of 070401 it's unclear if the value of _e_model_type_you_make is used for anything except other implems # of the same method. """ #doc -- class for datalike objects within the model [this may diverge from DelegatingInstanceOrExpr somehow -- or i might be mistaken that it needs to differ, but if so, it might have a better name! ###e] """ # One way it might diverge -- in having delegation to env.viewer_for_model_object [nim]; # something like this: ###e delegate = something from env.viewer_for_model_object(self) or so #070203 for now, superclass provides a default delegate of None, since some subclasses have one (which will override that) # and some don't, and without this, the ones that don't have an assertfail when they ought to have an AttributeError. delegate = None def _e_model_type_you_make(self): ###k 070215 very experimental """ #doc; overrides super version """ # but lots of specific DIorE don't delegate it... # model obj DIorE don't [that's us], but graphical ones do. For now assume we know by whether it's subclass of ModelObj. return InstanceOrExpr._e_model_type_you_make(self) # that implem has the right idea for us -- use classname pass class WithModelType(DelegatingInstanceOrExpr): # 070215 experimental, ###UNTESTED (except for not damaging delegate when instantiated) """ #doc better -- be like arg1, but with arg2 specifying the model type -- note, arg2 has to be accessed even when we're an expr """ delegate = Arg(InstanceOrExpr) #e first use of that as type -- ok in general? correct here? arg_for_model_type = Arg(str) #e wrong Arg type? #e have an option to say this Arg works even on exprs???? (very dubious idea) def _e_model_type_you_make(self): ###k 070215 very experimental # note: this would not be delegated even if overridden, I think, due to _e_ -- not sure! ####k if self._e_is_instance: return self.arg_for_model_type else: type_expr = self._e_args[1] # kluge? btw did this go thru canon_expr? yes... res = type_expr._e_constant_value ##k name ###e check for errors ##e use a helper function we have that does this (in If?) assert type(res) == type("") or res is None ##e remove when works, if we extend legal kinds of model_types return res pass pass class WithAttributes(DelegatingInstanceOrExpr): # 070216 experimental, STUB """ #doc better -- be like arg1, but with options specifying attrs you have (like customizations, but with new Option decls too) """ delegate = Arg(InstanceOrExpr) def _init_instance(self): for k, v in self._e_kws.items(): # we hope v is a constant_Expr ok, vv = expr_constant_value(v) assert ok, "WithAttributes only supports constant attribute values for now, not exprs like in %s = %r" % (k,v,) #e to support exprs, set up the same thing as if our class had k = Option(Anything) and v got passed in (as it did) # (note, vv is the eval of v, so we could just eval v here -- but need to wrap it in proper env... # sometime see how much of needed work _i_grabarg already does for us -- maybe it's not hard to unstub this. ##e) setattr(self, k, vv) return pass # == class _this(SymbolicExpr): # it needs to be symbolic to support automatic getattr_Expr """ _this(class) refers to the instance of the innermost lexically enclosing expr with the same name(?) as class. """ #### NOT YET REVIEWED FOR EVAL_REFORM 070117 #k will replacement in _e_args be ok? at first it won't matter, I think. def __init__(self, clas): assert is_Expr_pyclass(clas) #k self._e_class = clas self._e_thisname = thisname_of_class( self._e_class) return #e __str__ ? def __repr__(self): return "<%s#%d%s: %r>" % (self.__class__.__name__, self._e_serno, self._e_repr_info(), self._e_class,) def _e_eval(self, env, ipath): dflt = None ## 'stub default for ' + self._e_thisname #####e fix res = env.lexval_of_symbolname( self._e_thisname, dflt ) # I don't think we need to do more eval and thus pass ipath; # indeed, the value is an Instance but not necessarily an expr # (at least not except by coincidence of how _this is defined). # Caller/client could arrange another eval if it needed to. [061114 guess] assert res, "_this failed to find referent for %r" % self._e_thisname ##e improve return res pass # end of class _this ##class _this(SymbolicInstanceOrExpr_obs, DelegatingMixin): #061113; might work for now, prob not ok in the long run #e [see an outtakes file, or cvs rev 1.57, for more of this obs code for _this, which might be useful someday] # end
NanoCAD-master
cad/src/exprs/instance_helpers.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ TestIterator.py @author: bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. """ # not reviewed recently, was part of NewInval # as of 061106 the setup looks obs, but it might as well be revived and tested before Column is worked on much # revived 061113, see below from exprs.Overlay import Overlay from exprs.transforms import Translate from exprs.Column import SimpleColumn ##from exprs.Column import SimpleRow from geometry.VQT import V from exprs.Exprs import V_expr from exprs.widget2d import Widget2D, Stub, Widget from exprs.instance_helpers import InstanceMacro from exprs.attr_decl_macros import Arg, ArgExpr, Instance from exprs.ExprsConstants import PIXELS # just a guess for this symbol... ## from OpenGL.GL import glTranslatefv # I think this used to work but doesn't now, so instead: from OpenGL.GL import glTranslatef def glTranslatefv(vec): x, y, z = vec glTranslatef(x, y, z) return # == obs: HelperClass = Widget2D class TestIterator_old_nevertried(HelperClass): """ simple iterator which makes two instances of the same WE arg """ def _make(self, place): arg = self._e_args[0] # 061106 args -> _e_args (guess) self._define_kid(1, arg) # lexenvfunc can be default (identity), I think self._define_kid(2, arg) #####@@@@@ what about drawing coords? and layout? layout can be stubbed, but coords should differ. # do our kid instances even need to know about their coords? I doubt it. return def _move(self, kid1, kid2): "move between coords for kid1 (an index) and coords for kid2; either can be None to indicate self" ### guess, not yet called # algorithm: pretend we're Column, but in some trivial form. if kid1 is None: kid1 = 1 if kid2 is None: kid2 = 1 assert kid1 in (1,2) and kid2 in (1,2) glTranslatefv(V((kid2 - kid1) * 2.0, 0, 0)) return def draw(self): self._move(None, 1) self._draw_kid(1) self._move(1, 2) self._draw_kid(2) self._move(2, None) #k needed? return def _draw_kid(self, index): # might be in HelperClass self.drawkid( self._kids[index] ) ## self._kids[index].draw() # this might lazily create the kid, as self._kid_lvals[index].value or so return pass # == # [was once] real, but needs: # - Maker or so # - review Instance # - imports # - not sure if w1.width is always defined Maker = Stub # won't work, since Arg instantiates (unless several bugs conspire to make it work wrongly, eg with 1 shared instance) class TestIterator_alsoobsnow_nevertried(InstanceMacro): """ simple iterator which makes two instances of the same arg """ #e for debug, we should make args to pass to this which show their ipaths as text! thing = Arg(Maker(Widget)) # Maker? ExprFor? ProducerOf? Producer? Expr? w1 = Instance(thing) #k is number of evals correct in principle? internal uses of Instance assumed the expr was literal, were they wrong? # analyzing the code: this calls _i_inst with (an arg that evaluated to) getattr_Expr(_self, 'thing'), # and to instantiate that, it evals it, returning (I think) whatever self.thing is, which should be an instance of the arg. # This may make no sense but it's predicted that self.w1 and self.w2 should be instances, and the same one, of the arg. # that's wrong [thing's formula instantiates once too much, Instance(thing) once too little since I meant, I guess, I(*thing)] # , but it's not what I seem to be seeing, which is w1.width below running on either a non-instance # or something with a non-instance inside it. The non-instance is Translate, w1 should be a Boxed, so maybe that's consistent # if there's an error in Boxed. So I'm adding sanity checks to zome of: Boxed, Overlay, InstanceMacro, Translate. ###DOIT ## print "w1 before ExprsMeta = %r" % (w1,) ### w2 = Instance(thing) # kluge since we don't have Row yet: _value = Overlay( w1, Translate(w2, V_expr(w1.width + 4 * PIXELS, 0,0))) pass ##print "w1 after ExprsMeta = %r" % (TestIterator.__dict__['w1'],) ### # == class TestIterator(InstanceMacro): """ simple iterator which makes two distinct instances of the same arg """ #e for debug, we should make args to pass to this which show their ipaths as text! thing = ArgExpr(Widget) w1 = Instance(thing) w2 = Instance(thing) # two distinct instances _value = SimpleColumn( w1, w2) pass class TestIterator_wrong_to_compare(InstanceMacro): """ variant of that which shows one Instance twice """ thing = Arg(Widget) # the only difference w1 = Instance(thing) # these Instances will be idempotent w2 = Instance(thing) _value = SimpleColumn( w1, w2) # show one instance twice pass # == #k not reviewed: if 0: Rect = black = If = red = ToggleShow = 'needs import' _enclosing_If = 'needs implem' # see comment below goal1 = TestIterator(Rect(1,1,black)) goal2 = TestIterator(If(_enclosing_If.index[0] == 1, Rect(1,1,black), Rect(1,1,red))) #####@@@@@ _enclosing_If IMPLEM, part of lexenv goal3 = TestIterator(ToggleShow(Rect(1,1,red))) # with a def for ToggleShow # - iterator # - Cube, Checkerboard (and fancier: Table) # see also, in its context elsewhere, a common use for iterators "for the edges in some kind of 3d network or polyhedron..."
NanoCAD-master
cad/src/exprs/TestIterator.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ images.py - provide some image-displaying utilities and primitives @author: Bruce @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. semi-obs documentation: Image(filename) # a tile, exact same size as image in file (which loads into a texture, rounded up to twopow sizes) can be used as a texture, or drawn using pixel ops Image(filename, width, height) # if only width is given, preserves aspect ratio (or only height, possible when names used) (that's tricky to declare using defaults, btw; maybe default = None or Automatic) it can be rotated, translated, etc Q. what if we want to do image ops to get another image and use general tex coords to draw that? A. we need the image obj lying around, without drawing it. Q. do we keep one cache of image objs from filenames? A. yes. Note name conflict: our class Image, and PIL's Image class. To avoid even more confusion, I'll name this module images.py rather than Image.py (but note, there exists an unrelated directory cad/images). """ import os from OpenGL.GL import glGenTextures from OpenGL.GL import GL_TEXTURE_2D from OpenGL.GL import glBindTexture from OpenGL.GL import GL_CLAMP from OpenGL.GL import GL_TEXTURE_WRAP_S from OpenGL.GL import glTexParameterf from OpenGL.GL import GL_TEXTURE_WRAP_T from OpenGL.GL import GL_REPEAT from OpenGL.GL import GL_LINEAR from OpenGL.GL import GL_TEXTURE_MAG_FILTER from OpenGL.GL import GL_LINEAR_MIPMAP_LINEAR from OpenGL.GL import GL_TEXTURE_MIN_FILTER from OpenGL.GL import GL_NEAREST from OpenGL.GL import GL_DECAL from OpenGL.GL import GL_TEXTURE_ENV from OpenGL.GL import GL_TEXTURE_ENV_MODE from OpenGL.GL import glTexEnvf from OpenGL.GL import GL_REPLACE from OpenGL.GL import GL_BLEND from OpenGL.GL import glEnable 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 GL_ALPHA_TEST from OpenGL.GL import GL_GREATER from OpenGL.GL import glAlphaFunc from OpenGL.GL import glDisable from OpenGL.GL import glFlush ##from OpenGL.GL import glFinish from OpenGL.GL import GL_CULL_FACE from OpenGL.GLU import gluProject from exprs.draw_utils import draw_textured_rect, draw_textured_rect_subtriangle from exprs.Rect import Rect from exprs.Center import Center from utilities import debug_flags from geometry.VQT import V from foundation.env import seen_before from exprs.ExprsMeta import ExprsMeta from exprs.Exprs import call_Expr from exprs.py_utils import MemoDict from exprs.widget2d import Widget2D from exprs.attr_decl_macros import Arg, Option, Instance from exprs.instance_helpers import DelegatingInstanceOrExpr, InstanceOrExpr, DelegatingMixin from exprs.ExprsConstants import Vector, ORIGIN, PIXELS, D2X, D2Y, DX, DY from exprs.__Symbols__ import _self, Anything # NOTE: the following code contains some hardcoded "ui" which # should be UI_SUBDIRECTORY_COMPONENT ## from icon_utilities import UI_SUBDIRECTORY_COMPONENT # ImageUtils.py class nEImageOps -- see following comment # TODO: find out if the functions we need from texture_helpers could be imported here at toplevel: import graphics.drawing.texture_helpers as texture_helpers # Note: from texture_helpers we use: # function create_PIL_image_obj_from_image_file, a trivial glue function into ImageUtils.py class nEImageOps, # function loadTexture. from utilities.icon_utilities import image_directory # for finding texture & cursor files # last-resort image file (same image file is used in other modules, but for different purposes) courierfile = os.path.join( image_directory(), "ui/exprs/text/courier-128.png") ### TODO: RENAME # old comment about testdraw.py, not sure if still relevant as of 071017: # and we copy & modify other funcs from it into this file, but they also remain in testdraw for now, in some cases still used. # At some point we'll need to clean up the proper source file of our helper functions from testdraw... # when the time comes, the only reliable way to sort out & merge duplicated code (some in other cad/src files too) # is to search for all uses of the GL calls being used here. debug_glGenTextures = True #070308 ##### class _texture_holder(object): """ [private class for use in a public MemoDict] From a filename and other data, create on demand, and cache, a PIL Image object and an optional OpenGL texture object; objects of this class are meant to be saved as a memoized dict value with the filename being the dict key """ #e so far, no param choices, keep only one version, no mgmt, no scaling... __metaclass__ = ExprsMeta #e or could use ConstantComputeMethodMixin I think def __init__(self, tex_key): self.filename, self.pil_kws_items = tex_key # have to put sorted items tuple in key, since dict itself is unhashable self.pil_kws = dict(self.pil_kws_items) if 1: #e could remove when works, but don't really need to items = self.pil_kws.items() items.sort() assert tuple(items) == self.pil_kws_items # pil_kws added 061127, doc in nEImageOps; # current defaults are ideal_width = None, ideal_height = None, rescale = True, convert = False # everything else can be computed on-demand (image object, texture name, texture, etc) #e no provision yet for file contents changing; when there is, update policy or uniqid might need to be part of tex_key #e more options? maybe, but by default, get those from queries, store an optimal set of shared versions [nim] def _C__image(self): """ define self._image -- create a PIL Image object (enclosed in an neImageOps container) from the file, and return it """ return texture_helpers.create_PIL_image_obj_from_image_file(self.filename, **self.pil_kws) # (trivial glue function into ImageUtils.py class nEImageOps -- return nEImageOps(image_file, **kws)) def _C_tex_name(self): """ define self.tex_name -- allocate a texture name """ # code copied from texture_helpers.loadTexture (even though we call it, below, for its other code): tex_name = glGenTextures(1) if debug_glGenTextures and seen_before(('debug_glGenTextures', self.filename)): #070313 using env.seen_before (rename env module (cad/src) -> global_env? for now, basic imports seen_before via py_utils.) #k I'm not sure if, after certain reloads, I should expect to routinely see this message as textures get reloaded. 070313 print "debug fyi: same filename seen before, in glGenTextures -> %r for %r" % (tex_name, self) # note: by experiment (iMac G5 Panther), this returns a single number (1L, 2L, ...), not a list or tuple, # but for an argument >1 it returns a list of longs. We depend on this behavior here. [bruce 060207] tex_name = int(tex_name) # make sure it worked as expected assert tex_name != 0 return tex_name def _C_loaded_texture_data(self): """ define self.loaded_texture_data = (have_mipmaps, tex_name), which stands for the side effect of guaranteeing the texture is loaded (but not necessarily currently bound) """ image_obj = self._image tex_name = self.tex_name assert tex_name, "tex_name should have been allocated and should not be 0 or false or None, but is %r" % (tex_name,)#070308 have_mipmaps, tex_name = texture_helpers.loadTexture(image_obj, tex_name) ##testexpr_11n = imagetest("stopsign.png") # fails; guess, our code doesn't support enough in-file image formats; ## # exception is SystemError: unknown raw mode, [images.py:73] [testdraw.py:663] [ImageUtils.py:69] [Image.py:439] [Image.py:323] ## ##e need to improve gracefulness of response to this error glBindTexture(GL_TEXTURE_2D, 0) # make sure no caller depends on mere accessing of self.loaded_texture_data binding this texture, # which without this precaution would happen "by accident" (as side effect of loadTexture) # whenever self.loaded_texture_data ran this recompute method, _C_loaded_texture_data assert tex_name == self.tex_name return have_mipmaps, tex_name def bind_texture(self, clamp = False, use_mipmaps = True, decal = False, pixmap = False): """ bind our texture, and set texture-related GL params as specified. Anything that calls this should eventually call self.kluge_reset_texture_mode_to_work_around_renderText_bug(), but only after all drawing using the texture is done. """ # Notes [some of this belongs in docstring]: #e - we might want to pass these tex params as one chunk, or a flags word #e - we might want to optim for when they don't change # - most of them have default values like the old code had implicitly, but not pixmap, which old code had as implicitly true # - pixmap is misnamed, it doesn't use the pixmap ops, tho we might like to use those from the same image data someday have_mipmaps, tex_name = self.loaded_texture_data ## texture_helpers.setup_to_draw_texture_name(have_mipmaps, tex_name) # let's inline that instead, including its call of _initTextureEnv, and then modify it [061126] glBindTexture(GL_TEXTURE_2D, tex_name) # modified from _initTextureEnv(have_mipmaps) in texture_helpers.py if clamp: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) else: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) if not pixmap: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) if have_mipmaps and use_mipmaps: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) else: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) else: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) if decal: glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) else: # see red book p410-411 -- can use GL_DECAL, GL_REPLACE, GL_MODULATE, GL_BLEND, GL_ADD, GL_COMBINE. # (Except that I can't import GL_COMBINE (iMac G5) so maybe it's not always available.) # GL_DECAL leaves fragment alpha unchanged and uses texture alpha to mix its color with fragment color # (fragment data comes from the polygon's alpha & color as if drawn untextured). # GL_REPLACE just discards fragment data in favor of texture data incl alpha -- that would be a better default. # [later 070404: now it is the default.] # Eventually permit all these values -- for now just let decal = False mean GL_REPLACE. [070403] # ## print "getTextureData", self, self._image.getTextureData() # presence of correct alpha is plausible from this # (in testexpr_11pd2). By itself, it does make a difference (alpha 0 places are black in testexpr_11pd2, not blue # (probably a leaked color) like in testexpr_11pd1), but self.blend is also needed to make it translucent. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) return def kluge_reset_texture_mode_to_work_around_renderText_bug(self, glpane): #bruce 081205 glpane.kluge_reset_texture_mode_to_work_around_renderText_bug() return def __repr__(self): #070308 try: basename = os.path.basename(self.filename) #070312 except: basename = self.filename return "<%s at %#x for %r, %r>" % (self.__class__.__name__, id(self), basename, self.pil_kws) pass # end of class _texture_holder # == texture_holder_for_filename = MemoDict(_texture_holder) ###e should canonicalize the filename -- as another optional argfunc to MemoDict #doc: now texture_holder_for_filename[filename] is our memoized _texture_holder for a given filename. # note [added 061215]: no need to use LvalDict2, since _texture_holder never needs recomputing for a given filename # (and uses no usage-tracked values). # == DEBUG_IMAGE_SEARCH = False def canon_image_filename( filename): """ Figure out (or guess) the right absolute pathname for loading the given image file into OpenGL. @warning: the answer depends on what files are found on your disk, so it might differ for different users! [Note: It's not yet clear whether that's merely a development kluge, or a feature, or some of each; someday there might even be user prefs for image search paths, except that plugins can provide their own images.... ##e] """ orig_filename = filename # for debug prints or warnings ## #stub, might work for now: ## thisdir = os.path.dirname(__file__) # dir of exprs module ## CAD_SRC_PATH = os.path.dirname( thisdir) from utilities.constants import CAD_SRC_PATH # [note: in a built Mac release, this might be Contents/Resources/Python/site-packages.zip, or # a related pathname; see comments near its definition.] cad = os.path.dirname( CAD_SRC_PATH) # used below for cad/images # image file path extensively revised 070604, mainly so testmode can work in a built release package from platform_dependent.PlatformDependent import path_of_Nanorex_subdir # main exprs-package image directory cad_src_ui_exprs = os.path.join( image_directory(), "ui/exprs") # not necessarily really in cad/src (in a built release) # list of dirs in which to search for filename (#e could precompute; doesn't matter much) path = [ # first, search in a user-controlled dir, so they can override UI image files # (if those are accessed using the exprs module). path_of_Nanorex_subdir("UI"), # next, let the code specify the name exactly, relative to cad_src_ui_exprs cad_src_ui_exprs, # next, to support older code in this exprs package, # let it leave out the subdir component if it's one of these: os.path.join( cad_src_ui_exprs, "text" ), os.path.join( cad_src_ui_exprs, "widgets" ), os.path.join( cad_src_ui_exprs, "textures" ), os.path.join( cad_src_ui_exprs, "test" ), # next, permit access to anything in image_directory() # using the same relative path (starting with "ui/") # as typical code in cad/src does (e.g. when calling geticon) # (this means we could rewrite geticon to call this routine, # if we wanted it to be user-overridable someday #e) image_directory(), # for experimental things, let developers refer to things in cad/src/experimental -- # I guess they can do that using the image_directory() entry (which for developers is .../cad/src) # by using filenames starting with "experimental", which is not a big restriction # given that we're not doing this early enough to override built-in images # (so, no path entry needed for that) # we no longer support the old experimental/textures directory ## os.path.join( CAD_SRC_PATH, "experimental/textures"), # [not supported by autoBuild.py, and never will be] # but we do still support the obsolete cad/images dir, since some test code uses it # and it was still present in cvs (I think -- at least it's in my checkouts) as of 070604. os.path.join( cad, "images"), ] tries = map( lambda dir: os.path.join(dir, filename), path) lastresort = courierfile #e replace with some error-indicator image, or make one with the missing filename as text (on demand, or too slow) ## tries.append(lastresort) tries.append(-1) for filename in tries: if filename == -1: filename = lastresort if 'too important to not tell all users for now' or debug_flags.atom_debug: print "bug: image file %r not found, using last-resort image file %r" % (orig_filename, lastresort) ### filename = os.path.abspath(os.path.normpath(filename)) # faster to do this on demand if os.path.isfile(filename): if DEBUG_IMAGE_SEARCH: print " found:",filename return filename if DEBUG_IMAGE_SEARCH: print "didn't find:", filename assert 0, "lastresort file %r should always be present" % os.path.abspath(os.path.normpath(lastresort)) pass # end of canon_image_filename class Image(Widget2D): """ Image(filename, size = Rect(2)) draws a rectangular textured image based on the given image file, using the same size and position in model space as the lbox of an instance of self.size (a Widget2D, usually a Rect, Rect(2) by default, i.e. about 30 pixels square in home view). It uses an OpenGL texture size (resolution) given by options ideal_width and ideal_height [#e which need renaming, making into one option, and other improvements; see code comments for details]. [It doesn't yet work in POV-Ray but it ought to someday. #e] The other options are not fully documented here, and need improvements in design and sometimes in implem, but are summarized here: Options that affect how the file gets loaded into a PIL Image include rescale, convert, _tmpmode [#doc these], as well as the texture size options mentioned. (The PIL Image object is available as self._image even if our OpenGL texture is not used. [#doc more details?] [###WRONG or REVIEW -- isn't it the nEImageOps object which has that name??]) Options that affect how the texture gets made from the loaded image include... none yet, I think. Someday we'll want make_mipmaps (with filtering options for its use) and probably others. [###k need to verify none are used for this] @warning: variations in the above options (between instances, or over time [if that's implemented -- untested, unsure ##k]) cause both a new OpenGL texture to be created, and (even if it would not be necessarily in a smarter implem [i think] -- but the lack of image->texture options makes this academic for now) a new PIL Image to be created from the image file on disk. Options that affect how the texture is drawn (in any instance, at any moment) include: clamp, pixmap [#e misnamed], use_mipmaps, decal, tex_origin, nreps [#doc these]. [#e More options of this kind are needed.] All the texture-drawing options can be varied, either in different instances or over time in one instance (by passing them as formulae), without causing a new texture or PIL Image to be loaded as they vary. @warning: the image is not visible from the back by default, which is only ok for some uses, such as 2D widgets or solid-object faces or decals. Use two_sided = True to make it visible from both sides. """ ##e about options ideal_width and ideal_height: #e should be a single option, resolution or tex_size, number or pair, or smth to pick size based on image native size #e should let you specify an image subrect too, or more generally an expr to compute the image -- or this can be part of one... # note we do have tex_origin and nreps # #e size option is misnamed since it also controls position -- maybe give it another name # like where, place, footprint, lbox, box? none of those good enough. # Also we need a way to change the size but preserve the natural aspect ratio. # One way: let size and tex_size both be passed easily as formulas of native image size. # The main new thing that requires is an abbreviation for _this(Image), e.g. _my. [note: _my is now implemented, 061205] # args filename = Arg(str) use_filename = call_Expr( canon_image_filename, filename) # named options -- clamp = False, use_mipmaps = True, decal = False, pixmap = False [redundant with defaults in bind_texture] clamp = Option(bool, False) # clamp or (default) repeat pixmap = Option(bool, False) #e misnamed -- whether to use GL_NEAREST filtering use_mipmaps = Option(bool, True) # whether to use mipmaps, if present in loaded texture object; only matters if pixmap is False #e what determines whether mipmaps are present? For now, they always are; # later, it might depend on whether we had RAM, or on a more global pref, or .... decal = Option(bool, False, doc = "combine texture with color using GL_DECAL? (by default, use GL_REPLACE)") # as of 070403, False works and means GL_REPLACE # 070404 changing default to False; not sure if this can affect blend = false cases -- maybe yes beyond edges? ###UNTESTED #e should probably rename this and change it from a bool to a choice or to more bools # (since it has 5 or 6 possible values; see code comments) blend = Option(bool, False, doc = "whether to blend translucent images with background") #070403 # Note: blend doesn't turn off depth buffer writing, but does reject fully transparent fragments (via GL_ALPHA_TEST), # so only the translucent (i.e. partly transparent) pixels can obscure things if drawn first, # or can be hover-highlighted (affect sbar_text, act as drag-grip-point, etc). # This behavior is fine if translucency is used for antialiased edges. # (Except for images that have very small nonzero alphas that really ought to be zero instead, # like the one used in testexpr_11pd3 (fyi, see screenshot 'alpha fluctuations.jpg', not in cvs) -- # maybe this comes in through the rescaling and/or mipmap filtering?) # See also slightly related glStencilFunc, glDepthFunc. alpha_test = Option(bool, _self.blend, doc = "whether to use GL_ALPHA_TEST (by default, use it when blend option is true)" ) #070404 # this is effectively an option to not use GL_ALPHA_TEST when blend is True (as we'd normally do then) two_sided = Option(bool, False, doc = "whether to disable GL_CULL_FACE so that both sides get drawn") #080223 ###e should add option to turn off depth buffer writing -- see warning below ###e should add option to turn off color buffer writing -- glColorMask -- see warning below # see also disable_color (widget2d.py, maybe move to GLPane.py?) # [or find a more modular way to control things like that -- wrappers? std options?] ### WARNING: hard to disable those correctly (re restoring state) # if we ever get drawn in a larger thing that disables one of them -- as we might, # due to selobj highlighting! ###k CHECK THIS for other new disables too, alpha and blend... nreps = Option(float, 1.0) #e rename - repeat count; mostly only useful when clamp is False, but ought to work otherwise too ##e generalize to let caller supply tex_dx and tex_dy vectors, for rotating the texture within the drawing region; # (Can that be done as a more general value for this option? Unclear whether that's natural, tho passing in a matrix might be...) tex_origin = Option(Vector, ORIGIN) # offset option, to shift tex_origin; can be 2d or 3d, though we use only two dims of it #e design Qs: # - is it really Point rather than Vector? # - does it interact with [nim] drawing-region-origin so as to line up if we use the same one for adjacent regions? size = Option(Widget2D, Rect(2)) ##e also permit number or pair, ie args to Rect also should be ok # [experiment 061130] shape = Option(Anything, None, doc = """shape name ('upper-left-half' or 'lower-right-half'), or sequence of 3 2d points (intrinsic coords, CCW), to draw only a sub-triangle of the textured rect image""" ) ###e also permit shape option to specify polygon, not just triangle, or, any geometry-drawing expr # (see comments in helper function for more on that) # (has design issues re tex/model coord correspondence [tho current scheme is well-defined and might be best for many uses], # and possible embedded textured parts) bleft = size.bleft bright = size.bright bbottom = size.bbottom btop = size.btop # more options, which affect initial image loading from file, thus are part of the texture-cache key [061127] rescale = Option(bool, True) # whether to resize by rescaling or padding (default might be changed after testing #e) ideal_width = Option(int, 256) ###e let them be a func of image size, as a pair? (eg so they can be next greater 2pow?) someday. ideal_height = Option(int, 256) convert = Option(bool, False) #061128, whether to convert image to DESIRED_MODE RGBX. ### NOTE: type bool is wrong, since later [but long before 070404] it became able to let you specify another mode, # and in that case it also affects getTextureData retval mode. This is now routinely used for transparent texture images. _tmpmode = Option(str, None) #k None is not str, is that ok? #doc [might be temp kluge] #e these are not fully implem -- at best, when rescale = False, you'll see black padding when drawing; # what we need to do is pass a reduced tex coord so you don't. I hope the image (not padding) will be at the lower left corner # of what's drawn. [as of 061127 1022p] [it's not -- this is commented on elsewhere and explained, probably in ImageUtils.py] # formulae # THIS SHOULD WORK (I think), but doesn't, don't know why ####BUG: [is my syntax wrong for passing the kws to call_Expr???] ## texture_options = call_Expr( dict, clamp = clamp, pixmap = pixmap, use_mipmaps = use_mipmaps, decal = decal ) ## __get__ is nim in the Expr <type 'dict'>(*(), **{'clamp': <call_Expr#5175: ..... def _C__texture_holder(self): # pil_kws added 061127, doc in nEImageOps; # current defaults are ideal_width = None, ideal_height = None, rescale = True, convert = False, _tmpmode = None. # Note: don't include texture_options here, since they don't affect the PIL image object itself. pil_kws = dict(rescale = self.rescale, ideal_width = self.ideal_width, ideal_height = self.ideal_height, convert = self.convert, _tmpmode = self._tmpmode) items = pil_kws.items() items.sort() pil_kws_items = tuple(items) # make that dict hashable tex_key = (self.use_filename, pil_kws_items) # must be compatible with the single arg to _texture_holder.__init__ return texture_holder_for_filename[tex_key] # this shared global MemoDict is defined above _image = _self._texture_holder._image def bind_texture(self, **kws): """ bind our texture (and set other GL params needed to draw with it). Anything that calls this should eventually call self.kluge_reset_texture_mode_to_work_around_renderText_bug(), but only after all drawing using the texture is done. """ self._texture_holder.bind_texture(**kws) def kluge_reset_texture_mode_to_work_around_renderText_bug(self): """ This needs to be called after calling self.bind_texture, but only after drawing using the texture is done. """ self._texture_holder.kluge_reset_texture_mode_to_work_around_renderText_bug( self.env.glpane) def draw(self): # bind texture for image filename [#e or other image object], # doing whatever is needed of allocating texture name, loading image object, loading texture data; ###e optim: don't call glBindTexture if it's already bound, and/or have a "raw draw" which assumes it's already bound if 'workaround bug in formula for texture_options': texture_options = dict(clamp = self.clamp, pixmap = self.pixmap, use_mipmaps = self.use_mipmaps, decal = self.decal) else: texture_options = self.texture_options # never used, but desired once bug is fixed self.bind_texture( **texture_options) try: # figure out texture coords (from optional args, not yet defined ###e) -- stub for now nreps = float(self.nreps) # float won't be needed once we have type coercion; not analyzed whether int vs float matters in subr ## tex_origin = ORIGIN2 # see also testdraw's drawtest1, still used in testmode to draw whole font texture rect tex_origin = V(self.tex_origin[0], self.tex_origin[1]) ## tex_dx = D2X ; tex_dx *= nreps # this modifies a shared, mutable Numeric array object, namely D2X! Not what I wanted. tex_dx = D2X * nreps tex_dy = D2Y * nreps # where to draw it -- act like a 2D Rect for now, determined by self's lbox, # which presently comes from self.size origin = V(-self.bleft, -self.bbottom, 0) # see also the code in drawfont2 which tweaks the drawing position to improve the pixel alignment # (in a way which won't work right inside a display list if any translation occurred before now in that display list) # in case we want to offer that option here someday [070124 comment] ## dx = DX * self.bright ## dy = DY * self.btop dx = DX * (self.bleft + self.bright) # bugfix 070304: include bleft, bbottom here dy = DY * (self.bbottom + self.btop) blend = self.blend alpha_test = self.alpha_test two_sided = self.two_sided shape = self.shape # for now, None or a symbolic string (choices are hardcoded below) if blend: glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if alpha_test: glEnable(GL_ALPHA_TEST) # (red book p.462-463) glAlphaFunc(GL_GREATER, 0.0) # don't draw the fully transparent parts into the depth or stencil buffers ##e maybe let that 0.0 be an option? eg the value of alpha_test itself? Right now, it can be False ~== 0 (not None). if two_sided: glDisable(GL_CULL_FACE) if not shape: draw_textured_rect( origin, dx, dy, tex_origin, tex_dx, tex_dy) else: # support sub-shapes of the image rect, but with unchanged texture coords relative to the whole rect [070404 ###UNTESTED] if type(shape) == type(""): ##e use an external shape name->value mapping? # in fact, should such a mapping be part of the dynamic graphics-instance env (self.env)?? if shape == 'upper-left-half': shape = ((0,0), (1,1), (0,1)) elif shape == 'lower-right-half': shape = ((0,0), (1,0), (1,1)) elif shape == 'upper-right-half': #070628 shape = ((0,1), (1,0), (1,1)) elif shape == 'lower-left-half': #070628; untested shape = ((0,0), (1,0), (0,1)) else: assert 0, "in %r, don't know this shape name: %r" % (self, shape) # otherwise assume it might be the right form to pass directly # (list of 3 2d points in [0,1] x [0,1] relative coords -- might need to be in CCW winding order) draw_textured_rect_subtriangle( origin, dx, dy, tex_origin, tex_dx, tex_dy, shape ) pass if blend: glDisable(GL_BLEND) if alpha_test: glDisable(GL_ALPHA_TEST) if two_sided: glEnable(GL_CULL_FACE) finally: self.kluge_reset_texture_mode_to_work_around_renderText_bug() return # from Image.draw # note the suboptimal error message from this mistake: # bright = DX * 2 # ## TypeError: only rank-0 arrays can be converted to Python scalars. ... # ## [test.py:419 inst.draw()] [Column.py:91 glTranslatef(dx,0,0)] #e Ideally we'd have a typecheck on _self.bright (etc) in Widget2D # which would catch this error whenever self.bright was computed, # or even better, when it's a constant for the class (as in this case), # right when that constant formula is defined. pass # end of class Image # == IconImage = Image(ideal_width = 22, ideal_height = 22, convert = True, _tmpmode = 'TIFF', doc = "be the best way to use Image for an NE1 icon" # (informal docstring option 070124 -- not used, just there) ) # WARNING: size 22 MIGHT FAIL on some OpenGL drivers (which require texture dims to be powers of 2); # when that happens (or in any case, before a serious release), we'll need to ask OpenGL if it has that limitation # and implement this differently if it does. # # Intent of IconImage is just "be the best way to use Image for an NE1 icon", # so it might change in transparency behavior once we work that out inside Image, # and we'll hopefully not keep needing that _tmpmode kluge, etc. # == class NativeImage(DelegatingInstanceOrExpr): #070304 [works (imperfectly? see comments there) in testexpr_11u6] """ Show an image in its native size and aspect ratio -- that is, one image pixel == one texture pixel == one screen pixel, when the local coordsys is the standard viewing coordsys. Note: callers are advised to enclose this inside Highlightable, at least until we add local glnames to fix the bug of all bareMotion over non-Highlightable drawing causing redraws. """ # args filename = Arg(str, "x") #e better type, eg Filename? ###BUG: ought to take all options and pass them on to Image [070403 comment] # formulae [non-public in spite of the names] im1_expr = Image(filename, use_mipmaps = True, ideal_width = -1, ideal_height = -1) # customize Image to use native texture size (but without controlling the aspect ratio for display) ###e consider also including the options that IconImage does, or options passed by caller # (but passing general opts (like python **kws syntax can do) is nim in the exprs language) im1 = Instance(im1_expr) # grab an actual image so we can find out its native size th = im1._texture_holder # gets its _texture_holder object imops = th._image # get its nEImageOps object # appearance delegate = im1_expr(size = Center(Rect(imops.orig_width * PIXELS, imops.orig_height * PIXELS))) # (implem note: this customizes im1_expr options even though its args (filename) are already supplied. # That used to give a warning but apparently doesn't now. If it does again someday, # it's easy to fix here -- just give filename in each instantation rather than in im1_expr.) pass # === # for grabbing pixels, e.g. for visual tests of correctness, live vs saved image #e put in its own file? yes. #e search for "visual regression test framework" for ideas on that in comment below; refile them into PixelTester.py ##e class PixelGrabber(InstanceOrExpr, DelegatingMixin):#e draft, API needs revision to provide more control over when to save, button-compatible """ Act like our first argument, but after the first(??) draw call, save an image of the rendered pixels into the file named by arg2. """ ### issues: # - gluProject implem only works if we're not inside a display list; this is not checked for # - image might be cluttered with things like the origin axis. Maybe turn these off when using? # + It turns out this doesn't happen since those haven't been drawn yet! (or so it seems -- not fully confirmed) # - ###e redefine it to clear the color & depth buffers in its footprint, before drawing? # - no guarantee our pixel footprint is a pixel rect on screen. Might want to force this, or check for it? # Until then, use in home view. # (Or outside of the model's modelview matrix, once testmode intercepts render loop.) # + so far it's been a perfect rect, even tho i'm in perspective view. This makes sense in theory for a nonrotated view. # - only works if everything we draw actually appears on the glpane -- not outside its boundaries, not obscured beforehand # - it saves it on *every* draw call. [Maybe even those for glselect -- might cause bugs, not well tested ###k] # Maybe it ought to save when content changes? (Not yet detected.) # Really, better to have a "save button", but does that have to be provided in same class? If not, how is shared state named?#e ###e one possibility, sounds good: [see also PixelTester.py] # - separate method on the instance to save image; # - draw call just saves some helper info like lbox mousepoints; # - using env has to know how to call that method; # - convenience macro adds a button to do it, and a saved-image viewer, # and this becomes part of our desired "visual regression test framework", # which overall lets us select any test, see its code, rerun it, resave it, see saved image (maybe plus older ones), # do a "flicker test" where we switch between saved and current (recaptured?) image in one place as we toggle mousebutton, # maybe even show a computed "difference image", # and (makes it easier for us to) commit these images into cvs or other archive delegate = Arg(Widget2D) filename = Arg(str, "/tmp/PixelGrabber-test.jpg") # default value is just for debugging convenience, but can stay, it's useful def draw(self): self.drawkid( self.delegate) ## self.delegate.draw() self.save() #e shouldn't call so often -- see big comment above def save(self): glFlush() ##k needed? don't know; works with it. Or try glFinish? not sure it's legal here. Not needed, never tried. glpane = self.env.glpane image = glpane.grabFrameBuffer() # not sure this is legal during the draw... but it seems to work # This is a QGLWidget method. Does it have args? only withalpha, not size (no way to only grab a subimage directly). # It returns a QImage. # See also QGLWidget::renderPixmap (sounds easy to mess up, so not tried). # Or we could use OpenGL to grab raw data (as we now do from depth buffer), then use PIL (or QImage) to output it... # maybe best in long run, but grabFrameBuffer works ok for now. #e # # Note: Return value is a constants.qt.QImage object; for debug prints including dir(image), see cvs rev 1.8 #e optim: use GL calls instead -- but that optim won't matter once we stop this from happening on every draw call ## print "glpane dims",glpane.width, glpane.height # on bruce's g4 now, whole glpane dims 633 573 (plausible; same as image dims); on g5, 690 637, also same in image assert glpane.width == image.width() assert glpane.height == image.height() # figure out where the image of self lies in this image of the entire glpane (in a rect defined by GL window coords x0,x1, y0,y1) #### WARNING: this method only works if we're not inside a display list thing = self.delegate lbox_corners = [(x,y) for x in (-thing.bleft, thing.bright) for y in (-thing.bbottom, thing.btop)] # Note, these are in local model coords, with implicit z = 0, NOT pixels. #bugfix 061127 133p: those minus signs -- I forgot them, and it took hours to debug this, since in simple examples # the affected attrs are 0. Does this indicate a design flaw in the lbox attr meanings? Guess: maybe -- # it might affect a lot of code, and be worse in some code like Column. Maybe we just need a default lbox_rect formula # which includes the proper signs. ###e points = [gluProject(x,y,0) for x,y in lbox_corners] # each point is x,y,depth, with x,y in OpenGL GLPane-window coords ## print "raw points are",points # this shows they are a list of 4 triples, are fractional, and are perfectly rectangular (since view not rotated). xs = [p[0] for p in points] ys = [p[1] for p in points] x0, x1 = min(xs), max(xs) y0, y1 = min(ys), max(ys) ###e could warn if the points are not a rectangle, i.e. if self is drawn in a rotated view # add pixelmargin, but limit by window size (glpane.width, glpane.height) # (the reason is to verify this grabs bgcolor from around the image; not sure it will, if pixel coords are pixel-centers) pixelmargin = 2 + 0.5 #e make 2 an option, so more easily usable for display of saved images too # note: if original points are pixel centers, then 0.5 of this serves to turn them into pixel boundaries, # but then we'd also want to round them, differently for low and high values, # so to do that, add 1 to high values before int() ### REVIEW: should we use intRound to avoid issue of int() rounding towards zero # even for negative coordinates (for which adding 0.5 has the wrong effect)? [bruce 080521 Q] x0 -= pixelmargin x0 = int(x0) if x0 < 0: x0 = 0 y0 -= pixelmargin y0 = int(y0) if y0 < 0: y0 = 0 x1 += pixelmargin + 1 # 1 is for rounding (see comment) x1 = int(x1) if x1 > glpane.width: x1 = glpane.width ###k need -1?? are these pixels or pixel-boundaries?? assume boundaries, see comment above y1 += pixelmargin + 1 y1 = int(y1) if y1 > glpane.height: y1 = glpane.height # convert to Qt window coords [note: the other code that does this doesn't use -1 either] y0 = glpane.height - y0 y1 = glpane.height - y1 y0, y1 = y1, y0 w = x1-x0 h = y1-y0 ## print "subimage dims",w,h assert x0 <= x1, "need x0 <= x1, got x0 = %r, x1 = %r" % (x0,x1) assert y0 <= y1, "need y0 <= y1, got y0 = %r, y1 = %r" % (y0,y1) # trim image, i.e. replace it with a subimage which only shows self.delegate image = image.copy(x0, y0, w, h) # QImage::copy ( int x, int y, int w, int h, int conversion_flags = 0 ) -- copy a subarea, return a new image filename = self.filename try: os.remove(filename) except OSError: # file doesn't exist pass image.save(filename, "JPEG", 85) #e 85->100 for testing, or use "quality" option; option for filetype, or split into helper... #e also possible: image.save(filename, "PNG") ##e probably better: "If format is omitted, the format is determined from the filename extension, if possible." # (Note that's about image.img.save -- not sure it also applies yet to image.save itself. # It's in http://www.pythonware.com/library/pil/handbook/image.htm .) # But I'd need to read up about how the option should be given for other formats. if os.path.isfile(filename): print "saved image, %d x %d:" % (w,h), filename else: print "save image (%d x %d) didn't work:" % (w,h), filename return pass # end of class PixelGrabber # end
NanoCAD-master
cad/src/exprs/images.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ DraggableHandle.py - some convenience exprs for draggable handles @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. Note about the name: we use DraggableHandle rather than DragHandle, to avoid confusion with the DragHandler API (which would otherwise differ by only the final 'r'). """ from utilities.constants import white from exprs.attr_decl_macros import Instance, Option from exprs.transforms import Translate from exprs.Center import Center from exprs.ExprsConstants import StateRef, Vector from exprs.attr_decl_macros import State from exprs.ExprsConstants import Point, Drawable from exprs.ExprsConstants import ORIGIN, DX ##,DY from exprs.Highlightable import Highlightable from exprs.Rect import Rect from exprs.Exprs import tuple_Expr, call_Expr from exprs.__Symbols__ import _self from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.DragBehavior_AlongLine import DragBehavior_AlongLine # old todo: clean up from exprs.geometry_exprs import Ray from exprs.Set import Action from exprs.Exprs import call_Expr from exprs.If_expr import If_expr class DraggableHandle_AlongLine(DelegatingInstanceOrExpr): ### TODO: all options might need renaming! replace "height" everywhere. """ A kind of draggable handle which can be dragged along a line to change the value of a single floating point parameter (representing position along the line, using a scale and origin determined by our arguments). ### TODO: add epydoc parameters to this docstring? not sure that will work for a class! Maybe we need to synthesize those (from the doc options below) into a fake __init__ method for its sake?? """ # == args and options # options for appearance of handle appearance = Option( Drawable, Center(Rect(0.2, 0.2, white)), doc = "our appearance, when not highlighted") ###e take other args of Highlightable? appearance_highlighted = Option( Drawable, appearance, doc = "our appearance, when highlighted") sbar_text = Option(str, "draggable handle", doc = "our statusbar text on mouseover") # state variable controlled by dragging height_ref = Option(StateRef, doc = "stateref to a height variable") # TODO: rename, redoc range = Option(tuple_Expr, None, doc = "range limit of height (tuple)") ### MAYBE: RENAME to avoid conflict with python range in this code ### TODO: take values from the stateref if this option is not provided # action options, for Highlightable to do after the ones that come from # DragBehavior_AlongLine [new feature of this and Highlightable, 080129] on_press = Option(Action) on_drag = Option(Action) on_release = Option(Action) on_release_in = Option(Action, on_release) on_release_out = Option(Action, on_release) on_doubleclick = Option(Action) # line along which to drag it, and how to interpret the state as a position along that line (origin and scale) origin = Option( Point, ORIGIN) direction = Option( Vector, DX, doc = "vector giving direction and scale") # providing a default value is mainly just for testing #If this is false, the 'highlightable' object i.e. this handle #won't be drawn. The delegate (that defines a Highlightable) #We define an If_expr to check whether to draw the highlightable object. #[by Ninad] # [this should probably be revised, with hasValidParamsForDrawing replaced # with an overridable compute method, for robustness -- current implem # is suspected of causing tracebacks from insufficient update of this # state. Need to review whether methodname needs to be hasValidParamsForDrawing # to conform with any API. -- bruce 080409 comment] should_draw = State(bool, True) # == internal instances and formulae (modified from test_statearray_3.py) _drag_handler = Instance( DragBehavior_AlongLine( _self._delegate, height_ref, call_Expr(Ray, origin, direction), # note: we need call_Expr since Ray is an ordinary class, not an expr! ###FIX range = range )) # note: _drag_handler is also being used to compute the translation from the height, even between drags. #@see: DnaStrand_ResizeHandle.hasValidParamsForDrawing #@see: definition of State attr should_draw delegate = \ If_expr( _self.should_draw, Highlightable( Translate( appearance, _drag_handler._translation #k ok?? only if that thing hangs around even in between drags, i guess! #e #k not sure if this code-commoning is good, but it's tempting. hmm. ), highlighted = Translate( appearance_highlighted, _drag_handler._translation ), sbar_text = sbar_text, behavior = _drag_handler, on_press = _self.on_press, on_drag = _self.on_drag, # (note: no need to pass on_release) on_release_in = _self.on_release_in, on_release_out = _self.on_release_out, on_doubleclick = _self.on_doubleclick ) #end of Highlightable ) #end of If_expr def hasValidParamsForDrawing(self): """ Overridden in subclasses. Default implementation returns True if this object (the highlightable) can be drawn without any known issues @see: DnaStrand_ResizeHandle.hasValidParamsForDrawing for more notes. """ self.should_draw = True return self.should_draw pass # end of class
NanoCAD-master
cad/src/exprs/DraggableHandle.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ pallettes.py $Id$ """ from exprs.Highlightable import Highlightable from exprs.world import World from exprs.Boxed import Boxed from exprs.draggable import DraggableObject from utilities.constants import blue, green from exprs.Exprs import or_Expr, format_Expr from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.attr_decl_macros import ArgExpr, Option, State from exprs.ExprsConstants import PIXELS, ORIGIN from exprs.__Symbols__ import Anything, _self class PalletteWell(DelegatingInstanceOrExpr): """A place in the UI which can make copies of its expr for dragging to whereever you want [not fully working yet] """ # experimental, really a stub, 070212 -- but sort of works! (as tested in dna_ribbon_view.py) expr = ArgExpr(Anything) #e not really Anything, but some interface ##e should really be StateArg world = Option(World) ###e find in env, instead?? maybe not, since in typical cases we might rather make in some parent in # the model anyway, which depends on which kind of obj we are and which pallette we're in... # maybe we even need a make-function to be passed in. # If it was an arg, it'd be natural as arg1 (since this is like a method on the world); # but since it might become a dynamic env var, I'll use an option for now. # If it was a dynamic var by default but could be some container obj, an option would be good for that too (renamed #e). type = Option(str, doc = "type of thing to tell world we're making [type, api subject to change]") ###BUG: passing type to world.make_and_add is nim what_to_make_nickname = or_Expr(type, "something") #e classname of expr, after burrowing? some other namelike attr of expr? # (note, hard to have that, unless expr is a new special Instance type of "makable" rather than a bare expr -- # and it probably ought to be. ##e) sbar_text = Option(str, format_Expr("make %s", what_to_make_nickname) ) _what_to_make = DraggableObject(_self.expr) ##e rename DraggableObject -> Draggable? I misrecalled it as that... and "object" is arguably redundant. _newobj = State(Anything, None) # set internally to an object we create during _self.on_press delegate = Highlightable( Boxed(expr, borderthickness = 2 * PIXELS), # plain ###BUG: Boxed fails with exprs that don't have bleft, with a very hard to decipher exception Boxed(expr, borderthickness = 2 * PIXELS, bordercolor = blue), # highlight Boxed(expr, borderthickness = 2 * PIXELS, bordercolor = green), # [pressed] green signifies "going" (mainly, green != blue) on_press = _self.on_press, on_drag = _newobj.on_drag, on_release = _newobj.on_release, sbar_text = sbar_text ###e UI DESIGN: need to also pass sbar text (or a func to get it from selobj) for use during the drag ) def on_press(self): # make a new object self._newobj = self.world.make_and_add( self._what_to_make) ##e also pass the type option, taken from a new _self option? ###e UI DESIGN FLAW: we should probably not actually make the object until the drag starts... # better, make something now, but only a fake, cursor-like object (not placed in the model or its tree) # (maybe a thumbnail image made from expr? maybe use PixelGrabber on self, to get it?? #e) # and only make a real model object when the drag *ends* (in a suitable mouse position -- otherwise cancel the make). if 'kluge 070328, revised 070401': ###e see also comments in class World, 070401 self._newobj.copy_saved_coordsys_from( self.world._coordsys_holder ) # start a drag of the new object; first figure out where, in world coordinates, and in the depth plane # in which you want the new object to appear (and move the object there -- without that it'll be at the origin) point_in_newobj_coords = self._newobj.current_event_mousepoint(plane = ORIGIN) ### LOGIC BUG: this seems to work, but it presumbly has this bug: in current implem, self._newobj's local coordsys # can't be available yet, since it's never been drawn! So it presumably gives out a debug message I've been seeing # ("saved modelview_matrix is None, not using it") # and uses global modelview coords, which happen to be the same in the current test (in dna_ribbon_view.py). ###KLUGE: use ORIGIN (which we know) in place of center of view (which we don't) -- only correct when no trackballing self._newobj.motion = point_in_newobj_coords ###KLUGE since it centers new obj on mouse, even if mousedown was not centered on sample obj ###BUG (confirmed): I bet the point would be wrong in perspective view, unless we first corrected the depth plane, # then reasked for point. # trying that 070217 -- But how to fix? To correct the plane, we need to flush the DraggableObject in self._newobj, at least, # before current_event_mousepoint is likely to use correct coords (actually I'm not sure -- ###TEST) # but we can't since not all objects define .move (need to ###FIX sometime). ## self._newobj.flush() # so try this even though it might not work: ## point_in_newobj_coords_2 = self._newobj.current_event_mousepoint(plane = ORIGIN) ### but now, what do we do with this point??? # print "debug note: compare these points:",point_in_newobj_coords, point_in_newobj_coords_2 # result: identical coords. # so it doesn't work and doesn't even make sense yet... i probably can't proceed until the logic bug above is fixed. # There's also the issue of different object size on-screen if it's shown at a different depth. # (Unless that could help us somehow, in showing the depth? doubtful.) ### UI DESIGN FLAWS: the new obj is obscured, and there is no visual indication you "grabbed it", tho you did. # (actually there is one, if you wait long enough and didn't happen to grab it right on the center! but it's subtle -- # and worse, it's arguably due to a bug.) ##e would box border color change help? or box "dissolve"?? (ie temporarily remove the box) # or we might need to hide the pallette well (or make it translucent or not depth-writing) ###e need sbar messages, some message that you grabbed it (which would mitigate the visual flaw above) self._newobj.on_press() # needed so its on_drag and on_release behave properly when we delegate to them above return pass # end of class PalletteWell # end
NanoCAD-master
cad/src/exprs/pallettes.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ $Id$ """ # == local imports with reload from utilities.debug import safe_repr from utilities.debug import print_compact_stack from exprs.Exprs import internal_Expr ###k probably not needed (imported by basic) but needs test from exprs.py_utils import printnim from exprs.py_utils import printfyi from exprs.instance_helpers import DelegatingMixin from exprs.attr_decl_macros import Arg from exprs.widget2d import Widget from exprs.__Symbols__ import Anything # == def getattr_debugprint(obj, attr): #070211; tested, though not usually in use """a version of getattr which does better debug printing on exceptions (use it as a drop-in replacement for 2-arg getattr to help with debugging) """ try: return getattr(obj, attr) except AttributeError: print "getattr_debugprint: %s has no %r (reraising)" % (safe_repr(obj), attr) raise pass class debug_evals_of_Expr(internal_Expr):#061105, not normally used except for debugging "wrap a subexpr with me in order to get its evals printed (by print_compact_stack), with (I hope) no other effect" def _internal_Expr_init(self): self._e_args = self.args # so replace sees the args assert len(self.args) == 1 def _e_eval(self, env, ipath): assert env the_expr = self._e_args[0] res = the_expr._e_eval(env, ipath) print_compact_stack("debug_evals_of_Expr(%r) evals it to %r at: " % (the_expr, res)) # this works return res def _e_eval_lval(self, env, ipath):#070119 also print _e_eval_lval calls [maybe untested] assert env the_expr = self._e_args[0] res = the_expr._e_eval_lval(env, ipath) print_compact_stack("debug_evals_of_Expr(%r) eval-lvals it to %r at: " % (the_expr, res)) #k does this ever happen? return res pass printnim("bug in DebugPrintAttrs, should inherit from IorE not Widget, to not mask what that adds to IorE from DelegatingMixin")###BUG class DebugPrintAttrs(Widget, DelegatingMixin): # guess 061106; revised 061109, works now (except for ArgList kluge) """delegate to our arg, but print specified attrvalues before each draw call """ #e might be useful to also print things like x,y,depth hitpoint window coords & 3d coords (see obs code DebugDraw, removed after cvs rev 1.3) delegate = Arg(Anything) ## attrs = ArgList(str) # as of 061109 this is a stub equal to Arg(Anything) attrs = Arg(Anything, []) def draw(self): guy = self.delegate print "guy = %r" % (guy, ) ## attrs = self.args[1:] attrs = self.attrs if type(attrs) == type("kluge"): attrs = [attrs] printnim("need to unstub ArgList in DebugPrintAttrs") else: printfyi("seems like ArgList may have worked in DebugPrintAttrs") if 'ipath' not in attrs: attrs.append('ipath')#070118; not sure it's good for name in attrs: print "guy.%s is" % name, getattr(guy,name,"<unassigned>") return self.drawkid( guy) ## return guy.draw() pass # end
NanoCAD-master
cad/src/exprs/debug_exprs.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ Highlightable.py - general-purpose expr for mouse-responsive drawable objects @author: Bruce @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. This will start out as just a straight port of class Highlightable from cad/src/testdraw.py, with the same limitations in API and implem (e.g. it won't work inside display lists). Later we can revise it as needed. == Notable bug (really in check_target_depth in GLPane, not this file): highlighted-object-finder can be fooled by nearby depths due to check_target_depth_fudge_factor of 0.0001. This caused a bug in demo_drag.py which is so far only worked around, not really fixed. [070115 comment] Another bug involves Highlightable's use inside display lists, and is described elsewhere, probably in the BUGS file. And on 071102 I noticed another bug, probably related: the checkboxes in the lower right "control corner" don't highlight or operate after the main window (and thus glpane) is resized, until we next reload testdraw. But the "action buttons" next to them continue to work then. I don't know why they'd behave differently. """ from OpenGL.GL import glPushName from OpenGL.GL import glPopName from OpenGL.GL import GL_PROJECTION_MATRIX from OpenGL.GL import glGetDoublev from OpenGL.GL import GL_MODELVIEW_MATRIX from OpenGL.GL import GL_PROJECTION from OpenGL.GL import glMatrixMode from OpenGL.GL import glPushMatrix from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import glLoadMatrixd from OpenGL.GL import glPopMatrix from OpenGL.GLU import gluProject, gluUnProject from utilities import debug_flags from utilities.Comparison import same_vals from geometry.VQT import A from geometry.VQT import vlen from geometry.VQT import V from utilities.constants import noop from utilities.constants import green from utilities.debug import print_compact_traceback from exprs.Exprs import or_Expr, canon_expr from exprs.Exprs import printfunc from exprs.Exprs import is_expr_Instance_or_None from exprs.StatePlace import set_default_attrs from exprs.attr_decl_macros import Option, ArgOrOption, Arg from exprs.instance_helpers import InstanceOrExpr, DelegatingMixin, ModelObject, DelegatingInstanceOrExpr from exprs.ExprsConstants import ORIGIN from exprs.widget2d import Widget2D from exprs.Set import Action from exprs.py_utils import printnim from exprs.__Symbols__ import _self, Anything from graphics.drawables.DragHandler import DragHandler_API #bruce 070602 moved this from exprs/Highlightable.py to DragHandler.py, and renamed it from graphics.drawables.Selobj import Selobj_API # for the "selobj interface" (subject to renaming) # == # modified from testdraw.printfunc: def print_Expr(*args, **kws): ##e rename to include Action in the name?? #e refile """ #doc """ #e might be more useful if it could take argfuncs too (maybe as an option); or make a widget expr for that def printer(_guard = None, args = args): assert _guard is None # for now printfunc(*args, **kws) # defined in Exprs, has immediate effect, tho same name in testdraw is delayed like this print_Expr return canon_expr(printer) # == #e turn these into glpane methods someday, like all the other gl calls; what they do might need to get fancier def PushName(glname, drawenv = 'fake'): glPushName(glname) # glpane._glnames was needed by some experimental code in Invisible; see also *_saved_names (several files); might be revived: ## glpane = _kluge_glpane() ## glpane._glnames.append(glname) ###e actually we'll want to pass it to something in env, in case we're in a display list ####@@@@ return def PopName(glname, drawenv = 'fake'): glPopName() ##e should protect this from exceptions #e (or have a WE-wrapper to do that for us, for .draw() -- or just a helper func, draw_and_catch_exceptions) ## glpane = _kluge_glpane() ## popped = glpane._glnames.pop() ## assert glname == popped return # == # maybe todo: refile recycle_glselect_name next to alloc_my_glselect_name (assy method), or merge this with it somehow # (and maybe change all that into a gl-displist-context-specific data structure, accessed via a glpane) def recycle_glselect_name(glpane, glname, newobj): #e refile (see above) # 1. [nim] do something to make the old obj using this glname (if any) no longer valid, # or tell it the glname's being taken away from it (letting it decide what to do then, eg destroy itself), or so -- # requires new API (could be optional) in objs that call alloc_my_glselect_name. ##e # 2. If the old obj is the glpane's selobj, change that to point to the new obj. [#e might need improvement, see comment] # 3. register the new object for this glname. oldobj = glpane.object_for_glselect_name(glname, None) if oldobj is not None and glpane.selobj is oldobj: glpane.selobj = None ###### normally newobj -- SEE IF THIS HELPs THE BUG 061120 956p printnim("glpane.selobj = None ###### normally newobj") # worse, i suspect logic bug in the idea of reusing the glname.... ###k we might need to call some update routine instead, like glpane.set_selobj(newobj), # but I'm not sure its main side effect (env.history.statusbar_msg(msg)) is a good idea here, # so don't do it for now. ## env.obj_with_glselect_name[glname] = newobj glpane.assy._glselect_name_dict.obj_with_glselect_name[glname] #bruce 080917 revised; ### TODO: fix private access, by # moving this method into class GLPane and/or class Assembly & class glselect_name_dict return ##def selobj_for_glname(glname):#e use above? nah, it also has to store into here ## import foundation.env as env ## return env.obj_with_glselect_name.get(glname, None) # == def copy_pyopengl_matrix( matrix): #bruce 070704 # note, 081202: not known whether this works when matrix is a numpy.ndarray. try: # this works when it's a Numeric array (as it is in some Mac PyOpenGLs) return + matrix #k let's hope this is a deep copy! except TypeError: # this happens when it's a 'c_double_Array_4_Array_4' object (some sort of ctypes array, I assume) # which is what Mac Gold PyOpenGL returns for matrices. My initial web research reveals clues # about copying this into a Numeric array, but not yet a good method, nor a way to copy it into # another object of the same type, which is what's needed here. ## print "following exception was in copy_pyopengl_matrix( %r):" % (matrix,) ## raise # # Hmm, something on the web says "Since the ctype does support slicing", so I'll try that: return matrix[:] # works! (### REVIEW: Would it work for a Numeric array too? If so, should just use it always.) pass # == _DEBUG_SAVED_COORDS = False class _CoordsysHolder(InstanceOrExpr): # split out of class Highlightable, 070317 """ Abstract superclass [private] for Instances which can capture the current OpenGL drawing coordinates, restore them later, and do OpenGL state queries within them. Superclass of Highlightable [though maybe it could just own one of us in an attr, instead?? ##e]; and of SavedCoordsys, for holding a saved static coordsys. @warning: implem and API may change once we introduce "draw decorators" to fix Highlightable/DisplayListChunk bugs. """ projection = Option(bool, True) # whether to save projection matrix too # Note: this was default False until 081202 eve, when I changed it to True # in order to fix the "zoom disables checkbox" bug # (described in the 081202 update to DisplayListChunk module docstring), # which occurs when this interacts with DisplayListChunk # I am not sure if the buggy interaction involves DisplayListChunk outside or # inside this expr, or both, nor exactly why this change fixes it. # But it does, and (alternatively) disabling DisplayListChunk (by debug_pref) also does. # # There is a possible speed issue with this being default True, # but I think that won't matter for a small number of Highlightables, # and if I ever use lots of them I plan to reimplement it so it never # needs to save coordinates (to fix other bugs that I think still exist, # as well as for speed), in ways described elsewhere long ago. Alternatively, # maybe I could figure out in exactly which instances this needs to be True. def _init_instance(self): super(_CoordsysHolder, self)._init_instance() # == per_frame_state set_default_attrs( self.per_frame_state, saved_modelview_matrix = None, saved_projection_matrix = None ) #k safe? (why not?) #e can't work inside display lists return # from _init_instance def run_OpenGL_in_local_coords(self, func): #061206 """ Run the OpenGL code in func in self's local coordinate system (and with its GL context current), and not while compiling any display list. If we run func immediately (always true in present implem), return (True, func-retval); otherwise return (False, not-yet-defined-info-about-how-or-why-we-delayed-func). Intended to be called from user mouse event handlers (not sure if ok for key or wheel events ##k). Maybe we'll also sometimes call it from later parts of a rendering loop, after the main drawing part; see below for caveats related to that. For now, this is defined to run func immediately (thus it's illegal to call this if you're presently compiling a display list -- but this error might not yet be detected, unless func does something explicitly illegal then). More subtlely, the current implem may only work when self was (1) in fact drawn (rather than being not drawn, due to being hidden, culled at a high level since obscured or outside the view frustum, etc) in the most recently drawn frame, (2) drawn outside of a display list, rather than as part of one we ran, when it was drawn then. That's because this implem works by caching a matrix containing the local coords as a side effect of self being drawn. [#e For info on fixing that, see code comments.] WARNINGS: - The current implem assumes no widget expr modifies the OpenGL projection matrix. This will change someday, and we'll probably need to save and restore both matrices. #e [as of 061208 we tried that, but it may have broken highlightable, not for sbar text but for color change... could it relate to glselect?? hmm... i'm adding a flag so i can test this.] - This does not reproduce all OpenGL state that was used to draw self, but only its local modelview matrix. - This does not ensure that any display lists that might be called by func (or by self.draw) are up to date! #e Later we might revise this API so it adds self, func to a dict and runs func later in the rendering loop. Then it might be legal to call this while compiling a display list (though it might not be directly useful; for a related feature see draw_later [nim?]). We might add args about whether delayed call is ok, properties of func relevant to when to delay it too, etc. See also draw_in_abs_coords, which is sort of like a special case of this, but not enough for it to work by calling this. """ #e When this needs to work with display lists, see '061206 coordinate systems' on bruce's g5. #e We should probably move this to a mixin for all widget exprs that save their coordinates, # either as this current implem does, or by saving their position in a scenegraph/displaylist tree # and being able to do a fake redraw that gets back to the same coords. run_immediately = True if run_immediately: self.env.glpane.makeCurrent() # as of 070305 we might run this outside of paintGL, so this might be needed self.begin_using_saved_coords() try: res = func() finally: self.end_using_saved_coords() pass else: assert 0, "nim" res = None return run_immediately, res # from run_OpenGL_in_local_coords def save_coords(self): #e make private? most calls go thru save_coords_if_safe -- not quite all do. # weirdly, this seems to cause bugs if done in the other order (if self.projection is False but not checked here)... # could it change the current matrix?? or be wrong when the wrong matrix is current??? if self.projection: glMatrixMode(GL_PROJECTION) #k needed? self.per_frame_state.saved_projection_matrix = glGetDoublev( GL_PROJECTION_MATRIX ) # needed by draw_in_abs_coords glMatrixMode(GL_MODELVIEW) if _DEBUG_SAVED_COORDS: old = self.per_frame_state.saved_modelview_matrix if old is not None: old = + old self.per_frame_state.saved_modelview_matrix = new = glGetDoublev( GL_MODELVIEW_MATRIX ) # needed by draw_in_abs_coords ## if _DEBUG_SAVED_COORDS and (old != new): # The above can get this exception, caused by != on numpy.ndarray objects: ## ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() # [seen by bruce 081201 uaing python 2.5, not sure what version of PyOpenGL]. # Just using .any() doesn't work since (old != new) is sometimes a boolean which doesn't have that method # (untested guess: maybe that only happens when old is None?). # So to fix it in general, I extended the Python same_vals to handle that type # and use it here. The C same_vals is not yet extended for that, # but I fixed a bug in it (more precisely, worked around that bug in its .pyx caller) # to at least report the exception in that case. [bruce 081202] if _DEBUG_SAVED_COORDS: # print "_DEBUG_SAVED_COORDS type(old) = %r" % (type(old),) # NoneType or numpy.ndarray if not same_vals(old, new): print "_DEBUG_SAVED_COORDS: %r changes saved coords" % self # the following comments are about the implem of save_coords -- # need review -- which are obs and which should be moved? ### # ###WRONG if we can be used in a displaylist that might be redrawn in varying orientations/positions # # addendum 061121: if saved coords are usage tracked (which was never intended), then right here we invalidate whatever used it # (but nothing used it yet, the first time we draw), but in draw_in_abs_coords we use it, so if we ever redraw # after that (as we will - note, nothing yet clears/replaces this per_frame_state every frame), # then that invals the highlighted thing... i can imagine this creating extra invals, esp since the change # occurs during usage tracking of a computation (invalling it the first time), which then uses the same thing. # I don't quite see the exact cause, but I certainly see that it's not an intended use of this system. # (#e sometime I should think it through, understand what's legal and not legal, and add specific checks and warnings.) # Meanwhile, since all per_frame state is not intended to be usage-tracked, just recorded for ordinary untracked # set and get, I'll just change it to have that property. And review glpane_state too. ###@@@ [this, and 061120 cmts/stringlits] return def save_coords_if_safe(self): #070401 [#e rename?] """ call self.save_coords if the glpane drawing phase indicates the results should be valid for highlighting """ if not self.env.glpane.current_glselect: # when that cond is false, we have a nonstandard projection matrix # REVIEW: does the jig-select code in Select_GraphicsMode.py # also set it to indicate that? if not, does that cause any bugs # due to this condition not turning off save_coords then? # [bruce 081204 question] self.save_coords() # Historical note: using this cond apparently fixes the # projection = True bug (even when used in DrawInCorner_projection), # based on tests and debug prints of 070405. The cond itself was # added long before. See testexpr_9cx / testexpr_9cy. # It's not really known if that's all that fixed it; # on 070118 I said: # I don't know why/how/ifreally it got fixed, but maybe it did, # since I did a few things to highlighting code since that time, # including not using that z-offset kluge in the depth test, # changing to GL_LEQUAL (with different Overlay order), maybe more. # # For details of debug prints, see cvs rev 1.66. They show that # glpane.drawing_phase is 'main' here and 'glselect' when this cond # is false, at least when self.projection is true and when using # those testexprs. # # Update 081202: note (known at the above time, I think): # the reason adding this cond helps is that the projection matrix # is nonstandard when this cond is false, so saving it then # basically saves a nonsense value. return def begin_using_saved_coords(self): # fyi: examples of glLoadMatrix (and thus hopefully the glGet for that) # can be found in these places on bruce's G4: # - /Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/OpenGLContext/renderpass.py # - /Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/VisionEgg/Core.py projection_matrix = self.per_frame_state.saved_projection_matrix modelview_matrix = self.per_frame_state.saved_modelview_matrix #k make sure we can access these (to get the most likely exceptions # out of the way) (also shorten the remaining code) if self.projection: glMatrixMode(GL_PROJECTION) glPushMatrix() self.safe_glLoadMatrixd( projection_matrix, "projection_matrix") glMatrixMode(GL_MODELVIEW) glPushMatrix() self.safe_glLoadMatrixd( modelview_matrix, "modelview_matrix") # safe -> thus perhaps avoiding a crash bug [the one I had recently? 061214 Q] return def safe_glLoadMatrixd(self, matrix, name): # note: doesn't use self, ought to refile in draw_utils.py or a glpane proxy ###e """ call glLoadMatrixd(matrix) if it looks like matrix has the right type; print a warning otherwise. """ # as of initial commit, 061214 359, the crash bug never recurred but neither did I see any prints from this, # so it remains untested as a bugfix, tho it's tested as a matrix-loader. if matrix is None: print "in %r, saved %s is None, not using it" % (self, name,) # thus perhaps avoiding a crash bug # I predict I'll see this where i would have otherwise crashed; ### print until i'm sure the bug is fixed # text searches for this print statement might find it more easily if we add this text to the comment: # "saved modelview_matrix is None, not using it" [bait for a text search -- the real print statement has %s in it] return # I would like a matrix typecheck here, but the type depends on the PyOpenGL implementation # (for more info see the comments in the new function copy_pyopengl_matrix), # so I don't know how to do it correctly in all cases. The following code is what worked # in an older PyOpenGL, but the AttributeError inside it shows what happened in a newer one, # i.e. in the Mac "Gold" PyOpenGL for A9.1. [bruce 070703] ##try: ## matrix.shape != (4,4) ##except: ## print_compact_traceback("bug in matrix.shape check: ") ## ## AttributeError: 'c_double_Array_4_Array_4' object has no attribute 'shape' ## print "not using wrong type of %s, which is %r" % (name, matrix) ## return ##if matrix.shape != (4,4): ## print "not using misshappen %s, which is %r" % (name, matrix) ## return glLoadMatrixd(matrix) # crashes Python if matrix has wrong type or shape, it seems [guess for now] return def end_using_saved_coords(self): if self.projection: glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() def current_event_mousepoint(self, center = None, radius = None, plane = None, depth = None, _wXY = None): #061206; 070203 added 'plane' and revised docstring; 070226 added _wXY; 070314 added depth #e rename? #e add variant to get the drag-startpoint too #e cache the result #e is this the right class for it? self is only used for glpane and local coords, # but "run_OpenGL_in_local_coords" is only implementable in this class for the moment. """ Return the 3d point (in self's local coordinates) corresponding to the mouse position of the current mouse event (error if no current mouse event which stores the necessary info for this), interpreting its depth based on the arguments/options. If no options are passed, then the event's depth is defined (for now) by the depth buffer pixel clicked on, unless the click was in empty space, in which case the plane of the center of view [partly nim] is used. (This is partly nim as of 070203 since the actual cov is not used; local V(0,0,0) is used to approximate it.) If center is passed, it is used in place of the center of view to determine depth of empty-space clicks. (The behavior when center is not passed is equivalent to passing the "center of view" (in local coordinates) as center.) If radius [nim] and center are passed, then clicks in empty space only use center if they are close enough to it (within distance radius in center's plane) -- this imitates mouse hits on a screen-parallel circular disk defined by center and radius. If the disk is missed, the center of view is used as before. If plane is passed, all the above data is ignored (depth buffer, center of view, center, radius). If plane is a plane [nim], the hit is assumed to lie within it; if a point, the hit lies within the screen-parallel plane containing that point. Alternatively, an OpenGL depth value can be passed, and the hit lies at that depth. Private option for use by other methods: _wXY overrides the window coords of the mouse event, so you can get things like the corners/edges/center of a screen rectangle projected (ortho or perspective as approp) to the same depth as a point (passed in plane), assuming you know about glpane.width and .height. WARNING [partly obs]: this is so far implemented for click (press) but not drag or release; it remains to be seen exactly what it will do for drag when the depth under the mouse is varying during the drag. ##k [later: it is used for drag successfully in demo_drag.py, but in a way which can be confused by seeing depth of dragobj vs depth of background objs.] WARNING: this only works on widgets which store, or can reconstruct, their local coordinate system used to draw them in the just-drawn frame. Only some kinds can (for now only Highlightable), and only if they were actually drawn in the just-drawn frame (if they weren't, we might give wrong results rather than detecting the error). See more caveat comments in the current implementing submethod (run_OpenGL_in_local_coords). Terminology note: point implies 3d; pos might mean 2d, especially in the context of a 2d mouse. So it's named mousepoint rather than mousepos. Delegation usage note: this can be called on self, if self delegates to a Highlightable (perhaps indirectly) and uses the same local coordinate system as that Highlightable. """ glpane = self.env.glpane try: # during leftClick, this has been computed for us: info = glpane._leftClick_gl_event_info # this will fail if we're called during the wrong kind of user event except AttributeError: # during drag, it's often not needed, so compute it only if we need it -- which we do right now. # (WARNING: if we decide to cache it somewhere, don't do it in glpane._leftClick_gl_event_info or we'll cause bugs, # since that would not get delattr'd at the end of the drag-event, so it might confuse something which saw it later # (tho in practice that's unlikely since the next leftClick to a Highlightable would overwrite it). # But I bet we won't need to cache it -- maybe this routine will be called by some standard attr's # recompute method, so that attr will cache it.) # # Note: we could clean up/safen this system, and remove that warning above, if we just controlled a single dict or # attrholder in glpane, and cleared it each time; it could be full of per-user-event info of all kinds, # including some cached here -- or by its own recompute methods. We could have one for per-extended-drag info # and one for per-drawn-frame info. ###DOIT sometime mode = glpane._kluge_drag_mode event = glpane._kluge_drag_event gl_event_info = mode.dragstart_using_GL_DEPTH( event, more_info = True) # same as what mode did itself, for a leftClick #print "during drag got this info:",gl_event_info info = gl_event_info def func(center = center, radius = radius, plane = plane, depth0 = depth, _wXY =_wXY): """ [local helper func, to be passed to self.run_OpenGL_in_local_coords] """ # will the arg dflts fix this bug when I drag off the edge of the object? # UnboundLocalError: local variable 'center' referenced before assignment farQ, abs_hitpoint, wX, wY, depth, farZ = info if _wXY is not None: ### this case is UNTESTED, NOT YET USED wX, wY = _wXY if depth0 is not None: depth = depth0 farQ = False elif plane is not None: center = plane # assume it's a point -- # passing an actual plane is nim (btw, we don't even have a standard way of passing one) radius = None farQ = True # now we can use the remaining code #e [code cleanup needed: call a routine split from the following instead, # in case more options we'd have to turn off here are added later into the following code.] if not farQ: point = A(gluUnProject(wX, wY, depth)) else: if center is None: center = V(0,0,0) #e stub (not enough info) -- # we need the center of view in local coords (tho this substitute is not terrible!), # e.g. turn abs_hitpoint into local coords (how?) or into x,y,depth... maybe selectMode will need # to put more info into _leftClick_gl_event_info before we can do this. ###e ## point = center #e stub (since i'm lazy) -- # the rest of the work here is straightforward: # just intersect the mouseray (gotten using mymousepoints or equiv) with the center/radius sphere # (really with a screen-parallel plane through center) to decide what to do. In fact, the same code used # in mymousepoints could probably do it -- except that code uses glpane.lineOfSight # which might be in abs coords. (I'm not sure! Need to review that in GLPane.__getattr__. ###k) # Hmm, a simpler way might be to get center's depth using gluProject, then use that depth in gluUnProject # to get the mousepoint at the same depth, which is the intersection asked for above, then compare distance # to radius. xjunk, yjunk, center_depth = gluProject(center[0],center[1],center[2]) #k is there a "gluProjectv"? intersection = A(gluUnProject(wX, wY, center_depth)) if radius is not None and radius < vlen(intersection - center): # intersection is too far from center to count -- redo with cov instead of center pass # that's nim for now ####e point = intersection # point is a Numeric array, and we needn't copy it for safety since it was constructed anew in each case above return point # from func ran_already_flag, funcres = self.run_OpenGL_in_local_coords( func) assert ran_already_flag # it ran immediately # semi-obs comment from when I had this method in Widget but had run_OpenGL_in_local_coords in Highlightable, causing a bug: # note: run_OpenGL_in_local_coords only works (or is only defined) for some kinds of widgets, presently Highlightable. # Since it's not defined on other widgets, it will also delegate from them to a Highlightable if they delegate to one, # but this is often accidental (adding a Translate wrapper would break it), so it's not good to rely on it unless you # doc that. WORSE, if a transforming widget delegates other attrs (like that method) to a Highlightable inside, # IT WILL MAKE THIS SILENTLY GIVE WRONG RESULTS (in the wrong coords). This should be fixed by preventing this # from delegating through transforms (or maybe though anything), but that makes some upcoming code harder, # needlessly for now, so it's postponed. ##e # [##k this delegation is also untested, but then, so is everything else about this, as of 061206 9pm.] ###BUG: that comment warns about problems that are NOT obs, namely, delegation through a transform (like Translate) # to this routine. Probably we should define it on IorE, and ensure that it only delegates when justified, #####e DOIT # i.e. not in transforms, which need their own class so they can define this method as an error # (unless they can delegate it and then fix the result, which might be ok and useful). # # The bug was, I defined this in Widget, used it in a thing I expected to delegate twice to reach Highlightable, # but none of that stuff inherited Widget so it went all the way thru that into Rect to run this, then didn't # find the submethod inside Highlightable since delegation (its defect) had skipped it! [digr: Note: if that defect of # delegation bothers us in specific cases, a workaround is to pass self as explicit last arg to methods # that might get delegated to, but that want to call submethods on the original object!! ###e] return funcres # from current_event_mousepoint def gluProject(self, point): #070226; probably to be moved to more kinds of objects but implemented differently, eventually """ Return the same (wX, wY, depth) that gluProject would or should return if run in local model coords (and gl state for drawing) of this object, on point (which should be an x,y,z-tuple or Numeric array in the same coords). This may or may not actually run gluProject depending on the implementation [as of 070226 it always does, and has ###BUGS inside display lists after trackballing]. WARNING: Proper behavior inside a display list is not yet defined; maybe it will have to assume something about the list's initial coords... or the caller will have to pass those... or self will have to know how to ask a parent DisplayListChunk for those. ##e """ ###UNTESTED, NOT YET USED ran_already_flag, funcres = self.run_OpenGL_in_local_coords( lambda p = point: gluProject(p[0],p[1],p[2]) ) assert ran_already_flag # it ran immediately wX, wY, depth = funcres return wX, wY, depth def gluUnProject(self, wX, wY, depth): #070226 """ Act like gluUnProject... for more info (and bugs) see docstring for gluProject. """ ###UNTESTED, NOT YET USED ran_already_flag, funcres = self.run_OpenGL_in_local_coords( lambda: gluUnProject(wX, wY, depth) ) assert ran_already_flag x,y,z = funcres return V(x,y,z) def screenrect(self, point = ORIGIN):#070226 ##e rename? btw what interface are this and current_event_mousepoint part of? """ Return the 4 corners (in local model coords) of a screen rectangle, projected to the same depth as point (which is also in local model coords; if left out it's their origin). """ #e should add option to directly pass depth # we don't call self.gluProject etc since we don't want to internally call self.run_OpenGL_in_local_coords 5 times! def func(): p = point xjunk, yjunk, depth = gluProject(p[0],p[1],p[2]) # get depth of point glpane = self.env.glpane w = glpane.width h = glpane.height #e should we add one (or half) to those?? ie is true x range more like 0,w or -0.5, w + 0.5 or 0, w+1?? # (x,y) might be (in ccw order around the screenrect, starting from botleft to botright): res = map( lambda (wX, wY): A(gluUnProject(wX, wY, depth)), ((0,0), (w,0), (w,h), (0,h)) ) return res # from func ran_already_flag, funcres = self.run_OpenGL_in_local_coords( func ) assert ran_already_flag return funcres def copy_saved_coordsys_from(self, other): #070328 moved here from subclass SavedCoordsys, and renamed from copy_from if 'kluge 070328': other0 = other # for error messages only while not isinstance(other, _CoordsysHolder): try: other1 = other._delegate # might fail, but if it does, this method was doomed to fail anyway (in current implem) assert other1 is not None other = other1 except: print_compact_traceback("bug in %r.copy_saved_coordsys_from(%r): no _delegate in %r: " % (self, other0, other)) #e may need better error message if it fails return projection_matrix = other.per_frame_state.saved_projection_matrix modelview_matrix = other.per_frame_state.saved_modelview_matrix if projection_matrix is not None: projection_matrix = copy_pyopengl_matrix( projection_matrix) if modelview_matrix is not None: modelview_matrix = copy_pyopengl_matrix( modelview_matrix) self.per_frame_state.saved_projection_matrix = projection_matrix self.per_frame_state.saved_modelview_matrix = modelview_matrix pass # end of class _CoordsysHolder class SavedCoordsys(_CoordsysHolder): #070317 """ One of these can be told to save a static copy of the coordsys from any instance of a _CoordsysHolder subclass, or to save one from the current GL state, and then to make use of it in some of the same ways Highlightable can do. ###doc better """ def copy_from(self, other): #070328 moved the method body to superclass & renamed it there. #e Its fate here (both method & class existence) is undecided. # guess: a better structure is for a saved coordsys to be a *member* of class _CoordsysHolder, not a subclass. self.copy_saved_coordsys_from(other) pass # == printdraw = False # debug flag [same name as one in cad/src/testdraw.py] class Highlightable(_CoordsysHolder, DelegatingMixin, DragHandler_API, Selobj_API): #070317 split out superclass _CoordsysHolder #e rename to Button? make variant called Draggable? """ Highlightable(plain, highlighted = None, pressed_in = None, pressed_out = None) normally renders as plain (and delegates most things to it), but on mouseover, renders as plain plus highlight [#k or just highlight??]. ###doc more """ # WARNING: the abstract methods in superclass DragHandler_API will be inherited (if not overridden), # even if they are defined in the delegate. [in theory; unconfirmed.] This is good in this case. [061127 comment] #060722; # revised for exprs module, 061115 [not done] # note: uses super InstanceOrExpr rather than Widget2D so as not to prevent delegation of lbox attrs (like in Overlay) # args (which specify what it looks like in various states) plain = ArgOrOption(Widget2D) # Arg -> ArgOrOption 070304 -- but is it still required? it ought to be... but it's not.... ###e delegate = _self.plain # always use this one for lbox attrs, etc # Note that subclasses of Highlightable generally need to override plain, not delegate, # and also have to remember to override it with an Instance, not just an expr. # This is basically a flaw in using subclassing (or in our subclass interface, but it's not easily fixable here) # vs. delegation to normally-made Highlightables. [070326 comment] highlighted = ArgOrOption(Widget2D, plain) # fyi: leaving this out is useful for things that just want a glname to avoid mouseover stickiness # implem note: this kind of _self-referential dflt formula is not tested, but ought to work; # btw it might not need _self, not sure, but likely it does -- # that might depend on details of how Arg macro uses it ###k # these next args are really meant for Button -- maybe we split this into two variants, Button and Draggable pressed_in = ArgOrOption(Widget2D, or_Expr(_self.pressed, highlighted)) #e might be better to make it plain (or highlighted) but with an outline, or so...) pressed_out = ArgOrOption(Widget2D, or_Expr(_self.pressed, plain)) # ... good default for a Button, assuming we won't operate then -- but bad default for a draggable -- # but not only this, but everything about how to detect a "selobj" under mouse, should be changed for that [070213 comment] # options pressed = Option(Widget2D, None, doc = "if provided, pressed is the default for both pressed_in and pressed_out")#070224 sbar_text = Option(str, "") # mouseover text for statusbar #e on_enter, on_leave -- see comment below behavior = Option(Anything, doc = "an Instance whose on_press/on_drag/on_release* methods we use, unless overridden by specific options")#070316 on_press = Option(Action) on_drag = Option(Action) on_release = Option(Action, doc = "mouse-up action; can be overridden by on_release_in and/or on_release_out" ) # 070209 added this general release action, for when in or out doesn't matter on_release_in = Option(Action, on_release, doc = "mouse-up action for use if mouse is over highlighted object when it's released") on_release_out = Option(Action, on_release, doc = "mouse-up action for use if mouse is NOT over highlighted object when it's released") ###e should we add on_click, to be run at the same time as on_release but only if on_drag was never called? [070324 idea] on_doubleclick = Option(Action, # 070324 new feature doc = "mouse-down action for the 2nd click in a double click; on_release won't run for it") ###BUG (likely): on_release won't run, nor on_press, but on_drag probably will, if you drag before releasing that click! # (Unless Qt suppresses drag events in that situation -- unknown.###TEST) # But my guess is, most on_drag methods will fail in that case! ####FIX, here or in testmode or in selectMode cmenu_maker = Option(ModelObject) # object which should make a context menu, by our calling obj.make_selobj_cmenu_items if it exists # note: inherits projection Option from superclass _CoordsysHolder def _init_instance(self): super(Highlightable, self)._init_instance() # == transient_state set_default_attrs( self.transient_state, in_drag = False) # doc = "whether mouse is currently down (after a mousedown on self)" # Q 070210: would in_drag = State(...) be equivalent? # Guess: yes (but with more general access syntax) -- this is just an old form; not sure! ##k # note 070210: sometimes I've mistakenly thought that meant in_bareMotion [not a serious name-suggestion], # i.e. whether mouse is over self or not. We might need that, and/or action options to run when it changes, # perhaps called on_enter and on_leave. Right now I don't think we get notified about those events! ###e # note: set_default_attrs sets only the attrs which are not yet defined ###e should make an abbrev for that attr as HL.in_drag -- maybe use State macro for it? read only is ok, maybe good. ###e should add an accessible tracked attr for detecting whether we're over self, too. What to call it? # [061212 comments, also paraphrased near testexpr_9fx4] # some comments from pre-exprs-module, not reviewed: ## in_drag = False # necessary (hope this is soon enough) # some comments from now, 061115: # but we might like formulas (eg in args) to refer to _self.in_drag and have that delegate into this... # and we might like external stuff to see things like this, and of course to pass arb actions # (not all this style is fully designed, esp how to express actions on external state -- # i guess that state should have a name, then we have an action object, when run it has side effect to modify it # so no issue of that thing not knowing to run it, as there would be from a "formula contribution to an external lval"; # but from within here, the action is just a callable to call with whatever args it asks for, perhaps via formulae. # it could be a call_Expr to eval!) # == glpane_state set_default_attrs( self.glpane_state, glname = None) # glname, if we have one # allocate glname if necessary, and register self (or a new obj we make for that purpose #e) under glname # (kicking out prior registered obj if necessary) # [and be sure we define necessary methods in self or the new obj] glname_handler = self # self may not be the best object to register here, though it works for now glpane = self.env.glpane if self.glpane_state.glname is None or 'TRY ALLOCATING A NEW NAME EACH TIME 061120 958p': # allocate a new glname for the first time (specific to this ipath) glname = glpane.alloc_my_glselect_name( glname_handler) #bruce 080917 revised self.glpane_state.glname = glname else: # reuse old glname for new self if 0: # when we never reused glname for new self, we could do this: glname = glpane.alloc_my_glselect_name( glname_handler) self.glpane_state.glname = glname #e if we might never be drawn, we could optim by only doing this on demand else: # but now that we might be recreated and want to reuse the same glname for a new self, we have to do this: glname = self.glpane_state.glname recycle_glselect_name(self.env.glpane, glname, glname_handler) pass assert is_expr_Instance_or_None( self.plain ), "%r.plain must be an Instance or None, not %r" % (self, self.plain) # catch bugs in subclasses which override our formula for self.plain [070326] return # from _init_instance in Highlightable def draw(self): glpane = self.env.glpane self.save_coords_if_safe() if self.glname != self.glpane_state.glname: print "bug: in %r, self.glname %r != self.glpane_state.glname %r" % \ (self, self.glname, self.glpane_state.glname) #070213 -- since similar bug was seen for _index_counter in class World PushName(self.glname) try: draw_this = "<not yet set>" # for debug prints if self.transient_state.in_drag: if printdraw: print "pressed_out.draw", self draw_this = self.pressed_out #e actually this might depend on mouseover, or we might not draw anything then... # but this way, what we draw when mouse is over is a superset of what we draw in general, # easing eventual use of highlightables inside display lists. See other drawing done later when we're highlighted # (ie when mouse is over us)... [cmt revised 061115] # Note, 061115: we don't want to revise this to be the rule for self.delegate -- # we want to always delegate things like lbox attrs to self.plain, so our look is consistent. # But it might be useful to define at least one co-varying attr (self.whatwedraw?), and draw it here. ####e else: ## print "plain.draw", self draw_this = self.plain self.drawkid( draw_this) ## draw_this.draw() # split out draw_this, 070104 except: ##k someday this try/except might be unneeded due to drawkid print_compact_traceback("exception during pressed_out or plain draw, ignored: ")#061120 print "fyi: the object we wanted to draw when we got that exception was:", print "%r" % (draw_this,) pass # make sure we run the PopName PopName(self.glname) return def draw_in_abs_coords(self, glpane, color): """ #doc; called from GLPane using an API it specifies; see also run_OpenGL_in_local_coords for more general related feature """ # [this API comes from GLPane behavior: # - why does it pass color? historical: so we can just call our own draw method, with that arg (misguided even so??) # - what about coords? it has no way to know old ones, so we have no choice but to know or record them... # ] # # WARNING: This implem won't work when we can be inside a display list which is drawn in its own relative coords. # For latest info on what to do about that, see '061206 coordinate systems' on bruce's g5. # print "calling draw_in_abs_coords in", self # this does get called even when projection=True makes it seem to not work. # but mousing around over it does cause repeated draws, unlike when it works. Both as if it drew in wrong place. # Note: I'm guessing it's better to not call kid.draw() via self.drawkid( kid), in this method -- not sure. ###k [070210] self.begin_using_saved_coords() try: if self.transient_state.in_drag: if printdraw: print "pressed_in.draw", self self.pressed_in.draw() #e actually might depend on mouseover, or might not draw anything then... else: if printdraw: print "highlighted.draw", self self.highlighted.draw() finally: #061206 added try/finally as a precaution. ##e Future: maybe we should not reraise (or pass on) an exception here?? # GLPane's call is not well protected from an exception here, though it ought to be! self.end_using_saved_coords() return # from draw_in_abs_coords def __repr__THAT_CAUSES_INFRECUR(self): # this causes infrecur, apparently because self.sbar_text indirectly calls __repr__ (perhaps while reporting some bug??); # so I renamed it to disable it and rely on the super version. sbar_text = self.sbar_text or "" if sbar_text: sbar_text = " %r" % sbar_text return "<%s%s at %#x>" % (self.__class__.__name__, sbar_text, id(self)) ##e improve by merging in a super version ##e zap %#x ## [Highlightable.py:260] [ExprsMeta.py:250] [ExprsMeta.py:318] [ExprsMeta.py:366] [Exprs.py:184] [Highlightable.py:260] ... def mouseover_statusbar_message(self): # called in GLPane.set_selobj """ #doc [an optional method in NE1's "selobj interface"] """ ###e NEEDED: we need to pick up info from the mode about the hitpoint used to pick this selobj, # since we may also use it to determine sbar_text, or to determine what to offer in a cmenu # if one is requested at this point. (In the cmenu case, the point used to choose the selobj # is better to use than the current mousepoint, though ideally they would not differ.) [070205] # # Note: a test shows self.env.glpane.modkeys is set as expected here (to None, 'Shift', 'Control' or 'Shift+Control'), # but changing a modkey doesn't call this method again, as it would need to if the message we return # could depend on the modkeys. That is reasonably considered to be a ###BUG. [070224] return str(self.sbar_text) or "%r" % (self,) #e note: that str() won't be needed once the type-coercion in Option works def highlight_color_for_modkeys(self, modkeys): """ #doc; modkeys is e.g. "Shift+Control", taken from glpane.modkeys """ return green # KLUGE: The specific color we return doesn't matter, but it matters that it's not None, to GLPane -- # otherwise it sets selobj to None and draws no highlight for it. # (This color will be received by draw_in_abs_coords, but our implem of that ignores it.) ###@@@ got to here, roughly, in a complete review of porting this code from the old system into the exprs module def selobj_still_ok(self, glpane): ###e needs to compare glpane.part to something in selobj [i.e. self, i guess? 061120 Q], # and worry whether selobj is killed, current, etc # (it might make sense to see if it's created by current code, too; # but this might be too strict: self.__class__ is Highlightable ) # actually it ought to be ok for now: res = self.__class__ is Highlightable # i.e. we didn't reload this module since self was created if res: #061120 see if this helps -- do we still own this glname? our_selobj = self glname = self.glname ## owner = selobj_for_glname(glname) owner = glpane.assy.object_for_glselect_name(glname) #bruce 080917 revised if owner is not our_selobj: res = False # owner might be None, in theory, but is probably a replacement of self at same ipath # do debug prints print "%r no longer owns glname %r, instead %r does" % (self, glname, owner) # [perhaps never seen as of 061121] our_ipath = self.ipath owner_ipath = getattr(owner, 'ipath', '<missing>') if our_ipath != owner_ipath: # [perhaps never seen as of 061121] print "WARNING: ipath for that glname also changed, from %r to %r" % (our_ipath, owner_ipath) pass pass # MORE IS PROBABLY NEEDED HERE: that check above is about whether this selobj got replaced locally; # the comments in the calling code are about whether it's no longer being drawn in the current frame; # I think both issues are valid and need addressing in this code or it'll probably cause bugs. [061120 comment] ###BUG import foundation.env as env if not res and env.debug(): print "debug: selobj_still_ok is false for %r" % self ###@@@ return res # I forgot this line, and it took me a couple hours to debug that problem! Ugh. # Caller now prints a warning if it's None. ### [probably obs cmt:] grabbed from Button, maybe not yet fixed for here altkey = False # [070224] a new public Instance attr, boolean, meaningful only during press/drag/release -- # True iff alt/option/middlebutton was down when drag started. WARNING: NOT CHANGE TRACKED. # (Note: the code here does not enforce its not changing during a drag, # but I think glpane.fix_buttons does.) _glpane_button = None # private helper attr for altkey def _update_altkey(self): """ [private helper method for public read-only Instance attr self.altkey] """ self._glpane_button = self.env.glpane.button or self._glpane_button # persistence needed to handle None in ReleasedOn self.altkey = (self._glpane_button == 'MMB') return def leftClick(self, point, event, mode): # print "HL leftClick: glpane.button = %r" % (self.env.glpane.button,) # 'MMB' or 'LMB' self._update_altkey() # Note: it's probably the case that glpane.modkeys is one of None, 'Shift', 'Control' or 'Shift+Control', # in this and in other event methods, # but that as of 070224 this is never called when Option/Alt key (or middle mouse button) is pressed. ## if 1: ## print_compact_stack("fyi: on_press called: ")#061218 debug hl sync bug # print "mode._drag_handler_gl_event_info = %r" % (mode._drag_handler_gl_event_info,) # farQ, hitpoint, wX, wY, depth, farZ -- for use in gluUnProject in local coords (see also run_OpenGL_in_local_coords) # note: point == hitpoint. # point is in global coords, not ours; sometimes useful, but save enough info to compute the local version too. # But don't precompute it -- let the action ask for it if desired. That optim doesn't matter for this leftClick method, # but it might matter for the drag methods which use the same API to pass optional info to their actions. self.transient_state.in_drag = True self.inval(mode) #k needed? glpane_bindings = dict( _leftClick_global_point = point, _leftClick_gl_event_info = mode._drag_handler_gl_event_info ) # WARNING: the keys in that dict will be set as attrs in the main GLPane object. self._do_action('on_press', glpane_bindings = glpane_bindings ) mode.update_selobj(event) #061120 to see if it fixes bugs (see discussion in comments) self.inval(mode) #k needed? (done in two places per method, guess is neither is needed) return self # in role of drag_handler def DraggedOn(self, event, mode): # print "HL DraggedOn: glpane.button = %r" % (self.env.glpane.button,) # 'MMB' or 'LMB' self._update_altkey() # obs cmt: only ok for Button so far #e might need better args (the mouseray, as two points?) - or get by callback # print "draggedon called, need to update_selobj, current selobj %r" % mode.o.selobj # retested this 061204 in testexpr_10c; it gets called, but only during drag (motion when mouse is down); # the update_selobj is safe, won't trigger redraw unless selobj has changed. will when it does (off or on the object); # didn't test highlight behavior (tho it works in other tests), since _10c doesn't use it. glpane_bindings = dict( _kluge_drag_event = event, _kluge_drag_mode = mode ) #061207 self._do_action('on_drag', motion = True, glpane_bindings = glpane_bindings) mode.update_selobj(event) #e someday, optim by passing a flag, which says "don't do glselect or change stencil buffer if we go off of it", # valid if no other objects are highlightable during this drag (typical for buttons). Can't do that yet, # since current GLPane code has to fully redraw just to clear the highlight, and it clears stencil buffer then too. # for dnd-like moving draggables, we'll have to modify the highlighting alg so the right kinds of things highlight # during a drag (different than what highlights during baremotion). Or we might decide that this routine has to # call back to the env, to do highlighting of the kind it wants [do, or provide code to do as needed??], # since only this object knows what kind that is. return def ReleasedOn(self, selobj, event, mode): ### may need better args # print "HL ReleasedOn: glpane.button = %r" % (self.env.glpane.button,) # always None. self._update_altkey() ### written as if for Button, might not make sense for draggables self.transient_state.in_drag = False self.inval(mode) #k needed? (done in two places per method, guess is neither is needed) our_selobj = self #e someday this might be some other object created by self to act as the selobj try: # KLUGE 061116, handle case of us being replaced (instances remade) # between the mode or glpane seeing the selobj and us testing whether it's us if selobj and (selobj is not our_selobj) and getattr(selobj,'ipath','nope') == our_selobj.ipath: assert our_selobj.glname == selobj.glname, "glnames differ" # should be the same, since stored in glpane state at ipath print "kluge, fyi: pretending old selobj %r is our_selobj (self) %r" % (selobj, our_selobj) # NOTE: our_selobj (self) is OLDER than the "old selobj" (selobj) passed to us! # Evidence: the sernos in this print: ## kluge, fyi: pretending old selobj <Highlightable#2571(i) at 0x10982b30> ## is our_selobj (self) <Highlightable#2462(i) at 0x1092bad0> # I guess that's because the one first seen by mouseover was saved as selobj in glpane; # then it was replaced by one that drew highlighting; # then by the time this runs it was replaced again; # but WE ARE NOT THE LATEST ONE AT THAT IPATH, # but rather, the first saved one! # THIS COULD CAUSE BUGS if we are replaced on purpose with one which does different things! # But that's not supposed to happen, so rather than finding the latest one and having it do the work # (which is possible in theory -- look it up by glname), # I'll just ignore this issue, leave in the debug print, and expect the print # (and even the need for this kluge check code) to go away as soon as I optim # by not remaking instances on every redraw. [061116] selobj = our_selobj pass except: print_compact_traceback( "bug: exception in ReleasedOn ignored: ") pass if selobj is our_selobj: self._do_action('on_release_in') else: self._do_action('on_release_out') ## mode.update_selobj(event) #k not sure if needed -- if it is, we'll need the 'event' arg ## printnim("does ReleasedOn and also leftClick need the event arg so it can update_selobj so some bugs can be fixed??") ###### ##bug guess 061120 - i think it does. try it. any other files affected?? if maybe for leftClick, rename it PressedOn?? ###BUG? don't know if it matters as of 061121; was doing it since before bugs finally got fixed. # Maybe selectMode did it before calling us, btw. #k #e need update? mode.update_selobj(event) #061120 to see if it fixes bugs (see discussion in comments) self.inval(mode) #k needed? (done in two places per method, guess is neither is needed) return def leftDouble(self, event, graphicsMode): # print "fyi: Highlightable %r got leftDouble" % self # Note: if something (this code, or its on_doubleclick option) # decides to do on_press sometimes, it ought to reset the flag graphicsMode.ignore_next_leftUp_event # (assuming graphicsMode is indeed the graphicsMode, as I think it probably is & should be -- bruce 071022) # which was just set by testmode.leftDouble, which otherwise prevents calling self.ReleasedOn. # But if that something is the contents of on_doubleclick, how is that possible?!? # The only solution I can think of is for on_drag and on_release to get replaced by on_double_drag and # on_double_release in those cases (and to rename on_doubleclick to on_double_click).Hmm.... ###REVIEW SOON # # Note: this is called on the press of the 2nd click in a double click (when self is the drag_handler), # not on the release. # # Note: I don't know whether it's guaranteed that no significant mouse motion occurred during the doubleclick # (or even that the two clicks occurred in the same Qt widget -- btw, when they didn't, it can be due to mouse motion, # or to a widget being hidden or shown). self._do_action('on_doubleclick') #k is this all we need?? what about update_selobj? inval/gl_update? return def _do_action(self, name, motion = False, glpane_bindings = {}): """ [private, should only be called with one of our action-option names, like on_press or on_release_in (not on_release)] Do all actions defined for name: those from self.behavior, and those from our own options (in that order). @note: prior to 080129, an action option on self would override an action defined in self.behavior. Now it post-extends it instead. AFAIK this never mattered until now. """ ## if not motion: ## # debug print temporarily reenabled for sake of DnaSegment_EditCommand.py ## # since this is not getting called for on_release, don't know why ## # [bruce 080129] ## print "_do_action for %r in %r" % (name, self) assert name.startswith('on_') actions = [] # action from self.behavior behavior = self.behavior if behavior: # note: behavior shouldn't be another Highlightable, but a DragBehavior action = getattr(behavior, name, None) ## if behavior: ## if not action: ## print "%r: behavior %r but no action for %r" % (self, behavior, name) ## else: ## print "%r: behavior %r has action %r for %r" % (self, behavior, action, name) if action: actions.append(action) # action from an option of self action = getattr(self, name) # will always be defined, since Option will give it a default value if necessary ###BUG 061205: seems to not be defined in a certain bug where I supplied it a formula whose computing has an error! # and as a result it gets delegated. Guess: the exception makes it seem missing to the delegation code -- # because the exception also happens to be an AttributeError! (It does, in that bug: formula was _self.on_drag_bg # and that attr was not defined in that object.) # # ... Unfortunately I can't think of a trivial fix to prevent delegation... # I guess I could manually grab the class property and call its __get__ protocol... not too hard, try it sometime. ##e # Ah, found one: for an error in the recompute like that, turn it into my own exception (in lvals.py) # so it can't imitate another one -- at least not an AttributeError which causes delegation! # Ok, that's coded (for AttributeError only) and does prevent that error from causing delegation, makes it easier # to debug. Good. Not much need to try the other fix above. ###e should be None or a callable supplied to the expr, for now; later will be None or an Action if action: actions.append(action) del action # do the actions if actions: if glpane_bindings: # new feature 061205 - dynamic bindings of specific attrnames in glpane glpane = self.env.glpane for k,v in glpane_bindings.iteritems(): # these k should only be hardcoded in this class, not caller-supplied assert not hasattr(glpane, k) #e might revise to let it be a default value in the class, or more setattr(glpane, k, v) #e or could call glpane.somedict.update(glpane_bindings) -- maybe more controlled if it keeps them in a dict try: for action in actions: action() finally: if glpane_bindings: for k in glpane_bindings.iterkeys(): delattr(glpane, k) return def inval(self, mode): ###k needed?? """ we might look different now; make sure display lists that might contain us are remade [stub], and glpanes are updated """ ### 061120 guess: prob not needed in theory, and de-optim, but conservative, and otherwise harmless. # the fact that it comes before the side effect routines in its callers # ought to be ok unless they do recursive event processing. still, why not do it after instead? not sure... ##e # plan: try doing it after as last resort bugfix; otoh if bugs gone, try never doing it. ## exprs_globals.havelist = False ## mode.o.gl_update() self.KLUGE_gl_update() return def make_selobj_cmenu_items(self, menu_spec): # 070204 new feature, experimental """ Add self-specific context menu items to [mutable] <menu_spec> list when self is the selobj. [For more examples, see this method as implemented in chem.py, jigs*.py in cad/src.] """ obj = self.cmenu_maker # might be None or a ModelObject method = getattr(obj, 'make_selobj_cmenu_items', None) if 'debug070314': item = ('debug: self is %r' % self, noop, 'disabled') menu_spec.append(item) if obj is not None and obj is not self: item = ('debug: cmenu_maker is %r' % (obj,), noop, 'disabled') menu_spec.append(item) pass if method is not None: try: method(menu_spec, self) # 070205 revised API: pass self, so method can ask it about the event, e.g. current_event_mousepoint # (###e CLEANUP NEEDED: this should be cleaned up so most cmenu methods don't need to accept and ignore that arg -- # maybe it should be stored in dynenv, eg glpane, or maybe make current_event_mousepoint itself dynenv-accessible.) except: print "bah" ###e traceback print_compact_traceback("exception seen by selobj %r in %r.make_selobj_cmenu_items(): " % (self, obj) ) else: # remove soon, or improve -- classname?? item = ('no cmenu provided by this selobj', noop, 'disabled') menu_spec.append(item) return pass # end of class Highlightable Button = Highlightable # [maybe this should be deprecated, but it's still in use, and maybe it should instead be a variant subclass] # == class _UNKNOWN_SELOBJ_class(Selobj_API): #061218 """ [private helper, for a kluge] """ def handles_updates(self): #k guessing this one might be needed return True # these methods were found by experiment to be needed def selobj_still_ok(self, glpane): return (self is getattr(glpane.graphicsMode, 'UNKNOWN_SELOBJ')) # goal: True in the same graphicsMode instance that we were created for, False otherwise highlight_color_for_modkeys = noop #e will it need to be a method which returns a color? I doubt it. leftClick = noop # this is in case we didn't find one that's needed: def __getattr__(self, attr): # in class _UNKNOWN_SELOBJ_class if attr.startswith("__"): raise AttributeError, attr if debug_flags.atom_debug:### print "_UNKNOWN_SELOBJ_class returns noop for attr %r" % attr setattr(self, attr, noop) # optim return noop # fake bound method def __str__(self): #bruce 081211 return "UNKNOWN_SELOBJ" # we might need methods for other MouseSensor_interface methods: # (note, MouseSensor_interface is a proposed rename of part of Selobj_API) # draw_in_abs_coords # leftClick # mouseover_statusbar_message # highlight_color_for_modkeys # selobj_still_ok # etc pass def _setup_UNKNOWN_SELOBJ_on_graphicsMode(graphicsMode): #061218, revised 071010 """ [private helper, for a kluge -- see comment where called] """ # The only call as of 071010 is in exprs/test.py which sets it on testmode, and says: # fixes "highlight sync bug" in which click on checkbox, then rapid motion away from it, # then click again, could falsely click the same checkbox twice. # I can't recall exactly how that fix worked. About how glpane.selobj ever becomes equal to this, # there is code in SelectAtoms_GraphicsMode and SelectChunks_GraphicsMode # which does that, in update_selobj. # TODO: document how this works sometime, and figure out whether it should be set up # per-Command or per-graphicsMode. Either way we'll need a class constant to request it, # since right now nothing can set it up except in testmode. For now I'll treat it as per-command # since that seems best regarding the uniqueness... but this change is NIM. [bruce 071010] # bruce 071017 commenting out this isinstance assert, to help chop up the # import cycle graph, though it's legitimate in theory. A better fix would # be to split GraphicsMode into an API module (from which we'd import here) # and the implementation of basicGraphicsMode and GraphicsMode (which would # import a lot of other things). # ## from GraphicsMode import anyGraphicsMode # ok? ## assert isinstance(graphicsMode, anyGraphicsMode) # # bruce 071028 reinstating it in a harmless form: from command_support.GraphicsMode_API import GraphicsMode_interface assert isinstance(graphicsMode, GraphicsMode_interface) if not hasattr(graphicsMode, 'UNKNOWN_SELOBJ'): # note: this means each graphicsMode ends up with a unique UNKNOWN_SELOBJ, # which is considered still ok only within the same graphicsMode, due to the # comparison done in _UNKNOWN_SELOBJ_class.selobj_still_ok. # See comments in update_selobj routines about graphicsMode vs currentCommand for this # uniqueness and/or decision to use it -- it's just a guess to use graphicsMode for both. # [bruce 071010] graphicsMode.UNKNOWN_SELOBJ = _UNKNOWN_SELOBJ_class() return # == class BackgroundObject(DelegatingInstanceOrExpr): #070322 [renamed from _BackgroundObject, and moved here from demo_drag.py, 070323] """ ###doc. One way to describe it: analogous to DrawInCorner, but draws "normally but into the role of receiving events for clicks on the background" """ delegate = Arg(Highlightable, doc = "a Highlightable (or something that delegates to one) which can process background drag events") hide = Option(bool, False, doc = "if true, don't draw delegate, but still let it receive background events") def draw(self): if not self.hide: self.drawkid(self._delegate) else: self._delegate.save_coords() ###KLUGE, unsafe in general, though correct when it's a Highlightable -- # but without this, we get this debug print on every draw (for obvious reasons): ## ;;in <Highlightable#44572(i)>, saved modelview_matrix is None, not using it graphicsMode = self.env.glpane.graphicsMode # kluge?? maybe not, not sure command = graphicsMode.command # [seems best to go through graphicsMode to get to command -- bruce 071010] # tell event handlers that run after the present rendered frame to send press/drag/release events on empty space # to self._delegate command._background_object = self._delegate # see testmode.py comments for doc of _background_object (#doc here later) return pass # end of class BackgroundObject # fyi, here are some slightly older comments about how to solve the problem which is now solved by BackgroundObject() -- # the plan they describe is almost the same as what I did, but the part about "the dynenv binding for event-handler obj # at the time" is not part of what I did yet. # # Q: What about empty space events? # A: if done the same way, something needs to "draw empty space" so it can see dynenv event binding at the time # and know what testmode should send those events to. Maybe related to "drawing the entire model"?? # Sounds like a kluge, but otherwise, something needs to register itself with testmode as the recipient of those events. # In fact, those are the same: "draw empty space" can work by doing exactly that with the dynenv binding for event-handler obj # at the time. Not sure if this generalizes to anything else... anyway, drawing the world can do this if we ask it to, maybe... # not sure that's a good idea, what if we draw it twice? anyway, shouldn't it have more than one component we can draw? # model, different parts, MT, etc... maybe we can add another one for empty space. # [end of older comments] # end
NanoCAD-master
cad/src/exprs/Highlightable.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ demo_ui.py - try out a more CAD-like UI organization @author: Bruce @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. """ from exprs.toolbars import MainToolbar from exprs.command_registry import find_or_make_global_command_registry from utilities.constants import pink from utilities.prefs_constants import UPPER_LEFT, UPPER_RIGHT from exprs.Exprs import list_Expr from exprs.If_expr import If from exprs.widget2d import Stub from exprs.Rect import Rect from exprs.TextRect import TextRect from exprs.world import World from exprs.Overlay import Overlay from exprs.Column import SimpleColumn, SimpleRow from exprs.projection import DrawInCorner from exprs.Center import Top from exprs.attr_decl_macros import State, Instance from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.__Symbols__ import _self from exprs.demo_MT import MT_try2 testexpr_34 = Rect(0.7,0.3,pink) # just to make sure the imports from here are working -- replace it with a real test when we have one # ToolRuns #e rename-- or maybe those classes will be derived from Tool classes somehow class ToolRun(DelegatingInstanceOrExpr): # what is the super? it has several distinct parts we draw, but when do we draw "the whole thing" -- when editing one??? property_manager = None ### has to be None! not Spacer(0) ## None -- one of these Spacers might be needed; # guess1: Overlay/Row arg is not None but its delegate is! # guess2: bug in DrawInCorner(None) # guess3: Top(propmgr) graphics_area_topright_buttons = None ## Spacer(0) ## None pass class DefaultToolRun(ToolRun): """An internal pseudo-ToolRun that is always active, and controls the property manager display and other things normally controlled by the active tool or subtool when they exist (eg Done/Cancel buttons in graphics area). In general it just sets them to invisible stubs. """ pass # term/ui guesses until i learn otherwise: # - Tool is the classname of the thing whose tool button you hit to get into, # and which has its own prop mgr or inherits one from a parent tool # - A Tool Instance sits there whether or not the tool is active; it can supply things like a prefs pane, tool button, etc; # typically there's one long-lived instance for each Command eg Sketch or sub-command eg Line # - each time a Tool is activated it produces a new ToolRun... # - there is a stack of currently active toolruns, each one the parent of the next # (usual depth one or two, plus an outer constant one with no prop mgr, user-invisible) from exprs.debug_exprs import DebugPrintAttrs ###e move up, or into basic; rename to more memorable name (maybe just Debug?) (add DebugDraw?) #e set up a Sketch tool, which has a main button with a Sketch PM and for now has all the Sketch Entities we know about, # and later can be told to have a specific subset of them (if they are found) and an "other" item for access to more (incl custom ones). Tool = Stub class SketchTool(Tool): #e move to demo_sketch? "#doc" # it has a main command or PM # - default PM for subcommands without their own PM # - PM you see if you select a sketch for editing # - it might have some parts of this PM available when adding a specific element to the sketch, too # - in general, a PM has a bunch of possible groups, but each one has a condition for being shown. # and some of them exist on more than one PM. So a PM is an expr made of PMGroup exprs... # we could make one from a list of field names & types, but in general it's not made that way. # and an ability to host subcommands # - it makes a new Sketch for them if necessary; # - or like any command, since it needs a Sketch, maybe one is selected when it's entered; # but unlike some args, if none is selected user is not prompted for one - but is prompted for a ref plane or surface; # this is because Sketch has an Arg(RefPlaneOrSurface)... or special code to look for Args it doesn't have from the UI... # sort of like an Arg default expr, but not really the same thing. And maybe it's on a StateArg. # (If it's entered via Insert Line, this ref plane prompting happens too (V4d p15), even though PM title is Insert Line... hmm. # I can see some sense in that. All PMs have a message area; conditions determine whether it's active, # and if it is, it acts like a subcommand of its own, since the click effect depends on its being there, I think.) # # And maybe this special code is not on a Sketch modelobj, but on the MakeSketch command. And maybe SketchTool == MakeSketch? # But don't you get into it if you select an existing sketch in the right way? # It's a "tool for making, editing, inspecting sketches" which contains a lot of commands and other things. # You might get into it in various ways, eg a cmenu item on a sketch's MT node or on a visible sketch element. # SketchTool seems right. # # and a way to filter available commands to find subcommands to put on its flyout toolbar as subtools # which means it has a flyout toolbar, btw; and more fundamentally it has the list of items on it (since it has cmenu of those too) pass class main_ui_layout(DelegatingInstanceOrExpr): #e rename? is it not only the ui, but the entire app? (selection, files, etc) #e merge in the App obj from test.py, and the _recent_tests system in some form? # args (none yet) # internal state - permanent ###e note: when we reload and remake this instance, we'd prefer it if the world state stayed unchanged (as i presume it does) # but if the default_tool instance and toolstack state got remade. The lack of the latter has been confusing me # since changes to ui code aren't working. I think this is a difference between a ui and operations layer (should change) # vs model data layer (should not change even tho the op methods on it can change). So when I can put these things into layers # (not only State, but even Instance or attrs within them) and make those sensitive to reload, that will help. # In the meantime -- if I could kluge Instance and State to take an option to control this # (like index = exprs_globals.reload_counter) # it might help.... #####TRYIT SOMETIME, and BE CAREFUL UNTIL I DO. world = Instance(World()) default_tool = Instance(DefaultToolRun()) # internal state - varying toolstack = State(list_Expr, [default_tool]) # always has at least one tool on it; a stack of Instances not exprs # maybe the better term for this is something like command & subcommand current_tool = toolstack[-1] # last tool on the stack is current; exiting it will pop the stack (Instance not expr) ##e (add a type-assertion (as opposed to type-coercion) primitive, so I can say "this is an Instance" in the code?) # NOTE: this is not strictly speaking a tool, but ONE RUN of a tool. That might be important enough to rename it for, # to ToolRun or maybe ActiveTool or RunningTool or ToolInUse or ToolBeingUsed... # [but note, obj might remain around on history or in Undo stack, even when no longer being used], # since we also have to deal with Tools in the sense of Tool Run Producers, eg toolbuttons. ###e # parts of the appearance registry = find_or_make_global_command_registry() ## None ###STUB, will fail -- ## AttributeError: 'NoneType' object has no attribute 'command_for_toolname' toolstack_ref = None ###STUB toolbar = Instance( MainToolbar( registry, ["Features", "Build", "Sketch"], toolstack_ref ) ) #e arg order? ###e args/opts for what tools to show -- maybe their cmdnames & it loads them from elsewhere #e add row of tool buttons, and flyout toolbar; use ChoiceRow?? the things should probably look pressed... # they might need cmenus (find out what the deal is with the cmenus i see in the ui mockup - related to flyouts? # yes, it's like this: main tools have cmenus with subtools, and if you pick one, main tool and its subtool both look pressed # I'll need new specialized controls.py classes for these; new super Control for all kinds of controls?? (not sure why...) propmgr = SimpleColumn( TextRect("(property manager)"), #e possibly to become a tab control tab DebugPrintAttrs(current_tool.property_manager) # must be None if we don't want one visible; otherwise an Instance ###BUG: DebugPrintAttrs shows that it's a spacer -- I guess IorE turns None into one when it instantiates? Make it a false one?? ) mt = SimpleColumn( TextRect("(model tree)"), #e possibly to become a tab control tab, but only when we're in the left channel MT_try2(world) #e rename to "Feature Manager" ?? ##e soon, MT should be not on whole world but on model or cur. part, a specific obj in the world ) graphics_area = _self.world ##e ditto for what we show here, except it might not be the exact same object, and it will really be shown in a way # that depends on both the current display style and the current tool (command & subcommand) graphics_area_topright_buttons = current_tool.graphics_area_topright_buttons # overall appearance delegate = Overlay( # stuff in the corners -- note, these don't use the corner constants for standalone tests like PM_CORNER DrawInCorner(corner = UPPER_LEFT)( SimpleColumn( toolbar, #e add tab control SimpleRow( If( current_tool.property_manager, Top(propmgr), None), #k None?? prob ok now, see demo_MT comment 070302 ###k Top(mt)), #e actually we'd then put a splitter & glpane-like-thing... #e anything just below the propmgr? )), DrawInCorner(corner = UPPER_RIGHT)( ##e of graphics area, not entire screen... graphics_area_topright_buttons ### WRONG, these should go under the main toolbar area on the right # (but we don't yet have any 2dwidgets which expand to fill the available space, except DrawInCorner of entire screen) # (this won't matter once the toolbar is done entirely in Qt, so we don't need to correct it for now) ), #e other corners? "... an area (view) on the right side # of the main window for accessing the part library, on-line documentation, etc" # the main graphics area #e [this too ought to go under the toolbar and to the right of the propmgr, but that can wait until they're fully in Qt] graphics_area ) pass testexpr_34a = main_ui_layout() """ somehow encode the contents: Features: ? Build: Molecule DNA DNA Origami Carbon Nanotube [hmm, what about B-N, and graphene sheet] Heterojunction [hmm, doesn't say of what] Sketch: (Dimension) (On surface) Line """ # end
NanoCAD-master
cad/src/exprs/demo_ui.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ intern_ipath.py $Id$ For now, this module doesn't officially support reload, though doing so won't erase its database -- since it might mix interned values with different intern-mappings into one database. So basic.py doesn't try to reload it. """ # This may be refiled or renamed, since later we'll also intern exprs, # and maybe not the same exact way. Maybe there can be interning objects of which these globals become members # and two public ones for exprs and ipaths, and some using on-disk dbs too. try: _uninterned_from_interned except: # interning data is preserved across reloads [however, for now this module doesn't officially support reload at all] _uninterned_from_interned = {} _interned_from_uninterned = {} _next_interned_ipath = -101 assert len(_uninterned_from_interned) == len(_interned_from_uninterned) == (-101 - _next_interned_ipath) # The map from uninterned to interned will be # int (always nonnegative in a fully uninterned ipath) -> itself # string or None or boolean -> itself # tuple -> intern the components, then allocate a negative int (less than -100); dict key is tuple of 0 or more ints and strings # # The inverse map is: # negative int -> through the dict # positive int or string or None or boolean -> itself # # Client code is free to mix uninterned and interned ipaths at will. [##doc this publicly] # # (The only overlap in the set of legal values comes from ipaths whose uninterned and interned forms are the same, # so this is unambiguous. To ignore the issue of overlap when wondering if an ipath is interned or not when it # could be either, think of strings and nonneg ints and None as "already interned".) # # One way this interning strategy could fail is if the common parts of ipaths in the form of (first, rest) tuple-linked-lists # (innermost path component first) tend to be long sections of innermost components. Nothing will seem to be in common if the # outermost components are unique. # == #e the set of functions defined here (as an API into this module) may not be well-chosen. def is_interned(ipath): "is ipath a legal interned ipath value? True if yes, False if no, exception if illegal as uninterned or interned ipath." if type(ipath) == type(0): if not (ipath < -100 or ipath >= 0): print "ERROR: this int is not allowed as an ipath:",ipath # not an assert in case someone uses -1 -- we'll change spec if so return True # true either way: < -100 is an interned tuple, >= 0 is an interned int if type(ipath) in (str, bool): return True if ipath is None: return True if type(ipath) == type(()): return False # in this case we don't bother checking element legality -- it'll happen if caller goes on to intern it assert 0, "wrong type for ipath, whether or not interned; object is %r" % (ipath,) pass def _find_or_make_interned_ipath(ipath): "assume it's an uninterned tuple, but with all interned parts -- maybe not checked!" if 'check for now, remove when works': assert type(ipath) == type(()) for elt in ipath: assert is_interned(elt) # find try: return _interned_from_uninterned[ ipath] except KeyError: pass # make global _next_interned_ipath interned = _next_interned_ipath _next_interned_ipath -= 1 # note the sign -- they grow down _uninterned_from_interned[ interned] = ipath _interned_from_uninterned[ ipath] = interned return interned def intern_ipath(ipath): """Change ipath (hashable python data made of tuples, strings, ints, bools) into something shorter, but just as unique, which can't imitate an original (uninterned) one. To do this, use private knowledge about which ints and strings can be present in an original one. Be idempotent if ipath is already interned. """ if is_interned(ipath): return ipath assert type(ipath) == type(()) parts = map(intern_ipath, ipath) ipath = tuple(parts) return _find_or_make_interned_ipath(ipath) # end
NanoCAD-master
cad/src/exprs/intern_ipath.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ $Id$ """ from utilities.constants import white from exprs.attr_decl_macros import Instance, Option from exprs.transforms import Translate from exprs.Center import Center from exprs.ExprsConstants import StateRef, Vector from exprs.ExprsConstants import Point, Drawable from exprs.ExprsConstants import ORIGIN, DX ##,DY from exprs.Highlightable import Highlightable from exprs.Rect import Rect from exprs.Exprs import tuple_Expr from exprs.__Symbols__ import _self from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.DragBehavior_AlongCircle import DragBehavior_AlongCircle from exprs.Set import Action class DraggableHandle_AlongCircle(DelegatingInstanceOrExpr): """ A kind of draggable handle which can be dragged along a line to change the value of a single floating point parameter (representing position along the line, using a scale and origin determined by our arguments). ### TODO: add epydoc parameters to this docstring? not sure that will work for a class! Maybe we need to synthesize those (from the doc options below) into a fake __init__ method for its sake?? """ # == args and options # options for appearance of handle appearance = Option( Drawable, Center(Rect(0.2, 0.2, white)), doc = "appearance, when not highlighted") appearance_highlighted = Option( Drawable, appearance, doc = "appearance, when highlighted") sbar_text = Option(str, "draggable handle along circle", doc = "statusbar text on mouseover") # state variable controlled by dragging rotationDistanceRef = Option(StateRef, doc = "stateref to a dragged disctance variable") # action options, for Highlightable to do after the ones that come from # DragBehavior_AlongLine [new feature of this and Highlightable, 080129] on_press = Option(Action) on_drag = Option(Action) on_release = Option(Action) on_release_in = Option(Action, on_release) on_release_out = Option(Action, on_release) on_doubleclick = Option(Action) #origin of the handle itself origin = Option( Point, ORIGIN) # Center of the circle whose perimeter serves as a path along which to # drag center = Option( Point, ORIGIN) #Axis of the circle. axis = Option( Vector, DX, doc = "vector giving direction and scale") #radius Vector radiusVector = Option( Vector, DX, doc = "vector giving direction and scale") #angle range for the rotation range_for_rotation = Option(tuple_Expr, None, doc = "range limit of angle (tuple)") # == internal instances and formulae (modified from test_statearray_3.py) _drag_handler = Instance( DragBehavior_AlongCircle( _self._delegate, rotationDistanceRef, origin, center, axis, radiusVector, range_for_rotation = range_for_rotation)) #QUESTION: Should the 'RotateTranslate' transform from exprs.transforms be #used here? -- Ninad 2008-02-13 delegate = \ Highlightable( Translate( appearance, _drag_handler._rotation #k ok?? only if that thing hangs around even in between drags, i guess! #e #k not sure if this code-commoning is good, but it's tempting. hmm. ), highlighted = Translate( appearance_highlighted, _drag_handler._rotation ), sbar_text = sbar_text, behavior = _drag_handler, on_press = _self.on_press, on_drag = _self.on_drag, # (note: no need to pass on_release) on_release_in = _self.on_release_in, on_release_out = _self.on_release_out, on_doubleclick = _self.on_doubleclick, ) pass # end of class
NanoCAD-master
cad/src/exprs/DraggableHandle_AlongCircle.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ statearray.py @author: bruce @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. """ ###e still UNFINISHED in some ways, the worst being that our elements are staterefs # (see StateArrayRefs_getitem_as_stateref, # and ###BUG comment in test_statearray.py or related file, 070312) -- # this is now renamed a feature of StateArrayRefs rather than a bug of StateArray. from exprs.lvals import LvalForState, LvalDict2 from exprs.Exprs import call_Expr from exprs.widget2d import Stub from exprs.attr_decl_macros import State from exprs.ExprsConstants import StubType from exprs.__Symbols__ import _self, _E_ATTR # == # try 1 - works fine, but returns an array of StateRefs to its internal state elements, not lvalue-like state elements. # This might be useful, and it works and is tested, so rather than altering it and its test code, # I'll rename it to StateArrayRefs, and keep it around. # Later I'll write the real StateArray and see if that's indeed easier to use, and/or more efficient, or whatever. StateArrayRefs_type = StubType # rename to just StateArrayRefs if we can... def StateArrayRefs(type_expr, dfltval_expr, **kws): #e refile? """An array (expandable, arbitrarily indexed -- really a dictionary) of individually tracked/resettable state variables -- accessed as individual StateRefs to the variables. Usage: in a class definition that uses ExprsMeta, attr = StateArrayRefs( type_expr, dfltval_expr ) creates an attribute in each Instance which is effectively a dictionary of individually change/usage-tracked values, each coerced to type_expr [nim] (which can't yet depend on the dictionary index ###FIX), and each set to the value of dfltval_expr if it is accessed before it's first set. Note: dfltval_expr is evaluated without usage tracking; it is not yet decided whether it's evaluated only once (and if so when) or each time it's needed (the latter is more useful, but less efficient in many cases). There is not yet any way for dfltval_expr to depend on the dictionary index. ###FIX ###e There is not yet a way to control the possible or actual dictionary indices, or to provide an initial default value for the array as a whole (it's always {}). See also _CK_ and _CV_ rules, which provide read-only versions of those abilities. A combo of a _CK_/_CV_ interface to a StateArray could, for now, do much of what a _CK_-like feature in StateArray should do, though much more clumsily. In my first use of this I said "i want an arg for the index set... maybe even the initial set, or total set, so i can iter over it..." [NOTE: at least one dictlike class has that feature - review the ones in py_utils, see what _CK_ uses] ###e there may not yet be a way to delete an element (effectively resetting it to the value of dfltval_expr, computed somewhen). ###e there is not yet an unambiguous record of which elements are present or not in the array. ###e There is not yet a way to subscribe to updates of the set of defined array element indices, nor to updates of all changes to the entire set of values, let alone the same features for specific subsets, defined by index preds or sets. ###e There is not yet an efficient way to invalidate a range of indices at once (letting smart-enoguh subscribers receive just one summary inval). ###e There is not yet a way for some of the array to be set to a virtual array (e.g. a view of part of another array or set). See also: MapListToExpr, ArgList [nim], InstanceDict [nim], StateArg [nim]. """ #e should change to descriptor class... [why is that not easier than it is?] #e implem of type_expr coercion: depending on type & options, wrap with glue code when set, or coerce in simple way when set #e options: doc, debug_name #e somehow the State finds out its argname -- i think (does it really?) -- we might want that in debug_name return State( StateArrayRefs_type, call_Expr(_make_StateArrayRefs, type_expr, dfltval_expr, _E_ATTR, _self, **kws)) #k this use of **kws ###k i *think* that this will eval dfltval_expr once per Instance (w/o tracking, since it's part of State's default val expr) # at the time the StateArrayRefs attr is first accessed (e.g. for set or get of an element). def _make_StateArrayRefs(type_expr, dfltval_expr, attr, self, debug_name = None): "[private helper for StateArrayRefs]" # print "debug fyi: _make_StateArrayRefs type_expr = %r, dfltval_expr = %r, attr = %r, self = %r, debug_name = %r" % \ # (type_expr, dfltval_expr, attr, self, debug_name) ## example of what this prints: ## type_expr = <lexenv_ipath_Expr#20244: <widget_env at 0xf51d9e0 (_self = <test_StateArrayRefs_2#20226(i)>)>, ## (1, ('heights', ((-108, 0), ((-104, 0), (-101, '.'))))), S.Anything>, ## dfltval_expr = array([ 0., 0., 0.]), ## attr = 'heights', ## self = <test_StateArrayRefs_2#20226(i)>, ## debug_name = None ###NOTE: dfltval_expr is probably always a constant_Expr or maybe even just a constant -- not sure -- might need to Hold it # in the call and eval it here (which would be best anyway) ####e if debug_name: attr ###e maybe get this passed in (as a positional arg, always supplied) [this will fail for now, so debug_name is nim] debug_name = "%s.%s" % (debug_name, attr) # if we know the attr ###k not sure this copied code makes sense here ## valfunc = f(dfltval_expr) ###e maybe eval this expr (or even instantiate it???) in the env... get the env passed in somehow #e digr: can call_Expr have a feature that the value of self it's evaluating within can be passed to it? #e or should we just require the explicit use of _self in its arglist? (The latter.) ###e digr: getting a dflt passed in must relate to StateArg somehow # valfunc will be applied to key in order to recompute the value at key (only if it's accessed before first set) constant_default_val = dfltval_expr ####WRONG valfunc = lambda key: constant_default_val return LvalDict2(valfunc, LvalForState, debug_name = debug_name) ###BUG - elts of this are the lvals, not their values!!! But if not for that, how would we make setitem work in this?!? ### I think we need to return a new object which implements __setitem__ by passing it into the lvals properly. ###e But we also need access to per-element staterefs, # e.g. we need that in the first use of this in test_statearray.py or a related file. # [see also StateArrayRefs_getitem_as_stateref] def StateArrayRefs_getitem_as_stateref(statearrayrefs, index): #070313 renamed getitem_stateref to StateArrayRefs_getitem_as_stateref "#doc; args are values not exprs in the present form, but maybe can also be exprs someday, returning an expr..." if 'arg1 is a StateArrayRefs, not a StateArray': return statearrayrefs[index] # WARNING: # this only works due to a bug in the initial stub implem for StateArray -- # now declared a feature due to its being renamed to StateArrayRefs -- in which self.attr # is valued as a dict of LvalForState objects rather than of settable/gettable item values, # and *also* because I changed LvalForState to conform to the new StateRefInterface so it actually # has a settable/gettable .value attribute. ##### When that bug in StateArray is fixed, this code would be WRONG if applied to a real StateArray. # What we need is to ask for an lval or stateref for that StateArray at that index! # Can we do that using getitem_Expr (re semantics, reasonableness, and efficiency)? ##k else: StateRef_from_lvalue = 'nim' from exprs.Exprs import getitem_Expr # apparently the only use of that, and never runs, and requires an extension of it... return StateRef_from_lvalue( getitem_Expr(statearrayrefs, index)) ###IMPLEM this getitem_Expr behavior (proposed, not yet decided for sure; easy, see getattr_Expr for how) ###IMPLEM StateRef_from_lvalue if I can think of a decent name for it, and if I really want it around pass # == StateArray = Stub # end
NanoCAD-master
cad/src/exprs/statearray.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ projection.py - utilities loosely related to setting up the projection matrix @author: Bruce @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. """ from OpenGL.GL import glScalef from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import glMatrixMode from OpenGL.GL import glPushMatrix from OpenGL.GL import glLoadIdentity from OpenGL.GL import GL_PROJECTION from OpenGL.GL import GL_VIEWPORT from OpenGL.GL import glGetIntegerv from OpenGL.GL import glOrtho from OpenGL.GL import glTranslatef from OpenGL.GL import glPopMatrix from OpenGL.GLU import gluPickMatrix, gluUnProject try: from OpenGL.GL import glScale except: # The installed version of OpenGL requires argument-typed glScale calls. glScale = glScalef from utilities.prefs_constants import UPPER_RIGHT, UPPER_LEFT, LOWER_LEFT, LOWER_RIGHT # note: also in basic.py as of 070302 from exprs.attr_decl_macros import Arg, ArgOrOption, Option from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.widget2d import Widget2D from exprs.ExprsConstants import PIXELS class DrawInCorner_projection(DelegatingInstanceOrExpr): """ [DEPRECATED for general use -- use DrawInCorner instead.] This is a variant of DrawInCorner which works by changing the projection matrix, and which has several bugs/niys. It only works for the default corner argument, and any Highlightables in its main argument (delegate) only work properly for highlighting if they are given the option projection = True (which is not the default, for efficiency reasons [this may change on 081202]). Its usefulness is that it's the only expr (as of 070405) which changes the projection matrix for the subexprs it draws, so it's the only good test of Highlightable(projection = True). """ # Note: renamed from DrawInCorner_NOTWORKING_VERSION to DrawInCorner_projection on 070405, # since tests show that Highlightable(projection=True) has been working inside it for awhile. # # But to make it the usual implem of DrawInCorner would require: # - a good reason (like pixel alignment bugs after trackballing, in the other implem -- not yet annoying enough); # - args fixed up to match that one; # - implem the other corners -- only the default one works now, I think; # - make it unnecessary to say projection = True to embedded Highlightables, # using either a GLPane flag (with special provisions for display lists, # which might need two variants depending on that flag), # or a change of default value of that option, # or a change of algorithm in Highlightable. delegate = Arg(Widget2D) corner = Arg(int, LOWER_RIGHT) def draw(self): # this code is modified from drawcompass glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMatrixMode(GL_PROJECTION) # WARNING: we're now in nonstandard matrixmode (for sake of gluPickMatrix and glOrtho -- needed??##k) glPushMatrix() glLoadIdentity() try: glpane = self.env.glpane aspect = glpane.aspect # revised by bruce 070919, UNTESTED corner = self.corner delegate = self.delegate ###e should get glpane to do this for us (ie call a method in it to do this if necessary) # (this code is copied from it) glselect = glpane.current_glselect if glselect: # print "%r (ipath %r) setting up gluPickMatrix" % (self, self.ipath) x,y,w,h = glselect gluPickMatrix( x,y, w,h, glGetIntegerv( GL_VIEWPORT ) #k is this arg needed? it might be the default... ) # the first three cases here are still ###WRONG if corner == UPPER_RIGHT: glOrtho(-50 * aspect, 5.5 * aspect, -50, 5.5, -5, 500) # Upper Right elif corner == UPPER_LEFT: glOrtho(-5 * aspect, 50.5 * aspect, -50, 5.5, -5, 500) # Upper Left elif corner == LOWER_LEFT: glOrtho(-5 * aspect, 50.5 * aspect, -5, 50.5, -5, 500) # Lower Left else: ## glOrtho(-50 * aspect, 5.5 * aspect, -5, 50.5, -5, 500) # Lower Right ## glOrtho(-50 * aspect, 0, 0, 50, -5, 500) # Lower Right [used now] -- x from -50 * aspect to 0, y (bot to top) from 0 to 50 glOrtho(-glpane.width * PIXELS, 0, 0, glpane.height * PIXELS, -5, 500) # approximately right for the checkbox, but I ought to count pixels to be sure (note, PIXELS is a pretty inexact number) glMatrixMode(GL_MODELVIEW) ###k guess 061210 at possible bugfix (and obviously needed in general) -- # do this last to leave the matrixmode standard # (status of bugs & fixes unclear -- hard to test since even Highlightable(projection=True) w/o any change to # projection matrix (test _9cx) doesn't work!) offset = (-delegate.bright, delegate.bbottom) # only correct for LOWER_RIGHT glTranslatef(offset[0], offset[1], 0) self.drawkid( delegate) ## delegate.draw() finally: glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) # be sure to do this last, to leave the matrixmode standard glPopMatrix() return pass # end of class DrawInCorner_projection # == # Since the above does not yet work with highlighting, try it in a completely different way for now, not using projection matrix, # since we need the feature. Works! corner_abbrevs = { #070208 LOWER_RIGHT: (+1, -1), # (x,y) where for x, -1 is left, and for y, -1 is lower UPPER_RIGHT: (+1, +1), LOWER_LEFT: (-1, -1), UPPER_LEFT: (-1, +1), } _DEBUG_SAVED_STUFF = False class DrawInCorner(DelegatingInstanceOrExpr): """ DrawInCorner( thing, (-1,-1)) draws thing in the lower left corner of the screen (positioning thing so that its layout box's lower left corner nests directly into that corner of the screen). The depth can be specified by the option want_depth (between 0.0 and 1.0), which by default is 0.01 (very near the front). [###UNTESTED: it may be that non-default depths have never been tested.] The "corner" can be any corner, or any edge, or the center of the screen; it can be specified as a 2nd argument (x,y), or by the option corner = (x,y), where x can be -1, 0, or 1 (for left, center, or right respectively) and y can be -1, 0, or 1 (for bottom, center, or top). For the corners, the abbreviations defined in prefs_constants (small ints called UPPER_RIGHT, UPPER_LEFT, LOWER_LEFT, LOWER_RIGHT) are also permitted (and for convenience can also be imported from this class's source file). When thing does not need to touch a screen boundary (in one or both dimensions), it is not shifted at all, meaning its local origin is aligned with the specified position in that dimension. For drawing in an edge or the center, consider wrapping thing in Center or the like to modify this. (Without this feature, DrawInCorner( thing, (0,0)) would be equivalent to DrawInCorner( Center(thing), (0,0)).) ###BUG: The current implem (as of 070210) probably doesn't work properly after coordinate changes inside display lists. """ ##e should we reverse the arg order? [recent suggestion as of 070302] delegate = Arg(Widget2D) corner = ArgOrOption(int, LOWER_RIGHT, doc = "the corner/edge/center to draw in, as named int or 2-tuple; see class docstring for details") # note: semi-misnamed option, since it can also be an edge or the center ###KLUGE: type spec of 'int' is wrong -- we also allow it to be a pair of ints for x,y "symbolic posn" respectively want_depth = Option(float, 0.01) # this choice is nearer than cov_depth (I think!) but doesn't preclude 3D effects (I hope). def draw(self): if self.delegate is None: # 070210 -- but I'm not sure if this is a complete ###KLUGE, or good but ought to be done more generally, # or if it would be better to do it totally differently by instantiating None into something like Spacer(). ##k return glMatrixMode(GL_MODELVIEW) # not needed glPushMatrix() glLoadIdentity() try: glpane = self.env.glpane aspect = glpane.aspect # revised by bruce 070919 corner = self.corner delegate = self.delegate want_depth = self.want_depth # note about cov_depth: ## self.near = 0.25 ## self.far = 12.0 # so I predict cov_depth is 0.75 / 11.75 == 0.063829787234042548 # but let's print it from a place that computes it, and see. # ... hmm, only place under that name is in selectMode.py, and that prints 0.765957458814 -- I bet it's something # different, but not sure. ###k (doesn't matter for now) # modified from _setup_modelview: saveplace = self.transient_state # see if this fixes the bug 061211 1117a mentioned below -- it does, use it. # BUG (probably not related to this code, but not known for sure): # mousewheel zoom makes checkboxes inside DrawInCorner # either not highlight, or if they are close enough to # the center of the screen (I guess), highlight in the # wrong size and place. For more info and a partial theory, # see the 081202 update in DisplayListChunk.py docstring. # Before I realized the connection to DisplayListChunk, # I tried using saveplace = self.per_frame_state instead of # self.transient_state above, but that had no effect on the bug. # That was before I fixed some bugs in same_vals related to # numpy.ndarray, when I was plagued with mysterious behavior # from those in my debug code (since solved), but I tried it # again afterwards and it still doesn't fix this bug, which # makes sense if my partial theory about it is true. # # In principle (unrelated to this bug), I'm dubious we're # storing this state in the right place, but I won't change # it for now (see related older comments below). # # Note: I fixed the bug in another way, by changing # Highlightable's projection option to default True. # [bruce 081202] if glpane.current_glselect or (0 and 'KLUGE' and hasattr(saveplace, '_saved_stuff')): # kluge did make it faster; still slow, and confounded by the highlighting-delay bug; # now I fixed that bug, and now it seems only normally slow for this module -- ok for now. # when that cond is false, we have a nonstandard projection matrix # (see also the related comments in save_coords_if_safe in Highlightable.py) # [bruce 081204 comment] x1, y1, z1 = saveplace._saved_stuff # this is needed to make highlighting work! ###BUG [061211 1117a; fixed now, see above, using saveplace = self.transient_state]: # if we click on an object in testexpr_15d (with DrawInCorner used for other objs in the testbed) # before it has a chance to show its highlighted form, at least after a recent reload, we get an attrerror here. # Easy to repeat in the test conditions mentioned (on g5). Not sure how it can affect a different obj (self) # than the one clicked on too quickly. Best fix would be to let glpane give us the requested info, # which is usually the same for all callers anyway, and the same across reloads (just not across resizes). # But it does depend on want_depth, and (via gluUnProject) on the current modelview coords # (and projection coords if we ever changed them). So it's not completely clear how to combine ease, efficiency, # and safety, for that optim in general, even w/o needing this bugfix. # But the bug is easy to hit, so needs a soon fix... maybe memoize it with a key corresponding to your own # assumed choice of modelview coords and want_depth? Or maybe enough to put it into the transient_state? TRY THAT. works. if _DEBUG_SAVED_STUFF: print "_DEBUG_SAVED_STUFF: retrieved", x1, y1, z1 else: x1, y1, z1 = saveplace._saved_stuff = \ gluUnProject(glpane.width, glpane.height, want_depth) # max x and y, i.e. right top # (note, to get the min x and y we'd want to pass (0, 0, want_depth), # since these are windows coords -- (0, 0) is bottom left corner (not center)) # # Note: Using gluUnProject is probably better than knowing and reversing _setup_projection, # since it doesn't depend on knowing the setup code, except meaning of glpane height & width attrs, # and knowing that origin is centered between them and 0. if _DEBUG_SAVED_STUFF: print "_DEBUG_SAVED_STUFF: saved", x1, y1, z1 ## print x1,y1,z1 # use glScale to compensate for zoom * scale in _setup_projection, # for error in PIXELS, and for want_depth != cov_depth x1wish = glpane.width / 2.0 * PIXELS # / 2.0 because in these coords, screen center indeed has x == y == 0 r = x1 / x1wish glScale(r, r, r) ## x1 /= r ## y1 /= r z1 /= r # now the following might work except for z, so fix z here glTranslatef( 0.0, 0.0, z1) del x1, y1 # not presently used if _DEBUG_SAVED_STUFF: print "_DEBUG_SAVED_STUFF: r = %r, translated z by z1 == %r" % (r, z1) # I don't think we need to usage-track glpane height & width (or scale or zoomFactor etc) # since we'll redraw when those change, and redo this calc every time we draw. # The only exception would be if we're rendering into a display list. # I don't know if this code (gluUnProject) would even work in that case. # [I think I wrote a similar comment in some other file earlier today. #k] # move to desired corner, and align it with same corner of lbox # (#e could use an alignment prim for the corner if we had one) if corner in corner_abbrevs: # normalize how corner is expressed, into a 2-tuple of +-1's corner = corner_abbrevs[corner] x, y = corner if x == -1: # left x_offset = - glpane.width / 2.0 * PIXELS + delegate.bleft elif x == +1: # right x_offset = + glpane.width / 2.0 * PIXELS - delegate.bright elif x == 0: # center(x) x_offset = 0 # note: before 070210 this was (+ delegate.bleft - delegate.bright) / 2.0, # which has an unwanted (since unavoidable) centering effect; use explicit Center if desired. else: print "invalid corner",corner### raise ValueError, "invalid corner %r" % (corner,) if y == -1: # bottom y_offset = - glpane.height / 2.0 * PIXELS + delegate.bbottom elif y == +1: # top y_offset = + glpane.height / 2.0 * PIXELS - delegate.btop elif y == 0: # center(y) y_offset = 0 # note: # note: before 070210 this was (+ delegate.bbottom - delegate.btop) / 2.0 else: print "invalid corner",corner### raise ValueError, "invalid corner %r" % (corner,) offset = (x_offset, y_offset) glTranslatef(offset[0], offset[1], 0.0) if _DEBUG_SAVED_STUFF: print "_DEBUG_SAVED_STUFF: offset =", offset self.drawkid( delegate) ## delegate.draw() finally: glMatrixMode(GL_MODELVIEW) # not needed glPopMatrix() return pass # end of class DrawInCorner DrawInCenter = DrawInCorner(corner = (0,0), doc = "#doc") # a convenient abbreviation ###e we also want DrawInAbsCoords -- but its code doesn't seem very related; several implem strategies differ re displists/highlighting ###e another thing we want is more like "draw in the local coords of a given object" (DrawInThingsCoords?) -- # but that's harder -- and not even well-defined if that obj is drawn in more than one place (or nowhere) -- # unless the meaning is to redraw the argument once for each such place! See also Highlightable's "run_OpenGL_in_local_coords" or so. # This was wanted for demo_MT.py cross-highlighting, which might have some comments about alternatives to that. [070210] # end
NanoCAD-master
cad/src/exprs/projection.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ Exprs.py -- class Expr, and related subclasses and utilities, other than those involving Instances @author: Bruce @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. TODO: this file is getting kind of long - maybe split it in some sensible way? """ # note: this module should not import ExprsMeta, though its InstanceOrExpr subclass needs to (in another module). # instead, it is probably fully imported by ExprsMeta. from utilities.debug import compact_stack from utilities.debug import print_compact_stack from utilities.debug import safe_repr ##from debug_prefs import debug_pref, Choice_boolean_False, Choice_boolean_True, Choice from utilities.Comparison import same_vals from exprs.py_utils import printnim, printfyi, printonce from exprs.intern_ipath import intern_ipath from foundation.state_constants import _UNSET_ # == EVAL_REFORM = True # False supposedly acts like old code, True like new code which has by now become standard; # this affects all class defs, so to be safe, print a warning if the value is not true. # [bruce 070115 & 071102] if not EVAL_REFORM: print "EVAL_REFORM is %r" % EVAL_REFORM # == utilities #e refile def map_dictvals(func, dict1): """ This does to a dict's values what map does to lists -- i.e. it makes a new dict whose values v are replaced by func(v). [If you wish func also depended on k, see map_dictitems.] """ return dict([(k,func(v)) for k,v in dict1.iteritems()]) def map_dictitems(func, dict1): """ This does to a dict's items what map does to lists -- i.e. it makes a new dict whose items are f(item) from the old dict's items. Func should take 1 argument, a pair (k,v), and return a new pair (k2, v2). Often k2 is k, but this is not required. If the new items have overlapping keys, the result is... I don't know what. #k """ return dict(map(func, dict1.iteritems())) # == serial numbers (along with code in Expr.__init__) _next_e_serno = 1 # incremented after being used in each new Expr instance (whether or not _e_is_instance is true for it) ###e should we make it allocated in Expr subclasses too, by ExprsMeta, and unique in them? _debug_e_serno = -1 ## normally -1 # set to the serno of an expr you want to watch #k untested since revised def expr_serno(expr): """ Return the unique serial number of any Expr (except that Expr python subclasses all return 0). Non-Exprs all return -1. """ try: return expr._e_serno # what if expr is a class? is this 0 for all of those?? yes for now. ###k except: # for now, this case happens a lot, since ExprsMeta calls us on non-expr vals such as compute method functions, # and even sometimes on ordinary Python constants. assert not is_Expr(expr) return -1 pass # == predicates def is_Expr(expr): """ is expr an Expr -- meaning, a subclass or instance of class Expr? (Can be true even if it's also considered an Instance.) """ return hasattr(expr, '_e_serno') def is_expr_Instance(expr): ##e or just is_Instance?? or is_Expr_Instance? """ #doc """ return is_Expr(expr) and expr_is_Instance(expr) def is_expr_Instance_or_None(expr): #070326, common enough to have its own predicate return expr is None or is_expr_Instance(expr) def is_pure_expr(expr): ##e why not is_pure_Expr? is lowercase expr a generic term of some sort? [070207 terminology Q] """ is expr an Expr (py class or py instance), but not an Instance? """ return is_Expr(expr) and not expr_is_Instance(expr) def expr_is_Instance(expr): """ is an Expr an Instance? """ res = expr._e_is_instance assert res is False or res is True ###e hmm, might fail for classes, need to fix return res def is_Expr_pyinstance(expr): ##e make sure we check this before calling _e_eval / _e_compute_method / _e_make_in on an expr """ Is expr an Expr, and also a python instance (not an Expr subclass)? (This is necessary to be sure you can safely call Expr methods on it.) (Note: If so, it might or might not be an Instance.) [Use this instead of isinstance(Expr) in case Expr module was reloaded.] """ return is_Expr(expr) and is_Expr(expr.__class__) def is_Expr_pyclass(expr): """ Is expr an Expr and a python class (i.e. is it a subclass of Expr)? [This is easier to use than issubclass, since that has an exception on non-classes.] """ return is_Expr(expr) and not is_Expr(expr.__class__) def is_constant_expr(expr): # written for use in def If, not reviewed for more general use """ #doc; WARNING: not reviewed for use after some code gets reloaded during debugging [but, it seems like it should be ok, since constant_Expr is defined in this module, and this module is not auto-reloaded.] """ assert is_pure_expr(expr) return isinstance(expr, constant_Expr) ###k probably too limited; #e might need to delve in looking for sources of non-constancy; #e might prefer to return the simpified const value, or a non-constant indicator (eg an equiv constant_Expr or None) def expr_constant_value(expr): # written for use in def If, not reviewed for more general use """ #doc; WARNING: not fully reviewed for use after some code gets reloaded during debugging [see is_constant_expr doc for details]. """ if is_constant_expr(expr): return True, expr._e_constant_value #k will be wrong once is_constant_expr is improved -- a single func will need to do both things else: return False, "arb value" pass def is_constant_for_instantiation(expr): #070131, moved here 070321 from instance_helpers.py """ Is expr (which might be an arbitrary python object) a constant for instantiation? (If true, it's also a constant for eval, but not necessarily vice versa.) """ #e refile? should be compatible with _e_make_in methods in kinds of exprs it's true for # anything except a pure expr is a constant, and so is an Expr subclass if not (is_pure_expr(expr) and is_Expr_pyinstance(expr)): return True # cover a constant Symbol too, e.g. Automatic #e (merge _e_sym_constant with _e_instance? see comment in Symbol._e_make_in for discussion) if getattr(expr, '_e_sym_constant', False): return True return False # == class Expr(object): # notable subclasses: SymbolicExpr (OpExpr or Symbol), InstanceOrExpr """ abstract class for symbolic expressions that python parser can build for us, from Symbols and operations including x.a and x(a); also used as superclass for WidgetExpr helper classes, though those don't yet usually require the operation-building facility, and I'm not positive that kluge can last forever. All Exprs have in common an ability to: - replace lexical variables in themselves with other exprs, in some cases retaining their link to the more general unreplaced form (so some memo data can be shared through it), tracking usage of lexical replacements so a caller can know whether or not the result is specific to a replacement or can be shared among all replaced versions of an unreplaced form; ###@@@ details? - be customized by being "called" on new arg/option lists; ###@@@ - and (after enough replacement to be fully defined, and after being "placed" in a specific mutable environment) to evaluate themselves as formulas, in the current state of their environment, tracking usage of env attrs so an external system can know when the return value becomes invalid; - """ ##e for debug it would be useful to record line/file of expr construction, and then for any instance or expr # printed in an error msg or traceback, print the chain of these (as it gets customized, gets args, gets instantiated) -- # sort of like a stacktrace of where it was made. Not hard (see compact_stack for how). Enable using global flag. [070131] # default/initial values of instance variables _e_is_symbolic = False #061113 _e_args = () # this is a tuple of the expr's args (processed by canon_expr), whenever those args are always all exprs. _e_kws = {} # this is a dict of the expr's kw args (processed by canon_expr), whenever all kwargs are exprs. # note: all expr subclasses which use this should reassign to it, so this shared version remains empty. # note: all Expr subclasses should store either all or none of their necessary data for copy in _e_args and _e_kws, # or they should override methods including copy(?) and replace(?) which make that assumption. ##k [061103] _e_is_instance = False # override in certain subclasses or instances ###IMPLEM _e_serno = 0 ###k guess; since Expr subclasses count as exprs, they all have a serno of 0 (I hope this is ok) _e_has_args = False # subclass __init__ or other methods must set this True when it's correct... ###nim, not sure well-defined # (though it might be definable as whether any __init__ or __call__ had nonempty args or empty kws) # (but bare symbols don't need args so they should have this True as well, similar for OpExpr -- all NIM) # see also InstanceOrExpr .has_args -- if this survives, that should be renamed so it's the same thing [done now, 061102] # (the original use for this, needs_wrap_by_ExprsMeta, doesn't need it -- the check for _self is enough) [061027] def __init__(self, *args, **kws): assert 0, "subclass %r of Expr must implement __init__" % self.__class__.__name__ def __eq__(self, other):#070122 """ Default implem for many but not all subclasses of Expr. Note: we don't require _e_sernos to be equal! """ # this and/or its overridings assume: same_vals works on Exprs [not tested or reviewed ###DOIT], # and widget_env is also given a correct __eq__ [###NIM, means lexenv_Exprs will rarely compare equal when they should]. if self is other: return True if (not hasattr(other, '__class__')): return False # without this test, epydoc fails with: AttributeError: class SyntaxError has no attribute '__class__' if self.__class__.__name__ != other.__class__.__name__: return False #e this might change someday when comparing proxies -- see comment below if self.__class__ is not other.__class__: print "warning: exprs passed to __eq__, sernos %r and %r, have different classes with same name %s -- reload issue?" % \ (self._e_serno, other._e_serno, self.__class__.__name__) return False # this is safest (e.g. it lets us assume other is an Expr in the remaining code) if self._e_is_instance or other._e_is_instance: # this is not safe to ask unless we know other is an Expr return False # Instances are only equal if identical, for now (and an Instance can't equal a non-Instance); #e later two Instances might be equal if they know they're proxies for the same something else (not sure) # now we're comparing two pure exprs of the same class #e optim: if both are interned, return False; otherwise intern them and recompare # In case of Numeric array args, should we only use __ne__, use same_vals, or trust what we compare here to come out of # canon_expr? I think I'll trust canon_expr but use != anyway (redundant), but in constant_Expr use same_vals. if self._e_has_args != other._e_has_args: return False if self._e_args != other._e_args: return False if self._e_kws != other._e_kws: return False return True def __ne__(self, other): return not self.__eq__(other) def _e_init_e_serno(self): # renamed from _init_e_serno_, 061205 """ [private -- all subclasses must call this; the error of not doing so is not directly detected -- but if they call canon_expr on their args, they should call this AFTER that, so self._e_serno will be higher than that of self's args! This may not be required for ExprsMeta sorting to work, but we want it to be true anyway, and I'm not 100% sure it's not required. (Tentative proof that it's not required: if you ignore serno of whatever canon_expr makes, prob only constant_Expr, then whole serno > part serno anyway.)] Assign a unique serial number, in order of construction of any Expr. FYI: This is used to sort exprs in ExprsMeta, and it's essential that the order matches that of the Expr constructors in the source code of the classes created by ExprsMeta (for reasons explained therein, near its expr_serno calls). """ #e Probably this should be called by __init__ and our subclasses should call that, # but the above assert is useful in some form. # Note that this needn't be called by __call__ in InstanceOrExpr, # but only because that ends up calling __init__ on the new expr anyway. global _next_e_serno self._e_serno = _next_e_serno _next_e_serno += 1 if self._e_serno == _debug_e_serno: #k hope not too early for %r to work print_compact_stack("just made expr %d, %r, at: " % (_debug_e_serno, self)) return def _e_dir_added(self): # 061205 """ For a symbolic expr only, return the names in dir(self) which were stored by external assignments. """ assert self._e_is_symbolic assert not self._e_is_instance #k probably implied by _e_is_symbolic return filter( lambda name: not (name.startswith('_e_') or name.startswith('__')) , dir(self) ) def __call__(self, *args, **kws): assert 0, "subclass %r of Expr must implement __call__" % self.__class__.__name__ # note: for __getattr__, see also the subclasses; for __getitem__ see below def __get__(self, obj, cls): """ The presence of this method makes every Expr a Python descriptor. This is so an expr which is a formula in _self can be assigned to cls._C_attr for some attr (assuming cls inherits from InvalidatableAttrsMixin), and will be used as a "compute method" to evaluate obj.attr. The default implementation creates some sort of Lval object with its own inval flag and subscriptions, but sharing the _self-formula, which recomputes by evaluating the formula with _self representing obj. """ # more on the implem: # It stores this Lval object in obj.__dict__[attr], finding attr by scanning cls.__dict__ # the first time. (If it finds itself at more than one attr, this needs to work! Is that possible? Yes -- replace each # ref to the formula by a copy which knows attr... but maybe that has to be done when class is created? # Easiest way is first-use-of-class-detection in the default implem. (Metaclass is harder, for a mixin being who needs it.) # Ah, easier way: just store descriptors on the real attrs that know what to do... as we're in the middle of doing # in the code that runs when we didn't, namely _C_rule or _CV_rule. ###) if obj is None: return self #e following error message text needs clarification -- when it comes out of the blue it's hard to understand print "__get__ is nim in the Expr", self, ", which is assigned to some attr in", obj ####@@@@ NIM; see above for how [061023 or 24] print "this formula needed wrapping by ExprsMeta to become a compute rule...:", self ####@@@@ return def _e_compute_method(self, instance, index, _lvalue_flag = False): """ Return a compute method version of this formula, which will use instance as the value of _self, at the given index relative to instance. [index is a required arg as of 070120.] Example index [#k guess 061110]: the attrname where self was found in instance (as an attrvalue), or if self was found inside some attrval (but not equal to the whole), a tuple containing the attrname and something encoding where self occurred in the attrval. Update 070120: that "found inside some attrval" part is now handled by lexenv_ipath_Expr, and index can be modified as suggested by kluge070119 (experimental, not yet debugged). """ #####@@@@@ WRONG API in a few ways: name, scope of behavior, need for env in _e_eval, lack of replacement due to env w/in self. ##return lambda self = self: self._e_eval( _self = instance) #e assert no args received by this lambda? # TypeError: _e_eval() got an unexpected keyword argument '_self' ####@@@@ 061026 have to decide: are OpExprs mixed with ordinary exprs? even instances? do they need env, or just _self? # what about ipath? if embedded instances, does that force whole thing to be instantiated? (or no need?) # wait, embedded instances could not even be produced w/o whole thing instantiating... so i mean, # embedded things that *need to* instantiate. I guess we need to mark exprs re that... # (this might prevent need for ipath here, if pure opexprs can't need that path) # if so, who scans the expr to see if it's pure (no need for ipath or full env)? does expr track this as we build it? # try 2 061027 late: revised 070117 assert instance._e_is_instance, "compute method for %r asked for on non-Instance %r (index %r, lvalflag %r)" % \ (self, instance, index, _lvalue_flag) # happens if a kid is non-instantiated(?) # revised 070117 env, ipath = instance._i_env_ipath_for_formula_at_index( index) # split out of here into IorE, 070117 # does _self = instance binding [tho that might change -- 070120] if not _lvalue_flag: # usual case return lambda self=self, env=env, ipath=ipath: self._e_eval( env, ipath ) #e assert no args received by this lambda? else: # lvalue case, added 061204, experimental -- unclear if returned object is ever non-flyweight or has anything but .set_to # [note, this presumably never happens when EVAL_REFORM, at least as of late 070119] return lambda self=self, env=env, ipath=ipath: self._e_eval_lval( env, ipath ) pass def __repr__(self): # class Expr """ [often overridden by subclasses; __str__ can depend on __repr__ but not vice versa(?) (as python itself does by default(??))] """ ## return str(self) #k can this cause infrecur?? yes, at least for testexpr_1 (a Rect_old) on 061016 ## return "<%s at %#x: str = %r>" % (self.__class__.__name__, id(self), self.__str__()) return "<%s#%d%s>" % (self.__class__.__name__, self._e_serno, self._e_repr_info()) def _e_repr_info(self):#061114 """ [private helper for __repr__] """ if self._e_has_args: if self._e_is_instance: return '(i)' else: return '(a)' else: if self._e_is_instance: return '(i w/o a)' # an error, i think, at least for now else: return '' pass # == def __rmul__( self, lhs ): """operator b * a""" return mul_Expr(lhs, self) def __mul__( self, rhs ): """operator a * b""" return mul_Expr(self, rhs) def __rdiv__( self, lhs ): """operator b / a""" return div_Expr(lhs, self) def __div__( self, rhs ): """operator a / b""" return div_Expr(self, rhs) def __radd__( self, lhs ): """operator b + a""" return add_Expr(lhs, self) def __add__( self, rhs ): """operator a + b""" return add_Expr(self, rhs) def __rsub__( self, lhs ): """operator b - a""" return sub_Expr(lhs, self) def __sub__( self, rhs ): """operator a - b""" return sub_Expr(self, rhs) def __neg__( self): """operator -a""" return neg_Expr(self) def __pos__( self): """operator +a""" return pos_Expr(self) #e __mod__? (only ok if not used for print formatting -- otherwise we'd break debug prints like "%r" % expr) #e __len__? (might be ok, except lack of it catches bugs every so often, so I guess it's not a good idea) #e various type coercers... # but some special methodnames are impossible to support safely, like __str__, __eq__, etc... #e unless we have a special expr wrapper to give it the power to support all those too, but only if used right away. [061113] def __getitem__( self, index): #k not reviewed for slices, unlikely they'll work fully """ operator a[b] """ #e will Instances extend this to return their kids?? return getitem_Expr(self, index) # == not sure where these end up def __float__( self): """ operator float(a) """ print_compact_stack( "kluge: float(expr) -> 17.0: " )####@@@@ need float_Expr return 17.0 def _e_replace_using_subexpr_filter(self, func): #e rename, since more like map than filter; subexpr_mapper?? # zapped 061114 since common and so far always ok: ## if not isinstance(self, (OpExpr, constant_Expr)):#k syntax ## printfyi("_e_replace_using_subexpr_filter called on pyinstance of class %s" % self.__class__.__name__) ## ####k ever on an InstanceOrExpr?? might be wrong then, just as _e_eval should not go inside -- not sure! ## # more likely, it needs to go in but in a lexcontext-modified way! [061105 guess] ###@@@ args = self._e_args kws = self._e_kws if not args and not kws: return self # optim modargs = tuple(map(func, args)) modkws = map_dictvals(func, kws) if modargs == args and modkws == kws: # Note: requires fast == on Expr -- currently we let Python use 'is' by default. [#k in py doc, verify that's what happens] # Note: '==' (unlike other ops) is not meant as a formula. # (Could it be a formula, but with a boolean value too, stored independently??) # # Note: this is not affected by the Numeric Python design flaw (i.e. bug) about what '==' means, # since any Numeric arrays in args or kws have been wrapped by constant_Expr. # [070321, educated guess, not absolutely verified ####k] return self # helps prevent memory leaks (by avoiding needless reconstruction of equal exprs); might help serno too?? printnim("replace would be wrong for an expr with subexprs but also other data -- do we have any such? ##k")##k #k (wouldn't it also be wrong for expr w/ other data, even if no args/kws??) return self.__class__(*modargs, **modkws) def _e_free_in(self, sym): #e name is confusing, sounds like "free of" which is the opposite -- rename to "contains_free"?? """ Return True if self contains sym (Symbol or its name) as a free variable, in some arg or option value. [some subclasses override this] """ try: _e_args = self._e_args #k not sure this is defined in all exprs! indeed, not in a Widget2D python instance... ####@@@@ except AttributeError: #####@@@@ warning: following is slow, even when it doesn't print -- NEEDS OPTIM ####@@@@ printonce("debug note: _e_free_in is False since no _e_args attr in %r" % self) # print once per self return False ###k guess -- correct? #####@@@@@ for arg in _e_args: if arg._e_free_in(sym): return True printnim("_e_free_in is nim for option vals")###@@@ btw 061114 do we still use _e_free_in at all? see if this gets printed. return False def _e_eval_to_expr(self, env, ipath, expr):#070117, revised 070118 to save ipath """ #doc """ assert EVAL_REFORM # otherwise exprs don't eval to self except some Symbols, and I guess those don't call this tho i forget...#k return lexenv_ipath_Expr(env, ipath, expr) # the full ipath might not be needed but might be ok... ###k # note: _e_eval is nim in this class -- it must be implemented in subclasses that need it. # If you want to add a default errmsg def here, first review whether its presence would affect the expr-building code! # [070117 comment] def _e_burrow_for_find_or_make(self, env, ipath): #070119 #e might rename find_or_make to instantiate or so """ General case: Return (subexpr, new_env, new_ipath), where subexpr is the outermost subexpr of self which has no outermost local ipath or env mods, and those mods are stripped from self to get subexpr, and added to env, ipath to make new_env, new_ipath. Instantiating (self, env, ipath) and (subexpr, new_env, new_ipath) should get the same result semantically, and the implem enforces this by canonicalizing (self, env, ipath) using this method before instantiation. [###NIM] Trivial version for most expr classes: just return (self, env, ipath) unchanged. Overrides are only needed (so far, AFAIK) by lexenv_Expr and lexenv_ipath_Expr. [When IorE subclasses implement instance-sharing a la textureholders or (desired) CLE or other glue code (eg type coercion) objects, they too are likely to need a nontrivial implem of this, which filters the ipath down to the part that uniquely identifies the shared object. ##e] (Expr classes that can't be the result of evaluation (e.g. constant_Expr, If_expr, probably eval_Expr) don't need to override this, since exprs should be evalled before being instantiated. ###k) """ # Is the docstring right about this not being needed in If_expr? eval_Expr? constant_Expr?? other internal exprs? ###k return (self, env, ipath) pass # end of class Expr def safer_attrpath(obj, *attrs): #e refile, doc, rename for attr in attrs: try: obj = getattr(obj, attr) except AttributeError: return "<no %r in some %s>" % (attr, obj.__class__.__name__) continue return obj class SymbolicExpr(Expr): # Symbol or OpExpr _e_is_symbolic = True #061113 _e_sym_constant = False #070131, can be overridden in subclasses or instances; see class Symbol for doc def __call__(self, *args, **kws): assert not self._e_is_instance # (should never happen I think) return call_Expr(self, *args, **kws) def __getattr__(self, attr): # in class SymbolicExpr if attr.startswith('__'): # be very fast at not finding special python attrs like __repr__ raise AttributeError, attr # the code after this happens when constructing exprs, not when using them, # so a bit of slowness should be ok. assert not self._e_is_instance # (should never happen I think; if it can be legal, change to raise attrerror) if self._e_sym_constant: # [this special case might be evidence that _e_sym_constant should imply something like _e_is_instance -- # both of them mean "eval to self", "instantiate to self". Maybe they should even be merged... # idea not reviewed. Should check whether other special cases for _e_is_instance apply to _e_sym_constant. ###e 070131] raise AttributeError, "no attr %r in %s" % (attr, safe_repr(self)) if attr.startswith('_i_'): assert self._e_is_instance, \ "safety rule: automatic formation of getattr_Expr not allowed for attrs starting _i_, as in %r.%s" % \ (self, attr) #k not positive this is ok, we'll see [061105] # 070122 this failed with _app._i_instance(testexpr_19b) (and I added text to the assertion), # but that just means _app needs a public instancemaker rather than just that internal one -- now it has .Instance # note: self._e_is_instance is defined in all pyinstance exprs, not only InstanceOrExpr. assert 0 # not reached if attr.startswith('_e_') or (attr.startswith('_') and '__' in attr): # _i_ is handled separately above # We won't pretend to find Expr methods/attrs starting _e_ (also used in Instances), # or Instance ones starting _i_ -- but do reveal which class or object we didn't find them in. ##e ideally we'd reveal something longer than class and shorter than object... # 061203: also exclude _attr__xxx since it might be name-mangled. Needed to exclude _ExprsMeta__set_attr. # [Not confident this exclusion is always good -- maybe what we really need is a variant of hasattr # which turns off or detects and ignores the effect of this __getattr__. ###k] raise AttributeError, "no attr %r in %s" % (attr, safe_repr(self)) return getattr_Expr(self, attr) pass class OpExpr(SymbolicExpr): """ Any expression formed by an operation (treated symbolically) between exprs, or exprs and constants """ _e_debug = False #e move to a superclass? [bruce 070816 new feature] def __init__(self, *args, **kws): # arglist would just be "self, *args, doc = None" except that it's invalid syntax self._e_args = tuple(map(canon_expr, args)) # tuple is required, so _e_args works directly for a format string of same length self._e_init_e_serno() # call this AFTER canon_expr (for sake of _e_serno order) doc = kws.pop('doc', None) self.__doc__ = doc #070207 added this keyword arg -- supplied (to a StateAttr stub) but not yet used; # not sure it belongs in this class rather than the subclass that needed it (State) ##k # don't do this: junk = kws.pop('_KLUGE_fakeoption', None) debug = kws.pop('_e_debug', False) if debug: # activate some debug prints for self (only used by some subclasses) self._e_debug = True assert not kws, "unexpected keyword args for %s: %r" % (self.__class__.__name__, kws.keys()) self._e_init() return def _e_init(self): assert 0, "subclass of OpExpr must implement _e_init" def __repr__(self): # class OpExpr return "<%s#%d%s: %r>"% (self.__class__.__name__, self._e_serno, self._e_repr_info(), self._e_args,) def _e_argval(self, i, env,ipath): # see also a copy of this in IfExpr """ Under the same assumptions as _e_eval (see its docstring), compute and return the current value of an implicit kid-instance made from self._e_args[i], at relative index i, doing usage-tracking into caller (i.e. doing no memoization or caching of our own). """ def __debug_frame_repr__(locals): """return a string for inclusion in some calls of print_compact_stack""" # note: this will always run before res is available return "_e_argval(i = %r, ipath = %r), self = %r" % (i,ipath,self) ##e consider swapping argorder to 0,ipath,env or (0,ipath),env arg = self._e_args[i] try: res = arg._e_eval(env, (i,ipath)) except: print "following exception concerns arg._e_eval(...) where arg = %r" % (arg,) #070228 (guess: arg is class World itself) raise return res def _e_kwval(self, k, env,ipath): """ Like _e_argval, but return the current value of our implicit-kid-instance of self._e_kws[k], rel index k. """ return self._e_kws[k]._e_eval(env, (k,ipath)) def _e_eval(self, env, ipath): """ Considering ourself implicitly instantiated by the replacements (especially _self_) in env, or more precisely, instantiated as a formula residing in env's _self, after replacement by env's other replacements, with that implicit instance using the index-path given as ipath (and perhaps finding explicit sub-instances using that ipath, if we ever need those), compute and return our current value, doing usage-tracking into caller (i.e. doing no memoization or caching of our own). Note that an expr's current value might be any Python object; if it happens to be an Instance or Expr or special symbol, we should not notice that or do any special cases based on that (otherwise we'll cause bugs for uses of _e_eval on internal formulas like the ones made by the Arg macro). Most subclasses can use this implem, by defining an _e_eval_function which is applied to their arg values. If they have other data, or even kws, and/or if they don't want to always evaluate all args (like If or an InstanceOrExpr), they should redefine this method. [We're not presently in InstanceOrExpr at all, but that might change, though this implem won't work there since those want to never eval their args now. 061105] """ assert env #061110 assert not self._e_kws #e remove when done with devel -- just checks that certain subclasses overrode us -- or, generalize this func = self._e_eval_function # Note: these functions would turn into bound methods here, # if we didn't wrap them with staticmethod when assigning them. # Not doing that caused the "tuple_Expr bug" (see cvs for details). # Another solution would have been to grab the funcs only out of # the class's __dict__. Using staticmethod seems clearer. res = apply(func, [self._e_argval(i,env,ipath) for i in range(len(self._e_args))]) return res def _e_eval_lval(self, env,ipath): """ #doc """ assert env #061110 assert not self._e_kws #e remove when done with devel -- just checks that certain subclasses overrode us -- or, generalize this func = self._e_eval_lval_function res = apply(func, [self._e_argval(i,env,ipath) for i in range(len(self._e_args))]) return res pass # end of class OpExpr class call_Expr(OpExpr): # note: superclass is OpExpr, not SymbolicExpr, even though it can be produced by SymbolicExpr.__call__ ###BUG: __repr__ doesn't print self._e_kws [noticed 070119] def __init__(self, callee, *callargs, **kws): # we extend OpExpr.__init__ so we can have kws, and canon them self._e_kws = map_dictvals(canon_expr, kws) ###e optim: precede by "kws and" OpExpr.__init__(self, callee, *callargs) # call this AFTER you call canon_expr above (for sake of _e_serno order) def _e_init(self): # Store some args under more convenient names. # Note: this does NOT hide them from (nondestructive) _e_replace* methods, # since those find the original args, modify them, and construct a new expr from them. self._e_callee = self._e_args[0] self._e_call_args = self._e_args[1:] self._e_call_kws = self._e_kws #e could use cleanup below to not need this alias #e might be useful to record line number, at least for some heads like NamedLambda; see Symbol compact_stack call for how def __str__(self): if self._e_call_kws: return "%s(*%r, **%r)" % (self._e_callee, self._e_call_args, self._e_call_kws) #e need parens? elif self._e_call_args: return "%s%r" % (self._e_callee, self._e_call_args) else: return "%s%r" % (self._e_callee, self._e_call_args) # works the same i hope def _e_eval(self, env, ipath): """ [the only reason the super method is not good enough is that we have _e_kws too, I think; maybe also the distinction of that to self._e_call_kws, but I doubt that distinction is needed -- 061105] """ assert env #061110 # 061102: we do this (_e_eval in general) # by imagining we've done the replacements in env (e.g. for _self) to get an instance of the expr, # and then using ordinary eval rules on that, which include forwarding to _value for some Instances, # but typically result is an Instance or a python data object. # So, just eval it as a call, I think. argvals = [self._e_argval(i,env,ipath) for i in range(len(self._e_args))] # includes value of callee as argvals[0] # the following assumes _e_call_kws is a subset of (or the same as) _e_kws (with its items using the same keys). kwvals = map_dictitems( lambda (k,v): (k,self._e_kwval(k,env,ipath)), self._e_call_kws ) printnim('###e optim: precede by "self._e_call_kws and"') # in 2 places return argvals[0] ( *argvals[1:], **kwvals ) pass class LvalueFromObjAndAttr(object): #061204 for _e_eval_lval and LvalueArg, likely to be revised #e refile? #e later note 070316: we use this in toplevel expr macros to turn obj.attr into a stateref, # since getattr_Expr can't do that (it only makes a syntactic lval). # Should we rename this to e.g. getattr_StateRef, and put it into basic? (It's already in basic, since Exprs.* is.) # Maybe, but ONLY IF WE MAKE IT AN EXPR -- as it is, you have to use call_Expr with it. ##e make a variant for getitem_Expr? def __init__(self, obj, attr): self.obj = obj self.attr = attr def set_to(self, val): ###e probably we should rename set_to -> set_value, and define get_value and value -- see StateRefInterface [070312] try: setattr( self.obj, self.attr, val) except: print "following exception in setattr( self.obj, self.attr, val) concerns self = %r" % (self,) raise pass # 070312 conform to StateRefInterface set_value = set_to def get_value(self): return getattr(self.obj, self.attr) value = property( get_value, set_value) def __repr__(self): return "<%s at %#x for %r.%r>" % (self.__class__.__name__, id(self), self.obj, self.attr) #e some sort of .get function, .value attr (can be set or get), subscribe func, etc pass class getattr_Expr(OpExpr): def __call__(self, *args, **kws): msg = "error: getattr exprs are not callable: " \ "explicit call_Expr needed, instead of direct call " \ "of %r with:" % self, args, kws #bruce 080528 revised msg print msg assert 0, msg def _e_init(self): assert len(self._e_args) in (2,3) #e kind of useless and slow #e should also check types? #070203 permit 3-arg form attr = self._e_args[1] assert attr #e and assert that it's a python identifier string? Note, it's actually a constant_Expr containing a string! # And in theory it's allowed to be some other expr which evals to a string, # though I don't know if we ever call it that way # (and we might want to represent or print it more compactly when we don't). def __str__(self): if len(self._e_args) == 2: return "%s.%s" % self._e_args #e need parens? need quoting of 2nd arg? Need to not say '.' if 2nd arg not a py-ident string? else: return "getattr_Expr(%s, %s, %s)" % self._e_args _e_eval_function = getattr # this doesn't need staticmethod, maybe since <built-in function getattr> has different type than lambda ## _e_eval_lval_setto_function = setattr _e_eval_lval_function = staticmethod(LvalueFromObjAndAttr) #061204 #k not sure if staticmethod is required; at least it works ###UNREVIEWED for 3 args pass class getitem_Expr(OpExpr): #061110 def _e_init(self): assert len(self._e_args) == 2 #e kind of useless and slow?? # note, _e_args[1] is often constant_Expr(<an int as list-index> or <an attrname as dict key>), but could be anything def __str__(self): return "%s[%s]" % self._e_args #e need parens? _e_eval_function = staticmethod( lambda x,y:x[y] ) #e _e_eval_lval_function too, variant of LvalueFromObjAndAttr? pass class mul_Expr(OpExpr): def _e_init(self): assert len(self._e_args) == 2 def __str__(self): return "%s * %s" % self._e_args #e need parens? _e_eval_function = staticmethod( lambda x,y:x*y ) # does this have a builtin name? see operators module ###k pass class div_Expr(OpExpr): def _e_init(self): assert len(self._e_args) == 2 def __str__(self): return "%s / %s" % self._e_args #e need parens? _e_eval_function = staticmethod( lambda x,y:x/y ) pass class add_Expr(OpExpr): def _e_init(self): assert len(self._e_args) == 2 def __str__(self): return "%s + %s" % self._e_args #e need parens? _e_eval_function = staticmethod( lambda x,y:x+y ) ##e refile this note (proposed): [i, ipath] is an inlined sub_index(i,ipath); [] leaves room for intern = append pass class sub_Expr(OpExpr): def _e_init(self): assert len(self._e_args) == 2 def __str__(self): return "%s - %s" % self._e_args #e need parens? _e_eval_function = staticmethod( lambda x,y:x-y ) pass class neg_Expr(OpExpr): def _e_init(self): assert len(self._e_args) == 1 def __str__(self): return "- %s" % self._e_args #e need parens? _e_eval_function = staticmethod( lambda x:-x ) pass class pos_Expr(OpExpr):#061211 def _e_init(self): assert len(self._e_args) == 1 def __str__(self): return "+ %s" % self._e_args #e need parens? _e_eval_function = staticmethod( lambda x:+x ) pass class list_Expr(OpExpr): #k not well reviewed, re how it should be used, esp. in 0-arg case #aka ListExpr, but we want it not uppercase by convention for most OpExprs def _e_init(self): pass def __str__(self): return "%s" % (list(self._e_args),) #e need parens? _e_eval_function = staticmethod( lambda *args:list(args) ) ####e consider making this a tuple_Expr synonym -- see ArgList comments [070321] pass def printfunc(*args, **kws): #e refile, maybe rename dprint; compare to same-named *cannib*.py func prefix = kws.pop('prefix', '') assert not kws print "printfunc %s: %r" % (prefix, args) return args[0] class tuple_Expr(OpExpr): #k not well reviewed, re how it should be used, esp. in 0-arg case def _e_init(self): pass def __str__(self): return "%s" % (tuple(self._e_args),) #e need parens? def _e_eval_function(self, *argvals): # only become a tuple if we contain nothing to instantiate -- otherwise a tuple_Expr -- needed for ArgList [070321] for val in argvals: if is_pure_expr(val): #k not sure this condition is exactly right if self._e_args == argvals: return self # optimization return tuple_Expr(*argvals) continue return argvals # a tuple, not a tuple_Expr def _e_make_in(self, env, ipath): # 070321 needed for ArgList # we don't need to eval each arg expr, since we ourselves were just evalled (and are the result of that) # so all our args are evalled. But, not all evalled things have _e_make_in! Also, they went through canon_expr after eval. # Either we need to check both for constant_Expr (or anything else canon_expr can make ###k), and check # is_constant_for_instantiation like _i_instance does, or we need to actually call _i_instance, # depending, I think, on how much we want to cache these instances. For now I'll do what's easiest # (is_constant_for_instantiation, no caching) and review it later. WARNING: things like SimpleColumn # which declared each arg separately used to be able to cache them individually -- so THIS IS ######WRONG. # It'll work, I think, but be a slowdown. mades = [self._e_make_argval(argval, env, i, ipath) for (i,argval) in zip(range(len(self._e_args)), self._e_args)] return tuple(mades) def _e_make_argval(self, argval, env, i, ipath): """ [private helper] """ if is_constant_for_instantiation(argval): # print "fyi: tuple_Expr is_constant_for_instantiation true for %r" % (argval,) # this happens when an Instance is passed as an ArgList element, e.g. <PM_from_groups#40798(i)> in a SimpleColumn; # it's legit, so remove the print. [070322] return argval constflag, constval = expr_constant_value(argval) if constflag: # argval is a constant_Expr -- this happens here (but not in _i_instance) due to canon_expr. # btw, don't put _e_make_in on constant_Expr, i think - might hide bugs. (A correct def of it is there but cmted out.) return constval return argval._e_make_in(env, (i, ipath)) ###WRONG as explained in comment above. pass # same as in basic.py: from Numeric import dot from geometry.VQT import V, norm, vlen class V_expr(OpExpr): """ Make an expr for a Numeric array of floats. Called like VQT.py's V macro. """ # Note: the name contains 'expr', not 'Expr', since it's more public than the # typical class named op_Expr (official reason) and since it looks better in # contrast with V (real reason). Note that the real reason, but not the official one, # explains why we later used 'E' in format_Expr.] def _e_init(self): pass def __str__(self): return "V_expr%s" % (tuple(self._e_args),) #e need parens? _e_eval_function = staticmethod( lambda *args: V(*args) ) #e could inline as optim pass # == # these function -> OpExpr macros are quick hacks, fine except for their printform and maybe their efficiency. ##e maybe rewrite them like this: norm_Expr = func_Expr(norm) def norm_Expr(*args): return call_Expr( norm, *args) def vlen_Expr(*args): return call_Expr( vlen, *args) def dot_Expr(*args): return call_Expr( dot, *args) def max_Expr(*args): return call_Expr( max, *args) def min_Expr(*args): return call_Expr( min, *args) def int_Expr(*args): return call_Expr( int, *args) def not_Expr(arg): # maybe this is an operator so we can just make an OpExpr in usual way?? ###e try it - try using not instead, in the call of this, to see if __not__ is the right name return call_Expr(lambda val: not val, arg) def eq_Expr(arg1, arg2): return call_Expr(lambda a1,a2: a1 == a2, arg1, arg2) def ne_Expr(arg1, arg2): return call_Expr(lambda a1,a2: a1 != a2, arg1, arg2) def mod_Expr(arg1, arg2): return call_Expr( _eval_mod_Expr, arg1, arg2) def _eval_mod_Expr(a1, a2):#070121 """ private helper """ assert not (type(a1) == type('')), \ "mod_Expr arg1 %r is a string, would do string formatting instead of mod by %r" % (a1, a2) return a1 % a2 # == class and_Expr(OpExpr): #061128 """ Evaluate only enough args (out of 2 or more) to return the last one if they're all true, otherwise the first false one. """ def _e_init(self): assert len(self._e_args) >= 2 assert not self._e_kws #k needed? def __str__(self): return "and_Expr%r" % self._e_args def _e_eval(self, env, ipath): assert env for i in range(len(self._e_args)): res = self._e_argval(i,env,ipath) if not res: return res # the first false res continue return res # the last res, if they're all true # note: operator.__and__ requires exactly two args, and couldn't help anyway since we don't always want to eval arg2 pass class or_Expr(OpExpr): #061128 untested """ Evaluate only enough args (out of 2 or more) to return the last one if they're all false, otherwise the first true one. """ def _e_init(self): assert len(self._e_args) >= 2 assert not self._e_kws #k needed? def __str__(self): return "or_Expr%r" % self._e_args def _e_eval(self, env, ipath): assert env for i in range(len(self._e_args)): res = self._e_argval(i,env,ipath) if res: return res # the first true res continue return res # the last res, if they're all false pass # note: see also If_expr.py # == def assert_0_func(msg): #e refile #e rename """ Raise an AssertionError with msg, but be a function, so we're usable in lambdas. Typical usage: cond and result or assert_0_func("error-description" % args). """ assert 0, msg class format_Expr(OpExpr): #061113, seems to work #k (tho no test yet proved it defers eval til when it needs to -- hmm, same for *all* OpExprs, until we implem statemods? # no -- once something can access redraw_counter, that should provide a good enough test, for any OpExpr we make depend on that.) """ Make an expr for producing the results of <format_string> % <*args>. (See also mod_Expr [nim ##e], for exprs based on numeric uses of the % operator. Maybe they can be expressed using % directly?) Note, unlike __mod__ (sp??), this is varargs, not two args. It would be nice to be able to say the latter directly, but it's hard to do without dangerously interfering with debug prints of exprs in the code (though it might be possible someday -- see code comments for details). We might rename this to sprintf or format (not printf, since that implies a side effect on stdout). """ def _e_init(self): assert len(self._e_args) >= 2 #e later, change to >=1, since just 1 arg is legal -- I guess. # For now, >= 2 is usefully stricter for debugging. # In fact, maybe we'll keep it -- it catches use of '%' rather than ',', like in format_Expr("/tmp/%s.jpg" % testname) #e could assert arg0 is a string, but (1) not required until runtime, (2) hard to say anyway. pass def __str__(self): return "format_Expr%s" % (tuple(self._e_args),) #e need parens? _e_eval_function = staticmethod( lambda arg1, *args: ((type(arg1) is str) and (arg1 % args)) or assert_0_func("format_Expr got non-string format %r" % arg1) ) #e accept unicode arg1 too; python2.2 has an official way to express that (using the name string??) pass # format_Expr # == class internal_Expr(Expr): """ Abstract class for various kinds of low-level exprs for internal use that have no visible subexprs. """ def __init__(self, *args, **kws): """ store args & kws but don't canon_expr them -- assume they are not necessarily exprs (and even if they are, that they should be treated inertly) """ self.args = args # not sure if the non-_e_ name is ok... if not, try _e_data_args or so? ###k self.kws = kws self._internal_Expr_init() # subclasses should override this method to do their init self._e_init_e_serno() return def _internal_Expr_init(self): assert 0, "subclass must implem" def __eq__(self, other): """ [overrides Expr version; WARNING: must be overridden by any internal_Expr subclasses that use self.kws] """ if not Expr.__eq__(self, other): return False a1 = self.args a2 = other.args # must be tuples if a1 and a2: if not same_vals(a1,a2): ####k assume same_vals works properly for Exprs [perhaps never verified -- might give false negatives]; # we need to use it instead of just == or != due to Numeric arrays in lists or tuples return False else: if a1 != a2: # 'or' might be faster, and is correct, but that's less clear, so nevermind -- someday this will be in C anyway return False # the following is not yet needed by any internal_Expr subclasses so far -- so leave it out for now, but keep the code ##k1 = self.kws ##k2 = other.kws ##if k1 and k2: ## if not same_vals(k1,k2): ## return False ##else: ## if k1 != k2: ## return False return True pass class constant_Expr(internal_Expr): #### NOT YET REVIEWED FOR EVAL_REFORM 070117 [should it ever wrap the result using _e_eval_to_expr -- maybe in a variant class?] ###k super may not be quite right -- we want some things in it, like isinstance Expr, but not the __add__ defs [not sure, actually] def _internal_Expr_init(self): (self._e_constant_value,) = self.args def __repr__(self): # class constant_Expr return "<%s#%d%s: %r>"% (self.__class__.__name__, self._e_serno, self._e_repr_info(), self._e_constant_value,) def __str__(self): return "%r" % (self._e_constant_value,) #e need parens? #k 061105 changed %s to %r w/o reviewing calls (guess: only affects debugging) def _e_eval(self, env, ipath): assert env #061110 ## env._self # AttributeError if it doesn't have this [###k uses kluge in widget_env] # that failed (with the misleading AttrError from None due to Delegator), # but it's legit to fail now, since the constant can easily be in a lexenv with no binding for _self. return self._e_constant_value ## def _e_make_in(self, env, ipath): ###e equiv to _e_eval? see comment in _CV__i_instance_CVdict [061105] ## "Instantiate self in env, at the given index-path." ## #e also a method of InstanceOrExpr, tho not yet of any common superclass -- ## # I guess we'll add to OpExpr and maybe more -- maybe Expr, but not sure needed in all exprs ## return self._e_constant_value # thought to be completely correct, 061105 [and still, 061110, but zapping since redundant] pass class hold_Expr(constant_Expr): #e might be renamed to something like no_eval, or we might even revise call_Expr to not always eval its args... not sure """ Like constant_Expr, but (1) value has to be an expr, (2) replacements occur in value. Used internally to prevent eval of args to call_Expr. """ def _e_replace_using_subexpr_filter(self, func): #e rename, since more like map than filter; subexpr_mapper?? arg = self._e_constant_value #e another implem, maybe cleaner: store this data in _e_args; possible problems not reviewed modarg = func(arg) if modarg == arg: return self return self.__class__(modarg) pass class eval_to_lval_Expr(internal_Expr):#070119, needed only when EVAL_REFORM """ wrap a subexpr with me in order to cause _e_eval of me to only call _e_eval_lval on the subexpr """ def _internal_Expr_init(self): ## (self._e_the_expr,) = self.args self._e_args = self.args # so replace sees the args assert len(self.args) == 1 def _e_eval(self, env, ipath): assert env #061110 the_expr = self._e_args[0] ## self._e_the_expr res = the_expr._e_eval_lval(env, ipath) ##e needs better __repr__ for its prints of self to be useful # print "fyi (routine): %r l-evals it to %r" % (self, res) # remove when works return res def _e_eval_lval(self, env, ipath): print "fyi or bug? %r didn't expect to have its _e_eval_lval called; just passing it through" % (self,) ## if that happens much and is not an error, remove the print once i understand why -- probably harmless return self._e_eval(env, ipath) pass class property_Expr(internal_Expr): ##k guess, 061119, for attr 'open' in ToggleShow.py; # maybe just a kluge, since mixing properties with exprs is probably a temp workaround, tho in theory it might make sense... # if it can be rationalized then it's good to leave it in, maybe even encourage it. See also class State. """ #doc; canon_expr will turn a python property into this (or maybe any misc data descriptor??) """ def _internal_Expr_init(self): (self._e_property,) = self.args def __repr__(self): return "<%s#%d%s: %r>"% (self.__class__.__name__, self._e_serno, self._e_repr_info(), self._e_property,) def _e_eval(self, env, ipath): assert env #061110 instance = env._self # AttributeError if it doesn't have this [###k uses kluge in widget_env] # if this ever fails, see comments about this construction in constant_Expr and lexenv_Expr -- it might be ok. [070118] prop = self._e_property clas = instance.__class__ ### MIGHT BE WRONG, not sure, might not matter unless someone overrides the prop attr, not sure... res = prop.__get__(instance, clas) #k is this right? we want to call it like the class would to any descriptor. seems to work. ## print "%r evals in %r to %r" % (self, instance, res) return res pass class lexenv_Expr(internal_Expr): ##k guess, 061110 late """ lexenv_Expr(env, expr) evals expr inside env, regardless of the passed env, but without altering the passed ipath. THIS BEHAVIOR IS INCORRECT AND WILL BE CHANGED SOON [070109 comment]. It is opaque to replacement -- even by ExprsMeta, so it should never appear inside a class-attr value [##e should enforce that]. WARNING [070106]: lexenv_Expr will have a major bug once we implement anything that can override dynamic env vars, since it should, but doesn't, inherit dynamic vars from the passed env rather than from its own env argument -- only lexical vars should be overridden by the argument env. For more info see the discussion in widget_env.py docstring. To fix this bug, we need to know how to combine the lexical vars from the argument env with the dynamic ones from the passed env. ### """ def _internal_Expr_init(self): (self._e_env0, self._e_expr0) = self.args def __repr__(self): return "<%s#%d%s: %r, %r>" % (self.__class__.__name__, self._e_serno, self._e_repr_info(), self._e_env0, self._e_expr0,) def _e_call_with_modified_env(self, env, ipath, whatever = 'bug'): # revised 070119 """ [private helper method] Call self._e_expr0.<whatever> with lexenv self._e_env0 and [nim] dynenv taken from the given env """ # about the lval code: #061204 semi-guess; works for now. _e_eval and _e_eval_lval methods merged on 070109. # Generalized to whatever arg for _e_make_in and revised accordingly (for sake of EVAL_REFORM), 070117. #e (should the val/lval distinction be an arg in the _e_eval API? # maybe only for some classes, ie variant methods for fixed arg, another for genl arg??) expr, env, ipath = self._e_burrow_for_find_or_make( env, ipath) ###k more efficient than, and equiv to, _1step submethod = getattr(expr, whatever) res = submethod(env, ipath) #e if exception, print a msg that includes whatever? return res def _e_burrow_for_find_or_make(self, env, ipath): #070119 """ ###redoc, since redundant with Expr implem docstring: Return (expr, env, ipath) in an inner form, where expr has no outermost local ipath or env. [overrides trivial Expr version] Details: General case (Expr): Return (self, env, ipath) if self can be directly instantiated in env at ipath (i.e. if self will find or make itself at exactly that env and ipath, since self has no outermost local mods to them), or an equivalent-for-instantiation (subexpr, locally_modified_env, locally_modified_ipath) if not, where subexpr meets the condition described above, and is formed by stripping off outer env-mods and ipath-mods from self and adding them onto the passed env and ipath. This method implements that general case for lexenv_Expr and lexenv_ipath_Expr. """ new_expr, new_env, new_ipath = self._e_burrow_for_find_or_make_1step( env, ipath) return new_expr._e_burrow_for_find_or_make( new_env, new_ipath) def _e_burrow_for_find_or_make_1step(self, env, ipath): """ [private helper method for _e_burrow_for_find_or_make] """ new_expr = self._e_expr0 lexenv = self._e_env0 # now we want to combine the dynamic part of env with the lexical part of lexenv, to make a modified newenv. new_env = env.dynenv_with_lexenv(lexenv) # env supplies the dynenv part of new_env, lexenv the lexenv part. # WARNING: this is initially a stub which returns lexenv, equiv to the old code here. # PROBLEM: new_env is perhaps often recreated with an equal but not identical value from the same inputs, # but it's not memoized or change-tracked. It can't easily be changed-tracked ... maybe ipath finding handles this... ###k] #e Note: This might be renamed; might be turned into a helper function rather than a method ###e Q: does this ever need to modify ipath, eg move some of it into or out of dynenv? # I don't know; ipath can be thought of as part of the dynenv, so it's proper that it's passed on, anyway. [070118 comment] new_ipath = self._e_locally_modify_ipath(ipath) # differs for lexenv_Expr and lexenv_ipath_Expr return (new_expr, new_env, new_ipath) def _e_locally_modify_ipath(self, ipath): return ipath # differs for lexenv_Expr and lexenv_ipath_Expr # note: the following methods are similar in two classes def _e_eval(self, env, ipath): return self._e_call_with_modified_env(env, ipath, whatever = '_e_eval') def _e_eval_lval(self, env, ipath): return self._e_call_with_modified_env(env, ipath, whatever = '_e_eval_lval') def _e_make_in(self, env, ipath): assert EVAL_REFORM # since it only happens then return self._e_call_with_modified_env(env, ipath, whatever = '_e_make_in') pass # end of class lexenv_Expr class lexenv_ipath_Expr(lexenv_Expr): #070118 """ #doc """ #k Q: will this need to be Symbolic, so getattr_Expr can be formed from it? # A: I think not, since expr.attr should become a getattr_Expr only if expr "stands for an Instance", # like a Symbol or Arg() or Instance() does... this needs to be better understood, formalized, documented # (for example, those macros turn into some sort of OpExpr, not something which says specifically "I stand for an Instance"). # This came up since some code had an expr of this class (lexenv_ipath_Expr) which it thought was an Instance, # and took bleft from it, getting an AttributeError -- but if this class formed getattr_Exprs there would have been # no exception at all. [070212] def _internal_Expr_init(self): (self._e_env0, self._e_local_ipath, self._e_expr0) = self.args def __repr__(self): return "<%s#%d%s: %r, %r, %r>" % (self.__class__.__name__, self._e_serno, self._e_repr_info(), self._e_env0, self._e_local_ipath, self._e_expr0,) def _e_locally_modify_ipath(self, ipath): # WARNING: dup code for this in local_ipath_Expr and here localstuff = self._e_local_ipath # for now, just include it all [might work; might be too inefficient] if 1: # they are getting too long for debug prints already! [070121 morn] intern_ipath( ipath) # no need to use the result of this interning; not using it will make debug prints more understandable localstuff2 = intern_ipath( localstuff) ###e optim: do this in init? is that equivalent?? I think so... ######e # print "interned %r to %r" % (localstuff, localstuff2) # works localstuff = localstuff2 return (localstuff, ipath) pass # lexenv_ipath_Expr class local_ipath_Expr(lexenv_Expr): #070122 experimental """ experimental -- just add some local ipath components to the ipath -- no change in env """ #e probably, these 3 classes should be reorg'd into abstract/mixin1/mixin2/3reals, # so the shared code for doing more stuff (to env or to ipath) comes from mixins def _internal_Expr_init(self): (self._e_local_ipath, self._e_expr0) = self.args def __repr__(self): return "<%s#%d%s: %r, %r>" % (self.__class__.__name__, self._e_serno, self._e_repr_info(), self._e_local_ipath, self._e_expr0,) def _e_burrow_for_find_or_make_1step(self, env, ipath): """ [overrides lexenv_Expr implem] [private helper method for _e_burrow_for_find_or_make] """ new_expr = self._e_expr0 new_env = env # differs from superclass new_ipath = self._e_locally_modify_ipath(ipath) return (new_expr, new_env, new_ipath) def _e_locally_modify_ipath(self, ipath): # WARNING: dup code from lexenv_ipath_Expr (differs from superclass) localstuff = self._e_local_ipath if 1: intern_ipath( ipath) localstuff2 = intern_ipath( localstuff) localstuff = localstuff2 return (localstuff, ipath) pass # local_ipath_Expr class eval_Expr(OpExpr): """ An "eval operator", more or less. For internal use only [if not, indices need to be generalized]. Used when you need to put an expr0 inside some other expr1 where it will be evalled later, but you have, instead of expr0, expr00 which will eval to expr0. In such cases, you can put eval_Expr(expr00) in the place where you were supposed to put expr0, and when the time comes to eval that, expr00 will be evalled twice, in the same env and with appropriately differing indices. """ def _e_init(self): pass def _e_call_on_argval(self, env, ipath, whatever = 'bug'): "[private helper method]" # same initial comment as in lexenv_Expr applies here [as of 070117] assert env #061110 (arg,) = self._e_args ## argval = arg._e_eval(env, 'unused-index') # I think this index can never be used; if it can be, pass ('eval_Expr',ipath) index = 'eval_Expr(%s)' % whatever argval = arg._e_eval(env, (index, ipath)) #070109 this index can in fact be used, it turns out. # note: it's correct that we call arg._e_eval regardless of whatever being '_e_eval' or something else. try: submethod = getattr(argval, whatever) res = submethod(env, ipath) ###BUG (likely): if argval varies, maybe this ipath should vary with it -- but I'm not sure in what way. # We probably have to depend on argval to have different internal ipaths when it comes from different sources -- # but presently that's nim (nothing yet wraps exprs with local-ipath-modifiers, tho e.g. If probably should), # so this might lead to incorrectly overlapping ipaths. It's not at all clear how to fix this in general, # and most likely, most uses of eval_Expr are kluges which are wrong in some way anyway, which this issue is # hinting at, since it seems fundamentally unfixable in general. [070109 comment] # update 070118: the plan is that argval will soon have a local-ipath-modifier as its outer layer, # which adds something to the ipath we pass to the submethod above, thus presumably solving the problem # (though until we intern exprs/ipaths and/or memoize the ipath->storage association, it might make things slower). # update 070122: but it doesn't yet solve it for testexpr_21e or _21g, in which an ad-hoc function returns an expr # based on a passed argument (according to a guess at the bug cause). See discussion near testexpr_21g. except: print "following exception concerns argval.%s(...) where argval is %r and came from evalling %r" % \ (whatever, argval, arg) #061118, revised 070109 & 070117 raise ## print "eval_Expr eval%s goes from %r to %r to %r" % (_e_eval_lval and "_lval" or "", arg, argval, res) #untested since lval return res # note: the following methods are similar in two classes def _e_eval(self, env, ipath): return self._e_call_on_argval(env, ipath, whatever = '_e_eval') def _e_eval_lval(self, env, ipath): return self._e_call_on_argval(env, ipath, whatever = '_e_eval_lval') def _e_make_in(self, env, ipath): assert EVAL_REFORM # since it only happens then return self._e_call_on_argval(env, ipath, whatever = '_e_make_in') pass # end of class eval_Expr ##from VQT import V ###e replace with a type constant -- probably there's one already in state_utils ##V_expr = tuple_Expr ### kluge; even once this is defined, in formulas you may have to use V_expr instead of V, # unless we redefine V to not try to use float() on exprs inside it -- right now it's def V(*v): return array(v, Float) # (note: that Float is from Numeric and equals 'd') ##e (maybe we could make a new V def try to use old def, make __float__ asfail so that would fail, then use V_expr if any expr arg) def canon_expr(subexpr):###CALL ME FROM MORE PLACES -- a comment in Column.py says that env.understand_expr should call this... """ Make subexpr an Expr, if it's not already. Simple Python data (e.g. ints, floats, or None, and perhaps most Python class instances) will be wrapped with constant_Expr. Python lists or tuples (or dicts?##e) can contain exprs, and will become their own kind of exprs, or (as a future optim #e) will also be wrapped with constant_Expr if they don't contain exprs. (In future, we might also intern the resulting expr or the input expr. #e) """ if is_Expr(subexpr): # whether pure expr or Instance # bruce 070914 removing the following, since I'm not using it # and it's causing some (runtime) import loops (Exprs <-> instance_helpers): ## if is_Expr_pyclass(subexpr): ## if debug_pref("wrap expr subclasses in constant_Expr?", Choice_boolean_False, prefs_key = True): ## # new feature 070228; not sure if it ever came up before; if it did, this change might cause trouble; ## # therefore print something whenever it's used, for now. In fact, it is likely to be misguided so I'll make it a debug_pref. ## print "canon_expr treating this expr class as a constant: %r" % (subexpr,) ##e print_compact_stack? ## assert same_vals(subexpr, subexpr) ## return constant_Expr(subexpr) ## elif debug_pref("pseudo-customize IorE subclasses?", Choice_boolean_False, prefs_key = True): ## # turn it into an equivalent safer expr -- but only if it's in IorE ## from exprs.instance_helpers import InstanceOrExpr #k safe?? ## if issubclass(subexpr, InstanceOrExpr): ## res = subexpr( _KLUGE_fakeoption = None ) ## print "canon_expr turning expr class %r into %s" % (subexpr,res) #### remove when thought to be safe? printfyi? ## return res ## else: ## print "canon_expr not changing expr class %r" % (subexpr,) #### if subexpr._e_serno == _debug_e_serno: print_compact_stack( "_debug_e_serno %d seen as arg %r to canon_expr, at: " % (_debug_e_serno, subexpr)) return subexpr # true for Instances too -- ok?? [070122: see cmt in IorE._e_eval when EVAL_REFORM, which accomodates this] ## ## elif issubclass(subexpr, Expr): # TypeError: issubclass() arg 1 must be a class ## elif isinstance(subexpr, type) and issubclass(subexpr, Expr): ## return subexpr # for _TYPE_xxx = Widget2D, etc -- is it ever not ok? ####k elif isinstance(subexpr, type([])): return list_Expr(*subexpr) ###k is this always correct? or only in certain contexts?? # could be always ok if list_Expr is smart enough to revert back to a list sometimes. #e analogous things for tuple and/or dict? not sure. or for other classes which mark themselves somehow?? elif isinstance(subexpr, type(())): return tuple_Expr(*subexpr) ###e should optim when it's entirely constant, like (2,3) # [needed for (dx,dy) in Translate(thing, (dx,dy)), 061111] ## elif isinstance(subexpr, type(V(1,1.0))): ###e ## # try to handle things like V(dx,dy) too... turns out this is not yet supportable, probably never. ## # so this is more harmful than good -- a real V() is a constant, since it can't contain exprs anyway -- ## # if we redefine V to not require floats, we might as well go all the way to V_expr inside it. ## printnim("kluge: turning V(expr...) into a tuple_Expr for now!") #####@@@@@ ## return tuple_Expr(*subexpr) #e replace with NumericArray_expr or V_expr or so elif isinstance(subexpr, property): res = property_Expr(subexpr) ## print "canon_expr wrapping property %r into %r" % (subexpr, res) return res else: #e assert it's not various common errors, like expr classes or not-properly-reloaded exprs #e more checks? # assume it's a python constant #e later add checks for its type, sort of like we'd use in same_vals or so... in fact, how about this? assert same_vals(subexpr, subexpr) ###e at first i thought: we should delve into it and assert you don't find Exprs... but delve in what way, exactly? # if you have a way, you understand the type, and then just handle it instead of checking for the unmet need to handle it. # we could let data objects tell us their subobjs like they do for Undo (I forget the details, some way of scanning kids) return constant_Expr(subexpr) pass # == class Symbol(SymbolicExpr): """ A kind of Expr that is just a symbol with a given name. Often used via the __Symbols__ module. """ # Default values of instance variables. # These are normally set (optionally) after __init__, by the code that creates the symbols, # and never changed after that. _e_sym_constant = False # caller can set this to True if it's normal for this symbol to eval to itself (not deserving of warning) _e_eval_forward_to = _UNSET_ # caller can set this to something if it wants this symbol to evaluate to the same thing as that does. def __init__(self, name = None, doc = None): self._e_init_e_serno() if name is None: name = "?%s" % compact_stack(skip_innermost_n = 2).split()[-1] # kluge - show line where it's defined self._e_name = name self.__doc__ = doc # default is None, for a Symbol with no individual docstring. # (self.__doc__ can optionally be set by caller after we return) return def __str__(self): return self._e_name def __repr__(self): ## return 'Symbol(%r)' % self._e_name ##e should only use following form when name looks like a Python identifier! return 'S.%s' % self._e_name def __eq__(self, other): #k probably not needed, since symbols are interned as they're made return self.__class__ is getattr(other, '__class__', None) and self._e_name == other._e_name #070304 bugfix: survive not hasattr(other, '__class__') [maybe not tested since i'm not sure if this is ever used] def __ne__(self, other): return not (self == other) def _e_eval(self, env, ipath): """ As with super _e_eval, our job is: Imagine that env's replacements should be done in self, and that the resulting modified self should be instantiated within the object which is env's replacement for _self. Then evaluate the result at the current time. For self a symbol other than _self, that just means, do the replacement, worrying about symbols inside that value (in terms of repeated replacement if any), then evaluate the result. I am not sure what context the replacements are in, whether this can ever be used to create an expr result, whether _self is a special case, etc, so for now, print warnings (or maybe asfail) if any of those cases arise. For self the symbol _self, this happens all the time with env's value for _self being an instance, and what we want to return is that very instance. This may mean that technically env's value should be a constant expr which we should eval here, *or* that we should have a special case for _self here, *or* that we should never be recursively evaluating replacements here. For now, I'll handle this by not recursively evaluating, warning if _self doesn't get an Instance, and warning if self is not _self. [061105] """ #pre-061105 comments, probably obs & wrong: ## print "how do we eval a symbol? some sort of env lookup ..." #[later 061027: if lookup gets instance, do we need ipath? does instance have it already? (not same one, for sure -- this is # like replacement). If lookup gets expr, do we instantiate it here? For now, just make _self work -- pretend expr was already # instantiated and in the place of _self it had an instance. So, when we hit an instance with _e_eval, what happens? # If we believe that getattr_Expr, it returns a value which is "self" which is exactly the same instance -- # i.e. Thing instance evals to itself. This is not like OpExpr instance which evals to a value. I suppose If also evals # to not itself.... this is related to what CLE wanted to do, which is eval something to a "fixed instance" -- let's review # the API it proposed to use for calling that utility.... that's in GlueCodeMemoizer, it does instance.eval() but I knew it # might be misnamed, but I did think no point in passing it args (instance already knows them). I know some instances define # _value (like Boxed), maybe .eval() would go into it... probably it would. BTW, What if ._value is an expr (not Instance)? # What if we call it _e_value and it's defined on some expr?? ####@@@@ # Summary guess: look up sym, then eval result with same args. If instance, they have a method which looks for _value, # defaults to self. This method might be _e_eval itself... or have some other name.] #older comments: ## -- in the object (env i guess) or lexenv(?? or is that replacement??) which is which? # maybe: replacement is for making things to instantiate (uses widget expr lexenv), eval is for using them (uses env & state) # env ("drawing env") will let us grab attrs/opts in object, or things from dynenv as passed to any lexcontaining expr, i think... if self._e_eval_forward_to is not _UNSET_: printfyi("forwarding %r to value of %r" % (self, self._e_eval_forward_to))### return env._e_eval( self._e_eval_forward_to, ipath) #070131; note this forwarding is not overridable by env (experimental) val = env.lexval_of_symbol(self) # note: cares mainly or only about self._e_name; renamed _e_eval_symbol -> lexval_of_symbol # but I'm not sure it's really more lexenv than dynenv, at least as seen w/in env... [061028] ####@@@@ # val is an intermediate value, needs further eval [this old comment might be wrong; see docstring -- 061105] if self == val: # return self (perhaps wrapped), after perhaps printing a warning if self is not val: print "warning: %r and %r are two different Symbols with same name, thus equal" % (self, val) if EVAL_REFORM:#070117 if not self._e_sym_constant: #070131 added this cond (and attr) print "warning: Symbol(%r) evals to itself [perhaps wrapped by _e_eval_to_expr]" % self._e_name return self._e_eval_to_expr(env, ipath, self) else: if not self._e_sym_constant: #070131 added this cond (and attr) print "warning: Symbol(%r) evals to itself" % self._e_name return self # reached only when self != val assert self != val # remove when works if self._e_name not in ('_self', '_my', '_app'): #k Q: does this also happen for a thisname, _this_<classname> ? print "warning: _e_eval of a symbol other than _self or _my is not well-reviewed or yet well-understood:", self._e_name # e.g. what should be in env? what if it's an expr with free vars incl _self -- are they in proper context? # see docstring for more info [061105] ## pre-061105 code did: return val._e_eval(env, ipath) # and that might be needed for other syms -- not sure yet [061105] return val def _e_make_in(self, env, ipath):#070131 assert self._e_sym_constant, "only constant Symbols can be instantiated, not %r" % self # and (at least for now) they instantiate to themselves, like other constants do return self def _e_free_in(self, sym): ###k might be obs [070131 comment] """ General case: Return True if Expr self contains sym (Symbol or its name) as a free variable, in some arg or option value. For this class Symbol, that means: Return True if sym is self or self's name. [overrides super version] """ return (sym is self) or (sym == self._e_name) pass # end of class Symbol # note about Instance, Arg, Option, ArgOrOption, State -- they are now in another file to ease import-recursion issues. # end
NanoCAD-master
cad/src/exprs/Exprs.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Set.py - provide the assignment action called Set, and (for now) the deprecated older variant SetStateRefValue. @author: bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. Note: this operation name is important enough to override any worry about the potential name conflict with something related to mathematical set-theory sets or Python dict-like sets. And the use on arg1 being an lvalue is important enough to not worry much if arg1 being a stateref is harder to use -- now done in SetStateRefValue, might later be done in Set(stateref.value, ...). History, status, plans: first implem of SetStateRefValue written in controls.py, moved here 061203, renamed from Set to SetStateRefValue 061204. adding Set with arg1 an lval eg a getattr_Expr, 061204; works in testexpr_16 """ from exprs.attr_decl_macros import Arg, LvalueArg from exprs.instance_helpers import InstanceOrExpr from exprs.ExprsConstants import StateRef from exprs.__Symbols__ import Anything class Action(InstanceOrExpr): #061204 ; #e might refile to a new file actions.py """#doc; abstract superclass and coercion-type """ def __call__(self, *args, **kws): if self._e_is_instance: assert not args assert not kws ## self._i_do_action(*args, **kws) #k correct to pass args? # or just assert them missing right here? # [the latter for now; could let subclass define _i_do_action_with_args later, or put the args into its env somehow; # but for now i think no args will ever get passed, anyway.] self._i_do_action() return else: return super(Action, self).__call__(*args, **kws) # presumably a customized or arg-filled pure expr #k Q: could I also just say super(Action, self)(*args, **kws), without .__call__ ?? # Same Q for .__getattr__('attr') vs .attr, etc. # I am not sure they're equiv if super doesn't explicitly define the special method (or for that matter, if it does). # For all I know, they'd be infrecurs. In fact that seems likely -- it seems to be what I know is true for getattr. pass def _i_do_action(self): "#doc" assert 0, "subclass must implement" pass # SetStateRefValue(choiceref, choiceval) - instantiates to a py function (or Action wrapping that) that when called does cr.value = cv # note: compared to some other files' ideas (for Set), this takes a stateref rather than an lval as arg1 -- might be wrong [is wrong] # [a suffix of that comment is duped in two files] class SetStateRefValue(Action): # experimental, 061130; renamed from Set to SetStateRefValue 061204; deprecated """#doc """ stateref = Arg(StateRef) val = Arg(Anything) def _i_do_action(self): print "%r (deprecated, fyi): setting %r.value = %r" % (self, self.stateref , self.val)### if self.stateref == 0: # kluge: debug print for testexpr_16; this happens because SetStateRefValue is trying to be two things at once re arg1, # lval like _self.var to set, or stateref (this code, used in ToggleShow). print "that stateref of 0 came from this expr arg:", self._e_args[0] self.stateref.value = self.val return pass class Set(Action): # adding Set with arg1 an lval eg a getattr_Expr, 061204; untested, see testexpr_16 """Set( variable, value) is an Action which sets variable to value. More precisely, variable should be an expr that can "evaluate to a settable lvalue", e.g. _self.attr or obj.attr or obj-expr[index-expr] [latter case is nim as of 061204], and value can be any ordinary evaluatable expr. When this Action is performed, it calls lval.set_to(val) for lval the current lvalue-object corresponding to variable, and val the current value of value. See also SetStateRefValue (deprecated). """ var = LvalueArg(Anything) # LvalueArg is so macro-writers can pull in lvalue args themselves, easily; experimental; Option version? val = Arg(Anything) def _i_do_action(self): var = self.var val = self.val # print "%r: calling on our lval-object, %r.set_to(%r)" % (self, var , val) try: var.set_to( val) # .set_to is in api for lval-objects of this kind -- not the same kind as "exprs plus _self" (for now) ###e probably we should rename set_to -> set_value -- see StateRefInterface [070312] except: print "following exception in var.set_to( val) in %r concerns var = %r" % (self, var,) raise return pass # end
NanoCAD-master
cad/src/exprs/Set.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ attr_decl_macros.py -- Instance, Arg, Option, ArgOrOption, State @author: Bruce @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. [was in Exprs.py when developed, before State; split into this file 061203 to ease recursive import issues with State] """ # Symbols for private or semi-private use # (note, other modules that need these also import them directly from __Symbols__) from exprs.__Symbols__ import _E_ATTR, _E_REQUIRED_ARG_, _E_DFLT_FROM_TYPE_, _self from exprs.py_utils import printnim from exprs.Exprs import internal_Expr, OpExpr from exprs.Exprs import call_Expr from exprs.Exprs import eval_to_lval_Expr from exprs.Exprs import getattr_Expr from exprs.Exprs import hold_Expr from exprs.Exprs import tuple_Expr from exprs.Exprs import is_pure_expr from exprs.Exprs import constant_Expr from exprs.Exprs import eval_Expr from exprs.Exprs import canon_expr from exprs.Exprs import EVAL_REFORM from exprs.ExprsMeta import data_descriptor_Expr_descriptor from exprs.StatePlace import set_default_attrs from exprs.__Symbols__ import Anything # == # stubs for StateArg etc are defined lower down # == def Instance(expr, _index_expr = _E_ATTR, _lvalue_flag = False, _noinstance = False, doc = None): """ This macro is assigned to a class attr to declare that its value should be a lazily-instantiated Instance of expr (by default). Assuming the arg is an expr (not yet checked?), turn into the expr _self._i_instance(hold_Expr(expr), _E_ATTR), which is free in the symbols _self and _E_ATTR. [#e _E_ATTR might be changed to _E_INDEX, or otherwise revised.] This function is also used internally to help implement the Arg and Option macros; for their use only, it has a private _index_expr option, giving an index expr other than _E_ATTR for the new Instance (which is used to suggest an ipath for the new instance, relative to that of self). Similarly, it helps implement ArgExpr etc, for whose sake it has a private option _noinstance. Devel scratch comment: Note that the Arg and Option macros may have handy, not expr itself, but a "grabarg" expr which needs to be evaluated (with _self bound) to produce the expr to be instantiated. What should they pass?? eval_Expr of the expr they have. [#doc - reword this] Other private options: _lvalue_flag, _noinstance (_noinstance is only supported when EVAL_REFORM is true) """ if doc: printnim("Instance doc is not saved anywhere; should turn into a note to formulascanner to save it as metainfo, maybe")#e printnim("review: same index is used for a public Option and a private Instance on an attr; maybe ok if no overlap possible???")##e global _self # not needed, just fyi if EVAL_REFORM: if _lvalue_flag: assert not _noinstance # since it makes no sense to ask for this then, AFAIK (if ok for one, ok for all -- see below) #070119 bugfix to make Set(var,val) work again (eg when clicking a checkbox_pref) # rather than evalling var to its current value. This means _lvalue_flag never gets passed to _i_instance. res = call_Expr( getattr_Expr(_self, '_i_instance'), eval_to_lval_Expr(expr), _index_expr ) ####e if this works, then try simplifying it to remove the _i_instance call! (assuming the lval is never needing make) # (or given this macro's name, maybe it makes more sense for LvalueArg to manage to not call it...) elif _noinstance:#070122 # we ignore _index_expr, but callers can't help but pass one, so don't complain when they do return expr # i.e. Instance(expr) == expr -- not useful directly, but useful as a passthru option from Arg etc. else: res = call_Expr( getattr_Expr(_self, '_i_instance'), expr, _index_expr ) else: assert not _noinstance, "bug: _noinstance is only supported when EVAL_REFORM is true" res = call_Expr( getattr_Expr(_self, '_i_instance'), hold_Expr(expr), _index_expr, _lvalue_flag = _lvalue_flag ) return res _arg_order_counter = 0 #k might not really be needed? ##e problems w/ Arg etc as implem - they need an expr, which can be simplified as soon as an instance is known, # but we don't really have smth like that, unless we make a new Instance class to support it. # they need it to calc the index to use, esp for ArgOrOption if it depends on how the arg was supplied # (unless we implem that using an If or using default expr saying "look in the option" -- consider those!) def Arg( type_expr, dflt_expr = _E_REQUIRED_ARG_, _attr_expr = None, _arglist = False, **moreopts): ### [update 061204: i think this cmt is obs, not sure:] IMPLEM _E_REQUIRED_ARG_ - do we tell _i_instance somehow? ###e see new notes at end of file about how to reform Arg into a more coherent object, useful in wider contexts... [070321] """ To declare an Instance-argument in an expr class, use an assignment like this, directly in the class namespace: attr = Arg( type, optional default value expr ) Order matters (specifically, execution order of the Arg macros, or maybe only of the exprs containing them, while Python is executing a given class definition, before the metaclass's __new__ runs); those attrs which are not already defined as args in superclasses [nim] are appended to the inherited arglist, whose positions are counted from 0. (Handling anything about args in superclasses is NIM. ##e) The index of the instance made from this optional argument will be its position in the arglist (whether or not the arg was supplied or the default value expr was used). If the default value expr is not supplied, there is no default value (i.e. the arg is required). If it is supplied, it is processed through canon_expr (as if Arg was an Expr constructor), unless it's one of the special case symbols (meant only for private use by this family of macros) _E_REQUIRED_ARG_ or the other _E_ one.##doc [_attr_expr is a private option for use by ArgOrOption. So is _lvalue_flag and ###NIM _noinstance (in moreopts).] [_arglist is a private option for use by ArgList.] """ global _arg_order_counter _arg_order_counter += 1 required = (dflt_expr is _E_REQUIRED_ARG_) argpos_expr = _this_gets_replaced_with_argpos_for_current_attr( _arg_order_counter, required, _arglist ) # Implem note: # _this_gets_replaced_with_argpos_for_current_attr(...) makes a special thing to be noticed by the FormulaScanner # and replaced with the actual arg order within the class (but the same within any single attr). # ExprsMeta can do that by scanning values in order of Expr construction. # But it has to worry about two vals the same, since then two attrs have equal claim... # it does that by asserting that a given _arg_order_counter corresponds to only one attr. ########@@@@@@@nim # FYI, the other possible use for _arg_order_counter would be to assert that it only increases, # but this is not obviously true (or useful) in undoc but presently supported cases like # attr = If(cond, Arg(type1), Arg(type2)) # (which the present code treats as alternative type decls for the same arg position). ##printnim("asserting that a given _arg_order_counter corresponds to only one attr -- in a better way than ive_seen kluge below")####@@@@@ attr_expr = _attr_expr # what about current attr to use in index for arg instance and/or # in finding the arg expr in an instance (the replacement instance for _self) -- # this is None by default, since _E_ATTR (the attr we're on) shouldn't affect the index, # in this Arg macro. When we're used by other macros they can pass something else for that. return _ArgOption_helper( attr_expr, argpos_expr, type_expr, dflt_expr, _arglist = _arglist, **moreopts) def LvalueArg(type_expr, dflt_expr = _E_REQUIRED_ARG_): #061204, experimental syntax, likely to be revised; #e might need Option variant too """ Declare an Arg which will be evaluated not as usual, but to an lvalue object, so its value can be set using .set_to, etc. """ return Arg(type_expr, dflt_expr, _lvalue_flag = True) def _ArgOption_helper( attr_expr, argpos_expr, type_expr, dflt_expr, _lvalue_flag = False, _arglist = False, **moreopts ): """ [private helper for Arg, Option, and maybe ArgOrOption] attr_expr should be None, or some sort of expr (in practice always _E_ATTR so far) that will get replaced by a constant_Expr for the current attr (in ExprsMeta's FormulaScanner), according to whether the current attr should be part of the index and a public option-name for supplying the arg (we make sure those conditions are the same). [#e Note that if someday we wanted to include f(attr) in the index, but still use attr alone as an option name, we'd have to modify this to permit both f(attr) (or f) and attr to be passed.] argpos_expr should similarly be None, or some sort of expr (in practice a private subclass of internal_Expr) that will get replaced by a constant_Expr for the argument position (an int) that should be allocated to the current attr's arg (determined in ExprsMeta's FormulaScanner by allocating posns 0,1,2,etc to newly seen arg-attrs, whether or not the attr itself is public for that arg). type_expr ###doc, passed herein to canon_type dflt_expr ###doc, can also be _E_DFLT_FROM_TYPE_ or [handled in caller i think, but survives here unmatteringly] _E_REQUIRED_ARG_; will be passed through canon_expr _lvalue_flag is a private option used by LvalueArg. _arglist is a private option used by ArgList. """ if _lvalue_flag: printnim("_lvalue_flag's proper interaction with dflt_expr is nim") # in all cases below ### guess: we want it to be an expr for a default stateref global _self # fyi type_expr = canon_type( type_expr) printnim("can type_expr legally be self-dependent and/or time-dependent? ###k I guess that's nim in current code!")#070115 comment if _arglist: # new feature 070321. The type is applied to each element, but the default value is for the entire list -- # OTOH, when would it ever be used, since even if no args are supplied, the list can be formed?? # Probably it would only be used when the list was 0 length, and could meaningfully be [], (), or another list-like thing... # this is all a guess and I probably won't even review this code for this issue now, unless it fails when tried. ####k type_expr = tuple_Expr(type_expr) # type-coerce the value to a list of the given type [070321 guess] ###e or list_Expr??? if dflt_expr is _E_DFLT_FROM_TYPE_: dflt_expr = default_expr_from_type_expr( type_expr) ## note [070115], this would be impossible for time-dependent types! and for self-dep ones, possible but harder than current code. assert is_pure_expr(dflt_expr) #k guess 061105 else: dflt_expr = canon_expr(dflt_expr) # hopefully this finally will fix dflt 10 bug, 061105 guesshope ###k [works for None, 061114] assert is_pure_expr(dflt_expr) # not sure this is redundant, since not sure if canon_expr checks for Instance ###k printnim("not sure if canon_expr checks for Instance") # Note on why we use explicit call_Expr & getattr_Expr below, # rather than () and . notation like you can use in user-level formulae (which python turns into __call__ and getattr), # to construct Exprs like _self._i_grabarg( attr_expr, ...): # it's only to work around safety features which normally detect that kind of Expr-formation (getattr on _i_* or _e_*, # or getattr then call) as a likely error. These safety features are very important, catching errors that would often lead # to hard-to-diagnose bugs (when our code has an Expr but thinks it has an Instance), so it's worth the trouble. held_dflt_expr = hold_Expr(dflt_expr) # Note, this gets evalled back into dflt_expr (treated as inert, may or may not be an expr depending on what it is right here) # by the time _i_grabarg sees it (the eval is done when the call_Expr evals its args before doing the call). # So if we wanted _i_grabarg to want None rather than _E_REQUIRED_ARG_ as a special case, we could change to that (there & here). grabopts = {} if _arglist: grabopts.update(dict(_arglist = constant_Expr(_arglist))) grabarg_expr = call_Expr( getattr_Expr(_self, '_i_grabarg'), attr_expr, argpos_expr, held_dflt_expr, **grabopts ) # comments 070115: # - This will eval to an expr which depends on self but not on time. We could optim by wrapping it # (or declaring it final) in a way which effectively replaced it with its value-expr when first used. # (But it's not obvious where to store the result of that, since the exprs being returned now are assigned to classes # and will never be specific to single selfs. Do we need an expr to use here, which can cache its own info in self?? # Note: AFAIK, self will be the same as what _self gets replaced with when this is used. (We ought to assert that.) ###e) # - Further, grabarg_expr is probably supposed to be wrapped *directly* by eval_Expr, not with type_expr inside. I think I'll # make that change right now and test it with EVAL_REFORM still False, since I think it's always been required, as said # in other comments here. DOING THIS NOW. if attr_expr is not None and argpos_expr is not None: # for ArgOrOption, use a tuple of a string and int (attr and argpos) as the index index_expr = tuple_Expr( attr_expr, argpos_expr ) elif attr_expr is None and argpos_expr is None: assert 0, "attr_expr is None and argpos_expr is None ..." elif attr_expr is not None: # for Option, use a plain attr string as the index index_expr = attr_expr else: assert argpos_expr is not None # for Arg, use a plain int as the index # (note: ExprsMeta replaces argpos_expr with that int wrapped in constant_Expr, but later eval pulls out the raw int) index_expr = argpos_expr # see if this is fixed now, not that it means much since we were using a stub... but who knows, maybe the stub was buggy # and we compensated for that and this could if so cause a bug: ## printnim("I suspect type_expr (stub now) is included wrongly re eval_Expr in _ArgOption_helper, in hindsight 061117") ## ### I suspect the above, because grabarg expr needs to be evalled to get the expr whose type coercion we want to instantiate res = Instance( _type_coercion_expr( type_expr, eval_Expr(grabarg_expr) ), _index_expr = index_expr, _lvalue_flag = _lvalue_flag, **moreopts ) # note: moreopts might contain _noinstance = True, and if so, Instance normally returns its first arg unchanged # (depending on other options). # 070115 replaced eval_Expr( type_expr( grabarg_expr)) with _type_coercion_expr( type_expr, eval_Expr(grabarg_expr) ) return res # from _ArgOption_helper def _type_coercion_expr( type_expr, thing_expr): ###e should we make this a full IorE (except when type_expr is Anything?) in order to let it memoize/track its argvals? # (can import at runtime if nec.) """ [private helper for Arg, etc] [#e stub] Given an expr for a type and an expr [to be evalled to get an expr?? NO, caller use eval_Expr for that] for a thing, return an expr for a type-coerced version of the thing. """ if type_expr is None or type_expr is Anything: return thing_expr # ArgList causes us to get here as well: # print "ignoring this type_expr for now: %r" % (type_expr,) # <tuple_Expr#1833: (S.Anything,)> return thing_expr assert 0, "this will never run" # until we fix canon_type to not always return Anything!! print "TypeCoerce is nim, ignoring",type_expr #####070115 ###IMPLEM TypeCoerce from xxx import TypeCoerce # note, if xxx == IorE's file, runtime import is required, else recursive import error; use new file?? return TypeCoerce( type_expr, thing_expr) # a new expr, for a helper IorE -- this is an easy way to do some memoization optims (almost as good as optim for finalization), # and permit either expr to be time-dependent (not to mention self-dependent) [070115] class _this_gets_replaced_with_argpos_for_current_attr(internal_Expr):#e rename? mention FormulaScanner or ExprsMeta; shorten def _internal_Expr_init(self): (self._e__arg_order_counter, self._e_is_required, self._e_is_arglist) = self.args # _e_is_arglist added 070321 # first arg not presently used, might be obs here and even in caller ##k self.attrs_ive_seen = {} def _e_override_replace(self, scanner): """ This gets called by a formula scanner when it hits this object in an expr... it knows lots of private stuff about FormulaScanner. """ attr = scanner.replacements[_E_ATTR] # a constant_Expr, or an indication of error if this happens (maybe missing then?) attr = attr._e_constant_value if 1: # quick & dirty check for two attrs claiming one arg... come to think of it, is this wrong re inclusion? # no, as long as overall replace (of this) happens before this gets called, it'll be ok. # but, a better check & better errmsg can be done in scanner if we pass our own args to it. # WAIT, i bet this won't actually catch the error, since the replace would actually occur... have to do it in the scanner. printnim("improve quick & dirty check for two attrs claiming one arg (it may not even work)")###e self.attrs_ive_seen[attr] = 1 assert len(self.attrs_ive_seen) <= 1, "these attrs claim the same arg: %r" % self.attrs_ive_seen.keys() # WARNING: if this works, it will break the use of Arg in future things like lambda_expr or _e_extend # where the same Arg() object might get passed to multiple class/attr contexts in runtime-generated exprs with Arg decls. # If/when that happens, this object needs to be made immutable, which can be done by removing this code (inside 'if 1'), # since it's probably either not working or redundant, according to the comments above and my best guess now. [070321 comment] required = self._e_is_required arglist = self._e_is_arglist pos = scanner.argpos(attr, required, arglist = arglist) res = constant_Expr(pos) # this gets included in the scanner's processed expr return res def _e_eval(self, *args): assert 0, "this %r should never get evalled unless you forgot to enable formula scanning (I think)" % self ##k pass def Option( type_expr, dflt_expr = _E_DFLT_FROM_TYPE_, **moreopts): """ To declare a named optional argument in an expr class, use an assignment like this, directly in the class namespace, and (by convention only?) after all the Arg macros: attr = Option( type, optional default value) Order probably doesn't matter. The index of the instance made from this optional argument will be attr (the attribute name). If the default value is needed and not supplied, it comes from the type. """ global _E_ATTR # fyi argpos_expr = None attr_expr = _E_ATTR return _ArgOption_helper( attr_expr, argpos_expr, type_expr, dflt_expr, **moreopts) def ArgOrOption(type_expr, dflt_expr = _E_DFLT_FROM_TYPE_, **moreopts): """ means it can be given positionally or using its attrname [#doc better] index contains both attr and argpos; error to use plain Arg after this in same class (maybe not detected) """ global _E_ATTR # fyi attr_expr = _E_ATTR return Arg( type_expr, dflt_expr, _attr_expr = attr_expr, **moreopts) def ArgExpr(*args, **moreopts): ## return Arg(*args, _noinstance = True) -- syntax error, i don't know why moreopts['_noinstance'] = True #k let's hope we always own this dict return Arg(*args, **moreopts) def OptionExpr(*args, **moreopts): moreopts['_noinstance'] = True return Option(*args, **moreopts) def ArgOrOptionExpr(*args, **moreopts): moreopts['_noinstance'] = True return ArgOrOption(*args, **moreopts) def ArgList(*args, **moreopts): #070321 [tentatively replaces the scratch file ArgList.py] # status, 070321 9:30pm: works, except for bad de-optim mentioned below, # and unexplained 'expr or lvalflag for instance changed' in _30i. ###BUGS (not showstoppers) moreopts['_arglist'] = True ###WARNING: there is a bad de-optim due to this, explained in tuple_Expr._e_make_in -- no per-arglist-elt instance caching. # WARNING: the implementing code for this uses tuple_Expr, not list_Expr. # But args which take explicit lists typically declare their types as list_Expr, # and formulae to construct them typically use list_Expr. # Since all these are intended to be immutable lists # (though perhaps time-dependent ones, with lengths changing even by insertion # due to time-dependent formulae constructing them), # my guess is that eventually we'll just make list_Expr a synonym for tuple_Expr. # But for now, they are distinct Exprs which eval to python lists/tuples respectively # (when they contain nothing that needs instantiation). return Arg(*args, **moreopts) #e ArgListOrOption? it would let you pass a list inline as args, *or* (not and) as a list_Expr- or list- valued named option, # or (ignoring the difference I think) a tuple_Expr- or tuple- valued one. #e ArgExprList? it would let you pass a list of expr formulae inline, turning them into a tuple_Expr, instantiable to a list and/or # usable as a list of exprs (e.g. they might get individually wrapped before being instantiated, or get filtered or chosen from, etc) # But, we *won't* define the names: ArgListExpr (I think)... don't know about any mix of ArgListOrOption and Expr. # Don't know yet about any mixes of State and Expr, or State and Formula, either. [070321] # == # stubs: def ArgStub(*args): return Arg(Anything) ## ArgList = ArgStub #e see also ArgList.py InstanceList = InstanceDict = ArgStub StateArg = Arg ###STUB - state which can be initially set by an arg... # there may be some confusion about whether we set it to an arg formula & later replace with a set formula, # or set it to a snapshot in both cases. Review all uses -- maybe split into two variants. [070131] #e if it's snapshot version (as I usually thought), # StateArg etc can perhaps be implemented as State with a special dflt expr which is Arg (if scanner sees that deep); # index ought to be correct! StateOption = Option ###STUB StateArgOrOption = ArgOrOption ###STUB # StateInstance = Instance? Probably not... see class State (not always an Instance). #e ProducerOf? ExprFor? #e related macros: # - Instance(expr, optional index) # default index is attr we assign it to, you can replace or extend that (only replace is implem) # - InstanceDict(value-expr, optional key-set or key-sequence, optional key-to-index-func) # these exprs can be in _i/_key by default # - InstanceList(value-expr, number-of-elts, optional key-to-index-func) ## digr: a reason i try to say "range" for "domain" is the use of Python range to create the list of domain indices! # - Arg variants of those - replace expr with type, inferring expr as type(arg[i]) for i inferred as for Instance, # but also come in an order that matters; so: # - Arg(type, optional default-value expr) # - ArgList(type-expr) # applies to the remaining args; index should be (attr, posn in this list), I think # - ArgDict would apply to the remaining kwargs... not sure we'll ever want this # == def canon_type(type_expr):###stub [note: this is not canon_expr!] """ Return a symbolic expr representing a type for coercion """ return Anything # for now! when we implement TypeCoerce, revise this printnim("canon_type is a stub; got %r" % type_expr) ## so far: Widget2D, int return lambda x:x #stub ## # special cases [nim] ## for k,v in {int:Int, float:Float, str:String}.iteritems(): ## if type_expr is k: ## type_expr = v ## break ## ### not sure if for Widget2D or Color or Width we return that, or TypeCoerce(that), or something else ## assert is_pure_expr(type_expr) ## return type_expr #stub; needs to work for builtin types like int, ## # and for InstanceOrExpr subclasses that are types (like Widget -- or maybe even Rect??) ## # note that the retval will get called to build an expr, thus needs to be in SymbolicExpr -- will that be true of eg CLE? ## # if not, then some InstanceOrExpr objs need __call__ too, or constructor needs to return a SymbolicExpr, or so. def default_expr_from_type_expr(type_expr): #061115 ## note [070115], this would be impossible for time-dependent types! and for self-dep ones, possible but harder than current code. """ #doc """ ## assert type_expr is Stub # only permitted for these ones; not even correct for all of them, but surely not for others like int # Stub is not defined here, never mind return canon_expr(None) # stub; only right for Action, wrong for int, str, etc ###e might need revision for ArgList? # == class data_descriptor_Expr(OpExpr): def _e_init(self): assert 0, "subclass of data_descriptor_Expr must implement _e_init" def __repr__(self): # class data_descriptor_Expr # same as in OpExpr, for now ###e if we end up knowing our descriptor or its attr, print that too return "<%s#%d%s: %r>"% (self.__class__.__name__, self._e_serno, self._e_repr_info(), self._e_args,) pass class State(data_descriptor_Expr): """ """ # note: often referred to as "State macro", even though we don't presently say "def State" # (except right here as search engine bait) # TODO: big optim: make a variant which just stores the LvalForState object directly in instance.__dict__[attr]. # That requires replacing not only self._e_attrholder but its API -- now it returns something whose .attr # should be accessed; instead the callers need rewriting to just find the LvalForState object and use it. # We can then use that variant exclusively unless we want to support old-style reloading in pure exprs tests, # and reloading is disabled anyway, so the old style would probably never be returned to. And then we might not # need ipath -- not sure (not sure if that's the only use, and we'd still need indexes in single exprs I think). # BTW we'd still want State to be turned into a descriptor rather than actually being one, # since (I think) we still need ExprsMeta to do substitutions in the exprs it contains # (for type (someday) and default value). # [bruce 070831 comment] # experimental, 061201-04; works (testexpr_16); ## # supercedes the prior State macro in Exprs.py [already removed since obs and unfinished, 061203] ## # see also C_rule_for_lval_formula, now obs, meant to be used by that old design for the State macro, ## # but that design doesn't anticipate having an "lval formula", ## # but just has an implicit self-relative object and explicit attrname to refer to. # Note: the default value expr is evaluated only just when it's first needed. # Exception to that: if something like ObjAttr_StateRef asks for our lval using # self._e_StateRef__your_attr_in_obj_ref, we evaluate it then, # even though it won't strictly be needed until something asks that stateref for our value # (if it ever does). I don't know if this can cause problems of too-early eval of that default value. ###REVIEW # [bruce 070816 comment] _e_wants_this_descriptor_wrapper = data_descriptor_Expr_descriptor _e_descriptor = None def _e_init(self): def myargs(type, dflt = None): # note: these args (not kws) are exprs, and already went through canon_expr dflt = dflt ##e stub; see existing stateref code for likely better version to use here ##e do we need to de-expr these args?? (especially type) ##e dflt is reasonable to be an expr so we'll eval it each time, # but do we need code similar to what's in _i_grabarg to do that properly? guess: yes. self._e_state_type = type # not _e_type, that has a more general use as of 070215 self._e_default_val = dflt # note: this does not process _e_kws. self._e_debug was set in OpExpr.__init__. myargs(*self._e_args) # 070831 exploring new State keyword args, for metainfo like minimum for kw in self._e_kws.keys(): if kw != 'doc': print "\n*** unrecognized State keyword arg: %s" % kw continue return def _e_set_descriptor(self, descriptor): """ In general (ie part of API of this method, called by data_descriptor_Expr_descriptor): storing the descriptor is optional, since it's also passed into the get and set calls. In this subclass, we have to store it, since _e_eval can be called without otherwise knowing descriptor.attr. """ if self._e_descriptor is not None: assert self._e_descriptor is descriptor, \ "bug: %r is not None or %r in %r" % \ ( self._e_descriptor, descriptor, self) # bug: this failed for Ninad in class MultipleDnaSegmentResize_EditCommand(DnaSegment_EditCommand) # (not yet committed, won't be in that form); see email he sent me today [bruce 080514] else: self._e_descriptor = descriptor return def _e_get_for_our_cls(self, descriptor, instance): if self._e_debug: print "_e_get_for_our_cls",(self, descriptor, instance, ) if self._e_descriptor is not None: assert self._e_descriptor is descriptor, \ "different descriptors in get: %r stored, %r stored next" % (self._e_descriptor, descriptor) ####@@@@ I predict that will happen due to descriptor copying. (Unless we always access this through py code.) # (no, that was a bug effect -- i mean, as soon as we use subclasses inheriting a State decl.) # I think that copying is not needed in this case. So we probably need to disable it in our class of descriptor. #e [061204] attr = descriptor.attr holder = self._e_attrholder(instance, init_attr = attr) # might need attr for initialization using self._e_default_val return getattr(holder, attr) def _e_set_for_our_cls(self, descriptor, instance, val): if self._e_debug: print "_e_set_for_our_cls",(self, descriptor.attr, instance, val) if self._e_descriptor is not None: assert self._e_descriptor is descriptor, \ "different descriptors in set: %r stored, %r stored next" % (self._e_descriptor, descriptor) # see comment above attr = descriptor.attr holder = self._e_attrholder(instance) # doesn't need to do any initialization return setattr(holder, attr, val) def _e_attrholder(self, instance, init_attr = None): res = instance.transient_state #e or other kind of stateplace # init the default val if needed. if init_attr: attr = init_attr # we need to init the default value for attr, if it's not already defined. ####e OPTIM: this hasattr might be slow (or even buggy, tho i think it'll work # by raising an exception that's a subclass of AttributeError; the slow part is computing args for that every time) if not hasattr(res, attr): val = self._e_eval_defaultValue(attr, instance) #k should I just do setattr(res, attr, val), or is there something special and better about this: ## set_default_attrs(res, {attr : val}) ##k arg syntax set_default_attrs(res, **{attr : val}) # print_compact_stack( "\ndid set_default_attrs of %r, %r, %r: " % (res,attr,val)) val0 = getattr(res, attr) ## assert val is val0, if not (val is val0): print "bug: set_default_attrs should have stored %r at %r in %r, but it has %r" % (val, attr, res, val0) pass return res def _e_eval_defaultValue(self, attr, instance): #070904 split this out # Note [added 070904]: the default value should not depend on the # current values of other State slots (though it can be an expr, # and it's fine if it depends on customized instance parameters). # In current code, I suspect there can be errors (nondeterminisism) # if it does (not sure). This is especially true after today's kluge # (a new call of this helper method), which can evaluate this twice. # See KLUGE 070904 for cleanup suggestions. # Q: Would it be better to change this requirement, to make it say # "it's ok if it tries to depend on the values of other State, # but we eval it with all State slots at their default values # to make sure it's deterministic as used"? # eval the dflt expr here, much like _i_instance does it: val_expr = self._e_default_val index = attr val = instance._i_eval_dfltval_expr(val_expr, index) return val ## AttributeError: no attr '_e_eval_function' in <class 'exprs.attr_decl_macros.State'> -- why does someone want to call this?? # where i am 061203 1023p stopping for night -- wondering that. in testexpr_16. # ##exception in <Lval at 0xff2db70>._compute_method NO LONGER ignored: ## exceptions.AssertionError: recursion in self.delegate computation in <Highlightable#8076(i)> ## [lvals.py:209] [Exprs.py:208] [Exprs.py:400] [instance_helpers.py:677] def _e_eval(self, env, ipath): # 070112 comment: the print below has been there a long time and I don't recall ever seeing it, # so the comment below it guessing it may no longer happen is probably right, # meaning that this method probably never gets called anymore. # # 061204 comments: #e - compare to property_Expr # - it may indicate a bug that we get here at all -- i thought we'd go through our descriptor instead. maybe only thru py code? # - the descriptor knows attr, we don't -- is that ok? no -- it won't let us initialize attr or even find it! # SO WE HAVE TO GET DESCRIPTOR TO SET ITSELF (or at least attr) INSIDE US, exclusively. Doing this now. #######@@@@@@@ ##e - we may also want a variant of this which "evals us as an lvalue, for use as arg1 of Set()" [] assert env #061110 instance = env._self # AttributeError if it doesn't have this [###k uses kluge in widget_env] assert self._e_descriptor is not None descriptor = self._e_descriptor res = self._e_get_for_our_cls(descriptor, instance) print "fyi: _e_eval (not thru __get__, i think) of self = %r in instance = %r gets res = %r" % (self, instance, res) ### I SUSPECT this never happens now that formula-scanner is properly called on us, but I'm not sure, so find out. ### ALSO we'll now see the predicted above bug from copying the descriptor, when we use subclasses inheriting a State decl. return res def _e_StateRef__your_attr_in_obj_ref( self, descriptor, instance): if self._e_debug: print "_e_StateRef__your_attr_in_obj_ref",(self, descriptor, instance) ### TODO (if needed for future debugging): # - also print_compact_stack; # - also set lval._changes__debug_print on this lval. if self._e_descriptor is not None: assert self._e_descriptor is descriptor, \ "different descriptors in _e_StateRef__your_attr_in_obj_ref: %r stored, %r stored next" % \ (self._e_descriptor, descriptor) # see comment above attr = descriptor.attr holder = self._e_attrholder(instance, init_attr = attr) # might need attr for initialization using self._e_default_val # Note: passing init_attr is necessary to prevent a bug, if this is the first access to this lval # before either self._e_get_for_our_cls or self._e_set_for_our_cls. # The symptom of the bug was a mysterious error message, # ... LvalError_ValueIsUnset: access to key '653872' in some lvaldict in # <_attr_accessor(transient,) at 0x29742eb8>, before that value was set ... # which resulted from set_default_attrs never having been run in self._e_attrholder. # [bruce 070816 note and bugfix] ## print "got this holder, now what?", holder ## return setattr(holder, attr, val) lval = holder._attr_accessor__get_lval(attr) # should work for now..... ##KLUGE to assume what class & use private method # print "got lval: %r\n" % (lval,) # lval._changes__debug_print = True # cause various code that touches this lval to print what it does if not hasattr(lval, 'defaultValue'): # KLUGE 070904; needs cleanup and optim (can eval dflt val expr twice); # could be cleaned up easily if it turns out set_default_attrs # always calls _set_defaultValue in the lval, since we could make # that method set this attr, and make the call of it depend on it # not being set. Alternatively we could set a function for computing # default val if needed, on the lval itself. ###REVIEW lval.defaultValue = self._e_eval_defaultValue(attr, instance) return lval pass # end of class State # note: an old def of State, never working, from 061117, was removed 061203 from cvs rev 1.88 of Exprs.py # == # note: for StateArray or StateArrayRefs see statearray.py # == # some advice about reforming Arg in the future, and about implementing ArgList better then, but tolerably now # (which I'm in the middle of as of 070321 4pm): [edited 070323] """ ##e some future forms we might want: expr._e_customize( existing_option_or_arg = value_or_formula ) expr._e_extend( new_option = Option(type, dflt, doc = "")) expr._e_extend( new_arg = Arg(type, dflt, doc = "")) so Option and Arg turn into parameter-declaring exprs which are special because inside a class def, they are not treated as formula for value, but as formula for type or descriptor, used with other data to get value, as well as set method... so they are not exprs in the same way as other things are -- we might not want to say they are at all. Lets say they turn into parameter descriptors. (I'm guessing they'll be true Python descriptors. I haven't verified that's possible. ###k) expr._e_extend( new_var = State(type, dflt, doc = "")) # and options to control state-sharing, too expr._e_customize( _e_type = "..." ) ??? expr._e_customize( _e_type_for_<interface> = ... ) ??? expr._e_customize( _e_meets_<interface> = <boolean> ) ??? == Arg advice: ###e point to this in ExprsMeta.py and def ArgList too Here is some new advice about how to reform Arg(), make ArgList(), etc -- btw I then made ArgList today (or started it), but that doesn't supercede this: - it should become a kind of expr (also Option, etc; note that State already is an expr) - which is not mutable -- when it learns argpos or attr, it gets replaced with a related expr - which might be toplevel-expressed as the same thing with new options which reveal those params, i.e. Arg(type_expr, dflt_expr, doc = doc_expr, argpos = argpos_expr, attr = attr_expr, required = boolean) - which has special behavior when used as toplevel class assignment value (turning into a special kind of descriptor, perhaps one that wraps the decl) (but review the need for ExprsMeta then modifying the descriptor as it gets inherited into subclasses -- I can no longer remember a justification, since each use passes it the class, I think [#k verify that! there was some use that failed to pass something! just the attr?!?], but I can remember trying to remember a justification and failing...) - but which in future will also have similar special behavior when used in a lambda_expr [nim], or in the _e_extend forms shown above [in '070227 coding log', dated 070321], or the like - for direct assignment of the Arg expr itself to a class attr, wrap it in hold_Expr, I think (but since that permits replacements in general, does it turn them off in this case??? If not, we might need a special form of hold; or to make those special replacements only work at toplevel, i.e. if it's the whole rhs but not a subexpr of it.) (maybe they are not even "replacements" but something else -- interactions of the scanner with the top things, to decide how to treat them, which can do whatever they like, e.g. allow the scanner to add them to an arg-decl-list, known to the class, so it can finally detect extra or missing args, implem ArgList, etc.) - maybe the special behavior which assigns the argpos should be lazy... that is, replace Arg with something belonging to this instance of it but not yet knowing the exact argpos. Also put it in a list known to the class. Then the class (or customized expr) can scan that and assign numbers, and create code for processing real arglists and knowing what's extra, etc. Then ArgList is a simple variant of that processing code. == update 070323: let's think about how, in practice, we extract the arg decls from an expr (whether made by ExprsMeta, or also by _e_extend). ... Don't we want the expr to just know them? ExprsMeta should make them in an explicit way, and _e_extend should add to that (and know which ones are in the class and which ones only in customization formulae). There is, I guess, a decls object (or list, if that's enough) which has them all. It's trivial to add to them... a first step is reforming what these things like Arg() actually are. (See above on that.) There might be an easier short term kluge, too... - try1 idea [superseded below]: add stuff to those macros (def Arg, etc) which the formula scanner sees and adds to the decl list, even though it's not the same thing that makes it work. - better version of that: ##### DO THIS SOON make the new objects (class Arg, etc), let the scanner add them to the decl list, but to make them work, let it ask them to expand into the old macros for now. Just rename def Arg to def Arg_expansion, make a new class Arg, tell it about Arg_expansion, or something like that. For the simpler ones like ArgExpr and ArgList, let them have expansion methods instead. For how class Arg controls what ExprsMeta & its scanner does, see class State. Make sure class State fits into the scheme, too! == ... I decided to implem ArgList now [070321], so I'm doing it, in a few files, see _arglist... plan is to test it in SimpleColumn... I'll have to worry about def Apply in controls.py which overrides it -- my guess is, I should rewrite it more fully than just for that issue... ### [note that it works but is too inefficient, so using it in SimpleColumn is disabled until that can be worked out -- 070323] ### list_Expr or tuple_Expr? the latter -- see comment near def ArgList ### we might need some type related code to handle tuple_Expr(Anything) or so... ### we'll need new code for _e_make_in on tuple_Expr. ### tuple_Expr should eval to a tuple when it contains pure data, but not when it contains exprs that need instantiation!!! But right now we don't know how to tell the difference! Hmm, I guess we do -- does the value belong to IorE or have _e_make_in? A kluge but should work. """ # end
NanoCAD-master
cad/src/exprs/attr_decl_macros.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ command_registry.py $Id$ register the types & commands [stub] """ from exprs.instance_helpers import InstanceOrExpr ###e THIS WILL BE REFACTORED before it is ever used, probably into a plain old dict, fully global for now, for the app object later, # (later to be replaced by a kind of dict that can track its changes) # plus per-module funcs to add things to that dict (modifying their source info as needed) # plus code to extract useful summaries from it, eventually used to make demo_ui toolbars, # but first just used to make a command menu of some sort. # (Initially, we might deepcopy the dict into _app in order to notice when the whole thing changes, # like we do with redraw_counter.) #e can't we just make a tree of exprs which do things like union some dicts and modify nicknames for uniqueness? # then each module just sets the value of its own dict of names... # and a recompute rule figures out what that means for the toplevel summary... # == # but for now, here's the code we have for this, imported & partly called but not yet usefully used. # do dir() and globals() correspond?? yes, both 1244. ## print "len dir() = %d, len(globals()) = %d" % (len(dir()), len(globals())) # == class CommandRegistry: #e rename? def __init__(self): self.class_for_name = {} #e that should also register this registry with a more global one! def register(self, name, val, warn_if_not_registerable = True ): "#doc ... by default, warn if val is not registerable due to lacking some required decls" # figure out the kind of class val is, by its decls, and register as appropriate # print "nim: register %s = %r" % (name, val) # this gets called for what's expected, e.g. CommandWithItsOwnEditMode # now record the interesting decls which let something know what to do with the class motopic = getattr(val, '_e_model_object_topic', None) ###WRONG: only do following if we decide val is registerable self.class_for_name[name] = val # stub [btw should we be a UserDict? that depends -- are we dictlike in any sensible way?] pass #stub def command_for_toolname(self, toolname): #e rename to say "main"? assert 0 # nim # not possible, for subtools... might work for main tools. not sure! def subtools_for_command(self, command): #e rename command -> main_command? (in method, not arg) assert 0 # nim # for subtools, the alg needs to be, figure out the set you want, get their nicknames, disambiguate or discard dups... # return a name list and name->cmd mapping, but the mapping is not determined just from self # even given the set of cmds in it or set of names in it, so no method can do what this one says (except for fullnames). pass def auto_register( namespace, registry = None, modulename = None): ###e this function needs a more explicit name """###doc this better -- it's correct and complete, but very unclear: Register with registry (or with a global registry, if registry arg is not provided) every public name/value pair in namespace (typically, globals() for the calling module) whose value is a registerable class which (according to standard attrs such as __module__) says it was defined in a module with the given (dotted) modulename (namespace['__name__'] by default). This means that passing globals() of some module works as a way of providing that module's name. (The precise comparison, for val being worth considering, is val.__module__ == modulename.) (A public name is a name that doesn't start with '_'.) (A registerable class is one of a set of certain kinds of subclass of InstanceOrExpr (basically, ones which define any of several known interfaces for self-registration) -- see code comments for details.) """ #e permit namespace to be a list of names instead? but how would they be looked up? add another arg for the names? if modulename is None: # assume namespace is globals() of a module modulename = namespace['__name__'] # print "auto_register, modulename = %r" % (modulename,) if registry is None: registry = find_or_make_global_command_registry() for name in namespace.keys(): if not name.startswith('_'): wantit = False # set to True if name names a registratable class defined in the namespace (not just imported into it) try: val = 'bug' # for error message, in case of exception val = namespace[name] # should not fail if issubclass(val, InstanceOrExpr) and val.__module__ == modulename: # often fails for various reasons wantit = True except: if 'Polyline' in name: raise ####### show silly bugs like not importing InstanceOrExpr pass # note: this will happen a lot (since issubclass raises an exception for a non-class val) if wantit: registry.register(name, val, warn_if_not_registerable = False ) else: if 'Polyline' in name: print "not registering %r = %r" % (name,val,) ##### pass continue return # == def find_or_make_global_command_registry( remake = False ): """[with remake = True: to be called once per session, or per reload of exprs module; with it False - call as needed to find it] ###doc """ # it doesn't really matter where we store __main__._exprs__registry -- # a global in this module might make more sense, if reload issues are ok ... #k import __main__ if remake: __main__._exprs__registry = None del __main__._exprs__registry try: return __main__._exprs__registry except AttributeError: __main__._exprs__registry = CommandRegistry() return __main__._exprs__registry pass # end
NanoCAD-master
cad/src/exprs/command_registry.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ iterator_exprs.py $Id$ """ from exprs.Exprs import list_Expr, constant_Expr from exprs.Exprs import is_expr_Instance from exprs.Exprs import is_pure_expr from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.attr_decl_macros import ArgExpr, Arg, Option from exprs.ExprsConstants import Function from exprs.__Symbols__ import _self class MapListToExpr(DelegatingInstanceOrExpr): #e rename? should this be what map_Expr does, or does that need to be incremental-update? # note: this was modified from _MT_try2_kids_helper, which was then rewritten in terms of it. # args (#e should some be ArgOrOption? Note: that doesn't work right if it comes before Arg.) ###KLUGE: use ArgExpr to avoid problems when passing expr classes as functions -- not sure if generally ok (eg when ordinary callable is passed)##### function = ArgExpr(Function, doc = "a python function which maps members of elements to Instances or Exprs") elements = Arg(list_Expr, doc = "a list of elements (of whatever data type you want, suitable for passing to _my.function)") exprhead = ArgExpr(Function, doc = """a python function or expr which can be applied to a sequence of Instances to produce an Expr we should instantiate as our _delegate, whenever our input list of elements changes. Typical values include expr classes like SimpleColumn, or customized ones like SimpleRow(pixelgap = 2). WARNING: due to logic bugs at present, expr classes passed to this argument (or to the function argument) need to be wrapped in KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr. """ ) instance_function = Option(Function, _self.Instance, doc = "a python function with the API of some IorE object's .Instance method, to produce the Instances we delegate to" ) # I wanted to name this Instance, but I think that would cause infrecur when it used the default. # note: we pass it permit_expr_to_vary = True, which complicates the required API. But without this we could not pass someobj.Instance. # Maybe IorE needs a variant method of Instance with permit_expr_to_vary = True by default? VaryingInstance? # self._delegate recompute rule def _C__delegate(self): function = self.function elements = self.elements # usage tracked (that's important) exprhead = self.exprhead index = '_C__delegate' # compute the expr we need (see comment above for why we need a new one each time) elts = map( function, elements) def func2((elt, subindex)): #070320 if is_expr_Instance(elt): res = elt elif is_pure_expr(elt): # new feature 070320: if function(element) gives an expr, instantiate it with a suitable choice of index eli = self.instance_function( elt, (subindex, index), permit_expr_to_vary = True) assert is_expr_Instance(eli) #e error message with elt and eli res = eli else: assert is_expr_Instance(elt) or is_pure_expr(elt) #e message assert is_expr_Instance(res) # sanity check, can remove when works return res elts = map( func2, zip(elts, range(len(elts)))) expr = exprhead(*elts) # do we need to eval expr first? in theory i forget, but I think we do. # in practice it's very likely to eval to itself, so it doesn't matter for now. ###k ##e do we need to discard usage tracking during the following?? res = self.instance_function( expr, ('notint', index), permit_expr_to_vary = True) return res pass # end of class MapListToExpr def KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr( exprclass ): return constant_Expr( exprclass( _KLUGE_fake_option = 1)) # comment from when we tried everything simpler than this to pass SimpleColumn to MapListToExpr as its exprhead arg: # this kluge was not enough: passing constant_Expr(SimpleColumn) (several errors) # or was using ArgExpr in MapListToExpr # nor was this, by itself: exprclass( _KLUGE_fake_option = 1) # but using all three together, it works. # The things this klugetower avoids include: # - without ArgExpr we'd try to instantiate the function, ok for ordinary one but not for expr class let alone customized expr # - ArgExpr's grabarg wrapping the exprhead-as-function with a lexenv_ipath_Expr, which has no __call__: # AssertionError: subclass 'lexenv_ipath_Expr' of Expr must implement __call__ # (and a trivial __call__ would be incorrect, as explained in demo_ui.py recently [070302] # [thus the constant_Expr] # - AssertionError: pure exprs should not be returned from _i_instance: <class 'exprs.Column.SimpleColumn'> ) [thus the cust] # end
NanoCAD-master
cad/src/exprs/iterator_exprs.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ demo_polyline.py -- demo file for Polyline datatype (too unsophisticated for real life) and related commands $Id$ The "demo" in the filename indicates that this is not part of the exprs module per se, but shows how to use it for a specific app. For use in our real app, lots of this will be moved into new files and made more sophisticated (relative coords, relations, better editing, etc). See also: - demo_polygon.py, - class polyline in testexpr_19g demo_drag.py - (superseded by demo_draw_on_surface.py once that works), - DragCommand scratch, - free x-y rot code in draggable.py, - demo_ui.py (which is supposed to be able to provide access to these commands). """ from exprs.command_registry import auto_register from OpenGL.GL import GL_LIGHTING from OpenGL.GL import glDisable from OpenGL.GL import glColor3fv from OpenGL.GL import glLineStipple from OpenGL.GL import GL_LINE_STIPPLE from OpenGL.GL import glEnable from OpenGL.GL import glLineWidth from OpenGL.GL import GL_LINE_LOOP from OpenGL.GL import glBegin from OpenGL.GL import GL_LINE_STRIP from OpenGL.GL import glVertex3fv from OpenGL.GL import glEnd from utilities.constants import blue, noop from exprs.Exprs import list_Expr, call_Expr from exprs.instance_helpers import DelegatingInstanceOrExpr, ModelObject from exprs.attr_decl_macros import State, Option, Arg from exprs.ExprsConstants import StubType, ORIGIN class CommandWithItsOwnEditMode( DelegatingInstanceOrExpr): #e rename! and inherit from Command or MouseCommand or so... """ #doc """ #e rename evidence -- this is not the command, it's the edit mode for the command, right? # in fact, maybe it's only the redraw code for that -- an even more specialized fragment of it. # note that the API inside this is pretty much an entire "edit mode" since it handles time, motion, maybe its own selobj alg, etc; # the first few methods I'm writing don't even depend on any other aspect of this. # note 2: maybe we want to deleg to an obj that does side effects from events, and let this do redraw -- # rather than subclassing to that obj. # declare interface and give default methods/attrs for it # note: using xor mode is not obligatory, and someday we'll often use a better-looking method # (saved color and maybe depth image), and the xor mode look can be guessed from the more general # incremental look -- but classes that want xor-mode-specific drawing can define these anyway... def draw(self): """ [subclass can override this if desired] """ self.draw_background() self.draw_incrementally_over_fixed_background() return def draw_background(self): """ [subclass is encouraged to define this] #doc WARNING: subclass implem should avoid having its drawing effects change (in fact, should avoid using any usage tracked variable which changes) during mouse drags or baremotions which are supposed to update the screen quickly. That's because, if the state used by this does change, we'll need to redraw the background. [At least once we're smart enough to *know* we need to! But before we're smart enough to only redraw some of it.] """ pass def draw_incrementally_over_fixed_background(self): """ [subclass should define this, unless it needs no drawing beyond what's done in draw_background, or unless it overrides draw method itself] #doc """ pass def draw_incrementally_for_xor_mode(self): """ Draw our current graphics-area appearance (or undraw it -- we neither know nor care which) for use in xor-mode incremental drawing. Subclass implems can assume that the caller has set up the dynamic drawing env so that drawing primitives we call can find out that we're doing xor-mode incremental drawing and alter their color choices appropriately (since they probably know best how to do that). [###nim] They can also assume the caller will do whatever updating (e.g. swapbuffers) is needed, at the end. That means most subclasses can use the default method, which just calls self.draw_incrementally_over_fixed_background(). """ self.draw_incrementally_over_fixed_background() def do_baremotion_effects(self): """ [subclass should define this, if baremotion can have any effects] Do whatever state changes are needed as a result of baremotion while we're active. WARNING: if any state changes that affect draw_incrementally_for_xor_mode are done outside of this method, xor-mode undrawing might not match drawing, and bad graphics appearance bugs will result. """ return using_xor_mode_now = False # per-instance transient variable; let's hope no code reload can occur while it's True! #k using_background_incremental_drawing_now = False # ditto # see also some notes about a "better xor mode object" (not in cvs) [070325] def on_baremotion(self): #e args? grab from env? yes, submethod does that, not us. ### CALL ME - needs new interface... note, is API same for in motion or drag?? #e optim: be able to change state, usage track, then *redraw using old state* if drawing effects got invalled. # too hard to do now vs its important (which is not high, since we assume the drawing we do here is fast). if self.using_xor_mode_now: # note: at this point we better make sure no state changes used by draw_incrementally_for_xor_mode have been done yet! self.draw_incrementally_for_xor_mode() # change state (based on mouse motion now being reported to us, selobj detection done now (NOT using glselect I hope), etc self.do_baremotion_effects() self.draw_incrementally_for_xor_mode() elif self.using_background_incremental_drawing_now: self.do_baremotion_effects() self.draw_incrementally_over_fixed_background() else: self.draw() ###k return def on_time_passing(self): """ #doc [only needed if time-dependent animation needs doing; that might include delayed tooltip popups, fadeouts...] """ assert 0 # nim # similar to on_baremotion -- maybe even identical if we decide that's simpler -- # it probably is, since time passes during mouse motion too! pass #e ditto for other events - press, drag, release -- hmm, we don't want 5 complicated methods, better refactor this! #### pass # == class ClickClickCommand( CommandWithItsOwnEditMode): #e rename! """ Abstract class for a command in which repeated clicks build up one visible object, until terminated in some manner (e.g. by clicking in a final or illegal place, or using the escape key, or somehow invoking some other command). """ # do subclasses provide just the clicking behavior, and interactive display, or also a PM or its data? # guess: not the PM -- let that be provided separately, even if it often goes along with a subclass, # and even if the subclass tells the UI env that a PM for that cmd and showing a specific target obj # would be good to show right now. The env can find one, or make one from knowing the target obj type if necessary... ###e note: this does NOT yet handle anything related to scripting or undo, like all commands someday must do -- # tho hopefully when it does, almost no code changes will be needed in its specific subclasses. # declare interface and give default methods/attrs for it #e the 4 or 5 user event methods, i guess; things related to patterns of UI activity as command goes thru its phases pass # == ###e def the polyline model obj datatype class SketchEntity( ModelObject):#e stub """ abstract class for model objects which are Sketch Entities. """ #e what is special about a Sketch Entity, vs any old model object? # [the answers are what we want to encode in this class...] # - it is classified topically as a Sketch Entity: # - by default, in a UI, commands for making one should appear in a "sketch entity toolbar". _e_model_object_topic = "Sketch Entity" # tells default UI where to put a command for making/editing one of these, a display style for one, etc ###e this attr name is a stub: # - it needs a prefix to say it's a decl about the class (or about an expr customized from a subclass of the class, I think) # - it needs to be more specific than just "topic" -- it's a topic about what? # about the kind of model object this makes. But don't rely on superclass to tell you that, # since topic is an attrname in an interface more general than just for model objects, i think. # Also, if something delegates to this, it should only override this attr if it really wants to, # not if it has some other kind of topic. So saying "model object topic" might be enough. # - But maybe say kind rather than topic, since topic is something you can have more than one of?? # Possible names: # _e_model_object_class - no, that would sound like it was the specific subclass name e.g. Polyline, # even if the official name for that is different, e.g. using _type. # Also _e_ has disadvantages. # I wonder if this kind of decl (in some general sense) needs its own new prefix (not _i_ or _e_). # - maybe it needs to belong to a Sketch: # - when making one, find or make a Sketch to contain it in a standard way # - maybe a make-command for one can only run inside a sketch-making commandrun # (which supplies the sketch, making it as needed). # pass # caps: Polyline or PolyLine? see web search?? just initial cap seems most common. # note, in UI it might just be a line... OTOH that's not good in geometric prim code terms! # about removing points from a polyline: # fyi: http://softsurfer.com/Archive/algorithm_0205/algorithm_0205.htm # "We will consider several different algorithms for reducing the [set of] points in a polyline # to produce a simplified polyline that approximates the original within a specified tolerance. # Most of these algorithms work in any dimension..." class Polyline(SketchEntity): #e rename -- 2D or general? [see also class polyline3d in demo_draw_on_surface.py] #e assume SketchEntity super handles whatever relativity is needed? (even add_point coord transform??) # more comments on relativity at end of file # modified from: class polyline(InstanceOrExpr) in demo_drag.py, and some code therein that uses it (eg the add_point call) """ A graphical model object with an extendable (or resettable from outside I guess) list of points. (Q: Does it also consider that some of them are draggable control points and some are not?? Guess: not this class -- some other one might. This one considers all points to be equivalent independent state.) Also might have some Options, see the code -- or those might belong in wrapper objects for various display/edit modes. """ ###BUGS: doesn't set color, depends on luck. # could use cmenu to set the options. # end1 might be in MT directly and also be our kid (not necessarily wrong, caller needn't add it to MT). # when drawing on sphere, long line segs can go inside it and not be seen. points = State(list_Expr, []) ###k probably wrong way to say the value should be a list ## end1arg = Arg(StubType,None) ## end1 = Instance(eval_Expr( call_Expr(end1arg.copy,)( color = green) ))###HACK - works except color is ignored and orig obscures copy ## end1 = Arg(StubType, None, doc = "KLUGE arg: optional externally supplied drag-handle, also is given our cmenu by direct mod") # these style settings ought to be State attrs of self, changeable by cmenu and/or PM, as well as by construction (less important). closed = Option(bool, False, doc = "whether to draw it as a closed loop") _closed_state = State(bool, closed) ####KLUGE -- closed and _closed_state should be a single OptionState attr [nim] linecolor = blue ###KLUGE -- we want it to be a StateOption ###e name this linecolor or color?? even if linecolor, also accept color and use it for default?? # guess: I favor color for use as public option (but might like both to be there) and linecolor for use internally. linewidth = 2 ###KLUGE -- we want it to be a StateOption dashed = False ###KLUGE -- we want it to be a StateOption ## relative = Option(bool, True, doc = "whether to position it relative to the center of self.end1 (if it has one)") ## def _init_instance(self): ## end1 = self.end1 ## if end1: ## end1.cmenu_maker = self ## def _C__use_relative(self): ## "compute self._use_relative (whether to use the relative option)" ## if self.relative: ## try: ## center = self.end1.center ## return True ## except: ## #e print? ## return False ## return False def _C_center(self): #e how do we define the center? center of bbox?? #e is the center of rotation necessarily the same? (guess: yes -- what *else* would center mean, or be needed for?) # (if so, it ought to approximate the center of a minimal bounding circle -- ie its own bradius not be much larger than needed) ## if self._use_relative: ## return self.end1.center # this can vary! ## return ORIGIN assert 0 # nim def _C_origin(self): #070307 renamed this to origin from center (in demo_drag.py version); not sure if needed here at all ## if self._use_relative: ## return self.end1.center # this can vary! return ORIGIN def add_point(self, pos, replace = False): """ add a point at the given 3d position pos; if replace is True, it replaces the existing last point. If pos is None, then no point is added, and the last one is removed if replace is true. """ if replace: self.points = self.points[:-1]#UNTESTED if pos is not None: pos = pos - self.origin ##e be more general -- but should be done by superclass or glue code or by calling transform method... self.points = self.points + [pos] ### INEFFICIENT if lots of points, but need to use '+' for now to make sure it's change-tracked return def make_selobj_cmenu_items(self, menu_spec, highlightable): """ Add self-specific context menu items to <menu_spec> list when self is the selobj (or its delegate(?)... ###doc better). Only works if this obj (self) gets passed to Highlightable's cmenu_maker option (which DraggableObject(self) will do). [For more examples, see this method as implemented in chem.py, jigs*.py in cad/src.] """ menu_spec.extend([ ("Polyline", noop, 'disabled'), # or 'checked' or 'unchecked'; item = None for separator; submenu possible ## ("show potential crossovers", self._cmd_show_potential_crossovers), #e disable if none (or all are already shown or real) ## ## ("change length", [ ## ("left extend by 1 base", lambda self = self, left = 1, right = 0: self.extend(left, right)), ## ("left shrink by 1 base", lambda self = self, left = -1, right = 0: self.extend(left, right)), ## ("right extend by 1 base", lambda self = self, left = 0, right = 1: self.extend(left, right)), ## ("right shrink by 1 base", lambda self = self, left = 0, right = -1: self.extend(left, right)), ## ("both extend by 1 base", lambda self = self, left = 1, right = 1: self.extend(left, right)), ## ("both shrink by 1 base", lambda self = self, left = -1, right = -1: self.extend(left, right)), ## ] ), ]) pass # end of class Polyline Drawable = DelegatingInstanceOrExpr #stub; might replace Widget if it becomes real; but Widget is not delegating -- what's up there? #e also we might put in the delegate = Arg in here, # plus maybe another arg for the layer... otoh, if that's .env, it gets here specially # as an implicit make arg, not as an Arg! class Polyline_draw_helpers( Drawable): # The idea is that we delegate to a Polyline, and it keeps all ModelObject state & methods & has superclass for that, # but this class can wrap it for purpose of drawing it, and variants or subclasses of this class # can wrap it for drawing it in other styles or edit modes (varying display or behavior), # and a bundling class that can delegate diff attrs to diff delegs is possible but not yet known if needed. # # As for our own superclass, it would be based on the interface we're defining support for, # but which our delegate doesn't support, or for which we want to ignore whatever support it provides # (since that will happen -- anything our superclass defines will not be delegated). # # NOT YET KNOWN: # - naming convention for classes like this # - how they are registered as contributing to how to pull a Polyline into a view (and whether to let name do that automatically) # - do we have to say we have delegate = Arg(), or is that known from our superclass? # - if it's known, can we add more Options (or Args) of our own? # - is there also a standard arg for the layer we're in? (BTW if so, is this somehow related to self.env, or taking its place?) # - does the layer the new obj is instantiated into remove all need for specifying layers in State decls, and splitting ipath?? delegate = Arg(Polyline) def draw(self): self.draw_lines() #e option to also draw dots on the points # [btw they might be draggable -- but that's for an edit-wrapper's draw code # (and it might make draggable points on-demand for speed, and use a highlight method other than glnames... #e)] if 0: self.draw_points() return def draw_lines(self): """ draw our line segments, using our current style attrs [which are partly nim] """ # find variables which determine our GL state color = self.fix_color(self.linecolor) dashEnabled = self.dashed width = self.linewidth # set temporary GL state (code copied from drawer.drawline) glDisable(GL_LIGHTING) glColor3fv(color) if dashEnabled: glLineStipple(1, 0xAAAA) glEnable(GL_LINE_STIPPLE) if width != 1: glLineWidth(width) # draw the lines if self._closed_state: glBegin(GL_LINE_LOOP) else: glBegin(GL_LINE_STRIP) for pos in self.points: glVertex3fv(pos) # [note from old code: could be pos + origin if that can matter] glEnd() # restore default GL state [some of this might be moved up to callers] if width != 1: glLineWidth(1.0) if dashEnabled: glDisable(GL_LINE_STIPPLE) glEnable(GL_LIGHTING) return def draw_points(self): """ [nim] draw our points, using our current style attrs """ for pos in self.points: pass ###e draw a dot - how ? same size even if 3d & perspective?? prob ok as approx, even if not the true intent... # in that case we'll eventually be using a texture (or pixmap) with alpha so it looks nice! return def draw_alignment_lines(self): """ helper method for some interactive drawing wrappers: draw yellow and blue dotted alignment lines for the last segment """ assert 0 # nim def draw_tooltip(self): #e does this even belong here? prob not -- let edit wrapper ask for info and do it from the info assert 0 # nim pass # end of class xxx class _draggable_polyline_point(DelegatingInstanceOrExpr): # experimental 070308 pass def draggable_polyline_point(polyline): """ return a func of a point """ ##E oops! the point needs to know its index in the polyline! (and the polyline itself.) # it seems we don't want a pos like polyline.points has now, but a Point object for the polyline to give us! # e.g. polyline.point_objects, where each knows parent, has state, setting its state changes the parent state... return lambda point: 'bla' OverlayList = StubType ## Overlay #stub map_Expr = StubType class dragverts_Polyline(DelegatingInstanceOrExpr): # experimental 070308 polyline = Arg(Polyline) func = call_Expr( draggable_polyline_point, polyline) delegate = OverlayList( polyline, ##e make Overlay itself able to take a list arg mixed with a nonlist arg? Like Column? map_Expr( func, polyline.points ) ) ### .points can be what we need, if .point_posns is what this used to be pass ###stub #e type-inspecting/browsing/searching defs? #e PM defs? how indep of commands are these, btw? general UI Q: given existing one, can you edit it with mouse # much like you are allowed to make one? If so, in general, how does that affect the code here -- # do we pass an optional existing polyline to the so-called cmd_MakePolyline (so it starts off as if it's already making it)? # but the mouse would be in the wrong place... unless we only did that when user clicked right on the end-node in it! # instead do they click on any control vertex and we call this with the polyline and the control vertex both? # but that (drag an existing control point) is probably a different command, anyway. see also demo_polygon for a related one. # == class cmd_MakePolyline(ClickClickCommand): ##e review naming convention (and interface scope); # this cmd_ in the name might imply more, like bundling in a PM too -- or maybe that's ok but optional... # and OTOH since it's really the edit mode for that cmd, it may say editmode_MakePolyline or so instead. ##e # note: the superclass knows about this kind of drawing... and xor mode (just one kind of drawing it can do, of several)... # we just provide the state change methods and draw helper methods like draw_incrementally_for_xor_mode # args (?) #e the model # - how to make things to add to it -- current config, parent for new objs, etc # - what to show within it, when we draw #e the UI #e etc # state polyline = None # the polyline we're making/editing, if any ##e use State()?? or is this really just a ref to a model obj, or a proposed one # (created as a real obj, but not nec. in the MT or cur config yet)? # But either way, the polyline itself, or its attrs, or both (whatever can change as we run) do need to be usage tracked. ###e #e attrs for whether we're rubberbanding it right now, and data if we are (see especially class polyline in demo_drag re this) # appearance in graphics area def draw_background(self): """ [implements abstract class method] """ #e this could include fixed parts of the line, if they are numerous; that probably doesn't matter for now pass def draw_incrementally_over_fixed_background(self): """ [implements abstract class method] """ #e don't draw if end posn is illegal! (as noticed from a formula on some self-state which we assume is set properly) # but do draw the selobj-highlighting for anything that needs it during this op!!! self.polyline.draw() #e also draw the yellow and blue alignment lines, if present return #e actions for building it -- grab them from class polyline in demo_drag.py pass # end of class cmd_MakePolyline #e more commands for one? cmenu commands? etc # == ##e register the types & commands [stub] ##this_module_registry = registry() #e that should also register this registry with a more global one! ## ####class _x: pass # used only for _x.__module__ in following call [e.g. 'exprs.demo_polyline'] ## ##auto_register( this_module_registry, globals()) ## , _x.__module__ ) auto_register( globals()) ###e this function needs a more explicit name -- and passing the specific classnames would be better # == """ say above: intercept in testmode - baremotion, update_selobj i guess and some other selobj controls prob no need to intercept them in selectMode itself but i am not sure... i could have said the same about all my other mods to it... """ #e also move new incr methods in controls.py to class HL #e also say above where we get in and out of opengl xor mode, and grab eg code from BuildCrystal_Command or zoom or whatever to do that # (as helper methods in the superclass, or a mixin just for xormode drawing, which could define a swapbuffers method too) # btw is xormode used now for incr drawing in selmode itself, for region sel -- and if not why not? # is region sel itself able to be a cmd of this form -- even though the std editmode might get into it as its emptySpaceLeftDown? # btw, an advantage of xor mode in that case - it's ok if you didn't have a premade screen image around. """ really do review class polyline soon, and old demo_polygon too, esp for its Command supers, and command_scratch file too. an eg issue that came up in class polyline: we need to know what the sketch entity coords are rel to. If it's both draggable, and in/on a ref plane or surface, then it might be two-level-relative... tho the relativity for Draggable is probably best thought of as transient. ui discussion: the initial editmode lets you click to add segments, or Undo to un-add them i think (ie to undo the last click but not get out of being in the rubberband line mode), but there is also some way to drag verts or edges or add new control points or remove old ones... but how is that controlled -- a toolset in the PM? yet another level of flyout toolbar? PM tools seem preferable... code structure discussion: class polyline is one thing, and an editable view of it another, and they are different! The editable view is made by mapping the polyline elements into drawables with bindings, which differ depending on editmode and tool... tho for just making it (not fancier editing) this might not be needed. """ # end
NanoCAD-master
cad/src/exprs/demo_polyline.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Column.py - provide SimpleColumn and SimpleRow, and someday, fancier Column and Row [#e module might be renamed; otoh, if we have Table it'll be enough more complex to be in its own file] @author: bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. """ from OpenGL.GL import glPushMatrix, glPopMatrix, glTranslatef ##e revise later into glpane methods or so # from exprs.Rect import Spacer from exprs.TextRect import TextRect from exprs.Exprs import call_Expr, not_Expr, or_Expr, and_Expr, list_Expr from exprs.attr_decl_macros import ArgList, Option, Arg, Instance from exprs.widget2d import Widget2D from exprs.ExprsConstants import PIXELS from exprs.__Symbols__ import _self # == debug070321 = False class SimpleColumn_NEW(Widget2D): #061115, revised 070321 to use new ArgList -- but disabled 070322, # since too slow for routine use (eg in testexpr_19g), # until we fix that update speed bug which means a change in any element remakes them all. ### fyi: a test that puts too many elts for SimpleColumn_OLD into the MT: _30i, dna x 3, rects x 2 #e or use InstanceMacro using Overlay & Translate? Could work, but slower and not needed... might help in CL with fancier gaps. ## a0 = Arg(Widget2D) # note: this probably doesn't preclude caller from passing None, and even if it does, nothing enforces that yet; # if caller does pass None (to this or to Overlay), best thing is probably to replace this with Pass = Rect(0,0,white) # and use it as a drawable, but have special case to use no gap under it -- or the equiv, as a simple change # to our btop formula so it's 0 if not a0 -- which is already done, so maybe there's no need to worry about a0 = None. # Maybe it should be an optional arg like the others. [061115] args = ArgList(Widget2D, (), doc = "0 or more things (that can participate in 2d layout) to show in a column") def _C_a0(self): args = self.args args[0:] # make sure this works (i.e. args is a sequence) if len(args): return args[0] else: return None pass a0 = _self.a0 # kluge, but legal (due to special case in ExprsMeta, documented in comments there): # get a0 into the class-def namespace for direct use below def _init_instance(self):##### debug only super(SimpleColumn, self)._init_instance() try: args = 'bug' # for use in error message, in case of exception args = self.args len(args) # make sure this works! if debug070321: print "fyi: this SimpleColumn has %d args" % len(args) print "fyi: the args i mentioned are: %r" % (args,) ##### except: print "following exception concerns self = %r, args = %r" % (self, args) raise return ## gap = Option(Width, 3 * PIXELS) pixelgap = Option(float, 3) # 070104 int -> float gap = pixelgap * PIXELS print_lbox = Option(bool, False) #061127 for debugging; should be harmless; never tested (target bug got diagnosed in another way) drawables = call_Expr(lambda args: filter(None, args) , args) ## empty = not drawables ###e BUG: needs more Expr support, I bet; as it is, likely to silently be a constant False; not used internally empty = not_Expr(drawables) bleft = call_Expr(lambda drawables: max([arg.bleft for arg in drawables] + [0]) , drawables) # 070211 arg.bleft -> getattr_debugprint(arg, 'bleft') bright = call_Expr(lambda drawables: max([arg.bright for arg in drawables] + [0]) , drawables) height = call_Expr(lambda drawables, gap: sum([arg.height for arg in drawables]) + gap * max(len(drawables)-1,0) , drawables, gap) ## btop = a0 and a0.btop or 0 # bugfix -- use _Expr forms instead; i think this form silently turned into a0.btop [061205] btop = or_Expr( and_Expr( a0, a0.btop), 0) bbottom = height - btop def draw(self): if self.print_lbox: print "print_lbox: %r lbox attrs are %r" % (self, (self.bleft, self.bright, self.bbottom, self.btop)) glPushMatrix() prior = None for a in self.drawables: if prior: # move from prior to a dy = prior.bbottom + self.gap + a.btop glTranslatef(0,-dy,0) # positive is up, but Column progresses down prior = a self.drawkid(a) ## a.draw() glPopMatrix() return pass # end of class SimpleColumn_NEW or SimpleColumn # == # A simple Column to tide us over for testing other things # until the real one works. (See Column_old_nim.py for the "real one"; # it includes CW, CL, CLE, which some comments herein may refer to.) class SimpleColumn(Widget2D): #061115 #e or use InstanceMacro using Overlay & Translate? Could work, but slower and not needed... might help in CL with fancier gaps. ## a0 = Arg(Widget2D) # note: this probably doesn't preclude caller from passing None, and even if it does, nothing enforces that yet; # if caller does pass None (to this or to Overlay), best thing is probably to replace this with Pass = Rect(0,0,white) # and use it as a drawable, but have special case to use no gap under it -- or the equiv, as a simple change # to our btop formula so it's 0 if not a0 -- which is already done, so maybe there's no need to worry about a0 = None. # Maybe it should be an optional arg like the others. [061115] a0 = Arg(Widget2D, None) # even the first arg can be missing, as when applying it to a list of no elts [061205] a1 = Arg(Widget2D, None) a2 = Arg(Widget2D, None) a3 = Arg(Widget2D, None) a4 = Arg(Widget2D, None) a5 = Arg(Widget2D, None) # use ArgList here when that works a6 = Arg(Widget2D, None) a7 = Arg(Widget2D, None) a8 = Arg(Widget2D, None) a9 = Arg(Widget2D, None) a10 = Arg(Widget2D, None) a11 = Arg(Widget2D, None) # the 12th arg is 1 too many toomany = Instance(TextRect("too many args to SimpleColumn")) #070212 added Instance to fix mysterious bug manifesting as this debug output: ## getattr_debugprint: <lexenv_ipath_Expr... <TextRect#2331(a)>> has no 'bleft' args = list_Expr(a0,a1,a2,a3,a4,a5, a6,a7,a8,a9,a10, # could say or_Expr(a0, Spacer(0)) but here is not where it matters and_Expr(a11, toomany) ) ## gap = Option(Width, 3 * PIXELS) pixelgap = Option(float, 3) # 070104 int -> float gap = pixelgap * PIXELS print_lbox = Option(bool, False) #061127 for debugging; should be harmless; never tested (target bug got diagnosed in another way) drawables = call_Expr(lambda args: filter(None, args) , args) ## empty = not drawables ###e BUG: needs more Expr support, I bet; as it is, likely to silently be a constant False; not used internally empty = not_Expr(drawables) bleft = call_Expr(lambda drawables: max([arg.bleft for arg in drawables] + [0]) , drawables) # 070211 arg.bleft -> getattr_debugprint(arg, 'bleft') bright = call_Expr(lambda drawables: max([arg.bright for arg in drawables] + [0]) , drawables) height = call_Expr(lambda drawables, gap: sum([arg.height for arg in drawables]) + gap * max(len(drawables)-1,0) , drawables, gap) ## btop = a0 and a0.btop or 0 # bugfix -- use _Expr forms instead; i think this form silently turned into a0.btop [061205] btop = or_Expr( and_Expr( a0, a0.btop), 0) bbottom = height - btop def draw(self): if self.print_lbox: print "print_lbox: %r lbox attrs are %r" % (self, (self.bleft, self.bright, self.bbottom, self.btop)) glPushMatrix() prior = None for a in self.drawables: if prior: # move from prior to a dy = prior.bbottom + self.gap + a.btop glTranslatef(0,-dy,0) # positive is up, but Column progresses down prior = a self.drawkid(a) ## a.draw() glPopMatrix() return pass # end of class SimpleColumn or SimpleColumn_OLD # == class SimpleRow(Widget2D): # copy of SimpleColumn, but bbottom <-> bright, btop <-> bleft, width <- height, and 0,-dy -> dx,0, basically a0 = Arg(Widget2D, None) a1 = Arg(Widget2D, None) a2 = Arg(Widget2D, None) a3 = Arg(Widget2D, None) a4 = Arg(Widget2D, None) a5 = Arg(Widget2D, None) # use ArgList here when that works a6 = Arg(Widget2D, None) a7 = Arg(Widget2D, None) a8 = Arg(Widget2D, None) a9 = Arg(Widget2D, None) a10 = Arg(Widget2D, None) a11 = Arg(Widget2D, None) toomany = Instance(TextRect("too many args to SimpleRow")) args = list_Expr(a0,a1,a2,a3,a4,a5, a6,a7,a8,a9,a10, and_Expr(a11, toomany) ) pixelgap = Option(int, 3) gap = pixelgap * PIXELS drawables = call_Expr(lambda args: filter(None, args) , args) empty = not_Expr( drawables) btop = call_Expr(lambda drawables: max([arg.btop for arg in drawables] + [0]) , drawables) bbottom = call_Expr(lambda drawables: max([arg.bbottom for arg in drawables] + [0]) , drawables) width = call_Expr(lambda drawables, gap: sum([arg.width for arg in drawables]) + gap * max(len(drawables)-1,0) , drawables, gap) bleft = or_Expr( and_Expr( a0, a0.bleft), 0) bright = width - bleft def draw(self): glPushMatrix() prior = None for a in self.drawables: if prior: # move from prior to a dx = prior.bright + self.gap + a.bleft glTranslatef(dx,0,0) # positive is right, and Row progresses right prior = a self.drawkid(a) ## a.draw() glPopMatrix() return pass # end of class SimpleRow # end
NanoCAD-master
cad/src/exprs/Column.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ DragBehavior.py - the DragBehavior API and some useful specific behaviors @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. A DragBehavior is a behavior in response to drag events that a Drawable (called a "drag handle") can be given (in addition to whatever highlighting and cursor behavior it has) and that determines how drag events affect a position or position-determining state (one which maps to a position, perhaps constrained to a line or plane, and/or a region, and/or quantized) which this behavior is used to drag, and which usually (in part) determines the drawn position of the drag handle. """ from exprs.instance_helpers import InstanceOrExpr from exprs.attr_decl_macros import Arg, Instance from exprs.__Symbols__ import Anything from exprs.ExprsConstants import StateRef from exprs.Highlightable import SavedCoordsys class DragBehavior(InstanceOrExpr): """ abstract class [#doc, maybe more defaults] """ # default implems def on_press(self): pass def on_drag(self): pass def on_release(self): pass def on_release_in(self): self.on_release() return def on_release_out(self): self.on_release() return pass # == class SimpleDragBehavior(DragBehavior): #works circa 070317; revised 070318 """ the simplest kind of DragBehavior -- translate the passed state just like the mouse moves (screen-parallel) [#doc] """ ##e rename to indicate what it does -- translate, 3d, screen-parallel # (no limits, no grid, no constraint -- could add opts for those #e) # note: for now, it probably doesn't matter if we are remade per drag event, or live through many of them -- # we store state during a drag (and left over afterwards) but reset it all when the next one starts -- # ASSUMING we actually get an on_press event for it -- we don't detect the error of not getting that! # OTOH, even if we're newly made per drag, we don't detect or tolerate a missing initial on_press. ###BUG I guess # args: # a stateref to the translation state we should modify, # and something to ask about the drag event (for now, highlightable, but later, a DragEvent object) # (best arg order unclear; it may turn out that the DragEvent to ask is our delegate in the future -- so let it come first) highlightable = Arg(Anything) # for current_event_mousepoint (coordsys) -- will this always be needed? at least a DragEvent will be! translation_ref = Arg(StateRef, doc = "ref to translation state, e.g. call_Expr( LvalueFromObjAndAttr, some_obj, 'translation')" ) # state: saved_coordsys = Instance( SavedCoordsys() ) # provides transient state for saving a fixed coordsys to use throughout a drag def current_event_mousepoint(self, *args, **kws): #e zap this and inline it, for clarity? or move it into DragBehavior superclass?? return self.saved_coordsys.current_event_mousepoint(*args, **kws) # note: the following methods are heavily modified from the ones in DraggableObject. # [They are the methods of some interface, informal so far, # but I don't know if it's exactly the one I've elsewhere called Draggable.] def on_press(self): self.saved_coordsys.copy_from( self.highlightable) # needed, since self.highlightable's coordsys changes during the drag! point = self.current_event_mousepoint() # the touched point on the visible object (hitpoint) self.oldpoint = self.startpoint = point def on_drag(self): # Note (for any on_drag method -- really about the interface it's in [###e refile]): # we can assume this is a "real drag", # not one which is too short to count (and is therefore treated as a click instead), # since the caller is responsible for not calling on_drag until it decides this is a real drag. oldpoint = self.oldpoint # was saved by prior on_drag or by on_press point = self.current_event_mousepoint(plane = self.startpoint) self.translation_ref.value = self.translation_ref.value + (point - oldpoint) self.oldpoint = point def on_release(self): pass pass # end of class SimpleDragBehavior # end
NanoCAD-master
cad/src/exprs/DragBehavior.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. $Id$ old code for ToggleShow [nim], taken from testdraw2_cannib.py # types ##ImageWidget = Widget # not sure if we want this to be a definite subtype # could it be renamed to Image? possible name conflict (probably ok): import Image # from the PIL library # I'll rename it. # == ToggleAction from __Symbols__ import stateref ToggleAction = NamedLambda( ###e need to initialize the state if not there? NO, that's the job of the stateref (formula) itself! 'ToggleAction', ((stateref, StateRef),), Set(stateref, not stateref) ### will 'not' be capturable by a formula? ## [update 061204: lhs and rhs are both wrong now, see Set.py -- lhs must be lval, rhs must be not stateref.value or so [nim]] ) # == ToggleButton from __Symbols__ import stateref, false_icon, true_icon ToggleButton = NamedLambda( 'ToggleButton', ((stateref, StateRef), (false_icon, Image), #e add a default (true_icon, Image, false_icon), # same as false_icon, by default (default is a formula which can use prior symbols) ), Button( # plain image If(stateref, Overlay(Hidden(false_icon),Centered(true_icon)), # get the size of false_icon but the look of true_icon #e possible bugs: Centered might not work right if false_icon is not centered too; see also wrap/align options #e Overlay might work better outside, if otherwise something thinks the layout depends on the stateref state false_icon ), # highlighted image - ###e make this a lighter version of the plain image #e or a blue rect outlining the plain image -- I forget if Button assumes/implems the plain image always drawn under it... ###@@@ put this in somehow; missing things include my recollecting arg order of RectFrame, pixel units, dims of the icon, etc # actions -- for now, just do it immediately when pressed on_press = ToggleAction(stateref) )) # == ToggleShow ToggleFalseIcon = Rect(1,1,black) # stub ToggleTrueIcon = Rect(1,1,gray) # stub #e define default ToggleShow_stateref or StateRef value, in case env doesn't have one... from __Symbols__ import thing, label, stateref ToggleShow = NamedLambda( 'ToggleShow', ((thing, Widget), (label, Widget, None), (stateref, StateRef, Automatic)), #e or should we specify a default stateref more explicitly? letting env override it as a feature of NamedLambda? Column( Row( ToggleButton(stateref, ToggleFalseIcon, ToggleTrueIcon), label ), If( stateref, #k can you just plop in a stateref in place of asking for its value as a boolean? I guess so... it's a formula thing ) )) test_ToggleShow = ToggleShow( Rect(3,3,lightblue), "test_ToggleShow's label" ) #print test_ToggleShow
NanoCAD-master
cad/src/exprs/outtakes/ToggleShow-outtakes.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. $Id$ this file won't be in cvs for long -- but it might be there temporarily, since it's not yet fully cannibalized #####@@@@@ need to decide whether we or the formula should do usage tracking and subscribe self.inval to what we use. # to decide -- what kinds of formulas can be ortho to kinds of invalidatable lvalues? # do we memo in formula or here? who decides? do we own formula? what does it have, other than ability to recompute? # how often is it made by FormulaFromCallable -- always? yes, ie in both _C_rule and _CV_rule (using LvalDict 1 or 2). # - The differentest kind of lval is the one for displists; it represents a pair of virtual values, the displist direct # contents and the effect of calling it (only the latter includes sublist effects), both represented by version numbers # which is what "diff old and new" would use. Instead of get_value we have emit_value i.e. draw. For inval propogation # it needs to separate the two virtual values. Maybe it could use two Lval objects.... [latest code for it is in NewInval.py] # - It has to work with draw methods, which also emit side effects, have version numbers... do they, too, # distinguish between two virtual values, what OpenGL they emit vs what that will do when it runs?? # - The other big issue is formulas with no storage of their own, and not owned. (E.g. those coded using _self.) # - The biggest change in that is wanting to call its compute method with an arg, for use in grabbing attrs when evalling # and for knowing where to store usage (tho latter could be in dynenv in usual way, and should be). # - Note that what I often call a formula is just an expr, and a formula instance is an expr instance, class InstanceOrExpr, # even if it's an OpExpr. That thing has its own memo, implemented by this class Lval. So all it provides us is a # compute method. This is suggesting that our _formula should be merely a compute method. Does that fit in displist case?? # # ### # == some of the following will still be rewritten and used in ExprsMeta, i think class InvalidatableAttrsMixin(object): # object superclass is needed, to make this a new-style class, so a python property will work. ####@@@@ This class's behavior is likely to be merged into ExprsMeta. """Mixin class, for supporting "standard compute methods" in any client class. We support two kinds of compute methods: - _C_xxx methods, for recomputing values of individual attrs like self.xxx; - pairs of _CK_xxx and _CV_xxx methods, for recomputing the set of keys, and individual values, within dictlike attrs self.xxx. [Details to be explained. Features to be added: let client determine lval classes.] WARNING: entirely NIM or buggy as of 061020. """ def __getattr__(self, attr): # in class InvalidatableAttrsMixin # return quickly for attrs that can't have compute rules if attr.startswith('__') or attr.startswith('_C'): raise AttributeError, attr # must be fast for __repr__, __eq__, __add__, etc # Notes: # - We only catch __xx here, not _xx, since _xx is permitted to have compute rules, e.g. _C__xx. # Btw, __xx will only exist if it's really __xx__, since otherwise it would be name-mangled to _<classname>__xx. # - We exclude _Cxx so that no one tries to define a compute rule for a compute rule (hard to support, not very useful). # look for a compute method for attr, either _C_attr (used alone) or _CK_attr and/or _CV_attr (used together), # in self.__class__; if found, create and save a property in the class (so this only happens once per attr and class). # (#e should we grab the prefix out of the rule constructor, since it needs to know it anyway?) if _compile_compute_rule( self.__class__, attr, '_C_', _C_rule ) or \ _compile_compute_rule( self.__class__, attr, '_CV_', _CV_rule ): # also incorporates _CK_ for same attr, if it exists # One of the above calls of _compile_compute_rule defined a property in self.__class__ for attr. # Use it now! [This will cause infrecur if the function said it's there and it's not! Fix sometime. #e] return getattr(self, attr) raise AttributeError, attr pass # end of class InvalidatableAttrsMixin def _compile_compute_rule( clas, attr, prefix, propclass ): """[private helper function] Try to create a compute rule for accessing attr in clas (which needs to inherit from object for this to be possible), using a compute method named (prefix + attr) found in clas (if one is there). If you find that method, store a property (or similar object -- I forget the general name for them ###doc) implementing the compute rule in clas.attr, created by propclass(...), and return True. Otherwise return False. """ assert isinstance( clas, object), "compute rules are only supported on new-style classes, not %r" % clas try: unbound_method = getattr( clas, prefix + attr) except AttributeError: return False assert callable(unbound_method), "prefix %r is reserved for use on compute methods, but .%s is not callable on %r" % \ (prefix, prefix + attr, clas) prop = propclass( clas, attr, unbound_method, prefix ) # on error, this can raise an exception; or it can return None if prop is None: return False # assume prop is a suitable property object for use in a new-style class setattr( clas, attr, prop) ###e improved design: propclass should instead be an object which can store a list of new properties (descriptors) # on a list of corresponding attrs; # that way it could know the prefixes itself, know how to look for the unbound methods, # and support the definition of more than one attr-descriptor, e.g. one for attr and one for associated values # like direct access to an LvalDict associated with a _CV_rule attr. When we need the latter, revise the design like that. return True ### stuff after this is almost fully in ExprsMeta now, except maybe that big docstring, and some init code ### class _C_rule(object): ###e rename, since this is not a compute method? #e give it and _CV_rule a common superclass? "act like a property that implements a recompute rule using an Lval made from a _C_attr compute method" # note: the superclass "object" is required, for Python to recognize this as a descriptor. def __init__(self, clas, attr, unbound_method, prefix): assert prefix == '_C_' and unbound_method == getattr( clas, prefix + attr) # a sign of bad API design of _compile_compute_rule? #e store stuff self.attr = attr self.prefix = prefix return def __get__(self, instance, owner): if instance is None: # we're being accessed directly from clas return self # find the Lval object for our attr, which we store in instance.__dict__[attr] # (though in theory, we could store it anywhere, as long as we'd find a # different one for each instance, and delete it when instance got deleted) attr = self.attr try: lval = instance.__dict__[attr] except KeyError: # make a new Lval object from the compute_method (happens once per attr per instance) mname = self.prefix + attr compute_method = getattr(instance, mname) # should always work # permit not only bound methods, but formulas on _self, or constants # (but formulas and constants will also be permitted directly on attr; see ExprsMeta for more info) compute_method = bound_compute_method_to_callable( compute_method, formula_symbols = (_self,), constants = True ) lval = instance.__dict__[attr] = Lval(compute_method) return lval.get_value() # this does usage tracking, validation-checking, recompute if needed # Notes: # - There's a reference cycle between compute_method and instance, which is a memory leak. # This could be fixed by using a special Lval (stored in self, not instance, but with data stored in instance) # which we'd pass instance to on each use. (Or maybe a good solution is a C-coded metaclass, for making instance?) # - The __set__ below detects the error of the compute method setting the attr itself. Good enough for now. # Someday, if we use a special Lval object that is passed self and enough into to notice that itself, # then we could permit compute objects to do that, if desired. But the motivation to permit that is low. # - There is no provision for direct access to the Lval object (e.g. to directly call its .set_formula method). # We could add one if needed, but I don't know the best way. Maybe find this property (self) and use a get_lval method, # which is passed the instance? Or, setattr(instance, '_lval_' + attr, lval). def __set__(self, instance, val): # Note: the existence of this method means that this descriptor is recognized by Python as a "data descriptor", # and it overrides instance.__dict__ (that is, it's used for get, set, or del, even if instance.__dict__ contains a value). #k Q: can instance be None here?? assert 0, "not allowed to set attr %r in %r" % (self.attr, instance) #e could make __delete__ do an inval... should we?? ### pass # end of class _C_rule class _CV_rule(object): """Act like a property that implements a per-item recompute rule for a dictlike object stored at instance.attr, using an LvalDict made from a _CV_attr compute method for item values, and an optional _CK_attr compute method for the complete list of keys. If the _CK_attr method is not present, the set of keys is undefined and the dictlike object (value of instance.attr) will not support iteration over keys, items, or values. Whether or not iteration is supported, direct access to the LvalDict is provided [how? ###e, nim], which makes it possible to iterate over the dict items created so far. """ def __init__(self, clas, attr, unbound_method, prefix): assert prefix == '_CV_' and unbound_method == getattr( clas, prefixV + attr) self.attr = attr self.prefixV = prefix self.prefixK = '_CK_' self.has_CK = not not getattr( clas, prefixK + attr, False) return def __get__(self, instance, owner): if instance is None: # we're being accessed directly from class return self # find the RecomputableDict object for our attr in instance attr = self.attr try: obj = instance.__dict__[attr] print "warning: obj was not found directly, but it should have been, since this is a non-data descriptor", self #e more? except KeyError: # make a new object from the compute_methods (happens once per attr per instance) compute_methodV = getattr(instance, self.prefixV + attr) # should always work compute_methodV = bound_compute_method_to_callable( compute_methodV, formula_symbols = (_self, _i), ###IMPLEM _i constants = True ) # also permit formulas in _self and _i, or constants (either will be converted to a callable) assert callable(compute_methodV) compute_methodK = getattr(instance, self.prefixK + attr, None) # optional method or formula or constant (None can mean missing, since legal constant values are sequences) if compute_methodK is not None: compute_methodK = bound_compute_method_to_callable( compute_methodK, formula_symbols = (_self,), constants = True ) assert callable(compute_methodK) obj = instance.__dict__[attr] = RecomputableDict(compute_methodV, compute_methodK) return obj # Note: we have no __set__ method, so in theory (since Python will recognize us as a non-data descriptor), # once we've stored obj in instance.__dict__ above, it will be gotten directly # without going through __get__. We print a warning above if that fails. # Note: similar comments about memory leaks apply, as for _C_rule. pass # end of class _CV_rule debug code from LvalForState set_constant_value (after same_vals test says T) if isinstance(val, Q): #e could optim using flag set from default value?? (since test is not needed in all such cases) print "curval is %r, setting to quat %r, and same_vals says they're equal btw" % (self._value, val) assert self._value == val, "same_vals was wrong for %r == %r" % (self._value, val) #070227 (trying to catch a bug)
NanoCAD-master
cad/src/exprs/outtakes/lvals-outtakes.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ NewInval.py [to be cannibalized -- as of 061231, obs or mostly obs] $Id$ 061231 moved the displist comments and code from here to DisplayListChunk.py; what remains here is obs or mostly obs """ # == # Tue 060919 # env + expr -> understood expr (in that env), an obj with attrs (oresmic?) # expr + env/place -> placed expr; # done by a recompute rule, so it might get invalidated, and it's an attrval which is itself usage tracked # env is divided up - for us, expr interp rules, state (model, transient, optim, displists), glpane & its state and coords # and we might yet have to declare or divide it based on what changes rarely, per drawable instance, or per frame (affects inval code) # write these funcs so that their api does not preclude them from memoizing, or force them to # they can be env methods, since env determines how they all work and holds the memos # subenv for every expr level as i interpret, if necessary, or is it just a sub-place? # but it might only exist during interp -- it's parallel to, but perhaps more transient than, yet more general than, # transient-state container-hierarchy # do that code walkthough for a simple example - simple MT with displists (on paper) # then sort that code into methods on objects, then classes, then write it down in this style. # overall - recompute rule in drawing env, from expr to its implem (where to send draw events) # uses understood expr, which tells flags about whether it uses transient state, class or constructorfunc for creating drawable... # expr object - return the head, and arglist incl options or that there is none, and lexical class from parser if any # expr in env - understand it, incl how to make it, then make it (in place) (I guess place != env, env is that part of place # which affects understanding of expr, maybe not including the part that has changing vars at runtime, or even changing opt vals) # (but the understanding might say "opt X has type T" and then that might be what decided the val was in the other place, # for env opt vals? not sure.) # == class _Lval: ####@@@@ compare to later version in scratch5.py "I own a resettable formula (like a recompute callable, but usage-tracks), and maintain a lazy invalidatable .value." _invalid = True ### ok? what about propogation? _memoized_value = None _version_counter = 1 ###k ?? # ... [usual stuff removed] def get_value(self, args_each_time = None): # args_each_time can only be passed if you call this method explicitly "called whether or not we have the value" if self._invalid: self._recompute(args_each_time) return self._memoized_value def _recompute(self, args_each_time): "only called when we're invalid" new = self._compute_a_new_value(args_each_time) if new != self._memoized_value: # != ok? not for all numeric arrays? or is it? I forget. state_utils should say. self._version_counter += 1 ###k ?? self._memoized_value = new self._invalid = False return def _compute_a_new_value(self, args_each_time): "return a newly computed value" ### what about usage tracking?? return self._func(args_each_time) ###k actually call a formula, and let it usage-track for us, and we'll subscribe our inval to what we used. ### but does caller or this method do that? caller, since it might do funny things like choose memo place based on usage. pass class KidLval(_Lval): # this might have its own way to compute, ie a built-in python-coded formula-func, tho it might let superclass do usage tracking. # does that mean its own kind of formula, or an implicit builtin formula (since formulas do usage tracking)? def _raw_recompute(self, args_each_time): #####@@@@@ call me parent, index = args_each_time # this is where we put the code to ask the parent how to make that kid, and to make it, # but also, perhaps, to compare the inputs to last time and decide whether we really need to remake it (not sure). codeformula = parent._get_kid_codeformula(index) ####IMPLEM - this can change at runtime for the same kid, i think -- always remake then lexenv = parent._get_kid_lexenv(index) ####IMPLEM -- lexenv is an immutable and unchanging object, it's what we want here ###E compare codeformula to old value -- stored where?? ## worse -- is it really a formula? how do we monitor changes? when do they mean we need a new kid? usually it's just 'code expr'... # lets assume that's what it is, for now. if 'need to recompute': 'make a kid from lexenv, with index & code' code = codeformula kid = make_an_instance(code, lexenv, place) ####@@@@ also place? or, do we not even store that, but use it only at runtime? that might be a de-optim, but gives good flexibility -- # lets instance run in multiple copies -- OTOH only if entire index chain is the same, so maybe it's a silly idea. #### wait, put in the index, relative to the parent... is it in the lexenv? I think so. no, only in spirit, as optim we separate it. return kid return None ##k?? pass def make_an_instance(code, lexenv, place): "somebody decided a new instance needs to be made, in a certain place (incl index_chain, storage)... make it." nim(pseudocode) return code(lexenv, place) # pseudocode ###@@@ # why not just pass the place-related make args, and decide locally what they contain (index, stores, etc), so we can change that later? # and also the place-related each-frame args?? or do we have none of those? the old reasoning says none: they're often stable, # so when they change we want to notice explicitly, so we optim for when they're stable. # if we tried to let one instance live in two places, the optim data would all differ so we'd defeat the purpose. # ... so the place-related args are all in make, and we might as well just call them the place! class HelperClass: def __init__(self): self._kid_codeformulas = {} # convenience dict, of exceptions to whatever general rule we might have for these (??) self._kid_lexenvfuncs = {} # ditto, but missing or None ones are ok and mean "identity" (maybe) #e maybe one for coords? only in scenegraph model, not needed if we have _move self._kid_lvals = {} # this might define which kids we actually have (not sure, if set of kids could shrink & change back in one step) def _define_kid(self, index, codeformula = None, lexenvfunc = None): ### in general, is it best to pass these, or have a func to compute them? ####@@@@ decide by considering fancier-indexed iterators like Cube or Table. ### future note/digr: ### with fancy indexed sets with incremental inval, we'd need to receive inval signals for their pieces (values at indices). ### I imagine we could receive inval signals, new values, or mod-functions, or mod-func plus result ### (all of which are various portions of an "arrow" from old to new value of the piece in question). "[private] incremental make (or ensure made) of a kid" # pseudocode: new = not self._kid_lvals.has_key(index) # but even if not new, we might need to remake it... does that depend on code being new? # if so, is it automatic, from a diffing lval for the code, that will inval the kid-instance? #####@@@@@ if new: self._kid_lvals[index] = KidLval(self, index) #### i don't like passing self (re cycles) -- maybe it won't need to store it?? # what it might need it for is recomputing kid properties... maybe we can pass it self each time it needs that?? # when it needs it is when we ask for the kid-value. hmm. Ditto for index I suppose? if codeformula is not None: # otherwise we're not preventing a subclass method from computing this (??) self._kid_codeformulas[index] = codeformula if lexenvfunc is not None: #### hmm, identity None is ambiguous with don't-change-it None, WRONG but tolerable for now ####@@@@ self._kid_lexenvfuncs[index] = lexenvfunc #e something to be sure it's really made, or will be on demand; the kid needs to know its index #e something to see if we redefined those inputs? no, just guess we probably did if we called this self._kid_lvals[index].invalidate() #e how do we undefine a kid? return def _get_kid(self, index): ###e process saved-up kid index creations, if we ever buffer index creations from fancy indexed-set inputs lval = self._kid_lvals[index] # error if this does not exist, since keys define legal kids kid = lval.get_value( (self, index) ) # get the value -- the formula is assume to need this tuple of args, each time it runs, # and since we pass them, we're responsible for tracking invals in them and invalidating the kid # (as opposed to usage tracking occuring) ####@@@@ how does usage tracking fit in? return kid def _get_kid_lexenv(self, index): ###E memoize this -- really we want a recompute rule, i think... can it ever change? I don't think so... #e take parent lexenv, with localvars added, and use index to modify the various staterefs... # but how exactly does index interact, with different staterefs? # ... work that out later, ie write simple code now, quick to write & later read/revise. # uses of index: find transient state, # perhaps in various layers of differing permanence (ie same index-chain in different objects), # with varying sharing (ie different index-chains could point to same place, in some layer-objs but not others), # and also use it to get back to current coords: (index, parent) -> get to parent coords, then tell parent to get to mine via index. # something like: dict(_index = index, _inherit = parent-env) # where parent index chain is visible in _inherit, I guess... not sure & kluge. #### BTW it's so common for the index to be the only changing thing in the lexenv, that we might pass it in parallel as an optim/clarification. # then we ought to build up the chain explicitly as (local-index, parent-chain), and leave room for interning it as a key int, i suppose. # digr: do we intern it separately in separate layers? we might need to if they are persistent! (or intern it only in the most persistent one?) return self._lexenv # stub, and besides, are we supposed to store it? i suppose we might as well... could always zap if we finalize self... pass # ==
NanoCAD-master
cad/src/exprs/outtakes/NewInval.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ $Id """ outtakes file # [this first part was written in test.py, thus the globalvar naming scheme.] # 070228: # How can we get the functions of both _19i and _30i in one integrated setup? # Well, can we just display both their control panels (world_uis) in a column?? # yes [works more or less], but they need to share the same World! Right now they each make their own. # Also, they have different ideas of how to display their world -- both draw it unchanged, # but one of them draws a background too (for sketching on)... we might change that later # (for sketching on model objs instead), but for now, we'll switch between them (so leave them as # separate testexprs) but let each one show the same world differently. # We'll also want to move each of their tool_maker functions inside their world_ui instances. # And then we'll want the different possibly-drawn stuff (propmgr, mt, flyout tools, 3d, etc) # to be in the world_ui in different std attrs, and to wrap them in a general app-ui object. # And later that app-ui will just be the app object with a self-contained world_ui switcher and draw method. # Here's the "both panels" version (half-works but not useful -- both panels are on the same world_ui, only one does much): testexpr_34ix1 = eval_Expr( call_Expr( lambda world_ui: Overlay( world_ui, DrawInCorner( SimpleColumn( Boxed( eval_Expr( call_Expr( dna_ribbon_view_toolcorner_expr_maker, world_ui ))), Boxed( eval_Expr( call_Expr( demo_drag_toolcorner_expr_maker, world_ui.world ))), )), DrawInCorner( MT_try2(getattr_Expr(world_ui, 'world')), WORLD_MT_CORNER ), ), call_Expr( _app.Instance, testexpr_30b, "#34bi") ### needs to combine cmds in two kinds of world, # or add a cmd to make a thing to draw marks on like the bg object in _19haux # (and for that matter the make dna cyl has something to do with an origami construct # in a raster pattern) # (how would all this fit into a user story like mark's recent ones?) )) # Here instead are variants of _19i and _30i which use a shared world, but keep their outside function-made tool_makers. class _world_ui_user(DelegatingInstanceOrExpr): #e refile if accepted #e rename #e merge with app object?? not sure. "display the graphics area, property manager pane, and MT, given instructions on making it in an eclectic form (#fix soon)" world = Arg(World) world_ui_expr = ArgExpr(Anything) # an expr that needs the world as an option named 'world' tool_maker = Arg(Anything) # a function from world_ui to the prop mgr # formulae world_ui = Instance( world_ui_expr(world = world)() ) #k not sure this will work, or ought to -- might want ._e_customize or ._e_supply_args # btw this Instance is not strictly needed, but is what we want in spirit delegate = Overlay( world_ui, # this is the 3d graphics area, as seen via the given world_ui DrawInCorner( Boxed( eval_Expr( call_Expr( tool_maker, world_ui )) )), # prop mgr (but lower right at the moment (default corner)) DrawInCorner( MT_try2( ###e OPTIM: this object ought to be shared ###k Q: maybe it already is, if our ipath is? world_ui.world ## getattr_Expr(world_ui, 'world') ), WORLD_MT_CORNER ), # mt (upper left) ##e probably should revise arg order to DrawInCorner(corner, thing) ) pass testexpr_19jaux = GraphDrawDemo_FixedToolOnArg1( # note: testexpr_11q1b is an Image of a file that's only on bruce's mac, but on other macs it should turn into a default image Overlay( testexpr_11q1b(size = Rect(10)), SimpleRow(Sphere(2),Sphere(1),Sphere(0.5),Sphere(0.25)) ), ) def _19j_tool_maker(world_ui): return demo_drag_toolcorner_expr_maker(world_ui.world) testexpr_19j = eval_Expr( call_Expr( lambda world: _world_ui_user( world, testexpr_19jaux, # needs to receive an option for the world [coded now] _19j_tool_maker, ), call_Expr( _app.Instance, World(), "#shared world") # the shared world (assuming _app is) )) testexpr_30j = eval_Expr( call_Expr( lambda world: _world_ui_user( world, World_dna_holder, # needs to receive an option for the world [coded now] dna_ribbon_view_toolcorner_expr_maker, ), call_Expr( _app.Instance, World(), "#shared world") # the shared world )) # update, 070302 morn: # The problem is, those don't work yet. They need two NFRs/bugfixes in the underlying code, before they can work: # - make possible the customization of an ArgExpr (in this case, world_ui_expr, in the expr world_ui_expr(world = world)() ), # by pushing a wrapping lexenv_ipath_Expr (which it needs, since it came from outer to inner lexenv) inside it # (making a modified/simplified copy, and also caching this as a "forward value" from the original expr) # to its contained arg/opt exprs from prior customizations (stored in _e_args and _e_kws), # not forgetting to pick up the lexenv mods _i_grabarg would do using .env_for_args (which come in between), # also so that further customization exprs *don't* end up (incorrectly) inside that originally-wrapping lexenv_ipath_Expr. # (This also requires worrying about how to deal with ipath in this, and some other issues discussed in a non-cvs notesfile.) # - permit a bare Expr subclass (e.g. World_dna_holder in the eg above) to be passed in as a customizable ArgExpr. # This is probably not really needed for now, since we can probably work around it by customizing them first with a fake option. # # I worked out (partly on paper, 070301 late) the requirements & coding plans for "customization of an ArgExpr" -- the best way is to # split obj.env into .lexenv and .env, with .env coming from instantiation (and differing depending on its layer, eg for graphical # vs model objs, or being present more than once if we have partial instantiation (unlikely)), and being what i usually call dynenv # though it's not really that if that would mean something in the usual dynenv during a method call, # and with .lexenv being settable even on some pure exprs (as soon as their owning lexical environment is an Instance), # and in particular getting set as soon as a lexenv wrapper gets pushed in -- but when a copy is made for further customization, # getting removed from there and pushed further in (but modified by lexenv_for_args, to pick up grabarg's planned env for args) # around the stored arg exprs. The new arg exprs added by customization don't have that env wrapper, of course, which is the point. # But it might be better to defer that plan for now and just rework the above in the way I planned to anyway. # So let's try that here. # (TBC)
NanoCAD-master
cad/src/exprs/outtakes/demo_ui-outtakes.py
# == old comments, might be useful (e.g. the suggested formulas involving in_drag) # I don't think Local and If can work until we get WEs to pass an env into their subexprs, as we know they need to do ####@@@@ # If will eval its cond in the env, and delegate to the right argument -- when needing to draw, or anything else # Sensor is like Highlightable and Button code above # Overlay is like Row with no offsetting # Local will set up more in the env for its subexprs # Will they be fed the env only as each method in them gets called? or by "pre-instantiation"? ##def Button(plain, highlighted, pressed_inside, pressed_outside, **actions): ## # this time around, we have a more specific API, so just one glname will be needed (also not required, just easier, I hope) ## return Local(__, Sensor( # I think this means __ refers to the Sensor() -- not sure... (not even sure it can work perfectly) ## 0 and Overlay( plain, ## If( __.in_drag, pressed_outside), ## If( __.mouseover, If( __.in_drag, pressed_inside, highlighted )) ), ## # what is going to sort out the right pieces to draw in various lists? ## # this is like "difference in what's drawn with or without this flag set" -- which is a lot to ask smth to figure out... ## # so it might be better to just admit we're defining multiple different-role draw methods. Like this: ###@@@ ## DrawRoles( ##e bad name ## plain, dict( ## in_drag = pressed_outside, ### is this a standard role or what? do we have general ability to invent kinds of extras? ## mouseover = If( __.in_drag, pressed_inside, highlighted ) # this one is standard, for a Sensor (its own code uses it) ## )), ## # now we tell the Sensor how to behave ## **actions # that simple? are the Button actions so generic? I suppose they might be. (But they'll get more args...) ## )) # == old code if 0: Column( Rect(1.5, 1, red), ##Button(Overlay(TextRect(18, 3, "line 1\nline 2...."),Rect(0.5,0.5,black)), on_press = print_Expr("zz")), # buggy - sometimes invis to clicks on the text part, but sees them on the black rect part ###@@@ # (see docstring at top for a theory about the cause) ## Button(TextRect(18, 3, "line 1\nline 2...."), on_press = print_Expr("zztr")), # ## Button(Overlay(Rect(3, 1, red),Rect(0.5,0.5,black)), on_press = print_Expr("zzred")), # works ## Button(Rect(0.5,0.5,black), on_press = print_Expr("zz3")), # works Invisible(Rect(0.2,0.2,white)), # kluge to work around origin bug in TextRect ###@@@ Ribbon2(1, 0.2, 1/10.5, 50, blue, color2 = green), # this color2 arg stuff is a kluge Highlightable( Ribbon2(1, 0.2, 1/10.5, 50, yellow, color2 = red), sbar_text = "bottom ribbon2" ), Rect(1.5, 1, green), gap = 0.2 ## DrawThePart(), ) # ... FilledSquare(color, color) ... Closer(Column( Highlightable( Rect(2, 3, pink), # this form of highlight (same shape and depth) works from either front or back view Rect(2, 3, orange), # comment this out to have no highlight color, but still sbar_text # example of complex highlighting: # Row(Rect(1,3,blue),Rect(1,3,green)), # example of bigger highlighting (could be used to define a nearby mouseover-tooltip as well): # Row(Rect(1,3,blue),Rect(2,3,green)), sbar_text = "big pink rect" ), #Highlightable( Rect(2, 3, pink), Closer(Rect(2, 3, orange), 0.1) ) # only works from front # (presumably since glpane moves it less than 0.1; if I use 0.001 it still works from either side) Highlightable( # rename? this is any highlightable/mouseoverable, cmenu/click/drag-sensitive object, maybe pickable Rect(1, 1, pink), # plain form, also determines size for layouts Rect(1, 1, orange), # highlighted form (can depend on active dragobj/tool if any, too) #e sbar_text? # [now generalize to be more like Button, but consider it a primitive, as said above] # handling_a_drag form: If( True, ## won't work yet: lambda env: env.this.mouseoverme , ####@@@@ this means the Highlightable -- is that well-defined??? Rect(1, 1, blue), Rect(1, 1, lightblue) # what to draw during the drag ), sbar_text = "little buttonlike rect" ) )) # see also: ## ToggleShow-outtakes.py: 48: on_press = ToggleAction(stateref)
NanoCAD-master
cad/src/exprs/outtakes/Highlightable-old-demos.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ basic.py -- define things to be imported by every module in this package (using import *) $Id$ """ # Import order issues -- # This module basic gets imported first, and it will be imported at the beginning of most modules. # But it wants to define things of general interest to all modules. # # This can lead to recursive import problems. Here is how we will resolve them: # - If a high-level def should be included here, import it last. # Then when it imports basic, it will find what it needs already defined in basic. # - When we import several high-level defs, they should be lowest-level first; higher ones will find lower ones # defined in basic when they import it, but not vice versa (but they shouldn't need to find them). # - When we import symbols like Expr or define symbols like Arg, also do this in order of level, in terms of import dependency. # # Note that this means we can't put all our import statements first -- # we have to interleave them with local defs, based on level. # # Specific problems: # - ExprsMeta knows about special cases for some symbols defined in modules which have to import ExprsMeta for its metaclass. # Solution: ExprsMeta should only import those special-case symbols at runtime. # (And it should do so using reload_once, so their own modules can support runtime reload.) # # Approximate order of imports: # - Python and debug utilities (especially the ones needed by ExprsMeta), including those defined outside this exprs package # - ExprsMeta (needed as a metaclass by many classes we'll define) # - abstract classes like Expr and InstanceOrExpr # - widget classes, in order of lowest to highest level (most of them don't need to be imported by this module at all) # == imports from python itself import sys, os from Numeric import dot sys.setrecursionlimit(650) # 5000 is set in startup_funcs.py; this will ease debugging, but REMOVE WHEN DEVEL IS DONE [061121] # == imports from cad/src from geometry.VQT import V, A, Q, norm, vlen, cross from math import sqrt #070225 from math import pi, sin, cos #070130 from foundation.state_utils import transclose, same_vals ## not yet needed: from state_utils import _UNSET_ # warning: not included in "import *" from utilities.constants import noop # def noop(*args,**kws): pass from utilities.debug import print_compact_traceback, print_compact_stack, safe_repr from utilities.debug_prefs import debug_pref, Choice_boolean_False, Choice_boolean_True, Choice #070228 # consider also doing: import env as global_env [070313 suggestion] # == OpenGL imports -- for now, individual modules import things from submodules of OpenGL as needed; this might be revised from exprs.reload import reload_once # == low-level imports from this exprs package import exprs.py_utils reload_once(exprs.py_utils) #from py_utils import * # includes printnim, identity, seen_before from exprs.intern_ipath import intern_ipath # (it doesn't make sense to try to autoreload this module -- ###e it should say so in some attr) # == ExprsMeta #e and whatever it requires #from ExprsMeta import * ###e can this support autoreload?? ###e note -- this imports a few other modules - list those here ##doc from exprs.__Symbols__ import _self, _my # (__Symbols__ module doesn't support reload) # warning: not included in "import *" # _this is imported below from somewhere else -- since it's not a Symbol! Maybe __Symbols__ should warn if we ask for it. #e from exprs.__Symbols__ import _app # not included in import * [070108 in test.py, moved here 070122] # == fundamental defs import exprs.Exprs reload_once(exprs.Exprs) # doesn't support reload, for now, so this is a noop #from Exprs import * # Expr, lots of predicates and subclasses import exprs.StatePlace reload_once(exprs.StatePlace) from exprs.StatePlace import StatePlace, set_default_attrs # revised 061203, and moved before instance_helpers & If_expr import exprs.attr_decl_macros reload_once(exprs.attr_decl_macros) #from attr_decl_macros import * # Instance, Arg, Option, ArgOrOption, State, etc import exprs.instance_helpers reload_once(exprs.instance_helpers) from exprs.instance_helpers import InstanceOrExpr, DelegatingMixin, DelegatingInstanceOrExpr, InstanceMacro from exprs.instance_helpers import _this, ModelObject, WithModelType, WithAttributes import exprs.If_expr # 061128 reload_once(exprs.If_expr) #from If_expr import * ##import staterefs ##reload_once(staterefs) ##from staterefs import * import exprs.iterator_exprs # 070302 reload_once(exprs.iterator_exprs) #from iterator_exprs import * # === higher-level defs, common enough to import for everything import widget2d reload_once(widget2d) from widget2d import Widget, Widget2D # == higher-level stubs # stub types which are also defined as classes in other files import Set reload_once(Set) from Set import Action # import added 070115 ###k hmm, is the Set module name a conflict with the proposal for class Set to be imported in this file, basic.py? import statearray reload_once(statearray) from statearray import StateArray, StateArrayRefs # layout prims and the like (but for the most part, layout prims probably won't be defined in basic.py at all) # [none at the moment] # == end
NanoCAD-master
cad/src/exprs/outtakes/basic.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ $Id$ WARNING: perhaps never tested since removed from demo_MT.py on 070210 -- essentially just an outtakes file, saved in case comments are still relevant; mayb still be imported from test.py """ # == imports from basic import * from basic import _self from ToggleShow import * # e.g. If, various other imports we should do explicitly #e ### FIX THIS, do them explicitly from Set import Set ##e move to basic from Rect import Rect, Spacer from images import IconImage, Image #e and more from Center import CenterY from demo_MT import node_kids, node_openable, mt_node_id, node_name # == stubs If = If_kluge ####e until it works, then remove and retest Node = Stub # [later note 061215: this is probably the same as Utility.Node; it's NOT the same as that's new subclass, ModelNode.] # == trivial prototype of central cache of MT-viewers for objects # WARNING [added 061215]: this assumes _make_new_MT_viewer_for_object uses no usage-tracked values and thus never needs recomputing. # That's probably true since the reload counter is in the key. If that becomes false, we'll probably need to replace MemoDict # with a variant based on LvalDict2. def _make_new_MT_viewer_for_object(key): obj, essential_data, reload_counter = key print "viewing node %r, reload_counter = %r" % (obj, reload_counter) # leave this in, since it's only used by deprecated MT_try1 # obj is a Node or equivalent mt_instance = MT_try1(obj) # but will this work, with arg1 being already instantiated -- will it make an instance? not yet! ###IMPLEM that ###BUG (presumed, 070206, old): this is actually an expr, not an instance. # The correct fix is to instantiate it now -- *not* automatically when MT_try1(obj) is formed, as a comment above says should be done -- # and to index it by both the "whole MT" we're populating (perhaps a "self" this function should be a method in), # and the "node_id" of obj (something unique, and never recycled, unlike id(obj)). # This may require passing that "whole MT" in dynenv part of Instance.env with Instance part of essential data, # or revising how we call this so it can just get "whole MT" as one of the args. # The code that needs revising is mainly MT_kids_try1 -- see more comments therein. return mt_instance _MT_viewer_for_object = MemoDict( _make_new_MT_viewer_for_object) # args are (object, essential-data) where data diffs should prevent sharing of an existing viewer # (this scheme means we'd find an existing but not now drawn viewer... but we only have one place to draw one at a time, # so that won't come up as a problem for now.) # (this is reminiscent of the Qt3MT node -> TreeItem map... # will it have similar problems? I doubt it, except a memory leak at first, solvable someday by a weak-key node, # and a two-level dict, key1 = weak node, key2 = essentialdata.) def MT_viewer_for_object(obj, essential_data = None): from exprs.reload import exprs_globals # untested since vv was renamed and moved reload_counter = exprs_globals.reload_counter # ditto # this is so we clear this cache on reload (even if this module is not reloaded) # which partly makes up for not live-updating the displayed MT key = (obj, essential_data, reload_counter) return _MT_viewer_for_object[ key ] # assume essential_data is already hashable (eg not dict but sorted items of one) ##class Column(InstanceMacro): #kluge just for MT_kids_try1 ## eltlist = Arg(list_Expr) ## _value = SimpleColumn( *eltlist) ### this is wrong, but it seemed to cause an infinite loop -- did it? ###k ## exceptions.KeyboardInterrupt: ## [debug.py:1320] [debug.py:1305] [test.py:120] [demo_MT.py:100] [demo_MT.py:102] (this line) ## [Exprs.py:271] return getitem_Expr(self, index) [Exprs.py:360] [Exprs.py:880] # guess: *expr is an infloop, since it tries to turn it into a sequence, forming expr[0], expr[1], etc, forever. # the Exprs lines above are probably compatible with that. # Can this bug be detected? Is there an __xxx__ which gets called first, to grab the whole sequence, # which I can make fail with an error? I can find out: *debug_expr where that expr prints all getattr failures. Later. class MT_kids_try1(InstanceMacro): # args kids = Arg(list_Expr)####k more like List or list or Anything... ##### note: the kid-list itself is time-varying (not just its members); need to think thru instantiation behavior; # what we want in the end is to cache (somewhere, not sure if in _self) # the mapping from the kid instance (after If eval - that eval to fixed type thing like in Column, still nim) # to the MT_try1 instance made from that kid. We would cache these with keys being all the args... like for texture_holder. # so that's coarser grained caching than if we did it in _self, but finer than if we ignored poss of varying other args # (btw do i mean args, or arg-formulae??). # note that the caching gets done in here as we scan the kids... *this* instance is fixed for a given node.kids passed to it. # BTW maybe our arg should just be the node, probably that's simpler & better, # otoh i ought to at least know how it'd work with arg being node.kids which timevaries. ## _value = Column( map_Expr( MT_viewer_for_object, kids )) ###e change to caching map?? no, MT_viewer_for_object does the caching. #e needs Column which takes a time-varying list arg #e change to ScrollableColumn someday # (also resizable, scrolling kicks in when too tall; how do we pick threshhold? fixed at 10?) def _C__value(self): # we need this since we don't yet have a way of including " * map(func,expr)" in a toplevel expr. kids = self.kids assert type(kids) == type([]) elts = map(MT_viewer_for_object, kids) ###BUG (presumed, 070206): elts is a list of exprs; intention was a list of instances. # The effect is that, if this is recomputed (which does not happen in testexpr_18, but does in testexpr_30h, 070206 10pm), # it evals to itself and returns a different expr to be instantiated (by code in InstanceMacro) using the same index, # which prints ## bug: expr or lvalflag for instance changed: self = <MT_kids_try1#64648(i)>, index = (-1021, '!_value'), ## new data = (<SimpleColumn#65275(a)>, False), old data = (<SimpleColumn#64653(a)>, False) # and (evidently, from the failure of the visible MT to update) fails to make a new instance from the new expr. # The fix is discussed in comments in MT_viewer_for_object but requires a rewrite of MT_try1 and MT_kids_try1 classes. ####TRYIT res = SimpleColumn(*elts) # [note: ok even when not elts, as of bugfix 061205 in SimpleColumn] ## return res # bug: AssertionError: compute method asked for on non-Instance <SimpleColumn#10982(a)> # I guess that means we have to instantiate it here to get the delegate. kluge this for now: return res._e_eval(self.env, ('v',self.ipath)) # 'v' is wrong, self.env is guess pass ##_ColumnKluge = Column # don't let our kluge mess up someone who unwisely imports * from here ##del Column class MT_try1(InstanceMacro): # deprecated MT_try1 as of 070208, since MT_try2 works better # WARNING: compare to ToggleShow - lots of copied code -- also compare to the later _try2 version, which copies from this # args node = Arg(Node) #### type? the actual arg will be a node instance... # state refs open = State(bool, False) # other formulae # Note, + means openable (ie closed), - means closable (ie open) -- this is the Windows convention (I guess; not sure about Linux) # and until now I had them reversed. This is defined in two files and in more than one place in one of them. [bruce 070123] open_icon = Overlay(Rect(0.4), TextRect('-',1,1)) closed_icon = Overlay(Rect(0.4), TextRect('+',1,1)) openclose_spacer = Spacer(0.4) #e or Invisible(open_icon); otoh that's no simpler, since open_icon & closed_icon have to be same size anyway # the openclose icon, when open or close is visible (i.e. for openable nodes) openclose_visible = Highlightable( If( open, open_icon, closed_icon ), on_press = Set(open, not_Expr(open)) ) openclose_slot = If( call_Expr(node_openable, node), openclose_visible, openclose_spacer ) icon = Rect(0.4, 0.4, green)##stub; btw, would be easy to make color show hiddenness or type, bfr real icons work ###k is this a shared instance (multiply drawn)?? any issue re highlighting? need to "instantiate again"? ##e Better, this ref should not instantiate, only eval, once we comprehensively fix instantiation semantics. # wait, why did I think "multiply drawn"? it's not. nevermind. ##e selection behavior too label = TextRect( call_Expr(node_name, node) ) ###e will need revision to Node or proxy for it, so node.name is usage/mod-tracked ##e selection behavior too -- #e probably not in these items but in the surrounding Row (incl invis bg? maybe not, in case model appears behind it!) ##e italic for disabled nodes ##e support cmenu _value = SimpleRow( openclose_slot, SimpleColumn( SimpleRow(CenterY(icon), CenterY(label)), #070124 added CenterY, hoping to improve text pixel alignment (after drawfont2 improvements) -- doesn't work If( open, MT_kids_try1( call_Expr(node_kids, node) ), ###e implem or find kids... needs usage/mod tracking Spacer(0) ###BUG that None doesn't work here: see comment in ToggleShow.py ) ) ) pass # end of class MT_try1 # end
NanoCAD-master
cad/src/exprs/outtakes/demo_MT_try1_obs.py
$Id$ ## DraggableHandle(appearance = whatever, behavior = whatever, dragged_position = whatever) # formulae drag_behavior = Option( DragBehavior, SimpleDragBehavior, doc = "our drag behavior (not including a stateref to dragged position)") state = Option(StateRef, None, doc = "ref to the position-related state which dragging us should change, according to our drag_behavior") ###k _value = Highlightable( appearance, drag_behavior = drag_behavior(state) ) ###k pass
NanoCAD-master
cad/src/exprs/outtakes/DraggableHandle-outtakes.py
$Id$ # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. this file should not remain in cvs once devel is done class LvalForDisplistEffects(Lval): #stub -- see NewInval.py and paper notes """ Lval variant, for when the value in question is the total drawing effect of calling an OpenGL display list (which depends not only on the OpenGL commands in that display list, but on those in all display lists it calls, directly or indirectly). [The basic issues are the same as if the effect was of running an external subroutine, in a set of external subrs whose code we get to maintain, some of which call others. But there are a lot of OpenGL-specific details which affect the implementation. The analogous things (external Qt widgets, POV-Ray macros) are like that too, so it's unlikely a common superclass LvalForThingsLikeExternalSubroutines would be useful.] """ def _compute_value(self): "[unlike in superclass Lval, we first make sure all necessary display list contents are up to date]" pass pass ##DelegatingWidget3D DelegatingWidget # 2D or 3D -- I hope we don't have to say which one in the superclass! ### # Can the Delegating part be a mixin? Even if it is, we still have to avoid having to say the 2D or 3D part... ### class DisplayListChunk(DelegatingWidget): def _init_instance(self): DelegatingWidget._init_instance(self) instance_of_arg1 # what is this? it needs to be set up by the prior statement, or by that time... see our make_in code... ### # allocate display list and its lval LvalForDisplistEffects # do what with this class? see below #e or could use _C_ rule for this kid-object, so it'd be lazy... but don't we need to pass it instantiation context? #### self.displist_lval = LvalForDisplistEffects( instance_of_arg1 ) ####@@@@ like CLE, do we need to actually make one displist per instance of whatever we eval arg1 to?? # problem is, there's >1 way to do that... so for now, assume no. pass def draw(self): """ compile a call to our display list in a way which depends on whether we're compiling some other display list right now, in self.env.glpane -- how to do that is handled by our displist owner / displist effects lval """ self.displist_lval.call_displist() # this will call instance_of_arg1.draw() if it needs to compile that displist pass # == class DisplistInvalidatable: pass ### # several levels: opengl; invalidating a rewritable external subroutine; inval per se from lvals.py: class LvalForDrawingCode(Lval): #stub -- do we need this, or just pass an appropriate lambda to Lval? ##e """ [deal with get_value returning side effects? or using .draw instead -- just internally?] """ pass """ But when compiling another list, we're not *allowed* to do it that way, since we can't compile any other list (ours or one it calls) at the same time. Fortunately we don't have to, even if we don't discover which lists we call until we recompile ours, since it's safe to compile called lists later, as long as it happens before ours can next be called. So we add all lists we indirectly call (including our own) to a dict of lists maintained by the caller, which it will know it needs to recompile before calling ours. (In fact the caller is likely to run a recursive display list updating algorithm in which ours is not necessarily the top list; and the addition of our called lists has to occur lazily since they're not known until that algorithm recompiles ours To accomplish the above, we call , since they differ in when our display list call will be executed. In immediate mode, we have to first separately compile the display list, in order to (This might be executed immediately or compiled into another display list, depending on when we're called.) But a few extra effects are necessary: - If the contents of any display list used when ours is called are not up to date, we have to fix that before ours gets called. In immediate mode, this means, before emitting glCallList; if another list is being compiled, it means, sometime before that list's drawing effects are marked valid. ... tracking of two kinds, etc... explain recursion... list contents are not up to date, then before our list can be called, [Note: might be called when actual drawing is occurring, or when compiling another displist.] """ # === # Here are comments that might be up to date in main file, but even if so, might be redundant now, # and in any case are old and have not been recently reviewed. # So better to leave them out and rewrite them or review them later. # ... maybe just write down the pseudocode for calling a display list in imm mode, which remakes some, which calls some in compiled mode? """ Reviewing situation of lvals for displists, 061023: - What's interesting about draw methods in general, vs ordinary "compute methods": - they return their main value in the form of side effects - there are really two values they implicitly return, and the set of things used by these (re usage tracking for inval) differs! - the set of OpenGL commands they emit -- inval of this means any display list containing these commands needs rewriting - the effects on the current frame buffers of running those OpenGL commands -- this also depends on some of the GL state, including the content of certain display lists which they call (directly or indirectly, but only direct calls should be recorded, since the set of indirect calls might change due only to changes in content of directly called displists). - if drawing commands affect other OpenGL state, is their effect on each aspect of that state another thing that needs tracking? If so, the above two things are special cases: - effect on content of displist currently being compiled - effect on framebuffer contents, assuming no displisp is being compiled, *or* at a future time when current one is run. - complete tracking of these things would have to consider how OpenGL commands can *move* state between aspects of GL context state. I think we can ignore that now, since we're not compiling such general OpenGL into display lists. (Except in coordinate systems, if we compile a translation... which we can handle in a specialcase way.) - it may be that, in general, we need to generalize "track usage" to "track usage, and what state it affects", so anything we do (that gets usage-tracked) could say "I used this to affect that", where "that" is e.g. a specific display list, or the opengl commands being emitted. - a Q that needs answering, and leads to the above: if several kinds of usage are tracked, which one is tracked "normally" and which in special ways? I thought it was "displist calls are tracked specially, not variable accesses", but I'm having trouble explaining this rationally within the above framework. But, ordinary variable access, if it affects anything, affects both things we're tracking our effect on, since it affects our output of OpenGL. Display lists we call are the only things with a different effect on each one. This justifies tracking variable access in usual way, and called displists specially, but these *don't* correspond directly to the two things we can affect. It's as if we tracked usage in two parallel but independent worlds (python vars and opengl state) and "in the end" know how to combine them: drawing effect depends on both, opengl output depends on only one. Preliminary conclusions: - draw methods do track two different things... and ordinary var access tracking can be totally standard, unaffected by the parallel tracking of calls of displists. Not sure yet about tracking effects on other OpenGL state, esp if they use other OpenGL state. (Should we track an effective function we're applying to OpenGL state, via state = f(state)??) - we do need a special kind of Lval whose value is the OpenGL commands issued into a display list; and maybe another one, whose value is the OpenGL commands issued by any draw method. The latter is special re side effect output and need for a version number (when we need to store inputs to whoever used it, for diff old and new in them); the former is also special in the concern about which displists were called, and corresponds to an op on draw methods, one is "run a displist" and the inner one is "emit its contents when compiling it". Maybe this means two special lval classes, each having one inval flag, rather than one, handling two flags? ####@@@@ """ in class DisplayListChunk: """Each object of this class owns one OpenGL display list (initially unallocated) in a specific OpenGL context, and keeps track of whether its contents (OpenGL commands, as actually stored in our GL context) might be invalid, and whether any of its kids' contents might be invalid. (By "kids" here, we mean any displists ours calls, directly or indirectly.) We also need to know how to regenerate our displist's contents on demand, tracking all displists it directly calls, as well as doing the usual usage-tracking of modifiable values on which the contents depends. We record these things separately so we can be invalidated in the necessary ways. A main public method ensures that our contents and our kids' contents are up to date. The algorithm is to transclose on the set of displists we call (including self.displist), and by calling a private method of this class on each one, to ensure updatedness of its contents and of its record of its direct kids, allowing us to tranclose on the direct kids. We also have a public method to call our displist in immediate mode, which must first use the prior method to ensure updatedness of all displists that that would call. (That means it has to use GL_COMPILE followed by glCallList, not GL_COMPILE_AND_EXECUTE, since in the latter case, it might encounter an unexpected call to a kid displist which is not up to date, and have no way to make it up to date, since OpenGL doesn't permit recursive compiling of displists.) We also have a method to compile a call to self.displist, which although callable by arbitrary commands' drawing code, is semi-private in that it's only legally called while some object of this class is compiling a displist, and it assumes there is a global place in which to record that displist call for use by that object's tracking of called displists. # == To fit with the "maybe-inval" scheme for avoiding recomputes that we were warned might be needed, but turn out not to be (as detected by a recompute rule noticing old and new values of all inputs are equal, or "equal enough" for how it uses them), we would need a way of asking self.delegate.draw whether its output (i.e. the OpenGL commands it generates, usually reported only by side effect on a GL context -- note that its direct kidlist is a function of that output) would actually be different than the last time we called it for compiling into our display list. This is not yet implemented... it would probably require separation of "asking for drawing code", "diffing that" (via a proxy version-counter, or perhaps by direct graph comparison of the code's rep), and executing that in some GL context. ###k BTW [digr], I think the maybe-inval scheme in general is just to pass on a maybe-inval signal, and later to be asked whether inval is really needed, and to ask kids the same, perhaps diffing their values... the hard part is that different users of one value need different answers, e.g. if one user used it so long ago that it changed and changed back since then, though other users used it when it was changed. This is why we can't only ask the kid -- we can, but even if it recomputes, we have to diff to really know. I suspect this means that it's equivalent to an ordinary inval scheme, with each function also optimizing by memoizing the answer given certain inputs, namely the last ones it used. I'm not sure of all this. ###k Summary of public methods: - call our displist in immediate mode - call it while compiling another displist [both of those are called by glpane when it's asked to call a displist, or an array of them; it switches on its flag of whether it's currently compiling a displist; if it is, it knows the owning object, so it can *ask that object* to make the record.] MAYBE WRONG?, they are called by self.draw... ok?? no, prob not... ######@@@@@@ - report our displist name (this is just the public attribute self.displist, which has a recompute rule) """ # maybe semi-obs comments: # belongs to one gl-displist-context # has self.displist (glpane displist id in that context) # has arg, self.delegate, can redraw it - it's an instance of a drawable # maintains formula: thing's draw-effects is an input to this guy's draw-effects # so if thing's draw-effects change, and something wants "return" (do, where specified) of self draw-effects, # and that caller might or might not be itself making a displaylist, # then we can do that (by emitting a call of this guy's displist, perhaps merged with other calls if we call several in a row) # (that merging can be autodone by our glpane, if it records all gl commands -- hmm, that's errorprone, leave it for later, # it doesn't affect this guy's code anyway) # but for callers making a displist, only if we warn caller that before it runs that displist, it better have us recompile ours, # which we do by adding ourself to a set in the calling env; # whereas for callers not making a displist, only if we *first* remake ours, before emitting the call, # *or* if we remake ours in compile-execute mode (equiv since when it later means smth else, that doesn't matter anymore # since current cmds not being saved) (and i'm not sure it's always possible to first remake ours, then call it) # (though we can try and see -- it's a user pref which is mainly for debugging, might affect speed or gl-bugs) # if thing's draw effects don't change, and smth wants us to draw, in either case we just emit a call of the displist. # == obs stuff def call_in_immediate_mode(self): #i think this is OBS self.ensure_ready_for_immediate_mode_call() ### change to external helper func, since it works on many objs of this class? yes. # or class method? (nah) self.call_our_displist() #### RENAME to make private old = glpane.begin_tracking_displist_calls(new_sublists_dict) ###IMPLEM try: self.recompile_our_displist() # render our contents into our displist using glNewList except: print_compact_traceback() pass glpane.end_tracking_displist_calls(old) def ensure_our_displist_gets_recompiled_asap(self): self.glpane.displists_needing_recompile_asap[ self.displist] = self return def __init__(self): self.displists_needing_recompile_asap = {} def recompile_displists_that_need_it(self): while self.displists_needing_recompile_asap: listname, object = self.displists_needing_recompile_asap.popitem() if not self._not_needing_recompile.has_key(listname): # what we do next can add items to that dict, right? hmm, can they be the ones we already popped??? ######@@@@@@ self._not_needing_recompile[listname] = object # maybe we have to store a counter (saying when they were up to date)?? ### make sure that if they are in here, we don't think we need to remake them, or maybe check when we pull them out object.recompile_our_displist() return -- if 'self.delegate.draw() total effects changed': #####@@@@@ how to find out? not in usual way, that would draw it right now! # maybe: if self.delegate.draw_effects_version_counter > ... -- do we have to store version that got drawn, to make each # displist we call it in? no, just assume any inval tells us to remake it. inval propogate is enough, no counter needed, # i bet. ### or can we say, that would return a routine to draw it??? ## also what need we do, to say that we've updated to use this info? will running thing.draw revalidate it? # not in all contexts, just this one! will it incr a counter, so we can look and see which draw effects are latest # and which ones we last grabbed? yes, i think so, esp since other inval objects need to "diff" results, # and the number would stand for the results, hash them as it were. maybe we need it too for some reason. #####@@@@ if self.glpane.compiling_displist: self.do_glCallList() self.ensure_our_displist_gets_recompiled_asap() # this schedules something which will soon, but not now, call thing.draw # (asap means before drawing the one being compiled, eg before any immediate mode drawing) # WRONG [061023 comments]: just because total effects changed, doesn't mean gl commands changed. # What is right is: recompile of this one (or each one in the tree of diplist calls) might not be needed; # instead, visit the entire tree, but recomp only the ones that got an inval, and that does revise # their list of kids in the tree (really a dag; don't recomp one twice -- inval flag reset handles that), # then (using list of kids, and only first time hit, via transclose), look at list of kids. # So each one stores the list of kids, and uses it two ways: subs to total effects inval, and scan them. # This is stored next to "an lval for a displist's total effects". Maybe that points to "lval for dlist contents". # In other words, two new lval classes: Lval for a displist effects, Lval for opengl coming out of a draw method. else: # immediate mode - don't call it until it's remade! ###e also need to recompile any lists listed in self.glpane.displists_needing_recompile_asap!!! i think... if 'oneway': self.recompile_our_displist() self.glpane.recompile_displists_that_need_it() # might do more lists than before prior statement added some ### self.do_glCallList() else: # anotherway -- is this possible? only if we know in advance which lists will get used by the following! assert 0, "nim, since we need to know more..." #e recompile_displists_that_need_it, including ones we're about to call in following statement self.recompile_and_execute_our_displist() pass pass else: self.do_glCallList() -- the comments in the following now seem resolved, and the code correct, so removing most of them def invalidate_contents(self): "[private] called when something changes which might affect the sequence of OpenGL commands that should be compiled into self.displist" ###e should propogate?? not sure -- this needs to inval the drawing effects of whatever drawing uses us... # but if something draws, does it track anything? what if the glpane itself calls us? this should tell it to gl_update! # but right now it doesn't... we'll need some fix for that! or a toplevel use of one of these for it... or an invalidator arg for this expr... # IN THEORY this means that glpane (or other pixmaps made from draw calls) should subs to total drawing effect, # whereas a dlist compile (calling the very same draw method) should only subs to opengl commands, not their effect! # THIS MAY PROVE THE NEED FOR TRACKING TWO DIFFERENT THINGS IN THE ENV for everything we can call in draw... # or maybe not, since if we use something, how could it know which to affect? it can't. # so only correct way is to switch effects over at the boundaries of compiling a list (smth like what we do)... # but not sure it's correct YET. Guess: it's fine if we change glpane to also notice dlist calls, and change this code to inval it # when a dlist runs in imm mode. This code should do that with a special routine in glpane, called in imm mode draw... # or maybe, easier, by "using a fake lval" then, and changing it when our drawing effects change... # then that lval would relate somehow to the flag we have and the subs to effects of sublist drawing. #####k DOIT - NEED TO FIGURE THIS OUT CLEARLY # ... ok: in general you have to track what you use with what in your env it would effect. # if you emit a calllist, then in imm mode, the total drawing effect of that affects the pixmap you draw onto and the other gl state... # but in compiling mode, only the opengl commands affect the gl state, but the other stuff they do has to be tracked in some other way # with the list owner. So we're assuming that the only opengl commands we do that have effects dependent on other gl state or other list contents # are the calllists, even though in general this might be false. But assuming that, all we need to do is "track different usage in those cases" # in self.draw. ###DOIT ## printnim("propogate inval from invalidate_contents") # but maybe the only one to really propogate is for our total drawing effects... if self.contents_valid: self.contents_valid = False self.invalidate_drawing_effects() #k I THINK this is all the propogation we need to do. NEED TO REVISE ABOVE COMMENT if so. else: # this clause would not be needed except for fear of bugs; it detects/complains/works around certain bugs. if self.drawing_effects_valid: print "bug: self.drawing_effects_valid when not self.contents_valid. Error, but invalidate_drawing_effects anyway." self.invalidate_drawing_effects() pass return == # old cmt: prob wrong name [of method -- draw], see above too obvious: # (note: we pass self == self.displist owner, not self.displist)
NanoCAD-master
cad/src/exprs/outtakes/DisplayListChunk-outtakes.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Animate.py [just notes so far] $Id$ """ """ Animate [some thoughts, 061121] on_press = Animate(args) an Action which creates a temporary time-based formula... for interpolational-setting of the side effects listed, or explicit formula for setting external vars to, or.... [arg syntax unexplored, need some simple desired egs first, see below] redraws measure time since start, decide what to draw (based on time), whether to gl_update after draw (whether we didn't reach the end) (but the actual setting of a specific time comes at the start of the redraw, as late as possible, so motion looks as accurate as poss) (an indep setting gives max frame rate to permit, but for now, max possible will be what we want, very likely) (measurement is in real time, not counting time we're suspended in some way, eg user pause button, not in the app, etc) (we also want buttons to stop all anims, and to skip to end of all anims) other Actions: - Set(lval, newval) [see controls.py for a prototype, 061130, which takes a stateref rather than an lval as arg1 -- might be wrong] - Action(callable) # or just a bare callable? - give commands by their highlevel names see also scratch6.py, about behaviors & user events & binding actions to them simple desired egs: - interpolate any given attr-change in a gradual way - (over a given or standard (user pref) time duration) - (with the interpolation method a property of the attr itself -- as if a fancier form of __setattr__, __setattr_animated__) [implem: does it actually temporarily set it to a formula? might be most efficient, if not all such attrs are always needed!!] - pass constants to formulas in an animated range - ie when specifying rotation of a newly made thing, say it starts x, anims to y, rests at y (ie real value for saving in files is y) - ambiguity - for using in other computations, use final or animating value? if final, we have to know (declare) which other comps are for drawing and which are not. hmm. motivations: - in a lot of user actions in UIs, it'd be easier to understand if the change occurred gradually. (and we want this to be easy to express) - might be useful for inputs to interactive physics, too. (ie it's a form of programmed control path) - might even be useful for inputs to non-interactive physics -- this lets you preview the path interactively as you devel it, but the same path can be passed to a sim which will use it as input, even if sim itself is not realtime in speed and/or interaction. - production of movies -- e.g. part of a "key-frame animator". Note that in some egs, the animated actions effectively need to be first-class savable objects. (key-frame anim, sim path control) In those, the start time is somehow programmed, not "literally the time of giving the command" as in the user-action animation app. """ from basic import * # includes Action class Animate(Action): ... # end for now
NanoCAD-master
cad/src/exprs/scratch/Animate.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ demo_polygon.py [recently renamed from demo_dna.py] $Id$ scratch file about Resizer, Draggable, and especially Interface... and polygon-vertex dragging, for exploring some Draggable/DragCommand structure issues. The specific code in it is mostly about polygon-vertex dragging. """ from basic import * from basic import _self from Rect import Rect, RectFrame from Overlay import Overlay from transforms import Translate from Center import Center from Highlightable import Highlightable # let's start with a resizable rectangular raster of dna turns. # it's really a resizable guide shape on which we can draw regions of dna to fill in, # and they in turn act as guide shapes for placing actual strands, cyls, etc, or paths or seams. # but to start with, let's just be able to draw it... and have it draw some little objs on which to click to fill it or make crossovers. # so something much simpler is a resizable table of little rects. # it has the rects, and a resize handle. # do we bother at this stage to split it into its data and its appearance? Not yet, since that's hard.... Grid = Resizer = Stub class xxx(DelegatingInstanceOrExpr): nrows = State(int, 5) # each row is actually two helices ncols = State(int, 10) delegate = Overlay( Grid( Rect(1), nrows, ncols ), Resizer() # resizer of what? and, displayed where? aligned with a grid corner? how? # is a Box resizer (one per corner) any simpler? ) pass # ok, I've still never made a resizable box, resizable at each corner. class newerBoxed(DelegatingInstanceOrExpr): # args thing = Arg(Widget2D) # options borderthickness = Option(Width, 4 * PIXELS) gap = Option(Width, 4 * PIXELS) bordercolor = Option(Color, white) # internal formulas extra1 = gap + borderthickness ww = thing.width + 2 * extra1 #k I'm not sure that all Widget2Ds have width -- if not, make it so ##e [061114] hh = thing.height + 2 * extra1 # value delegate = Overlay( Translate( RectFrame( ww, hh, thickness = borderthickness, color = bordercolor), - V_expr( thing.bleft + extra1, thing.bbottom + extra1) ), #e can't we clarify this somehow? thing) pass ##class ResizableBox(DelegatingWidgetExpr): # compare to Boxed ## Overlay(RectFrame(), ## class resizablyBoxed(DelegatingInstanceOrExpr): # args thing = Arg(Widget2D) # display thing (arg1) in the box, but don't use it for the size except to initialize it # options borderthickness = Option(Width, 4 * PIXELS) gap = Option(Width, 4 * PIXELS) bordercolor = Option(Color, white) # state - initialize from formulas based on args and instance sizes, is that ok?? thing_width = State(float, thing.width) #k I'm not sure that all Widget2Ds have width -- if not, make it so ##e [061114] thing_height = State(float, thing.height) # internal formulas, revised to use state extra1 = gap + borderthickness ww = thing_width + 2 * extra1 hh = thing_height + 2 * extra1 # not yet any way to change the state... to test, add on_press which adds 1 to it or so #e # value delegate = Overlay( Translate( RectFrame( ww, hh, thickness = borderthickness, color = bordercolor), - V_expr( thing.bleft + extra1, thing.bbottom + extra1) ), #e can't we clarify this somehow? yes -- RectFrame should take origin, dx, & dy args. Highlightable(thing, on_press = _self.on_press_thing)) #e now we need to say that at each corner there's a resizer. # Resizer -- of what? looks like what? shown where? # really it's a kind of draggable -- a draggable corner, used to drag two intersecting lines (perp in this case). # We have to express an aspect of our state as "the posns of these two lines" -- # # / # if corner is ____/, then each line can be moved along the other one, so each line gives a vector of motion for a control point # on the other -- in fact, the vertex itself can be the control point for both (provided we can express the line that way on demand). # So a resizer of intersecting edges needs the edges as args, then it gets the point how? # But a polygon is natively more like a bunch of points... and variants of moving cmds of those are discussed elsewhere... # one is to move a set of points, controlling some edges fully (if both ends in the set) and some partly (keeping them parallel # or keeping other end fixed, depending on the tool). So we first turn selection into controlled & fixed aspects, then into # drag action on controlled aspects, which is basically a command to take a delta or new point and apply it to the state. # So how do we express a drag command of that kind? # Drag( what? a set of points... with info about how other things respond -- which depends on where you got the point-lvals.) # polygon.draggable_edges( vertex_set) -> ... # polygon.draggable_vertices( vertex_set) -> ... # Those can be args to whatever wants to know what to drag! The result is equivalent to a single draggable point, I guess... # anything that can accept a drag_from_p1_to_p2 command. So an object with some looks, and some drag commands in certain places, # can take draggables as args. Resizer() has a certain look, and places itself at the drag point: Resizer(draggable). # Note that it needs the draggable to have a center or corner or so, not just an ability to move from p1 to p2. # (The center is not usually equal to p1, but slightly offset from it.) # A CornerResizer would be specialized (in look) for a draggable corner. Also EdgeResizer. They'd still need binding to some # givable event (mouse button and mod key combo) (or to have a cmenu or so). And options to affect the look (like whether to have one). def on_press_thing(self): self.thing_width += 1 self.thing_height += 2 pass Data = Stub # Type? Interface? class DraggableCorner(Data): ### a description of a data type (an interface to data -- can be state-like, readable/settable) "an interface which has a draggable center point, and a corner on it (an ordered pair of vectors coming from it)" # attrs -- Attr?? Data?? State? Arg? Option? Are they used for construction? Implication of orthogonality for Set? point = Attr(Point) # Point? Position? it's supposed to be Draggable -- where do we say that? just say DraggablePoint here? vnext = Attr(Vector) # vector to next corner point (in ccw order) (e.g. to the right and up, if we're a bottom corner) vprev = Attr(Vector) # vector to previous corner point (e.g. to left and up, if we're a bottom corner) ###k these make sense as 2d vectors -- what about 3d? can still make perfect sense if we assume the thing is planar. draggable_commands = point.draggable_commands ###k ok to say it that way?? pass class Resizer(DelegatingInstanceOrExpr): "anything that has a delegate for looks, and puts a drag-binding on it which drags self.what" # looks like this, drags that ## def _cmd_drag_from_to(self, p1, p2): ## self.what._cmd_drag_from_to(p1,p2) ###k? or all the draggable_commands?? draggable_commands = _self.what.draggable_commands #e do we ask for this interface by name, when giving any of these commands?? ####k #e as if IorE had a rule, _cmd_drag_from_to = _self.draggable_commands._cmd_drag_from_to ? # overridable of course by a specific def of _cmd_drag_from_to. # (But if we override _cmd_drag_from_to, has that overridden something else asking us for self.draggable_commands? # Only if the specific methodname is effectively an alias (even for redef and inheritance, at least by deleg) for the # one in self.draggable_commands. That can be done somehow, *if* we can figure out the exact desired rules. ###e) # An alternative way of defining/implementing per-Interface delegation -- just a modification of delegation & inheritance # which can look up, for each attr, what interface it's in and therefore how to delegate it & define it. # Do we have a naming convention for assignable interfaces? _I_draggable = _self.what._I_draggable pass # which commands are the draggable_commands, aka _I_draggable or _I_Draggable ? # - _cmd_drag_from_to [#e rename -- more concise?] # - point or center (?) (also part of some more basic geometric interface) # (in fact a Draggable would often have a size & shape -- but it's not required) class CornerResizer(Resizer): what = Arg(DraggableCorner) mylen = 2 #stub; ideally we'd ask the edges if they have a thickness, and assign them one if not (for our sib corners to see) delegate = Rect(origin = what.point, dx = UnitVector(what.vnext) * mylen, dy = UnitVector(what.vprev) * mylen, color = white) # parallelogram pass # hmm, all we need for that is details and biggies: # - UnitVector # - Rect(origin = , dx = , dy =, color =) # - unstub mylen # - Data, and interface concept in general # - assign draggable_commands separately [could be done as outlined above] # - declare Attr/Data/State/Arg or whatever within a data type # - a lot of the ways we want to extend this are assuming we have a good way to bring extra info along for free # (like edge thickness to affect resizer size, tooltip text to come with a drag-command, etc) # - part of the point of a declared interface is to help the system know what goes with what, by default (conjecture) # - a more important part is for auto-glue-code (like type coercion) # - it means we have to declare the interfaces things have... superclasses count... # and it needs to be easy to define the glue in the original class (show how to make it fit some interface) or separately # - the interface bundling a set of attrs that can also be accessed directly seems common -- in fact, maybe they preexisted it # (i.e. the attrs were defined, then we decided later they were all part of an interface) class Corner(Interface): # why call it Interface, even if it is one? # It's many things: a constructor for a thing which follows that interface, # a data type we could use in other things and save... # nothing prevents other things from acting like this, and saying they can act like it, and how... # not least, an expr written as Corner(formulas). # In fact that's the usual way something would say how to coerce itself to a Corner -- describe one which is the result of that. # It can do that on an attr whose name is the interface name, or formed from that: thing._as_Corner. # There is some way to supply everything with a formula like that (default and/or overriding?) -- lexically for use # when your code asks to convert things to Corners? Or dynamically, when things you call do that?? In the "drawing env" # (the env used to produce certain outputs or to run methods in a certain interface)? # # digr: BTW, a Widget is just a thing which might have state and which follows a certain small set of interfaces, # e.g. for looks, size, ui responses, etc. point = Arg(Point) vprev = Arg(Vector) vnext = Arg(Vector) pass c1 = Corner(p, v0, v1) # using up words is risky ... what about a 3D corner? \ | / # \|/ # it has more stuff, a point and a circularly-ordered set of vectors giving it 3 2d corners, but is just as deserving of the name Corner. # # specific point: I might call them Corner2D and Corner3D. # general point: we'll need namespaces. # I've also called Interfaces Situations... the connotations are different -- is there any formal difference? ##k # What are the interfaces I know I need so far? # - every data type I've used in type coercion: # Point Vector Position Type StateRef Width Color Widget Widget2D # - implicit interfaces, not yet named: # - draw method # - variants for highlighting, transparency # - lbox attrs # - others # - command # - action, event binding, tool # - ... every complex data type seems to also be an interface # a data type can say how to coerce it to an interface; an interface can say how it coerces data. # What if they both say that? Then the data type wins, since if it says this, it's not distinguishable from it *already* being # in that interface. A program, OTOH, can see the true datatype and do whatever it likes with it... # but if what it does is ask it to coerce itself to an interface, that's what happens, acc'd to datatype. # Would it matter which one it asked first, data or interface? Not sure, seems bad. # What interfaces do my classes, so far, belong to? # - all their superclasses # - that's just about all, except for a few basic interfaces that should be known to the supers. # # A super needs to be able to say how a sub coerces, using things to be defined in the sub. # It does this by giving a formula for the coerced version and/or pieces of it. # I think the fundamental defs of what class is in what types has to be runtime -- # that means, my existing classes should be defining defaults for this, by ExprsMeta or by a general rule that it defaults to the supers. # (Or at least the ones that say they can be used as types.) # So is an Interface just a Type? (note, it might be a distinct concept, but able to be automade (coerced) from a Type.) # For a long time, we don't need nontrivial coercers! They can just look up formulas and fail if they don't find them. # We do however need the option to define one thing in a variety of ways, # so if certain things are given and others not, we can say in general how to compute the rest, w/o being ambiguous or circular. # Q: does the following way work: let caller specify some formulas, then whichever ones are not there, use defaults, # and detect circularity as an error, "not enough specified"? I doubt that's enough. We need to pick correct formula for X # based on whether Y or Z was defined. It's almost more like executing a program that says "if these are defined and those not, do this"... # This means, we need to know if a super, defining an attr, is defining it in a way that counts for this, or only as a default. # == # back to drag commands: (use some supers from Command_scratch_1.py) class typical_DragCommand(ClickDragCommand): # ??? maybe this is also a declared way of coercing any Draggable to a ClickDragCommand? # if so we might rename it in such a way as to indicate that and permit it to be autoregistered for that use. # (it has to be registered with either Draggable or ClickDragCommand or TypeCoerce or env... details unknown.) delegate = Arg(Draggable) # general delegate?? or change to a delegate just for _cmd_drag_from_to? # argument in favor of general: maybe it wants to define extra info to be used for this purpose. # I wonder if it can define extra info "only to be visible if i'm coerced to or seen as a DragCommand"... #k def on_press(self): point = whatever # see example in demo_drag.py; point should be the touched point on the visible object (hitpoint) self.oldpoint = point return def on_drag(self): point = whatever # see example in demo_drag.py oldpoint = self.oldpoint # was saved by prior on_drag and by on_press self._cmd_drag_from_to( oldpoint, point) # use Draggable interface cmd (to delegate) self.oldpoint = point return def on_release(self): pass pass # let's assume that a Corner can be dragged because setting its point will work (preserving vectors, or not touching their formulae -- # so they might change if they are defined in terms of point, and not if they are defined as indep state) # and by default the implem of _cmd_drag_from_to will work by resetting self.point with the same delta in 3d space. class _default_Draggable_methods: ###e name, super -- is it just part of Draggable itself?? def _cmd_drag_from_to( self, p1, p2): self.point += (p2 - p1) return pass class Draggable(...): ###e super? is it a kind of Command in all these cases? not sure. point = Attr(Point) # declare it as something any draggable must have. Do we say State so if not overridden it's defined as state??##k def _cmd_drag_from_to( self, p1, p2): self.point += (p2 - p1) return #e some tooltip and disablement cond to go with that cmd # (the reason it starts with _cmd_ is so its clients know they can look for these -- # it's a kind of interface made of several methodnames parametrized by one methodname-root!) pass # == # some specifics about dragging a set of polygon vertices while keeping edge directions unchanged. (as an example DragCommand) class drag_verts_while_edgedirs_unchanged(DragCommand): verts = Arg(ListOf(Vertex)) ###IMPLEM ListOf ##e rename Vertex? they need to be "polygon vertices" for this to work. Do we need the poly itself?? def _init_instance(self): ###k might be wrong method, if instance only means we're considering the drag -- later method means doing it """ Given: a set of vertices to be dragged together, with edges staying parallel, in a polygon or the like, Come up with: an object which accepts drag commands and alters state of them and connected verts. Note: we assume each vert has exactly 2 neighbor verts and thus 2 edges. Extending to valence 1 would be easy, but for higher valences, it would require some new UI decisions, since we would not know what to do when dragging 2 out of 3 neighbors of a vert we're not dragging (which ought to move that vert along, but can't). [future implem note: I suppose it could just go ahead and move it (perhaps unless the internal analyzer.ok flag was false), but I can't recall if that was the only problem in here with higher valence... maybe it was, so I should generalize this. There are other cases too, but if in general we either drag or leave fixed when confused, it'll probably be ok. ###e] Note: we may assume the entire graph is in 2D, but I can't think of a specific place where we assume that, so it might work in 3D (for a non-planar polygon or graph, and drags of verts in any 3D direction). When the graph/polygon is 2D, the user may wish to constrain delta to the same plane, either for a tilted polygon vs the screen, or to avoid nonplanarity due to roundoff errors. Our alg does not yet handle this in either case. The caller should constrain delta to the polygon's plane, *and* should separately constrain all newly set vert positions to that plane to avoid roundoff error. (Or maybe we should have a feature to do those things for it.) ###e """ verts = self.verts # an input list; each v in it has .edges (exactly 2 or fewer) # [Q: do we need to identify the net or poly too? yes, if v doesn't imply it... nevermind for now, easy to add later] # [maybe we'll just need to specify in there that the polygon for all of them has to be the same one... # but note that it doesn't! They could be in a set of polygons and this alg would work fine -- and that's useful in a UI! hmm...] # find the edges touched twice or once -- but for boundary verts, transclose on them if near 180 -- # in other words, find all verts "affected" (which need to move) by transclose dragverts = dict([(dv,dv) for dv in verts]) # a set of those verts [##e maybe the arg should be SetOf(Vertex) so we don't need to do this here??] analyzers = {} def collect_straightneighbors(dv, dict1): nn = dv.neighbors ###IMPLEM .neighbors for v in nn: if v not in dict1: # (this is just an optim, but it's a big one ###k verify that it works, re transclose semantics; doc in transclose if so) analyzer = corner_analyzer(v, dv, other_of_pair(nn,dv)) # (here's one place where we'd need revision for a general graph) nim ###IMPLEM revised arg order ##e rename -- induced_motion_analyzer? #e should v0 arg be done in the class, e.g. in case >1? # analyzer figures out how it would work to drag dv and thereby induce motion in v # (assuming v's other neighbor is fixed, which is not yet known -- we'll discard this later if it's not, using extra_dragverts) if not analyzer.ok: ###IMPLEM ok dict1[v] = v # make v also a dragvert else: # save analyzer for use when we do the drag (but not all of them will be used) if v in analyzers: analyzers[v] = "invalid" # >1 analyzers were found; this means v will end up in extra_dragverts, so no analyzer for v will be used else: analyzers[v] = analyzer # Note: in principle we should index analyzers by both v and dv, in case v is found from both sides; # but if that happens, we know we'll never use them, since v will end up in extra_verts. # Another solution (more general since it better supports general graphs) # would be for one analyzer to learn about new neighbors of v becoming dragverts, # so as long as v itself didn't, it always knows how to handle v's motion for whatever neighhors are dragverts # with the others assumed fixed. # (This might also help with the general optim for drag-specific displists, discussed below -- not sure.) # # Come to think of it, that's how we'd handle a much-generalized drag of some dofs, with constraints tying them to others, # some of which we should also drag, others update partially. Each dof would get analyzed, updating that alalysis incrementally in a # transclose, whose units (dict entries) might be influences (effect arrows between dofs or their owning objs, not dofs themselves) # so each unit has binary not gradual inclusion into the transclose set. Even during runtime we might update these analyzers # to bring more stuff into the drag if limits were reached. Then they'd compile the drag-code (e.g. displist membership) for the drag, # helped by knowing enough about the dofs to know which objects were purely translated. nim ###IMPLEM the use pass continue return def collect_allneighbors(v,dict1): ###e this could be removed since they're in analyzers for v2 in v.neighbors: dict1[v2] = v2 return dragverts = transclose(dragverts, collect_straightneighbors) # all the verts we have to drag (will later include extra_dragverts) allverts = transclose(dragverts, collect_allneighbors) # all the verts affected when we drag those (including those) # the formula for vert motion is simple: dragverts move with the drag, and any other verts move because one edge # connects them to some dragvert, and needs to stay parallel -- unless they have more than one edge connected to a dragvert, # in which case, assume they move entirely with the drag -- and assume they have no other edges (this alg breaks down here # for a general graph, which seems harder). extra_dragverts = {} # verts effectively dragged since both their neighbors are dragged move_verts = [] # verts moved by the motion of one neighbor dragvert, paired with a direction along which to constrain their motion for v in allverts: # .keys() but works ok, since these sets are v->v maps if v not in dragverts: dragneighbors = intersection(v.neighbors, dragverts)###IMPLEM intersection, complement if necessary (does py23 have a sets module?) assert len(dragneighbors) > 0 # otherwise v should not be in allverts if len(dragneighbors) > 1: extra_dragverts[v] = v # just drag these too else: otherneighbors = complement(v.neighbors, dragneighbors) assert len(otherneighbors) == 1 # can't handle general graphs #e not yet not bothering to handle free ends (easy to fix) v0 = otherneighbors[0] direction = UnitVector(v-v0) move_verts.append( (v, direction) ) pass continue dragverts.update(extra_dragverts) # now all affected verts are in one of dragverts or move_verts. self.dragverts = dragverts self.move_verts = move_verts def motion_func(self, delta): ##e rename -- something in the Draggable or DragCommand interface for v,unit in move_verts: # just project delta onto the line from v0 to v (in direction of unit) wrong: motion = dot(delta,unit) * unit ###WRONG -- we need to divide by dot, or something like that # to be correct: # the actual motion, projected onto unit, should equal delta, projected onto unit. length-of-motion == dot(delta,unit) -- STILL WRONG! #### to correct this, use corner_analyzer below, which we ought to memoize for v/dv during the transclose v.pos += motion # the dragverts move independently, so it doesn't matter what other verts we moved already, among them or others for v in dragverts: v.pos += delta return ###e add something to help the UI visually indicate which verts are moved in different ways -- there are 4 kinds here: # original dragged verts, added due to angle 180, added due to both neighbors dragged, induced motion since one neighbor dragged. # We want to create a visible object on each, with one of 4 looks (but the first is not needed since they'll probably be the selected verts). # All we need is 3 new attrs which define these sets during the motion, and some default looks for them, and our own default look made of those -- # the look of a drag command is whatever extra stuff you should draw when doing it (or considering it, maybe -- maybe that's a separate look # so it can be turned off by default). # ###e BTW we might also want to take over defining the look of the stuff we're moving (as an optional feature of the DragCommand interface) -- # not so much to make it look different (tho that might be useful) as to implem the optim of having the moving and fixed stuff in different # display lists! in fact, we want different ones for fixed stuff, moving-with-mouse stuff, and each other indep motion set -- assume each vert # in move_verts is indep, so just put all of them into a displist we remake all the time (or not in any displist at all -- probably that's better), # but the ones that move together should be in a single displist which moves as a unit, and which won't need to be remade during the drag! # This requires somehow pulling our v's (and all their edges, and any other stuff attached to them) out of the "main displist for v's". # (And sorting it into those categories of motion -- surely this requires new general additions to some interface they're all part of ##e). # It also requires *not* moving them by v.pos += delta, but by redefining v.pos to be relative, then moving the collection. # [later Q: can any .pos implicitly have associated attrs "which coordsystem" and a related one "which displist" or "which displist-variation"?] # One possible trick for part of that -- introduce a temporary state variable "in-drag" in which things with a certain attr are not visible # in the normal way -- that'll be things moving due to the drag. # And make normal displists have variants for when the app is in that mode and any of their own elements are being dragged. # (Details not entirely clear.) pass # for comparison: drag verts while other verts unchanged (should be simpler!) class drag_verts(DragCommand): verts = Arg(ListOf(Vertex)) def motion_func(self, delta): for v in self.verts: v.pos += delta return pass class _use_ExprsMeta(object): #e refile, if not already there under another name __metaclass__ = ExprsMeta pass def other_of_pair(lis, thing): a,b = lis # error if wrong length if thing == a: return b assert thing == b return a class corner_analyzer(_use_ExprsMeta): ###e nim: handle UnitVector(0) ie v == dv or v == v0 ###CALL ME """Figure out how to propogate vertex-drag of dv (with all edge directions unchanged) into an adjacent vertex v, based on local geometry of v's "corner" (i.e. positions of 3 adjacent vertices dv, v, v0). Assume without checking that dv will be directly dragged, but v and v0 won't be, meaning that v will have induced partial motion and v0 will remain fixed. It's up to the caller to determine whether this is actually true and ignore our analysis if not (and this happens in practice in our current uses). """ def __init__(self, v0, v, dv): """we're the corner from v0 to v to dv (or the same 3 verts in reverse order), where dv is a dragvert and v has induced motion and v0 is fixed and all edge-directions are fixed """ self.vars = (v0, v, dv) def motion_of_v(self, delta): """if dv moves by delta (a vector), how much (as a vector) should v move by? [Note: this will be asked for at every drag-step (so it should be fast).] """ return self.unit * dot(self.control, delta) # the following compute methods are run at most once per self def _C_unit(self): "compute self.unit, a unit vector in the direction in which v should move" v0, v, dv = self.vars return UnitVector(v-v0) def _C_control(self): "compute self.control, a vector whose dot product with delta determines the desired signed distance of motion, or V(0,0,0) if it's too sensitive to work" # this vector should have the direction of unit projected perp to the dir of null motion, but inverted length v0, v, dv = self.vars unit = self.unit nullunit = UnitVector(dv-v) # a direction of no induced motion of v control_dir = unit - nullunit * dot(unit, nullunit) # perp to nullunit; shorter if induced motion is more sensitive inverse_sensitivity = vlen(control_dir) if inverse_sensitivity < 0.01: # guess return V(0,0,0) # wrong, but the right answer is an excessively long vector for excessively sensitive motion (infinitely so, if points are colinear) control_dir /= inverse_sensitivity # now it's unit length return control_dir / inverse_sensitivity # now it's longer when motion should be more sensitive pass
NanoCAD-master
cad/src/exprs/scratch/demo_polygon.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ ModelNode.py @author: bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. Note: as of sometime before 070129 this is an unfinished stub, and it's not clear whether it will be used. == Introduction / history / implem plans: ModelNode is an abstract subclass of Node for model objects which want to be stored in assy.tree so as to let a lot of existing NE1 interfaces reach them there: MT display: MT-cmenu maybe Edit Properties DND selection via MT, with its Group/Part-related selection semantics copy/cut/delete via MT 3d drawing subject to: current Part Show/Hide Undo mmp file save/load Maybe also 3D selection and move? We only "get these for free" if we make it a subclass of Chunk or Atom or Bond or (most likely -- fewest assumptions) Jig, but that might not be worth the trouble, compared to just modifying the necessary code in the existing modes, especially selectMode. ModelNode will have specific subclasses for specific model objects. It might have a Node and Group variant, if I have any trouble with isinstance(x,Group) or varying of node.openable. But I hope I won't need that. Maybe any such trouble is easily fixable. I decided I needn't bother with a separate Node proxy object, since there is not much overlap with required method names. The draw method is not even needed on my model objects -- they can in general get looked up to find a viewer for them. So the superclass has Node-compatible draw which calls exprs draw on the drawable form that gets looked up as their viewer. (For convenience, esp to start with, they could have their own default_draw method to be used if that lookup fails.) The MT, when redrawing, should usage-track and subscribe mt_update as the invalidator. Undo will need decls... Copy -- can SimpleCopyMixin work? It needs an exception to usage-tracking (basically to discard it) since it is defined to take a snapshot. ... much later: see also non-cvs notes (files & paper) of 070105 """ import time from foundation.Utility import Node from foundation.state_constants import S_DATA from exprs.Rect import Sphere from exprs.lvals import RecomputingMemoDict ##, call_but_discard_tracked_usage, LvalError_ValueIsUnset import foundation.env as env from utilities.constants import gray from exprs.instance_helpers import InstanceOrExpr from exprs.attr_decl_macros import StateArg, StateArgOrOption, Arg from exprs.ExprsConstants import Position, ORIGIN, Width, Color # === # WRONG ##class ModelNode(Node, SimpleCopyMixin, InstanceOrExpr): ## __metaclass__ = ExprsMeta ## reload failed (not supported in this version?); continuing: exceptions.TypeError: Cannot create a consistent method resolution ## order (MRO) for bases Node, SimpleCopyMixin, InstanceOrExpr ## [debug.py:1320] [debug.py:1305] [test.py:137] [ModelNode.py:69] [ExprsMeta.py:900] ## ## ### why can't it? ## ## ### that might be yet another reason not to make ModelObjects and their Nodes the same object class ModelNode(InstanceOrExpr): #e rename since not a Node anymore (unless I actually like this name; doubtful; try ModelObject) ###IMPLEM - rewrite the rest of this class, it's obsolete def __init__(self, stuff, name = None): assy = env.mainwindow().assy #k wrongheaded?? Node.__init__(self, assy, name)###WRONG now that Node is no longer a superclass self.stuff = stuff # exprs for what to draw (list of objects) _s_attr_stuff = S_DATA def draw(self, glpane, dispdef): if self.picked: # only draw when picked! (good?) draw_stuff(self.stuff, glpane) ### FIX: Undefined variable 'draw_stuff' def writemmp(self, mapping): """ Write this Node to an mmp file, as controlled by mapping, which should be an instance of writemmp_mapping. """ line = "# nim: mmp record for %r" % self.__class__.__name__ mapping.write(line + '\n') # no warning; this happens all the time as we make undo checkpoints return def __CM_upgrade_my_code(self): # experiment """ replace self with an updated version using the latest code, for self *and* self's data! """ name = self.__class__.__name__ print "name is",name # "DebugNode" print self.__class__.__module__ #e rest is nim; like copy_val but treats instances differently, maps them through an upgrader # new code: def draw(self, glpane, dispdef): # follows Node.draw API #e should create appropriate drawable for the given glpane and dispdef; # even if we kluge them as fixed, we need to instantiate our "appearance-expr" (which might default to self? no, draw method is an issue) # btw isn't there a parent env and ipath we need to inherit, to draw properly? # from this draw-interface, the best ipath might be id(self) or so -- or self.ipath if it has one. or parent-node index-path?? # not really, given moving of nodes. # maybe a per-node serno is best. _e_serno could work unless it changes too often. And it does. hmm. # Maybe this has to be specified by whoever makes *us*! that means, self.ipath is best. kid = self.find_or_make_kid('_value', glpane) ###IMPLEM find_or_make_kid -- think through the issues self.drawkid( kid) ## kid.draw() pass class Sphere_ExampleModelNode(ModelNode): """ A sphere. """ pos = StateArg(Position, ORIGIN) ###IMPLEM StateArg , StateArgOrOption #e or can all arg/option formulas be treated as state, if we want them to be? (no, decl needed) #e or can/should the decl "this is changeable, ie state" as a flag option to the Arg macro? #e can it be set to a new *formula*, not just a new constant value? (for constraint purposes) #e - if so, does this require a decl to say it's possible, or is it always possible? (note: it affects mmp writing and copy) if 0: # StateArg might be equivalent to this (except for the name to use in the Arg if it matters, e.g. for StateOption): _orig_pos = Arg(Position, ORIGIN) #e can we pass an index to override '_orig_pos' if it matters? pos = State(Position, _orig_pos) # see similar code in demo_drag (in class Vertex I think) radius = StateArg(Width, 1) color = StateArgOrOption(Color, gray) ## def draw_unpicked(self): ## ###KLUGE: this is copied from Sphere.draw in Rect.py. ## ##e Instead, we should define and cache a real Sphere using self-formulas, and draw that, ## # and delegate to it for lbox as well. ## from drawer import drawsphere # drawsphere(color, pos, radius, detailLevel) ## drawsphere(self.fix_color(self.color), self.center, self.radius, self.detailLevel) # some of this won't work ######IMPLEM # so is using Sphere hard? maybe not: _value = Sphere(pos, radius, color) # and something to delegate to it... but only for drawing and lbox, delegation by ModelNode?? # wait, why would we delegate lbox? if we're a Node does that mean we have a position? if lbox is used, does that mean we're # drawn by a graphic parent, not as the appearance of some node? For now, assume we won't delegate lbox. OTOH can some # graphic thing use a model object as shorthand for "whatever that looks like in the present env"? Without wrapping it?? # If so, that might lead to our desire to delegate lbox, and everything else in some to-be-formalized "3dgraphics API". #e but how would we make that depend on the current display mode? just look at self.env? Or is that part of the model? # what about instances of drawables -- they depend on env, maybe they are not fixed for a given model object like we are!!! # should we grab env out of glpane when Node.draw is called? ###LOGIC PROBLEM 1: Group.draw assumes there's 1-1 correspondence between subnodes in MT and subnodes drawn. # POSSIBLE EASY FIX: override Group.draw for our own kind of Grouplike objects. At least, it can modify drawing env, # even if it also usually calls the subnode draw methods. BTW we could pass env to draw as a new optional arg. ###LOGIC PROBLEM 2: we'd really rather make a parallel drawable (perhaps a tree) and draw that, not call draw on subnodes # directly. POSSIBLE EASY FIX: just do it -- don't call draw on subnodes directly, assume they're kids of main drawable. # Then Node.draw only gets called at the top of "our kind of Group". That can even work for subnodes not of our type, # if we turn them into drawables of a simple kind, by wrapping them with "draw old-style Node using old API". ### PROBLEM 3: what if we are drawn multiply in one screen, how does it work? # SOLUTION: the Node.draw is not our normal draw api -- that's "find view of this model object and draw it" # (specific to env, ipath, other things). The Node.draw is mainly used when legacy modes (not testmode) draw the object. # Those can only draw it in one place so it doesn't matter. (Hmm, what if we define a Grouplike node which draws whatever's # under it in more than one place? It'd have to work by altering global coords before calling Node.draw. It could pass # optional env and ipath args, or whatever, to permit smart nodes to create Instances of their appearance... # think this through. ###e) (It's almost like we just want to add new dynamic args to Node.draw and start using that... # in order to coexist in mixed ways with old-style Nodes. They should be dynamic so they pass through old-style Nodes # unchanged and are still seen by their new-style Node children. But does this work when there's >1 glpane? # BTW, what about drawing with Atoms or Bonds (old drawables, but not Nodes)?? # I'm not even sure their .draw API is the same. It might be, or could be made to be.) ### WORSE PROBLEM 4: what if >1 MT, with different MT-views of one model object? Letting model obj be its own MTNode # is a scheme only one of the MTs can use, or that requires the MT-views to be identical (even for value of node.open). # If we had multiple MTs we'd want each to have its own set of Nodes made to view our model objects. # That would be a fundamentally better scheme anyway. So we'll want it for our own newer MTs (like the ones in the GLPane). # So will we want it from the start? # Or let it coexist with "model obj can give you a node for another MT, and at same time, be one for "the MT""? # ... I guess it now seems like making a separate Node proxy is best, and only using it for this old-MT interface # but noting the multiple purposes of that (all the ones listed in the module docstring, unless testmode is running # and not using the old rendering code on the assy). For awhile, even in testmode, save file will still use assy.tree, etc. # So we'll keep needing to interface with these old APIs through the "old MT view". But we'll like having new views too, # incl new-MT (in glpane or not) and new-graphics view (various dispmodes). # SO FIRST FIGURE OUT THE GENERAL WAY TO GET VIEW OBJECTS FROM MODEL OBJECTS. Some sort of caching recomputing dict? # preferably with adaptive keys, that automatically generalize when subkeys are not used in main expr or subexprs... # but for now, ok to ignore that optim (esp if we redecide the key for each subexpr, and some *know* they don't use # some parts of the most general key). Compare to what's in demo_MT, texture_holder, CL. # # ... re all that, see RecomputingMemoDict (written just now, not yet used). ###e # The idea is to use it to map objects into images (views) of themselves (with keys containing objs and other data), # where instances are images of exprs, view objs are instances of model objs # (whether the view objs are Nodes (old MT) or MTViews (new one) or _3DViews(?)), glue code wrapped things of those things. # But in some cases we'd like the dict val to permanent -- in that case, use MemoDict and a wayfunc that recomputes internally # and delegates to what it recomputes (or forwards to it if it becomes final, as an optim). This might be true for glue code, # not sure about viewers. We might like to say which style we prefer in each case (as if part of the key). # # Note: current direct uses of MemoDict are texture holders and MTView; of LvalDict2 are subinstances -- and any others? # StatePlaces -- but they don't make use of the recomputing ability. pass class OldNodeDrawer(InstanceOrExpr): node = Arg(Node) def draw(self): glpane = self.env.glpane dispdef = None ###STUB node.draw(glpane, dispdef) #####PROBLEM: attrs of old nodes or their subnodes are not usage/change-tracked. return pass def testfunc(key): return "%s, %s" % (key, time.asctime()) # note: uses no usage-tracked values!!! rcmd = RecomputingMemoDict(testfunc) def dictmap(dict1, list1): ##e does this have another name in py_utils, or is there a dict->func converter there?? #e return tuple?? return [dict1[key] for key in list1] if 0: print "rcmd maps 1 to %r, 2 to %r, 1 to %r" % tuple(dictmap(rcmd, [1,2,1])) #e change time to counter so you can tell it didn't recompute # end
NanoCAD-master
cad/src/exprs/scratch/ModelNode.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PixelTester.py $Id$ """ # PixelTester is untested -- not even fully parsed by python yet ##e needs save button, per-session filenames, access to on disk log of prior files, # or way of reading new image from same file, and including reread-policy # (and id if done "by command to instance") # along with filename in the texture-dict key # (but optim for when multiple reads got same image data, whether by same instance or different ones?? # not simple -- eg if single textures have varying data or (worse for displists) names, other issues, and somewhat orthogonal) #e more imports from utilities.constants import blue, purple from exprs.widget2d import Widget2D from exprs.Exprs import format_Expr from exprs.TextRect import TextRect from exprs.Boxed import Boxed from exprs.Column import SimpleColumn #e reloadable from exprs.images import Image, PixelGrabber from exprs.Rect import Spacer from exprs.instance_helpers import InstanceOrExpr, DelegatingMixin from exprs.attr_decl_macros import Arg class PixelTester(InstanceOrExpr, DelegatingMixin): # ought to be InstanceMacro but trying this alternate style just to see it # args testexpr = Arg(Widget2D) # instantiated right here, hope that's ok testname = Arg(str) # required for now, used to form filename # value filename = format_Expr("/tmp/%s.jpg", testname) delegate = SimpleColumn( TextRect("saved image from PRIOR session, in blue box"), # kluge: execute this first, so we read file before writing it Boxed(bordercolor = blue)( Image(filename) ), Spacer(0.3), TextRect("live widget, in purple box"), Boxed(bordercolor = purple)( PixelGrabber(testexpr, filename) ), ##e and put current session image here, for comparison, or put top on in a tab control for flicker test ) pass # end of class PixelTester # end
NanoCAD-master
cad/src/exprs/scratch/PixelTester.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ rendering.py -- rendering loop control, etc $Id$ """ IorE drawkid def should be sort of like: def drawkid(self, kid): warpfuncs = getattr(self.env.glpane, '_exprs__drawkid_funcs', None) #070218 or so new feature while warpfuncs: func, warpfuncs = warpfuncs try: color0 = '?' # for error message in case of exception color0 = func(color) # don't alter color itself until we're sure we had no exception in this try clause color = normalize_color(color0) except: print_compact_traceback("exception in %r.fix_color(%r) warping color %r with func %r (color0 = %r): " % \ ( self, color_orig, color, func, color0 ) ) pass continue return color and is now: (except it doesn't really contain that _exprs__whatever line): def drawkid(self, kid): # note: supersedes nim _e_decorate_draw [070210] #e plans: protect from exceptions, debug_pref for no-coord-change enforcement (for testing), # and most importantly, make possible a drawing pass which draws only a specified subset of drawables # but in their coord- or glstate- transforming containers, e.g. for a highlight-drawing pass. # (that last is what we're doing now, with _exprs__whatever 070218) oldfunc = getattr(glpane, '_exprs__whatever', None) #e rename attr if kid is not None: kid.draw() return class _drawkid_oldfunc: # use this to replace glpane drawkid func called inside IorE drawkid ###implem "One of these becomes the temporary drawkid func ... " # other code is WRONG, oldfunc(parent, kid) is what we need to be able to call def __init__(self, drawkid_contrib_func, oldfunc): self.drawkid_contrib_func = drawkid_contrib_func # public for set? if not, need a set method too self.oldfunc = oldfunc or noop # oldfunc might be None def parent_draw_kid(self, parent, kid): "when self is active in dynenv, a bound method made from this method is what gets called in place of (or by?) usual drawkid (in oldfunc)" func = self.drawkid_contrib_func # what someone contributed... #doc better oldfunc = self.oldfunc func(oldfunc, parent, kid) def set_drawkid_contrib_func(self, func): # (a rare case where I think a set method is better (clearer) than a public settable attr) self.drawkid_contrib_func = func pass class SelectiveRedrawer(InstanceOrExpr): #070217 to make highlighting work in displists, someday [replaces "draw decorators"] """ """ def draw(self): self._parents_lists = {} # maps obj (drawn during us) to list of all its draw-parents (highest possible parent being self) self._later = {} # maps obj to list of funcs to call later in same GL state & coords as used to draw obj #e put self in dynenv if needed, to permit registration of selective redraw or point-finding (x,y,depth) #### QUESTION: (when is that done? for make of delegate?? or right now, in glpane? (if so, restore prior, or reg with all???) # begin having drawkid track parents in us # (as well as in whatever objs it did before, in glpane linked list like for fix_color) ###### WAIT, what about displists it calls? they'll need to have tracked parents ahead of time, i think... ####e glpane = self.env.glpane oldfunc = getattr(glpane, '_exprs__whatever', None) #e rename attr newfunc = _drawkid_oldfunc( self._drawkid_collect_parents, oldfunc) #e rename _drawkid_oldfunc and maybe the args passed setattr(glpane, '_exprs__whatever', newfunc) # this means IorE.drawkid will call it ###IMPLEM try: self.drawkid(self.delegate) # has try/except, so we don't need our own around just this call ###k make sure what it has is not try/finally # end having drawkid track that (see below) # some of those kids/grandkids also entered things into our list of things needing redraw # figure out transclose of parents of things we need to redraw (or run code in their coords anyway -- redraw in modified way) objdict = dict([(obj,obj) for obj in self._later]) junk, self._proper_parents = self._transclose_parents(objdict) # begin modifying drawkid to filter... the method of mod is really to wrap it with our own code... newfunc.set_drawkid_contrib_func( self._drawkid_selective ) # self.drawkid(self.delegate) except: msg = "bug: exception somewhere in %r.draw(), delegate %r; len(parents_lists) = %d, len(_later) = %d" % \ (self, self.delegate, len(self._parents_lists), len(self._later)) print_compact_traceback( msg + ": ") pass # end setattr(glpane, '_exprs__whatever', oldfunc) #e and repeat, if we have more than one redraw-pass return def _drawkid_collect_parents(self, oldfunc, parent, kid): """This intercepts (a func called by) parent.drawkid(kid) when we're collecting parents, with oldfunc being (a func called inside) parent.drawkid as if we were not active in dynenv. """ if 0: # this would be equiv to behavior we replace: oldfunc(parent, kid) return # parent is a draw-parent of kid self._parents_lists.setdefault(kid, []).append(parent) #e could optim oldfunc(parent, kid) return def redraw_later(self, obj, func): ### PUT SELF in env so i can be called """This should be called during self.draw (by something we're drawing). obj should be that something, or anything else we might draw during self.draw. This registers func to be called (in our later special selective-redrawing pass) once for each time obj was drawn in the main pass, in the same local coords and OpenGL state obj was drawn in at the time (but not inside any display lists being called or compiled, whether or not obj was drawn into one). Typical values for func are obj.draw(), modified(obj).draw(), a lambda that calls gluProject or so.... [#e we might add ways to ask for more args to be passed to func (none are now), like the draw-parent, self, etc.] """ self._later.setdefault(obj, []).append(func) #e could optim return def _transclose_parents(self, objdict): """Given a dict from obj to obj, for some objs to redraw-modifiedly, return two things: a dict including them & all their parents (recursively), and a dict including only the ones that were parents. """ proper_parents = {} # proper parents (objdict objs not in there unless they are also parents) def collect_parents(obj, dict1): for parent in self._parents_lists[obj]: dict1[parent] = parent proper_parents[parent] = parent return res1 = transclose(objdict, collect_parents) return res1, proper_parents #k no need to return res1? def _drawkid_selective(self, oldfunc, parent, obj): """Called using same interface as _drawkid_collect_parents. What we do: - for objs registered in _later, call their func (or funcs). GL state and coords will be same as when obj.draw was called. - for objs which are draw-parents of other objs, call their .draw (so as to get called for their kids, in GL state they set up). (If they also do direct drawing, this should not hurt; they can also check a flag and not do it, someday. #e) - for other objs, do nothing. """ for func in self._later.get(obj, ()): try: func() except: msg = "bug: %r._drawkid_selective() ignoring exception in func %r for %r (parent %r)" % \ (self, func, obj, parent) print_compact_traceback( msg + ": ") continue if obj in self._proper_parents: oldfunc(parent, obj) ##k return pass
NanoCAD-master
cad/src/exprs/scratch/rendering.py
""" $Id$ """ # experimental, bruce 070814 class StatelessExpr: # probably not IorE... but might be if these are not needed to define that _e_stateless_expr = True # should be F in super pass class AttrDeclExpr(StatelessExpr): #e special behavior in the metaclass, or when used as a descriptor -- # expr objects *are* descriptors? or can make them on request by metaclass? pass class Instance(AttrDeclExpr): pass class ArgOrOption(AttrDeclExpr): pass class Arg(AttrDeclExpr): pass class Option(AttrDeclExpr): pass # etc # add code to turn them into equiv exprs... metaclass can use that code # and if we want it can be defined using existing code... then cleaned up later
NanoCAD-master
cad/src/exprs/scratch/AttrDeclExprs.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ Column_old_nim.py $Id$ 070129 moved from Column.py and instance_helpers.py; this code is old and nim; implem is obs but intent is not (tho not urgent) """ from exprs.widget2d import Widget2D from exprs.instance_helpers import InstanceOrExpr from exprs.attr_decl_macros import ArgList from exprs.py_utils import printnim from exprs.lvals import LvalDict1 from exprs.py_utils import interleave_by_func from exprs.Rect import Spacer # undefined global symbol: fixed_type_instance # undefined global symbol: ListInstanceType # undefined global symbol: index_path ##from instance_helpers import GlueCodeMemoizer, DelegatingInstance_obs # moved here from instance_helpers.py 070129 [and sufficiency of imports not tested since then] class DelegatingInstanceOrExpr_obs(InstanceOrExpr): #061020; as of 061109 this looks obs since the _C_ prefix is deprecated; #e use, instead, DelegatingMixin or DelegatingInstanceOrExpr combined with formula on self.delegate """#doc: like Delegator, but self.delegate is recomputable from _C_delegate as defined by subclass. This is obsolete; use DelegatingMixin instead. [#e need to rewrite GlueCodeMemoizer to not use this; only other uses are stubs.] """ def _C_delegate(self): assert 0, "must be overridden by subclass to return object to delegate to at the moment" def __getattr__(self, attr): # in class DelegatingInstanceOrExpr_obs try: return InstanceOrExpr.__getattr__(self, attr) # handles _C_ methods via InvalidatableAttrsMixin # note, _C__attr for _attr starting with _ is permitted. except AttributeError: if attr.startswith('_'): raise AttributeError, attr # not just an optim -- we don't want to delegate these. return getattr(self.delegate, attr) # here is where we delegate. pass DelegatingInstance_obs = DelegatingInstanceOrExpr_obs #k ok? (for when you don't need the expr behavior, but (i hope) don't mind it either) #e rewrite this to use DelegatingMixin [later 061212: nevermind, it's probably obs, tho not sure] class GlueCodeMemoizer( DelegatingInstanceOrExpr_obs): ##e rename WrapperMemoizer? WrappedObjectMemoizer? WrappedInstanceMemoizer? probably yes [061020] """Superclass for an InstanceOrExpr which maps instances to memoized wrapped versions of themselves, constructed according to the method ###xxx (_make_wrapped_obj?) in each subclass, and delegates to the wrapped versions. """ # renamed to InstanceWrapper from DelegatingObjectMapper -- Wrapper? WrapAdder? Dynamic Wrapper? GlueCodeAdder? InstanceWrapper! # but [061020] I keep remembering it as GlueCodeMapper or GlueCodeMemoizer, and GlueCodeMemoizer was an old name for a private superclass! # So I'll rename again, to GlueCodeMemoizer for now. ###e 061009 -- should be a single class, and renamed; # known uses: CLE, value-type-coercers in general (but not all reasonable uses are coercers); # in fact [061020], should it be the usual way to find all kids? maybe not, e.g. CL does not use this pattern, it puts CLE around non-fixed arginsts. def _C_delegate(self): # renamed from _eval_my_arg printnim("self.args[0] needs review for _e_args or setup, in GlueCodeMemoizer; see DelegatingMixin")###e 061106 arg = self.args[0] # formula instance argval = arg.eval() ###k might need something passed to it (but prob not, it's an instance, it has an env) ####@@@@ might be arg.value instead; need to understand how it relates to _value in Boxed [061020] #### isn't this just get_value? well, not really, since it needs to do usage tracking into the env... # maybe that does, if we don't pass another place?? or call its compute_value method?? # argval might be arg, btw; it's an instance with a fixed type (or perhaps a python constant data value, e.g. None) #e might look at type now, be special if not recognized or for None, depending on memo policy for those funny types lval = self._dict_of_lvals[argval] return lval.get_value() def _C__dict_of_lvals(self): #e rename self._dict_of_lvals -- it holds lvals for recomputing/memoizing our glue objects, keyed by inner objects ##e assert the value we're about to return will never need recomputing? # this method is just a way to init this constant (tho mutable) attr, without overriding _init_instance. assert self._e_is_instance return LvalDict1( self._recomputer_for_wrapped_version_of_one_instance) #e make a variant of LvalDict that accepts _make_wrapped_obj directly?? I think I did, LvalDict2 -- try it here ####@@@@ ## try this: return LvalDict2( self._make_wrapped_obj ) # then zap _recomputer_for_wrapped_version_of_one_instance ####e ##e pass arg to warn if any usage gets tracked within these lvals (since i think none will be)?? # actually this depends on the subclass's _make_wrapped_obj method. # More generally -- we want schemes for requesting warnings if invals occur more often than they would # if we depended only on a given set of values. #e ####@@@@ def _make_wrapped_obj( self, fixed_type_instance ): """Given an Instance of fixed type, wrap it with appropriate glue code.""" assert 0, "subclass must implement this" def _recomputer_for_wrapped_version_of_one_instance( self, instance): """[private] This is what we do to _make_wrapped_obj so we can pass it to LvalDict, which wants us to return a recomputer that knows all its args. We return something that wants no args when called, but contains instance and can pass it to self._make_wrapped_obj. """ # We use the lambda kluge always needed for closures in Python, with a guard to assert it is never passed any arguments. def _wrapped_recomputer(_guard_ = None, instance = instance): assert _guard_ is None return self._make_wrapped_obj( fixed_type_instance) # _make_wrapped_obj comes from subclass of GlueCodeMemoizer return _wrapped_recomputer # obs comments about whether _make_wrapped_obj and LvalDict should be packaged into a helper function or class: "maintain an auto-extending dict (self._dict_of_lvals) of lvals of mapped objects, indexed by whatever objects are used as keys" ###e redoc -- more general? how is it not itself just the LvalDict? # i mean, what value does it add to that? just being a superclass?? # well, it does transform _make_wrapped_obj to _recomputer_for_wrapped_version_of_one_instance -- # maybe it should turn into a trivial helper function calling LvalDict?? ie to the variant of LvalDict mentioned above?? pass # == # moved here from Column.py 070129; never finished or tested class CLE(GlueCodeMemoizer): # not reviewed recently """Column list element: - handles 0 or more actual rows, perhaps varying in time, as described by one formula arg to Column - for each instance that formula evals to, this adds type-specific glue code (memoized for that instance) and delegates to it, also making the result available as the value of self.delegate - also contains the type-specific glue code ### as methods or classes? """ printnim("CLE not reviewed recently")###k def _make_wrapped_obj(self, fixed_type_instance): # _c_ means "informal compute method" (not called in standard way) "make a new helper object for any fixed_type_instance, based on its type" ###e note, the only real "meat" here is a map from .type to the wrapper class CW/CL (and maybe an error value or None value), # so we might want an easier way, so you can just give a dict of types -> classes, or so t = fixed_type_instance.type #k if t is ListInstanceType:####@@@@ helper = CL(fixed_type_instance) else: helper = CW(fixed_type_instance) ###stub, also handle None, error return helper pass class CW(DelegatingInstance_obs): #e make sure arg has a layout box -- can't we do this by some sort of type coercion? for now, just assume it does. # that means it'll have height, since all lboxes have that even if it's not fundamental. # all we might need to add is empty = False. empty = False #k might work pass class CL(InstanceOrExpr): """[private to Column] Handle a List expr instance given to Column, directly or indirectly in its nested-list argument values. Specifically, use CLE to treat list elements as contributing sometimes-empty sequences of column elements. """ # 061106 possible newer version of the self.elts definition of instantiated args (older one moved to an outtakes file): elts = ArgList( CLE) # can it be that simple? and can this replace all references herein to self.args or self.kids? I think so. ####k # == figure out what to draw, # based on which elements need gaps inserted between them; # the main result is self.drawables (the recomputable ordered list of nonempty elements and gaps to draw); # the main input is self.elts, a list (not dict) of element-instances, # whose values (as determined by the code above) are fixed CLE instances, one per CL argument. # (The only reason it can't be a dict is that we use the list-subsequence syntax on it, self.elts[i1:i2], # when we want to move from one place in it to another. # We also might like to use "map" to create it, above... but index is needed, so maybe that's not relevant... # but we might use list extension... OTOH, to be lazy, we might like a compute rule for set of indices, and for kid-code...) def nonempty_elts(self, i1 = 0, i2 = -1): """Return the current list of nonempty elts, out of the list of all elts between the given between-elt indices (but i2 = -1 means include all elts)""" if i2 == -1: # we use -1, since 0 could be legal, getting an empty list. # WARNING: meaning would differ if i2 = -1 was an elt index -- # in that case, -1 would be equivalent to len - 1, not len. i2 = len(self.elts) # if elts know their own indices, or (better?) if gaps depend on their id not index, # we can just grab & filter the elts themselves: return filter(lambda elt: elt.nonempty, self.elts[i1:i2]) def insert_gaps(self, elts): "Given a list of 0 or more of our elts, return a new list with appropriate gap objects inserted between the elements." return interleave_by_func(self.elts, self.gapfunc) def gapfunc(self, elt1, elt2): "find or make a gap object to be drawn between a given two of our elements" #e in real life, we'd memoize not on e1 and e2 themselves, but we'd eval their current gap-influencer (perhaps still an instance obj) # and memoize on that. this would be to support fancy gaps, actually drawn, with mouse bindings, colored indicators, variable height... # ... correction: what we'd memoize on would probably be elt1.last_nonempty_elt and elt2.first_nonempty_elt -- not sure... return self._constant_gap #e for now, only constant gap is supported def _C__constant_gap(self): return Spacer(0,self.gap) # this is only constant at a given time -- self.gap itself can be a formula (vary with time), that's ok # note that this spacer can be drawn in more than one place! I guess that's ok since it's not highlightable and has no transparent parts. #k # def _C_drawables(self): "maintain our list of elts and gaps to draw -- the nonempty elts, and gaps between them" return self.insert_gaps(self.drawable_elts) def _C_drawable_elts(self): return self.nonempty_elts() # def _C_first_nonempty_elt(self): #k needed? ne = self.drawable_elts if not ne: return None return ne[0] def _C_last_nonempty_elt(self): #k needed? ne = self.drawable_elts if not ne: return None return ne[-1] def _C_nonempty(self): # worth _C_ rather than _get_, to memoize it, # in case a future optim diffs successive values and avoids inval # (if that happens in this lval as opposed to in whoever uses it #k) return not not self.drawable_elts def _get_empty(self): return not self.nonempty # == relative coordinates, for redrawing specific parts def move_from_top_to_kidindex(self, i2): ###@@@ CALL ME? not quite sure how this is called... esp due to its top-dependence... # i2 is an elt-index of an elt we drew, and we want to move from top, to top of that elt; needn't be fast. h = 0 for d in self.drawables: if d.index == i2: ###k; what about the spacer? does it have some "default" index, repeated but never equal to i2? # move down over accumulated distance before we hit this elt self.glpane.move_down(h) return h += d.height assert False, "didn't find index %r" % i2 # == compute layout-box of whole from lboxes of drawable parts def _C_height(self): return sum([d.height for d in self.drawables]) def _C_btop(self): if not self.elts: return 0 return self.elts[0].btop # assumes we have some elts; intentionally ignores whether elts[0] is empty, or its bbottom or gap. def _C_bbottom(self): return self.height - self.btop # an anti-optim no one should mind: depends needlessly on elts[0].btop. #e [someday, optim: can we declare that lack of dependence, and explicitly remove the usage-record? doesn't matter in this example.] def _C_bleft(self): return max([d.bleft for d in self.drawables] or [0]) def _C_bright(self): return max([d.bright for d in self.drawables] or [0]) # == drawing code def draw_from_top_to_bottom(self): for d in self.drawables: d.draw_from_top_to_bottom() return pass # end of class CL class CW_scratch: empty = False nonempty = True #e it might be nice if we only needed one of these -- not important for now def draw_from_top_to_bottom(self): self.glpane.move_down(self.btop) # move to origin self.draw() # does this leave end pos fixed, or undefined? assume fixed for now. ###k self.glpane.move_down(self.bbottom) # move to bottom pass # missing from CL_scratch: creating elt kids. esp with .index; running formulas. not even sure of role of gaplike formulas in CL -- # does it no longer have any two-way interfaces anywhere?? # missing from recent coding: fill in inval stubs; anything about make, lexenv. class LayoutWidget2D(Widget2D): pass #####@@@@@ get from layout.py class Column(LayoutWidget2D): """Column(w1, w2, w3) arranges one or more widgets in a vertical column, aligned by their drawing-origins, with w1's drawing origin inherited by the entire column. The arguments can actually be variable nested lists of widgets; for convenience, None is equivalent to []. For example, Column(w1, [w2, w3]) is equivalent to Column(w1, w2, w3), and Column(w1, If(cond, w2, None)) is equivalent to If(cond, Column(w1, w2), w1) (except perhaps for efficiency issues). The arguments can even contain refs to lists of widgets computed separately [#e syntax for this is not yet devised], with lists and sublists in those values properly interpreted as indicating vertical arrangement. Gap widgets (simple spacers, by default) are automatically inserted between adjacent drawn widgets; in general they can be arbitrary widgets which depend on the ones they're inserted between, in appearance and behavior [but this dependence is nim]. ###e TBD: options for gapfunc or spacing. options for alignment, or for wrapping all elts with something. """ # we work by using helper functions CL, CW, CLE... def _init_instance(self): self._value = CLE(list(self._e_args)) # 061106 educated guess: self.args -> self._e_args, assuming _value is auto-instantiated # or that the below does that -- not reviewed now. #####@@@@@ printnim("Column _vlaue instantiation not reviewed") #k do we need to instantiate this, or is that automatic somehow? guess: we do, though a class assignment of it would not. self._value = self.make(self._value) #### might be better to assign expr to self._E__value (or _C__value??), letting self._value be automade from that -- # then it can include '_value' as relative index, too. ###e Now we have to make self.draw work, here or in CLE. pass # == junk or scratch below here # understand understood -- only a big comment, NewInval.py: 275: # env + expr -> understood expr (in that env), an obj with attrs (oresmic?) if 0: understood_expr = env.understand_expr(expr, lexmods = None) # retval contains env + lexmods. we do this inside another understood expr... expr itself has no env. # understand_expr can be done by anything with an env (it's delegated to that env), and it's done by a portion of the env, the expr-understander, # which includes the lexenv. # btw this also handles kluges like [x,y] -> list_Expr(x,y). it might wrap nonobvious python constants with constant_Expr. # btw it also does replacements, or binds in enough info to do them lazily. ## understood_expr._e_make_in(env.place, index) understood_expr._e_make_in(env, index_path) #k - where to make things -- a portion of env says that; and how (glp vs pov) -- ditto [ambig with understanding it??]; # but we also have to supply a local-where, ie an index. # and i forget if the various *kinds* of places (datalayers), which use index indeply & could be revised indeply, should be in one env.place thing... # this maker, if it makes something with kids, should make lexmods containing the new index prepended onto a path (inside->outside order, functional), # perhaps interning the path... and put that in the env to be given to those kids, which is "this instance's env". class KidMakingUtilsMixin: def make_kid(self, expr, index, lexmods = None): "for use in certain kinds of compute rules for kids" understood_expr = self.env.understand_expr(expr, lexmods = lexmods) # ideally the caller would split this out, if making several kids from this ###e to facilitate that, do we offer autoprefixes for understood versions of kid-expr attrs (usually args)? no, too weird to be worth it. # or just self.understand? probably. someday, a better formula notation so it's easy to set these things up per-use. return understood_expr._e_make_in(self.env, index_path) # standard compute rules for kids - set up set of kid indices, and func from index to code (aka expr), lexmods. let recompute rules do the rest. def _in_kids_i_C_val(self, i): ##??? # get code, get lexmods, call make_kid... pass pass # end
NanoCAD-master
cad/src/exprs/scratch/Column_old_nim.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ scratch6.py $Id$ """ # [061025; exploring a graph-editing eg, gets into interesting comments about # exprs for behaviors, actions, events, potential & actual, command offers, # and pattern syntax and semantics.] # you can DND a new edge from one node to another # using the following behavior, which we might add to some editmodes and not others... # let's see, what does it say: # - appearance of the during-drag graphic: # (a rubberband edge from an existing node to an object showing what would happen if you dropped at that point) # - dragging thingy, which looks under it to see what it might drop on, looking for: # - something that edges (of its kind) from nodes (of its kind) can be attached to # - empty space into which new edges (of its kind) can be drawn (creating new nodes to attach to) # specifically, in either case (existing or new droptarget), it somehow highlights & has translucent stuff to show what it'd do. # we're likely to like to do that by: # - creating a first class feature or object, which is what we'd make real if we dropped # - but until we drop, "show it as a potential feature or object" # - for which standard behavior can be used: # - potential object is shown translucent # - potential feature (attachment to target) is shown by highlighting target... # but in reality, the highlighting of the target is more like a special case for DND. # OTOH, when target is space, we highlight the drop point, not the target, based on what we'll do there. # so it sounds like these potential actions (putting action and appearance when potential into one thing) do exist, # but might be specialized for this DND-like use. # That's ok, they're useful even if always custom -- # they can have statustext, help info, history info, name & accel key, cmdline equivalent, etc, too. # They are pretty much like a command with some standard type & args (some args symbolic or from env). # potential actions for use while DNDing an edge, relative to the edge itself: AttachTo(target) AttachToNew(space, position, what) edge.AttachTo(target) # action is about an edge, thus it's "edge.something" # capital A is standard for command names, which are special case of type names (command == type of action) # - the above is still something like a widget expr, since we can instantiate it as a way of actually doing the action! # - but there is a related expr, maybe a param of that one(??) (or of an instance of it, even if it isn't done yet) # which shows the potential of doing it, and has the mentioned metainfo about that. # Q: do we instantiate the action as soon as it's a specific potential action, or only when we do it? # A: when it's a specific potential action. # Proof 1: if history mentions the potential action (eg it's shown like this at this time), # and then we do it, and history mentions that, they need tying together; # both being same instance (at different lifecycle stages) is the simplest way. # Proof 2: if each action instance has a random color or whatever, # we might want to show this in the appearance of the potential action. # That means we instantiate all the potential actions we show (e.g. as menu items, or translucent alternatives for deposit). # Note that if we do something, unrelated potential actions now have new starting conditions and might look different; # sometimes they'd need to become new instances (if the process of making them used something that just changed). # does that mean that edge.AttachTo(target) is already instantiated? Hmm... edge is, and target is... OTOH, # I could imagine passing it into something which decides whether to instantiate it... so I guess it's not. # e.g. action1 = If(cond, edge.AttachTo(target1), edge.AttachTo(target2)) # note: the thing doing the action could be symbolic: _thing.AttachTo(target) # Q: is that the same as this?? AttachTo(target) # I don't know. [Guess: yes, if we wanted it (or something like it) to be the same as this, when we designed AttachTo.] #### # Related Q: do some exprheads autocurry, so that Sym(x1) is the same as Sym(x1, _somespecificsymbol), or perhaps more analogously, # the same as lambda x: Sym(x1,x)?? #### # (Digr: the latter need not be expanded on each use -- it can be expanded on a symbol, and the resulting expr lexreplaced on each use. # And the arg/kw signature (len args, keys of kws) to use can be determined at runtime, the first time each signature is used. # These ideas are mostly mentioned previously in recent notesfiles or papers.) # Now how might we use some of these potential-action exprs? # - instantiate some of them, bound to possible user actions (like drop under certain conds (eg on what, in where) with certain modkeys), # these are still potential since the user actions (events) are possible rather than actual. # - these have looks -- draw some of them, maybe all the ones in some set that we also "bind to reality", ie to a source of a real event. # - the fact that they're bound to that event-source which has a present potential existence (the drag before the drop, # or the menu before the menuitem selection) does two things at once, which we like to have tied together: # - display the appearance of the potential action (which can now depend on which potential events it's tied to -- it's a bound action) # - enable this action as the real one to happen, if that possible event happens. # Note: binding the potential action to a possible event constitutes offering the action. This is visible, and it's a real offer. # So "real offers should be visible" -- this is why those two things should be tied together. # so we have: potential action, as expr or instance, bound to possible event (ortho to whether it's expr or instance afterwards, i think ###), # which if bound to an instance of a possible event is offered to whatever might do that event. # a possible event expr: ControlDropOn(Node) # how do we say Node is the type of _target?? (do we??) # a potential action expr: AttachTo # edge. ? (target)? # map from possible events to their actions # (the word "potential" is often implicit; that's ok since it's really a matter of how the action relates to other things) { ControlDropOn(Node) : edge.AttachTo } # this assumes Node is the type of "the arg" and edge.AttachTo is a method to apply to "the arg" edge.AttachTo # a reasonable "bound method" ControlDropOn(Node) # a bit weird, since ControlDropOn(thing) (for thing perhaps being of type Node) might be an instance of this type, # so it's as if we had a pattern language in which any term in an expr can be replaced by a type for that term... # but this leaves a lot of things implicit unless types and ordinary terms are always distinguishable, # which seems unlikely if types are firstclass. # So don't we want to say ControlDropOn(_:Node) # or the like? # (digr: i bet that syntax could actually work, if we can use Slice as a pattern-forming operator. # Whether it *should* work is another matter... no idea. ###) # hmm -- we might rather say AnythingOfType(Node) rather than <thing that looks like a lexvar of a specific name, even _> of type Node. # Then we can say that AnythingOfType is a special kind of pattern-forming exprhead, one of a few things treated specially in patterns. # OTOH maybe ControlDropOn is able, when used as a pattern, to coerce its arg1 into a type?? Which Node already is... # or even easier, detect that it's a type (of things you can drop on)? After all, a type is an individual, but it isn't # an individual in the class "things you can drop on" which is what ControlDropOn(arg1) wants in arg1 to be an event. # So maybe Exrphead(arg1, arg2) with full typedecls for the args has no problem detecting typelike args, re those types, # and treating them as patterns? I guess there could be problems created by finding recursive types of themselves in lambda calc... # surely we needn't worry about that in making a heuristic be ANAP? (As Nice As Possible) #### # Conclusion: I think ControlDropOn(Node) can work if I want it to, when designing ControlDropOn.
NanoCAD-master
cad/src/exprs/scratch/scratch6.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ dna_ribbon_view_scraps.py $Id$ outtakes from dna_ribbon_view.py which are importable now [070201] ###UNTESTED and might be worth finishing and testing, or salvaging useful code/ideas from. Any old code from demo_dna-outtakes.py that was still in dna_ribbon_view.py is now only here. """ # == from basic import * from basic import _self from Overlay import Overlay from TextRect import TextRect from OpenGL.GL import * #e move what needs this into draw_utils from dna_ribbon_view import * ###e reloadable -- needed at least for IorE, probably more from utilities import debug_flags # == Corkscrew = Stub class Ribbon_oldcode_for_edges(Corkscrew): # generates a sequence of rects (quads) from two corkscrews, then draws a ribbon using them def draw(self, **mods): if 1: # draw the ribbon-edges; looks slightly better this way in some ways, worse in other ways -- # basically, looks good on egdes that face you, bad on edges that face away (if the ribbons had actual thickness) # (guess: some kluge with lighting and normals could fix this) Corkscrew.draw(self, color = interior_color) if 0: glTranslate(offset, 0,0) Corkscrew.draw(self, color = interior_color) ### maybe we should make the two edges look different, since they are (major vs minor groove) glTranslate(-offset, 0,0) # == ##class Ribbon2(Ribbon): # draws, using the same params needed for a corkscrew, a pair of ribbons that look like a DNA double helix ## # radius, axis, turn, n ## pass class Rotate(IorE):#e refile with Translate -- in fact, reexpress it as interposing on draw and lbox methods, ignoring the rest... # (as discussed extensively elsewhere, not sure if in code or notesfile or paper, 1-3 days before 070131) # needs to transform other things too, like lbox -- same issue as Translate thing = Arg(Widget) angle = Arg(float) axis = ArgOrOption(Vector, DZ) ###e or LineSegment, then do translate too ###e should normalize axis and check for 0,0,0 def draw(self): glRotatef(angle, axis[0], axis[1], axis[2]) # angle is in degrees, I guess self.drawkid( self.thing) ## self.thing.draw(self) glRotatef(-angle, axis[0], axis[1], axis[2]) # might be optional, I forget the semantics of things like Overlay ###k pass call_lambda_Expr = Stub lambda_Expr = Stub ShareInstances = Stub class Ribbon2_try1(Macro): ###e perhaps needs some axis -> axisvector """Ribbon2(thing1, thing2) draws a thing1 instance in red and a thing2 instance in blue. If thing2 is not supplied, a rotated thing1 instance is used for it, and also drawn in blue. """ angle = 150.0 arg1 = ArgExpr(Widget) # but it better have .axis if we use it to make arg2! BUT if it's an expr, how can it have that yet? #### are some attrs of exprs legal if they don't require instanceness to be computed, depending on the type? #### (typical for geometric stuff) or only if this kind of expr is "born an instance"? But if it's highlightable, it's not... # but it might have an axis anyway... but do we really mean arg2's axis? no... maybe a special instance of arg1 used in this expr alone? yes. _arg1_for_arg2 = Instance(arg1) # only used if arg2's dflt expr is needed; has to be an instance so we can ask for its .axis #e maybe this requirement can be relaxed since.axis does not depend on self?? not sure -- anyway it might... since it # might depend on local coords -- no, it's defined to be rel to local coords, so it doesn't.... ###k arg2 = ArgExpr(Widget, Rotate( _arg1_for_arg2, angle, _arg1_for_arg2.axis)) # in old code we passed a single Ribbon, used it twice delegate = Overlay(arg1(color = red), arg2(color = blue)) ###PROBLEM: too late to customize arg2 if it's an Instance! ## (unless this sets some state and is thereby possible on an instance... seems fishy even so.) # is the real intent of _arg1_for_arg2 to be an instance? what if arg2, using it, was made multiple times? # so no, that's the bug -- _arg1_for_arg2 is an expr which when made in those two places in arg2 dflt should be shared -- # but it's not already an instance. It's like an ArgExpr with all ipath components added locally in this class already fixed # rather than coming from whatever gets built up -- as if we wrapped it when it came in and we did this, # then were able to strip off whatever ipath it got -- or equivly, we wrap it with "ignore outer ipath, just use this one". # As if I said _arg1_for_arg2 = ShareInstances(arg1) -- it gets an ipath but then ignores furtherly added ones. Hmm... # probably easy to implem if I decide it's right! # # [then I did Ribbon2_try2, then I extended this to say:] ### BUT IT'S WRONG, since if we use arg2 (expr) in several places here, how do we let each of *them* use different instances # of _arg1_for_arg2? We'd somehow have to say in arg2 dflt that we use the same instance of _arg1_for_arg2 for each inst of it -- # but only for that, not for other instances of it. As if it had a quantifier for "what inst of arg1 to use in here". # As our lambda_Expr would make possible... ###DIGR can we let a call_Expr imply a lambda_Expr if arg1 is a lambda?? if 'do this instead': dflt_arg2 = call_lambda_Expr( lambda myarg1: Rotate( myarg1, angle, myarg1.axis), arg1 ) # or maybe a lambda_Expr is callable and doing so makes a call expr -- as opposed to being customizable (until called): dflt_arg2 = 0 and lambda_Expr( lambda arg1: Rotate( arg1, angle, arg1.axis))( arg1 ) # lambda is really called on an Instance # without '0 and', due to Stub bug, we get AssertionError: not permitted to re-supply already supplied positional args, in <Widget2D#17093(a)> arg2 = ArgExpr(Widget, dflt_arg2) _customized_arg2 = arg2(color=blue) ### PROBLEM: it might *still* be too late to customize, # since color=whatever won't burrow into things like localipathmod, let alone Rotate! ######### # this current expr could only work if customizations on certain exprs would get passed into the interior # to be used by, or before, instantiations called for inside them. Hmm, same issue for If_expr(cond, expr1, expr2)(color=blue) # assuming expr[12] accept color customization. ####### if these custs became an OpExpr, eval could eval its arg1... might work. # # later, 070127: passthru customization seems unclear & hard but wanted: # maybe the feeling that customization ought to burrow into Rotate or localipathmod is related to them delegating to an arg -- # since attr accesses delegate, so should attr definitions (but only for the attrs that actually delegate). That does make sense. # It's not easy to implement -- we have no list of attrs that don't delegate, we just try getattr and see if we get into __getattr__. # So to customize an attr -- wait, would it work to customize it at the outer level? No, because the draw call occurs inside. # It's as if we wanted to constrain X and Rotate(X) to have the same def and value of attr (if it delegates), e.g. color. # But the fact that X.draw uses X.color is not even dependent on whether Rotate delegates color! Ignoring that last point, # can customize mean "find the internal users of the def of color, and make them use this different def"? These internal users # are kid instances. They are self-contained in ability to use color. So parent would have to modify them -- presumably when it makes them. # So parent(color = cust) would have to instantiate, not its normal kid delegate, but kid(color = cust), I guess. I don't see an # easy implem, and I'm also suspicious it's the right idea. # So maybe the only soln is to do the color cust first, as the docstring had to say to describe the intent, anyway. pass class Ribbon2_try2(Macro):###e perhaps needs some axis -> axisvector ###IMPLEM ShareInstances - or not, if that lambda_Expr in _try1 makes it unneeded... it might be wrong anyway # if it provides no way to limit the sharing within the class that says to do it, or if doing that is too cumbersome or unclear. """Ribbon2(thing1, thing2) draws a thing1 instance in red and a thing2 instance in blue. If thing2 is not supplied, a rotated thing1 instance is used for it, and also drawn in blue. """ angle = 150.0 arg1 = ArgExpr(Widget) _drawn_arg1 = Instance(arg1(color=red)) ###e digr: could I have said Instance(arg1, color=red)? I bet people will try that... _arg1_for_arg2 = ShareInstances(arg1(color=blue)) # still an expr; in fact, this ASSUMES arg1 is passed in as an expr, not as an instance! Hmm##### ## arg2 = ArgExpr(Widget, Rotate( _arg1_for_arg2, angle, _arg1_for_arg2.axis)) arg2 = ArgExpr(Widget, Rotate( _arg1_for_arg2, angle, getattr_Expr( _arg1_for_arg2, 'axis') )) _drawn_arg2 = Instance(arg2(color=blue)) ####KLUGE: add color here in case arg2 was supplied, but in dflt expr in case we used that delegate = Overlay(_drawn_arg1, _drawn_arg2) class Ribbon2_try3(Macro): #070129 ###e perhaps needs some axis -> axisvector """Ribbon2(thing1, thing2) draws a thing1 instance in red and a thing2 instance in blue, assuming they are color-customizable. If thing2 is not supplied, a rotated thing1 instance (different drawable instance, same model object instance) is used for it (also drawn in blue). """ angle = 150.0 arg1 = Arg(ModelObject3D) ###k type implies that it has 3d shape etc, determines how much gets instantiated here (axis, not color??) arg2 = Arg(ModelObject3D, Rotate(arg1, angle, arg1.axis) ) # doesn't yet work... see below # Rotate works on a ModelObject3D instance which is like a Drawable expr # note: Rotate's default axis is the Z axis, not arg1.axis even if that exists delegate = Overlay(arg1(color = red), arg2(color = blue)) # doesn't yet work... see below # For all this to work requires two proposed semantic changes: # - Rotate delegation more like customization -- instance of Rotate produces no separate instance of its delegate # - partial instantiation by Arg, only of attrs that are part of its declared type (mentioned above) # (these changes make it likely that the 'delegate' attr will be renamed, too) pass # very old cmt: # Ribbon2 has: radius, axis (some sort of length - of one bp?), turn (angle??), n, color1, color2, and full position/orientation # and it will have display modes, incl cyl with helix/base/groove texture, and flexible coloring; # and ability to show the units in it, namely strands, or basepairs, or bases (selected/opd by type) # and for us to add cmd bindings like "make neighbor strand" (if room) or "make crossover here" (maybe only on a base?) # but as a first step, we can select it as a unit, copy/paste, deposit, move, etc. # In this, it is sort of like an atom or set of co-selected atoms... some relation to chunk or jig too. # I'd get best results by letting it be its own thing... but fastest, by borrowing one of those... class obs: path = StateArg(Cylinder_HelicalPath) path.someattr = Option(Something, 'dflt') # set path.someattr to Option(...) -- ExprsMeta scanner would need to see this -- # but what attrname would it use in the Option?? maybe the _try1 version is better since it says the name, # or maybe you can give it in Option as string arg1. class todo: # might need other state, like some colors # and links to things made from this guide shape -- or a superclass or whatever that says we are a guide shape # (and all of them can have links like that) # and ops to make attached things like crossovers, to give posns for potential ones # and display styles for self and those things... # for now just have default drawing code, using the Ribbon classes above. pass # == import Command_scratch_1 # == if 0: # old example usage Ribbon2(1, 0.2, 1/10.5, 50, blue, color2 = green), # this color2 arg stuff is a kluge Highlightable( Ribbon2(1, 0.2, 1/10.5, 50, yellow, color2 = red), sbar_text = "bottom ribbon2" ), # end
NanoCAD-master
cad/src/exprs/scratch/dna_ribbon_view_scraps.py
""" test_animation_mode.py -- scratch code for animation loop, connectWithState, exprs drawing. @author: Bruce @version: $Id$ To run this code: 1. shell commands to make a symbolic link (or you can copy it if you don't want to recommit your edits): % cd ~/Nanorex/Modes % ln -s /Nanorex/trunk/cad/src/exprs/scratch/test_animation_mode.py . # or whatever this file's absolute pathname is 2. rerun NE1 (needed?) 3. debug menu -> custom modes -> test_animation_mode History: this was mostly written long ago in my spare time, just for fun. I put it in cvs since it's sometimes useful now as a testbed. Bugs: updated 070831 - Needs fix for exit to remove PM tab, like in test_commands - Performance is worse in NE1 PyOpenGL than in the PyOpenGL I have on the iMac G5 (the same thing is true for testmode) - refers to a missing image file on my desktop (out of date below this) test_animation_mode bugs as of 060219 night: - loop stops; should be checkbox - arrow keys are not camera relative; they're player-rel but player never turns; really they're world-rel (which is wrong) - camera never tries to swing behind player - camera dynamics are not very good (should get there faster, stop sooner, maybe have inertia) - stuff is not in MT or mmp file - stuff is not very interesting yet and a couple more noted on g4: - antialiasing - a few more """ from widgets.prefs_widgets import Preferences_StateRef, Preferences_StateRef_double, ObjAttr_StateRef from foundation.changes import Formula ## from test_animation_mode_PM import test_animation_mode_PM from prototype.test_command_PMs import ExampleCommand1_PM from PM.PM_GroupBox import PM_GroupBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_PushButton import PM_PushButton from PM.PM_CheckBox import PM_CheckBox from command_support.Command import Command from command_support.GraphicsMode import GraphicsMode from utilities.debug import print_compact_traceback, register_debug_menu_command import time, math from foundation.state_utils import copy_val from utilities.constants import green, red, white, pink, black, brown, gray # other colors below from math import pi from graphics.drawing.CS_draw_primitives import drawline from graphics.drawing.drawers import drawbrick from graphics.drawing.CS_draw_primitives import drawsphere from graphics.drawing.CS_draw_primitives import drawcylinder from OpenGL.GL import GL_LIGHTING, glDisable, glEnable from geometry.VQT import cross, proj2sphere, V, norm, Q, vlen from foundation.Utility import Node import foundation.env as env DX = V(1,0,0) DY = V(0,1,0) DZ = V(0,0,1) from PyQt4.Qt import Qt, QCursor # for Qt.Key_Left, etc shiftButton = Qt.ShiftModifier controlButton = Qt.ControlModifier # from experiment, 070813, intel macbook pro _key_control = 16777250 _key_command = 16777249 # for points of interest in this file, search for: # - class test_animation_mode ###TODO: # works in exprs/test.py: Image("/Users/bruce/Desktop/IMG_0560 clouds1.png") # see test_commands.py... # WARNING: if you have test_animation_mode.py OR test_animation_mode.pyc in cad/src, that one gets imported instead of one in ~/Nanorex/Modes. # see also test_animation_mode-outtakes.py [lots of obs stuff moved there, 060219] class Sketch3D_entity: pass class Sketch3D_Sphere(Sketch3D_entity): # see class Sphere in exprs.Rect -- that ought to be enough info for a complete one! pass ##from exprs.staterefs import PrefsKey_StateRef ## ##def Preferences_StateRef_double( prefs_key, defaultValue = 0.0): #UNTESTED ## ### TODO: cache this instance somehow (based on our args), as we IMPLEM the way to make it -- see test_commands for that ## expr = PrefsKey_StateRef( prefs_key, defaultValue) ## return find_or_make_expr_instance( expr, cache_key = ('PrefsState', prefs_key), assert_same = (defaultValue,) ) ## ##### IMPLEM find_or_make_expr_instance, and make it fast when expr already exists (but do make it check assert_same, for now) CANNON_HEIGHT_PREFS_KEY = "a9.2 devel/test_animation_mode/cannon height" CANNON_HEIGHT_DEFAULT_VALUE = 7.5 def cannon_height(): # make a method?? why? return env.prefs.get( CANNON_HEIGHT_PREFS_KEY, CANNON_HEIGHT_DEFAULT_VALUE) def set_cannon_height(val): env.prefs[CANNON_HEIGHT_PREFS_KEY] = val CANNON_OSCILLATES_PREFS_KEY = "a9.2 devel/test_animation_mode/cannon oscillates" CANNON_OSCILLATES_DEFAULT_VALUE = True def cannon_oscillates(): return env.prefs.get( CANNON_OSCILLATES_PREFS_KEY, CANNON_OSCILLATES_DEFAULT_VALUE) SILLY_TEST = False #### TESTING_KLUGES = False # temporary class test_animation_mode_PM(ExampleCommand1_PM): """ [does not use GBC; at least Done & Cancel should work] """ title = "test_animation_mode PM" def __init__(self, command): #bruce 080909/080910, remove win arg ExampleCommand1_PM.__init__(self, command) def _addGroupBoxes(self): """ Add the groupboxes for this Property Manager. """ self.pmGroupBox1 = \ PM_GroupBox( self, title = "test_animation_mode globals", ) self._loadGroupBox1(self.pmGroupBox1) self.pmGroupBox2 = \ PM_GroupBox( self, title = "commands", ) self._loadGroupBox2(self.pmGroupBox2) return _sMaxCannonHeight = 20 def _loadGroupBox1(self, pmGroupBox): """ Load widgets into groupbox 1 (passed as pmGroupBox) """ ## elementComboBoxItems = self._sElementSymbolList ## self.elementComboBox = \ ## PM_ComboBox( pmGroupBox, ## label = "Elements :", ## choices = elementComboBoxItems, ## index = 0, ## setAsDefault = True, ## spanWidth = False ) ### change to a control for cannon height, dflt 7.5. # have to figure out what state that is, how to share it and track it. # use expr state to store it?? change class cannon into an expr? # but then when we adjust this does it affect all cannons or only a current one? either is possibly desirable... # and if both can work, it means cannon instances have formulas for their height, # some referring to default from class or maker... self.cannonHeightSpinbox = \ PM_DoubleSpinBox( pmGroupBox, label = "cannon height:", #e try ending that label with " :" rather than ":", too value = CANNON_HEIGHT_DEFAULT_VALUE, # guess: default value or initial value (guess they can't be distinguished -- bug -- yes, doc confirms) setAsDefault = True, minimum = 3, maximum = self._sMaxCannonHeight, singleStep = 0.25, decimals = self._sCoordinateDecimals, suffix = ' ' + self._sCoordinateUnits ) ### REVIEW: when we make the connection, where does the initial value come from if they differ? # best guess answer: PM_spec above specifies default value within PM (if any); existing state specifies current value. self.cannonHeightSpinbox.connectWithState( Preferences_StateRef_double( CANNON_HEIGHT_PREFS_KEY, CANNON_HEIGHT_DEFAULT_VALUE ) ) self.cannonWidthSpinbox = \ PM_DoubleSpinBox( pmGroupBox, label = "cannon width:", value = 2.0, setAsDefault = True, minimum = 0.1, maximum = 15.0, singleStep = 0.1, decimals = self._sCoordinateDecimals, suffix = ' ' + self._sCoordinateUnits ) self.cannonWidthSpinbox.connectWithState( ObjAttr_StateRef( self.command, 'cannonWidth') # first real test of ObjAttr_StateRef. # test results: pm change -> tracked state change (mode attr), with redraw being triggered: works. # other direction (mode change to cannonWidth, in cmd_Start -> pm change) -- fails! ###BUG # note: the prefs state also was not tested in that direction! now it is, in fire command, and it works, # but this, also tested there, still fails. ... What could be different in these two cases? # Is there an API mismatch in the lval we get for this, with get_value not doing usage tracking? ) self.cannonOscillatesCheckbox = \ PM_CheckBox(pmGroupBox, text = 'oscillate cannon during loop' , ## value = CANNON_OSCILLATES_DEFAULT_VALUE ### BUG: not working as default value for restore defaults # in fact, worse bug -- TypeError: __init__() got an unexpected keyword argument 'value' ) self.cannonOscillatesCheckbox.setDefaultValue(CANNON_OSCILLATES_DEFAULT_VALUE) #bruce extension to its API self.cannonOscillatesCheckbox.connectWithState( ### UNTESTED in direction mode->PM, tho i think code is tested in user prefs Preferences_StateRef( CANNON_OSCILLATES_PREFS_KEY, CANNON_OSCILLATES_DEFAULT_VALUE ) ) return def _loadGroupBox2(self, pmGroupBox): self.startButton = \ PM_PushButton( pmGroupBox, label = "", text = "Start", spanWidth = False ) ###BUG: button spans PM width, in spite of this setting self.startButton.setAction( self.cmd_Start, cmdname = "Start") self.stopButton = \ PM_PushButton( pmGroupBox, label = "", text = "Stop", spanWidth = False ) self.stopButton.setAction( self.cmd_Stop, cmdname = "Stop") #e also let in_loop be shown, or control whether they're disabled... note it can be changed by external effects # so we need to track it and control their disabled state, using a formula that gets checked sufficiently often... # connect the expr or formula for self.command._in_loop to the update function... ## whenever_state_changes( ObjAttr_StateRef( self.command, '_in_loop'), self.update_GroupBox2 ) ###IMPLEM 2 things ## or just do this?? call_often(update_GroupBox2) -- a few times per sec, and explicit calls on the buttons... seems worse... self._keepme = Formula( self.update_GroupBox2, self.update_GroupBox2 ) ### hmm..... return def update_GroupBox2(self, junk = None): in_loop = self.command._in_loop ### or should this be passed in?? probably a better habit is if it's not... # note we can't track it from running this, since that attr is not directly usage tracked. # maybe we should change it so it is? then just call this once and say "call whenever what it used changes"... ##### TODO / REVIEW self.startButton.setEnabled( not in_loop) ### TODO: make something like setEnabledFormula for this... pass it a function?? self.stopButton.setEnabled( in_loop) return def cmd_Start(self): self.command.cmd_Start() def cmd_Stop(self): self.command.cmd_Stop() def _addWhatsThisText(self): """ What's This text for some of the widgets in the Property Manager """ self.cannonHeightSpinbox.setWhatsThis("cannon height") return pass # test_animation_mode_PM """ File "/Nanorex/Working/cad/src/platform.py", line 92, in ascii return filter_key( self._qt_event.ascii() ) #k (does filter_key matter here?) AttributeError: ascii """ #unfixed bug in arrow key bindings -- due to event.ascii ### BUG: not available in Qt4 [070811] keynames = {} for keyname in filter(lambda s: s.startswith('Key'), dir(Qt)): keynames[getattr(Qt, keyname)] = keyname def keyname(key):#070812 try: return keynames[keyname] except KeyError: return "<key %r>" % (key,) pass pink1 = (0.8, 0.4, 0.4) yellow = (0.8, 0.7, 0.0) yellow2 = (0.8, 0.7, 0.2) ygreen = (0.4, 0.85, 0.1) blue = (0.0, 0.2, 0.9) orange = (1.0, 0.35, 0.05) orange = (1.0, 0.3, 0.00) pumpkin = (0.9, 0.4, 0.0) purple = (0.7, 0.0, 0.7) #060218 bugfix def light(color, whiteness = 0.25): return mix(color, white, whiteness) def mix(color1, color2, amount2): amount2 = V(amount2, amount2, amount2) #e optional? amount1 = V(1, 1, 1) - amount2 return color1 * amount1 + color2 * amount2 lgreen = light(green) lblue = light(blue) lred = light(red) colorkeys = dict(R = light(red), G = light(green), B = light(blue), P = light(purple), W = light(black, 0.8), K = light(black), Y = yellow, O = orange, ) # and these, once we move them there: ####@@@@ assume Node inherits _S_State_Mixin ### that and other _S_ mixins can define writemmp, which classes can override if they want to use trad methods, # calling utils in it to write info if desired (worry - don't Groups do that for them in some cases??), # or they can not define it or tell it to call that mixin version, and then it just uses decls. # also we can support binary mmp from them, as well as undo of course. # undo policy decls can override what you'd guess from state decls. ###refile this S_DATA = 'S_DATA' # S_DATA, S_CHILD, S_CHILDREN, S_PARENT, S_PARENTS, S_REF, S_REFS, S_CACHE, S_JUNK, S_OWNED_BY, ... class _S_Data_Mixin: pass #e stub #e refile in state_utils class _S_ImmutableData_Mixin(_S_Data_Mixin): """ For efficiency, inheritors of this mixin promise that all their declared data is immutable, so it can be shared by all copies, and so they themselves can be copied as themselves. (Most of them deepcopy the data passed into them, to protect themselves from callers who might pass shared data.) """ def _s_deepcopy(self, copyfunc): ##k API [not presently called as of 081229, AFAIK] #e maybe someday we'll inherit this from (say) _S_ImmutableData_Mixin return self def _s_copy_for_shallow_mod(self): #e likely to be renamed, maybe ...private_mod """ Private method for main class -- copy self, sharing data, in anticipation that the copy will be privately modified and then returned as a new immutable data object. """ assert 0, "nim" #e but should be easily done using _s_initargs, or perhaps the set of _s_attr decls pass # see also comments about _s_initargs API, below # == def do_what_MainWindowUI_should_do(win): pass _superclass = Command # see also _superclass_for_GM # new stuff 060218 # local copy for debugging & customization, original by josh in VQT.py class myTrackball: """ A trackball object. The current transformation matrix can be retrieved using the "matrix" attribute. """ def __init__(self, wide, high): """ Create a Trackball object. "size" is the radius of the inner trackball sphere. """ self.w2=wide/2.0 self.h2=high/2.0 self.scale = 1.1 / min(wide/2.0, high/2.0) self.quat = Q(1,0,0,0) self.oldmouse = None def rescale(self, wide, high): self.w2=wide/2.0 self.h2=high/2.0 self.scale = 1.1 / min(wide/2.0, high/2.0) def start(self, px, py): self.oldmouse=proj2sphere((px-self.w2)*self.scale, (self.h2-py)*self.scale) def update(self, px, py, uq=None): newmouse = proj2sphere((px-self.w2)*self.scale, (self.h2-py)*self.scale) if self.oldmouse and not uq: quat = Q(self.oldmouse, newmouse) elif self.oldmouse and uq: quat = uq + Q(self.oldmouse, newmouse) - uq else: quat = Q(1,0,0,0) self.oldmouse = newmouse ## print "trackball quat would rotate V(0,0,1) to",quat.rot(V(0,0,1)) showquat("trackball quat", quat, where = V(-3,0,0)) ## drawline(white, self.origin, endpoint) return quat pass def hacktrack(glpane): print "hacking trackball, permanently" glpane.trackball = myTrackball(10, 10) glpane.trackball.rescale(glpane.width, glpane.height) quats_to_show = {} def showquat(label, quat, where = V(0,0,0)): quats_to_show[label] = (Q(quat), + where) def draw_debug_quats(glpane): for quat, where in quats_to_show.values(): drawquat(glpane, quat, where) def drawquat(glpane, quat, where): # not yet good enough: need to correct for screensize and scale, put it in fixed place/size on screen. # more importantly, what I *need* to show is accumulation of several small quats... not sure how. # or maybe, the *history* of this one? as it is, latest value might be "0" and so i don't see the transient one. oldquat = glpane.quat newquat = oldquat + quat def trans(screenpos): return glpane.pov + oldquat.unrot(screenpos) # show how the x,y,z axes would be moved. p0 = trans(where) for vec, color in [ (V(1,0,0), red), (V(0,1,0), green), (V(0,0,1), blue) ]: vecnow = oldquat.rot(vec) vecthen = newquat.rot(vec) p1 = trans(where + vecnow) p2 = trans(where + vecthen) drawline(color, p0, p1) drawline(color, p1, p2) return # i want a trackball which is constrained to keep the Y axis in the up/out plane. # this cmd works, but interface is a pain... at least needs button, but really needs to be a trackball option for this mode. # well, it can be, since we intercept the trackballing events! def novertigo_cmd(widget): glpane = widget novertigo(glpane) return def novertigo(glpane): """ Rotate the view so that the Y axis V(0,1,0) points up, plus maybe a bit in or out. """ xjunk, y, z = Y = glpane.quat.rot(V(0,1,0)) # we'll use a projection of this into the y,z plane, but fix it to be within our range; note, y,z could be (0,0) k = 2 # determines max angle from vertical ## print "Y =",Y ## printvec("Y",Y) if y < k * abs(z): y = k * abs(z) if y == 0 and z == 0: y, z = 1, 0 proj = norm(V(0, y, z)) ##printvec("proj",proj) ## print proj # proj is where we want Y to be incrquat = Q(Y, proj) showquat("incrquat",incrquat, V(3,0,0)) glpane.quat += incrquat ## q2 = glpane.quat + Q(Y, proj) ## glpane.snapToView(q2, glpane.scale, glpane.pov, glpane.zoomFactor) return def printvec(label, vec): print label, "(%03f, %03f, %03f)" % (vec[0], vec[1], vec[2]) # why does it print with 6 digits? Y (-0.003402, 0.696759, 0.717297) register_debug_menu_command("novertigo", novertigo_cmd) # will only work in glpane debug menu def hack_standard_repaint_0(glpane, prefunc): """ replace glpane.standard_repaint_0 with one which calls prefunc and then calls the class version of standard_repaint_0 """ def imposter(glpane = glpane, prefunc = prefunc): prefunc() glpane.__class__.standard_repaint_0(glpane) return glpane.standard_repaint_0 = imposter return # == class CyberTextNode(Node): """ Hold some text which can be edited and displayed, and a few properties to control when/where/how to display it. Also try to let it exist in cyberspace, i.e. when it's changed, store it there, and when we're reshown, reload it from there. For initial test, cyberspace means a file whose basename we contain and whose dirname is hardcoded. Or a prefs db entry, or something like that. - Hmm... how does user make one? Mt cmenu. - How does user edit text? Ideally, select node, then text is shown in editable text field. This field is only there when something has text to edit (not nec. us). Optional cool feature: if multiple nodes selected, show all of them (editably) in that text field (longer, scrollable). - Where do we put that text field? Better make one... no good place at the moment. Do we have *any* code to grab for that? - history widget - debug text edit - glpane text, with our own key bindings for editing -- sounds harder, not sure it really is (need focus to follow selected node) Related nE-1 desired features: - edit props for any node, in a pane added below it in MT when it's selected -- this is almost identical to what we want here - text-containing node, for notes, or display in 3dview -- also almost identical - the cyberspace part is the only weird part So, what to do? - have a text widget at MT bottom, hide/show on demand - be able to tie it to edit any textual lvalue; some owner takes it over by providing that lval's API, later releases it, and new owners can also kick out old ones - this node, when selected, takes it over unless it's locked, or always if some cmenu command is used or if it's unlocked - this locking is controlled by a cmenu on the text widget, or a checkbox, or equivalent """ # see Macintosh HD:Nanorex:code, work notes:060401 code snippets # QTextEdit(win.mt) def find_or_make_textpane(win): try: return win.__textpane except: pass try: vs = win.vsplitter2 except: return None # make it only once te = QTextEdit(vs) #e use subclass with key bindings; maybe put it in a 1-pixel frame vs.setSizes([vs.height() - 100, 100]) #k assumes our new widget is only the 2nd shown thing of two things (1st being win.mt) te.show() win.__textpane = te return te """ set mtree_in_a_vsplitter in MWsemantics (edit it before startup) (debug_pref?) from __main__ import foo as win import test_animation_mode print test_animation_mode.find_or_make_textpane(win) """ # == class DebugNode(Node): def __init__(self, stuff, name = None): assy = env.mainwindow().assy #k wrongheaded?? Node.__init__(self, assy, name) self.stuff = stuff # exprs for what to draw (list of objects) _s_attr_stuff = S_DATA def draw(self, glpane, dispdef): if self.picked: # only draw when picked! (good?) draw_stuff(self.stuff, glpane) def writemmp(self, mapping): """ Write this Node to an mmp file, as controlled by mapping, which should be an instance of writemmp_mapping. """ line = "# nim: mmp record for %r" % self.__class__.__name__ mapping.write(line + '\n') # no warning; this happens all the time as we make undo checkpoints return def __CM_upgrade_my_code(self): # experiment """ replace self with an updated version using the latest code, for self *and* self's data! """ name = self.__class__.__name__ print "name is",name # "DebugNode" print self.__class__.__module__ # "test_animation_mode" #e rest is nim; like copy_val but treats instances differently, maps them through an upgrader pass def draw_stuff(stuff, glpane): if type(stuff) in (type(()), type([])): for thing in stuff: draw_stuff(thing, glpane) else: try: stuff.draw(glpane) except: print_compact_traceback("draw_stuff skipping %r: " % (stuff,)) return # == class DrawableStuff(_S_Data_Mixin): def __init__(self, *args, **kws): self.args = copy_val(args) self.kws = copy_val(kws) self.process_args() _s_attr_args = S_DATA _s_attr_kws = S_DATA def _s_initargs(self): #####k API -- in this case we're providing full info, # but didn't the _um_ version get to leave out some attrs, and instead handle them with diffs?? ###@@@ # we want to keep it simple, but we know there are some objects that require that approach... # maybe let them define a *different* method and leave this one undefined?? or have a different retval format for that case?? return self.args, self.kws def process_args(self): # callers can add arg asserts if they want; we guarantee __init__ will call this, so it can store args in attrs, # which _S_Data_Mixin will effectively treat as S_CACHE by default pass pass class makeline(DrawableStuff): def process_args(self): self.color, self.pos1, self.pos2 = self.args[0:3] def draw(self, glpane): drawline(self.color, self.pos1, self.pos2) pass class makedot(DrawableStuff): def process_args(self): self.color, self.pos = self.args[0:2] def draw(self, glpane): #e stub, need to choose radius based on pixel size, and make a circle not sphere detailLevel = 2 radius = 0.1 ### total stub and guess drawsphere(self.color, self.pos, radius, detailLevel) pass #####@@@@@ pass class makevecs(DrawableStuff): def process_args(self): self.origin, self.vecs, self.colors = self.args[0:3] self.vecs_colors = zip(self.vecs, self.colors) def draw(self, glpane): for vec, color in self.vecs_colors: drawline(color, self.origin, self.origin + vec) return pass # == class attrholder: def __init__(self, **options): self.__dict__.update(options) pass DEFAULT_DIRECTIONS = attrholder(away = - DZ, towards = DZ, up = DY, down = - DY, left = - DX, right = DX) # maybe attrnames should differ? def interpret_arrow_key( key, space = None): ###TODO: pass space if nec. """ return None for a non-3d-arrow-key, or a direction vector for one, taken from space or DEFAULT_DIRECTIONS """ if not space: space = DEFAULT_DIRECTIONS if key == Qt.Key_Up: # 4115:# up means in = lineofsight = away from user return space.away elif key == Qt.Key_Down: # 4117: # down means out = towards user return space.towards elif key == Qt.Key_Left: # 4114: # left, right mean themselves return space.left elif key == Qt.Key_Right: # 4116: return space.right elif key == Qt.Key_PageUp: # 4118: # pageup means up return space.up elif key == Qt.Key_PageDown: # 4119: # pagedown means down return space.down return None # == class shelvable_graphic: # some default state attrs (kluge, should be in a graphical subclass) pos = V(0,0,0) dir = V(1,0,0) size = V(1,1,1) color = pink1 dead = False # set self.dead to True in instances, to cause destroy() and culling on next redraw # ok to set it during a command (then it prevents redraw of self) or during redraw (culls upon return); see guy.draw for implem def __init__(self, space, dict1 = {}): self.__dict__.update(dict1) # do first so we don't overwrite the following ones self.space = space # note: this is the mode, a test_animation_mode instance [assume it is a Command, not a GraphicsMode] self.glpane = space.glpane self.stuff = {} # kids, i guess [need a way of removing old ones] self.creation_time = space.simtime def changed(self):#050116 [long after shelvable_graphic stub created; note that it never worked yet] global_changed[self] = self ###k does self count as a legit key, or not? def save(self, storage, key): storage[key] = self.state() def state(self): res = {} for k in self.__dict__.keys(): # not dir(self), that includes class methods... if not (k.startswith('_') or k in ['space','stuff']): ###@@@ see also "snaps.py" which I started writing... #k don't exclude stuff... need pickle methods to turn objs into refs to them or their snapshot then. res[k] = self.__dict__[k] return res def contents(self): """ other objs whose state is sometimes considered part of ours, but not in self.state() """ return self.stuff.values() def load(self, storage, key): """ change our state to match what's in the storage """ stored = storage[key] self.__dict__.update(stored) # dangerous! def destroy(self): ## print "destroying", self # works pass def move(self, vec): self.pos = self.pos + vec pass # pickleable, mainly ##class brick(shelvable_graphic): # this is not right yet ## "a brick, in standard orientation, std size, brighter if keyfocus is on it; has specified shelf-key for state" ## def draw(self, pos = V(0,0,0), dir = V(1,0,0), size = V(1,1,1), color = pink1): ## # drawbrick(pink1, self.origin + V(2.5, 0, 0), self.right, 2.0, 4.0, 6.0) - uses current GL context (that's ok) ## drawbrick(color, pos, dir, size[0], size[1], size[2]) ## pass class wireguy(shelvable_graphic): # used for square tiles in the "racetrack" moves = False # to change this, let it be in the dict arg when we create this def draw(self, glpane): ## drawwirecube(self.color, self.pos, 1.02 / 2.0)# no place for self.dir; last number is not what i hoped... pos = self.pos if self.moves: pos = pos + DY * (self.space.simtime - self.creation_time) # 070813 [071010 glpane .mode -> self.space == a Command] drawbrick( self.color, pos - V(0, 0.6, 0), self.dir, 1.0, 1.0, 0.05) ## 0.98, 0.98, 0.05) pass TOOFAR = 100 # some things disappear when this far away -- to test this, use 6 so things disappear within sight -- works CANNONBALL_SPEED = 21 BIRD_SPEED = 11 # not yet used class cannonball(shelvable_graphic): motion = V(0,0,0) # caller may want to use CANNONBALL_SPEED when setting this position = None velocity = None last_update_time = None acceleration = -10 * DY * 3 def update_incr(self): if self.last_update_time is None: self.last_update_time = self.creation_time if self.position is None: self.position = V(0,0,0) + self.pos ###k if self.velocity is None: self.velocity = V(0,0,0) + self.motion ###k now = self.space.simtime delta_time = now - self.last_update_time # if too large, do the following in several steps, or use a quadratic formula self.position += (delta_time * self.velocity) self.velocity += (delta_time * self.acceleration) self.last_update_time = now ## print "dt = %r, so set position = %r, velocity %r" % (delta_time, self.position, self.velocity) return def draw(self, glpane): self.update_incr() # now self.position should be correct; self.pos is starting position ## age = (self.space.simtime - self.creation_time) ## displacement = self.motion * age displacement = self.position - self.pos if vlen(displacement) > TOOFAR: self.dead = True # causes delayed destroy/cull else: pos = self.position drawsphere( blue, pos, 1, 2) return pass class cannon(shelvable_graphic): # one of these is self.cannon in test_animation_mode; created with mode = that mode direction = norm(DY - DX) #070821 def basepos(self): mode = self.space ## pos = mode.origin pos = self.pos # changed by .move() return pos + V(mode.brickpos, 0, 0) - DY * 9 def draw(self): # needs glpane arg if ever occurs in object list mode = self.space # note: uses mode.brickpos for position, updated separately -- should bring that in here ## drawwirecube(purple, mode.origin, 5.0) ## drawwirecube(gray, mode.origin, 6.5) ## if 0: drawbrick(yellow, mode.origin, mode.right, 2.0, 4.0, 6.0) basepos = self.basepos() drawbrick(pink1, basepos + 1.0 * self.direction, mode.right, 2.0, 2.0, 1.0) # wrong orientation detailLevel = 2 drawsphere(red, basepos + 2.5 * self.direction, 2, detailLevel) ###@@@ radius = mode.cannonWidth / 2.0 # note: this is usage-tracked! drawcylinder(lgreen, basepos + 2.5 * self.direction, basepos + cannon_height() * self.direction, radius, True) # with red, its lighting is pretty poor; pink1 looks nice def fire(self): # bound to command key toppos = self.basepos() + cannon_height() * self.direction # note: cannon_height() is usage tracked, but needn't be in this context, but that needs to be ok without any reason # to mention it here, since the same issue affects all usage tracked variables used in commands. new = cannonball(self.space, dict(pos = toppos, motion = self.direction * CANNONBALL_SPEED)) self.space.appendnew(new) if SILLY_TEST: self.grow_cannon() return def grow_cannon(self): set_cannon_height(cannon_height()+1) # test of whether pm gets updated -- it does! self.space.cannonWidth += 0.5 # ditto - in this case it doesn't! bug [fixed now] pass # class cannon class guy(shelvable_graphic): """ a combo of object list and a specific thing ###FIX """ def draw(self, glpane): # this main guy is the one that needs to be transparent, so you can see what's he's making under him! # and, the thing he might make also needs to be transparent but there. and, a key should put it down for you... and unput it. # and, remove any other stuff in same pos! pos = self.pos ## + self.space.now # 070813 experiment -- works [since then, glpane .mode -> self.space, but i don't want to move this guy (the 3d cursor) drawbrick(self.color, pos, self.dir, 1, 1, 1) ## 2.0, 4.0, 6.0) # uses current GL context glDisable(GL_LIGHTING) drawbrick(gray, pos * V(1,0,1) - V(0, 6, 0), self.dir, 1, 1, 0.02) # brick dims for this dir are x, inout, z glEnable(GL_LIGHTING) drawline(light(black, 0.2), pos, pos * V(1,0,1) - V(0, 6, 0)) #e and a line between them deads = [] for thing in self.stuff.itervalues(): #e move to superclass? ... well, they need to notice our shadow hitting them! be transparent? fog? # i bet transparent is not super hard to do... note that for cubes (or any convex solids) # it's easy to know back to front order... if thing.dead: # (thing.dead was set during a command -- don't draw it) deads.append(thing) else: thing.draw(glpane) # arg? if thing.dead: # (thing.dead was set during draw method itself, which may or may not have returned early) deads.append(thing) for thing in deads: thing.destroy() del self.stuff[id(thing)] return def keyPressEvent(self, event): key = event.key() ## asc = event.ascii() ### BUG: not available in Qt4 [070811] ## but = event.stateAfter() ### BUG: not available in Qt4 [070811] ## but = event.state() ### BUG: not available in Qt4 [070811] but = -1 self.shift = but & shiftButton # not set correctly at the moment; used to control whether to makeonehere self.control = but & controlButton # not yet used try: chrkey = chr(key) except: chrkey = None ##print key, asc, but, chrkey if key == Qt.Key_Return: # 4100: # Return key = ord('\n') ## asc = key ## if key == ord('\n') or 32 <= key <= 126: ## # use asc, so 'a' vs 'A' is correct ## self.text = str_insert(self.text, self.curpos, chr(asc)) ## self.curpos += 1 ## ## didn't work: return 1 ###@@@ incrkluge test; not correct btw! ## elif key == 'rdel': # names like that are stubs ## self.text = self.text[:self.curpos] + self.text[self.curpos+1:] ## elif key in [4099, 'del']: # Delete on Mac; unable to bind the "del" key! ## self.text = self.text[:self.curpos-1] + self.text[self.curpos:] ## self.curpos -= 1 ## print "data:", asc, key, chrkey, self.colorkeys # asc = 114, key = 82, chr(key) = 'R' arrowdir = interpret_arrow_key(key) if chrkey in colorkeys: self.color = colorkeys[chrkey] ### 060402 new arrow keys [not done., disabled] ## elif key == 4114: ## # left ## self.space.o.left # end of 060402 new arrow keys #e also arrow keys... should these be model relative as here? # [this is in class guy, but would make more sense in class test_animation_mode] elif arrowdir is not None: if not self.space._in_loop: self.move( arrowdir) else: self.space.cannon.move( arrowdir) elif chrkey == ',': # '<' self.space.rotleft(0.05) # far away stuff goes left, that much of 360deg ... around what center? elif chrkey == '.': # '>' self.space.rotleft(-0.05) ###@@@ subr is wrong at the moment else: print "test_animation_mode received key:", keyname(event.key()) ## "(%r)" % event.key() self.save() def save(self): pass # save the state! just store our dict at a key... but turn values from objs to refs... ask the objs for those. ###@@@ def move(self, delta): """ overrides superclass move; compatible but does more """ if self.shift: self.makeonehere() # should be in the space, not the guy itself! ###@@@ self.lastmotion = delta # this is superclass.move: ###FIX, call it pos = self.pos = self.pos + delta ##print "new pos and proj", pos, pos * V(1,0,1) - V(0,6,0) # caller does redraw, no need to tell it to here def makeonehere(self): d1 = dict(self.__dict__) if self.space._in_loop: ## FIX: could simplify since self.space == mode [did it now, glpane .mode -> space] ## d1['moves'] = True # sets new.moves = True d1['motion'] = DY * 3 # new.motion new = cannonball(self.space, d1) else: new = wireguy(self.space, d1) # note: it inherits copies of all our attributes! such as pos, color. #e remove any existing stuff in the same place! let's store them in a dict by place, not this list... ###@@@ self.space.appendnew(new) ## self.stuff.append(new) pass # end of class guy # == 'editToolbar', 'fileToolbar', 'helpToolbar', 'modifyToolbar', 'molecularDispToolbar', annoyers = [##'editToolbar', 'fileToolbar', 'helpToolbar', 'modifyToolbar', ##'molecularDispToolbar', 'selectToolbar', 'simToolbar', ## 'toolsToolbar', ##'viewToolbar', ] # all have been renamed in Qt4 # code copied from test_commands.py: # these imports are not needed in a minimal example like ExampleCommand1; # to make that clear, we put them down here instead of at the top of the file from graphics.drawing.CS_draw_primitives import drawline from utilities.constants import red, green ##from exprs.ExprsConstants import PIXELS from exprs.images import Image ##from exprs.Overlay import Overlay from exprs.instance_helpers import get_glpane_InstanceHolder from exprs.Rect import Rect # needed for Image size option and/or for testing from exprs.Boxed import Boxed from exprs.draggable import DraggablyBoxed from exprs.instance_helpers import InstanceMacro from exprs.attr_decl_macros import State from exprs.TextRect import TextRect#k class TextState(InstanceMacro):#e rename? text = State(str, "initial text", doc = "text")#k _value = TextRect(text) #k value #e need size?s pass # ============================================================================== _superclass_for_GM = GraphicsMode # print "_superclass = %r, _superclass_for_GM = %r" % (_superclass, _superclass_for_GM)#### class test_animation_mode_GM( _superclass_for_GM ): def leftDown(self, event): pass def leftDrag(self, event): pass def leftUp(self, event): pass def middleDrag(self, event): glpane = self.glpane ## q1 = Q(glpane.quat) _superclass_for_GM.middleDrag(self, event) self.command.modelstate += 1 ## q2 = Q(glpane.quat) novertigo(glpane) ## q3 = Q(glpane.quat) ## print "nv", q1, q2, q3 return def pre_repaint(self): """ This is called early enough in paintGL to have a chance (unlike Draw) to update the point of view. """ if self.isCurrentGraphicsMode() and self.command._in_loop: ## self.glpane.quat += Q(V(0,0,1), norm(V(0, 0.01, 0.99))) ## now = time.time() - self._loop_start_time now = self.command.simtime self.now = now # not used?? if cannon_oscillates(): self.command.brickpos = 2.5 + 0.7 * math.sin(now * 2 * pi) else: self.command.brickpos = 2.5 self.set_cov() return def set_cov(self):#060218... doesn't yet work very well. need to check if 6*self.glpane.scale is correct... # not that i know what would fail if not. return ###### try: space = self.command # since this method is in the GraphicsMode glpane = self.glpane cov = - glpane.pov # center of view, ie what camera is looking at guy_offset = space.guy.pos - cov # camera wants to rotate, but can't do this super-quickly, and it might have inertia, not sure... # kluge, test: set cov to some fraction of the distance newcov = + cov newcov += guy_offset * 0.2 # now figure out new pos of camera (maintains distance), then new angle... what is old pos of camera? eyeball = (glpane.quat).unrot(V(0, 0, 6 * glpane.scale)) - glpane.pov # code copied from selectMode; the 6 might be wrong # took out - from -glpane.quat since it looks wrong... this drastically improved it, still not perfect. # but it turned out that was wrong! There was some other bug (what was it? I forget). # And th - was needed. I prefer to put in unrot instead. _debug_oldeye = + eyeball desireddist = 6*glpane.scale nowdist = vlen(eyeball - newcov) #k not used? should it be? # now move it partway towards guy... what about elevation? should we track its shadow instead? # ignore for now and see what happens? or just use fixed ratio? desired_elev = 2 * glpane.scale ## guess desired_h_dist = math.sqrt( desireddist * desireddist - desired_elev * desired_elev) ## print "desireddist = %s, desired_elev = %s, desired_h_dist = %s" % (desireddist, desired_elev, desired_h_dist) # figure out coords for use in setting camera position from this dx, dy, dz = eyeball - newcov # x, z is a ratio to maintain eyedir = norm(V(dx, 0, dz)) * desired_h_dist # dir on ground only eyedir += desired_elev * V(0,1,0) # eyedir is ideal position rel to newcov, but eyeball should only move partway towards it... perfect this later (inertia?) eyeball += ((eyedir + newcov) - eyeball) * 0.2 # now we know where eyeball is... it should look towards newcov... so real cov is partly there realcov = eyeball + norm(newcov - eyeball) * desireddist ## print "desired-eyeball to desired-cov dist is", vlen(eyeball - realcov) # the quat is one which would look from eyeball to realcov, but keeping y in that vertical plane. # hmm... wish I could just use gluLookAt. # 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. # Standard axes: eyeball from cov is positive z... wantz = norm(eyeball - realcov) Y = V(0,1,0) wantx = norm(cross(Y, wantz)) wanty = cross(wantz, wantx) ## ## print "w", wantx, wanty, wantz realquat = - Q(wantx, wanty, wantz) # added '-' since should be correct... ## print "X_AXIS =? realquat.rot(wantx)", realquat.rot(wantx) ## print "Y_AXIS =? realquat.rot(wanty)", realquat.rot(wanty) ## print "Z_AXIS =? realquat.rot(wantz)", realquat.rot(wantz) glpane.pov = - realcov glpane.quat = realquat ###@@@ see if - helps... makes elev 0 and makes it unstable eventually... but should be correct! #e store attrs for debug drawing # DON'T ZAP THIS, it might be very useful for improving the camera follower algorithm ## # want to show (maybe elsewhere in diff coords): old eyeball, old guy, new guy, new place to lookat, ## # new eyeball, actual cov... and some lines between them, blobs at them, etc; and store this for later back/fwd browsing ## # (hmm, use ericm's little movie format? or smth similar, with back/fwd buttons for replay, or node per frame in MT, ## # visible when selected) ## oldeye = _debug_oldeye ## oldcov = cov ## newguy = + space.guy.pos ## guylookat = + newcov ## debug_stuff = [makeline(white, oldeye, oldcov), makeline(gray, oldcov, newguy), makedot(gray, guylookat), ## makeline(orange, oldeye, eyeball), makedot(green, eyeball), ## makedot(blue, realcov), ## makevecs(realcov, [wantx, wanty, wantz], [red, green, blue]), ## ] ## dn = DebugNode(debug_stuff, name = "debug%d" % env.redraw_counter) ## space.placenode(dn) #e maybe ought to put them in a group, one per loop? not sure, might be more inconvenient than useful. ## print "tried to set eyeball to be at", eyeball, "and cov at", realcov ## apparenteyeball = (glpane.quat).unrot(V(0, 0, 6*glpane.scale)) - glpane.pov ### will unrot fix it? yes! ## print "recomputed eyeball from formula is", apparenteyeball, "and also", realcov + glpane.out * desireddist ## # 2nd formula says we got it right. first formula must be wrong (also in earlier use above). ## # if we assume that glpane.eyeball() is nonsense (too early for gluUnProject??) ## # then the data makes sense. Could the selectMode formula source have been right all along? #####@@@@@ except: print_compact_traceback("math error: ") space.cmd_Stop() pass return def Draw_model(self): """ """ _superclass_for_GM.Draw_model(self) glpane = self.glpane glpane.assy.draw(glpane) def Draw_other(self): """ """ _superclass_for_GM.Draw_other(self) glpane = self.glpane ## # can we use smth lke mousepoints to print model coords of eyeball? ## print "glpane says eyeball is now at", glpane.eyeball(), "and cov at", - glpane.pov, " ." ####@@@@ origin = self.command.origin endpoint = origin + self.command.right * 10.0 drawline(white, origin, endpoint) self.command.cannon.draw() ## thing.draw(glpane, endpoint) self.command.guy.draw(glpane) ## draw_debug_quats(glpane) self.command._expr_instance.draw() #070813 - works, but resizer highlight doesn't work, didn't investigate why not ###BUG return def keyPressEvent(self, event): ## ascii = event.ascii() ### BUG: not available in Qt4 [070811] key = event.key() ## if ascii == ' ': # doesn't work ## self.cmd_Stop() if key == 32 or key == ord('S'): # note: 32 doesn't work, gets caught at some earlier stage and makes an orientation window ### note: ord('s') does not work... 83 is presumably the ascii code of 'S', not 's' self.command.cmd_Stop() ## if not self.what_has_our_focus: # can this be a single floor tile? or only the entire floor? # note that the focus is like the "character" in a game...camera should follow it through 3d space... # and it might have a dir, not just be an object... it might be a guy *near* the object. # so this var might be "what's near our guy" or "what's under our guy". # yeah, i'm sure it should be a guy (who might be over empty space, might move continuously). # otoh, this guy might have a finger poiinting at a thing, which is what gets our key events! # so we feed key to him, he feeds it out his feet or finger. # why not do "depmode" but with a guy walking around the mol? ... but how to draw the guy? not easy! # the keyfocus concept is that it's invisible, or a highlight state of the thing near it! or a simple line... elif key == _key_command or key == ord('F'): # F repeats, command doesn't self.command.cannon.fire() elif key == ord('G'): self.command.cannon.grow_cannon() # useful for testing PM update else: self.command.guy.keyPressEvent(event) ## wrong anyway : or thing.keyPressEvent(event) ## self.incrkluge = thing.keyPressEvent(event) self.redraw() def keyReleaseEvent(self, event): pass ## thing.keyReleaseEvent(event) def redraw(self): #e could be optimized if nothing but typing, and no DEL, occurred! self.command.modelstate += 1 ##bruce 050528 zapped this: self.glpane.paintGL() - do it this newer way now: self.glpane.gl_update() def update_cursor_for_no_MB(self): """ [part of GraphicsMode subclass API] """ self.o.setCursor(QCursor(Qt.ArrowCursor)) pass # end of class test_animation_mode_GM # ======== from exprs.ExprsMeta import ExprsMeta from exprs.StatePlace import StatePlace from exprs.IorE_guest_mixin import IorE_guest_mixin # REVIEW: can we use State_preMixin here? class test_animation_mode(_superclass, IorE_guest_mixin): # list of supers might need object if it doesn't have IorE_guest_mixin; see also __init__ __metaclass__ = ExprsMeta # this seems to cause no harm. # Will it let us define State in here (if we generalize the implem)?? # probably not just yet, but we'll try it and see what errors we get. transient_state = StatePlace('transient') # see if this makes State work... it's not enough -- # it is a formula with a compute method, and Exprs.py:273 asserts self._e_is_instance before # proceeding with that. I predict self would need a lot of IorE to work here... _e_is_instance = True # I predict this just gets to another exception... if it's even correct -- # it might be wrong to say it in the class itself!!! anyway it didn't complain about that # but i was right, it then asked for _i_env_ipath_for_formula_at_index... # so there is a set of things we need, to be able to support formulae like that one for transient_state, # and i bet IorE is mostly that set of things, but also with support for things we don't need or even want, # like child instances, call == customize, etc. # # So there are different ways to go: ### DECIDE: # - revise State to work without transient_state [probably desirable in the long run, anyway] # - make a more standalone way of defining transient_state # - split IorE into the part we want here and the rest (the part we want here might be a post-mixin) # - revise IorE to be safe to inherit here (as a post-mixin I guess), ie make it ask us what __call__ should do. # # Let's see what happens if we just inherit IorE. maybe it already works due to _e_is_instance, # and if not, maybe I can override __call__ or remove __call__ alone from what I inherit. # class constants needed by mode API backgroundColor = 103/256.0, 124/256.0, 53/256.0 commandName = 'test_animation_mode' # must be same as module basename, for 'custom mode' to work featurename = "Prototype: Example Animation Mode" from utilities.constants import CL_ENVIRONMENT_PROVIDING command_level = CL_ENVIRONMENT_PROVIDING # other class constants PM_class = test_animation_mode_PM GraphicsMode_class = test_animation_mode_GM # tracked state (specially defined instance variables) # (none yet, but we want to put _in_loop here, at least) # can we say: _in_loop = State(boolean, False) ? # Or would that overload State too much, or use a too-generic word? ###REVIEW ## _in_loop = False ###TODO: unset this when we're suspended due to some temp commands -- but not all?? _in_loop = State(bool, False) cannonWidth = State(float, 2.0) ## add , _e_debug = True to see debug prints about some accesses to this state # initial values of instance variables now = 0.0 #070813 [still used? maybe simtime has replaced it?] brickpos = 2.5 # in _superclass anyMode: propMgr = None _please_exit_loop = False _loop_start_time = 0 simtime = 0.0 # this is a constant between loops, and grows with real time during loops. only changed in cmd_Start. never reset. def __init__(self, commandSequencer): """ create an expr instance, to draw in addition to the model """ # code copied from test_commands.py super(test_animation_mode, self).__init__(commandSequencer) # that only calls some mode's init method, not IorE.__init__, # so (for now) call that separately glpane = commandSequencer.assy.glpane IorE_guest_mixin.__init__(self, glpane) if 0: # expr from test_commands - works except for resizer highlighting ## expr1 = Rect(4, 1, green) expr1 = TextState() expr2 = DraggablyBoxed(expr1, resizable = True) ###BUG: resizing is projecting mouseray in the wrong way, when plane is tilted! # I vaguely recall that the Boxed resizable option was only coded for use in 2D widgets, # whereas some other constrained drag code is correct for 3D but not yet directly usable in Boxed. # So this is just an example interactive expr, not the best way to do resizing in 3D. (Though it could be fixed.) expr = expr2 if 0: expr = Rect() # works if 1: expr = Image("/Users/bruce/Desktop/IMG_0560 clouds g5 2.png", size = Rect(), two_sided = True) # note: this code is similar to _expr_instance_for_imagename in confirmation_corner.py ih = get_glpane_InstanceHolder(glpane) index = (id(self),) # WARNING: needs to be unique, we're sharing this InstanceHolder with everything else in NE1 self._expr_instance = ih.Instance( expr, index, skip_expr_compare = True) ## in Draw: add self._expr_instance.draw() if TESTING_KLUGES: self._clear_command_state() ###### FOR TESTING print "_clear_command_state in init, testing kluge"#### return def _clear_command_state(self): """ [private, not part of command API] """ self.cmd_Stop() if TESTING_KLUGES: print "KLUGE FOR TESTING: set cannonWidth in cmd_Stop" self.cannonWidth = 2.0 ########### DOES IT FIX THE BUG? THEN ZAP. return # == def command_will_exit(self): self._clear_command_state() _superclass.command_will_exit(self) return def command_enter_PM(self): if not self.propMgr: self.propMgr = self.PM_class(self) # [080910 change] return def _command_enter_effects(self): print print "entering test_animation_mode again", time.asctime() ## self.assy = self.w.assy # [AttributeError: can't set attribute -- property?] hacktrack(self.glpane) hack_standard_repaint_0(self.glpane, self.graphicsMode.pre_repaint) # KLUGE -- this ought to be part of an Enter_GraphicsMode method... # there was something like that in one of those Pan/Rotate/Zoom classes too... # need to find those and decide when to call a method like that. self.glpane.pov = V(0, 0, 0) self.glpane.quat = Q(1,0,0,0) + Q(V(1,0,0),10.0 * pi/180) print "self.glpane.scale =", self.glpane.scale # 10 -- or 10.0? self.glpane.scale = 20.0 #### 070813 # note: using 20 (int not float) may have caused AssertionError: ## in GLPane.py 3473 in typecheckViewArgs ## assert isinstance(s2, float) print "self.glpane.scale changed to", self.glpane.scale self.right = V(1,0,0) ## self.glpane.right self.up = V(0,1,0) self.left = - self.right self.down = - self.up self.away = V(0,0,-1) self.towards = - self.away self.origin = - self.glpane.pov ###k replace with V(0,0,0) self.guy = guy(self) self.cannon = cannon(self) ##self.glbufstates = [0, 0] # 0 = unknown, number = last drawn model state number self.modelstate = 1 # set perspective view -- no need, just do it in user prefs return def command_entered(self): _superclass.command_entered(self) self._command_enter_effects() return def command_enter_misc_actions(self): #bruce 080909 guess self.hidethese = hidethese = [] for tbname in annoyers: try: tb = getattr(self.w, tbname) if tb.isVisible(): # someone might make one not visible by default tb.hide() hidethese.append(tb) # only if hiding it was needed and claims it worked except: print_compact_traceback("hmm %s: " % tbname) # someone might rename one of them return def command_exit_misc_actions(self): #bruce 080909 guess for tb in self.hidethese: tb.show() return # not used now, but keep (was used to append DebugNodes): ## def placenode(self, node): ## "place newly made node somewhere in the MT" ## # modified from Part.place_new_jig ## part = self.assy.part ## part.ensure_toplevel_group() ## part.topnode.addchild(node) # order? later ones come below earlier ones, which is good. ## self.w.mt.mt_update() ## return def appendnew(self, new): ##FIX: stores object list (really a dict) in self.guy stuff = self.guy.stuff ## stuff.append(new) # it's a list stuff[id(new)] = new # it's a dict ## print "appendnew: %d things" % len(stuff) # test culling of old things -- works return def rotleft(self, amount): """ [#doc is in caller] """ # from Q doc: Q(V(x,y,z), theta) is what you probably want. #060218 bugfix: left -> down self.glpane.quat += Q(self.down, amount * 2 * pi) # does something, but not yet what i want. need to transform to my model...###@@@ ## self.redraw() - do in caller def makeMenus(self): _superclass.makeMenus(self) self.Menu_spec = [ ('loop', self.cmd_Start), ] return def cmd_Start(self): # renamed from myloop # WARNING: this does not return until the loop stops; it does recursive event processing # (including going into temporary subcommand modes, or even going entirely into other modes) # while it runs. If we wish some subcommands to suspect the simtime updates and redraws this # does, they should somehow set a flag here which affects this loop, since they have no # direct way to exit this loop immediately. if SILLY_TEST: self.cannonWidth = 5.0 - self.cannonWidth # test whether pm gets updated -- it doesn't (bug) if self._in_loop: print "cmd_Start: already in loop, ignoring" #e future: increase the time remaining return print "cmd_Start: starting loop" glpane = self.glpane starttime = self._loop_start_time = time.time() start_simtime = self.simtime safety_timeout = 600.0 # 10 minutes -- not really needed as long as 's' works to stop the loop self._please_exit_loop = False self._in_loop = True # if the menu stays up all this time, we'll have to instead set a flag to make this happen later, or so... # anyway, it doesn't. min_frame_time = 0.1 ### 0.02 while not self._please_exit_loop and time.time() < starttime + safety_timeout: ## glpane.quat += Q(glpane.up, glpane.out) # works self.simtime = start_simtime + (time.time() - starttime) glpane.gl_update_duration() # This processes events (including keypresses etc, which mode should record), # and then does a redraw (which should update the state vars first), # times the redraw (and the other event processing) in glpane._repaint_start_time, glpane._repaint_end_time, # and sets glpane._repaint_duration = max(MIN_REPAINT_TIME, duration), where MIN_REPAINT_TIME = 0.01. # # If any of those events exit this mode, that will happen right away, but our _clear_command_state method # will run cmd_Stop so that this loop will exit ASAP. To make this exit faster, # we also test _please_exit_loop just below. (REVIEW: do we need to set such a flag to be tested # inside gl_update_duration itself??) if not self._please_exit_loop: #### TODO: also test whether app is exiting, in this and every other internal event loop duration = glpane._repaint_end_time - glpane._repaint_start_time # this is actual duration of state-update-calcs and redraw. if too fast, slow down! if duration < min_frame_time: time.sleep(min_frame_time - duration) continue ## self.simtime = start_simtime + (time.time() - starttime) -- no, might cause glitch on next redraw self._in_loop = False return def cmd_Stop(self): if self._in_loop: print "cmd_Stop: exiting loop" self._please_exit_loop = True else: print "cmd_Stop: not in loop, ignoring" #e show this msg in PM somewhere? return pass # end of class test_animation_mode # DebugNode # end
NanoCAD-master
cad/src/exprs/scratch/test_animation_mode.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ Command_scratch_1.py $Id$ [061212 is the date of some small mods to make this parse -- probably it was mostly written then or a few days before, within demo_drag.py] 070105 moved the pseudocode for Command & DragCommand class etc from demo_drag.py into this new file Command_scratch_1.py -- see this file for ideas about Command, DragCommand, _PERMIT_SETS_INSIDE_, DragANode, ClickDragCommand, MakeANode. (But some comments in demo_drag.py still discuss Command and MakeANode in important ways. ####e) """ from basic import * from basic import _self, _this, _my Alias = mousepos = Vertex = Stub class Command(InstanceMacro): #k super is prob wrong """#doc a subclass can make exprs that are specific available commands: - when they get args they know their param-formulas relative to event sources they're bound to - when instantiated, they are a potential real command, all decisions made, offerable (eg in a context menu) - some further protocol (not yet designed, but controlled by the event source) decides to start doing them, binding them to a real event (perhaps a long-running one like drag, or an even longer one if they are wizard-like commands that take over a window for awhile, with lots of mode like variables, lots of controls, etc -- in that case the "event" is just "all user events to this subwindow while this wizard is active" or "all user events controlled by this wizard" -- they're like a mode, in the old NE1) and letting them control what's shown (graphics area, in their own optional separate panes, etc), and what is left (as their side effect, changed or created stuff) at the end. """ pass class DragCommand(Command): """Commands that are bound to (give behavior/action to) a single drag-event (starting when the user-event-processing-system decides it's a real drag (not just a click), ending when the mouse goes up and the resulting intended effect (if any) can be done by this command). """ pass _PERMIT_SETS_INSIDE_ = attrholder # temporary kluge class DragANode(DragCommand): """this runs on a new Vertex made by the click which started this drag (assumed made before this drag starts) [whether we can or should really separate click and drag actions like that, in this example, is not clear ###k] [but if we can, then this *same* command can also drag an *old* node, which would be nice, if we rename it. #e] [I think we can sep them, by noticing that the node-maker on click can then decide what to do with "the rest of its drag". #k In fact, I bet it will continue to exist as an ongoing command, delegating its remaining user-event stream to the subcommand it selects for handling that "rest". #k] """ # the new Vertex is an Arg, I guess. How does caller know its name? or is it always arg1? node = Arg(Vertex) # it has a position which we will drag. # This is really its posn in a specific space... for now assume it (or our view of it, anyway) # owns that pos and knows that space. pos = Alias( node.pos) # Alias is so we can set or change pos as a way of changing node.pos [#nim, & not even fully decided on] # [later 070111: note that in real life, pos should be a *translated* form of node.pos, but still be settable as an lval. # in general we'll want to transform the settable for drag parts of node, to those of a drag-target with a uniform # interface, then let the mouse drag events modify the drag-target in a standard way. See '070111 settable coordinate vars' # [not in cvs] for related discussion.] # Q: if system decides it's a drag only after it moves a little bit, does the object then jump, or start smoothly, # as it starts to move? # A: what does NE1 do? what do I prefer? should it be a user pref? If so, can this code not even know about it somehow? # What would make this code simplest? # Does this code need a dragpoint on the new object (perhaps with a depth)? Does it need a drag-delta instead? (At what depth?) # Can this code work w/o change if someone hooks up a 3d drag device? (Meaning, it accepts a 3d drag path, for now always planar.) # ok, now it's time to specify our effect, which is basically, set node pos to mouse pos. How simple can it be, in that case? ## pos = mousepos # won't work, since erases above other set of pos in the class namespace. node.pos = mousepos # won't work -- syntax error [predicted] .. wait, turns out it's not one!!! # But what does it do? It ought to be doing setattr on an expr returned by Arg(Vertex) -- which does what? # Oh, just sets the attr in there, silently! Can we capture it? If the attrname is arbitrary (seems likely, not certain), # then only with expensive code (on all symbolic exprs?) to notice all sets of attrs not starting with _e_ etc... # (hmm, maybe we don't need to notice them except later? that is, it's just a formula sitting inside the value of node, # created by Arg just for us after all, which we can notice from dir(node) since the attrname doesn't start _e_?? # As experiment just try printing them all. But first keep deciding if we want this syntax, since it's kind of weird. # E.g. it implies we do this continuously, *all the time* that this instance exists [wrong, see below] -- # which might be what we want... hmm. # It also naturally only lets us assign a specific thing as one formula... at least at the whole-class level. Hmm. # actually it doesn't have to mean we do the action continuously. The formulas could get grabbed and stored, # for whole class or per-symbol or per-symbol.attr.attr (or all of those), and then done by a specific method call, # either once at the end or continuosly, and in various "modes of doing them" like accept or offer or reject/cancel... # this would let us set up the side effects, then do them tentatively during the command, do them fully after it, # or reject/cancel them in an automatic way using a single call (doing right thing re history, undo, etc). # If the command-end method didn't exist, the standard super one could just accept the changes # (and same with setting up to tentatively accept them during the command, showing that in std ways). # # BTW the way tentativeness can be shown is to store metainfo with the attr-set side effects # (eg obj._tentativeness_of_attr = True # (paraphrased)), then for display styles to notice that and let it affect them, # maybe noticing it automatically for all attrs they use -- i.e. "or" some caveat-flags (incl warnings, uncertainties...) # as you usage-track so you'll know what caveats apply to some value you compute. (Or actually use them, in case they change. # I guess only use them for a parallel computation of your own caveats.) print_node_mod_demo = False # 061212 # print_node_mod_demo = True # 070130 - works, disabling again for now if print_node_mod_demo: print "our node symexpr has:",node._e_dir_added() ## for attr in dir(node): ## if attr.startswith('_e_') or attr.startswith('__'): ## pass ## else: ## print attr, # _init_e_serno_ [fixed?], pos ## continue ## print node.pos.subattr = 1 node.pos2 = _PERMIT_SETS_INSIDE_() node.pos2.subattr2 = 1 if print_node_mod_demo: print "now it has:",node._e_dir_added() ###BUG [before i had _PERMIT_SETS_INSIDE_() above] - where is pos2? #print "dir is",dir(node) # it's not in here either! OH, I never made it, I only asked for it (for val of node.pos2) # and I got a getattr_Expr of node and pos2! Can that be fixed? As it is I can't even see that getattr_Expr, # it was discarded. Can/should I capture the setattr of attr in symbolic getattr_Expr? Guess: probably I can. ###k # (Alternatively I could capture the making of the getattr_Expr on a symbolic expr, # and do something equiv to the set to _PERMIT_SETS_INSIDE_() above -- this might make basic sense... # but it would only work if I didn't return the getattr_Expr itself, but whatever object I stored for it! # But wait, why not just store that same getattr_Expr, so it's memoized (might save mem or help in other ways)? Hmm.. # note that the exact cond for doing this being ok is not _e_is_symbolic but something inherited from arg1 of some OpExprs... # ###k # # [digr: it might even have other uses, like a convenient record of how we use each symbol, # which can be checked against its type later on, # or checked against specific values passed in, or used in other ways....]) # # [Then I could also warn if i thought it might be discarded -- if the set fails to know it "tells something it was done".] ####e First decide if i want to. My tentative guess is yes, but the idea is too new to be sure. # But I could test the idea without that, just by requiring kluge workaround of a set of node.pos2 to a special value; try above. node.blorg = node.blorg + 1 # hopefully this will set it to a OpExpr of a getattr_Expr, equiv to the expr node.blorg + 1 if print_node_mod_demo: print "and now it has:",node._e_dir_added() print "node.blorg is now",node.blorg # it does! #### pass # end of class DragANode ClickDragCommand = DragCommand # STUB #e the idea is, ClickDragCommand includes initial click, whereas DragCommand only starts when real drag is recognized # (later: we might decide to drop the type-distinction between ClickDragCommand and DragCommand, # for economy in set of concepts, trading it off for making the common DragCommand more complex or ambiguous # since it may or may not include the initial click -- but it has to be given enough info as if it did.) class MakeANode(ClickDragCommand): #k super? #e will be bound to empty space, or guide surfaces/objects you can make nodes on # (but might want them as arg, to attach to -- hmm, not only the surface, but the space! # same arg? -- what it's a feature of or on? or, feature of and feature on might both be space, or might be space and obj?? # related: what its saved pos is relative to. ####e decide that...) """ """ # hmm, they clicked, at some pos, and we know a kind of node to make... let's make it newnodepos = V_expr(0,0,0) #stub newnodepos = _self.pos # what other kind of pos can we have? well, we could have the continuously updated mousepos... newnodepos = _self.clickpos #e rename; note we have dragstart_posn or so in other files newnode = Vertex(newnodepos, 'some params') ###PROBLEM: is that just an Expr (pure expr, not instance, not more symbolic than IorE) assigned to an attr? # is it symbolic enough to let us do newnode.pos = whatever later if we want? # see cmt below about how to list it as "_what_we_make". # (typically some params would be formulas) # - do those params say where in space, relative to mousepos? yes, they must, since it can vary for other commands, # eg if it's built on top of something that exists (see above comment about attaching to an obj, too). # now we want to say: # - where to put it -- i mean, what collection to assign it to # - now permit it to be dragged (or in other kinds of commands, permit some aspect of it to be dragged) # - maybe with some params of the node -- or of this command (temporary params not in the node itself) -- # being controlled during the drag # by letting this event be taken over (after its side effects, maybe before its own wrapups) by another command # but binding that other command to the event that a real drag starts -- HOW? ###e ## _value_if_a_real_drag_starts___is_made_from_this_expr = DragANode # ___is_made_from_this_expr should be implicit #e DragANode with what args? self? self.newnode? might need self if it needs to change the look based on self... # otoh it has access to the drag event, so maybe that would be rare... # except that self is probably controlling "tentativity". hmm.... ###k #e revise to look like a bunch of subevents bound to actions/behaviors (commands), when we know what that looks like # tho this special case might be common enough to have its own name, shorter than this one, e.g. _continue_drag _value_if_a_real_drag_starts = DragANode( newnode) # defect: this requires us to define DragANode first in the file; if a problem, replace it with _forward.DragANode or so if 0: # I disabled this 061212 to avoid the warning which in real life would be suppressed for this special case: ## warning: formula <Vertex#8661(a)> already in replacements -- error?? its rhs is ## <getattr_Expr#8669: (S._self, <constant_Expr#8668: '_what_we_make'>)>; new rhs would be for attr 'newnode' _what_we_make = newnode # maybe we'll just name newnode so this is obvious... # btw this can be an exception to not allowing two attrs = one expr, since _what_we_make is a special name... so ignore this: ## warning: formula <Widget2D#12737(a)> already in replacements -- error?? ## its rhs is <getattr_Expr#12741: (S._self, <constant_Expr#12740: '_what_we_make'>)>; ## new rhs would be for attr 'newnode' # should we make its specialness obvious (for it and _value and _continue_drag and all other special names)?? # I mean by a common prefix or so. BTW are they all different kinds of "values" or "results"? Could use _V_ or _v_ or _r_... # ####e decide # an alternate way to say what we make, and to say where: some sort of side effect formula... maybe worse re POLS. if 0: _something.make(newnode) _something.add(newnode) _self.something.make(newnode) make(newnode) # etc pass # end of class MakeANode
NanoCAD-master
cad/src/exprs/scratch/Command_scratch_1.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ rules.py $Id$ This is really a scratch/notes file, though it has some code near the end that might become real. """ # Coming out of this comment just added to demo_drag.py: # Summary of this and Vertex_new -- make use_VertexView work -- # [long comment added 070111; devel on this code has been inactive for a few days] # # it's an example of dynamically mapping selobj thru toolstate to get looks & behavior, # so the model object itself can be split out and needs no graphics/interaction code of its own. # My general sense in hindsight is that it's too low-level -- I need to figure out how all this could/should look as toplevel exprs. # # See a new file rules.py for more on that. # Basic idea is that we're modifying the env by incrementally adding a rule for how to view some objs. # The rule knows what objs it handles and delegates the rest. It has to be applied in a localmost way -- # effectively it filters the entire env. We can implem it that way now and optim it later -- but the syntax should # be how we think of it, which is "a rule that says what it applies to (at least roughly, ie with a typename)". # The typename might as well be the Python class, even if we compare classname so as to not worry about reload. # # In general the env has a big mapping from model objs to their views... which is added to by many sources. # But how is that mapping *used*, and what are semantics of an object which can be used to add to it? # The obj is an expr, the outer layers can be a typefilter, # that can be used two ways (dict key for optim, or predicate for test each time), # so it's sort of logical or mathematical... it's a pattern operator; another one is a general condition (evals a pred formula). # Another one not only evals, but makes some localvar bindings, probably in the form of an object with attrs (formulas) or a dict. # # So the outermost operation here is "modify env.whatever by preadding this rule to it"; # rule semantics are "match: succeed with data or fail", and for optim, maybe "match to some kinds of parts inside this thing", # "get compiled in this way", etc. # # What we modify in env is "how to view model objs". is that just "how to view things?" The model obj type might be enough... # we can ignore issues raised by "how to view graphical objs" for now. # # So the env has some general viewer mapping which gets applied to everything before we draw/lbox it... as memoized glue code... # and which knows how to extract a suitable memo index (dict key) from the obj it looks at, guess maybe based on what the patterns # in the rules ask about. Trivial version - rule asks about outer type, so mapping extracts that to classify, # but rule rhs then applies to entire obj, so mapping extracts id of obj (really ipath, i guess) as index, # whereas if rhs only cared about obj.attr1, # maybe mapping would only extract ipath of obj.attr1 (not sure; optim, so can ignore at first). # # So we also (finally) need these mapping objects, which extract their own indexkeys, as if obj itself was the *given* index. # And the mapping object is just called with a method with the passed input obj as arg -- or applied to it as if it's a func or dict. # I guess __call__ is most flexible (eg it works with python map operation, with compose, etc). # This fits with env.viewer_for_object as a func which takes obj to its view (or a default view for an unknown obj, if nec). # I was thinking "it's identity for all but model objs", but really, it uses default glue for all but viewable objs! # Then for *those*, it's id for non-model objs. So objs to it are unknown (default glue), or viewable, further divided # into graphical (identity unless we're using weird rules not needed for now), or model (look up view in the rules). # But as said, the rules can tell what's what, so it's all equiv to: try the model->view rules, else notice it's already viewable, # else use default glue for foreign objs (which need a minimal interface like asking for their py class and py id, and/or repr). # # what about 3d vs MT view? these are just a very high classification of a display style, which also has lower classifications... right? # but they can just as well be a difference in the rules themselves in different local envs... otoh we'd always like access to either one # by name. hmm. # # Back to "the env has some general viewer mapping" -- given the old and new one of those, with what op do we combine them? # just a "compose rules in series" op. But what's the __call__ interface -- how does it say "i don't apply" vs "i'm identity"? # Maybe with an exception when it fails? Note the similarity to ParseRules, and indeed, they're very related. # (They might get even more related if we use this to bind actions to event streams, and need different rules # to bind to different portions of it and leave the rest for more.) def rules_in_series(r1, r2): # revise to a class, since otherwise it'll need that x=x in def arglist kluge, and return res; anyway it's really an expr def res(thing, r1=r1, r2=r2): try: return r1(thing) except RuleFailedException: # note this return r2(thing) pass return res class RuleOp(...): #e __init__ from Expr or similar superclass I guess #e something to set .args? or is a rule one of those pure exprs which is already enough of an instance? # sometimes no -- the instance can memoize! def __call__(self, arg, *args, **kws): #e do something uniform about more args & kws. so now there is only one arg res = self.apply(arg) #e might raise RuleFailedException (or other ones on errors) return res pass class rules_in_series(RuleOp): #e doc; this form has only one more line, which is not a problem compared to its benefits def apply(self, thing): r1, r2 = self.args try: return r1(thing) except RuleFailedException: return r2(thing) pass pass # Now a mapping is a just a big kind of rule-like thing... but it has all that index-finding and memoizing intelligence, # all the stuff that old GlueCodeMemoizer had... don't code it until I decide how it should work. # Note a lot of them will be modified views of a big main one in the env. # Note someday it'll do compiling and other fancy stuff too... and something else I just forgot I wanted to say... oh yeah, weak index-part handling # maybe type coercion too... and easy formation of incrly modified versions... # # ... what about some example rules? # can an expr that needs one arg of a certain type, count as a rule? # calling it means applying it... as expr or instance, maybe doesn't matter(??)... # if the types don't match, it might raise an exception -- why not? # so that might actually work. Vertex # a type of model obj class VertexViewer(...): vertex = Arg(Vertex) # requires arg to be a Vertex object... hmm, do we say it has to be an Instance of one, already?? # that means it has a pos, rel to whatever obj the vertex type is rel to... but how do we capture that idea # that Vertex is really a parametrized type? well, put that off for now since it's not one in demo_drag.py (safe??) delegate = Translate( Rect(0.2, color = vertex.color), vertex.pos ) # or so pass # my worries about the above include: # - is the exception for argtype being wrong really the same (or a subclass) of the one for RuleFailedException? # in particular, is it "not an error" (unless it was your last rule in a series)? # - is RuleFailedException a dangerous concept, since if it gets out of the inside of a rule (eg while running its body), # it might seem to apply to the rule itself? # - how do we capture the idea that Vertex is really a parametrized type? # do we cheat and say "a vertex also has a host object"? (which determines the type of pos it has, including its coord sys) # actually that might be a good idea (ie not cheating) -- since we can select vertices of different hosts at one time! # So letting host (and pos type) just be another attr of each vertex (with optims someday when they're constant) does make sense. # let's make another example rule where we explicitly list the argtype, avoiding some of the worries above. Rule(Vertex, VertexViewer) # arg1 is a type, arg2 is a func from arg1 (of that type) to the result (error if it fails) # worries about *that*: # - does it use up the word Rule for a special case of argstyle which might not even be the most common one? # - it seems to *prove* that either: # - argtype failure in VertexViewer should not raise RuleFailedException, or, # - if it does, Rule should not pass it on unchanged. (which is not hard, i guess, just slightly non-POLS.) # Here is more evidence that argtype mismatch is not RuleFailedException -- it can happen arbitrary deep inside something, # and percolate up w/o being transformed. # # One way out is to wrap VertexViewer with something to turn it into a rule, which turns argtype mismatch into RuleFailedException -- # but this is only ok if it can verify that the arg whose type did not match was an arg of its direct argument VertexViewer. # But it could check that (if we defined the data of the argtype exception to include the object whose arg had the wrong type, # and if we ignore the possibility of cheating when constructing one to raise)... so we could define such a wrapper -- # and that wrapper could even be autoapplied to turn an expr needing one arg into a rule, in argslots needing a rule. # === # Actually I think returning None is better than raising an exception, for a rule about what things should look like. # Then you serially combine rules with Or, and exceptions are errors, so catching them is less often needed. # But can None be the "no answer result" for *all* rules (regardless of purpose)? Surely not. So we need a special object, # which will be boolean false, so in cases where all correct answers are true, we can still use "or" to combine them. # But then the general rule utilities can't use "or". So another possibility is that they return None or a true thing, # and the true thing contains the answer, but is not only the answer. E.g. they return (ok, res) or (bindings, res) or wrapped(res). # On failure do they return (False, None) or just None or a weird object that acts like both? Failure is common -- just None. class rules_in_series(RuleOp): #e doc; all correct rule results must be true; the convention for encoding arbitrary objects is up to the rule-user; # in the present app we're using them to encode exprs or exprheads or Instances, no all legit values are true def apply(self, thing): r1, r2 = self.args return r1(thing) or r2(thing) pass # that's simpler! # (maybe "in parallel" is more accurate -- no obj goes thru more than one of the rules. Just call it a "rule list" for now.) # (it has some relation to or_Expr, but it can't be the same thing unless our instantiation env can supply the "thing"... # i.e. be different than usual in semantics. Save that idea for later.) # when the time comes for optim for lots of rules, rules can have methods to add themselves to classifier trees # which have questions and answer-keyed dicts as nodes. # what we need for use_VertexView is just a simple way to say "in this env, if obj.type is X, then view obj using Y". # And we want to use things like that to construct mappings for other purposes too. # # So we want a Rule object API (for rules and rulesets), ops like rule lists, a way to make a Mapping from a Rule, # and a standard mapping in the env for model_object_viewers, and a standard way to locally incrementally pre-extend its rulelist. WithRule(expr, rule) # this is fine if there is only one ruleset we need to extend, and if "in the dynenv" can be implicit. WithEnv(expr, rule) # no, sounds like it's the whole env. WithEnvRule(expr, rule) # explicit env, still assumes one ruleset in env. The rule would have to apply to all exprs for all purposes... WithViewRule(expr, rule) # says the rule is for how to view something... implies it's in dynenv, since all viewing rules are. LocalEnv(expr, view_rule = rule) # .... # I think I don't want to force this mod into a general form for other kinds of mods, now -- the relation to the general form # might change, and the namespace of different kinds doesn't have enough names in it to pick good names for specific ones. UseViewRule # I guess I like With better than Use -- so far all forms of "with" mean "with local mods, not destructive to parent". WithViewRule( expr, (Vertex, VertexView)) # 2-tuple (type, func) can be interpreted as Rule if you try... seems good. # But if we adopt that, and also for lists of rules, we better decide whether it has to be done to every value at runtime, # when the arg is a formula. It also makes the code harder to read, perhaps... WithViewRule( expr, Rule(Vertex, VertexView)) # use this form # this form of Rule(type, func) can be general if we say that type can be fancy, as long as it returns False or (True, *args) # with *args passed as extra args to func! Not sure if that way of fancification makes sense... ok for now, # since there'll be few enough of these (for some time from now) that changing them all in name or syntax would be ok. # BTW can a func, or an exprhead needing one arg, be interchangeable here? I hope so and guess so, but don't know for sure, # and I doubt it's already implemented. It might require instantiating such an expr without its arg, getting a func # that wants an arg instance! But then I'd worry about whether erroneous uses of that feature could be detected. # Maybe they could by attr access too early... or maybe the argslot would have to specifically permit this kind of instantiation. class Rule(FunctionExpr): # FunctionExpr means it instantiates into a function, and has the __call__ interface to self.apply #e or we might decide that any sort of expr can define apply, with that meaning on its instances # (if so should we rename apply to _e_apply or _i_apply or so? probably _i_apply.) """Rule(type, func) is an Expr for a rule which matches any Instance which has the given type, and wraps it with func. Once instantiated, it can be applied to an Instance (thing) by being called on it (Python __call__), returning None if it doesn't match, or func(thing) if it does. (That result is presumed to be an Instance, and is required to be true, though perhaps neither condition is checked.) Note that it is meant for use on Instances, and is hard to use on arbitrary Python values if any legal values can be false. """ type = Arg(Type) func = Arg(Function) def apply(self, thing): "return None if it doesn't match, or func(thing) if it does" type = self.type func = self.func ## if type.matches(thing): ####k??? this assumes canon_type or other coercion to Type tames type and gives it this method if isa(type)(thing): # this (isa(), vs. x.matches()) is easier to support since it can work for python types too res = func(thing) assert res, "%r requires %r(%r) == %r to not be false" % (self, func, thing, res) return res return None pass class RuleList(...): args = ArgList(Rule) # assumes Rule is also usable as a type -- though above Rule class has no provision for that ###IMPLEM ArgList -- it makes args a list of instances, doing instantiation and type coercion on each one (lazy per elt??) # (note: this semantics is precisely the same as a few other files desiring ArgList, so it must be an ok design!) ###e do we want it to let args also be python lists of rules (or list_Exprs thast make them)? probably yes -- someday. # (just as in Column) (all it needs is a more flexible typecheck and a system like in Column to map the args...) def apply(self, thing): for rule in self.args: res = rule(thing) if res: return res assert res is None, "Rule %r applied to %r was %r -- should be None or something true" % (rule, thing, res) #e maybe weaken that to a warning, so we can treat it as None and continue? also file it centrally as a RuleOp method # (assuming this can be a subclass of RuleOp (#e rename?), which I guess is itself a subclass of FunctionExpr) continue return None pass class WithViewRule( ...) # it's not a good sign that i keep deferring the superclass -- it probably means InstanceOrExpr spelling is too long """#doc; example: WithViewRule( expr, Rule(Vertex, VertexView)) """ #e modify env locally... turn into a special form of WithEnvMods. See other file for stub of that. pass # ... the above needs ArgList, and might need working type coercion too. # let's implement some iterators (like rect with corners) first, and both of those internal features. # Just make another macro like Arg, make it get told its starting pos like Arg does, # and let the type coercion in those macros *not* work by using type in direct call (like it may do now, not sure). # [070112 morn] # == # older stuff than the above, moved here from demo_drag.py 070123, and then with a new docstring class WithViewerFunc(DelegatingInstanceOrExpr):#070105 stub experiment for use with use_VertexView option ### NOT YET USED non-stubbily """[docstring added much later, 070123 -- not sure it matches original intent, but who cares, the code was a stub] WithViewerFunc(world, viewerfunc) means show world using viewerfunc, which converts some kinds of objects into new ones which are more directly viewable (usually by wrapping them with glue code). (#k Is it an incremental addition in front of (and in series with, ie able to delegate to) the existing env.viewerfunc? I think so.) Note that viewerfunc is an example of a Rule or RuleSet or RuleOp (see rules.py) and is often a "memoizing mapping". (More precisely, a Rule expr is typically instantiated into a memoizing mapping which uses it, by code in its highest abstract superclass, perhaps RuleOp or MemoizingMapping.) Conventions about a viewerfunc: - When applied to a collection, it typically does nothing (as with any object it doesn't recognize), but the default collection-viewer will usually use the full env's viewerfunc to view its elements, so viewerfunc will end up getting applied to the collection's elements. - When applied to things it doesn't recognize, it leaves them alone. (So it is *not* the kind of rule that returns None then. Hmm.) - When it does recognize something, it should turn it into something more viewable, but perhaps still high-level ie requiring other viewerfuncs to view it. - Typically it turns some model objs into graphical objs, and leaves graphical objs alone, but the same scheme might be used to turn HL graphicals into LL ones, applying styles and prefs. """ world = Arg(Anything) viewerfunc = Arg(Anything) ### NOT YET USED in this stub delegate = _self.world # stub #e what we actually want is to supply a different env to delegate == arg1, which contains a change from parent env, # which depends on viewerfunc. We want a standard way to ask env for viewers, and the change should override that way. # But we don't yet have a good way to tell this macro to override env for some arg. # We probably have some way to do that by overriding some method to find the env to use for an arg... # but we didn't, so i made one. def env_for_arg(self, index): # 070105 experiment -- for now, it only exists so we can override it in some subclasses env = self.env_for_args #e or could use super of this method [better #e] if index == 0: #KLUGE that we know index for that arg (world, delegate, arg1) env = env.with_lexmods({}) #### something to use viewerfunc return env pass # let's try a more primitive, more general version: class WithEnvMods(DelegatingInstanceOrExpr):#070105 stub experiment -- refile into instance_helpers.py if accepted ### NOT YET USED """WithEnvMods(something, var1 = val1, var2 = val2) delegates to something, but with something instantiated in a modified dynamic environment compared to self, in which env.var1 is defined by the formula val1, etc, with the formulae interpreted as usual in the lexical environment of self (e.g. they can directly contain Symbol objects which have bindings in env, or they can reference any symbol binding in env using _env.symbolname ###IMPLEM or maybe other notations not yet defined such as _the(classname) ###MAYBE IMPLEM). """ # The goal is to just say things like WithEnvMods(model, viewer_for_object = bla) # in order to change env.viewer_for_object, with bla able to refer to the old one by _env.viewer_for_object, I guess. # This assumes env.viewer_for_object is by convention a function used by ModelObjects to get their views. (Why "viewer" not "view"?) delegate = Arg(Anything) var1 = Option(Anything) ###WRONG, but shows the idea for now... def env_for_arg(self, index): env = self.env # note: not self.env_for_args, since we'd rather not lexically bind _my. # But by convention that means we need a new lowercase name... ####e if index == 0: #KLUGE that we know index for that arg (delegate, arg1) mods = {} ###stub, WRONG #### how do we make these mods? _e_kws tells which, but what env/ipath for the formulae? # for that matter do we eval them all now, or (somehow) wait and see if env clients use them? # ... would it be easier if this was an OpExpr rather than an InstanceOrExpr? env = env.with_lexmods(mods) return env pass # == trivial prototype of central cache of viewers for objects -- copied/modified from demo_MT.py, 070105, not yet used, stub def _make_viewer_for_object(obj, essential_data): ###stub assert obj.__class__.__name__.endswith("Vertex") return VertexView(obj) # semiobs cmt (del or refile a bit below #e): # args are (object, essential-data) where data diffs should prevent sharing of an existing viewer # (this scheme means we'd find an existing but not now drawn viewer... but we only have one place to draw one at a time, # so that won't come up as a problem for now.) # (this is reminiscent of the Qt3MT node -> TreeItem map... # will it have similar problems? I doubt it, except a memory leak at first, solvable someday by a weak-key node, # and a two-level dict, key1 = weak node, key2 = essentialdata.) def _make_viewer_for_object_using_key(key): """[private, for use in a MemoDict or LvalDict2] #doc key is whatever should determine how to make the viewer and be used as the key for the dict of cached viewers so it includes whatever matters in picking which obj to make/cache/return but *not* things that determine current viewer but in which changes should invalidate and replace cached viewers. """ obj, essential_data, reload_counter = key ###k assume key has this form print "make viewer for obj %r, reload_counter = %r" % (obj, reload_counter) ### # obj is any model object viewer = _make_viewer_for_object(obj) return viewer _viewer_lvaldict = LvalDict2( _make_viewer_for_object_using_key ) def _viewer_for_object(obj, essential_data = None): #####@@@@@ CALL ME "Find or make a viewer for the given model object. Essential data is hashable data which should alter which viewer to find. ###k??" from exprs.reload import exprs_globals reload_counter = exprs_globals.reload_counter # this is so we clear this cache on reload (even if this module is not reloaded) # assume essential_data is already hashable (eg not dict but sorted items of one) key = (obj, essential_data, reload_counter) lval = _viewer_lvaldict[ key ] viewer = lval.get_value() ###k? return viewer # end
NanoCAD-master
cad/src/exprs/scratch/rules.py
$Id$ class ControlPoint: """ abstract class for any kind of control point for use inside another object like a polyline; subclasses can include ones on a reference object # note: obs name: PointOnReferenceObject """ pass class PolylineSegment: """ abstract class for any kind of polyline segment """ pass class ModelObject: pass # rename Model3D_Component or so? class Polyline(ModelObject): """ A version of a polyline model object type based on a graph, with control points able to be on different ref objects; this class provides the data type and necessary low-level operations; it does NOT provide drawing and editing-UI code -- when those are needed they must be provided by associated classes. """ # each one has a graph of control points and segments # which have to have types that meet some APIs for them # (which depend only on our own code, since it uses those APIs) # (but note that if methods are added to this class that might add to the list of required APIs for the parts!) controlPointType = ControlPoint ### REVIEW: capitalize attr name? # note: this is the data type, not the UI, so we have the # most general type we can; a typical UI would encourage or require # the creation of points of some more specific type; # if so, that's declared in that UI code. segmentType = PolylineSegment _graph = Instance( Graph( vertexType = controlPointType, edgeType = segmentType ) ) # Q. is Instance required? # Note: this declaration implicitly says that this member is part of our data # (to be inspected, saved, copied, etc)... # Q. but what about the private name? does it indicate we'd rather save it # in terms of the separate accessors with public names?? controlPoints = _graph.vertices segments = _graph.edges ## addControlPoint = _graph.addVertex #e or is it better to require use of controlPoints as a dict, adding or extending? # not necessarily... e.g. this method would require that the point was not already there. # OTOH we can use it as a set instead and make sure the set.add method requires that... ###k # the price of not doing this is having to alias tons of method names... # but these aliases seem useful addControlPoint = controlPoints.add addSegment = segments.add pass class Polyline_drawer(Drawer): """ a view of a polyline for the purpose of drawing it """ delegate = Arg(Polyline, doc = "the Polyline we draw") ###e rename to self.polyline? but we do need to delegate to it for convenience. def draw(self): ### IMPLEM self.drawer as something to draw objects in their usual way, # subject to usual env rules for that (drawing styles and filters); # drawset can have optims for drawing a large set; # maybe we'll pass options about their role in us, # for it to use when looking up display styles. # # OR it can just be self, if this doesn't cause confusion due to delegation # by hiding parts of self.delegate. Hmm... should we declare what attrs to delegate? self.drawer.drawset( self.controlPoints ) self.drawer.drawset( self.segments ) return pass def Polyline_UI_helper: #k super? should provide helper methods for this kind of component # (one which adds data editing ops for use by a graphical UI) """ methods for editing polylines for use by a graphical UI """ data = Arg(Polyline, doc = "the Polyline we help to edit") #e rename to self.polyline? def addControlPoint(self, pointType): #k not sure if we need this, but it's like addSegment below... # note that it takes the type, not the object! because we know it's new... # but it's not really a type, it's a description, since it has all the data as well. ### RENAME the arg! ## point = pointType() ###k ?? no, the container needs to make it, from the description... or is it an expr with code? HMM ##### point = self.data.makeControlPoint(pointType) # note: this implem is generic for things that can instantiate descriptions, # except for knowing to call makeControlPoint rather than make... # which differs from make in having defaults suitable for self.data.ControlPointType self.data.addControlPoint(point) def addSegment(self, fromPoint, toPoint, segmentType): # note: this is sort of like self.make(segmentType(fromPoint, toPoint)) # if we imagine that those descriptions (in the arg) carried enough info # for us to know their roles in self. """ Add a new segment of type Line from fromPoint to point toPoint, each of which might be either an existing Point object in self or a description of a new one we should create (e.g. as coords and ref object or frame). """ ## fromPoint = self.canonicalizePoint(fromPoint) #e rename: find or make? this adds the points if needed. # Note re choosing the name: # it is a purely UI method -- the only reason to not know, here, if it's an existing or new point, # is that we had user mouse position data, then we saw if user was hovering over an existing point, # and if so passed that point, else the mouse position. # (So should the caller turn the posn into a new point, for clarity? # maybe only the caller knows the point type, whether that's ok given what's near, etc? # YES, make caller do that, thus we comment this out.) ## toPoint = self.canonicalizePoint(toPoint) line = segmentType(fromPoint, toPoint) ###k? old code said self.Line... self.Line is a type and constructor for whatever we use as a line... # but does this method care whether the points are in the same ref object? no, it does not require that. self.data.addSegment(line) # the more fundamental method; so self.data is our polyline data, not self! ###k return def # now bring in code from: # - my polyline drawing eg code -- it can add lines or sketched curves # for the latter, add the angle cond from squeak -- # or is that part of separate UI class for a stroke? yes, it is... in this code # just say: collect a stroke from the drag, give me the points to be drawing # (if we want to optim, give me the permanent and tentative ones seply, and give permanent ones incrly) # (so my stroke-drawing code can optim for a stroke being built up, by making a displist tree...) # - my scratch code for drawing this with its construction lines, in xor mode # - if i like this way of splitting up classes, then split the file and make separate files # conclusions: # - yes, do it like this, keep this (at least as scratch to make clean & real) # - want separate classes # - want formulae # - want types # - maybe it's more like a sketch than a line... as you added sketch elements, they might share one set of control points, # and those might be kept by the sketch in per-ref-object sets for efficiency. # so one sketch element (entity) might then refer to or own various sketch primitives including points and segments. # So this object here is really more like the sketch itself. # (But do sketches share points between them? No -- if you want that, promote those points to ReferencePoints outside the sketch.) # - note we'll have folding paths, etc, in future, related to this code # - note they're like sketches in being able to have disconected pieces, other things in them, etc # - and fancier -- tags on the elements, etc # - they'd make good use of using generic helper objects but with more specific implem and UI classes for those obj's components. # (eg a graph but of a specific kind of points)
NanoCAD-master
cad/src/exprs/scratch/Polyline_G.py