Exemplo n.º 1
0
 def close(self, e = None):
     """
     When the user closes the dialog by clicking the 'X' button
     on the dialog title bar, do whatever the cancel button does.
     """
     print "\nfyi: GeneratorBaseClass.close(%r) was called" % (e,)
         # I think this is never called anymore,
         # and would lead to infinite recursion via cancel_btn_clicked
         # (causing bugs) if it was. [bruce 070829]
     
     # Note: Qt wants the return value of .close to be of the correct type,
     # apparently boolean; it may mean whether to really close (just a guess)
     # (or it may mean whether Qt needs to process the same event further,
     #  instead)
     # [bruce 060719 comment, updated after 070724 code review]
     try:
         self.cancel_btn_clicked()
         return True
     except:
         #bruce 060719: adding this print, since an exception here is either
         # an intentional one defined in this file (and should be reported as
         # an error in history -- if this happens we need to fix this code to
         # do that, maybe like _ok_or_preview does), or is a bug. Not
         # printing anything here would always hide important info, whether
         # errors or bugs.
         print_compact_traceback("bug in cancel_btn_clicked, or in not reporting an error it detected: ")
         return False
    def leftDrag(self, event):
        """
        Translate the selected object(s):
        - in the plane of the screen following the mouse,
        - or slide and rotate along the an axis

        @param event: The mouse left drag event.
        @type  event: QMouseEvent instance
        """
        _superclass.leftDrag(self, event)

        if self.cursor_over_when_LMB_pressed == "Empty Space":
            # The _superclass.leftDrag considers this condition.
            # So simply return and don't go further. Fixes bug 2607
            return

        if self.leftDownType in ["TRANSLATE", "A_TRANSLATE"]:
            try:
                self.leftDragTranslation(event)
                return
            except:
                msg1 = "Controlled translation not allowed. "
                msg2 = "Key must be pressed before starting the drag"
                env.history.statusbar_msg(msg1 + msg2)
                if debug_flags.atom_debug:
                    msg3 = "Error occured in " "TranslateChunks_GraphicsMode.leftDragTranslation."
                    msg4 = "Possibly due to a key press that activated. "
                    msg5 = "Rotate groupbox. Aborting drag operation"
                    print_compact_traceback(msg3 + msg4 + msg5)
Exemplo n.º 3
0
def submenu_from_name_value_pairs(nameval_pairs,
                                  newval_receiver_func,
                                  curval=None,
                                  mitem_value_func=None,
                                  indicate_defaultValue=False,
                                  defaultValue=None):
    #bruce 080312 revised to use same_vals (2 places)
    from utilities.debug import print_compact_traceback  # do locally to avoid recursive import problem
    submenu = []
    for name, value in nameval_pairs:
        text = name
        if indicate_defaultValue and same_vals(value, defaultValue):
            #bruce 070518 new feature
            text += " (default)"
        command = (
            lambda  ## event = None,
            func=newval_receiver_func, val=value: func(val))
        mitem = (text, command, same_vals(curval, value) and 'checked' or None)
        if mitem_value_func is not None:
            try:
                res = "<no retval yet>"  # for error messages
                res = mitem_value_func(mitem, value)
                if res is None:
                    continue  # let func tell us to skip this item ###k untested
                assert type(res) == type((1, 2))
                mitem = res
            except:
                print_compact_traceback(
                    "exception in mitem_value_func, or error in retval (%r): "
                    % (res, ))
                #e improve, and atom_debug only
                pass
        submenu.append(mitem)
    return submenu
def find_plugin_dir(plugin_name):
    """
    Return (True, dirname) or (False, errortext), with errortext wording chosen as if the requested plugin ought to exist.
    """
    try:
        userdir = user_plugins_dir()
        if userdir and os.path.isdir(userdir):
            path = os.path.join(userdir, plugin_name)
            if os.path.isdir(path):
                return True, path
    except:
        print_compact_traceback("bug in looking for user-customized plugin %r; trying builtin plugins: ")
        pass
    try:
        appdir = builtin_plugins_dir()
        assert appdir
        if not os.path.isdir(appdir):
            return False, "error: can't find built-in plugins directory [%s] (or it's not a directory)" % (appdir,)
        path = os.path.join(appdir, plugin_name)
        if os.path.isdir(path):
            return True, path
        return False, "can't find plugin %r" % (plugin_name,)
    except:
        print_compact_traceback("bug in looking for built-in plugin %r: " % (plugin_name,))
        return False, "can't find plugin %r" % (plugin_name,)
    pass
Exemplo n.º 5
0
 def colorframe_bgcolor_setter(color):
     #e no convenient/clean way for Formula API to permit but not require this function to receive the formula,
     # unless we store it temporarily in env._formula (which we might as well do if this feature is ever needed)
     try:
         # make sure errors here don't stop the formula from running:
         # (Need to protect against certain kinds of erroneous color values? RGBf_to_QColor does it well enough.)
         ## Qt3 code used: colorframe.setPaletteBackgroundColor(RGBf_to_QColor(color))
         qcolor = RGBf_to_QColor(color)
         palette = QPalette(
         )  # QPalette(qcolor) would have window color set from qcolor, but that doesn't help us here
         qcolorrole = QPalette.Window
         ## http://doc.trolltech.com/4.2/qpalette.html#ColorRole-enum says:
         ##   QPalette.Window    10    A general background color.
         palette.setColor(QPalette.Active, qcolorrole,
                          qcolor)  # used when window is in fg and has focus
         palette.setColor(
             QPalette.Inactive, qcolorrole,
             qcolor)  # used when window is in bg or does not have focus
         palette.setColor(QPalette.Disabled, qcolorrole,
                          qcolor)  # used when widget is disabled
         colorframe.setPalette(palette)
         colorframe.setAutoFillBackground(True)
         # [Note: the above scheme was revised again by bruce 070430, for improved appearance
         #  (now has thin black border around color patch), based on Ninad's change in UserPrefs.py.]
         ## no longer needed: set color for qcolorrole = QPalette.ColorRole(role) for role in range(14)
         ## no longer needed: colorframe.setLineWidth(500) # width of outline of frame (at least half max possible size)
     except:
         print "data for following exception: ",
         print "colorframe %r has palette %r" % (colorframe,
                                                 colorframe.palette())
         # fyi: in Qt4, like in Qt3, colorframe is a QFrame
         print_compact_traceback(
             "bug (ignored): exception in formula-setter: "
         )  #e include formula obj in this msg?
     pass
    def __get_csdl_collector(self):
        """
        get method for self.csdl_collector property:

        Initialize self._csdl_collector if necessary, and return it.
        """
        try:
            ## print "__get_csdl_collector", self
            if not self._csdl_collector:
                ## print "alloc in __get_csdl_collector", self
                self._csdl_collector = self._csdl_collector_class(self)
                # note: self._csdl_collector_class changes dynamically
            return self._csdl_collector
        except:
            # without this try/except, python will report any exception in here
            # (or at least any AttributeError) as if it was an AttributeError
            # on self.csdl_collector, discarding all info about the nature
            # and code location of the actual error! [bruce 090220]
            ### TODO: flush all output streams in print_compact_traceback;
            # in current code, the following prints before we finish printing
            # whatever print statement had the exception partway through, if one did
            print_compact_traceback(
                "\nfollowing exception is *really* this one, inside __get_csdl_collector: "
            )
            print
            raise
        pass
