<commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.

from __future__ import division, print_function

import numpy as np
from time import sleep

from ._default_app import default_app
from ..util.event import EmitterGroup, Event
from ..util.ptime import time
from .base import BaseCanvasBackend as CanvasBackend  # noqa

# todo: add functions for asking about current mouse/keyboard state
# todo: add hover enter/exit events
# todo: add focus events

def _gloo_initialize(event):
    from ..gloo import gl_initialize
    gl_initialize()

class Canvas(object):
    """Representation of a GUI element with an OpenGL context

    Receives the following events:
    initialize, resize, paint, mouse_press, mouse_release, mouse_move,
    mouse_wheel, key_press, key_release, stylus, touch, close

    Arguments
    ---------
    title : str
        The widget title
    size : (width, height)
        The size of the window.
    position : (x, y)
        The position of the window in screen coordinates.
    show : bool
        Whether to show the widget immediately. Default False.
    autoswap : bool
        Whether to swap the buffers automatically after a paint event.
        Default True.
    app : Application
        Give vispy Application instance to use as a backend.
        (vispy.app is used by default.)
    create_native : bool
        Whether to create the widget immediately. Default True.
    init_gloo : bool
        Initialize standard values in gloo (e.g., ``GL_POINT_SPRITE``).
    native_args : iterable
        Extra arguments to use when creating the native widget.
    native_kwargs : dict
        The keyword arguments to use when creaing the native widget.
    """

    def __init__(self, title='Vispy canvas', size=(800, 600), position=None,
                 show=False, autoswap=True, app=None, create_native=True,
                 init_gloo=True, native_args=None, native_kwargs=None):
        self.events = EmitterGroup(source=self,
                                   initialize=Event,
                                   resize=ResizeEvent,
                                   paint=PaintEvent,
                                   mouse_press=MouseEvent,
                                   mouse_release=MouseEvent,
                                   mouse_move=MouseEvent,
                                   mouse_wheel=MouseEvent,
                                   key_press=KeyEvent,
                                   key_release=KeyEvent,
                                   stylus=Event,
                                   touch=Event,
                                   close=Event,
                                   )

        # Initialize backend attribute
        self._backend = None
        if init_gloo:
            self.events.initialize.connect(_gloo_initialize)
        self._init_gloo = init_gloo
        self._native_args = native_args or ()
        self._native_kwargs = native_kwargs or {}

        # Collect arguments that we will use later
        self._our_kwargs = {}
        self._our_kwargs['title'] = title
        self._our_kwargs['size'] = size
        self._our_kwargs['position'] = position
        self._our_kwargs['show'] = show
        self._our_kwargs['autoswap'] = autoswap

        # Initialise some values
        self._title = ''
        self._frame_count = 0
        self._fps = 0
        self._basetime = time()
        self._fps_callback = None

        # Get app instance
        self._app = default_app if app is None else app

        # Create widget now
        if create_native:
            self.create_native()

    def create_native(self):
        """ Create the native widget if not already done so. If the widget
        is already created, this function does nothing.
        """
        if self._backend is None:
            # Make sure that the app is active
            self._app.use()
            self._app.native
            # Instantiate the backend with the right class
            self._set_backend(
                self._app.backend_module.CanvasBackend(*self._native_args,
                                                       **self._native_kwargs))

    def _set_backend(self, backend):
        self._backend = backend
        if backend is not None:
            backend._vispy_canvas = self
        else:
            return

        # Initialize it
        self.title = self._our_kwargs['title']
        self.size = self._our_kwargs['size']
        if self._our_kwargs['position']:
            self.position = self._our_kwargs['position']
        if self._our_kwargs['autoswap']:
            fun = lambda x: self._backend._vispy_swap_buffers()
            self.events.paint.callbacks.append(fun)  # Append callback to end
        if self._our_kwargs['show']:
            self.show()

    def _warmup(self):
        """Hack workaround for slow startup"""
        from vispy.gloo import gl
        for _ in range(10):
            self._backend._vispy_set_current()
            sleep(0.05)
            gl.glClear(gl.GL_COLOR_BUFFER_BIT)
            gl.glFinish()
            self.app.process_events()

    @property
    def app(self):
        """ The vispy Application instance on which this Canvas is based.
        """
        return self._app

    @property
    def native(self):
        """ The native widget object on which this Canvas is based.
        """
        return self._backend._vispy_get_native_canvas()

    def connect(self, fun):
        """ Connect a function to an event. The name of the function
        should be on_X, with X the name of the event (e.g. 'on_paint').

        This method is typically used as a decorater on a function
        definition for an event handler.
        """
        # Get and check name
        name = fun.__name__
        if not name.startswith('on_'):
            raise ValueError('When connecting a function based on its name, '
                             'the name should start with "on_"')
        eventname = name[3:]
        # Get emitter
        try:
            emitter = self.events[eventname]
        except KeyError:
            raise ValueError(
                'Event "%s" not available on this canvas.' %
                eventname)
        # Connect
        emitter.connect(fun)

    # ---------------------------------------------------------------- size ---
    @property
    def size(self):
        """ The size of canvas/window """
        return self._backend._vispy_get_size()

    @size.setter
    def size(self, size):
        return self._backend._vispy_set_size(size[0], size[1])

    # ------------------------------------------------------------ position ---
    @property
    def position(self):
        """ The position of canvas/window relative to screen """
        return self._backend._vispy_get_position()

    @position.setter
    def position(self, position):
        assert len(position) == 2
        return self._backend._vispy_set_position(position[0], position[1])

    # --------------------------------------------------------------- title ---
    @property
    def title(self):
        """ The title of canvas/window """
        return self._title

    @title.setter
    def title(self, title):
        self._title = title
        self._backend._vispy_set_title(title)

    # --------------------------------------------------------------- fps ---
    @property
    def fps(self):
        """ The fps of canvas/window, measured as the rate that events.paint
        is emitted. """
        return self._fps

    def swap_buffers(self):
        """ Swap GL buffers such that the offscreen buffer becomes visible.
        """
        self._backend._vispy_swap_buffers()

    def resize(self, w, h):
        """ Resize the canvas given size """
        return self._backend._vispy_set_size(w, h)

    def move(self, x, y):
        """ Move the widget or window to the given position """
        self._backend._vispy_set_position(x, y)

    def show(self, visible=True):
        """ Show (or hide) the canvas """
        return self._backend._vispy_set_visible(visible)

    def update(self):
        """ Inform the backend that the Canvas needs to be repainted """
        if self._backend is not None:
            return self._backend._vispy_update()
        else:
            return

    def close(self):
        """ Close the canvas """
        if self._backend is not None:
            self._backend._vispy_close()

    def _update_fps(self, event):
        """ Updates the fps after every window and resets the basetime
        and frame count to current time and 0, respectively
        """
        self._frame_count += 1
        diff = time() - self._basetime
        if (diff > self._fps_window):
            self._fps = self._frame_count/diff
            self._basetime = time()
            self._frame_count = 0
            self._fps_callback(self.fps)

    def measure_fps(self, window=1, callback=print):
        """ Sets the update window, connects the paint event to
        update_fps and sets the callback function
        If no callback is passed, measurement stops
        """
        # Connect update_fps function to paint
        self.events.paint.disconnect(self._update_fps)
        if callback:
            self._fps_window = window
            self.events.paint.connect(self._update_fps)
            self._fps_callback = callback
        else:
            self._fps_callback = None

    def __repr__(self):
        return ('<Vispy canvas (%s backend) at %s>'
                % (self.app.backend_name, hex(id(self))))

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    # def mouse_event(self, event):
        #"""Called when a mouse input event has occurred (the mouse has moved,
        # a button was pressed/released, or the wheel has moved)."""

    # def key_event(self, event):
        #"""Called when a keyboard event has occurred (a key was pressed or
        # released while the canvas has focus)."""

    # def touch_event(self, event):
        #"""Called when the user touches the screen over a Canvas.

        # Event properties:
        #     event.touches
        #     [ (x,y,pressure), ... ]
        #"""

    # def stylus_event(self, event):
        #"""Called when a stylus has been used to interact with the Canvas.

        # Event properties:
        #     event.device
        #     event.pos  (x,y)
        #     event.pressure
        #     event.angle
        #"""

    # def initialize_event(self, event):
        #"""Called when the OpenGL context is initialy made available for this
        # Canvas."""

    # def resize_event(self, event):
        #"""Called when the Canvas is resized.

        # Event properties:
        #     event.size  (w,h)
        #"""

    # def paint_event(self, event):
        #"""Called when all or part of the Canvas needs to be repainted.

        # Event properties:
        #     event.region  (x,y,w,h) region of Canvas requiring repaint
        #"""

