/[thuban]/branches/WIP-pyshapelib-bramz/Thuban/UI/mainwindow.py
ViewVC logotype

Diff of /branches/WIP-pyshapelib-bramz/Thuban/UI/mainwindow.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 150 by bh, Tue May 7 16:55:38 2002 UTC revision 653 by jonathan, Fri Apr 11 14:28:29 2003 UTC
# Line 1  Line 1 
1  # Copyright (C) 2001, 2002 by Intevation GmbH  # Copyright (C) 2001, 2002, 2003 by Intevation GmbH
2  # Authors:  # Authors:
3  # Jan-Oliver Wagner <[email protected]>  # Jan-Oliver Wagner <[email protected]>
4  # Bernhard Herzog <[email protected]>  # Bernhard Herzog <[email protected]>
# Line 12  The main window Line 12  The main window
12    
13  __version__ = "$Revision$"  __version__ = "$Revision$"
14    
15  import sys, os  __ThubanVersion__ = "0.2" #"$THUBAN_0_2$"
16    #__BuildDate__ = "$Date$"
17    
18    import os
19    
20  from wxPython.wx import *  from wxPython.wx import *
21    
22  import Thuban  import Thuban
23  from Thuban.Model.session import Session, create_empty_session  from Thuban import _
24  from Thuban.Model.map import Map  from Thuban.Model.session import create_empty_session
25  from Thuban.Model.layer import Layer  from Thuban.Model.layer import Layer
26  from Thuban.Model.color import Color  from Thuban.Model.color import Color
27  from Thuban.Model.proj import Projection  from Thuban.Model.proj import Projection
# Line 27  import view Line 30  import view
30  import tree  import tree
31  import proj4dialog  import proj4dialog
32  import tableview, identifyview  import tableview, identifyview
33    from Thuban.UI.classifier import Classifier
34    import legend
35    from menu import Menu
36    
37    from context import Context
38    from command import registry, Command, ToolCommand
39    from messages import LAYER_SELECTED, SHAPES_SELECTED, VIEW_POSITION, DOCKABLE_DOCKED, DOCKABLE_UNDOCKED, DOCKABLE_CLOSED
40    
41  import main  from Thuban.UI.dock import DockableWindow, DockFrame, DockPanel
42  from command import registry, Command  
43  from messages import SELECTED_SHAPE, VIEW_POSITION  import resource
44    
45    
46  # the directory where the toolbar icons are stored  # the directory where the toolbar icons are stored
47  bitmapdir = os.path.join(Thuban.__path__[0], os.pardir, "Resources", "Bitmaps")  bitmapdir = os.path.join(Thuban.__path__[0], os.pardir, "Resources", "Bitmaps")
48  bitmapext = ".xpm"  bitmapext = ".xpm"
49    
50    ID_WINDOW_LEGEND = 4001
51    ID_WINDOW_CANVAS = 4002
52    
53    
54  class MainWindow(wxFrame):  class MainWindow(DockFrame):
55    
56      def __init__(self, parent, ID, interactor):      # Some messages that can be subscribed/unsubscribed directly through
57          wxFrame.__init__(self, parent, ID, 'Thuban',      # the MapCanvas come in fact from other objects. This is a map to
58                           wxDefaultPosition, wxSize(400, 300))      # map those messages to the names of the instance variables they
59        # actually come from. This delegation is implemented in the
60        # Subscribe and unsubscribed methods
61        delegated_messages = {LAYER_SELECTED: "canvas",
62                              SHAPES_SELECTED: "canvas"}
63    
64        # Methods delegated to some instance variables. The delegation is
65        # implemented in the __getattr__ method.
66        delegated_methods = {"SelectLayer": "canvas",
67                             "SelectShapes": "canvas",
68                             }
69    
70        def __init__(self, parent, ID, title, application, interactor,
71                     initial_message = None, size = wxSize(-1, -1)):
72            DockFrame.__init__(self, parent, ID, title, wxDefaultPosition, size)
73            #wxFrame.__init__(self, parent, ID, title, wxDefaultPosition, size)
74    
75          self.interactor = interactor          self.application = application
76    
77          self.CreateStatusBar()          self.CreateStatusBar()
78          self.SetStatusText("This is the wxPython-based "          if initial_message:
79                        "Graphical User Interface for exploring geographic data")              self.SetStatusText(initial_message)
80    
81          self.identify_view = None          self.identify_view = None
82    
83          self.init_ids()          self.init_ids()
84    
85          menuBar = wxMenuBar()          # creat the menubar from the main_menu description
86            self.SetMenuBar(self.build_menu_bar(main_menu))
87    
88          menu = wxMenu()          # Similarly, create the toolbar from main_toolbar
89          menuBar.Append(menu, "&File");          toolbar = self.build_toolbar(main_toolbar)
         for name in ["new_session", "open_session", None,  
                      "save_session", "save_session_as", None,  
                      "show_session_tree", None,  
                      "exit"]:  
             self.add_menu_command(menu, name)  
   
         menu = wxMenu()  
         menuBar.Append(menu, "&Map");  
         for name in ["layer_add", "layer_remove",  
                      None,  
                      "map_projection",  
                      None,  
                      "map_zoom_in_tool", "map_zoom_out_tool", "map_pan_tool",  
                      "map_identify_tool", "map_label_tool",  
                      None,  
                      "map_full_extent",  
                      None,  
                      "map_print"]:  
             self.add_menu_command(menu, name)  
   
         menu = wxMenu()  
         menuBar.Append(menu, "&Layer");  
         for name in ["layer_fill_color", "layer_transparent_fill",  
                      "layer_ourline_color", "layer_no_outline",  
                      None,  
                      "layer_raise", "layer_lower",  
                      None,  
                      "layer_show", "layer_hide",  
                      None,  
                      "layer_show_table"]:  
             self.add_menu_command(menu, name)  
   
         menu = wxMenu()  
         menuBar.Append(menu, "&Help");  
         self.add_menu_command(menu, "help_about")  
   
         self.SetMenuBar(menuBar)  
   
         # toolbar  
         toolbar = self.CreateToolBar(wxTB_3DBUTTONS)  
   
         # set the size of the tools' bitmaps. Not needed on wxGTK, but  
         # on Windows. We probably shouldn't hardwire the bitmap size  
         # here  
         toolbar.SetToolBitmapSize(wxSize(24, 24))  
   
         for name in ["map_zoom_in_tool", "map_zoom_out_tool", "map_pan_tool",  
                      "map_identify_tool", "map_label_tool", "map_full_extent"]:  
             self.add_toolbar_command(toolbar, name)  