Exemplo n.º 7
0
 def project_2d(self, pt):
     """
     like project_2d_noeyeball, but take into account self.eyeball;
     return None for a point that is too close to eyeball to be projected
     [in the future this might include anything too close to be drawn #e]
     """
     p = self.project_2d_noeyeball(pt)
     if self.eyeball:
         # bruce 041214: use "pfix" to fix bug 30 comment #3
         pfix = self.project_2d_noeyeball(self.org)
         p -= pfix
         try:
             ###e we recompute this a lot; should cache it in self or self.shp--Bruce
             ## Huaicai 04/23/05: made the change as suggested by Bruce above.
             p = p / (dot(pt - self.eyeball, self.normal) / self.eye2Pov)
         except:
             # bruce 041214 fix of unreported bug:
             # point is too close to eyeball for in-ness to be determined!
             # [More generally, do we want to include points which are
             #  projectable without error, but too close to the eyeball
             #  to be drawn? I think not, but I did not fix this yet
             #  (or report the bug). ###e]
             if debug_flags.atom_debug:
                 print_compact_traceback("atom_debug: ignoring math error for point near eyeball: ")
             return None
         p += pfix
     return p
Exemplo n.º 8
0
def find_plugin_dir(plugin_name):
    """
    Return (True, dirname) or (False, errortext), with errortext wording chosen as if the requested plugin ought to exist.
    """
    try:
        userdir = user_plugins_dir()
        if userdir and os.path.isdir(userdir):
            path = os.path.join(userdir, plugin_name)
            if os.path.isdir(path):
                return True, path
    except:
        print_compact_traceback(
            "bug in looking for user-customized plugin %r; trying builtin plugins: "
        )
        pass
    try:
        appdir = builtin_plugins_dir()
        assert appdir
        if not os.path.isdir(appdir):
            return False, "error: can't find built-in plugins directory [%s] (or it's not a directory)" % (
                appdir, )
        path = os.path.join(appdir, plugin_name)
        if os.path.isdir(path):
            return True, path
        return False, "can't find plugin %r" % (plugin_name, )
    except:
        print_compact_traceback("bug in looking for built-in plugin %r: " %
                                (plugin_name, ))
        return False, "can't find plugin %r" % (plugin_name, )
    pass
Exemplo n.º 9
0
def open_wiki_help_URL(
    url,
    whosdoingthis="Wiki help"
):  #bruce 051229 split this out of open_wiki_help_dialog
    """
    Try to open the given url in the user's browser (unless they've set preferences to prevent this (NIM)),
    first emitting a history message containing the url
    (which is described as coming from whosdoingthis, which should be a capitalized string).
    Return True if there's no evidence of an error; print error message to history and return False if it definitely failed.
    """
    url = str(url)  # precaution in case of QString
    ###e should check prefs to see if we should really open browser; if not, print different hist message
    env.history.message(
        "%s: opening " % whosdoingthis +
        url)  # see module docstring re "wiki help" vs. "web help"
    # print this in case user wants to open it manually or debug the url prefix preference
    try:
        webbrowser_open(url)
        worked = True
    except:
        #bruce 051201 catch exception to mitigate bug 1167
        # (e.g. when Linux user doesn't have BROWSER env var set).
        # Probably need to make this more intelligent, perhaps by
        # catching the specific exception in the bug report, knowing
        # the OS, passing options to webbrowser.open, etc.
        print_compact_traceback("webbrowser exception: ")
        env.history.message( redmsg("Problem opening web browser.") +
            "Suggest opening above URL by hand. "\
            "On some platforms, setting BROWSER environment variable might help."
         )
        worked = False
    return worked
Exemplo n.º 10
0
def _safely_call_getEquilibriumDistanceForBond( eltnum1, eltnum2, ltr): #bruce 080405 split this out
    """
    #doc
    eg: args for C-C are (6, 6, '1')

    @return: ideal length in Angstroms (as a positive float),
             or None if the call of getEquilibriumDistanceForBond failed
    """
    try:
        pm = thePyrexSimulator().getEquilibriumDistanceForBond(eltnum1,
                                                               eltnum2,
                                                               ltr)
        assert pm > 2.0, "too-low pm %r for getEquilibriumDistanceForBond%r" % \
               (pm, (eltnum1, eltnum2, ltr))
            # 1.0 means an error occurred; 2.0 is still ridiculously low
            # [not as of 070410]; btw what will happen for He-He??
            # update 070410: it's 1.8 for (202, 0, '1').
            # -- but a new sim-params.txt today changes the above to 170
        nicelen = pm / 100.0 # convert picometers to Angstroms
        return nicelen
    except:
        # be fast when this happens a lot (not important now that our retval
        # is cached, actually; even so, don't print too much)
        if not env.seen_before("error in getEquilibriumDistanceForBond"):
            #e include env.redraw_counter to print more often? no.
            msg = "bug: ignoring exceptions when using " \
                  "getEquilibriumDistanceForBond, like this one: "
            print_compact_traceback(msg)
        return None
    pass
Exemplo n.º 11
0
def register_MMP_RecordParsers():  #bruce 071019
    """
    Register MMP_RecordParser subclasses for the model objects that can be read
    from mmp files, and whose parsers are not hardcoded into files_mmp.py.
    """
    import model.Comment as Comment
    Comment.register_MMP_RecordParser_for_Comment()

    import analysis.GAMESS.jig_Gamess as jig_Gamess
    jig_Gamess.register_MMP_RecordParser_for_Gamess()

    import model.PovrayScene as PovrayScene
    PovrayScene.register_MMP_RecordParser_for_PovrayScene()

    try:
        import dna.model.DnaMarker as DnaMarker
        DnaMarker.register_MMP_RecordParser_for_DnaMarkers()
    except:
        print_compact_traceback(
            "bug: ignoring exception in register_MMP_RecordParser_for_DnaMarkers: "
        )
        pass

    # TODO: add more of these.

    return
Exemplo n.º 12
0
 def __getitem__(self, key):
     # get the "current glpane" and its graphicsMode
     # (for purposes of determining modes & prefs)
     # (how we do it is not necessarily a kluge, given that this is being
     #  used to define a constant value for use when a better one was
     #  not passed)
     if debug_flags.atom_debug:
         print "fyi: getting %r from %r" % (key, self)
         # This happens 5 or 6 times when entering Build Atoms command;
         # not sure why, but probably ok.
         # Historical note: On 081003 I fixed what I thought was a typo below
         # (mainWindow -> mainwindow), here and in another place below,
         # and was surprised that this had no effect, and wondered why the
         # prior presumed exception had been silently discarded. In fact,
         # it was not a typo -- mainWindow is an alias for mainwindow in env.
         # So there was no exception and there is no mystery.
         # (An actual exception here causes, at least, a bug when hovering
         #  over a 3' strand end arrowhead, in Select Chunks mode.)
         # [bruce 081211 comment]
     win = env.mainwindow()
     glpane = win.glpane
     graphicsMode = glpane.graphicsMode
     # let the graphicsMode interpret the prefs key,
     # in case it wants to override it with a local pref
     # (or conceivably, someday, track it in a different way)
     # (note, ThumbView has no graphicsMode, but that doesn't
     #  affect this code since it uses main glpane even when
     #  drawing into a ThumbView. [bruce 080606 comment])
     try:
         res = graphicsMode.get_prefs_value(key)
     except:
         msg = "bug: exception in %r.get_prefs_value(%r), %s" % (graphicsMode, key, "falling back to env.prefs")
         print_compact_traceback(msg + ": ")
         res = env.prefs[key]
     return res
    def insertItems(self, row, items, setAsDefault = True):
        """
        Insert the <items> specified items in this list widget.
        The list widget shows item name string , as a QListwidgetItem.

        This QListWidgetItem object defines a 'key' of a dictionary
        (self._itemDictionary) and the 'value' of this key is the object
        specified by the 'item' itself.
        Example: self._itemDictionary['C6'] = instance of class Atom.

        @param row: The row number for the item.
        @type row: int

        @param items: A list of objects. These objects are treated as values in
                      the self._itemDictionary
        @type items: list

        @param setAsDefault: Not used here. See PM_ListWidget.insertItems where
                             it is used.

        @see: self.renameItemValue() for a comment about
              self._suppress_itemChanged_signal

        """

        #delete unused argument. Should this be provided as an argument in this
        #class method ?
        del setAsDefault

        #self.__init__ for a comment about this flag
        self._suppress_itemChanged_signal = True

        #Clear the previous contents of the self._itemDictionary
        self._itemDictionary.clear()

        #Clear the contents of this list widget, using QListWidget.clear()
        #See U{<http://doc.trolltech.com/4.2/qlistwidget.html>} for details
        self.clear()

        for item in items:
            if hasattr(item.__class__, 'name'):
                itemName = item.name
            else:
                itemName = str(item)
            listWidgetItem = QListWidgetItem(itemName, self)

            #When we support editing list widget items , uncomment out the
            #following line . See also self.editItems -- Ninad 2008-01-16
            listWidgetItem.setFlags( listWidgetItem.flags()| Qt.ItemIsEditable)

            if hasattr(item.__class__, 'iconPath'):
                try:
                    listWidgetItem.setIcon(geticon(item.iconPath))
                except:
                    print_compact_traceback()

            self._itemDictionary[listWidgetItem] = item

        #Reset the flag that temporarily suppresses itemChange signal.
        self._suppress_itemChanged_signal = False