# Event subclasses specific to the Canvas
class MouseEvent(Event):

    """ Class describing mouse events.

    Note that each event object has an attribute for each of the input
    arguments listed below.

    Input arguments
    ---------------
    type : str
       String indicating the event type (e.g. mouse_press, key_release)
    pos : (int, int)
        The position of the mouse (in screen coordinates).
    button : int
        The button that generated this event (can be None).
        Left=1, right=2, middle=3.
    buttons : [int, ...]
        The list of buttons depressed during this event.
    modifiers : tuple of Key instances
        Tuple that specifies which modifier keys were pressed down at the
        time of the event (shift, control, alt, meta).
    delta : (float, float)
        The amount of scrolling in horizontal and vertical direction. One
        "tick" corresponds to a delta of 1.0.
    press_event : MouseEvent
        The press event that was generated at the start of the current drag,
        if any.
    last_event : MouseEvent
        The MouseEvent immediately preceding the current event. During drag
        operations, all generated events retain their last_event properties,
        allowing the entire drag to be reconstructed.
    native : object (optional)
       The native GUI event object
    **kwds : keyword arguments
        All extra keyword arguments become attributes of the event object.

    """

    def __init__(self, type, pos=None, button=None, buttons=None,
                 modifiers=None, delta=None, last_event=None, press_event=None,
                 **kwds):
        Event.__init__(self, type, **kwds)
        self._pos = (0, 0) if (pos is None) else (pos[0], pos[1])
        self._button = int(button) if (button is not None) else 0
        self._buttons = [] if (buttons is None) else buttons
        self._modifiers = tuple(modifiers or ())
        self._delta = (0.0, 0.0) if (delta is None) else (delta[0], delta[1])
        self._last_event = last_event
        self._press_event = press_event

    @property
    def pos(self):
        return self._pos

    @property
    def button(self):
        return self._button

    @property
    def buttons(self):
        return self._buttons

    @property
    def modifiers(self):
        return self._modifiers

    @property
    def delta(self):
        return self._delta

    @property
    def press_event(self):
        return self._press_event

    @property
    def last_event(self):
        return self._last_event

    def _forget_last_event(self):
        # Needed to break otherwise endless last-event chains
        self._last_event = None

    @property
    def is_dragging(self):
        """ Indicates whether this event is part of a mouse drag operation.
        """
        return self.press_event is not None

    def drag_events(self):
        """ Return a list of all mouse events in the current drag operation.

        Returns None if there is no current drag operation.
        """
        if not self.is_dragging:
            return None

        event = self
        events = []
        while True:
            # mouse_press events can only be the start of a trail
            if event is None or event.type == 'mouse_press':
                break
            events.append(event)
            event = event.last_event

        return events[::-1]

    def trail(self):
        """ Return an (N, 2) array of mouse coordinates for every event in the
        current mouse drag operation.

        Returns None if there is no current drag operation.
        """
        events = self.drag_events()
        if events is None:
            return None

        trail = np.empty((len(events), 2), dtype=int)
        for i, ev in enumerate(events):
            trail[i] = ev.pos

        return trail

class KeyEvent(Event):

    """ Class describing mouse events.

    Note that each event object has an attribute for each of the input
    arguments listed below.

    Input arguments
    ---------------
    type : str
       String indicating the event type (e.g. mouse_press, key_release)
    key : vispy.keys.Key instance
        The Key object for this event. Can be compared to string names.
    text : str
        The text representation of the key (can be an empty string).
    modifiers : tuple of Key instances
        Tuple that specifies which modifier keys were pressed down at the
        time of the event (shift, control, alt, meta).
    native : object (optional)
       The native GUI event object
    **kwds : keyword arguments
        All extra keyword arguments become attributes of the event object.
    """

    def __init__(self, type, key=None, text='', modifiers=None, **kwds):
        Event.__init__(self, type, **kwds)
        self._key = key
        self._text = text
        self._modifiers = tuple(modifiers or ())

    @property
    def key(self):
        return self._key

    @property
    def text(self):
        return self._text

    @property
    def modifiers(self):
        return self._modifiers

class ResizeEvent(Event):

    """ Class describing canvas resize events.

    Note that each event object has an attribute for each of the input
    arguments listed below.

    Input arguments
    ---------------
    type : str
       String indicating the event type (e.g. mouse_press, key_release)
    size : (int, int)
        The new size of the Canvas.
    native : object (optional)
       The native GUI event object
    **kwds : extra keyword arguments
        All extra keyword arguments become attributes of the event object.
    """

    def __init__(self, type, size=None, **kwds):
        Event.__init__(self, type, **kwds)
        self._size = tuple(size)

    @property
    def size(self):
        return self._size

class PaintEvent(Event):

    """ Class describing canvas paint events.
    This type of event is sent to Canvas.events.paint when a repaint
    is required.

    Note that each event object has an attribute for each of the input
    arguments listed below.

    Input arguments
    ---------------
    type : str
       String indicating the event type (e.g. mouse_press, key_release)
    region : (int, int, int, int) or None
        The region of the canvas which needs to be repainted (x, y, w, h).
        If None, the entire canvas must be repainted.
    native : object (optional)
       The native GUI event object
    **kwds : extra keyword arguments
        All extra keyword arguments become attributes of the event object.
    """

    def __init__(self, type, region=None, **kwds):
        Event.__init__(self, type, **kwds)
        self._region = region

    @property
    def region(self):
        return self._region
<commit_msg>FIX?: Tests<commit_after># -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.

from __future__ import division, print_function

import numpy as np
from time import sleep

from ._default_app import default_app
from ..util.event import EmitterGroup, Event
from ..util.ptime import time
from .base import BaseCanvasBackend as CanvasBackend  # noqa

# todo: add functions for asking about current mouse/keyboard state
# todo: add hover enter/exit events
# todo: add focus events

def _gloo_initialize(event):
    from ..gloo import gl_initialize
    gl_initialize()

class Canvas(object):
    """Representation of a GUI element with an OpenGL context

    Receives the following events:
    initialize, resize, paint, mouse_press, mouse_release, mouse_move,
    mouse_wheel, key_press, key_release, stylus, touch, close

    Arguments
    ---------
    title : str
        The widget title
    size : (width, height)
        The size of the window.
    position : (x, y)
        The position of the window in screen coordinates.
    show : bool
        Whether to show the widget immediately. Default False.
    autoswap : bool
        Whether to swap the buffers automatically after a paint event.
        Default True.
    app : Application
        Give vispy Application instance to use as a backend.
        (vispy.app is used by default.)
    create_native : bool
        Whether to create the widget immediately. Default True.
    init_gloo : bool
        Initialize standard values in gloo (e.g., ``GL_POINT_SPRITE``).
    native_args : iterable
        Extra arguments to use when creating the native widget.
    native_kwargs : dict
        The keyword arguments to use when creaing the native widget.
    """

    def __init__(self, title='Vispy canvas', size=(800, 600), position=None,
                 show=False, autoswap=True, app=None, create_native=True,
                 init_gloo=True, native_args=None, native_kwargs=None):
        self.events = EmitterGroup(source=self,
                                   initialize=Event,
                                   resize=ResizeEvent,
                                   paint=PaintEvent,
                                   mouse_press=MouseEvent,
                                   mouse_release=MouseEvent,
                                   mouse_move=MouseEvent,
                                   mouse_wheel=MouseEvent,
                                   key_press=KeyEvent,
                                   key_release=KeyEvent,
                                   stylus=Event,
                                   touch=Event,
                                   close=Event,
                                   )

        # Initialize backend attribute
        self._backend = None
        if init_gloo:
            self.events.initialize.connect(_gloo_initialize)
        self._init_gloo = init_gloo
        self._native_args = native_args or ()
        self._native_kwargs = native_kwargs or {}

        # Collect arguments that we will use later
        self._our_kwargs = {}
        self._our_kwargs['title'] = title
        self._our_kwargs['size'] = size
        self._our_kwargs['position'] = position
        self._our_kwargs['show'] = show
        self._our_kwargs['autoswap'] = autoswap

        # Initialise some values
        self._title = ''
        self._frame_count = 0
        self._fps = 0
        self._basetime = time()
        self._fps_callback = None

        # Get app instance
        self._app = default_app if app is None else app

        # Create widget now
        if create_native:
            self.create_native()

    def create_native(self):
        """ Create the native widget if not already done so. If the widget
        is already created, this function does nothing.
        """
        if self._backend is None:
            # Make sure that the app is active
            self._app.use()
            self._app.native
            # Instantiate the backend with the right class
            self._set_backend(
                self._app.backend_module.CanvasBackend(*self._native_args,
                                                       **self._native_kwargs))

    def _set_backend(self, backend):
        self._backend = backend
        if backend is not None:
            backend._vispy_canvas = self
        else:
            return

        # Initialize it
        self.title = self._our_kwargs['title']
        self.size = self._our_kwargs['size']
        if self._our_kwargs['position']:
            self.position = self._our_kwargs['position']
        if self._our_kwargs['autoswap']:
            fun = lambda x: self._backend._vispy_swap_buffers()
            self.events.paint.callbacks.append(fun)  # Append callback to end
        if self._our_kwargs['show']:
            self.show()

    def _warmup(self):
        """Hack workaround for slow startup"""
        from vispy.gloo import gl
        for _ in range(10):
            self._backend._vispy_set_current()
            sleep(0.02)
            gl.glClear(gl.GL_COLOR_BUFFER_BIT)
            gl.glFinish()
            self.app.process_events()

    @property
    def app(self):
        """ The vispy Application instance on which this Canvas is based.
        """
        return self._app

    @property
    def native(self):
        """ The native widget object on which this Canvas is based.
        """
        return self._backend._vispy_get_native_canvas()

    def connect(self, fun):
        """ Connect a function to an event. The name of the function
        should be on_X, with X the name of the event (e.g. 'on_paint').

        This method is typically used as a decorater on a function
        definition for an event handler.
        """
        # Get and check name
        name = fun.__name__
        if not name.startswith('on_'):
            raise ValueError('When connecting a function based on its name, '
                             'the name should start with "on_"')
        eventname = name[3:]
        # Get emitter
        try:
            emitter = self.events[eventname]
        except KeyError:
            raise ValueError(
                'Event "%s" not available on this canvas.' %
                eventname)
        # Connect
        emitter.connect(fun)

    # ---------------------------------------------------------------- size ---
    @property
    def size(self):
        """ The size of canvas/window """
        return self._backend._vispy_get_size()

    @size.setter
    def size(self, size):
        return self._backend._vispy_set_size(size[0], size[1])

    # ------------------------------------------------------------ position ---
    @property
    def position(self):
        """ The position of canvas/window relative to screen """
        return self._backend._vispy_get_position()

    @position.setter
    def position(self, position):
        assert len(position) == 2
        return self._backend._vispy_set_position(position[0], position[1])

    # --------------------------------------------------------------- title ---
    @property
    def title(self):
        """ The title of canvas/window """
        return self._title

    @title.setter
    def title(self, title):
        self._title = title
        self._backend._vispy_set_title(title)

    # --------------------------------------------------------------- fps ---
    @property
    def fps(self):
        """ The fps of canvas/window, measured as the rate that events.paint
        is emitted. """
        return self._fps

    def swap_buffers(self):
        """ Swap GL buffers such that the offscreen buffer becomes visible.
        """
        self._backend._vispy_swap_buffers()

    def resize(self, w, h):
        """ Resize the canvas given size """
        return self._backend._vispy_set_size(w, h)

    def move(self, x, y):
        """ Move the widget or window to the given position """
        self._backend._vispy_set_position(x, y)

    def show(self, visible=True):
        """ Show (or hide) the canvas """
        return self._backend._vispy_set_visible(visible)

    def update(self):
        """ Inform the backend that the Canvas needs to be repainted """
        if self._backend is not None:
            return self._backend._vispy_update()
        else:
            return

    def close(self):
        """ Close the canvas """
        if self._backend is not None:
            self._backend._vispy_close()
            self.app.process_events()

    def _update_fps(self, event):
        """ Updates the fps after every window and resets the basetime
        and frame count to current time and 0, respectively
        """
        self._frame_count += 1
        diff = time() - self._basetime
        if (diff > self._fps_window):
            self._fps = self._frame_count/diff
            self._basetime = time()
            self._frame_count = 0
            self._fps_callback(self.fps)

    def measure_fps(self, window=1, callback=print):
        """ Sets the update window, connects the paint event to
        update_fps and sets the callback function
        If no callback is passed, measurement stops
        """
        # Connect update_fps function to paint
        self.events.paint.disconnect(self._update_fps)
        if callback:
            self._fps_window = window
            self.events.paint.connect(self._update_fps)
            self._fps_callback = callback
        else:
            self._fps_callback = None

    def __repr__(self):
        return ('<Vispy canvas (%s backend) at %s>'
                % (self.app.backend_name, hex(id(self))))

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    # def mouse_event(self, event):
        #"""Called when a mouse input event has occurred (the mouse has moved,
        # a button was pressed/released, or the wheel has moved)."""

    # def key_event(self, event):
        #"""Called when a keyboard event has occurred (a key was pressed or
        # released while the canvas has focus)."""

    # def touch_event(self, event):
        #"""Called when the user touches the screen over a Canvas.

        # Event properties:
        #     event.touches
        #     [ (x,y,pressure), ... ]
        #"""

    # def stylus_event(self, event):
        #"""Called when a stylus has been used to interact with the Canvas.

        # Event properties:
        #     event.device
        #     event.pos  (x,y)
        #     event.pressure
        #     event.angle
        #"""

    # def initialize_event(self, event):
        #"""Called when the OpenGL context is initialy made available for this
        # Canvas."""

    # def resize_event(self, event):
        #"""Called when the Canvas is resized.

        # Event properties:
        #     event.size  (w,h)
        #"""

    # def paint_event(self, event):
        #"""Called when all or part of the Canvas needs to be repainted.

        # Event properties:
        #     event.region  (x,y,w,h) region of Canvas requiring repaint
        #"""

