# Copyright (C) 2001, 2002, 2003, 2004, 2005 by Intevation GmbH
# Authors:
# Jan-Oliver Wagner <jan@intevation.de>
# Bernhard Herzog <bh@intevation.de>
# Frank Koormann <frank.koormann@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

"""
The main window
"""

__version__ = "$Revision: 1.142 $"
# $Source: /thubanrepository/thuban/Thuban/UI/mainwindow.py,v $
# $Id: mainwindow.py,v 1.142 2005/01/27 14:19:41 jonathan Exp $

import os
import copy

from wxPython.wx import *

import Thuban

from Thuban import _
from Thuban.Model.messages import TITLE_CHANGED, LAYER_PROJECTION_CHANGED, \
     MAP_PROJECTION_CHANGED, MAP_LAYERS_ADDED, MAP_LAYERS_REMOVED

from Thuban.Model.session import create_empty_session
from Thuban.Model.layer import Layer, RasterLayer
from Thuban.Model.postgisdb import PostGISShapeStore, has_postgis_support
# XXX: replace this by
# from wxPython.lib.dialogs import wxMultipleChoiceDialog
# when Thuban does not support wxPython 2.4.0 any more.
from Thuban.UI.multiplechoicedialog import wxMultipleChoiceDialog

import view
import tree
import tableview, identifyview
import legend
from menu import Menu

from context import Context
from command import registry, Command, ToolCommand
from messages import LAYER_SELECTED, SHAPES_SELECTED, VIEW_POSITION, \
     MAP_REPLACED
from about import About

from Thuban.UI.dock import DockFrame
from Thuban.UI.join import JoinDialog
from Thuban.UI.dbdialog import DBFrame, DBDialog, ChooseDBTableDialog
import resource
import Thuban.Model.resource

import projdialog

from Thuban.UI.classifier import Classifier
from Thuban.UI.rasterlayerproperties import RasterLayerProperties
from Thuban.Model.layer import RasterLayer

from Thuban.Lib.classmapper import ClassMapper

layer_properties_dialogs = ClassMapper()
layer_properties_dialogs.add(RasterLayer, RasterLayerProperties)
layer_properties_dialogs.add(Layer, Classifier)

