#
#   PyGUI - Gtk input event handling
#

import gtk
from gtk import gdk
from Events import Event, _gtk_key_event_of_interest

_gdk_events_of_interest = (
    gdk.BUTTON_MOTION_MASK |
    gdk.BUTTON_PRESS_MASK |
    gdk.BUTTON_RELEASE_MASK |
    gdk.KEY_PRESS_MASK |
    gdk.KEY_RELEASE_MASK
)

_gtk_last_keyval_down = None

class GtkInput:
    #  Mixin for adding translation from Gtk mouse and keyboard
    #  events to PyGUI messages.

    def __init__(self, gtk_widget):
        self._last_mouse_down_time = 0
        self._click_count = 0
        gtk_widget.set_property('can-focus', 1)
        gtk_widget.add_events(_gdk_events_of_interest)
        self._gtk_connect(gtk_widget, 'button-press-event',
            self._gtk_button_press_event_signal)
        self._gtk_connect(gtk_widget, 'motion-notify-event',
            self._gtk_motion_notify_event_signal)
        self._gtk_connect(gtk_widget, 'button-release-event',
            self._gtk_button_release_event_signal)
        self._gtk_connect(gtk_widget, 'key-press-event',
            self._handle_gtk_key_event)
        self._gtk_connect(gtk_widget, 'key-release-event',
            self._handle_gtk_key_event)

    def _gtk_button_press_event_signal(self, gtk_event):
        if gtk_event.type == gdk.BUTTON_PRESS: # don't want 2BUTTON or 3BUTTON
            event = Event._from_gtk_mouse_event(gtk_event)
            last_time = self._last_mouse_down_time
            this_time = event.time
            num_clicks = self._click_count
            if this_time - last_time <= 0.25:
                num_clicks += 1
            else:
                num_clicks = 1
            event.num_clicks = num_clicks
            self._click_count = num_clicks
            self._last_mouse_down_time = this_time
            self.mouse_down(event)
    
    def _gtk_motion_notify_event_signal(self, gtk_event):
        self._mouse_event = Event._from_gtk_mouse_event(gtk_event)

    def _gtk_button_release_event_signal(self, gtk_event):
        self._mouse_event = Event._from_gtk_mouse_event(gtk_event)

    def _handle_gtk_key_event(self, gtk_event):
        """Convert a Gtk key-press or key-release event into an Event
        object and pass it up the message path."""
        global _gtk_last_keyval_down
        if _gtk_key_event_of_interest(gtk_event):
            event = Event._from_gtk_key_event(gtk_event)
            if event.kind == 'key_down':
                this_keyval = gtk_event.keyval
                if _gtk_last_keyval_down == this_keyval:
                    event.auto = 1
                _gtk_last_keyval_down = this_keyval
            else:
                _gtk_last_keyval_down = None
            self.handle(event.kind, event)
        return 1