# Event subclasses specific to the Canvas
class MouseEvent(Event):

    """ Class describing mouse events.

    Note that each event object has an attribute for each of the input
    arguments listed below.

    Input arguments
    ---------------
    type : str
       String indicating the event type (e.g. mouse_press, key_release)
    pos : (int, int)
        The position of the mouse (in screen coordinates).
    button : int
        The button that generated this event (can be None).
        Left=1, right=2, middle=3.
    buttons : [int, ...]
        The list of buttons depressed during this event.
    modifiers : tuple of Key instances
        Tuple that specifies which modifier keys were pressed down at the
        time of the event (shift, control, alt, meta).
    delta : (float, float)
        The amount of scrolling in horizontal and vertical direction. One
        "tick" corresponds to a delta of 1.0.
    press_event : MouseEvent
        The press event that was generated at the start of the current drag,
        if any.
    last_event : MouseEvent
        The MouseEvent immediately preceding the current event. During drag
        operations, all generated events retain their last_event properties,
        allowing the entire drag to be reconstructed.
    native : object (optional)
       The native GUI event object
    **kwds : keyword arguments
        All extra keyword arguments become attributes of the event object.

    """

    def __init__(self, type, pos=None, button=None, buttons=None,
                 modifiers=None, delta=None, last_event=None, press_event=None,
                 **kwds):
        Event.__init__(self, type, **kwds)
        self._pos = (0, 0) if (pos is None) else (pos[0], pos[1])
        self._button = int(button) if (button is not None) else 0
        self._buttons = [] if (buttons is None) else buttons
        self._modifiers = tuple(modifiers or ())
        self._delta = (0.0, 0.0) if (delta is None) else (delta[0], delta[1])
        self._last_event = last_event
        self._press_event = press_event

    @property
    def pos(self):
        return self._pos

    @property
    def button(self):
        return self._button

    @property
    def buttons(self):
        return self._buttons

    @property
    def modifiers(self):
        return self._modifiers

    @property
    def delta(self):
        return self._delta

    @property
    def press_event(self):
        return self._press_event

    @property
    def last_event(self):
        return self._last_event

    def _forget_last_event(self):
        # Needed to break otherwise endless last-event chains
        self._last_event = None

    @property
    def is_dragging(self):
        """ Indicates whether this event is part of a mouse drag operation.
        """
        return self.press_event is not None

    def drag_events(self):
        """ Return a list of all mouse events in the current drag operation.

        Returns None if there is no current drag operation.
        """
        if not self.is_dragging:
            return None

        event = self
        events = []
        while True:
            # mouse_press events can only be the start of a trail
            if event is None or event.type == 'mouse_press':
                break
            events.append(event)
            event = event.last_event

        return events[::-1]

    def trail(self):
        """ Return an (N, 2) array of mouse coordinates for every event in the
        current mouse drag operation.

        Returns None if there is no current drag operation.
        """
        events = self.drag_events()
        if events is None:
            return None

        trail = np.empty((len(events), 2), dtype=int)
        for i, ev in enumerate(events):
            trail[i] = ev.pos

        return trail

class KeyEvent(Event):

    """ Class describing mouse events.

    Note that each event object has an attribute for each of the input
    arguments listed below.

    Input arguments
    ---------------
    type : str
       String indicating the event type (e.g. mouse_press, key_release)
    key : vispy.keys.Key instance
        The Key object for this event. Can be compared to string names.
    text : str
        The text representation of the key (can be an empty string).
    modifiers : tuple of Key instances
        Tuple that specifies which modifier keys were pressed down at the
        time of the event (shift, control, alt, meta).
    native : object (optional)
       The native GUI event object
    **kwds : keyword arguments
        All extra keyword arguments become attributes of the event object.
    """

    def __init__(self, type, key=None, text='', modifiers=None, **kwds):
        Event.__init__(self, type, **kwds)
        self._key = key
        self._text = text
        self._modifiers = tuple(modifiers or ())

    @property
    def key(self):
        return self._key

    @property
    def text(self):
        return self._text

    @property
    def modifiers(self):
        return self._modifiers

class ResizeEvent(Event):

    """ Class describing canvas resize events.

    Note that each event object has an attribute for each of the input
    arguments listed below.

    Input arguments
    ---------------
    type : str
       String indicating the event type (e.g. mouse_press, key_release)
    size : (int, int)
        The new size of the Canvas.
    native : object (optional)
       The native GUI event object
    **kwds : extra keyword arguments
        All extra keyword arguments become attributes of the event object.
    """

    def __init__(self, type, size=None, **kwds):
        Event.__init__(self, type, **kwds)
        self._size = tuple(size)

    @property
    def size(self):
        return self._size

class PaintEvent(Event):

    """ Class describing canvas paint events.
    This type of event is sent to Canvas.events.paint when a repaint
    is required.

    Note that each event object has an attribute for each of the input
    arguments listed below.

    Input arguments
    ---------------
    type : str
       String indicating the event type (e.g. mouse_press, key_release)
    region : (int, int, int, int) or None
        The region of the canvas which needs to be repainted (x, y, w, h).
        If None, the entire canvas must be repainted.
    native : object (optional)
       The native GUI event object
    **kwds : extra keyword arguments
        All extra keyword arguments become attributes of the event object.
    """

    def __init__(self, type, region=None, **kwds):
        Event.__init__(self, type, **kwds)
        self._region = region

    @property
    def region(self):
        return self._region
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.

from __future__ import division

import weakref

from ..util.event import Event, EmitterGroup
from ..visuals.transforms import (NullTransform, BaseTransform,
                                  ChainTransform, create_transform,
                                  TransformSystem)