90          # call Realize to make sure that the tools appear.          # call Realize to make sure that the tools appear.
91          toolbar.Realize()          toolbar.Realize()
92    
93    
94          # Create the map canvas          # Create the map canvas
95          canvas = view.MapCanvas(self, -1, interactor)          canvas = view.MapCanvas(self, -1)
96          canvas.Subscribe(VIEW_POSITION, self.view_position_changed)          canvas.Subscribe(VIEW_POSITION, self.view_position_changed)
97            canvas.Subscribe(SHAPES_SELECTED, self.identify_view_on_demand)
98          self.canvas = canvas          self.canvas = canvas
99    
100            self.SetMainWindow(self.canvas)
101    
102            self.SetAutoLayout(True)
103    
104          self.init_dialogs()          self.init_dialogs()
105    
106          interactor.Subscribe(SELECTED_SHAPE, self.identify_view_on_demand)          EVT_CLOSE(self, self._OnClose)
107    
108        def Subscribe(self, channel, *args):
109            """Subscribe a function to a message channel.
110    
111          EVT_CLOSE(self, self.OnClose)          If channel is one of the delegated messages call the appropriate
112            object's Subscribe method. Otherwise do nothing.
113            """
114            if channel in self.delegated_messages:
115                object = getattr(self, self.delegated_messages[channel])
116                object.Subscribe(channel, *args)
117            else:
118                print "Trying to subscribe to unsupported channel %s" % channel
119    
120        def Unsubscribe(self, channel, *args):
121            """Unsubscribe a function from a message channel.
122    
123            If channel is one of the delegated messages call the appropriate
124            object's Unsubscribe method. Otherwise do nothing.
125            """
126            if channel in self.delegated_messages:
127                object = getattr(self, self.delegated_messages[channel])
128                object.Unsubscribe(channel, *args)
129    
130        def __getattr__(self, attr):
131            """If attr is one of the delegated methods return that method
132    
133            Otherwise raise AttributeError.
134            """
135            if attr in self.delegated_methods:
136                return getattr(getattr(self, self.delegated_methods[attr]), attr)
137            raise AttributeError(attr)
138    
139      def init_ids(self):      def init_ids(self):
140          """Initialize the ids"""          """Initialize the ids"""
141          self.current_id = 6000          self.current_id = 6000
142          self.id_to_name = {}          self.id_to_name = {}
143          self.name_to_id = {}          self.name_to_id = {}
144            self.events_bound = {}
145    
146      def get_id(self, name):      def get_id(self, name):
147          """Return the wxWindows id for the command named name.          """Return the wxWindows id for the command named name.
# Line 138  class MainWindow(wxFrame): Line 154  class MainWindow(wxFrame):
154              self.name_to_id[name] = ID              self.name_to_id[name] = ID
155              self.id_to_name[ID] = name              self.id_to_name[ID] = name
156          return ID          return ID
157            
158        def bind_command_events(self, command, ID):
159            """Bind the necessary events for the given command and ID"""
160            if not self.events_bound.has_key(ID):
161                # the events haven't been bound yet
162                EVT_MENU(self, ID, self.invoke_command)
163                if command.IsDynamic():
164                    EVT_UPDATE_UI(self, ID, self.update_command_ui)
165    
166        def build_menu_bar(self, menudesc):
167            """Build and return the menu bar from the menu description"""
168            menu_bar = wxMenuBar()
169    
170            for item in menudesc.items:
171                # here the items must all be Menu instances themselves
172                menu_bar.Append(self.build_menu(item), item.title)
173    
174            return menu_bar
175    
176        def build_menu(self, menudesc):
177            """Return a wxMenu built from the menu description menudesc"""
178            wxmenu = wxMenu()
179            last = None
180            for item in menudesc.items:
181                if item is None:
182                    # a separator. Only add one if the last item was not a
183                    # separator
184                    if last is not None:
185                        wxmenu.AppendSeparator()
186                elif isinstance(item, Menu):
187                    # a submenu
188                    wxmenu.AppendMenu(wxNewId(), item.title, self.build_menu(item))
189                else:
190                    # must the name the name of a command
191                    self.add_menu_command(wxmenu, item)
192                last = item
193            return wxmenu
194    
195        def build_toolbar(self, toolbardesc):
196            """Build and return the main toolbar window from a toolbar description
197    
198            The parameter should be an instance of the Menu class but it
199            should not contain submenus.
200            """
201            toolbar = self.CreateToolBar(wxTB_3DBUTTONS)
202    
203            # set the size of the tools' bitmaps. Not needed on wxGTK, but
204            # on Windows, although it doesn't work very well there. It seems
205            # that only 16x16 icons are really supported on windows.
206            # We probably shouldn't hardwire the bitmap size here.
207            toolbar.SetToolBitmapSize(wxSize(24, 24))
208    
209            for item in toolbardesc.items:
210                if item is None:
211                    toolbar.AddSeparator()
212                else:
213                    # assume it's a string.
214                    self.add_toolbar_command(toolbar, item)
215    
216            return toolbar
217    
218      def add_menu_command(self, menu, name):      def add_menu_command(self, menu, name):
219          """Add the command with name name to the menu menu.          """Add the command with name name to the menu menu.
220    
# Line 152  class MainWindow(wxFrame): Line 228  class MainWindow(wxFrame):
228                  ID = self.get_id(name)                  ID = self.get_id(name)
229                  menu.Append(ID, command.Title(), command.HelpText(),                  menu.Append(ID, command.Title(), command.HelpText(),
230                              command.IsCheckCommand())                              command.IsCheckCommand())
231                  EVT_MENU(self, ID, self.invoke_command)                  self.bind_command_events(command, ID)
                 if command.IsDynamic():  
                     EVT_UPDATE_UI(self, ID, self.update_command_ui)  