Exemplo n.º 14
0
    def kill_with_contents(self):
        """
        Kill this Node including the 'logical contents' of the node. i.e. 
        the contents of the node that are self.members as well as non-members. 
        Example: A DnaSegment's logical contents are AxisChunks and StrandChunks 
        Out of these, only AxisChunks are the direct members of the DnaSegment
        but the 'StrandChunks are logical contents of it (non-members) . 
        So, some callers may specifically want to delete self along with its 
        members and logical contents. These callers should use this method. 
        The default implementation just calls self.kill()
        @see: B{Node.DnaSegment.kill_with_contents}  which is overridden here
              method. 
        @see: EditCommand._removeStructure() which calls this Node API method
        @see: DnaDuplex_EditCommand._removeSegments()
        @see: dna_model.DnaLadder.kill_strand_chunks() for a comment.
        
        @see: A note in self.kill() about NFR bug 2749
        
        """
        for member in self.members:
            if isinstance(member, DnaAxisChunk):
                ladder = member.ladder
                try:
                    #See a note in dna_model.kill_strand_chunks. Should we
                    #instead call ladder.kill() and thus kill bothstrand
                    #and axis chunks. ?
                    ladder.kill_strand_chunks()
                except:
                    print_compact_traceback("bug in killing the ladder chunk")

        DnaStrandOrSegment.kill_with_contents(self)
Exemplo n.º 15
0
 def kill(self):
     """
     Overrides superclass method. For a Dnasegment , as of 2008-04-09,
     the default implementation is that deleting a segment will delete 
     the segment along with its logical contents (see bug 2749).
     """
     # It is tempting to call self.kill_with_contents , BUT DON'T CALL IT HERE!
     # ...as kill_with_contents  is used elsewhere (before bug 2749 NFR was
     # suggested and it calls self.kill() at the end. So that will create 
     # infinite recursions. 
     ### TODO: code cleanup/ refactoring to resolve kill_with_content issue
     
     #The following block is copied over from self.kill_with_contents()
     #It implements behavior suggested in bug 2749 (deleting a segment will 
     #delete the segment along with its logical contents )
     #See method docsting above on why we shouldn't call that method instead
     for member in self.members:
         if isinstance(member, DnaAxisChunk):          
             ladder = member.ladder
             try:
                 #See a note in dna_model.kill_strand_chunks. Should we 
                 #instead call ladder.kill() and thus kill bothstrand 
                 #and axis chunks. ?
                 ladder.kill_strand_chunks()
             except:
                 print_compact_traceback("bug in killing the ladder chunk")
                 
     DnaStrandOrSegment.kill(self)
Exemplo n.º 16
0
 def project_2d(self, pt):
     """
     like project_2d_noeyeball, but take into account self.eyeball;
     return None for a point that is too close to eyeball to be projected
     [in the future this might include anything too close to be drawn #e]
     """
     p = self.project_2d_noeyeball(pt)
     if self.eyeball:
         # bruce 041214: use "pfix" to fix bug 30 comment #3
         pfix = self.project_2d_noeyeball(self.org)
         p -= pfix
         try:
             ###e we recompute this a lot; should cache it in self or self.shp--Bruce
             ## Huaicai 04/23/05: made the change as suggested by Bruce above.
             p = p / (dot(pt - self.eyeball, self.normal) / self.eye2Pov)
         except:
             # bruce 041214 fix of unreported bug:
             # point is too close to eyeball for in-ness to be determined!
             # [More generally, do we want to include points which are
             #  projectable without error, but too close to the eyeball
             #  to be drawn? I think not, but I did not fix this yet
             #  (or report the bug). ###e]
             if debug_flags.atom_debug:
                 print_compact_traceback("atom_debug: ignoring math error for point near eyeball: ")
             return None
         p += pfix
     return p
Exemplo n.º 17
0
 def kill_with_contents(self):  
     """
     Kill this Node including the 'logical contents' of the node. i.e. 
     the contents of the node that are self.members as well as non-members. 
     Example: A DnaSegment's logical contents are AxisChunks and StrandChunks 
     Out of these, only AxisChunks are the direct members of the DnaSegment
     but the 'StrandChunks are logical contents of it (non-members) . 
     So, some callers may specifically want to delete self along with its 
     members and logical contents. These callers should use this method. 
     The default implementation just calls self.kill()
     @see: B{Node.DnaSegment.kill_with_contents}  which is overridden here
           method. 
     @see: EditCommand._removeStructure() which calls this Node API method
     @see: InsertDna_EditCommand._removeSegments()
     @see: dna_model.DnaLadder.kill_strand_chunks() for a comment.
     
     @see: A note in self.kill() about NFR bug 2749
     
     """   
     for member in self.members:            
         if isinstance(member, DnaAxisChunk):                
             ladder = member.ladder
             try:
                 #See a note in dna_model.kill_strand_chunks. Should we 
                 #instead call ladder.kill() and thus kill bothstrand 
                 #and axis chunks. ?
                 ladder.kill_strand_chunks()
             except:
                 print_compact_traceback("bug in killing the ladder chunk")
     
     DnaStrandOrSegment.kill_with_contents(self)
Exemplo n.º 18
0
    def close(self):
        """
        Closes the Property Manager.
        """
        if not self.pw:
            self.pw = self.win.activePartWindow()
        self.pw.pwProjectTabWidget.setCurrentIndex(0)

        ## try: [bruce 071018 moved this lower, since errmsg only covers attr]
        pmWidget = self.pw.propertyManagerScrollArea.widget()
        if debug_flags.atom_debug:  #bruce 071018
            "atom_debug fyi: %r is closing %r (can they differ?)" % \
                        (self, pmWidget)
        try:
            pmWidget.update_props_if_needed_before_closing
        except AttributeError:
            if 1 or debug_flags.atom_debug:
                msg1 = "Last PropMgr %r doesn't have method" % pmWidget
                msg2 = " update_props_if_needed_before_closing. That's"
                msg3 = " OK (for now, only implemented for Plane PM). "
                msg4 = "Ignoring Exception: "
                print_compact_traceback(msg1 + msg2 + msg3 + msg4)
                #bruce 071018: I'll define that method in PM_Dialog
                # so this message should become rare or nonexistent,
                # so I'll make it happen whether or not atom_debug.
        else:
            pmWidget.update_props_if_needed_before_closing()

        self.pw.pwProjectTabWidget.removeTab(
            self.pw.pwProjectTabWidget.indexOf(
                self.pw.propertyManagerScrollArea))

        if self.pw.propertyManagerTab:
            self.pw.propertyManagerTab = None