class MainWindow(DockFrame):

    # Some messages that can be subscribed/unsubscribed directly through
    # the MapCanvas come in fact from other objects. This is a map to
    # map those messages to the names of the instance variables they
    # actually come from. This delegation is implemented in the
    # Subscribe and unsubscribed methods
    delegated_messages = {LAYER_SELECTED: "canvas",
                          SHAPES_SELECTED: "canvas",
                          MAP_REPLACED: "canvas"}

    # Methods delegated to some instance variables. The delegation is
    # implemented in the __getattr__ method.
    delegated_methods = {"SelectLayer": "canvas",
                         "SelectShapes": "canvas",
                         "SelectedLayer": "canvas",
                         "SelectedShapes": "canvas",
                         }

    # Messages from the canvas that may require a status bar update.
    # The update_status_bar method will be subscribed to these messages.
    update_status_bar_messages = (VIEW_POSITION, LAYER_PROJECTION_CHANGED,
                                  MAP_PROJECTION_CHANGED, MAP_LAYERS_ADDED,
                                  MAP_LAYERS_REMOVED)

    def __init__(self, parent, ID, title, application, interactor,
                 initial_message = None, size = wxSize(-1, -1)):
        DockFrame.__init__(self, parent, ID, title, wxDefaultPosition, size)
        #wxFrame.__init__(self, parent, ID, title, wxDefaultPosition, size)

        self.application = application

        self.CreateStatusBar()
        if initial_message:
            self.SetStatusText(initial_message)

        self.identify_view = None

        self.init_ids()

        # creat the menubar from the main_menu description
        self.SetMenuBar(self.build_menu_bar(main_menu))

        # Similarly, create the toolbar from main_toolbar
        toolbar = self.build_toolbar(main_toolbar)
        # call Realize to make sure that the tools appear.
        toolbar.Realize()


        # Create the map canvas
        canvas = view.MapCanvas(self, -1)
        canvas.Subscribe(SHAPES_SELECTED, self.identify_view_on_demand)
        self.canvas = canvas
        self.canvas.Subscribe(TITLE_CHANGED, self.title_changed)

        for channel in self.update_status_bar_messages:
            self.canvas.Subscribe(channel, self.update_status_bar)

        self.SetMainWindow(self.canvas)

        self.SetAutoLayout(True)

        self.init_dialogs()

        self.ShowLegend()

        EVT_CLOSE(self, self.OnClose)

    def Subscribe(self, channel, *args):
        """Subscribe a function to a message channel.

        If channel is one of the delegated messages call the appropriate
        object's Subscribe method. Otherwise do nothing.
        """
        if channel in self.delegated_messages:
            object = getattr(self, self.delegated_messages[channel])
            object.Subscribe(channel, *args)
        else:
            print "Trying to subscribe to unsupported channel %s" % channel

    def Unsubscribe(self, channel, *args):
        """Unsubscribe a function from a message channel.

        If channel is one of the delegated messages call the appropriate
        object's Unsubscribe method. Otherwise do nothing.
        """
        if channel in self.delegated_messages:
            object = getattr(self, self.delegated_messages[channel])
            try:
                object.Unsubscribe(channel, *args)
            except wxPyDeadObjectError:
                # The object was a wxObject and has already been
                # destroyed. Hopefully it has unsubscribed all its
                # subscribers already so that it's OK if we do nothing
                # here
                pass

    def __getattr__(self, attr):
        """If attr is one of the delegated methods return that method

        Otherwise raise AttributeError.
        """
        if attr in self.delegated_methods:
            return getattr(getattr(self, self.delegated_methods[attr]), attr)
        raise AttributeError(attr)

    def init_ids(self):
        """Initialize the ids"""
        self.current_id = 6000
        self.id_to_name = {}
        self.name_to_id = {}
        self.events_bound = {}

    def get_id(self, name):
        """Return the wxWindows id for the command named name.

        Create a new one if there isn't one yet"""
        ID = self.name_to_id.get(name)
        if ID is None:
            ID = self.current_id
            self.current_id = self.current_id + 1
            self.name_to_id[name] = ID
            self.id_to_name[ID] = name
        return ID

    def bind_command_events(self, command, ID):
        """Bind the necessary events for the given command and ID"""
        if not self.events_bound.has_key(ID):
            # the events haven't been bound yet
            EVT_MENU(self, ID, self.invoke_command)
            if command.IsDynamic():
                EVT_UPDATE_UI(self, ID, self.update_command_ui)

    def build_menu_bar(self, menudesc):
        """Build and return the menu bar from the menu description"""
        menu_bar = wxMenuBar()

        for item in menudesc.items:
            # here the items must all be Menu instances themselves
            menu_bar.Append(self.build_menu(item), item.title)

        return menu_bar

    def build_menu(self, menudesc):
        """Return a wxMenu built from the menu description menudesc"""
        wxmenu = wxMenu()
        last = None
        for item in menudesc.items:
            if item is None:
                # a separator. Only add one if the last item was not a
                # separator
                if last is not None:
                    wxmenu.AppendSeparator()
            elif isinstance(item, Menu):
                # a submenu
                wxmenu.AppendMenu(wxNewId(), item.title, self.build_menu(item))
            else:
                # must the name the name of a command
                self.add_menu_command(wxmenu, item)
            last = item
        return wxmenu

    def build_toolbar(self, toolbardesc):
        """Build and return the main toolbar window from a toolbar description

        The parameter should be an instance of the Menu class but it
        should not contain submenus.
        """
        toolbar = self.CreateToolBar(wxTB_3DBUTTONS)

        # set the size of the tools' bitmaps. Not needed on wxGTK, but
        # on Windows, although it doesn't work very well there. It seems
        # that only 16x16 icons are really supported on windows.
        # We probably shouldn't hardwire the bitmap size here.
        toolbar.SetToolBitmapSize(wxSize(24, 24))

        for item in toolbardesc.items:
            if item is None:
                toolbar.AddSeparator()
            else:
                # assume it's a string.
                self.add_toolbar_command(toolbar, item)

        return toolbar

    def add_menu_command(self, menu, name):
        """Add the command with name name to the menu menu.

        If name is None, add a separator.
        """
        if name is None:
            menu.AppendSeparator()
        else:
            command = registry.Command(name)
            if command is not None:
                ID = self.get_id(name)
                menu.Append(ID, command.Title(), command.HelpText(),
                            command.IsCheckCommand())
                self.bind_command_events(command, ID)
            else:
                print _("Unknown command %s") % name

    def add_toolbar_command(self, toolbar, name):
        """Add the command with name name to the toolbar toolbar.

        If name is None, add a separator.
        """
        # Assume that all toolbar commands are also menu commmands so
        # that we don't have to add the event handlers here
        if name is None:
            toolbar.AddSeparator()
        else:
            command = registry.Command(name)
            if command is not None:
                ID = self.get_id(name)
                bitmap = resource.GetBitmapResource(command.Icon(), 
                                                    wxBITMAP_TYPE_XPM)
                toolbar.AddTool(ID, bitmap,
                                shortHelpString = command.HelpText(),
                                isToggle = command.IsCheckCommand())
                self.bind_command_events(command, ID)
            else:
                print _("Unknown command %s") % name

    def Context(self):
        """Return the context object for a command invoked from this window
        """
        return Context(self.application, self.application.Session(), self)

    def invoke_command(self, event):
        name = self.id_to_name.get(event.GetId())
        if name is not None:
            command = registry.Command(name)
            command.Execute(self.Context())
        else:
            print _("Unknown command ID %d") % event.GetId()

    def update_command_ui(self, event):
        #print "update_command_ui", self.id_to_name[event.GetId()]
        context = self.Context()
        command = registry.Command(self.id_to_name[event.GetId()])
        if command is not None:
            sensitive = command.Sensitive(context)
            event.Enable(sensitive)
            if command.IsTool() and not sensitive and command.Checked(context):
                # When a checked tool command is disabled deselect all
                # tools. Otherwise the tool would remain active but it
                # might lead to errors if the tools stays active. This
                # problem occurred in GREAT-ER and this fixes it, but
                # it's not clear to me whether this is really the best
                # way to do it (BH, 20021206).
                self.canvas.SelectTool(None)
            event.SetText(command.DynText(context))
            if command.IsCheckCommand():
                    event.Check(command.Checked(context))

    def RunMessageBox(self, title, text, flags = wxOK | wxICON_INFORMATION):
        """Run a modal message box with the given text, title and flags
        and return the result"""
        dlg = wxMessageDialog(self, text, title, flags)
        dlg.CenterOnParent()
        result = dlg.ShowModal()
        dlg.Destroy()
        return result

    def init_dialogs(self):
        """Initialize the dialog handling"""
        # The mainwindow maintains a dict mapping names to open
        # non-modal dialogs. The dialogs are put into this dict when
        # they're created and removed when they're closed
        self.dialogs = {}

    def add_dialog(self, name, dialog):
        if self.dialogs.has_key(name):
            raise RuntimeError(_("The Dialog named %s is already open") % name)
        self.dialogs[name] = dialog

    def dialog_open(self, name):
        return self.dialogs.has_key(name)

    def remove_dialog(self, name):
        del self.dialogs[name]

    def get_open_dialog(self, name):
        return self.dialogs.get(name)

    def update_status_bar(self, *args):
        """Handler for a bunch of messages that may require a status bar update

        Currently this handles the canvas' VIEW_POSITION_CHANGED
        messages as well as several messages about changes in the map
        which may affect whether and how projections are used.

        These messages affect the text in the status bar in the following way:

        When VIEW_POSITION_CHANGED messages are sent and the mouse is
        actually in the canvas window, display the current mouse
        coordinates as defined by the canvas' CurrentPosition method.

        If there is no current position to show, check whether there is
        a potential problem with the map and layer projections and
        display a message about it.  Otherwise the status bar will
        become empty.

        The text is displayed in the status bar using the
        set_position_text method.
        """
        # Implementation note: We do not really have to know which
        # message was sent.  We can simply call the canvas'
        # CurrentPosition method and if that returns a tuple, it was a
        # VIEW_POSITION_CHANGED message and we have to display it.
        # Otherwise it was a VIEW_POSITION_CHANGED message where the
        # mouse has left the canvas or it was a message about a change
        # to the map, in which case we check the projections.
        #
        # When changing this method, keep in mind that the
        # VIEW_POSITION_CHANGED message are sent for every mouse move in
        # the canvas window, that is they happen very often, so the path
        # taken in that case has to be fast.
        text = ""
        pos = self.canvas.CurrentPosition()
        if pos is not None:
            text = "(%10.10g, %10.10g)" % pos
        else:
            for layer in self.canvas.Map().Layers():
                bbox = layer.LatLongBoundingBox()
                if bbox:
                    left, bottom, right, top = bbox
                    if not (-180 <= left <= 180 and
                            -180 <= right <= 180 and
                            -90 <= top <= 90 and
                            -90 <= bottom <= 90):
                        text = _("Select layer '%s' and pick a projection "
                                 "using Layer/Projection...") % layer.title
                        break

        self.set_position_text(text)

    def set_position_text(self, text):
        """Set the statusbar text to that created by update_status_bar

        By default the text is shown in field 0 of the status bar.
        Override this method in derived classes to put it into a
        different field of the statusbar.

        For historical reasons this method is called set_position_text
        because at first the text was always either the current position
        or the empty string.  Now it can contain other messages as well.
        The method will be renamed at one point.
        """
        # Note: If this method is renamed we should perhaps think about
        # some backwards compatibility measures for projects like
        # GREAT-ER which override this method.
        self.SetStatusText(text)

    def OpenOrRaiseDialog(self, name, dialog_class, *args, **kw):
        """
        Open or raise a dialog.

        If a dialog with the denoted name does already exist it is
        raised.  Otherwise a new dialog, an instance of dialog_class,
        is created, inserted into the main list and displayed.
        """
        dialog = self.get_open_dialog(name)

        if dialog is None:
            dialog = dialog_class(self, name, *args, **kw)
            self.add_dialog(name, dialog)
            dialog.Show(True)
        else:
            dialog.Raise()
                          
    def save_modified_session(self, can_veto = 1):
        """If the current session has been modified, ask the user
        whether to save it and do so if requested. Return the outcome of
        the dialog (either wxID_OK, wxID_CANCEL or wxID_NO). If the
        dialog wasn't run return wxID_NO.

        If the can_veto parameter is true (default) the dialog includes
        a cancel button, otherwise not.
        """
        if self.application.session.WasModified():
            flags = wxYES_NO | wxICON_QUESTION
            if can_veto:
                flags = flags | wxCANCEL
            result = self.RunMessageBox(_("Exit"),
                                        _("The session has been modified."
                                         " Do you want to save it?"),
                                        flags)
            if result == wxID_YES:
                self.SaveSession()
        else:
            result = wxID_NO
        return result

    def NewSession(self):
        if self.save_modified_session() != wxID_CANCEL:
            self.application.SetSession(create_empty_session())

    def OpenSession(self):
        if self.save_modified_session() != wxID_CANCEL:
            dlg = wxFileDialog(self, _("Open Session"),
                               self.application.Path("data"), "", 
                               "Thuban Session File (*.thuban)|*.thuban", 
                               wxOPEN)
            if dlg.ShowModal() == wxID_OK:
                self.application.OpenSession(dlg.GetPath(),
                                             self.run_db_param_dialog)
                self.application.SetPath("data", dlg.GetPath())
            dlg.Destroy()

    def run_db_param_dialog(self, parameters, message):
        dlg = DBDialog(self, _("DB Connection Parameters"), parameters,
                       message)
        return dlg.RunDialog()

    def SaveSession(self):
        if self.application.session.filename == None:
            self.SaveSessionAs()
        else:
            self.application.SaveSession()

    def SaveSessionAs(self):
        dlg = wxFileDialog(self, _("Save Session As"),
                           self.application.Path("data"), "",
                           "Thuban Session File (*.thuban)|*.thuban", 
                           wxSAVE|wxOVERWRITE_PROMPT)
        if dlg.ShowModal() == wxID_OK:
            self.application.session.SetFilename(dlg.GetPath())
            self.application.SaveSession()
            self.application.SetPath("data",dlg.GetPath())
        dlg.Destroy()

    def Exit(self):
        self.Close(False)

    def OnClose(self, event):
        result = self.save_modified_session(can_veto = event.CanVeto())
        if result == wxID_CANCEL:
            event.Veto()
        else:
            # FIXME: it would be better to tie the unsubscription to
            # wx's destroy event, but that isn't implemented for wxGTK
            # yet.
            for channel in self.update_status_bar_messages:
                self.canvas.Unsubscribe(channel, self.update_status_bar)

            DockFrame.OnClose(self, event)
            for dlg in self.dialogs.values():
                dlg.Destroy()
            self.canvas.Destroy()
            self.Destroy()

    def SetMap(self, map):
        self.canvas.SetMap(map)
        self.update_title()

        dialog = self.FindRegisteredDock("legend")
        if dialog is not None:
            dialog.GetPanel().SetMap(self.Map())

    def Map(self):
        """Return the map displayed by this mainwindow"""

        return self.canvas.Map()

    def ToggleSessionTree(self):
        """If the session tree is shown close it otherwise create a new tree"""
        name = "session_tree"
        dialog = self.get_open_dialog(name)
        if dialog is None:
            dialog = tree.SessionTreeView(self, self.application, name)
            self.add_dialog(name, dialog)
            dialog.Show(True)
        else:
            dialog.Close()

    def SessionTreeShown(self):
        """Return true iff the session tree is currently shown"""
        return self.get_open_dialog("session_tree") is not None

    def About(self):
        dlg = About(self)
        dlg.ShowModal()
        dlg.Destroy()

    def DatabaseManagement(self):
        name = "dbmanagement"
        dialog = self.get_open_dialog(name)
        if dialog is None:
            map = self.canvas.Map()
            dialog = DBFrame(self, name, self.application.Session())
            self.add_dialog(name, dialog)
            dialog.Show()
        dialog.Raise()

    def AddLayer(self):
        dlg = wxFileDialog(self, _("Select one or more data files"), 
                           self.application.Path("data"), "",
                           _("Shapefiles (*.shp)") + "|*.shp;*.SHP|" +
                           _("All Files (*.*)") + "|*.*",
                           wxOPEN | wxMULTIPLE)
        if dlg.ShowModal() == wxID_OK:
            filenames = dlg.GetPaths()
            for filename in filenames:
                title = os.path.splitext(os.path.basename(filename))[0]
                map = self.canvas.Map()
                has_layers = map.HasLayers()
                try:
                    store = self.application.Session().OpenShapefile(filename)
                except IOError:
                    # the layer couldn't be opened
                    self.RunMessageBox(_("Add Layer"),
                                       _("Can't open the file '%s'.")%filename)
                else:
                    layer = Layer(title, store)
                    map.AddLayer(layer)
                    if not has_layers:
                        # if we're adding a layer to an empty map, fit the
                        # new map to the window
                        self.canvas.FitMapToWindow()
                    self.application.SetPath("data",filename)
        dlg.Destroy()

    def AddRasterLayer(self):
        dlg = wxFileDialog(self, _("Select an image file"), 
                           self.application.Path("data"), "", "*.*",
                           wxOPEN)
        if dlg.ShowModal() == wxID_OK:
            filename = dlg.GetPath()
            title = os.path.splitext(os.path.basename(filename))[0]
            map = self.canvas.Map()
            has_layers = map.HasLayers()
            try:
                layer = RasterLayer(title, filename)
            except IOError:
                # the layer couldn't be opened
                self.RunMessageBox(_("Add Image Layer"),
                                   _("Can't open the file '%s'.") % filename)
            else:
                map.AddLayer(layer)
                if not has_layers:
                    # if we're adding a layer to an empty map, fit the
                    # new map to the window
                    self.canvas.FitMapToWindow()
                self.application.SetPath("data", filename)
        dlg.Destroy()

    def AddDBLayer(self):
        """Add a layer read from a database"""
        session = self.application.Session()
        dlg = ChooseDBTableDialog(self, self.application.Session())

        if dlg.ShowModal() == wxID_OK:
            dbconn, dbtable, id_column, geo_column = dlg.GetTable()
            try:
                title = str(dbtable)

                # Chose the correct Interface for the database type
                store = session.OpenDBShapeStore(dbconn, dbtable,
                                                 id_column = id_column,
                                                 geometry_column = geo_column)
                layer = Layer(title, store)
            except:
                # Some error occured while initializing the layer
                self.RunMessageBox(_("Add Layer from database"),
                                   _("Can't open the database table '%s'")
                                   % dbtable)
                return

            map = self.canvas.Map()

            has_layers = map.HasLayers()
            map.AddLayer(layer)
            if not has_layers:
                self.canvas.FitMapToWindow()

        dlg.Destroy()

    def RemoveLayer(self):
        layer = self.current_layer()
        if layer is not None:
            self.canvas.Map().RemoveLayer(layer)

    def CanRemoveLayer(self):
        """Return true if the currently selected layer can be deleted.

        If no layer is selected return False.

        The return value of this method determines whether the remove
        layer command is sensitive in menu.
        """
        layer = self.current_layer()
        if layer is not None:
            return self.canvas.Map().CanRemoveLayer(layer)
        return False

    def LayerToTop(self):
        layer = self.current_layer()
        if layer is not None:
            self.canvas.Map().MoveLayerToTop(layer)

    def RaiseLayer(self):
        layer = self.current_layer()
        if layer is not None:
            self.canvas.Map().RaiseLayer(layer)

    def LowerLayer(self):
        layer = self.current_layer()
        if layer is not None:
            self.canvas.Map().LowerLayer(layer)

    def LayerToBottom(self):
        layer = self.current_layer()
        if layer is not None:
            self.canvas.Map().MoveLayerToBottom(layer)

    def current_layer(self):
        """Return the currently selected layer.

        If no layer is selected, return None
        """
        return self.canvas.SelectedLayer()

    def has_selected_layer(self):
        """Return true if a layer is currently selected"""
        return self.canvas.HasSelectedLayer()

    def has_selected_shape_layer(self):
        """Return true if a shape layer is currently selected"""
        return isinstance(self.current_layer(), Layer)

    def has_selected_shapes(self):
        """Return true if a shape is currently selected"""
        return self.canvas.HasSelectedShapes()

    def HideLayer(self):
        layer = self.current_layer()
        if layer is not None:
            layer.SetVisible(False)

    def ShowLayer(self):
        layer = self.current_layer()
        if layer is not None:
            layer.SetVisible(True)

    def ToggleLayerVisibility(self):
        layer = self.current_layer()
        layer.SetVisible(not layer.Visible())

    def DuplicateLayer(self):
        """Ceate a new layer above the selected layer with the same shapestore
        """
        layer = self.current_layer()
        if layer is not None and hasattr(layer, "ShapeStore"):
            new_layer = Layer(_("Copy of `%s'") % layer.Title(),
                              layer.ShapeStore(),
                              projection = layer.GetProjection())
            new_classification = copy.deepcopy(layer.GetClassification())
            new_layer.SetClassificationColumn(
                    layer.GetClassificationColumn())
            new_layer.SetClassification(new_classification)
            self.Map().AddLayer(new_layer)

    def CanDuplicateLayer(self):
        """Return whether the DuplicateLayer method can create a duplicate"""
        layer = self.current_layer()
        return layer is not None and hasattr(layer, "ShapeStore")

    def LayerShowTable(self):
        """
        Present a TableView Window for the current layer.
        In case the window is already open, bring it to the front.
        In case, there is no active layer, do nothing.
        In case, the layer has no ShapeStore, do nothing.
        """
        layer = self.current_layer()
        if layer is not None:
            if not hasattr(layer, "ShapeStore"):
                return
            table = layer.ShapeStore().Table()
            name = "table_view" + str(id(table))
            dialog = self.get_open_dialog(name)
            if dialog is None:
                dialog = tableview.LayerTableFrame(self, name,
                                         _("Layer Table: %s") % layer.Title(),
                                         layer, table)
                self.add_dialog(name, dialog)
                dialog.Show(True)
            else:
                dialog.Raise()

    def MapProjection(self):

        name = "map_projection"
        dialog = self.get_open_dialog(name)

        if dialog is None:
            map = self.canvas.Map()
            dialog = projdialog.ProjFrame(self, name, 
                     _("Map Projection: %s") % map.Title(), map)
            self.add_dialog(name, dialog)
            dialog.Show()
        dialog.Raise()

    def LayerProjection(self):

        layer = self.current_layer()

        name = "layer_projection" + str(id(layer))
        dialog = self.get_open_dialog(name)

        if dialog is None:
            map = self.canvas.Map()
            dialog = projdialog.ProjFrame(self, name, 
                     _("Layer Projection: %s") % layer.Title(), layer)
            self.add_dialog(name, dialog)
            dialog.Show()
        dialog.Raise()

    def LayerEditProperties(self):

        #
        # the menu option for this should only be available if there
        # is a current layer, so we don't need to check if the 
        # current layer is None
        #

        layer = self.current_layer()
        self.OpenLayerProperties(layer)

    def OpenLayerProperties(self, layer, group = None):
        """
        Open or raise the properties dialog.

        This method opens or raises the properties dialog for the
        currently selected layer if one is defined for this layer
        type.
        """
        dialog_class = layer_properties_dialogs.get(layer)

        if dialog_class is not None:
            name = "layer_properties" + str(id(layer))
            self.OpenOrRaiseDialog(name, dialog_class, layer, group = group)

    def LayerJoinTable(self):
        layer = self.canvas.SelectedLayer()
        if layer is not None:
            dlg = JoinDialog(self, _("Join Layer with Table"),
                             self.application.session,
                             layer = layer)
            dlg.ShowModal()

    def LayerUnjoinTable(self):
        layer = self.canvas.SelectedLayer()
        if layer is not None:
            orig_store = layer.ShapeStore().OrigShapeStore()
            if orig_store:
                layer.SetShapeStore(orig_store)

    def ShowLegend(self):
        if not self.LegendShown():
            self.ToggleLegend()

    def ToggleLegend(self):
        """Show the legend if it's not shown otherwise hide it again"""
        name = "legend"
        dialog = self.FindRegisteredDock(name)

        if dialog is None:
            dialog = self.CreateDock(name, -1, _("Legend"), wxLAYOUT_LEFT)
            legend.LegendPanel(dialog, None, self)
            dialog.Dock()
            dialog.GetPanel().SetMap(self.Map())
            dialog.Show()
        else:
            dialog.Show(not dialog.IsShown())

    def LegendShown(self):
        """Return true iff the legend is currently open"""
        dialog = self.FindRegisteredDock("legend") 
        return dialog is not None and dialog.IsShown()

    def TableOpen(self):
        dlg = wxFileDialog(self, _("Open Table"), 
                           self.application.Path("data"), "", 
                           _("DBF Files (*.dbf)") + "|*.dbf|" + 
                           #_("CSV Files (*.csv)") + "|*.csv|" + 
                           _("All Files (*.*)") + "|*.*", 
                           wxOPEN)
        if dlg.ShowModal() == wxID_OK:
            filename = dlg.GetPath()
            dlg.Destroy()
            try:
                table = self.application.session.OpenTableFile(filename)
            except IOError:
                # the layer couldn't be opened
                self.RunMessageBox(_("Open Table"),
                                   _("Can't open the file '%s'.") % filename)
            else:
                self.ShowTableView(table)
                self.application.SetPath("data",filename)

    def TableClose(self):
        tables = self.application.session.UnreferencedTables()

        lst = [(t.Title(), t) for t in tables]
        lst.sort()
        titles = [i[0] for i in lst]
        dlg = wxMultipleChoiceDialog(self, _("Pick the tables to close:"),
                                     _("Close Table"), titles,
                                     size = (400, 300),
                                     style = wxDEFAULT_DIALOG_STYLE | 
                                             wxRESIZE_BORDER)
        if dlg.ShowModal() == wxID_OK:
            for i in dlg.GetValue():
                self.application.session.RemoveTable(lst[i][1])


    def TableShow(self):
        """Offer a multi-selection dialog for tables to be displayed

        The windows for the selected tables are opened or brought to
        the front.
        """
        tables = self.application.session.Tables()

        lst = [(t.Title(), t) for t in tables]
        lst.sort()
        titles = [i[0] for i in lst]
        dlg = wxMultipleChoiceDialog(self, _("Pick the table to show:"),
                                     _("Show Table"), titles,
                                     size = (400,300), 
                                     style = wxDEFAULT_DIALOG_STYLE | 
                                             wxRESIZE_BORDER)
        if (dlg.ShowModal() == wxID_OK):
            for i in dlg.GetValue():
                # XXX: if the table belongs to a layer, open a
                # LayerTableFrame instead of QueryTableFrame
                self.ShowTableView(lst[i][1])

    def TableJoin(self):
        dlg = JoinDialog(self, _("Join Tables"), self.application.session)
        dlg.ShowModal()

    def ShowTableView(self, table):
        """Open a table view for the table and optionally"""
        name = "table_view%d" % id(table)
        dialog = self.get_open_dialog(name)
        if dialog is None:
            dialog = tableview.QueryTableFrame(self, name,
                                               _("Table: %s") % table.Title(),
                                               table)
            self.add_dialog(name, dialog)
            dialog.Show(True)
        dialog.Raise()

    def TableRename(self):
        """Let the user rename a table"""

        # First, let the user select a table
        tables = self.application.session.Tables()
        lst = [(t.Title(), t) for t in tables]
        lst.sort()
        titles = [i[0] for i in lst]
        dlg = wxMultipleChoiceDialog(self, _("Pick the table to rename:"),
                                     _("Rename Table"), titles,
                                     size = (400,300), 
                                     style = wxDEFAULT_DIALOG_STYLE | 
                                             wxRESIZE_BORDER)
        if (dlg.ShowModal() == wxID_OK):
            to_rename = [lst[i][1] for i in dlg.GetValue()]
            dlg.Destroy()
        else:
            to_rename = []

        # Second, let the user rename the layers
        for table in to_rename:
            dlg = wxTextEntryDialog(self, _("Table Title:"), _("Rename Table"),
                                    table.Title())
            try:
                if dlg.ShowModal() == wxID_OK:
                    title = dlg.GetValue()
                    if title != "":
                        table.SetTitle(title)

                        # Make sure the session is marked as modified.
                        # FIXME: This should be handled automatically,
                        # but that requires more changes to the tables
                        # than I have time for currently.
                        self.application.session.changed()
            finally:
                dlg.Destroy()


    def ZoomInTool(self):
        self.canvas.ZoomInTool()

    def ZoomOutTool(self):
        self.canvas.ZoomOutTool()

    def PanTool(self):
        self.canvas.PanTool()

    def IdentifyTool(self):
        self.canvas.IdentifyTool()
        self.identify_view_on_demand(None, None)

    def LabelTool(self):
        self.canvas.LabelTool()

    def FullExtent(self):
        self.canvas.FitMapToWindow()

    def FullLayerExtent(self):
        self.canvas.FitLayerToWindow(self.current_layer())

    def FullSelectionExtent(self):
        self.canvas.FitSelectedToWindow()

    def ExportMap(self):
        self.canvas.Export()

    def PrintMap(self):
        self.canvas.Print()

    def RenameMap(self):
        dlg = wxTextEntryDialog(self, _("Map Title:"), _("Rename Map"),
                                self.Map().Title())
        if dlg.ShowModal() == wxID_OK:
            title = dlg.GetValue()
            if title != "":
                self.Map().SetTitle(title)

        dlg.Destroy()

    def RenameLayer(self):
        """Let the user rename the currently selected layer"""
        layer = self.current_layer()
        if layer is not None:
            dlg = wxTextEntryDialog(self, _("Layer Title:"), _("Rename Layer"),
                                    layer.Title())
            try:
                if dlg.ShowModal() == wxID_OK:
                    title = dlg.GetValue()
                    if title != "":
                        layer.SetTitle(title)
            finally:
                dlg.Destroy()

    def identify_view_on_demand(self, layer, shapes):
        """Subscribed to the canvas' SHAPES_SELECTED message

        If the current tool is the identify tool, at least one shape is
        selected and the identify dialog is not shown, show the dialog.
        """
        # If the selection has become empty we don't need to do
        # anything. Otherwise it could happen that the dialog was popped
        # up when the selection became empty, e.g. when a new selection
        # is opened while the identify tool is active and dialog had
        # been closed
        if not shapes:
            return

        name = "identify_view"
        if self.canvas.CurrentTool() == "IdentifyTool":
            if not self.dialog_open(name):
                dialog = identifyview.IdentifyView(self, name)
                self.add_dialog(name, dialog)
                dialog.Show(True)
            else:
                # FIXME: bring dialog to front?
                pass

    def title_changed(self, map):
        """Subscribed to the canvas' TITLE_CHANGED messages"""
        self.update_title()

    def update_title(self):
        """Update the window's title according to it's current state.

        In this default implementation the title is 'Thuban - ' followed
        by the map's title or simply 'Thuban' if there is not map.
        Derived classes should override this method to get different
        titles.

        This method is called automatically by other methods when the
        title may have to change. For the methods implemented in this
        class this usually only means that a different map has been set
        or the current map's title has changed.
        """
        map = self.Map()
        if map is not None:
            title = _("Thuban - %s") % (map.Title(),)
        else:
            title = _("Thuban")
        self.SetTitle(title)


