コード例 #1
0
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
コード例 #2
0
ファイル: controls.py プロジェクト: vcsrc/nanoengineer
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
コード例 #3
0
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
コード例 #4
0
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
コード例 #5
0
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
コード例 #6
0
ファイル: Rect.py プロジェクト: elfion/nanoengineer
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
コード例 #7
0
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
コード例 #8
0
ファイル: transforms.py プロジェクト: vcsrc/nanoengineer
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
コード例 #9
0
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
コード例 #10
0
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
コード例 #11
0
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
コード例 #12
0
ファイル: Rect.py プロジェクト: elfion/nanoengineer
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
コード例 #13
0
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
コード例 #14
0
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
コード例 #15
0
ファイル: images.py プロジェクト: vcsrc/nanoengineer
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
コード例 #16
0
ファイル: demo_drag.py プロジェクト: vcsrc/nanoengineer
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
コード例 #17
0
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
コード例 #18
0
ファイル: staterefs.py プロジェクト: vcsrc/nanoengineer
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
コード例 #19
0
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
コード例 #20
0
ファイル: Set.py プロジェクト: elfion/nanoengineer
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
コード例 #21
0
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
コード例 #22
0
ファイル: ModelNode.py プロジェクト: vcsrc/nanoengineer
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
コード例 #23
0
ファイル: Rect.py プロジェクト: elfion/nanoengineer
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
コード例 #24
0
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
コード例 #25
0
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
コード例 #26
0
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
コード例 #27
0
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
コード例 #28
0
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
コード例 #29
0
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
コード例 #30
0
ファイル: Rect.py プロジェクト: elfion/nanoengineer
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