Exemplo n.º 19
0
 def _draw_by_remaking(self, glpane, selected, highlighted, wantlist, draw_now):
     """
     """
     # modified from similar code in ChunkDrawer.draw
     assert not (not wantlist and not draw_now)
     if wantlist:
         match_checking_code = self.begin_tracking_usage()
             # note: method defined in superclass, SubUsageTrackingMixin
         ColorSorter.start(glpane, self.csdl, selected)
             ### REVIEW: is selected arg needed? guess yes,
             # since .finish will draw it based on the csdl state
             # which is determined by that arg. If so, this point needs
             # correcting in the docstring for csdl.draw().
     self.comparator.before_recompute()
     try:
         self._do_drawing()
     except:
         print_compact_traceback(
             "bug: exception in %r._do_drawing, skipping the rest: " % self)
         self.comparator.after_recompute()
             # note: sets self.comparator.valid (in spite of error)
         pass
     else:
         self.comparator.after_recompute()
     if wantlist:
         ColorSorter.finish(draw_now = draw_now)
         # needed by self._invalidate_display_lists for gl_update
         self._glpane = glpane
         self.end_tracking_usage( match_checking_code,
                                  self._invalidate_display_lists )
     return
Exemplo n.º 20
0
def open_wiki_help_URL(url, whosdoingthis="Wiki help"):  # bruce 051229 split this out of open_wiki_help_dialog
    """
    Try to open the given url in the user's browser (unless they've set preferences to prevent this (NIM)),
    first emitting a history message containing the url
    (which is described as coming from whosdoingthis, which should be a capitalized string).
    Return True if there's no evidence of an error; print error message to history and return False if it definitely failed.
    """
    url = str(url)  # precaution in case of QString
    ###e should check prefs to see if we should really open browser; if not, print different hist message
    env.history.message("%s: opening " % whosdoingthis + url)  # see module docstring re "wiki help" vs. "web help"
    # print this in case user wants to open it manually or debug the url prefix preference
    try:
        webbrowser_open(url)
        worked = True
    except:
        # bruce 051201 catch exception to mitigate bug 1167
        # (e.g. when Linux user doesn't have BROWSER env var set).
        # Probably need to make this more intelligent, perhaps by
        # catching the specific exception in the bug report, knowing
        # the OS, passing options to webbrowser.open, etc.
        print_compact_traceback("webbrowser exception: ")
        env.history.message(
            redmsg("Problem opening web browser.") + "Suggest opening above URL by hand. "
            "On some platforms, setting BROWSER environment variable might help."
        )
        worked = False
    return worked
Exemplo n.º 21
0
def editMakeCheckpoint(win):
    """
    This is called from MWsemantics.editMakeCheckpoint,
    which is documented as:

      "Slot for making a checkpoint (only available when
       Automatic Checkpointing is disabled)."
    """
    env.history.message(greenmsg("Make Checkpoint"))
    # do it
    try:
        #REVIEW: Should make sure this is correct with or without
        # auto-checkpointing enabled, and leaves that setting unchanged.
        # (This is not urgent, since in present UI it can't be called
        #  except when auto-checkpointing is disabled.)
        um = win.assy.undo_manager
        if um:
            um.make_manual_checkpoint()
            # no msg needed, was emitted above:
            ## env.history.message(greenmsg("Make Checkpoint"))
            pass
        else:
            # this should never happen
            msg = "Make Checkpoint: error, no undo_manager"
            env.history.message(redmsg(msg))
    except:
        print_compact_traceback("exception caught in editMakeCheckpoint: ")
        msg = "Internal error in Make Checkpoint. " \
              "Undo/Redo might be unsafe until a new file is opened."
        env.history.message(redmsg(msg))
        #e that wording assumes we can't open more than one file at a time...
    return
Exemplo n.º 22
0
    def pastable_atomtype(self):
        """
        Return the current pastable atomtype.

        [REVIEW: This appears to be very similar (if not completely redundant) to 
        get_atomtype_from_MMKit() in this file. This is still used as of 071025;
        that one is called only by the slot transmutePressed -- can that still
        be called?]
        """
        #e we might extend this to remember a current atomtype per element
        #... not sure if useful
        current_element = self.pastable_element()
        if len(current_element.atomtypes) > 1:
            if self.propMgr and hasattr(self.propMgr, 'elementChooser'):
                try:
                    hybrid_name = self.propMgr.elementChooser.atomType                
                    atype = current_element.find_atomtype(hybrid_name)
                    if atype is not None:
                        self._pastable_atomtype = atype
                except:
                    print_compact_traceback("exception (ignored): ") 
                pass
            else:
                # we're presumably a subclass with no propMgr or a different one
                pass
        if self._pastable_atomtype is not None and self._pastable_atomtype.element is current_element:
            return self._pastable_atomtype
        self._pastable_atomtype = current_element.atomtypes[0]
        return self._pastable_atomtype
Exemplo n.º 23
0
 def delta_frame_bytes(self, n):
     """
     return the bytes of the delta frame which has index n (assuming our file is open and n is within legal range)
     """
     # note: the first one has index 1 (since it gives delta from time 0 to time 1).
     assert n > 0
     nbytes = self.natoms * 3  # number of bytes in frame (if complete) -- no relation to frame index n
     filepos = ((n - 1) * nbytes) + 4
     try:
         # several things here can fail if file is changing on disk in various ways
         if not self.fileobj:
             # this might not yet ever happen, not sure.
             self.open_file(
             )  #e check for error? check length still the same, etc?
         self.fileobj.seek(
             filepos
         )  ####@@@@ failure here might be possible if file got shorter after size measured -- not sure
         res = self.fileobj.read(nbytes)
         assert len(
             res
         ) == nbytes  # this can fail, if file got shorter after we measured its size...
     except:
         # might be good to detect, warn, set flag, return 0s.... ####@@@@ test this
         if debug_flags.atom_debug:  # if this happens at all it might happen a lot...
             print_compact_traceback(
                 "atom_debug: ignoring exception reading delta_frame %d, returning all 00s: "
                 % n)
         res = "\x00" * nbytes
         assert len(
             res
         ) == nbytes, "mistake in python zero-byte syntax"  # but I checked it, should be ok
     return res
Exemplo n.º 24
0
def drawcylinder_wireframe(color, end1, end2, radius): #bruce 060608
    """
    Draw a wireframe cylinder (not too pretty, definitely could look nicer, but
    it works.)
    """
    # display polys as their edges (see drawer.py's drawwirecube or Jig.draw for
    # related code) (probably we should instead create a suitable lines display
    # list, or even use a wire-frame-like texture so various lengths work well)
    glPolygonMode(GL_FRONT, GL_LINE)
    glPolygonMode(GL_BACK, GL_LINE)
    glDisable(GL_LIGHTING)
    # This makes motors look too busy, but without it, they look too weird
    # (which seems worse.)
    glDisable(GL_CULL_FACE)
    try:
        ##k Not sure if this color will end up controlling the edge color; we
        ## hope it will.
        drawcylinder(color, end1, end2, radius)
    except:
        debug.print_compact_traceback("bug, ignored: ")
    # The following assumes that we are never called as part of a jig's drawing
    # method, or it will mess up drawing of the rest of the jig if it's
    # disabled.
    glEnable(GL_CULL_FACE)
    glEnable(GL_LIGHTING)
    glPolygonMode(GL_FRONT, GL_FILL)
    glPolygonMode(GL_BACK, GL_FILL) # could probably use GL_FRONT_AND_BACK
    return