232              else:              else:
233                  print "Unknown command %s" % name                  print _("Unknown command %s") % name
234    
235      def add_toolbar_command(self, toolbar, name):      def add_toolbar_command(self, toolbar, name):
236          """Add the command with name name to the toolbar toolbar.          """Add the command with name name to the toolbar toolbar.
# Line 171  class MainWindow(wxFrame): Line 245  class MainWindow(wxFrame):
245              command = registry.Command(name)              command = registry.Command(name)
246              if command is not None:              if command is not None:
247                  ID = self.get_id(name)                  ID = self.get_id(name)
248                  filename = os.path.join(bitmapdir, command.Icon()) + bitmapext                  bitmap = resource.GetBitmapResource(command.Icon(),
249                  bitmap = wxBitmap(filename, wxBITMAP_TYPE_XPM)                                                      wxBITMAP_TYPE_XPM)
250                  toolbar.AddTool(ID, bitmap,                  toolbar.AddTool(ID, bitmap,
251                                  shortHelpString = command.HelpText(),                                  shortHelpString = command.HelpText(),
252                                  isToggle = command.IsCheckCommand())                                  isToggle = command.IsCheckCommand())
253                    self.bind_command_events(command, ID)
254              else:              else:
255                  print "Unknown command %s" % name                  print _("Unknown command %s") % name
256    
257        def Context(self):
258            """Return the context object for a command invoked from this window
259            """
260            return Context(self.application, self.application.Session(), self)
261    
262      def invoke_command(self, event):      def invoke_command(self, event):
263          name = self.id_to_name.get(event.GetId())          name = self.id_to_name.get(event.GetId())
264          if name is not None:          if name is not None:
265              command = registry.Command(name)              command = registry.Command(name)
266              command.Execute(self)              command.Execute(self.Context())
267          else:          else:
268              print "Unknown command ID %d" % event.GetId()              print _("Unknown command ID %d") % event.GetId()
269    
270      def update_command_ui(self, event):      def update_command_ui(self, event):
271          #print "update_command_ui", self.id_to_name[event.GetId()]          #print "update_command_ui", self.id_to_name[event.GetId()]
272            context = self.Context()
273          command = registry.Command(self.id_to_name[event.GetId()])          command = registry.Command(self.id_to_name[event.GetId()])
274          if command is not None:          if command is not None:
275              event.Enable(command.Sensitive(self))              sensitive = command.Sensitive(context)
276              event.SetText(command.DynText(self))              event.Enable(sensitive)
277                if command.IsTool() and not sensitive and command.Checked(context):
278                    # When a checked tool command is disabled deselect all
279                    # tools. Otherwise the tool would remain active but it
280                    # might lead to errors if the tools stays active. This
281                    # problem occurred in GREAT-ER and this fixes it, but
282                    # it's not clear to me whether this is really the best
283                    # way to do it (BH, 20021206).
284                    self.canvas.SelectTool(None)
285                event.SetText(command.DynText(context))
286              if command.IsCheckCommand():              if command.IsCheckCommand():
287                  event.Check(command.Checked(self))                      event.Check(command.Checked(context))
288    
289      def RunMessageBox(self, title, text, flags = wxOK | wxICON_INFORMATION):      def RunMessageBox(self, title, text, flags = wxOK | wxICON_INFORMATION):
290          """Run a modla message box with the given text, title and flags          """Run a modal message box with the given text, title and flags
291          and return the result"""          and return the result"""
292          dlg = wxMessageDialog(self, text, title, flags)          dlg = wxMessageDialog(self, text, title, flags)
293            dlg.CenterOnParent()
294          result = dlg.ShowModal()          result = dlg.ShowModal()
295          dlg.Destroy()          dlg.Destroy()
296          return result          return result
# Line 213  class MainWindow(wxFrame): Line 304  class MainWindow(wxFrame):
304    
305      def add_dialog(self, name, dialog):      def add_dialog(self, name, dialog):
306          if self.dialogs.has_key(name):          if self.dialogs.has_key(name):
307              raise RuntimeError("The Dialog named %s is already open" % name)              raise RuntimeError(_("The Dialog named %s is already open") % name)
308          self.dialogs[name] = dialog          self.dialogs[name] = dialog
309    
310      def dialog_open(self, name):      def dialog_open(self, name):
# Line 231  class MainWindow(wxFrame): Line 322  class MainWindow(wxFrame):
322              text = "(%10.10g, %10.10g)" % pos              text = "(%10.10g, %10.10g)" % pos
323          else:          else:
324              text = ""              text = ""
325            self.set_position_text(text)
326    
327        def set_position_text(self, text):
328            """Set the statusbar text showing the current position.
329    
330            By default the text is shown in field 0 of the status bar.
331            Override this method in derived classes to put it into a
332            different field of the statusbar.
333            """
334          self.SetStatusText(text)          self.SetStatusText(text)
335    
336      def save_modified_session(self, can_veto = 1):      def save_modified_session(self, can_veto = 1):
# Line 242  class MainWindow(wxFrame): Line 342  class MainWindow(wxFrame):
342          If the can_veto parameter is true (default) the dialog includes          If the can_veto parameter is true (default) the dialog includes
343          a cancel button, otherwise not.          a cancel button, otherwise not.
344          """          """
345          if main.app.session.WasModified():          if self.application.session.WasModified():
346              flags = wxYES_NO | wxICON_QUESTION              flags = wxYES_NO | wxICON_QUESTION
347              if can_veto:              if can_veto:
348                  flags = flags | wxCANCEL                  flags = flags | wxCANCEL
349              result = self.RunMessageBox("Exit",              result = self.RunMessageBox(_("Exit"),
350                                          ("The session has been modified."                                          _("The session has been modified."
351                                           " Do you want to save it?"),                                           " Do you want to save it?"),
352                                          flags)                                          flags)
353              if result == wxID_YES:              if result == wxID_YES:
# Line 256  class MainWindow(wxFrame): Line 356  class MainWindow(wxFrame):
356              result = wxID_NO              result = wxID_NO
357          return result          return result
358    
359        def prepare_new_session(self):
360            for d in self.dialogs.values():
361                if not isinstance(d, tree.SessionTreeView):
362                    d.Close()
363    
364      def NewSession(self):      def NewSession(self):
365          self.save_modified_session()          self.save_modified_session()
366          main.app.SetSession(create_empty_session())          self.prepare_new_session()
367            self.application.SetSession(create_empty_session())
368    
369      def OpenSession(self):      def OpenSession(self):
370          self.save_modified_session()          self.save_modified_session()
371          dlg = wxFileDialog(self, "Select a session file", ".", "",          dlg = wxFileDialog(self, _("Open Session"), ".", "", "*.thuban", wxOPEN)
                            "*.thuban", wxOPEN)  
