#
#		Python GUI - Events - Macintosh
#

from Carbon.Events import mouseDown, mouseUp, keyDown, keyUp, autoKey, \
    shiftKey, controlKey, cmdKey, optionKey
from Carbon.Evt import GetDblTime
from GEvents import Event as GEvent

_mac_what_to_kind = {
    mouseDown: 'mouse_down',
    mouseUp: 'mouse_up',
    keyDown: 'key_down',
    keyUp: 'key_up',
    autoKey: 'key_down',
}

_mac_keycode_to_keyname = {
    1:  'home',
    3:  'enter',
    4:  'end',
    5:  'help',
    11: 'page_up',
    12: 'page_down',
    28: 'left_arrow',
    29: 'right_arrow',
    30: 'up_arrow',
    31: 'down_arrow',
}

_last_click_time = 0    # in ticks
_num_clicks = 0				  # Multiple click counter

class Event(GEvent):
    """Platform-dependent modifiers (boolean):
        command            The Macintosh Command key.
        option             The Macintosh Option key.
    """

    def __init__(self, mac_event_record, kind = None):
        global _last_click_time, _num_clicks
        mac_what, mac_message, mac_when, mac_where, mac_modifiers \
            = mac_event_record
        if kind:
            self.kind = kind
        else:
            self.kind = _mac_what_to_kind[mac_what]
        self.auto = mac_what == autoKey
        self.global_position = self.position = mac_where
        self.time = mac_when / 60.0
        if mac_what == mouseDown:
            if mac_when - _last_click_time <= GetDblTime():
                _num_clicks += 1
            else:
                _num_clicks = 1
            _last_click_time = mac_when
            self.num_clicks = _num_clicks
        else:
            self.num_clicks = 1
        if mac_what == keyDown or mac_what == keyUp or mac_what == autoKey:
            code = mac_message & 0xff
            special_key = _mac_keycode_to_keyname.get(code, "")
            if special_key and not (mac_modifiers & controlKey):
                if special_key == 'enter':
                    self.char = "\r"
                else:
                    self.char = ""
                self.key = special_key
            else:
                self.char = chr(code)
                self.key = ""
        else:
            self.char = ""
            self.key = ""
        self.shift = self._extend_contig = (mac_modifiers & shiftKey) <> 0
        self.control = (mac_modifiers & controlKey) <> 0
        self.command = self.extend_noncontig = (mac_modifiers & cmdKey) <> 0
        self.option = (mac_modifiers & optionKey) <> 0
        self._mac_key_code = (mac_message >> 8) & 0xff
        self._mac_modifiers = mac_modifiers

    def _platform_modifiers_str(self):
        return " command:%s option:%s" % (self.command, self.option)
