# Copyright (C) 2001, 2002, 2003 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.123 $"
# $Source: /thubanrepository/thuban/Thuban/UI/mainwindow.py,v $
# $Id: mainwindow.py,v 1.123 2003/12/01 16:09:10 bh Exp $

import os
import copy

from wxPython.wx import *

import Thuban

from Thuban import _
from Thuban.Model.messages import TITLE_CHANGED
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
from Thuban.UI.classifier import Classifier
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


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",
                         }

    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(VIEW_POSITION, self.view_position_changed)
        canvas.Subscribe(SHAPES_SELECTED, self.identify_view_on_demand)
        self.canvas = canvas
        self.canvas.Subscribe(TITLE_CHANGED, self.title_changed)

        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])
            object.Unsubscribe(channel, *args)

    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 view_position_changed(self):
        pos = self.canvas.CurrentPosition()
        if pos is not None:
            text = "(%10.10g, %10.10g)" % pos
        else:
            text = ""
        self.set_position_text(text)

    def set_position_text(self, text):
        """Set the statusbar text showing the current position.

        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.
        """
        self.SetStatusText(text)

    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"), ".", "", 
                               "Thuban Session File (*.thuban)|*.thuban", 
                               wxOPEN)
            if dlg.ShowModal() == wxID_OK:
                self.application.OpenSession(dlg.GetPath(),
                                             self.run_db_param_dialog)
            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"), ".", "",
                           "Thuban Session File (*.thuban)|*.thuban", 
                           wxSAVE|wxOVERWRITE_PROMPT)
        if dlg.ShowModal() == wxID_OK:
            self.application.session.SetFilename(dlg.GetPath())
            self.application.SaveSession()
        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.
            self.canvas.Unsubscribe(VIEW_POSITION, self.view_position_changed)
            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"), ".", "",
                           _("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()
        dlg.Destroy()

    def AddRasterLayer(self):
        dlg = wxFileDialog(self, _("Select an image file"), ".", "", "*.*",
                           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()
        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 = dlg.GetTable()
            try:
                title = str(dbtable)

                # Chose the correct Interface for the database type
                store = PostGISShapeStore(dbconn, dbtable)
                session.AddShapeStore(store)
                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)

            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 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 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_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(0)

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

    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.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):
        layer = self.current_layer()
        if layer is not None:
            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:
                # FIXME: bring dialog to front here
                pass

    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):
        name = "layer_properties" + str(id(layer))
        dialog = self.get_open_dialog(name)

        if dialog is None:
            dialog = Classifier(self, name, self.Map(), layer, group)
            self.add_dialog(name, dialog)
            dialog.Show()
        dialog.Raise()

    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"), ".", "", 
                           _("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)

    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_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 1
    return 0

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_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_layer,
                helptext = _("Join and attach a table to the 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"])