Exemplo n.º 25
0
 def careful_widget_setter(self, value):
     # Note: for some time we used self.widget_setter rather than this method,
     # by mistake, and it apparently worked fine. We'll still use this method
     # as a precaution; also it might be truly needed if the widget quantizes
     # the value, unless the widget refrains from sending signals when
     # programmatically set. [bruce 070815]
     if self.debug:
         print "\n_changes__debug_print: %r setting %r to %r using %r" % \
               ( self, self.widget, value, self.widget_setter )
     self.disconnect() # avoid possible recursion
     try:
         self.widget_setter(value)
     except:
         print_compact_traceback("bug: ignoring exception setting value of %r to %r: " % (self, value))
         print_compact_stack(" fyi: prior exception came from: ")
         self.destroy() #bruce 080930
             # this seems to be safe, but debug output implies it fails to stop formula
             # from continuing to call setter! but that seems unlikely... nevermind for now.
             # Review: do we want subsequent use of self
             # to be silently ok, smaller message, or error? If this destroy worked
             # then I think it should be silently ok, but might not be now,
             # depending on how refs to self continue to be used.
         pass
     else:
         self.connect()
         ### WARNING: .connect is slow, since it runs our Python code to set up an undo wrapper
         # around the slot! We should revise this to tell Qt to block the signals instead.
         # [We can use: bool QObject::blockSignals ( bool block ) ==> returns prior value of signalsBlocked,
         #  now used in a helper function setValue_with_signals_blocked]
         # This will matter for performance when this is used for state which changes during a drag.
         # Note: avoiding the slot call is needed not only for recursion, but to avoid the
         # Undo checkpoint in the wrapper.
         # [bruce comments 071015; see also bug 2564 in other code]
     return
Exemplo n.º 26
0
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
Exemplo n.º 27
0
 def newval_receiver_func(newval):
     from utilities.debug import print_compact_traceback # do locally to avoid recursive import problem
     assert self.dtype.legal_value(newval), "illegal value for %r: %r" % (self, newval)
         ###e change to ask dtype, since most of them won't have a list of values!!! this method is specific to Choice.
     if self.current_value() == newval: #bruce 060126; revised 060209 to use self.current_value() rather than self.value
         if self.print_changes:
             print "redundant change:", 
         ##return??
     self.value = newval
     extra = ""
     if self.prefs_key:
         env.prefs[self.prefs_key] = newval
         # note: when value is looked up, this is the assignment that counts (it overrides self.value) [as of 060209 bugfix]
         extra = " (also in prefs db)"
     if self.print_changes:
         ## msg = "changed %r to %r%s" % (self, newval, extra)
         msg = "changed %s to %r%s" % (self, newval, extra) # shorter version for console too [bruce 080215]
         print msg
         msg = "changed %s to %r%s" % (self, newval, extra) # shorter version (uses %s) for history [bruce 060126]
         env.history.message(msg, quote_html = True, color = 'gray') #bruce 060126 new feature
     for sub in self.subscribers[:]:
         #bruce 060213 new feature; as of 070613 this also supports the call_with_new_value feature
         from utilities.debug import print_compact_traceback # do locally to avoid recursive import problem
         try:
             unsub = sub()
         except:
             print_compact_traceback("exception ignored in some subscriber to changes to %s: " % self)
             unsub = 1
         if unsub:
             self.subscribers.remove(sub) # should work properly even if sub is present more than once
         continue
     return # from newval_receiver_func
    def changeBackgroundColor(self, idx):
        """
        Slot method for the background color combobox.
        """
        #print "changeBackgroundColor(): Slot method called. Idx =", idx

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

        self.win.glpane.gl_update() # Needed!
        return
Exemplo n.º 29
0
    def leftUp(self, event):
        """
        Event handler for Left Mouse button left-up event
        @see: Line_Command._f_results_for_caller_and_prepare_for_new_input()
        """
        
        if len(self.command.mouseClickPoints) == 3:
            self.endPoint2 = None
            self.command.rotateAboutPoint()
            try:
                self.command._f_results_for_caller_and_prepare_for_new_input()
            except AttributeError:
                print_compact_traceback(
                    "bug: command %s has no attr"\
                    "'_f_results_for_caller_and_prepare_for_new_input'.")
                self.command.mouseClickPoints = []
                self.resetVariables()
    
            self.glpane.gl_update()
            return


        assert len(self.command.mouseClickPoints) <= self.command.mouseClickLimit

        if len(self.command.mouseClickPoints) == self.command.mouseClickLimit:
            self.endPoint2 = None
            self._snapOn = False
            self._standardAxisVectorForDrawingSnapReference = None
            self.glpane.gl_update()
            self.command.rotateAboutPoint()
            #Exit this GM's command (i.e. the command 'RotateAboutPoint')
            self.command.command_Done()
        return
Exemplo n.º 30
0
    def kill(self):
        """
        Overrides superclass method. For a Dnasegment , as of 2008-04-09,
        the default implementation is that deleting a segment will delete 
        the segment along with its logical contents (see bug 2749).
        It is tempting to call self.kill_with_contents , BUT DON'T CALL IT HERE!
        ...as kill_with_contents  is used elsewhere (before bug 2749 NFR was
        suggested and it calls self.kill() at the end. So that will create 
        infinite recursions. 
        @TODO: code cleanup/ refactoring to resolve kill_with_content issue
        """

        #The following block is copied over from self.kill_with_contents()
        #It implements behavior suggested in bug 2749 (deleting a segment will
        #delete the segment along with its logical contents )
        #See method docsting above on why we shouldn't call that method instead
        for member in self.members:
            if isinstance(member, DnaAxisChunk):
                ladder = member.ladder
                try:
                    #See a note in dna_model.kill_strand_chunks. Should we
                    #instead call ladder.kill() and thus kill bothstrand
                    #and axis chunks. ?
                    ladder.kill_strand_chunks()
                except:
                    print_compact_traceback("bug in killing the ladder chunk")

        DnaStrandOrSegment.kill(self)
Exemplo n.º 31
0
 def colorframe_bgcolor_setter(color):
     #e no convenient/clean way for Formula API to permit but not require this function to receive the formula,
     # unless we store it temporarily in env._formula (which we might as well do if this feature is ever needed)
     try:
         # make sure errors here don't stop the formula from running:
         # (Need to protect against certain kinds of erroneous color values? RGBf_to_QColor does it well enough.)
         ## Qt3 code used: colorframe.setPaletteBackgroundColor(RGBf_to_QColor(color))
         qcolor = RGBf_to_QColor(color)
         palette = QPalette() # QPalette(qcolor) would have window color set from qcolor, but that doesn't help us here
         qcolorrole = QPalette.Window
             ## http://doc.trolltech.com/4.2/qpalette.html#ColorRole-enum says:
             ##   QPalette.Window    10    A general background color.
         palette.setColor(QPalette.Active, qcolorrole, qcolor) # used when window is in fg and has focus
         palette.setColor(QPalette.Inactive, qcolorrole, qcolor) # used when window is in bg or does not have focus
         palette.setColor(QPalette.Disabled, qcolorrole, qcolor) # used when widget is disabled
         colorframe.setPalette(palette)
         colorframe.setAutoFillBackground(True)
         # [Note: the above scheme was revised again by bruce 070430, for improved appearance
         #  (now has thin black border around color patch), based on Ninad's change in UserPrefs.py.]
         ## no longer needed: set color for qcolorrole = QPalette.ColorRole(role) for role in range(14)
         ## no longer needed: colorframe.setLineWidth(500) # width of outline of frame (at least half max possible size)
     except:
         print "data for following exception: ",
         print "colorframe %r has palette %r" % (colorframe, colorframe.palette())
             # fyi: in Qt4, like in Qt3, colorframe is a QFrame
         print_compact_traceback( "bug (ignored): exception in formula-setter: " ) #e include formula obj in this msg?
     pass
