jschuengel: thuban/Extensions/umn_mapserver mf_import.py,1.9,1.10

cvs@intevation.de cvs at intevation.de
Tue Aug 3 13:58:07 CEST 2004


Author: jschuengel

Update of /thubanrepository/thuban/Extensions/umn_mapserver
In directory doto:/tmp/cvs-serv14479

Modified Files:
	mf_import.py 
Log Message:
Added a Class and a function to show the Annotation layer in thuban. The layer don't do anything.
Its only to show the layer. Necessary to save the layer order.
Added a funtion to import only layers to thuban and not the other settings like projection or scalebar.
Moved the _has_umn_mapobj function and the create_new_mapfile functions from mf_handle.py to mf_import.py.
(select_layer2import): Moved the code for showing the number of layer from import_mapfile to this function.


Index: mf_import.py
===================================================================
RCS file: /thubanrepository/thuban/Extensions/umn_mapserver/mf_import.py,v
retrieving revision 1.9
retrieving revision 1.10
diff -u -d -r1.9 -r1.10
--- mf_import.py	28 Jul 2004 12:44:26 -0000	1.9
+++ mf_import.py	3 Aug 2004 11:58:05 -0000	1.10
@@ -47,7 +47,7 @@
 from Thuban.Model.proj import Projection
 
 # needed to add the new menu
-from Thuban.UI.mainwindow import main_menu
+from Thuban.UI.mainwindow import main_menu, wxID_CANCEL
 
 from Thuban.Model.classification import ClassGroupSingleton, \
                                         ClassGroupRange, \
@@ -67,6 +67,49 @@
 # Mainpart of the Extension
 #
 # ###################################
+from Thuban.Model.layer import BaseLayer
+class AnnotationLayer(BaseLayer):
+    """
+    Class to show AnnontationLayer in Thuban.
+    This Class is temporary and has only the task 
+    to indicate the layer in the layerlist.
+    """
+    def __init__(self, title, data, visible = False, projection = None):
+        
+        BaseLayer.__init__(self, title, 
+                                 visible = visible,
+                                 projection = projection)
+        self.store = None
+        self.SetShapeStore(data)
+    
+    def SetShapeStore(self, store):
+        self.store = store
+    
+    def ShapeStore(self):
+        return self.store
+    
+    def ShapeType(self):
+        """Return the type of the shapes in the layer.
+        """
+        return "annotation"
+    
+    def BoundingBox(self):
+        """Return the layer's bounding box in the intrinsic coordinate system.
+
+        If the layer has no shapes, return None.
+        """
+        return self.store.BoundingBox()
+
+    def LatLongBoundingBox(self):
+        """Return the layer's bounding box in lat/long coordinates.
+
+        Return None, if the layer doesn't contain any shapes.
+        """
+        bbox = self.BoundingBox()
+        if bbox is not None and self.projection is not None:
+            bbox = self.projection.InverseBBox(bbox)
+        return bbox
+
 
 def set_projection_to_tb(tb_con, mapobj):
     """
@@ -195,6 +238,45 @@
     else:
         return (None,errorstring)
 
+def add_annotationlayer(context, tb_map, mapobj, maplayer):
+    """
+    add a polygonlayer to thuban
+    
+    tb_map = context.mainwindow.canvas.Map()
+    
+    mapobj = the Mapobject created from the mapfile
+    
+    maplayer = layer obj to add to thuban
+    """
+    filepath = mapobj.get_mappath()
+    layertitle = maplayer.get_name()
+    if maplayer.get_data():
+        if os.path.isabs(maplayer.get_data()):
+            filename = maplayer.get_data() +".shp"
+        else:
+            filename = os.path.join(filepath, mapobj.get_shapepath(), \
+                                           maplayer.get_data())
+            filename = filename + ".shp"
+        # Normalize the pathname by collapses 
+        # redundant separators and up-level references
+        filename = os.path.normpath(filename)
+    else:
+        context.mainwindow.RunMessageBox(_('Error Loading Layer'),
+            _("no shp file definied, maybe used a feature obj '%s'.") % layertitle)
+    # try to open the layer
+    try:
+        store = context.application.Session().OpenShapefile(filename)
+    except IOError:
+        # the layer couldn't be opened
+        context.mainwindow.RunMessageBox(_('Open Shapepath'),
+                                         _("Can't open the file '%s'.") % filename)
+    else:
+        # added an annotation layer as empty layer to thuban
+        # because thuban don't supports annotation.
+        layertitle = maplayer.get_name()
+        annotationlayer = AnnotationLayer(layertitle,store)
+        tb_map.AddLayer(annotationlayer)
+    
 
 def add_rasterlayer(context, tb_map, mapobj, maplayer):
     """