class Node(object):
    """ Base class representing an object in a scene.

    A group of nodes connected through parent-child relationships define a
    scenegraph. Nodes may have any number of children.

    Each Node defines a ``transform`` property, which describes the position,
    orientation, scale, etc. of the Node relative to its parent. The Node's
    children inherit this property, and then further apply their own
    transformations on top of that.

    With the ``transform`` property, each Node implicitly defines a "local"
    coordinate system, and the Nodes and edges in the scenegraph can be thought
    of as coordinate systems connected by transformation functions.

    Parameters
    ----------
    parent : Node
        The parent of the Node.
    name : str
        The name used to identify the node.
    """

    # Needed to allow subclasses to repr() themselves before Node.__init__()
    _name = None

    def __init__(self, parent=None, name=None, transforms=None):
        self.name = name
        self._visible = True
        self._canvas = None
        self._document_node = None
        self._scene_node = None
        self._opacity = 1.0
        self._picking = False

        # clippers inherited from parents
        self._clippers = weakref.WeakKeyDictionary()  # {node: clipper}

        # whether this widget should clip its children
        self._clip_children = False
        self._clipper = None

        self.transforms = (TransformSystem() if transforms is None else
                           transforms)

        # Add some events to the emitter groups:
        events = ['canvas_change', 'parent_change', 'children_change',
                  'transform_change', 'mouse_press', 'mouse_move',
                  'mouse_release', 'mouse_wheel', 'key_press', 'key_release']
        # Create event emitter if needed (in subclasses that inherit from
        # Visual, we already have an emitter to share)
        if not hasattr(self, 'events'):
            self.events = EmitterGroup(source=self, auto_connect=True,
                                       update=Event)
        self.events.add(**dict([(ev, Event) for ev in events]))

        self._children = []
        self._transform = NullTransform()
        self._parent = None
        if parent is not None:
            self.parent = parent

        self._document = None

    @property
    def visible(self):
        """ Whether this node should be drawn or not. Only applicable to
        nodes that can be drawn.
        """
        return self._visible

    @visible.setter
    def visible(self, val):
        self._visible = bool(val)
        self.update()

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, n):
        self._name = n

    @property
    def opacity(self):
        return self._opacity

    @opacity.setter
    def opacity(self, o):
        self._opacity = o
        self._update_opacity()

    def _update_opacity(self):
        pass

    def set_clipper(self, node, clipper):
        """Assign a clipper that is inherited from a parent node.

        If *clipper* is None, then remove any clippers for *node*.
        """
        pass

    @property
    def clip_children(self):
        """Boolean indicating whether children of this node will inherit its
        clipper.
        """
        return self._clip_children

    @clip_children.setter
    def clip_children(self, clip):
        if self._clip_children == clip:
            return
        self._clip_children = clip

        for ch in self.children:
            ch.set_clipper(self, self.clipper)

    @property
    def clipper(self):
        """A visual filter that can be used to clip visuals to the boundaries
        of this node.
        """
        return self._clipper

    @property
    def children(self):
        """ A copy of the list of children of this node. Do not add
        items to this list, but use ``x.parent = y`` instead.
        """
        return list(self._children)

    @property
    def parent(self):
        """The parent of this node in the scenegraph.

        Nodes inherit coordinate transformations and some filters (opacity and
        clipping by default) from their parents. Setting this property assigns
        a new parent, changing the topology of the scenegraph.

        May be set to None to remove this node (and its children) from a
        scenegraph.
        """
        if self._parent is None:
            return None
        else:
            return self._parent()

    @parent.setter
    def parent(self, parent):
        if not isinstance(parent, (Node, type(None))):
            raise ValueError('Parent must be Node instance or None (got %s).'
                             % p.__class__.__name__)
        prev = self.parent
        if parent is prev:
            return
        if prev is not None:
            prev._remove_child(self)
            # remove all clippers inherited from parents
            for k in list(self._clippers):
                self.set_clipper(k, None)
        if parent is None:
            self._set_canvas(None)
            self._parent = None
        else:
            self._set_canvas(parent.canvas)
            self._parent = weakref.ref(parent)
            parent._add_child(self)
            # inherit clippers from parents
            p = parent
            while p is not None:
                if p.clip_children:
                    self.set_clipper(p, p.clipper)
                p = p.parent

        self.events.parent_change(new=parent, old=prev)
        self._update_trsys(None)
        self.update()

    def _add_child(self, node):
        self._children.append(node)
        self.events.children_change(added=node)
        node.events.children_change.connect(self.events.children_change)
        self.events.parent_change.connect(node.events.parent_change)

    def _remove_child(self, node):
        self._children.remove(node)
        self.events.children_change(removed=node)
        node.events.children_change.disconnect(self.events.children_change)
        self.events.parent_change.disconnect(node.events.parent_change)

    def on_parent_change(self, event):
        self._scene_node = None

    def is_child(self, child):
        if child in self.children:
            return True
        for c in self.children:
            if c.is_child(child):
                return True
        return False

    @property
    def canvas(self):
        """The canvas in which this node's scenegraph is being drawn.
        """
        if self._canvas is None:
            return None
        else:
            return self._canvas()

    @property
    def document_node(self):
        """The node to be used as the document coordinate system.

        By default, the document node is `self.root_node`.
        """
        if self._document_node is None:
            return self.root_node
        return self._document_node

    @document_node.setter
    def document_node(self, doc):
        self._document_node = doc
        self._update_transform()

    @property
    def scene_node(self):
        """The first ancestor of this node that is a SubScene instance, or self
        if no such node exists.
        """
        if self._scene_node is None:
            from .subscene import SubScene
            p = self.parent
            while True:
                if isinstance(p, SubScene) or p is None:
                    self._scene_node = p
                    break
                p = p.parent
            if self._scene_node is None:
                self._scene_node = self
        return self._scene_node

    @property
    def root_node(self):
        node = self
        while True:
            p = node.parent
            if p is None:
                return node
            node = p

    def _set_canvas(self, c):
        if self._canvas is c:
            return

        old = self._canvas

        # Use canvas/framebuffer transforms from canvas
        if c is None:
            self._canvas = None
        else:
            self._canvas = weakref.ref(c)
            tr = c.transforms
            self.transforms.canvas_transform = tr.canvas_transform
            self.transforms.framebuffer_transform = tr.framebuffer_transform

        # update all children
        for ch in self.children:
            ch._set_canvas(c)

        self.events.canvas_change(old=old, new=c)

    def update(self):
        """
        Emit an event to inform listeners that properties of this Node have
        changed. Also request a canvas update.
        """
        self.events.update()
        c = getattr(self, 'canvas', None)
        if c is not None:
            c.update(node=self)

    @property
    def document(self):
        """ The document is an optional property that is an node representing
        the coordinate system from which this node should make physical
        measurements such as px, mm, pt, in, etc. This coordinate system
        should be used when determining line widths, font sizes, and any
        other lengths specified in physical units.

        The default is None; in this case, a default document is used during
        drawing (usually this is supplied by the SceneCanvas).
        """
        return self._document

    @document.setter
    def document(self, doc):
        if doc is not None and not isinstance(doc, Node):
            raise TypeError("Document property must be Node or None.")
        self._document = doc
        self.update()

    @property
    def transform(self):
        """ The transform that maps the local coordinate frame to the
        coordinate frame of the parent.
        """
        return self._transform

    @transform.setter
    def transform(self, tr):
        # Other nodes might be interested in this information, but turning it
        # on by default is too expensive.
        assert isinstance(tr, BaseTransform)
        self._transform = tr
        self._update_trsys(None)

    def set_transform(self, type_, *args, **kwargs):
        """ Create a new transform of *type* and assign it to this node.

        All extra arguments are used in the construction of the transform.

        Parameters
        ----------
        type_ : str
            The transform type.
        *args : tuple
            Arguments.
        **kwargs : dict
            Keywoard arguments.
        """
        self.transform = create_transform(type_, *args, **kwargs)

    def _update_trsys(self, event):
        for ch in self.children:
            ch._update_trsys(event)
        self.events.transform_change()
        self.update()

    def parent_chain(self):
        """
        Return the list of parents starting from this node. The chain ends
        at the first node with no parents.
        """
        chain = [self]
        while True:
            try:
                parent = chain[-1].parent
            except Exception:
                break
            if parent is None:
                break
            chain.append(parent)
        return chain

    def describe_tree(self, with_transform=False):
        """Create tree diagram of children

        Parameters
        ----------
        with_transform : bool
            If true, add information about node transform types.

        Returns
        ----------
        tree : str
            The tree diagram.
        """
        # inspired by https://github.com/mbr/asciitree/blob/master/asciitree.py
        return self._describe_tree('', with_transform)

    def _describe_tree(self, prefix, with_transform):
        """Helper function to actuall construct the tree"""
        extra = ': "%s"' % self.name if self.name is not None else ''
        if with_transform:
            extra += (' [%s]' % self.transform.__class__.__name__)
        output = ''
        if len(prefix) > 0:
            output += prefix[:-3]
            output += '  +--'
        output += '%s%s\n' % (self.__class__.__name__, extra)

        n_children = len(self.children)
        for ii, child in enumerate(self.children):
            sub_prefix = prefix + ('   ' if ii+1 == n_children else '  |')
            output += child._describe_tree(sub_prefix, with_transform)
        return output

    def common_parent(self, node):
        """
        Return the common parent of two entities

        If the entities have no common parent, return None.

        Parameters
        ----------
        node : instance of Node
            The other node.

        Returns
        -------
        parent : instance of Node | None
            The parent.
        """
        p1 = self.parent_chain()
        p2 = node.parent_chain()
        for p in p1:
            if p in p2:
                return p
        return None

    def node_path_to_child(self, node):
        """Return a list describing the path from this node to a child node

        If *node* is not a (grand)child of this node, then raise RuntimeError.

        Parameters
        ----------
        node : instance of Node
            The child node.

        Returns
        -------
        path : list | None
            The path.
        """
        if node is self:
            return []

        # Go up from the child node as far as we can
        path1 = [node]
        child = node
        while child.parent is not None:
            child = child.parent
            path1.append(child)
            # Early exit
            if child is self:
                return list(reversed(path1))

        # Verify that we're not cut off
        if path1[-1].parent is None:
            raise RuntimeError('%r is not a child of %r' % (node, self))

        def _is_child(path, parent, child):
            path.append(parent)
            if child in parent.children:
                return path
            else:
                for c in parent.children:
                    possible_path = _is_child(path[:], c, child)
                    if possible_path:
                        return possible_path
            return None

        # Search from the parent towards the child
        path2 = _is_child([], self, path1[-1])
        if not path2:
            raise RuntimeError('%r is not a child of %r' % (node, self))

        # Return
        return path2 + list(reversed(path1))

    def node_path(self, node):
        """Return two lists describing the path from this node to another

        Parameters
        ----------
        node : instance of Node
            The other node.

        Returns
        -------
        p1 : list
            First path (see below).
        p2 : list
            Second path (see below).

        Notes
        -----
        The first list starts with this node and ends with the common parent
        between the endpoint nodes. The second list contains the remainder of
        the path from the common parent to the specified ending node.

        For example, consider the following scenegraph::

            A --- B --- C --- D
                   \
                    --- E --- F

        Calling `D.node_path(F)` will return::

            ([D, C, B], [E, F])

        """
        p1 = self.parent_chain()
        p2 = node.parent_chain()
        cp = None
        for p in p1:
            if p in p2:
                cp = p
                break
        if cp is None:
            raise RuntimeError("No single-path common parent between nodes %s "
                               "and %s." % (self, node))

        p1 = p1[:p1.index(cp)+1]
        p2 = p2[:p2.index(cp)][::-1]
        return p1, p2

    def node_path_transforms(self, node):
        """Return the list of transforms along the path to another node.

        The transforms are listed in reverse order, such that the last
        transform should be applied first when mapping from this node to
        the other.

        Parameters
        ----------
        node : instance of Node
            The other node.

        Returns
        -------
        transform : instance of Transform
            The transform.
        """
        a, b = self.node_path(node)
        return ([n.transform.inverse for n in b] +
                [n.transform for n in a[:-1]])[::-1]

    def node_transform(self, node):
        """
        Return the transform that maps from the coordinate system of
        *self* to the local coordinate system of *node*.

        Note that there must be a _single_ path in the scenegraph that connects
        the two entities; otherwise an exception will be raised.

        Parameters
        ----------
        node : instance of Node
            The other node.

        Returns
        -------
        transform : instance of ChainTransform
            The transform.
        """
        return ChainTransform(self.node_path_transforms(node))

    def __repr__(self):
        name = "" if self.name is None else " name="+self.name
        return "<%s%s at 0x%x>" % (self.__class__.__name__, name, id(self))

    @property
    def picking(self):
        """Boolean that determines whether this node (and its children) are
        drawn in picking mode.
        """
        return self._picking

    @picking.setter
    def picking(self, p):
        for c in self.children:
            c.picking = p
        self._picking = p
