tuikit/button.py
author Radek Brich <radek.brich@devl.cz>
Sun, 31 Jul 2011 13:04:39 +0200
changeset 9 7175ed629a76
parent 7 d4a291b31cbb
child 13 19ebde2fd594
permissions -rw-r--r--
Added ComboBox, HorizontalLayout, TreeNode, TreeModel, TreeView. Widget is now descendant of EventSource. Improved color management (color prefixes).

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

import curses
import locale

from .widget import Widget


class Button(Widget):
    def __init__(self, label=''):
        Widget.__init__(self, len(label) + 4, 1)

        self.label = label
        self.bg = 'button'
        self.bghi = 'button-active'
        self.highlight = False

        self.lbracket = '<'
        self.rbracket = '>'

        self.connect('draw', self.on_draw)
        self.connect('mousedown', self.on_mousedown)
        self.connect('mouseup', self.on_mouseup)
        self.connect('keypress', self.on_keypress)

        self.addevents('click')


    def on_draw(self, screen, x, y):
        l = (self.width - len(self.label)) // 2
        screen.pushcolor(self.getcolor())
        screen.putch(x, y, self.lbracket)
        for i in range(x+1, x+l):
            screen.putch(i, y, ' ')
        screen.puts(x + l, y, self.label)
        for i in range(x+l+len(self.label), x+self.width-1):
            screen.putch(i, y, ' ')
        screen.putch(x + self.width - 1, y, self.rbracket)
        screen.popcolor()


    def on_mousedown(self, ev):
        self.highlight = True
        self.redraw()


    def on_mouseup(self, ev):
        self.highlight = False
        self.redraw()

        if self.enclose(ev.px, ev.py):
            self.handle('click')


    def on_keypress(self, keyname, char):
        if keyname == 'enter':
            self.handle('click')


    def getcolor(self):
        if self.highlight or self.hasfocus():
            return self.bghi
        return self.bg