#
#		Python GUI - Views - PyObjC
#

from Foundation import NSMakeRect
from AppKit import NSView, NSScrollView
from Containers import PyGUI_Flipped_NSView
from GViews import View as GView, default_size
from Canvases import Canvas
from Geometry import rect_to_ns_rect
from ViewBases import PyGUI_NS_ViewBase
from Utils import NSMultiClass

class View(GView):

    def __init__(self, _ns_scrollable = False, **kwds):
        width, height = default_size
        ns_frame = NSMakeRect(0, 0, width, height)
        ns_inner_view = PyGUI_User_NSView.alloc().initWithFrame_(ns_frame)
        if _ns_scrollable:
            ns_view = NSScrollView.alloc().initWithFrame_(ns_frame)
            ns_view.setDocumentView_(ns_inner_view)
        else:
            ns_view = ns_inner_view
        ns_inner_view.pygui_component = self
        GView.__init__(self, _ns_view = ns_view, _ns_inner_view = ns_inner_view)
        self.set(**kwds)
    
    def destroy(self):
        #print "View.destroy:", self ###
        ns_inner_view = self._ns_inner_view
        GView.destroy(self)
        if ns_inner_view:
            #print "View.destroy: breaking back link from", ns_inner_view ###
            ns_inner_view.pygui_component = None
    
    def invalidate(self):
        self._ns_inner_view.setNeedsDisplay_(True)
    
    def invalidate_rect(self, r):
        self._ns_inner_view.setNeedsDisplayInRect_(rect_to_ns_rect(r))

    def with_canvas(self, proc):
        ns_view = self._ns_view
        ns_view.lockFocus()
        proc(Canvas())
        ns_view.unlockFocus()
    
    def update(self):
        self._ns_view.displayIfNeeded()
    
    def track_mouse(self):
        return self._ns_track_mouse(self._ns_inner_view)
    
#------------------------------------------------------------------------------

class PyGUI_User_NSView(PyGUI_Flipped_NSView, PyGUI_NS_ViewBase):
    __metaclass__ = NSMultiClass
    #
    #  pygui_component   View
    
    def drawRect_(self, ns_rect):
        (l, t), (w, h) = ns_rect
        rect = (l, t, l + w, t + h)
        self.pygui_component.draw(Canvas(), rect)