Exemplo n.º 32
0
 def draw_after_highlighting(self, 
                             glpane, 
                             dispdef, 
                             pickCheckOnly = False):
     """
     For ESPImage class, this does all the drawing. (does it after main
     drawing code is finished drawing) . This method ensures that the 
     ESP image jig gets selected even when you click inside the 
     rectangular box (i.e. not just along the edgets of the box)
     @see: GraphicsMode.Draw_after_highlighting()
     @see: Node.draw_after_highlighting()
     @see:Plane.draw_after_highlighting()
     """
     anythingDrawn = False
     if self.hidden:
         return anythingDrawn
     
     self.pickCheckOnly = pickCheckOnly        
     try:
         anythingDrawn = True
         glPushName(self.glname)
         self._draw(glpane, dispdef) #calls self._draw_jig()
     except:
         anythingDrawn = False
         glPopName()
         print_compact_traceback("ignoring exception when drawing Jig %r: " % self)
     else:
         glPopName()
         
     return anythingDrawn
Exemplo n.º 33
0
    def __init__(self):
        ok, nd1_plugin_path = find_plugin_dir("NanoDynamics-1")
        if (not ok):
            env.history.redmsg("Error: can't find " + nd1_plugin_path)
            nd1_plugin_path = "."
        fileName = os.path.join(nd1_plugin_path, "sim-params.txt")

        self._parameterValues = {}
        try:
            print "sim parameters used by NE1 read from: [%s]" % fileName
            parametersFile = open(fileName)
            for line in parametersFile:
                s = line.split()
                if (len(s) > 0 and s[0] == "ne1"):
                    if (len(s) > 1):
                        key = s[1]
                        if (len(s) > 2):
                            value = " ".join(s[2:])
                        else:
                            value = True
                        self._parameterValues[key] = value
        except IOError:
            msg = "Error reading [%s]" % fileName
            print_compact_traceback(msg + ": ")
            env.history.redmsg(msg)
            self._parameterValues = {}
Exemplo n.º 34
0
def _find_or_make_nanorex_dir_0():
    """
    private helper function for find_or_make_Nanorex_directory
    """
    #Create the temporary file directory if not exist [by huaicai ~041201]
    # bruce 041202 comments about future changes to this code:
    # - we'll probably rename this, sometime before Alpha goes out,
    #   since its purpose will become more user-visible and general.
    # - it might be good to create a README file in the directory
    #   when we create it. And maybe to tell the user we created it,
    #   in a dialog.
    # - If creating it fails, we might want to create it in /tmp
    #   (or wherever some python function says is a good temp dir)
    #   rather than leaving an ususable path in tmpFilePath. This
    #   could affect someone giving a demo on a strange machine!
    # - If it exists already, we might want to test that it's a
    #   directory and is writable. If we someday routinely create
    #   a new file in it for each session, that will be a good-
    #   enough test.
    tmpFilePath = os.path.normpath(os.path.expanduser("~/Nanorex/"))
    if not os.path.exists(tmpFilePath):
        try:
            os.mkdir(tmpFilePath)
        except:
            #bruce 041202 fixed minor bug in next line; removed return statement
            print_compact_traceback(
                "exception in creating temporary directory: \"%s\"" %
                tmpFilePath)
            #bruce 050104 new feature [needs to be made portable so it works on Windows ###@@@]
            os_tempdir = "/tmp"
            print "warning: using \"%s\" for temporary directory, since \"%s\" didn't work" % (
                os_tempdir, tmpFilePath)
            tmpFilePath = os_tempdir
    #e now we should create or update a README file in there [bruce 050104]
    return tmpFilePath
Exemplo n.º 35
0
def fix_tooltip(qaction, text):  #060126
    """
    Assuming qaction's tooltip looks like "command name (accel keys)" and might contain unicode in accel keys
    (as often happens on Mac due to symbols for Shift and Command modifier keys),
    replace command name with text, leave accel keys unchanged (saving result into actual tooltip).
       OR if the tooltip doesn't end with ')', just replace the entire thing with text, plus a space if text ends with ')'
    (to avoid a bug the next time -- not sure if that kluge will work).
    """
    whole = unicode(qaction.toolTip())  # str() on this might have an exception
    try:
        #060304 improve the alg to permit parens in text to remain; assume last '( ' is the one before the accel keys;
        # also permit no accel keys
        if whole[-1] == ')':
            # has accel keys (reasonable assumption, not unbreakably certain)
            sep = u' ('
            parts = whole.split(sep)
            parts = [text, parts[-1]]
            whole = sep.join(parts)
        else:
            # has no accel keys
            whole = text
            if whole[-1] == ')':
                whole = whole + ' '  # kluge, explained in docstring
            pass
        # print "formed tooltip",`whole` # printing whole might have an exception, but printing `whole` is ok
        qaction.setToolTip(whole)  # no need for __tr, I think?
    except:
        print_compact_traceback("exception in fix_tooltip(%r, %r): " %
                                (qaction, text))
    return
Exemplo n.º 36
0
    def insertItems(self, row, items, setAsDefault = True):
        """
        Insert the <items> specified items in this list widget. 
        The list widget shows item name string , as a QListwidgetItem. 

        This QListWidgetItem object defines a 'key' of a dictionary 
        (self._itemDictionary) and the 'value' of this key is the object 
        specified by the 'item' itself.         
        Example: self._itemDictionary['C6'] = instance of class Atom. 

        @param row: The row number for the item. 
        @type row: int

        @param items: A list of objects. These objects are treated as values in 
                      the self._itemDictionary
        @type items: list 

        @param setAsDefault: Not used here. See PM_ListWidget.insertItems where 
                             it is used.

        @see: self.renameItemValue() for a comment about 
              self._suppress_itemChanged_signal

        """       

        #delete unused argument. Should this be provided as an argument in this
        #class method ?  
        del setAsDefault

        #self.__init__ for a comment about this flag
        self._suppress_itemChanged_signal = True

        #Clear the previous contents of the self._itemDictionary 
        self._itemDictionary.clear()

        #Clear the contents of this list widget, using QListWidget.clear()
        #See U{<http://doc.trolltech.com/4.2/qlistwidget.html>} for details
        self.clear()

        for item in items:
            if hasattr(item.__class__, 'name'):
                itemName = item.name
            else:
                itemName = str(item)
            listWidgetItem = QListWidgetItem(itemName, self)

            #When we support editing list widget items , uncomment out the 
            #following line . See also self.editItems -- Ninad 2008-01-16
            listWidgetItem.setFlags( listWidgetItem.flags()| Qt.ItemIsEditable)

            if hasattr(item.__class__, 'iconPath'):
                try:
                    listWidgetItem.setIcon(geticon(item.iconPath))
                except:
                    print_compact_traceback()

            self._itemDictionary[listWidgetItem] = item  

        #Reset the flag that temporarily suppresses itemChange signal.   
        self._suppress_itemChanged_signal = False