372          if dlg.ShowModal() == wxID_OK:          if dlg.ShowModal() == wxID_OK:
373              main.app.OpenSession(dlg.GetPath())              self.prepare_new_session()
374                self.application.OpenSession(dlg.GetPath())
375          dlg.Destroy()          dlg.Destroy()
376    
377      def SaveSession(self):      def SaveSession(self):
378          if main.app.session.filename == None:          if self.application.session.filename == None:
379              self.SaveSessionAs()              self.SaveSessionAs()
380          main.app.SaveSession()          else:
381                self.application.SaveSession()
382    
383      def SaveSessionAs(self):      def SaveSessionAs(self):
384          dlg = wxFileDialog(self, "Enter a filename for session", ".", "",          dlg = wxFileDialog(self, _("Save Session As"), ".", "",
385                             "*.thuban", wxOPEN)                             "*.thuban", wxOPEN)
386          if dlg.ShowModal() == wxID_OK:          if dlg.ShowModal() == wxID_OK:
387              main.app.session.SetFilename(dlg.GetPath())              self.application.session.SetFilename(dlg.GetPath())
388              main.app.SaveSession()              self.application.SaveSession()
389          dlg.Destroy()          dlg.Destroy()
390    
391      def Exit(self):      def Exit(self):
392          self.Close(false)          self.Close(False)
393    
394      def OnClose(self, event):      def _OnClose(self, event):
395          result = self.save_modified_session(can_veto = event.CanVeto())          result = self.save_modified_session(can_veto = event.CanVeto())
396          if result == wxID_CANCEL:          if result == wxID_CANCEL:
397              event.Veto()              event.Veto()
398          else:          else:
399                # FIXME: it would be better to tie the unsubscription to
400                # wx's destroy event, but that isn't implemented for wxGTK
401                # yet.
402                self.canvas.Unsubscribe(VIEW_POSITION, self.view_position_changed)
403                DockFrame._OnClose(self, event)
404              self.Destroy()              self.Destroy()
405    
406      def SetMap(self, map):      def SetMap(self, map):
407          self.canvas.SetMap(map)          self.canvas.SetMap(map)
408            self.__SetTitle(map.Title())
409            #self.legendPanel.SetMap(map)
410    
411        def Map(self):
412            """Return the map displayed by this mainwindow"""
413    
414      def ShowSessionTree(self):          # sanity check
415            #assert(self.canvas.Map() is self.legendPanel.GetMap())
416    
417            return self.canvas.Map()
418    
419        def ToggleSessionTree(self):
420            """If the session tree is shown close it otherwise create a new tree"""
421          name = "session_tree"          name = "session_tree"
422          dialog = self.get_open_dialog(name)          dialog = self.get_open_dialog(name)
423          if dialog is None:          if dialog is None:
424              dialog = tree.SessionTreeView(self, main.app, name)              dialog = tree.SessionTreeView(self, self.application, name)
425              self.add_dialog(name, dialog)              self.add_dialog(name, dialog)
426              dialog.Show(true)              dialog.Show(True)
427          else:          else:
428              # FIXME: bring dialog to front here              dialog.Close()
429              pass  
430        def SessionTreeShown(self):
431            """Return true iff the session tree is currently shown"""
432            return self.get_open_dialog("session_tree") is not None
433    
434      def About(self):      def About(self):
435          self.RunMessageBox("About",          self.RunMessageBox(_("About"),
436                             ("Thuban is a program for\n"                             _("Thuban v%s\n"
437                                #"Build Date: %s\n"
438                                "\n"
439                                "Thuban is a program for\n"
440                              "exploring geographic data.\n"                              "exploring geographic data.\n"
441                              "Copyright (C) 2001 Intevation GmbH.\n"                              "Copyright (C) 2001-2003 Intevation GmbH.\n"
442                              "Thuban is licensed under the GPL"),                              "Thuban is licensed under the GNU GPL"
443                               % __ThubanVersion__), #__BuildDate__)),
444                             wxOK | wxICON_INFORMATION)                             wxOK | wxICON_INFORMATION)
445    
446      def AddLayer(self):      def AddLayer(self):
447          dlg = wxFileDialog(self, "Select a data file", ".", "", "*.*",          dlg = wxFileDialog(self, _("Select a data file"), ".", "", "*.*",
448                             wxOPEN)                             wxOPEN)
449          if dlg.ShowModal() == wxID_OK:          if dlg.ShowModal() == wxID_OK:
450              filename = dlg.GetPath()              filename = dlg.GetPath()
# Line 326  class MainWindow(wxFrame): Line 456  class MainWindow(wxFrame):
456                  map.AddLayer(layer)                  map.AddLayer(layer)
457              except IOError:              except IOError:
458                  # the layer couldn't be opened                  # the layer couldn't be opened
459                  self.RunMessageBox("Add Layer",                  self.RunMessageBox(_("Add Layer"),
460                                     "Can't open the file '%s'." % filename)                                     _("Can't open the file '%s'.") % filename)
461              else:              else:
462                  if not has_layers:                  if not has_layers:
463                      # if we're adding a layer to an empty map, for the                      # if we're adding a layer to an empty map, fit the
464                      # new map to the window                      # new map to the window
465                      self.canvas.FitMapToWindow()                      self.canvas.FitMapToWindow()
466          dlg.Destroy()          dlg.Destroy()
# Line 340  class MainWindow(wxFrame): Line 470  class MainWindow(wxFrame):
470          if layer is not None:          if layer is not None:
471              self.canvas.Map().RemoveLayer(layer)              self.canvas.Map().RemoveLayer(layer)
472    
473        def CanRemoveLayer(self):
474            """Return true if the currently selected layer can be deleted.
475    
476            If no layer is selected return False.
477    
478            The return value of this method determines whether the remove
479            layer command is sensitive in menu.
480            """
481            layer = self.current_layer()
482            if layer is not None:
483                return self.canvas.Map().CanRemoveLayer(layer)
484            return False
485    
486      def RaiseLayer(self):      def RaiseLayer(self):
487          layer = self.current_layer()          layer = self.current_layer()
488          if layer is not None:          if layer is not None:
489              self.canvas.Map().RaiseLayer(layer)              self.canvas.Map().RaiseLayer(layer)
490            
491      def LowerLayer(self):      def LowerLayer(self):
492          layer = self.current_layer()          layer = self.current_layer()
493          if layer is not None:          if layer is not None:
# Line 355  class MainWindow(wxFrame): Line 498  class MainWindow(wxFrame):
498    
499          If no layer is selected, return None          If no layer is selected, return None
500          """          """
501          return self.interactor.SelectedLayer()          return self.canvas.SelectedLayer()
502    
503      def has_selected_layer(self):      def has_selected_layer(self):
504          """Return true if a layer is currently selected"""          """Return true if a layer is currently selected"""
505          return self.interactor.HasSelectedLayer()          return self.canvas.HasSelectedLayer()
506    
507      def choose_color(self):      def choose_color(self):
508          """Run the color selection dialog and return the selected color.          """Run the color selection dialog and return the selected color.
# Line 377  class MainWindow(wxFrame): Line 520  class MainWindow(wxFrame):
520          dlg.Destroy()          dlg.Destroy()
521          return color          return color
522    
     def LayerFillColor(self):  
         layer = self.current_layer()  
         if layer is not None:  
             color = self.choose_color()  
             if color is not None:  
                 layer.SetFill(color)  
   
     def LayerTransparentFill(self):  
         layer = self.current_layer()  
         if layer is not None:  
             layer.SetFill(None)  
   
     def LayerOutlineColor(self):  
         layer = self.current_layer()  
         if layer is not None:  
             color = self.choose_color()  
             if color is not None:  
                 layer.SetStroke(color)  
   
     def LayerNoOutline(self):  
         layer = self.current_layer()  
         if layer is not None:  
             layer.SetStroke(None)  
   