<commit_msg>perf fix<commit_after># -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.

from __future__ import division

import weakref

from ..util.event import Event, EmitterGroup
from ..visuals.transforms import (NullTransform, BaseTransform,
                                  ChainTransform, create_transform,
                                  TransformSystem)

class Node(object):
    """ Base class representing an object in a scene.

    A group of nodes connected through parent-child relationships define a
    scenegraph. Nodes may have any number of children.

    Each Node defines a ``transform`` property, which describes the position,
    orientation, scale, etc. of the Node relative to its parent. The Node's
    children inherit this property, and then further apply their own
    transformations on top of that.

    With the ``transform`` property, each Node implicitly defines a "local"
    coordinate system, and the Nodes and edges in the scenegraph can be thought
    of as coordinate systems connected by transformation functions.

    Parameters
    ----------
    parent : Node
        The parent of the Node.
    name : str
        The name used to identify the node.
    """

    # Needed to allow subclasses to repr() themselves before Node.__init__()
    _name = None

    def __init__(self, parent=None, name=None, transforms=None):
        self.name = name
        self._visible = True
        self._canvas = None
        self._document_node = None
        self._scene_node = None
        self._opacity = 1.0
        self._picking = False

        # clippers inherited from parents
        self._clippers = weakref.WeakKeyDictionary()  # {node: clipper}

        # whether this widget should clip its children
        self._clip_children = False
        self._clipper = None

        self.transforms = (TransformSystem() if transforms is None else
                           transforms)

        # Add some events to the emitter groups:
        events = ['canvas_change', 'parent_change', 'children_change',
                  'transform_change', 'mouse_press', 'mouse_move',
                  'mouse_release', 'mouse_wheel', 'key_press', 'key_release']
        # Create event emitter if needed (in subclasses that inherit from
        # Visual, we already have an emitter to share)
        if not hasattr(self, 'events'):
            self.events = EmitterGroup(source=self, auto_connect=True,
                                       update=Event)
        self.events.add(**dict([(ev, Event) for ev in events]))

        self._children = []
        self._transform = NullTransform()
        self._parent = None
        if parent is not None:
            self.parent = parent

        self._document = None

    @property
    def visible(self):
        """ Whether this node should be drawn or not. Only applicable to
        nodes that can be drawn.
        """
        return self._visible

    @visible.setter
    def visible(self, val):
        self._visible = bool(val)
        self.update()

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, n):
        self._name = n

    @property
    def opacity(self):
        return self._opacity

    @opacity.setter
    def opacity(self, o):
        self._opacity = o
        self._update_opacity()

    def _update_opacity(self):
        pass

    def set_clipper(self, node, clipper):
        """Assign a clipper that is inherited from a parent node.

        If *clipper* is None, then remove any clippers for *node*.
        """
        pass

    @property
    def clip_children(self):
        """Boolean indicating whether children of this node will inherit its
        clipper.
        """
        return self._clip_children

    @clip_children.setter
    def clip_children(self, clip):
        if self._clip_children == clip:
            return
        self._clip_children = clip

        for ch in self.children:
            ch.set_clipper(self, self.clipper)

    @property
    def clipper(self):
        """A visual filter that can be used to clip visuals to the boundaries
        of this node.
        """
        return self._clipper

    @property
    def children(self):
        """ A copy of the list of children of this node. Do not add
        items to this list, but use ``x.parent = y`` instead.
        """
        return list(self._children)

    @property
    def parent(self):
        """The parent of this node in the scenegraph.

        Nodes inherit coordinate transformations and some filters (opacity and
        clipping by default) from their parents. Setting this property assigns
        a new parent, changing the topology of the scenegraph.

        May be set to None to remove this node (and its children) from a
        scenegraph.
        """
        if self._parent is None:
            return None
        else:
            return self._parent()

    @parent.setter
    def parent(self, parent):
        if not isinstance(parent, (Node, type(None))):
            raise ValueError('Parent must be Node instance or None (got %s).'
                             % p.__class__.__name__)
        prev = self.parent
        if parent is prev:
            return
        if prev is not None:
            prev._remove_child(self)
            # remove all clippers inherited from parents
            for k in list(self._clippers):
                self.set_clipper(k, None)
        if parent is None:
            self._set_canvas(None)
            self._parent = None
        else:
            self._set_canvas(parent.canvas)
            self._parent = weakref.ref(parent)
            parent._add_child(self)
            # inherit clippers from parents
            p = parent
            while p is not None:
                if p.clip_children:
                    self.set_clipper(p, p.clipper)
                p = p.parent

        self.events.parent_change(new=parent, old=prev)
        self._update_trsys(None)
        self.update()

    def _add_child(self, node):
        self._children.append(node)
        self.events.children_change(added=node)
        node.events.children_change.connect(self.events.children_change)
        self.events.parent_change.connect(node.events.parent_change)

    def _remove_child(self, node):
        self._children.remove(node)
        self.events.children_change(removed=node)
        node.events.children_change.disconnect(self.events.children_change)
        self.events.parent_change.disconnect(node.events.parent_change)

    def on_parent_change(self, event):
        self._scene_node = None

    def is_child(self, child):
        if child in self.children:
            return True
        for c in self.children:
            if c.is_child(child):
                return True
        return False

    @property
    def canvas(self):
        """The canvas in which this node's scenegraph is being drawn.
        """
        if self._canvas is None:
            return None
        else:
            return self._canvas()

    @property
    def document_node(self):
        """The node to be used as the document coordinate system.

        By default, the document node is `self.root_node`.
        """
        if self._document_node is None:
            return self.root_node
        return self._document_node

    @document_node.setter
    def document_node(self, doc):
        self._document_node = doc
        self._update_transform()

    @property
    def scene_node(self):
        """The first ancestor of this node that is a SubScene instance, or self
        if no such node exists.
        """
        if self._scene_node is None:
            from .subscene import SubScene
            p = self.parent
            while True:
                if isinstance(p, SubScene) or p is None:
                    self._scene_node = p
                    break
                p = p.parent
            if self._scene_node is None:
                self._scene_node = self
        return self._scene_node

    @property
    def root_node(self):
        node = self
        while True:
            p = node.parent
            if p is None:
                return node
            node = p

    def _set_canvas(self, c):
        if self._canvas is c:
            return

        old = self._canvas

        # Use canvas/framebuffer transforms from canvas
        if c is None:
            self._canvas = None
        else:
            self._canvas = weakref.ref(c)
            tr = c.transforms
            self.transforms.canvas_transform = tr.canvas_transform
            self.transforms.framebuffer_transform = tr.framebuffer_transform

        # update all children
        for ch in self.children:
            ch._set_canvas(c)

        self.events.canvas_change(old=old, new=c)

    def update(self):
        """
        Emit an event to inform listeners that properties of this Node have
        changed. Also request a canvas update.
        """
        self.events.update()
        c = getattr(self, 'canvas', None)
        if c is not None:
            c.update(node=self)

    @property
    def document(self):
        """ The document is an optional property that is an node representing
        the coordinate system from which this node should make physical
        measurements such as px, mm, pt, in, etc. This coordinate system
        should be used when determining line widths, font sizes, and any
        other lengths specified in physical units.

        The default is None; in this case, a default document is used during
        drawing (usually this is supplied by the SceneCanvas).
        """
        return self._document

    @document.setter
    def document(self, doc):
        if doc is not None and not isinstance(doc, Node):
            raise TypeError("Document property must be Node or None.")
        self._document = doc
        self.update()

    @property
    def transform(self):
        """ The transform that maps the local coordinate frame to the
        coordinate frame of the parent.
        """
        return self._transform

    @transform.setter
    def transform(self, tr):
        # Other nodes might be interested in this information, but turning it
        # on by default is too expensive.
        assert isinstance(tr, BaseTransform)
        if tr is not self._transform:
            self._transform = tr
            self._update_trsys(None)

    def set_transform(self, type_, *args, **kwargs):
        """ Create a new transform of *type* and assign it to this node.

        All extra arguments are used in the construction of the transform.

        Parameters
        ----------
        type_ : str
            The transform type.
        *args : tuple
            Arguments.
        **kwargs : dict
            Keywoard arguments.
        """
        self.transform = create_transform(type_, *args, **kwargs)

    def _update_trsys(self, event):
        for ch in self.children:
            ch._update_trsys(event)
        self.events.transform_change()
        self.update()

    def parent_chain(self):
        """
        Return the list of parents starting from this node. The chain ends
        at the first node with no parents.
        """
        chain = [self]
        while True:
            try:
                parent = chain[-1].parent
            except Exception:
                break
            if parent is None:
                break
            chain.append(parent)
        return chain

    def describe_tree(self, with_transform=False):
        """Create tree diagram of children

        Parameters
        ----------
        with_transform : bool
            If true, add information about node transform types.

        Returns
        ----------
        tree : str
            The tree diagram.
        """
        # inspired by https://github.com/mbr/asciitree/blob/master/asciitree.py
        return self._describe_tree('', with_transform)

    def _describe_tree(self, prefix, with_transform):
        """Helper function to actuall construct the tree"""
        extra = ': "%s"' % self.name if self.name is not None else ''
        if with_transform:
            extra += (' [%s]' % self.transform.__class__.__name__)
        output = ''
        if len(prefix) > 0:
            output += prefix[:-3]
            output += '  +--'
        output += '%s%s\n' % (self.__class__.__name__, extra)

        n_children = len(self.children)
        for ii, child in enumerate(self.children):
            sub_prefix = prefix + ('   ' if ii+1 == n_children else '  |')
            output += child._describe_tree(sub_prefix, with_transform)
        return output

    def common_parent(self, node):
        """
        Return the common parent of two entities

        If the entities have no common parent, return None.

        Parameters
        ----------
        node : instance of Node
            The other node.

        Returns
        -------
        parent : instance of Node | None
            The parent.
        """
        p1 = self.parent_chain()
        p2 = node.parent_chain()
        for p in p1:
            if p in p2:
                return p
        return None

    def node_path_to_child(self, node):
        """Return a list describing the path from this node to a child node

        If *node* is not a (grand)child of this node, then raise RuntimeError.

        Parameters
        ----------
        node : instance of Node
            The child node.

        Returns
        -------
        path : list | None
            The path.
        """
        if node is self:
            return []

        # Go up from the child node as far as we can
        path1 = [node]
        child = node
        while child.parent is not None:
            child = child.parent
            path1.append(child)
            # Early exit
            if child is self:
                return list(reversed(path1))

        # Verify that we're not cut off
        if path1[-1].parent is None:
            raise RuntimeError('%r is not a child of %r' % (node, self))

        def _is_child(path, parent, child):
            path.append(parent)
            if child in parent.children:
                return path
            else:
                for c in parent.children:
                    possible_path = _is_child(path[:], c, child)
                    if possible_path:
                        return possible_path
            return None

        # Search from the parent towards the child
        path2 = _is_child([], self, path1[-1])
        if not path2:
            raise RuntimeError('%r is not a child of %r' % (node, self))

        # Return
        return path2 + list(reversed(path1))

    def node_path(self, node):
        """Return two lists describing the path from this node to another

        Parameters
        ----------
        node : instance of Node
            The other node.

        Returns
        -------
        p1 : list
            First path (see below).
        p2 : list
            Second path (see below).

        Notes
        -----
        The first list starts with this node and ends with the common parent
        between the endpoint nodes. The second list contains the remainder of
        the path from the common parent to the specified ending node.

        For example, consider the following scenegraph::

            A --- B --- C --- D
                   \
                    --- E --- F

        Calling `D.node_path(F)` will return::

            ([D, C, B], [E, F])

        """
        p1 = self.parent_chain()
        p2 = node.parent_chain()
        cp = None
        for p in p1:
            if p in p2:
                cp = p
                break
        if cp is None:
            raise RuntimeError("No single-path common parent between nodes %s "
                               "and %s." % (self, node))

        p1 = p1[:p1.index(cp)+1]
        p2 = p2[:p2.index(cp)][::-1]
        return p1, p2

    def node_path_transforms(self, node):
        """Return the list of transforms along the path to another node.

        The transforms are listed in reverse order, such that the last
        transform should be applied first when mapping from this node to
        the other.

        Parameters
        ----------
        node : instance of Node
            The other node.

        Returns
        -------
        transform : instance of Transform
            The transform.
        """
        a, b = self.node_path(node)
        return ([n.transform.inverse for n in b] +
                [n.transform for n in a[:-1]])[::-1]

    def node_transform(self, node):
        """
        Return the transform that maps from the coordinate system of
        *self* to the local coordinate system of *node*.

        Note that there must be a _single_ path in the scenegraph that connects
        the two entities; otherwise an exception will be raised.

        Parameters
        ----------
        node : instance of Node
            The other node.

        Returns
        -------
        transform : instance of ChainTransform
            The transform.
        """
        return ChainTransform(self.node_path_transforms(node))

    def __repr__(self):
        name = "" if self.name is None else " name="+self.name
        return "<%s%s at 0x%x>" % (self.__class__.__name__, name, id(self))

    @property
    def picking(self):
        """Boolean that determines whether this node (and its children) are
        drawn in picking mode.
        """
        return self._picking

    @picking.setter
    def picking(self, p):
        for c in self.children:
            c.picking = p
        self._picking = p
