#
#   Python GUI - Containers - Macintosh version
#

from Carbon.Qd import NewRgn, CopyRgn, OffsetRgn, RectRgn, SectRgn, \
    SetEmptyRgn, SetOrigin, GetClip, SetClip, GetPort, SetPort, FrameRect, EraseRect
from MacDummy import _mac_dummy_port, _mac_dummy_window
from Geometry import inset_rect, pt_in_rect
from GContainers import Container as GContainer

class Frame(GContainer):

    def _mac_update_viewport(self):
        GContainer._mac_update_viewport(self)
        self._mac_update_subcomponent_viewports()
    
    def _mac_update_subcomponent_viewports(self):
        # Update the origins and clip regions of all the subcomponents
        # of this component.
        for child in self._contents:
            child._mac_update_viewport()
    
    def _add(self, comp):
        GContainer._add(self, comp)
        comp._mac_update_viewport()
        if comp.visible:
            self._invalidate_subcomponent(comp)
    
    def _remove(self, comp):
        if comp.visible:
            self._invalidate_subcomponent(comp)
        GContainer._remove(self, comp)
        comp._mac_update_viewport()

    def _invalidate_subcomponent(self, comp):
        # Invalidate the region of the container covered by the given
        # subcomponent, including its border if any.
        r = comp.bounds
        halo = comp._mac_halo
        if comp._border:
            halo = max(halo, 1)
        if halo:
            r = inset_rect(r, (-halo, -halo))
        self.invalidate_rect(r)
    
    def _mac_draw(self):
        # Draw this component and its subcomponents, assuming
        # that the grafport is focused on this component.
        EraseRect(self.viewed_rect())
        self._mac_draw_self()
        for child in self._contents:
            if child._border:
                r = inset_rect(child.bounds, (-1, -1))
                FrameRect(r)
            child._mac_update()
    
    def _mac_draw_self(self):
        # Draw the contents of this component only, excluding
        # its subcomponents, assuming that the grafport is focused
        # on this component.
        pass
    
    def _dispatch_mouse_event(self, event):
        # The event's position is given in our container's coordinates.
        # Transform it to local coordinates, then pass it on to one of our
        # subcomponents or handle it ourselves.
        #print "Container._dispatch_mouse_event:", event ###
        pos = self.container_to_local(event.position)
        event.position = pos
        contents = self._contents
        for i in xrange(len(contents) - 1, -1, -1):
            child = contents[i]
            if child.visible:
                b = child.bounds ###
                #print "...checking", pos, "in", b ###
                if pt_in_rect(pos, b): #child.bounds):
                    child._dispatch_mouse_event(event)
                    return
        GContainer._dispatch_mouse_event(self, event)

Container = Frame