523      def HideLayer(self):      def HideLayer(self):
524          layer = self.current_layer()          layer = self.current_layer()
525          if layer is not None:          if layer is not None:
# Line 418  class MainWindow(wxFrame): Line 537  class MainWindow(wxFrame):
537              name = "table_view" + str(id(table))              name = "table_view" + str(id(table))
538              dialog = self.get_open_dialog(name)              dialog = self.get_open_dialog(name)
539              if dialog is None:              if dialog is None:
540                  dialog = tableview.TableFrame(self, self.interactor, name,                  dialog = tableview.LayerTableFrame(self, name,
541                                                "Table: %s" % layer.Title(),                                                 _("Table: %s") % layer.Title(),
542                                                layer, table)                                                     layer, table)
543                  self.add_dialog(name, dialog)                  self.add_dialog(name, dialog)
544                  dialog.Show(true)                  dialog.Show(true)
545              else:              else:
# Line 444  class MainWindow(wxFrame): Line 563  class MainWindow(wxFrame):
563              map.SetProjection(proj)              map.SetProjection(proj)
564          proj4Dlg.Destroy()          proj4Dlg.Destroy()
565    
566        def LayerEditProperties(self):
567    
568            #
569            # the menu option for this should only be available if there
570            # is a current layer, so we don't need to check if the
571            # current layer is None
572            #
573    
574            layer = self.current_layer()
575            self.OpenLayerProperties(layer)
576    
577        def OpenLayerProperties(self, layer, group = None):
578            name = "layer_properties" + str(id(layer))
579            dialog = self.get_open_dialog(name)
580    
581            if dialog is None:
582                dialog = Classifier(self, name, layer, group)
583                self.add_dialog(name, dialog)
584                dialog.Show()
585            dialog.Raise()
586    
587    
588        def ShowLegend(self):
589            if not self.LegendShown():
590                self.ToggleLegend()
591    
592        def ToggleLegend(self):
593            """Show the legend if it's not shown otherwise hide it again"""
594            name = "legend"
595            dialog = self.FindRegisteredDock(name)
596    
597            if dialog is None:
598                dialog = self.CreateDock(name, -1, _("Legend"), wxLAYOUT_LEFT)
599                legend.LegendPanel(dialog, None, self)
600                dialog.Dock()
601                dialog.GetPanel().SetMap(self.Map())
602                dialog.Show()
603            else:
604                dialog.Show(not dialog.IsShown())
605    
606        def LegendShown(self):
607            """Return true iff the legend is currently open"""
608            dialog = self.FindRegisteredDock("legend")
609            return dialog is not None and dialog.IsShown()
610    
611      def ZoomInTool(self):      def ZoomInTool(self):
612          self.canvas.ZoomInTool()          self.canvas.ZoomInTool()
613    
# Line 466  class MainWindow(wxFrame): Line 630  class MainWindow(wxFrame):
630      def PrintMap(self):      def PrintMap(self):
631          self.canvas.Print()          self.canvas.Print()
632    
633      def identify_view_on_demand(self, layer, shape):      def RenameMap(self):
634            dlg = wxTextEntryDialog(self, "Map Title: ", "Rename Map",
635                                    self.Map().Title())
636            if dlg.ShowModal() == wxID_OK:
637                title = dlg.GetValue()
638                if title != "":
639                    self.Map().SetTitle(title)
640                    self.__SetTitle(title)
641    
642            dlg.Destroy()
643    
644        def identify_view_on_demand(self, layer, shapes):
645          name = "identify_view"          name = "identify_view"
646          if self.canvas.CurrentTool() == "IdentifyTool":          if self.canvas.CurrentTool() == "IdentifyTool":
647              if not self.dialog_open(name):              if not self.dialog_open(name):
648                  dialog = identifyview.IdentifyView(self, self.interactor, name)                  dialog = identifyview.IdentifyView(self, name)
649                  self.add_dialog(name, dialog)                  self.add_dialog(name, dialog)
650                  dialog.Show(true)                  dialog.Show(True)
651              else:              else:
652                  # FIXME: bring dialog to front?                  # FIXME: bring dialog to front?
653                  pass                  pass
654    
655        def __SetTitle(self, title):
656            self.SetTitle("Thuban - " + title)
657    
658  #  #
659  # Define all the commands available in the main window  # Define all the commands available in the main window
660  #  #
# Line 484  class MainWindow(wxFrame): Line 662  class MainWindow(wxFrame):
662    
663  # Helper functions to define common command implementations  # Helper functions to define common command implementations
664  def call_method(context, methodname, *args):  def call_method(context, methodname, *args):
665      """Call the context's method methodname with args *args"""      """Call the mainwindow's method methodname with args *args"""
666      apply(getattr(context, methodname), args)      apply(getattr(context.mainwindow, methodname), args)
667    
668  def _method_command(name, title, method, helptext = "",  def _method_command(name, title, method, helptext = "",
669                      icon = "", sensitive = None):                      icon = "", sensitive = None, checked = None):
670      """Add a command implemented by a method of the context object"""      """Add a command implemented by a method of the mainwindow object"""
671      registry.Add(Command(name, title, call_method, args=(method,),      registry.Add(Command(name, title, call_method, args=(method,),
672                           helptext = helptext, icon = icon,                           helptext = helptext, icon = icon,
673                           sensitive = sensitive))                           sensitive = sensitive, checked = checked))
674    
675    def make_check_current_tool(toolname):
676        """Return a function that tests if the currently active tool is toolname
677    
678        The returned function can be called with the context and returns
679        true iff the currently active tool's name is toolname. It's directly
680        usable as the 'checked' callback of a command.
681        """
682        def check_current_tool(context, name=toolname):
683            return context.mainwindow.canvas.CurrentTool() == name
684        return check_current_tool
685    
686  def _tool_command(name, title, method, toolname, helptext = "",  def _tool_command(name, title, method, toolname, helptext = "",
687                    icon = ""):                    icon = "", sensitive = None):
688      """Add a tool command"""      """Add a tool command"""
689      def check_current_tool(context, name=toolname):      registry.Add(ToolCommand(name, title, call_method, args=(method,),
690          return context.canvas.CurrentTool() == name                               helptext = helptext, icon = icon,
691      registry.Add(Command(name, title, call_method, args=(method,),                               checked = make_check_current_tool(toolname),
692                           helptext = helptext, icon = icon,                               sensitive = sensitive))
                          checked = check_current_tool))  