@@ -396,21 +478,27 @@
         #add the projection if exists
         set_projection_to_tb(layer, maplayer)
         
-        # associate the maplayer object to the layer in thuban.
-        layer.extension_umn_layerobj = maplayer
-    
-        #add the projection if exists
-        set_projection_to_tb(layer, maplayer)
-
+        # associate a copy of the maplayer object to the layer in thuban.
+        # layer.extension_umn_layerobj =maplayer
         #add the layer into thuban
         tb_map.AddLayer(layer)
 
+
 def select_layer2import(context, mapobj):
     """
     shows a dialog to select the layers to import.
     
     mapobj = the Mapobject created from the mapfile
     """
+    # Show number of Layer found in file
+    numlayers = len(mapobj.get_layers())
+    if numlayers == 0:
+        context.mainwindow.RunMessageBox(_('Loading Layer'),
+                                     _("No Layer found."))
+    else:
+        context.mainwindow.RunMessageBox(_('Loading Layer'),
+                                         _("%s Layer loaded from file.") % numlayers)
+    # Show a dialog to select layers to load into thuban only    
     lst = []
     selectedlayer = []
     numlayers = len(mapobj.get_layers())
@@ -430,17 +518,11 @@
         selectedlayer = dlg.GetValue()
     return selectedlayer
 
-
-def import_mapfile(context):
+def import_layer_from_mapfile(context):
     """
-    Import the mapfile from a file given by the user. After that parse
-    the mapfile with the mapscript parser to create all necessary objects.
-
-    Loaded polygon layer like polygon, line or point into thuban.
-    Raster layer are supported also.
-
-    context - the thuban context
+    Import only the layers which are selectes from a mapfile
     """
+    # open a dialog to select the mapfile to import
     dlg = wxFileDialog(context.mainwindow,
                        _("Select MapFile file"), ".", "",
                        _("UMN MapServer Mapfiles (*.map)|*.map|") +
@@ -451,10 +533,10 @@
         dlg.Destroy()
     else:
         return
-        
+
     # Parse mapfile
     mapobj = parse_mapfile(filename)
-
+    
     # Show number of Layer found in file
     numlayers = len(mapobj.get_layers())
     if numlayers == 0:
@@ -469,16 +551,36 @@
         selectedlayer = select_layer2import(context,mapobj)
     else:
         selectedlayer = []
+
+def import_layer_from_mapfile(context):
+    """
+    import layers from a mapfile
+    """
+    # open a dialog to select the mapfile to import from
+    dlg = wxFileDialog(context.mainwindow,
+                       _("Select MapFile file"), ".", "",
+                       _("UMN MapServer Mapfiles (*.map)|*.map|") +
+                       _("All Files (*.*)|*.*"),
+                       wxOPEN|wxOVERWRITE_PROMPT)
+    if dlg.ShowModal() == wxID_OK:
+        filename = dlg.GetPath()
+        dlg.Destroy()
+    else:
+        return
+        
+    # Parse mapfile
+    mapobj = parse_mapfile(filename)
+    oldmapobj = context.mainwindow.canvas.Map().extension_umn_mapobj
+
+    # shows a dialog to select layers to import
+    selectedlayer = select_layer2import(context,mapobj)
+
     # counter to show the numer of layer loaded into Tuban
     layer_count = 0
     # import settings to thuban only if one layer is selected
     if len(selectedlayer) != 0:
         # thuban map context
         tb_map = context.mainwindow.canvas.Map()
-        # set the titel and projection
-        tb_map.SetTitle(mapobj.get_name())
-        set_projection_to_tb(tb_map,mapobj)
-            
         # Check for each Layer if it is possible to show in Thuban
         for layernr in selectedlayer:
             maplayer = mapobj.get_layers()[layernr]
@@ -495,27 +597,103 @@
                  (maplayer.get_type() == 'point')):
                 add_polygonlayer(context, tb_map, mapobj, maplayer)
                 layer_count += 1