#
# Define all the commands available in the main window
#


# Helper functions to define common command implementations
def call_method(context, methodname, *args):
    """Call the mainwindow's method methodname with args *args"""
    apply(getattr(context.mainwindow, methodname), args)

def _method_command(name, title, method, helptext = "",
                    icon = "", sensitive = None, checked = None):
    """Add a command implemented by a method of the mainwindow object"""
    registry.Add(Command(name, title, call_method, args=(method,),
                         helptext = helptext, icon = icon,
                         sensitive = sensitive, checked = checked))

def make_check_current_tool(toolname):
    """Return a function that tests if the currently active tool is toolname

    The returned function can be called with the context and returns
    true iff the currently active tool's name is toolname. It's directly
    usable as the 'checked' callback of a command.
    """
    def check_current_tool(context, name=toolname):
        return context.mainwindow.canvas.CurrentTool() == name
    return check_current_tool

def _tool_command(name, title, method, toolname, helptext = "",
                  icon = "", sensitive = None):
    """Add a tool command"""
    registry.Add(ToolCommand(name, title, call_method, args=(method,),
                             helptext = helptext, icon = icon,
                             checked = make_check_current_tool(toolname),
                             sensitive = sensitive))

def _has_selected_layer(context):
    """Return true if a layer is selected in the context"""
    return context.mainwindow.has_selected_layer()