693    
694  def _has_selected_layer(context):  def _has_selected_layer(context):
695      """Return true if a layer is selected in the context"""      """Return true if a layer is selected in the context"""
696      return context.has_selected_layer()      return context.mainwindow.has_selected_layer()
697    
698    def _can_remove_layer(context):
699        return context.mainwindow.CanRemoveLayer()
700    
701    def _has_tree_window_shown(context):
702        """Return true if the tree window is shown"""
703        return context.mainwindow.SessionTreeShown()
704    
705    def _has_visible_map(context):
706        """Return true iff theres a visible map in the mainwindow.
707    
708        A visible map is a map with at least one visible layer."""
709        map = context.mainwindow.Map()
710        if map is not None:
711            for layer in map.Layers():
712                if layer.Visible():
713                    return 1
714        return 0
715    
716    def _has_legend_shown(context):
717        """Return true if the legend window is shown"""
718        return context.mainwindow.LegendShown()
719    
720    
721  # File menu  # File menu
722  _method_command("new_session", "&New Session", "NewSession")  _method_command("new_session", _("&New Session"), "NewSession")
723  _method_command("open_session", "&Open Session", "OpenSession")  _method_command("open_session", _("&Open Session"), "OpenSession")
724  _method_command("save_session", "&Save Session", "SaveSession")  _method_command("save_session", _("&Save Session"), "SaveSession")
725  _method_command("save_session_as", "Save Session &As", "SaveSessionAs")  _method_command("save_session_as", _("Save Session &As"), "SaveSessionAs")
726  _method_command("show_session_tree", "Show Session &Tree", "ShowSessionTree")  _method_command("toggle_session_tree", _("Session &Tree"), "ToggleSessionTree",
727  _method_command("exit", "&Exit", "Exit")                  checked = _has_tree_window_shown)
728    _method_command("toggle_legend", _("Legend"), "ToggleLegend",
729                    checked = _has_legend_shown)
730    _method_command("exit", _("E&xit"), "Exit")
731    
732  # Help menu  # Help menu
733  _method_command("help_about", "&About", "About")  _method_command("help_about", _("&About"), "About")
734    
735    
736  # Map menu  # Map menu
737  _method_command("map_projection", "Pro&jection", "Projection")  _method_command("map_projection", _("Pro&jection"), "Projection")
738    
739  _tool_command("map_zoom_in_tool", "&Zoom in", "ZoomInTool", "ZoomInTool",  _tool_command("map_zoom_in_tool", _("&Zoom in"), "ZoomInTool", "ZoomInTool",
740                helptext = "Switch to map-mode 'zoom-in'", icon = "zoom_in")                helptext = _("Switch to map-mode 'zoom-in'"), icon = "zoom_in",
741  _tool_command("map_zoom_out_tool", "Zoom &out", "ZoomOutTool", "ZoomOutTool",                sensitive = _has_visible_map)
742                helptext = "Switch to map-mode 'zoom-out'", icon = "zoom_out")  _tool_command("map_zoom_out_tool", _("Zoom &out"), "ZoomOutTool", "ZoomOutTool",
743  _tool_command("map_pan_tool", "&Pan", "PanTool", "PanTool",                helptext = _("Switch to map-mode 'zoom-out'"), icon = "zoom_out",
744                helptext = "Switch to map-mode 'pan'", icon = "pan")                sensitive = _has_visible_map)
745  _tool_command("map_identify_tool", "&Identify", "IdentifyTool", "IdentifyTool",  _tool_command("map_pan_tool", _("&Pan"), "PanTool", "PanTool",
746                helptext = "Switch to map-mode 'identify'", icon = "identify")                helptext = _("Switch to map-mode 'pan'"), icon = "pan",
747  _tool_command("map_label_tool", "&Label", "LabelTool", "LabelTool",                sensitive = _has_visible_map)
748                helptext = "Add/Remove labels", icon = "label")  _tool_command("map_identify_tool", _("&Identify"), "IdentifyTool",
749  _method_command("map_full_extent", "&Full extent", "FullExtent",                "IdentifyTool",
750                 helptext = "Full Extent", icon = "fullextent")                helptext = _("Switch to map-mode 'identify'"), icon = "identify",
751  _method_command("map_print", "Prin&t", "PrintMap", helptext = "Print the map")                sensitive = _has_visible_map)
752    _tool_command("map_label_tool", _("&Label"), "LabelTool", "LabelTool",
753                  helptext = _("Add/Remove labels"), icon = "label",
754                  sensitive = _has_visible_map)
755    _method_command("map_full_extent", _("&Full extent"), "FullExtent",
756                   helptext = _("Full Extent"), icon = "fullextent",
757                  sensitive = _has_visible_map)
758    _method_command("map_print", _("Prin&t"), "PrintMap",
759                    helptext = _("Print the map"))
760    _method_command("map_rename", _("&Rename"), "RenameMap",
761                    helptext = _("Rename the map"))
762    
763  # Layer menu  # Layer menu
764  _method_command("layer_add", "&Add Layer", "AddLayer",  _method_command("layer_add", _("&Add Layer"), "AddLayer",
765                  helptext = "Add a new layer to active map")                  helptext = _("Add a new layer to active map"))
766  _method_command("layer_remove", "&Remove Layer", "RemoveLayer",  _method_command("layer_remove", _("&Remove Layer"), "RemoveLayer",
767                  helptext = "Remove selected layer(s)",                  helptext = _("Remove selected layer(s)"),
768                  sensitive = _has_selected_layer)                  sensitive = _can_remove_layer)
769  _method_command("layer_fill_color", "&Fill Color", "LayerFillColor",  _method_command("layer_raise", _("&Raise"), "RaiseLayer",
770                  helptext = "Set the fill color of selected layer(s)",                  helptext = _("Raise selected layer(s)"),
                 sensitive = _has_selected_layer)  
 _method_command("layer_transparent_fill", "&Transparent Fill",  
                 "LayerTransparentFill",  
                 helptext = "Do not fill the selected layer(s)",  
771                  sensitive = _has_selected_layer)                  sensitive = _has_selected_layer)
772  _method_command("layer_ourline_color", "&Outline Color", "LayerOutlineColor",  _method_command("layer_lower", _("&Lower"), "LowerLayer",
773                  helptext = "Set the outline color of selected layer(s)",                  helptext = _("Lower selected layer(s)"),
774                  sensitive = _has_selected_layer)                  sensitive = _has_selected_layer)
775  _method_command("layer_no_outline", "&No Outline", "LayerNoOutline",  _method_command("layer_show", _("&Show"), "ShowLayer",
776                  helptext = "Do not draw the outline of the selected layer(s)",                  helptext = _("Make selected layer(s) visible"),
777                  sensitive = _has_selected_layer)                  sensitive = _has_selected_layer)
778  _method_command("layer_raise", "&Raise", "RaiseLayer",  _method_command("layer_hide", _("&Hide"), "HideLayer",
779                  helptext = "Raise selected layer(s)",                  helptext = _("Make selected layer(s) unvisible"),
780                  sensitive = _has_selected_layer)                  sensitive = _has_selected_layer)
781  _method_command("layer_lower", "&Lower", "LowerLayer",  _method_command("layer_show_table", _("Show Ta&ble"), "LayerShowTable",
782                  helptext = "Lower selected layer(s)",                  helptext = _("Show the selected layer's table"),
783                  sensitive = _has_selected_layer)                  sensitive = _has_selected_layer)
784  _method_command("layer_show", "&Show", "ShowLayer",  _method_command("layer_properties", _("Properties"), "LayerEditProperties",
                 helptext = "Make selected layer(s) visible",  
                 sensitive = _has_selected_layer)  
 _method_command("layer_hide", "&Hide", "HideLayer",  
                 helptext = "Make selected layer(s) unvisible",  
                 sensitive = _has_selected_layer)  
 _method_command("layer_show_table", "Show Ta&ble", "LayerShowTable",  
                 helptext = "Show the selected layer's table",  
785                  sensitive = _has_selected_layer)                  sensitive = _has_selected_layer)
786    
787    # the menu structure
788    main_menu = Menu("<main>", "<main>",
789                     [Menu("file", _("&File"),
790                           ["new_session", "open_session", None,
791                            "save_session", "save_session_as", None,
792                            "toggle_session_tree", None,
793                            "exit"]),
794                      Menu("map", _("&Map"),
795                           ["layer_add", "layer_remove",
796                            None,
797                            "map_projection",
798                            None,
799                            "map_zoom_in_tool", "map_zoom_out_tool",
800                            "map_pan_tool", "map_identify_tool", "map_label_tool",
801                            None,
802                            "map_full_extent",
803                            None,
804                            "toggle_legend",
805                            None,
806                            "map_print",
807                            None,
808                            "map_rename"]),
809                      Menu("layer", _("&Layer"),
810                            ["layer_raise", "layer_lower",
811                            None,
812                            "layer_show", "layer_hide",
813                            None,
814                            "layer_show_table",
815                            None,
816                            "layer_properties"]),
817                      Menu("help", _("&Help"),
818                           ["help_about"])])
819    
820    # the main toolbar
821    
822    main_toolbar = Menu("<toolbar>", "<toolbar>",
823                        ["map_zoom_in_tool", "map_zoom_out_tool", "map_pan_tool",
824                         "map_full_extent", None,
825                         "map_identify_tool", "map_label_tool"])

Legend:
Removed from v.150  
changed lines
  Added in v.653

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26