-        
-        # remove alle layer from the mapobj, because the layer will be
-        # created new in export, and the unused layers are not needed
-        # TODO: Save the layers which are not used somewhere, to edit
-        # them later and export it.
-        for nr in range(len(mapobj.get_layers())-1, -1, -1):
-            mapobj.remove_layer(nr)
-
-        # add the map object to thuban, to use it later
-        tb_map.extension_umn_mapobj = mapobj
+            
+            if (maplayer.get_type() == 'annotation'):
+                add_annotationlayer(context, tb_map, mapobj, maplayer)
 
         # show a message how many layer were loaded into thuban
         # if the number of layers is not null
         if layer_count != 0:
-            # get the extent from the map and set it in thuban
-            extentrect = mapobj.get_extent().get_rect()
-            # fit the new map extent to the window
-            context.mainwindow.canvas.FitRectToWindow(extentrect)
             context.mainwindow.RunMessageBox(_('Layer loaded'),
                                              _("%s Layer loaded into Thuban") % layer_count)
 
+def import_mapfile(context):
+    """
+    Import the mapfile from a file given by the user. After that parse
+    the mapfile with the mapscript parser to create all necessary objects.
+
+    Loaded polygon layer like polygon, line or point into thuban.
+    Raster layer are supported also.
+
+    context - the thuban context
+    """
+    # create a new session befor a mapfile is imported
+    if context.mainwindow.save_modified_session() != wxID_CANCEL:
+        context.application.SetSession(mainwindow.create_empty_session())
+        
+        # context.mainwindow.NewSession()
+        # open a dialog to select the mapfile to import
+        dlg = wxFileDialog(context.mainwindow,
+                           _("Select MapFile file"), ".", "",
+                           _("UMN MapServer Mapfiles (*.map)|*.map|") +
+                           _("All Files (*.*)|*.*"),
+                           wxOPEN|wxOVERWRITE_PROMPT)
+        if dlg.ShowModal() == wxID_OK:
+            filename = dlg.GetPath()
+            dlg.Destroy()
+        else:
+            return
+        
+        # Parse mapfile
+        mapobj = parse_mapfile(filename)
+    
+        # shows a dialog to select layers to import
+        selectedlayer = select_layer2import(context,mapobj)
+        
+        # counter to show the numer of layer loaded into Tuban
+        layer_count = 0
+        # import settings to thuban only if one layer is selected
+        if len(selectedlayer) != 0:
+            # thuban map context
+            tb_map = context.mainwindow.canvas.Map()
+            # set the titel and projection
+            tb_map.SetTitle(mapobj.get_name())
+            set_projection_to_tb(tb_map,mapobj)
+
+            selectedlayer = list(selectedlayer)
+
+            # Check for each Layer if it is possible to show in Thuban
+            for layernr in selectedlayer:
+
+                maplayer = mapobj.get_layers()[layernr]
+                
+                #check if rasterlayer type
+                if maplayer.get_type() == 'raster':
+                    add_rasterlayer(context, tb_map, mapobj, maplayer)
+                    layer_count += 1
+        
+                #check if polygonlayer type
+                if ((maplayer.get_type() == 'polygon') or   
+                     (maplayer.get_type() == 'line') or
+                     (maplayer.get_type() == 'circle') or
+                     (maplayer.get_type() == 'point')):
+                    add_polygonlayer(context, tb_map, mapobj, maplayer)
+                    layer_count += 1
+                
+                if (maplayer.get_type() == 'annotation'):
+                    add_annotationlayer(context, tb_map, mapobj, maplayer)
+                    layer_count += 1
+    
+            # remove alle layer from the mapobj, because the layer will be
+            # created new in export, and the unused layers are not needed
+            # TODO: Save the layers which are not used somewhere, to edit
+            # them later and export it.
+    ##~         for nr in range(len(mapobj.get_layers())-1, -1, -1):
+    ##~             mapobj.remove_layer(nr)
+    
+            # add the map object to thuban, to use it later
+            tb_map.extension_umn_mapobj = mapobj
+    
+            # show a message how many layer were loaded into thuban
+            # if the number of layers is not null
+            if layer_count != 0:
+                # get the extent from the map and set it in thuban
+                extentrect = mapobj.get_extent().get_rect()
+                # fit the new map extent to the window
+                context.mainwindow.canvas.FitRectToWindow(extentrect)
+                context.mainwindow.RunMessageBox(_('Layer loaded'),
+                                                 _("%s Layer loaded into Thuban") % layer_count)
+
 def parse_mapfile(filename):
     """
     Parse the mapfile.
@@ -531,6 +709,15 @@
 
     return MF_Map(theMap)
 
+# check if an mapobj exists, to control the menuitem is available or not
+def _has_umn_mapobj(context):
+    """Return true if a umn_mapobj exists"""
+    return hasattr(context.mainwindow.canvas.Map(), "extension_umn_mapobj")
+
+#create a new mapfile
+def create_new_mapfile(context):
+    theMap = MF_Map(mapObj(""))
+    context.mainwindow.canvas.Map().extension_umn_mapobj = theMap
 
 # ###################################
 #
@@ -538,14 +725,31 @@
 #
 # ###################################
 
-# register the new command
-registry.Add(Command("import_mapfile", _("Import mapfile"), import_mapfile,
-                     helptext = _("Import a mapfile")))
-
 # find the extensions menu (create it anew if not found)
 experimental_menu = main_menu.FindOrInsertMenu("experimental", _("Experimenta&l"))
 # find the extension menu and add a new submenu if found
 mapserver_menu = experimental_menu.FindOrInsertMenu("mapserver", _("&MapServer"))
 
+# register the new command
+registry.Add(Command("create_new_mapfile", _("Create new mapfile"), \
+                     create_new_mapfile, \
+		           helptext = _("Create a new empty mapscript MapObj")))
 # finally add the new entry to the extensions menu
-mapserver_menu.InsertItem("import_mapfile")
+mapserver_menu.InsertItem("create_new_mapfile")
+
+# register the new command
+registry.Add(Command("import_mapfile", _("Import mapfile"), import_mapfile,
+                     helptext = _("Import a mapfile")))
+# finally add the new entry to the extensions menu
+mapserver_menu.InsertItem("import_mapfile",  after = "create_new_mapfile" )
+
+# register the new command
+registry.Add(Command("import_layer_from_mapfile", _("Import layer from mapfile"), 
+                     import_layer_from_mapfile,
+                     helptext = _("Import a layer from a mapfile"),
+                     sensitive = _has_umn_mapobj))
+# finally add the new entry to the extensions menu
+mapserver_menu.InsertItem("import_layer_from_mapfile", 
+                          after = "import_mapfile" )
+
+





More information about the Thuban-devel mailing list

This site is hosted by Intevation GmbH (Datenschutzerklärung und Impressum | Privacy Policy and Imprint)