<|endoftext|>


<commit_before>import logging

import twisted
from twisted.internet.defer import maybeDeferred
from twisted.internet.threads import deferToThread

def maybeDeferredWrap(funcToWrap):
    """ Maybe Deferred Wrap

    A decorator that ensures a function will return a deferred.

    """

    def func(*args, **kwargs):
        return maybeDeferred(funcToWrap, *args, **kwargs)

    return func

def vortexLogFailure(failure, logger, consumeError=False, successValue=True):
    if not hasattr(failure, '_vortexLogged'):
        if failure.getTraceback():
            logger.error(failure.getTraceback())
        failure._vortexFailureLogged = True
    return successValue if consumeError else failure

def printFailure(failure, logger):
    logger.error(failure)
    return failure

def deferToThreadWrapWithLogger(logger):
    assert isinstance(logger, logging.Logger), """Usage:
    import logging
    logger = logging.getLogger(__name__)
    @deferToThreadWrapWithLogger(logger)
    def myFunction(arg1, kw=True):
        pass
    """

    def wrapper(funcToWrap):
        def func(*args, **kwargs):
            if not twisted.python.threadable.isInIOThread():
                raise Exception(
                    "Deferring to a thread can only be done from the main thread")

            d = deferToThread(funcToWrap, *args, **kwargs)
            d.addErrback(vortexLogFailure, logger)
            return d

        return func

    return wrapper

def noMainThread():
    if twisted.python.threadable.isInIOThread():
        raise Exception("Blocking operations shouldn't occur in the reactors thread.")
<commit_msg>Improved vortexLogFailure for when it causes an exception<commit_after>import logging

import twisted
from twisted.internet.defer import maybeDeferred
from twisted.internet.threads import deferToThread

logger = logging.getLogger(__name__)

def maybeDeferredWrap(funcToWrap):
    """ Maybe Deferred Wrap

    A decorator that ensures a function will return a deferred.

    """

    def func(*args, **kwargs):
        return maybeDeferred(funcToWrap, *args, **kwargs)

    return func

def vortexLogFailure(failure, loggerArg, consumeError=False, successValue=True):
    try:
        if not hasattr(failure, '_vortexLogged'):
            if failure.getTraceback():
                loggerArg.error(failure.getTraceback())
            failure._vortexFailureLogged = True
        return successValue if consumeError else failure
    except Exception as e:
        logger.exception(e)

printFailure = vortexLogFailure

def deferToThreadWrapWithLogger(logger):
    assert isinstance(logger, logging.Logger), """Usage:
    import logging
    logger = logging.getLogger(__name__)
    @deferToThreadWrapWithLogger(logger)
    def myFunction(arg1, kw=True):
        pass
    """

    def wrapper(funcToWrap):
        def func(*args, **kwargs):
            if not twisted.python.threadable.isInIOThread():
                raise Exception(
                    "Deferring to a thread can only be done from the main thread")

            d = deferToThread(funcToWrap, *args, **kwargs)
            d.addErrback(vortexLogFailure, logger)
            return d

        return func

    return wrapper

def noMainThread():
    if twisted.python.threadable.isInIOThread():
        raise Exception("Blocking operations shouldn't occur in the reactors thread.")
<|endoftext|>


<commit_before># endcoding = utf-8
'''
author :
email :
'''

__author__ = 'vex1023'
__email__ = 'vex1023@qq.com'
__version__ = '0.0.3'
__homepages__ = 'https://github.com/vex1023/vxUtils'
__logger__ = 'vxUtils'<commit_msg>版本号:0.0.4<commit_after># endcoding = utf-8
'''
author :
email :
'''

__author__ = 'vex1023'
__email__ = 'vex1023@qq.com'
__version__ = '0.0.4'
__homepages__ = 'https://github.com/vex1023/vxUtils'
__logger__ = 'vxUtils'<|endoftext|>


<commit_before>from urllib import parse

from wapps.feed import SiteFeed
from wapps.utils import get_image_url