Exemplo n.º 37
0
def fix_tooltip(qaction, text): #060126
    """
    Assuming qaction's tooltip looks like "command name (accel keys)" and might contain unicode in accel keys
    (as often happens on Mac due to symbols for Shift and Command modifier keys),
    replace command name with text, leave accel keys unchanged (saving result into actual tooltip).
       OR if the tooltip doesn't end with ')', just replace the entire thing with text, plus a space if text ends with ')'
    (to avoid a bug the next time -- not sure if that kluge will work).
    """
    whole = unicode(qaction.toolTip()) # str() on this might have an exception
    try:
        #060304 improve the alg to permit parens in text to remain; assume last '( ' is the one before the accel keys;
        # also permit no accel keys
        if whole[-1] == ')':
            # has accel keys (reasonable assumption, not unbreakably certain)
            sep = u' ('
            parts = whole.split(sep)
            parts = [text, parts[-1]]
            whole = sep.join(parts)
        else:
            # has no accel keys
            whole = text
            if whole[-1] == ')':
                whole = whole + ' ' # kluge, explained in docstring
            pass
        # print "formed tooltip",`whole` # printing whole might have an exception, but printing `whole` is ok
        qaction.setToolTip(whole) # no need for __tr, I think?
    except:
        print_compact_traceback("exception in fix_tooltip(%r, %r): " % (qaction, text) )
    return
Exemplo n.º 38
0
def editMakeCheckpoint(win):
    """
    This is called from MWsemantics.editMakeCheckpoint,
    which is documented as:

      "Slot for making a checkpoint (only available when
       Automatic Checkpointing is disabled)."
    """
    env.history.message( greenmsg("Make Checkpoint")) 
    # do it
    try:
        #REVIEW: Should make sure this is correct with or without
        # auto-checkpointing enabled, and leaves that setting unchanged.
        # (This is not urgent, since in present UI it can't be called
        #  except when auto-checkpointing is disabled.)
        um = win.assy.undo_manager 
        if um:
            um.make_manual_checkpoint()
            # no msg needed, was emitted above:
            ## env.history.message(greenmsg("Make Checkpoint"))
            pass
        else:
            # this should never happen
            msg = "Make Checkpoint: error, no undo_manager"
            env.history.message(redmsg(msg))
    except:
        print_compact_traceback("exception caught in editMakeCheckpoint: ")
        msg = "Internal error in Make Checkpoint. " \
              "Undo/Redo might be unsafe until a new file is opened."
        env.history.message(redmsg(msg))
            #e that wording assumes we can't open more than one file at a time...
    return
Exemplo n.º 39
0
    def _do_leftShiftCntlUp_delete_operations(self,
                                              event,
                                              objUnderMouse,
                                              parentNodesOfObjUnderMouse = ()):
        """
        Overridden in subclasses, default implementation just deletes the
        parent node of the object under cursor (provides as an argument)

        @param parentNodesOfObjUnderMouse: Tuple containing the
                parent chunk(s), of which, the object
                under mouse  is a part of,  or, some other node such as a
                DnaStrand Or DnaSegment etc which the user probably wants to
                operate on.
        @type: Tuple

        @see: self.chunkLeftUp()
        @see: self.leftShiftCntlUp() which calls this method.

        @see: BuildDna_GraphicsMode._do_leftShiftCntlUp_delete_operations()
        """
        obj = objUnderMouse
        if obj is self.o.selobj:
            if parentNodesOfObjUnderMouse:
                try:
                    for node in parentNodesOfObjUnderMouse:
                        node.kill()
                except:
                    print_compact_traceback(
                        "Error deleting objects %r" % parentNodesOfObjUnderMouse)
Exemplo n.º 40
0
    def _draw_jig(self, glpane, color, highlighted=False):
        """
        Draw a linear motor as a long box along the axis, with a thin cylinder (spoke) to each atom.
        """
        glPushMatrix()
        try:
            glTranslatef( self.center[0], self.center[1], self.center[2])
            q = self.quat
            glRotatef( q.angle*180.0/pi, q.x, q.y, q.z)

            orig_center = V(0.0, 0.0, 0.0)
            drawbrick(color, orig_center, self.axis, 
                      self.length, self.width, self.width, 
                      opacity = self.opacity)
            
            drawLinearSign((0,0,0), orig_center, self.axis, self.length, self.width, self.width)
                # (note: drawLinearSign uses a small depth offset so that arrows are slightly in front of brick)
                # [bruce comment 060302, a guess from skimming drawLinearSign's code]
            for a in self.atoms[:]:
                drawcylinder(color, orig_center, 
                             a.posn()-self.center, 
                             self.sradius, 
                             opacity = self.opacity)
        except:
            #bruce 060208 protect OpenGL stack from exception analogous to that seen for RotaryMotor in bug 1445
            print_compact_traceback("exception in LinearMotor._draw, continuing: ")
        glPopMatrix()
Exemplo n.º 41
0
    def leftDown(self, event):
        """
        Event handler for all LMB press events.
        """
        # Note: the code of SelectAtoms_GraphicsMode and SelectChunks_GraphicsMode .leftDown methods
        # is very similar, so I'm removing the redundant comments from
        # this one (SelectChunks_GraphicsMode); see SelectAtoms_GraphicsMode to find them.
        # [bruce 071022]

        self.set_cmdname('ChunkClick')
            # TODO: this should be set again later (during the same drag)
            # to a more specific command name.

        self.reset_drag_vars()
        env.history.statusbar_msg(" ")

        self.LMB_press_event = QMouseEvent(event)

        self.LMB_press_pt_xy = (event.pos().x(), event.pos().y())

        obj = self.get_obj_under_cursor(event)
        if obj is None: # Cursor over empty space.
            self.emptySpaceLeftDown(event)
            return

        method = getattr(obj, 'leftClick', None)
        if method:
            # This looks identical to the code from SelectAtoms_GraphicsMode.leftDown
            # which I just split into a separate method call_leftClick_method,
            # so I will shortly move that into our common superclass and
            # call it here instead of duplicating that code.
            #[bruce 071022 comment]
            gl_event_info = self.dragstart_using_GL_DEPTH( event,
                                                           more_info = True)
            self._drag_handler_gl_event_info = gl_event_info
            farQ_junk, hitpoint, wX, wY, depth, farZ = gl_event_info
            del wX, wY, depth, farZ
            try:
                retval = method(hitpoint, event, self)
            except:
                print_compact_traceback("exception ignored "\
                                        "in %r.leftClick: " % (obj,))
                return
            self.drag_handler = retval # needed even if this is None
            if self.drag_handler is not None:
                #the psuedoMoveMode left down might still be needed even when
                #drag handler is not None
                #(especially to get the self._leftDrag_movables)
                self._leftDown_preparation_for_dragging(obj, event)
                self.dragHandlerSetup(self.drag_handler, event)
                return

        self.doObjectSpecificLeftDown(obj, event)

        if self.glpane.modkeys is None:
            self._leftDown_preparation_for_dragging(obj, event)

        self.w.win_update()

        return # from SelectChunks_GraphicsMode.leftDown
Exemplo n.º 42
0
 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
Exemplo n.º 43
0
    def leftUp(self, event):
        """
        Event handler for Left Mouse button left-up event
        @see: Line_Command._f_results_for_caller_and_prepare_for_new_input()
        """

        if len(self.command.mouseClickPoints) == 3:
            self.endPoint2 = None
            self.command.rotateAboutPoint()
            try:
                self.command._f_results_for_caller_and_prepare_for_new_input()
            except AttributeError:
                print_compact_traceback(
                    "bug: command %s has no attr"\
                    "'_f_results_for_caller_and_prepare_for_new_input'.")
                self.command.mouseClickPoints = []
                self.resetVariables()

            self.glpane.gl_update()
            return

        assert len(
            self.command.mouseClickPoints) <= self.command.mouseClickLimit

        if len(self.command.mouseClickPoints) == self.command.mouseClickLimit:
            self.endPoint2 = None
            self._snapOn = False
            self._standardAxisVectorForDrawingSnapReference = None
            self.glpane.gl_update()
            self.command.rotateAboutPoint()
            #Exit this GM's command (i.e. the command 'RotateAboutPoint')
            self.command.command_Done()
        return