def _has_selected_layer_visible(context):
    """Return true if a layer is selected in the context which is
    visible."""
    if context.mainwindow.has_selected_layer():
        layer = context.mainwindow.current_layer()
        if layer.Visible(): return True
    return False

def _has_selected_shape_layer(context):
    """Return true if a shape layer is selected in the context"""
    return context.mainwindow.has_selected_shape_layer()

def _has_selected_shapes(context):
    """Return true if a layer is selected in the context"""
    return context.mainwindow.has_selected_shapes()

def _can_remove_layer(context):
    return context.mainwindow.CanRemoveLayer()

def _has_tree_window_shown(context):
    """Return true if the tree window is shown"""
    return context.mainwindow.SessionTreeShown()

def _has_visible_map(context):
    """Return true iff theres a visible map in the mainwindow.

    A visible map is a map with at least one visible layer."""
    map = context.mainwindow.Map()
    if map is not None:
        for layer in map.Layers():
            if layer.Visible():
                return True
    return False

def _has_legend_shown(context):
    """Return true if the legend window is shown"""
    return context.mainwindow.LegendShown()

def _has_gdal_support(context):
    """Return True if the GDAL is available"""
    return Thuban.Model.resource.has_gdal_support()

def _has_dbconnections(context):
    """Return whether the the session has database connections"""
    return context.session.HasDBConnections()