class BlogFeed(SiteFeed):
    def __init__(self, blog, *args, **kwargs):
        self.blog = blog
        super().__init__(*args, **kwargs)

    def __call__(self, request, *args, **kwargs):
        kwargs['page'] = self.blog
        return super().__call__(request, *args, **kwargs)

    def title(self):
        return ' » '.join((self.meta.site_title, self.blog.title))

    def description(self):
        return self.meta.description

    subtitle = description

    def link(self):
        return self.blog.full_url

    def items(self):
        return self.blog.get_queryset()[:20]

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.body

    def item_pubdate(self, item):
        return item.date

    def item_link(self, item):
        return item.full_url

    def item_enclosure_url(self, item):
        if item.image:
            image_url = get_image_url(item.image, 'fill-1920x1080')
            return parse.urljoin(self.site.root_url, image_url)

    def item_enclosure_mime_type(self, item):
        if item.image:
            return 'image/png'

    def item_enclosure_length(self, item):
        if item.image:
            return 0

    def item_content(self, item):
        return str(item.body)
<commit_msg>Fix feed content<commit_after>from urllib import parse

from wagtail.wagtailcore.rich_text import expand_db_html

from wapps.feed import SiteFeed
from wapps.utils import get_image_url

class BlogFeed(SiteFeed):
    def __init__(self, blog, *args, **kwargs):
        self.blog = blog
        super().__init__(*args, **kwargs)

    def __call__(self, request, *args, **kwargs):
        kwargs['page'] = self.blog
        return super().__call__(request, *args, **kwargs)

    def title(self):
        return ' » '.join((self.meta.site_title, self.blog.title))

    def description(self):
        return self.meta.description

    subtitle = description

    def link(self):
        return self.blog.full_url

    def items(self):
        return self.blog.get_queryset()[:20]

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.summarize()

    def item_pubdate(self, item):
        return item.date

    def item_link(self, item):
        return item.full_url

    def item_enclosure_url(self, item):
        if item.image:
            image_url = get_image_url(item.image, 'fill-1920x1080')
            return parse.urljoin(self.site.root_url, image_url)

    def item_enclosure_mime_type(self, item):
        if item.image:
            return 'image/png'

    def item_enclosure_length(self, item):
        if item.image:
            return 0

    def item_content(self, item):
        return expand_db_html(item.body)
<|endoftext|>


<commit_before>import ply.lex as lex

class TclParser():

    def __init__(self):
        tokens = (
                'COMMENT',
                'TEXT',
                'LBRACE',
                'RBRACE',
                'LBRACKET',
                'RBRACKET',
                'QUOT',
                'NEWLINE',
                'SEMICOLON',
                'BACKSLASH',

                'DEREFERENCE',
                'SLASH',
                'NUMBER',
                'WHITESPACE',
                'GREATER',
                'EQUALS',
                'LPAREN',
                'RPAREN',
                'NUMOP',
            )

        t_BACKSLASH = r'\\'
        t_LBRACE = r'\{'
        t_RBRACE = r'\}'
        t_TEXT = r'[:!\'.\w]+'
        t_NUMOP = r'[\*\+\-]'
        t_EQUALS = r'='
        t_GREATER = r'>'
        t_SLASH = r'\/'
        t_LPAREN = r'\('
        t_RPAREN = r'\)'
        t_LBRACKET = r'\['
        t_RBRACKET = r'\]'
        t_QUOT = r'"'
        t_NEWLINE = r'\n'
        t_SEMICOLON = r';'
        t_DEREFERENCE = r'\$'
        t_WHITESPACE = r'[ \t]+'

        def t_NUMBER(t):
            r'\d+'
            #t.value = int(t.value)
            #return t
            pass

        def t_COMMENT(t):
            r'\#.*'
            pass

        # Error handling rule
        def t_error(t):
            print "Illegal character '%s'" % t.value[0]
            t.lexer.skip(1)

        self.lexer = lex.lex()

    def input_file(self,name):
        data = ''
        with open(name) as f:
            for line in f:
                data += line

        self.input(data)

    def input(self,data):
        self.lexer.input(data)

    def token(self):
        return self.lexer.token()

    def parse(self):
        state = 'idle'
        commands = []
        command = []
        commands_stack = []
        expr = ''
        depth = 0
        ignore_newline = False
        while True:
            tok = self.token()
            if not tok: break
            #if tok.type == 'NEWLINE' and len(commands) == 20:
            #    print commands
            #    print command
            #    break
            #print commands
            #print command
            #print tok
            if state == 'idle':
                if tok.type == 'TEXT':
                    state = 'command'
                    expr += tok.value
                    depth = 0
                    command = []
            elif state == 'command':
                if tok.type == 'NEWLINE' or tok.type == 'SEMICOLON':
                    if tok.type == 'NEWLINE' and ignore_newline:
                        ignore_newline = True
                        continue
                    state = 'idle'
                    if len(expr) > 0:
                        command.append(expr)
                    expr = ''
                    #if command and command[0] == 'source':
                    #    p = TclParser()
                    #    try:
                    #        p.input_file(command[1])
                    #        commands.extend(p.parse())
                    #    except IOError:
                    #        if len(command) > 0:
                    #            commands.append(command)
                    #            command = []

                    #else:
                    if len(command) > 0:
                        commands.append(command)
                        command = []
                elif tok.type == 'BACKSLASH':
                    ignore_newline = True
                elif tok.type == 'WHITESPACE':
                    ignore_newline = False
                    if len(expr) > 0:
                        command.append(expr)
                        expr = ''
                elif tok.type == 'LBRACKET':
                    ignore_newline = False
                    #print "lbracket"
                    #print commands
                    depth += 1
                    if len(expr) > 0:
                        command.append(expr)
                        expr = ''
                    #print command
                    commands_stack.append(commands)
                    commands = command
                    command = []
                    #print commands
                    #print command

                elif tok.type == 'RBRACKET':
                    ignore_newline = False
                    #print "rbracket"
                    #print commands
                    if len(expr) > 0:
                        command.append(expr)
                        expr = ''
                    #print command

                    commands.append(command)
                    command = []
                    #print commands
                    #print command
                    last_commands = commands_stack.pop()
                    last_commands.append(commands)
                    commands = last_commands
                    #print "last one"
                    #print commands
                    #print command
                    depth -= 1
                else:
                    ignore_newline = False
                    expr += tok.value

        return commands

<commit_msg>decent almost-finsihed TCL parser version<commit_after>import ply.lex as lex
import ply.yacc as yacc
import re, pprint, os

class Parser:
    """
    Base class for a lexer/parser that has the rules defined as methods
    """
    tokens = ()
    precedence = ()

    def __init__(self, filename, **kw):
        self.filename = filename
        self.debug = kw.get('debug', 0)
        self.names = { }
        try:
            modname = os.path.split(os.path.splitext(__file__)[0])[1] + "_" + self.__class__.__name__
        except:
            modname = "parser"+"_"+self.__class__.__name__
        self.debugfile = modname + ".dbg"
        self.tabmodule = modname + "_" + "parsetab"
        #print self.debugfile, self.tabmodule

        # Build the lexer and parser
        self.lexer = lex.lex(module=self, debug=self.debug)
        self.parser = yacc.yacc(module=self,
                  debug=self.debug,
                  debugfile=self.debugfile,
                  tabmodule=self.tabmodule)

    def run(self):
        self.run_on_file(self.filename)

    def run_on_file(self,filename):
        data = ''
        with open(filename) as f:
            for line in f:
                data += line

        #lexer debugging
        if 0:
            self.lexer.input(data)

            tok = self.lexer.token()
            while tok:
                print tok
                tok = self.lexer.token()

        self.parser.parse(data)

        #while 1:
            #try:
                #self.parser.parse(data)
            #except TypeError as e:
                #print e
                #break

