#------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
# 
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license.  The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
# Thanks for using Enthought open source!
# 
# Author: Enthought, Inc.
# Description: <Enthought pyface package component>
#------------------------------------------------------------------------------
""" The abstract base class for all Pyface windows. """

# Standard library imports.
import logging

# Major package imports.
import wx

# Enthought library imports.
from enthought.traits.api import Any, Bool, Event, Instance, Int, Property, Str
from enthought.traits.api import Tuple

# Local imports.
from constant import OK
from key_pressed_event import KeyPressedEvent
from widget import Widget


# Create a logger for this module.
logger = logging.getLogger(__name__)


class Window(Widget):
    """ The abstract base class for all Pyface windows.

    A Pyface window has no visual representation until it is opened (ie. its
    'control' trait will be None until it is opened).

    Usage: Create a sub-class of this class and override the protected
    '_create_control' (if necessary), '_create_contents', and '_size_control'
    (if necessary) methods.

    """

    #### 'Window' interface ###################################################
    
    # The sizer which handles the main layout of the content (None if the
    # layout is handled exclusively by the frame)
    main_sizer = Instance(wx.BoxSizer)

    # The window's parent (None if the window is a top-level window).
    parent = Any

    # The position of the window.
    position = Property(Tuple) 
    
    # The return code after the window is closed (this is useful in dialogs
    # etc, to indicate whether the dialog was closed via 'Ok' or 'Cancel').
    return_code = Int(OK)

    # The size of the window.
    size = Property(Tuple)
    
    # The sizer which contains the content area.
    sizer = Instance(wx.BoxSizer)
    
    # Thw window title.
    title = Str

    #### Events #####

    # The window has been activated.
    activated = Event

    # The window has been deactivated.
    deactivated = Event
    
    # The window is about to be closed.
    closing =  Event
    
    # The window has been closed.
    closed =  Event

    # The window is about to open.
    opening = Event
    
    # The window has been opened.
    opened = Event

    # A key was pressed while the window had focus.
    key_pressed = Event(KeyPressedEvent)

    #### Private interface ####################################################

    # Shadow trait for size.
    _size = Tuple((-1, -1))

    # Shadow trait for position.
    _position = Tuple((-1, -1))

    ###########################################################################
    # 'Window' interface.
    ###########################################################################

    #### Properties ###########################################################

    def _get_position(self):
        """ Property getter for position. """

        return self._position

    def _set_position(self, position):
        """ Property setter for position. """

        # Save for event notification.
        old = self._position

        # Set the shadow trait.
        self._position = position

        # Notify interested parties.
        self.trait_property_changed('position', old, position)

        return

    def _get_size(self):
        """ Property getter for size. """

        return self._size

    def _set_size(self, size):
        """ Property setter for size. """

        # Save for event notification.
        old = self._size

        # Set the shadow trait.
        self._size = size

        # Notify interested parties.
        self.trait_property_changed('size', old, size)
            
        return
    
    #### Methods ##############################################################
    
    def open(self):
        """ Opens the window. """

        # Trait notification.
        self.opening = self

        if self.control is None:
            self._create()

        self.control.Show(True)

        # Trait notification.
        self.opened = self
        
        return

    def close(self):
        """ Closes the window. """

        if self.control is not None:
            # Trait notification.
            self.closing = self

            # Cleanup the toolkit-specific control.
            self.control.Destroy()

            # Cleanup our reference to the control so that we can (at least in
            # theory!) be opened again.
            self.control = None

            # Trait notification.
            self.closed = self

        else:
            logger.debug('window is not open %s' % str(self))
            
        return

    def refresh(self):
        """ Workaround for VTK render window sizing bug. """

        self.control.SendSizeEvent()

        return

    ###########################################################################
    # Protected 'Window' interface.
    ###########################################################################

    def _create(self):
        """ Creates the window's widget hierarchy. """

        # Create the toolkit-specific control that represents the window.
        self.control = self._create_control(self.parent)

        # Create the contents of the window.
        content = self._create_contents(self.control)
        
        if self.sizer is not None:
            self.sizer.Add(content, 1, wx.ALL | wx.EXPAND)

        if self.main_sizer is not None:
            self.main_sizer.Fit(self.control)

        self._size_control(self.control, content)

        # Wire up event any event listeners required by the window.
        self._add_event_listeners(self.control)
        
        return

    def _add_event_listeners(self, control):
        """ Adds any event listeners required by the window. """

        # Frame events.
        wx.EVT_ACTIVATE(self.control, self._on_activate)
        wx.EVT_CLOSE(self.control, self._on_close)
        wx.EVT_SIZE(self.control, self._on_control_size)
        wx.EVT_MOVE(self.control, self._on_control_move)
        wx.EVT_CHAR(self.control, self._on_char)

        return
    
    def _create_control(self, parent):
        """ Create the toolkit-specific control that represents the window.

        This method is intended to be overridden if necessary.  By default we
        just create an empty frame.

        """

        control = wx.Frame(
            parent, -1, self.title, size=self.size, pos=self.position
        )
        
        return control
            
    def _create_contents(self, parent):
        """ Creates the window contents.

        This method is intended to be overridden if necessary.  By default we
        just create an empty (and blue!) panel.

        """

        panel = wx.Panel(parent, -1)
        panel.SetSize((500, 400))
        panel.SetBackgroundColour('blue')
        
        return panel

    def _size_control(self, control, content):
        """ Set the size of the toolkit specific control.

        This method is intended to be overridden if necessary.  By default we
        set the size to the value of the 'size' trait.  Subclasses may choose
        another strategy for their initial size, if for instance, they wish
        to set the size based on the size of the contents.
        
        """

        if self.size != (-1, -1):
            self.control.SetSize(self.size)

        return

    ###########################################################################
    # Private interface.
    ###########################################################################

    #### Trait event handlers #################################################

    #### Static ####

    def _position_changed(self, position):
        """ Static trait change handler. """

        if self.control is not None:
            self.control.SetPosition(position)

        return

    def _size_changed(self, size):
        """ Static trait change handler. """
        
        if self.control is not None:
            self.control.SetSize(size)

        return

    def _title_changed(self, title):
        """ Static trait change handler. """

        if self.control is not None:
            self.control.SetTitle(title)

        return

    #### wx event handlers ####################################################

    def _on_activate(self, event):
        """ Called when the frame is being activated or deactivated. """

        # Trait notification.
        if event.GetActive():
            self.activated = self

        else:
            self.deactivated = self

        return

    def _on_close(self, event):
        """ Called when the frame is being closed. """

        logger.debug('window [%s] closed by user', self)
        
        self.close()

        return
    
    def _on_control_move(self, event):
        """ Called when the window is resized. """

        # Get the real position and set the trait without performing
        # notification.

        # WXBUG - From the API documentation you would think that you could
        # call event.GetPosition directly, but that would be wrong.  The pixel
        # reported by that call is the pixel just below the window menu and
        # just right of the Windows-drawn border.
        self._position = event.GetEventObject().GetPositionTuple()
        
        event.Skip()

        return
        
    def _on_control_size(self, event):
        """ Called when the window is resized. """

        # Get the new size and set the shadow trait without performing
        # notification.
        wxsize = event.GetSize()
        self._size = (wxsize.GetWidth(), wxsize.GetHeight())

        event.Skip()

        return

    def _on_char(self, event):
        """ Called when a key is pressed when the tree has focus. """

        self.key_pressed = KeyPressedEvent(
            alt_down     = event.AltDown() == 1,
            control_down = event.ControlDown() == 1,
            shift_down   = event.ShiftDown() == 1,
            key_code     = event.GetKeyCode(),
            event        = event
        )
        
        event.Skip()
        
        return
        
#### EOF ######################################################################