def _has_postgis_support(context):
    return has_postgis_support()


# File menu
_method_command("new_session", _("&New Session"), "NewSession",
                helptext = _("Start a new session"))
_method_command("open_session", _("&Open Session..."), "OpenSession",
                helptext = _("Open a session file"))
_method_command("save_session", _("&Save Session"), "SaveSession",
                helptext =_("Save this session to the file it was opened from"))
_method_command("save_session_as", _("Save Session &As..."), "SaveSessionAs",
                helptext = _("Save this session to a new file"))
_method_command("toggle_session_tree", _("Session &Tree"), "ToggleSessionTree",
                checked = _has_tree_window_shown,
                helptext = _("Toggle on/off the session tree analysis window"))
_method_command("toggle_legend", _("Legend"), "ToggleLegend",
                checked = _has_legend_shown,
                helptext = _("Toggle Legend on/off"))
_method_command("database_management", _("&Database Connections..."),
                "DatabaseManagement",
                sensitive = _has_postgis_support)
_method_command("exit", _("E&xit"), "Exit",
                helptext = _("Finish working with Thuban"))

# Help menu
_method_command("help_about", _("&About..."), "About",
                helptext = _("Info about Thuban authors, version and modules"))


# Map menu
_method_command("map_projection", _("Pro&jection..."), "MapProjection",
                helptext = _("Set or change the map projection"))

