#
#   Python GUI - Buttons - Macintosh
#

from struct import pack, unpack
from Carbon.Controls import kControlPushButtonDefaultTag, kControlPushButtonCancelTag, \
    kControlNoPart, kControlButtonPart
from Carbon.Ctl import CreatePushButtonControl
from Carbon.Evt import WaitNextEvent
from Properties import overridable_property
from Actions import Action
from Controls import Control
from StdFonts import system_font
from MacDummy import _mac_dummy_window
from GButtons import Button as GButton

class Button(GButton):
    """ A pushbutton control."""
    
    _style = 'normal'
    _mac_halo = 2
    
    def __init__(self, title = "Button", font = system_font, **kwds):
        title_width = font.width(title)
        default_width = max(28 + title_width, 69)
        mac_control = CreatePushButtonControl(
            _mac_dummy_window, (0, 0, default_width, 20), title)
        GButton.__init__(self, mac_control, **kwds)
    
    def get_style(self):
        return self._style
    
    def set_style(self, v):
        self._style = v
        self._mac_set_is_default(v == 'default')
        self._mac_set_is_cancel(v == 'cancel')
    
    def _mac_set_is_default(self, x):
        data = pack("b", not not x)
        self._with_focus(self._mac_control.SetControlData, 0, kControlPushButtonDefaultTag, data)
    
    def _mac_set_is_cancel(self, x):
        data = pack("b", not not x)
        self._with_focus(self._mac_control.SetControlData, 0, kControlPushButtonCancelTag, data)
    
    def activate(self):
        """Highlight the button momentarily and then perform its action."""
        self.flash()
        self.do_action()
    
    def flash(self):
        """Highlight the button momentarily as though it had been clicked,
        without performing the action."""
        self._with_focus(self._mac_flash)
    
    def _mac_flash(self):
        ctrl = self._mac_control
        ctrl.HiliteControl(kControlButtonPart)
        WaitNextEvent(0, 5, None)
        ctrl.HiliteControl(kControlNoPart)
    
    def _mac_control_part_hit(self, mac_part_code):
        if mac_part_code:
            self.do_action()
    