#
#		Python GUI - View Base - PyObjC
#

import Foundation
import AppKit
import Applications
from Properties import overridable_property
from Events import Event
from Components import PyGUI_NS_EventHandler
from GViewBases import ViewBase as GViewBase

ns_tracking_mask = (
    AppKit.NSLeftMouseDraggedMask |
    AppKit.NSRightMouseDraggedMask |
    AppKit.NSOtherMouseDraggedMask |
    AppKit.NSLeftMouseUpMask |
    AppKit.NSRightMouseUpMask |
    AppKit.NSOtherMouseUpMask)

# Need to use NSDefaultRunLoopMode here otherwise timers don't fire.
ns_tracking_mode = Foundation.NSDefaultRunLoopMode # AppKit.NSEventTrackingRunLoopMode

ns_distant_future = Foundation.NSDate.distantFuture()


class ViewBase(GViewBase):

    def _ns_track_mouse(self, ns_view):
        ns_app = Applications.ns_application
        tracking = True
        while tracking:
            ns_event = ns_app.nextEventMatchingMask_untilDate_inMode_dequeue_(
                ns_tracking_mask, ns_distant_future, ns_tracking_mode, True)
            event = ns_view._ns_mouse_event_to_event(ns_event)
            yield event
            tracking = event.kind <> 'mouse_up'

    def _cursor_changed(self):
        #print "ViewBase._cursor_changed:", self ###
        ns_view = self._ns_view
        ns_window = ns_view.window()
        #print "...ns_window =", ns_window ###
        if ns_window:
            #print "...invalidating cursor rects for", ns_view ###
            # invalidateCursorRectsForView_ doesn't seem to trigger
            # resetCursorRects on the view.
            #ns_window.invalidateCursorRectsForView_(ns_view)
            ns_window.resetCursorRects()

    def _ns_reset_cursor_rects(self):
        #print "ViewBase._ns_reset_cursor_rects:", self ###
        #print "...ns_view =", self._ns_view ###
        cursor = self._cursor
        if cursor:
            ns_view = self._ns_inner_view
            ns_rect = ns_view.visibleRect()
            #print "...adding", ns_rect, "for", cursor._ns_cursor, \
            #	"with", cursor._ns_cursor.image() ###
            ns_view.addCursorRect_cursor_(ns_rect, cursor._ns_cursor)
    
#------------------------------------------------------------------------------

class PyGUI_NS_ViewBase(PyGUI_NS_EventHandler):
    #  Methods to be mixed in with PyGUI_NSView classes.
    #
    #  pygui_component   ViewBase
    
    tracking_rect = None
    
    def becomeFirstResponder(self):
        self.pygui_component.targeted()
        return True
    
    def resignFirstResponder(self):
        self.pygui_component.untargeted()
        return True

    def resetCursorRects(self):
        tag = self.tracking_rect
        if tag:
            self.removeTrackingRect_(tag)
        self.tracking_rect = self.addTrackingRect_owner_userData_assumeInside_(
            self.visibleRect(), self, 0, False)
        self.pygui_component._ns_reset_cursor_rects()