_tool_command("map_zoom_in_tool", _("&Zoom in"), "ZoomInTool", "ZoomInTool",
              helptext = _("Switch to map-mode 'zoom-in'"), icon = "zoom_in",
              sensitive = _has_visible_map)
_tool_command("map_zoom_out_tool", _("Zoom &out"), "ZoomOutTool", "ZoomOutTool",
              helptext = _("Switch to map-mode 'zoom-out'"), icon = "zoom_out",
              sensitive = _has_visible_map)
_tool_command("map_pan_tool", _("&Pan"), "PanTool", "PanTool",
              helptext = _("Switch to map-mode 'pan'"), icon = "pan",
              sensitive = _has_visible_map)
_tool_command("map_identify_tool", _("&Identify"), "IdentifyTool",
              "IdentifyTool",
              helptext = _("Switch to map-mode 'identify'"), icon = "identify",
              sensitive = _has_visible_map)
_tool_command("map_label_tool", _("&Label"), "LabelTool", "LabelTool",
              helptext = _("Add/Remove labels"), icon = "label",
              sensitive = _has_visible_map)
_method_command("map_full_extent", _("&Full extent"), "FullExtent",
               helptext = _("Zoom to the full map extent"), icon = "fullextent",
              sensitive = _has_visible_map)
_method_command("layer_full_extent", _("&Full layer extent"), "FullLayerExtent",
                helptext = _("Zoom to the full layer extent"),
                icon = "fulllayerextent", sensitive = _has_selected_layer)