Exemplo n.º 44
0
 def get_atomtype_from_MMKit(self):
     """
     Return the current atomtype selected in the MMKit.
     
     Note: This appears to be very similar (if not completely redundant) to 
     pastable_atomtype() in this file. 
     """
     elm = self.propMgr.elementChooser.getElement()
     atomtype = None
     if len(elm.atomtypes) > 1: 
         try:
             # Obtain the hybrid index from the hybrid button group, not
             # the obsolete hybrid combobox. Fixes bug 2304. Mark 2007-06-20
             hybrid_name = self.propMgr.elementChooser.atomType
             atype = elm.find_atomtype(hybrid_name)
             if atype is not None:
                 atomtype = atype
         except:
             print_compact_traceback("exception (ignored): ") 
         pass
     if atomtype is not None and atomtype.element is elm:
         return atomtype
         
     # For element that doesn't support hybridization
     return elm.atomtypes[0]    
Exemplo n.º 45
0
 def draw_after_highlighting(self, 
                             glpane, 
                             dispdef, 
                             pickCheckOnly = False):
     """
     For ESPImage class, this does all the drawing. (Does it after main
     drawing code is finished drawing.) This method ensures that the 
     ESP image jig gets selected even when you click inside the 
     rectangular box (i.e. not just along the edges of the box).
     """
     anythingDrawn = False
     if self.hidden:
         return anythingDrawn
     
     self.pickCheckOnly = pickCheckOnly        
     anythingDrawn = True
     glPushName(self.glname)
     try:
         self._draw(glpane, dispdef) #calls self._draw_jig()
     except:
         anythingDrawn = False
         msg = "ignoring exception when drawing Jig %r" % self
         print_compact_traceback(msg + ": ")
     glPopName()
     
     return anythingDrawn
Exemplo n.º 46
0
    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
Exemplo n.º 47
0
    def get_atomtype_from_MMKit(self):
        """
        Return the current atomtype selected in the MMKit.
        
        Note: This appears to be very similar (if not completely redundant) to 
        pastable_atomtype() in this file. 
        """
        elm = self.propMgr.elementChooser.getElement()
        atomtype = None
        if len(elm.atomtypes) > 1:
            try:
                # Obtain the hybrid index from the hybrid button group, not
                # the obsolete hybrid combobox. Fixes bug 2304. Mark 2007-06-20
                hybrid_name = self.propMgr.elementChooser.atomType
                atype = elm.find_atomtype(hybrid_name)
                if atype is not None:
                    atomtype = atype
            except:
                print_compact_traceback("exception (ignored): ")
            pass
        if atomtype is not None and atomtype.element is elm:
            return atomtype

        # For element that doesn't support hybridization
        return elm.atomtypes[0]
Exemplo n.º 48
0
    def draw_after_highlighting(self, glpane, dispdef, pickCheckOnly=False):
        """
        For ESPImage class, this does all the drawing. (does it after main
        drawing code is finished drawing) . This method ensures that the 
        ESP image jig gets selected even when you click inside the 
        rectangular box (i.e. not just along the edgets of the box)
        @see: GraphicsMode.Draw_after_highlighting()
        @see: Node.draw_after_highlighting()
        @see:Plane.draw_after_highlighting()
        """
        anythingDrawn = False
        if self.hidden:
            return anythingDrawn

        self.pickCheckOnly = pickCheckOnly
        try:
            anythingDrawn = True
            glPushName(self.glname)
            self._draw(glpane, dispdef)  #calls self._draw_jig()
        except:
            anythingDrawn = False
            glPopName()
            print_compact_traceback(
                "ignoring exception when drawing Jig %r: " % self)
        else:
            glPopName()

        return anythingDrawn
Exemplo n.º 49
0
    def pastable_atomtype(self):
        """
        Return the current pastable atomtype.

        [REVIEW: This appears to be very similar (if not completely redundant) to 
        get_atomtype_from_MMKit() in this file. This is still used as of 071025;
        that one is called only by the slot transmutePressed -- can that still
        be called?]
        """
        #e we might extend this to remember a current atomtype per element
        #... not sure if useful
        current_element = self.pastable_element()
        if len(current_element.atomtypes) > 1:
            if self.propMgr and hasattr(self.propMgr, 'elementChooser'):
                try:
                    hybrid_name = self.propMgr.elementChooser.atomType
                    atype = current_element.find_atomtype(hybrid_name)
                    if atype is not None:
                        self._pastable_atomtype = atype
                except:
                    print_compact_traceback("exception (ignored): ")
                pass
            else:
                # we're presumably a subclass with no propMgr or a different one
                pass
        if self._pastable_atomtype is not None and self._pastable_atomtype.element is current_element:
            return self._pastable_atomtype
        self._pastable_atomtype = current_element.atomtypes[0]
        return self._pastable_atomtype
Exemplo n.º 50
0
    def leftDrag(self, event):
        """
        Translate the selected object(s):
        - in the plane of the screen following the mouse,
        - or slide and rotate along the an axis

        @param event: The mouse left drag event.
        @type  event: QMouseEvent instance
        """
        _superclass.leftDrag(self, event)

        if self.cursor_over_when_LMB_pressed == 'Empty Space':
            #The _superclass.leftDrag considers this condition.
            #So simply return and don't go further. Fixes bug 2607
            return

        if self.leftDownType in ['TRANSLATE', 'A_TRANSLATE']:
            try:
                self.leftDragTranslation(event)
                return
            except:
                msg1 = "Controlled translation not allowed. "
                msg2 = "Key must be pressed before starting the drag"
                env.history.statusbar_msg(msg1 + msg2)
                if debug_flags.atom_debug:
                    msg3 = "Error occured in modifyMode.leftDragTranslation."
                    msg4 = "Possibly due to a key press that activated. "
                    msg5 = "Rotate groupbox. Aborting drag operation"
                    print_compact_traceback(msg3 + msg4 + msg5)
Exemplo n.º 51
0
def _find_or_make_nanorex_dir_0():
    """
    private helper function for find_or_make_Nanorex_directory
    """
    #Create the temporary file directory if not exist [by huaicai ~041201]
    # bruce 041202 comments about future changes to this code:
    # - we'll probably rename this, sometime before Alpha goes out,
    #   since its purpose will become more user-visible and general.
    # - it might be good to create a README file in the directory
    #   when we create it. And maybe to tell the user we created it,
    #   in a dialog.
    # - If creating it fails, we might want to create it in /tmp
    #   (or wherever some python function says is a good temp dir)
    #   rather than leaving an ususable path in tmpFilePath. This
    #   could affect someone giving a demo on a strange machine!
    # - If it exists already, we might want to test that it's a
    #   directory and is writable. If we someday routinely create
    #   a new file in it for each session, that will be a good-
    #   enough test.
    tmpFilePath = os.path.normpath(os.path.expanduser("~/Nanorex/"))
    if not os.path.exists(tmpFilePath):
        try:
            os.mkdir(tmpFilePath)
        except:
            #bruce 041202 fixed minor bug in next line; removed return statement
            print_compact_traceback("exception in creating temporary directory: \"%s\"" % tmpFilePath)
            #bruce 050104 new feature [needs to be made portable so it works on Windows ###@@@]
            os_tempdir = "/tmp"
            print "warning: using \"%s\" for temporary directory, since \"%s\" didn't work" % (os_tempdir, tmpFilePath)
            tmpFilePath = os_tempdir
    #e now we should create or update a README file in there [bruce 050104]
    return tmpFilePath