tuikit/menubar.py
author Radek Brich <radek.brich@devl.cz>
Sun, 27 Jan 2013 23:51:59 +0100
changeset 70 db2eab0beb45
parent 64 03f591f5fe5c
permissions -rw-r--r--
Update drivers: Rename setcolor to defcolor, add real setcolor which ignores color stack. Application: Add overridable startup() method. Fix Widget draw clipping.

# -*- coding: utf-8 -*-

from tuikit.layout import HorizontalLayout
from tuikit.button import Button
from tuikit.container import Container


class MenuButton(Container, Button):
    def __init__(self, label='', menu=None):
        Container.__init__(self)
        Button.__init__(self, label)
        if menu:
            self.menu = menu

    @property
    def menu(self):
        return self.children[0]

    @menu.setter
    def menu(self, widget):
        self.add_floater(widget)
        widget.move(0, 1)
        widget.hide()

    def on_keypress(self, ev):
        if ev.keyname == 'escape':
            if not self.menu.hidden:
                self.menu.hide()
                return True

    def on_click(self, ev):
        self.menu.show()

    def on_unfocus(self, ev):
        self.menu.hide()

    def show_menu(self):
        if not self.menu.hidden:
            return False
        self.menu.show()
        return True


class MenuBar(HorizontalLayout):
    def __init__(self, items = []):
        HorizontalLayout.__init__(self, spacing=4)
        self._default_size.update(20, 1)
        self.allow_focus = True

        self.bg = 'menu'
        self.highlight = 'menu-active'

        for title, widget in items:
            self.add_menu(title, widget)

    def add_menu(self, title, widget):
        btn = MenuButton(title)
        btn.menu = widget
        btn.bg = self.bg
        btn.bghi = self.highlight
        btn.prefix = ''
        btn.suffix = ''
        self.add(btn)

    def on_draw(self, ev):
        ev.driver.pushcolor(self.bg)
        ev.driver.puts(ev.x, ev.y, ' ' * self.width)
        ev.driver.popcolor()

    def on_keypress(self, ev):
        # do we have some menu dropped down?
        menu_visible = not self.focuschild.menu.hidden
        if ev.keyname == 'left':
            res = self.focus_previous()
            if menu_visible:
                return self.focuschild.show_menu()
            return res
        elif ev.keyname == 'right':
            res = self.focus_next()
            if menu_visible:
                return self.focuschild.show_menu()
            return res
        elif ev.keyname == 'down':
            return self.focuschild.show_menu()