_method_command("selected_full_extent", _("&Full selection extent"),
                "FullSelectionExtent",
                helptext = _("Zoom to the full selection extent"),
                icon = "fullselextent", sensitive = _has_selected_shapes)
_method_command("map_export", _("E&xport"), "ExportMap",
                helptext = _("Export the map to file"))
_method_command("map_print", _("Prin&t"), "PrintMap",
                helptext = _("Print the map"))
_method_command("map_rename", _("&Rename..."), "RenameMap",
                helptext = _("Rename the map"))
_method_command("layer_add", _("&Add Layer..."), "AddLayer",
                helptext = _("Add a new layer to the map"))
_method_command("rasterlayer_add", _("&Add Image Layer..."), "AddRasterLayer",
                helptext = _("Add a new image layer to the map"),
                sensitive = _has_gdal_support)
_method_command("layer_add_db", _("Add &Database Layer..."), "AddDBLayer",
                helptext = _("Add a new database layer to active map"),
                sensitive = _has_dbconnections)
_method_command("layer_remove", _("&Remove Layer"), "RemoveLayer",
                helptext = _("Remove selected layer"),
                sensitive = _can_remove_layer)

# Layer menu
_method_command("layer_projection", _("Pro&jection..."), "LayerProjection",
                sensitive = _has_selected_layer,
                helptext = _("Specify projection for selected layer"))
