File: mainwindow.py

package info (click to toggle)
thuban 1.2.2-14
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 9,176 kB
  • sloc: python: 30,410; ansic: 6,181; xml: 4,234; cpp: 1,595; makefile: 145
file content (1408 lines) | stat: -rw-r--r-- 55,278 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
# Copyright (C) 2001, 2002, 2003, 2004, 2005, 2007 by Intevation GmbH
# Authors:
# Jan-Oliver Wagner <jan@intevation.de>
# Bernhard Herzog <bh@intevation.de>
# Frank Koormann <frank.koormann@intevation.de>
# Bernhard Reiter <bernhard@intevation.de> 2007
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

"""
The main window
"""

__version__ = "$Revision: 2873 $"
# $Source$
# $Id: mainwindow.py 2873 2009-04-04 10:38:54Z dpinte $

import os
import copy
import sys, traceback

import wx

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
from Thuban.UI import internal_from_wxstring
from wx.lib.dialogs import MultipleChoiceDialog

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 = wx.Size(-1, -1)):
        DockFrame.__init__(self, parent, ID, title, wx.DefaultPosition, 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()

        self.Bind(wx.EVT_CLOSE, 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 wx.PyDeadObjectError:
                # 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
            self.Bind(wx.EVT_MENU, self.invoke_command, id=ID)
            if command.IsDynamic():
                self.Bind(wx.EVT_UPDATE_UI, self.update_command_ui, id=ID)

    def unbind_command_events(self, command, ID):
        """Unbind the necessary events for the given command and ID"""
        if self.events_bound.has_key(ID):
            self.Unbind(wx.EVT_MENU, self.invoke_command, id=ID)
            if command.IsDynamic():
                self.Unbind(wx.EVT_UPDATE_UI, self.update_command_ui, id=ID)

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

        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 = wx.Menu()
        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(wx.NewId(), 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(wx.TB_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(wx.Size(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 remove_menu_command(self, menu, name):
        if name is None:
            return
        else:
            command = registry.Command(name)
            if command is not None:
                assert isinstance(menu, wx.Menu)
                ID = self.get_id(name)
                menu.Remove(ID)
                self.unbind_command_events(command, ID)

    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)
                if isinstance(command.Icon(), wx.Bitmap):
                    bitmap = command.Icon()
                else:
                    bitmap = resource.GetBitmapResource(command.Icon(),
                                                    wx.BITMAP_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 remove_toolbar_command(self, toolbar, name):
        """Remove the command with name name from the toolbar
        """
        if name is None:
            return
        else:
            command = registry.Command(name)
            if command is not None:
                ID = self.get_id(name)
                assert isinstance(toolbar, wx.ToolBar)
                toolbar.RemoveTool(ID)
                self.unbind_command_events(command, ID)             
                
    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 = wx.OK | wx.ICON_INFORMATION):
        """Run a modal message box with the given text, title and flags
        and return the result"""
        dlg = wx.MessageDialog(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 = wx.YES_NO | wx.ICON_QUESTION
            if can_veto:
                flags = flags | wx.CANCEL
            result = self.RunMessageBox(_("Exit"),
                                        _("The session has been modified."
                                         " Do you want to save it?"),
                                        flags)
            if result == wx.ID_YES:
                self.SaveSession()
        else:
            result = wx.ID_NO
        return result

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

    def OpenSession(self):
        if self.save_modified_session() != wx.ID_CANCEL:
            dlg = wx.FileDialog(self, _("Open Session"),
                               self.application.Path("data"), "",
                               "Thuban Session File (*.thuban)|*.thuban",
                               wx.OPEN)
            if dlg.ShowModal() == wx.ID_OK:
                path = internal_from_wxstring(dlg.GetPath())
                self.application.OpenSession(path, self.run_db_param_dialog)
                self.application.SetPath("data", path)
            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 = wx.FileDialog(self, _("Save Session As"),
                           self.application.Path("data"), "",
                           "Thuban Session File (*.thuban)|*.thuban",
                           wx.SAVE|wx.OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            path = internal_from_wxstring(dlg.GetPath())
            self.application.session.SetFilename(path)
            self.application.SaveSession()
            self.application.SetPath("data",path)
        dlg.Destroy()

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

    def OnClose(self, event):
        result = self.save_modified_session(can_veto = event.CanVeto())
        if result == wx.ID_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, mymap):
        self.canvas.SetMap(mymap)
        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:
            dialog = DBFrame(self, name, self.application.Session())
            self.add_dialog(name, dialog)
            dialog.Show()
        dialog.Raise()

    def AddLayer(self):
        dlg = wx.FileDialog(self, _("Select one or more data files"),
                           self.application.Path("data"), "",
                           _("Shapefiles (*.shp)") + "|*.shp;*.SHP|" +
                           _("All Files (*.*)") + "|*.*",
                           wx.OPEN | wx.MULTIPLE)
        if dlg.ShowModal() == wx.ID_OK:
            filenames = map(internal_from_wxstring, dlg.GetPaths())
            for filename in filenames:
                title = os.path.splitext(os.path.basename(filename))[0]
                mymap = self.canvas.Map()
                has_layers = mymap.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)
                    mymap.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 = wx.FileDialog(self, _("Select an image file"),
                           self.application.Path("data"), "", "*.*",
                           wx.OPEN | wx.MULTIPLE)
        if dlg.ShowModal() == wx.ID_OK:
            filenames = map(internal_from_wxstring, dlg.GetPaths())
            for filename in filenames:
                title = os.path.splitext(os.path.basename(filename))[0]
                mymap = self.canvas.Map()
                has_layers = mymap.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:
                    mymap.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() == wx.ID_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 occurred while initializing the layer
                traceback.print_exc(file=sys.stderr)
                self.RunMessageBox(_("Add Layer from database"),
                                   _("Can't open the database table '%s'")
                                   % dbtable)
                return

            mymap = self.canvas.Map()

            has_layers = mymap.HasLayers()
            mymap.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:
            mymap = self.canvas.Map()
            dialog = projdialog.ProjFrame(self, name,
                     _("Map Projection: %s") % mymap.Title(), mymap)
            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:
            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"), wx.LAYOUT_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 = wx.FileDialog(self, _("Open Table"),
                           self.application.Path("data"), "",
                           _("DBF Files (*.dbf)") + "|*.dbf|" +
                           #_("CSV Files (*.csv)") + "|*.csv|" + 
                           _("All Files (*.*)") + "|*.*",
                           wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            filename = internal_from_wxstring(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 = MultipleChoiceDialog(self, _("Pick the tables to close:"),
                                     _("Close Table"), titles,
                                     size = (400, 300),
                                     style = wx.DEFAULT_DIALOG_STYLE |
                                             wx.RESIZE_BORDER)
        if dlg.ShowModal() == wx.ID_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 = MultipleChoiceDialog(self, _("Pick the table to show:"),
                                     _("Show Table"), titles,
                                     size = (400,300),
                                     style = wx.DEFAULT_DIALOG_STYLE |
                                             wx.RESIZE_BORDER)
        if (dlg.ShowModal() == wx.ID_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 = MultipleChoiceDialog(self, _("Pick the table to rename:"),
                                     _("Rename Table"), titles,
                                     size = (400,300),
                                     style = wx.DEFAULT_DIALOG_STYLE |
                                             wx.RESIZE_BORDER)
        if (dlg.ShowModal() == wx.ID_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 = wx.TextEntryDialog(self, _("Table Title:"), _("Rename Table"),
                                    table.Title())
            try:
                if dlg.ShowModal() == wx.ID_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 = wx.TextEntryDialog(self, _("Map Title:"), _("Rename Map"),
                                self.Map().Title())
        if dlg.ShowModal() == wx.ID_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 = wx.TextEntryDialog(self, _("Layer Title:"), _("Rename Layer"),
                                    layer.Title())
            try:
                if dlg.ShowModal() == wx.ID_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, mymap):
        """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.
        """
        mymap = self.Map()
        if mymap is not None:
            title = _("Thuban - %s") % (mymap.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."""
    mymap = context.mainwindow.Map()
    if mymap is not None:
        for layer in mymap.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 wx.Platform == '__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"])