tuikit/button.py
author Radek Brich <radek.brich@devl.cz>
Wed, 02 Jan 2013 00:16:12 +0100
changeset 43 369c8ef5070a
parent 41 37b7dfc3eae6
child 45 43b2279b06e1
permissions -rw-r--r--
Rename emitter module to events.

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

from tuikit.widget import Widget
from tuikit.events import Event


class Button(Widget):

    '''Clickable button.'''

    def __init__(self, label=''):
        '''Create button with given label, size according to label.'''
        w = len(label) + 4
        h = 1
        Widget.__init__(self, w, h)

        #: Button label.
        self.label = label
        #: Text or graphics to be added before label
        self.prefix = '['
        #: Text or graphics to be added after label
        self.suffix = ']'
        #: How should label be aligned if button has excess space - center | left | right
        self.align = 'center'

        self.allow_focus = True

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

        # size
        self.sizereq.w = w
        self.sizereq.h = h

        self.add_events('click', Event)


    def _handle_draw(self, ev):
        super()._handle_draw(ev)
        pad = self.width - len(self.label) - len(self.prefix) - len(self.suffix)
        lpad, rpad = self._divide_padding(pad)
        ev.driver.pushcolor(self.getcolor())
        # prefix
        ev.driver.puts(ev.x, ev.y, self.prefix)
        pos = len(self.prefix)
        # left pad
        ev.driver.puts(ev.x + pos, ev.y, ' ' * lpad)
        pos += lpad
        # label
        ev.driver.puts(ev.x + pos, ev.y, self.label)
        pos += len(self.label)
        # right pad
        ev.driver.puts(ev.x + pos, ev.y, ' ' * rpad)
        pos += rpad
        # suffix
        ev.driver.puts(ev.x + pos, ev.y, self.suffix)
        ev.driver.popcolor()

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

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

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

    def _handle_keypress(self, ev):
        super()._handle_keypress(ev)
        if ev.keyname == 'enter':
            self.emit('click')

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

    def _divide_padding(self, pad):
        # default is 'left'
        lpad, rpad = 0, pad
        if self.align == 'center':
            lpad = pad // 2
            rpad = pad - lpad
        elif self.align == 'right':
            lpad, rpad = pad, 0
        return lpad, rpad