class TclParser(Parser):

    tokens = (
            'COMMENT',
            'WHITESPACE',
            'COMMANDEND',
            'BACKSLASH',
            'LBRACKET',
            'QUOT',
            'RPAREN',
            'RBRACKET',
            'LBRACE',
            'RBRACE',
            'TEXT',
        )

    t_WHITESPACE = r'[ \t]+'
    t_BACKSLASH = r'\\'
    t_LBRACKET = r'\['
    t_QUOT = r'"'
    t_RPAREN = r'\)'
    t_RBRACKET = r'\]'
    t_LBRACE = r'\{'
    t_RBRACE = r'\}'
    t_TEXT = r'[\w\d\-\/\.\$\!\=]'

    def __init__(self,filename,**kw):
        Parser.__init__(self,filename,**kw)
        self.pp = pprint.PrettyPrinter()
        self.variables = {}

    def t_COMMENT(self,t):
        r'\#.*\n?'
        if '\n' in t.value:
            t.lexer.lineno += 1
        pass

    # Error handling rule
    def t_error(self,t):
        print "Illegal character '%s'" % t.value[0]
        t.lexer.skip(1)

    def t_COMMANDEND(self,t):
        r'[;\n]'
        if t.value == '\n':
            t.lexer.lineno += 1
        return t

    def p_end(self,p):
        '''end : script
               | empty'''
        self.pp.pprint(self.variables)

    def p_script(self,p):
        '''script : command
                  | script script'''
        if len(p) == 3:
            p[0] = p[1] + p[2]
        else:
            p[0] = [p[1]]

    def p_empty_command(self,p):
        '''command : COMMANDEND'''
        p[0] = []

    def p_string_text(self,p):
        '''string : TEXT
                  | string TEXT
                  | string string'''
        if len(p) == 3:
            p[0] = p[1] + p[2]
        else:
            p[0] = p[1]

    def p_backslash(self,p):
        '''string : BACKSLASH TEXT
                  | BACKSLASH LBRACKET'''
        p[0] = p[2]

    def p_subcommand(self,p):
        '''subcommand : LBRACKET
                      | subcommand word'''
        if len(p) == 2:
            p[0] = []
        else:
            p[0] = p[1] + [p[2]]

    def p_command_subcommand(self,p):
        '''string : subcommand RBRACKET'''
        p[0] = self.interpret(p,1)

    def p_quotword_start(self,p):
        '''quotword : QUOT'''
        p[0] = ''

    def p_quotword_cont(self,p):
        '''quotword : quotword TEXT
                    | quotword COMMANDEND
                    | quotword LBRACKET
                    | quotword WHITESPACE
                    | quotword RBRACKET
                    | quotword LBRACE
                    | quotword RBRACE'''
        p[0] = p[1] + p[2]

    def p_quotword_end(self,p):
        '''word : quotword QUOT'''
        p[0] = p[1]

    def p_braceword_start(self,p):
        '''braceword : LBRACE'''
        p[0] = p[1]

    def p_braceword_cont(self,p):
        '''braceword : braceword TEXT
                     | braceword COMMANDEND
                     | braceword WHITESPACE
                     | braceword word'''
        p[0] = p[1] + p[2]

    def p_braceword_end(self,p):
        '''word : braceword RBRACE'''
        p[0] = p[1] + p[2]

    def p_command_word(self,p):
        '''command : wordlist COMMANDEND'''
        p[0] = p[1]
        self.interpret(p,0)

    def p_word_list(self,p):
        '''wordlist : word
                    | wordlist word'''
        if len(p) == 3:
            p[0] = p[1] + [p[2]]
        else:
            p[0] = [p[1]]

    def p_word_string(self,p):
        '''word : string
                | braceword
                | string WHITESPACE
                | word WHITESPACE'''
        p[0] = p[1]

    def p_empty(self,p):
        'empty : '
        pass

    def p_error(self,p):
        if p:
            #print("Syntax error at token", p.type)
            # Just discard the token and tell the parser it's okay.
            #self.parser.errok()
            raise TypeError("Syntax error at token %s at position %d" % (p.type,p.lexpos))
        else:
            print("Syntax error at EOF")

    def interpret(self,p,commandpos):
        command = p[commandpos]
        print command
        variable_re = re.compile(r'\$\{?(\w+)\}?')
        for pos,word in enumerate(command):
            m = variable_re.match(word)
            if m:
                print m.group(1)
                try:
                    command[pos] = self.variables[m.group(1)]
                except KeyError:
                    #raise Exception("You have to define variable %s first" % (word[1:]))
                    print "You have to define variable %s first" % (m.group(1))

        if command[0] == 'set':
            assert(len(command) == 3)
            self.variables[command[1]] = command[2]
            self.pp.pprint(self.variables)
        elif command[0] == 'getenv':
            assert(len(command) == 2)
            return os.environ[command[1]]
        elif command[0] == 'source':
            assert(len(command) == 2)
            self.run_on_file(command[1])

#class TclParser(Parser):

    #tokens = (
            #'COMMENT',
            #'WHITESPACE',
            #'NEWLINE',
            #'SEMICOLON',
            #'QUOT',
            #'TEXT',
            ##'LBRACE',
            ##'RBRACE',
            ##'DEREFERENCE',
            ##'BACKSLASH',
            ##'SLASH',
            #'LBRACKET',
            #'RBRACKET',
            ##'EQUALS',

            ##'NUMBER',
            ##'GREATER',
            ##'LPAREN',
            ##'RPAREN',
            ##'NUMOP',
        #)

    #t_WHITESPACE = r'[ \t]+'
    #t_SEMICOLON = r';'
    #t_QUOT = r'"'
    #t_TEXT = r'[\{\}\$-:!\'.\w]+'
    #t_LBRACKET = r'\['
    #t_RBRACKET = r'\]'

    ##t_DEREFERENCE = r'\$'
    ##t_LBRACE = r'\{'
    ##t_RBRACE = r'\}'
    ##t_BACKSLASH = r'\\'
    ##t_SLASH = r'\/'
    ##t_EQUALS = r'='

    ##t_NUMOP = r'[\*\+\-]'
    ##t_GREATER = r'>'
    ##t_LPAREN = r'\('
    ##t_RPAREN = r'\)'

    ##def t_NUMBER(self,t):
    ##    r'\d+'
    ##    t.value = int(t.value)
    ##    return t

    #def t_COMMENT(self,t):
        #r'\#.*\n?'
        #pass

    ## Error handling rule
    #def t_error(self,t):
        #print "Illegal character '%s'" % t.value[0]
        #t.lexer.skip(1)

    #def t_NEWLINE(self,t):
        #r'\n'
        #t.lexer.lineno += 1
        #return t

    #def __init__(self,filename,**kw):
        #Parser.__init__(self,filename,**kw)
        #self.commands = []
        #self.current_command = []
        #self.pp = pprint.PrettyPrinter()

    #def p_start(self,p):
        #'''start : script
                 #| empty'''
        #if p[1]:
            #self.interpret(p[1])

    #def p_script_empty(self,p):
        #'''script : NEWLINE
                  #| WHITESPACE'''
                  ##| script NEWLINE
                  ##| script WHITESPACE'''
        ##print "Hello"
        #if len(p) == 3:
            #p[0] = p[1]
        #else:
            #p[0] = []

    #def p_string_text(self,p):
        #'''string : TEXT
                  #| string string'''
        #if len(p) == 3:
            #p[0] = p[1] + p[2]
        #else:
            #p[0] = p[1]

    #def p_word_string(self,p):
        #'''word : string
                #| string WHITESPACE'''
        #p[0] = p[1]

    #def p_script_command(self,p):
        #'''
        #script : command SEMICOLON
               #| command NEWLINE'''
        #p[0] = [p[1]]

    #def p_script_script(self,p):
        #'script : script script'
        #p[0] = p[1] + p[2]

    #def p_quotword(self,p):
        #'quotword : QUOT string'
        #p[0] = p[2]

    #def p_quot_string(self,p):
        #'''quotword : quotword string
                    #| quotword NEWLINE
                    #| quotword WHITESPACE
                    #| quotword SEMICOLON'''
        #p[0] = p[1] + p[2]

    #def p_quot_word(self,p):
        #'string : quotword QUOT'
        #p[0] = p[1]

    #def p_bracket_command(self,p):
        #'brackword : LBRACKET string'
        #p[0] = p[1] + p[2]

    #def p_bcommand_word(self,p):
        #'''brackword : brackword string
                     #| brackword WHITESPACE'''
        #p[0] = p[1] + p[2]

    #def p_command_bcommand(self,p):
        #'string : brackword RBRACKET'
        #p[0] = p[1] + p[2]

    #def p_command_word(self,p):
        #'''command : word'''
        #p[0] = [p[1]]

    #def p_command_append(self,p):
        #'command : command command'
        #p[0] = p[1] + p[2]

    #def p_empty(self,p):
        #'empty : '
        #pass

    #def p_error(self,p):
        #if p:
            ##print("Syntax error at token", p.type)
            ## Just discard the token and tell the parser it's okay.
            ##self.parser.errok()
            #raise TypeError("Syntax error at token %s at position %d" % (p.type,p.lexpos))
        #else:
            #print("Syntax error at EOF")

    #def interpret(self,script):
        #variables = {}
        #for command in script:
            ##if command[0] == 'set':
                ##variables[command[1]] = self.interpret(command[2])
                ##print command
            ##if command[0] == 'source'
                ##with open(self.interpre(command[) as f:
                    ##self.parser.parse(
            #print command

        #print variables

    #def parse(self):
        #state = 'idle'
        #commands = []
        #command = []
        #commands_stack = []
        #expr = ''
        #depth = 0
        #ignore_newline = False
        #while True:
            #tok = self.token()
            #if not tok: break
            ##if tok.type == 'NEWLINE' and len(commands) == 20:
            ##    print commands
            ##    print command
            ##    break
            ##print commands
            ##print command
            ##print tok
            #if state == 'idle':
                #if tok.type == 'TEXT':
                    #state = 'command'
                    #expr += tok.value
                    #depth = 0
                    #command = []
            #elif state == 'command':
                #if tok.type == 'NEWLINE' or tok.type == 'SEMICOLON':
                    #if tok.type == 'NEWLINE' and ignore_newline:
                        #ignore_newline = True
                        #continue
                    #state = 'idle'
                    #if len(expr) > 0:
                        #command.append(expr)
                    #expr = ''
                    ##if command and command[0] == 'source':
                    ##    p = TclParser()
                    ##    try:
                    ##        p.input_file(command[1])
                    ##        commands.extend(p.parse())
                    ##    except IOError:
                    ##        if len(command) > 0:
                    ##            commands.append(command)
                    ##            command = []

                    ##else:
                    #if len(command) > 0:
                        #commands.append(command)
                        #command = []
                #elif tok.type == 'BACKSLASH':
                    #ignore_newline = True
                #elif tok.type == 'WHITESPACE':
                    #ignore_newline = False
                    #if len(expr) > 0:
                        #command.append(expr)
                        #expr = ''
                #elif tok.type == 'LBRACKET':
                    #ignore_newline = False
                    ##print "lbracket"
                    ##print commands
                    #depth += 1
                    #if len(expr) > 0:
                        #command.append(expr)
                        #expr = ''
                    ##print command
                    #commands_stack.append(commands)
                    #commands = command
                    #command = []
                    ##print commands
                    ##print command

                #elif tok.type == 'RBRACKET':
                    #ignore_newline = False
                    ##print "rbracket"
                    ##print commands
                    #if len(expr) > 0:
                        #command.append(expr)
                        #expr = ''
                    ##print command

                    #commands.append(command)
                    #command = []
                    ##print commands
                    ##print command
                    #last_commands = commands_stack.pop()
                    #last_commands.append(commands)
                    #commands = last_commands
                    ##print "last one"
                    ##print commands
                    ##print command
                    #depth -= 1
                #else:
                    #ignore_newline = False
                    #expr += tok.value

        #return commands

<|endoftext|>