_method_command("layer_duplicate", _("&Duplicate"), "DuplicateLayer",
                helptext = _("Duplicate selected layer"),
          sensitive = lambda context: context.mainwindow.CanDuplicateLayer())
_method_command("layer_rename", _("Re&name ..."), "RenameLayer",
                helptext = _("Rename selected layer"),
                sensitive = _has_selected_layer)
_method_command("layer_raise", _("&Raise"), "RaiseLayer",
                helptext = _("Raise selected layer"),
                sensitive = _has_selected_layer)
_method_command("layer_lower", _("&Lower"), "LowerLayer",
                helptext = _("Lower selected layer"),
                sensitive = _has_selected_layer)
_method_command("layer_show", _("&Show"), "ShowLayer",
                helptext = _("Make selected layer visible"),
                sensitive = _has_selected_layer)
_method_command("layer_hide", _("&Hide"), "HideLayer",
                helptext = _("Make selected layer unvisible"),
                sensitive = _has_selected_layer)
_method_command("layer_show_table", _("Show Ta&ble"), "LayerShowTable",
                helptext = _("Show the selected layer's table"),
                sensitive = _has_selected_shape_layer)
_method_command("layer_properties", _("&Properties..."), "LayerEditProperties",
                sensitive = _has_selected_layer,
                helptext = _("Edit the properties of the selected layer"))
_method_command("layer_jointable", _("&Join Table..."), "LayerJoinTable",
                sensitive = _has_selected_shape_layer,
                helptext = _("Join and attach a table to the selected layer"))

# further layer methods:
_method_command("layer_to_top", _("&Top"), "LayerToTop",
                helptext = _("Put selected layer to the top"),
                sensitive = _has_selected_layer)
_method_command("layer_to_bottom", _("&Bottom"), "LayerToBottom",
                helptext = _("Put selected layer to the bottom"),
                sensitive = _has_selected_layer)
_method_command("layer_visibility", _("&Visible"), "ToggleLayerVisibility",
                checked = _has_selected_layer_visible,
                helptext = _("Toggle visibility of selected layer"),
                sensitive = _has_selected_layer)

def _can_unjoin(context):
    """Return whether the Layer/Unjoin command can be executed.

    This is the case if a layer is selected and that layer has a
    shapestore that has an original shapestore.
    """
    layer = context.mainwindow.SelectedLayer()
    if layer is None:
        return 0
    getstore = getattr(layer, "ShapeStore", None)
    if getstore is not None:
        return getstore().OrigShapeStore() is not None
    else:
        return 0
_method_command("layer_unjointable", _("&Unjoin Table..."), "LayerUnjoinTable",
                sensitive = _can_unjoin,
                helptext = _("Undo the last join operation"))


def _has_tables(context):
    return bool(context.session.Tables())

# Table menu
_method_command("table_open", _("&Open..."), "TableOpen",
                helptext = _("Open a DBF-table from a file"))
_method_command("table_close", _("&Close..."), "TableClose",
       sensitive = lambda context: bool(context.session.UnreferencedTables()),
                helptext = _("Close one or more tables from a list"))
_method_command("table_rename", _("&Rename..."), "TableRename",
                sensitive = _has_tables,
                helptext = _("Rename one or more tables"))
_method_command("table_show", _("&Show..."), "TableShow",
                sensitive = _has_tables,
                helptext = _("Show one or more tables in a dialog"))
_method_command("table_join", _("&Join..."), "TableJoin",
                sensitive = _has_tables,
                helptext = _("Join two tables creating a new one"))

#  Export only under Windows ...
map_menu = ["layer_add", "layer_add_db", "rasterlayer_add", "layer_remove",
                        None,
                        "map_rename",
                        "map_projection",
                        None,
                        "map_zoom_in_tool", "map_zoom_out_tool",
                        "map_pan_tool",
                        "map_full_extent",
                        "layer_full_extent",
                        "selected_full_extent",
                        None,
                        "map_identify_tool", "map_label_tool",
                        None,
                        "toggle_legend",
                        None]
if wxPlatform == '__WXMSW__':
    map_menu.append("map_export")
map_menu.append("map_print")

# the menu structure
main_menu = Menu("<main>", "<main>",
                 [Menu("file", _("&File"),
                       ["new_session", "open_session", None,
                        "save_session", "save_session_as", None,
                        "database_management", None,
                        "toggle_session_tree", None,
                        "exit"]),
                  Menu("map", _("&Map"), map_menu),
                  Menu("layer", _("&Layer"),
                       ["layer_rename", "layer_duplicate",
                        None,
                        "layer_raise", "layer_lower",
                        None,
                        "layer_show", "layer_hide",
                        None,
                        "layer_projection",
                        None,
                        "layer_show_table",
                        "layer_jointable",
                        "layer_unjointable",
                        None,
                        "layer_properties"]),
                  Menu("table", _("&Table"),
                       ["table_open", "table_close", "table_rename",
                       None,
                       "table_show",
                       None,
                       "table_join"]),
                  Menu("help", _("&Help"),
                       ["help_about"])])

# the main toolbar

main_toolbar = Menu("<toolbar>", "<toolbar>",
                    ["map_zoom_in_tool", "map_zoom_out_tool", "map_pan_tool", 
                     "map_full_extent", 
                     "layer_full_extent", 
                     "selected_full_extent", 
                     None, 
                     "map_identify_tool", "map_label_tool"])

