tuikit/core/container.py
author Radek Brich <radek.brich@devl.cz>
Wed, 03 Sep 2014 08:53:44 +0200
changeset 106 abcadb7e2ef1
parent 104 742e504ec053
child 108 11dac45bfba4
permissions -rw-r--r--
Use Point for mouse events, add them to Container and Widget.

from tuikit.core.widget import Widget
from tuikit.core.coords import Point
from tuikit.layouts.fixed import FixedLayout


class Container(Widget):

    """Container widget.

    Can contain other widgets to create hierarchical structure.

    """

    def __init__(self, layout_class=FixedLayout):
        Widget.__init__(self)
        #: List of child widgets.
        self.children = []
        self.focus_child = None
        self.mouse_child = None
        self.layout = layout_class()

    def add(self, widget):
        """Add widget into container."""
        self.children.append(widget)
        widget.parent = self
        widget.window = self.window
        widget.set_theme(self.theme)
        self.layout.add(widget)
        if self.focus_child is None:
            self.focus_child = widget

    def resize(self, w, h):
        Widget.resize(self, w, h)
        self.layout.resize()

    def draw(self, buffer):
        """Draw child widgets."""
        Widget.draw(self, buffer)
        for child in self.children:
            with buffer.moved_origin(child.x, child.y):
                with buffer.clip(buffer.origin.x, buffer.origin.y,
                                 child.width, child.height):
                    child.draw(buffer)

    def set_theme(self, theme):
        Widget.set_theme(self, theme)
        for child in self.children:
            child.set_theme(theme)

    @property
    def cursor(self):
        """Return cursor coordinates or None if cursor is not set
        or is set outside of widget boundaries.

        If this container has child with focus, return its cursor position instead.

        """
        if self.focus_child:
            cursor = self.focus_child.cursor
            if cursor is not None:
                return cursor.moved(*self.focus_child.pos)
        else:
            if self._cursor in Rect._make((0, 0), self._size):
                return self._cursor

    ## input events ##

    def keypress(self, keyname, char, mod=0):
        if self.focus_child:
            self.focus_child.keypress(keyname, char, mod)

    def mousedown(self, button, pos):
        self.mouse_child = None
        for child in reversed(self.children):
            if pos in child.boundaries:
                child.mousedown(button, pos - child.pos)
                self.mouse_child = child

    def mouseup(self, button, pos):
        if self.mouse_child:
            self.mouse_child.mouseup(button, pos - self.mouse_child.pos)

    def mousemove(self, button, pos, relpos):
        if self.mouse_child:
            self.mouse_child.mousemove(button,
                pos - self.mouse_child.pos, relpos)