[GRASS-SVN] r61370 - in grass/branches/releasebranch_7_0: . gui/wxpython/core

svn_grass at osgeo.org svn_grass at osgeo.org
Wed Jul 23 04:50:20 PDT 2014


Author: neteler
Date: 2014-07-23 04:50:19 -0700 (Wed, 23 Jul 2014)
New Revision: 61370

Modified:
   grass/branches/releasebranch_7_0/
   grass/branches/releasebranch_7_0/gui/wxpython/core/render.py
   grass/branches/releasebranch_7_0/gui/wxpython/core/ws.py
Log:
 wxGUI/rendering: change environment only for subprocesses; wxGUI amd d.mon should now work together (trunk, r60376)


Property changes on: grass/branches/releasebranch_7_0
___________________________________________________________________
Modified: svn:mergeinfo
   - /grass/trunk:59505,59646,60215,60219,60278,60610,60807,60835,60936-60937,61159-61160,61165,61275,61288,61290,61292,61294,61301
   + /grass/trunk:59505,59646,60215,60219,60278,60376,60610,60807,60835,60936-60937,61159-61160,61165,61275,61288,61290,61292,61294,61301

Modified: grass/branches/releasebranch_7_0/gui/wxpython/core/render.py
===================================================================
--- grass/branches/releasebranch_7_0/gui/wxpython/core/render.py	2014-07-23 11:49:24 UTC (rev 61369)
+++ grass/branches/releasebranch_7_0/gui/wxpython/core/render.py	2014-07-23 11:50:19 UTC (rev 61370)
@@ -89,10 +89,11 @@
         self.renderMgr = None
 
         self.Map = Map
-        self.type      = None
+        self.type = None
         self.SetType(ltype)
-        self.name  = name
-        
+        self.name = name
+        self.environ = os.environ.copy()
+
         if self.type == 'command':
             self.cmd = list()
             for c in cmd:
@@ -139,7 +140,7 @@
                                  {'type' : self.type, 'name' : self.name})
         
         if self.mapfile:
-            os.environ["GRASS_PNGFILE"] = self.mapfile
+            self.environ["GRASS_PNGFILE"] = self.mapfile
         
         # execute command
         try:
@@ -150,9 +151,9 @@
                     if ret != 0:
                         break
                     if not read:
-                        os.environ["GRASS_PNG_READ"] = "TRUE"
+                        self.environ["GRASS_PNG_READ"] = "TRUE"
                 
-                os.environ["GRASS_PNG_READ"] = "FALSE"
+                self.environ["GRASS_PNG_READ"] = "FALSE"
             else:
                 ret, msg = self._runCommand(self.cmd)
             if ret != 0:
@@ -168,11 +169,7 @@
                     continue
                 grass.try_remove(f)
                 f = None
-        
-        # stop monitor
-        if self.mapfile and "GRASS_PNGFILE" in os.environ:
-            del os.environ["GRASS_PNGFILE"]
-        
+
         self.forceRender = False
         
         return self.mapfile
@@ -183,11 +180,12 @@
         if self.type == 'wms':
             ret = 0
             msg = ''
-            self.renderMgr.Render(cmd)
+            self.renderMgr.Render(cmd, env=self.environ)
         else:
             ret, msg = RunCommand(cmd[0],
                                   getErrorMsg = True,
                                   quiet = True,
+                                  env=self.environ,
                                   **cmd[1])
         
         return ret, msg
@@ -304,6 +302,10 @@
         # for re-rendering
         self.forceRender = True
 
+    def SetEnvironment(self, environ):
+        """!Sets environment for rendering."""
+        self.environ = environ
+
     def IsDownloading(self):
         """!Is data downloading from web server e. g. wms"""
         if self.renderMgr is None:
@@ -388,10 +390,7 @@
         
         self.overlays  = list()  # stack of available overlays
         self.ovlookup  = dict()  # lookup dictionary for overlay items and overlays
-        
-        # environment settings
-        self.env   = dict()
-        
+
         # path to external gisrc
         self.gisrc = gisrc
         
@@ -399,7 +398,6 @@
         self.mapfile = grass.tempfile(create = False) + '.ppm'
         
         # setting some initial env. variables
-        self._initGisEnv() # g.gisenv
         if not self.GetWindow():
             sys.stderr.write(_("Trying to recover from default region..."))
             RunCommand('g.region', flags='d')
@@ -408,16 +406,12 @@
         self.progressInfo = None
 
         # GRASS environment variable (for rendering)
-        self.env = {"GRASS_BACKGROUNDCOLOR" : "000000",
-               "GRASS_PNG_COMPRESSION" : "0",
-               "GRASS_TRUECOLOR"       : "TRUE",
-               "GRASS_TRANSPARENT"     : "TRUE",
-               "GRASS_PNG_READ"        : "FALSE",
-               }
+        self.default_env = {"GRASS_BACKGROUNDCOLOR" : "000000",
+                            "GRASS_PNG_COMPRESSION" : "0",
+                            "GRASS_TRUECOLOR"       : "TRUE",
+                            "GRASS_TRANSPARENT"     : "TRUE"
+                            }
 
-        for k, v in self.env.iteritems():
-            os.environ[k] = v
-
         # projection info
         self.projinfo = self._projInfo()
 
@@ -427,30 +421,6 @@
         self.layerChanged = Signal('Map.layerChanged')
         self.updateProgress = Signal('Map.updateProgress')
 
-    def _runCommand(self, cmd, **kwargs):
-        """!Run command in environment defined by self.gisrc if
-        defined"""
-        # use external gisrc if defined
-        gisrc_orig = os.getenv("GISRC")
-        if self.gisrc:
-            os.environ["GISRC"] = self.gisrc
-        
-        ret = cmd(**kwargs)
-        
-        # back to original gisrc
-        if self.gisrc:
-            os.environ["GISRC"] = gisrc_orig
-        
-        return ret
-    
-    def _initGisEnv(self):
-        """!Stores GRASS variables (g.gisenv) to self.env variable
-        """
-        if not os.getenv("GISBASE"):
-            sys.exit(_("GISBASE not set. You must be in GRASS GIS to run this program."))
-        
-        self.env = self._runCommand(grass.gisenv)
-            
     def GetProjInfo(self):
         """!Get projection info"""
         return self.projinfo
@@ -462,10 +432,11 @@
         if not grass.find_program('g.proj', '--help'):
             sys.exit(_("GRASS module '%s' not found. Unable to start map "
                        "display window.") % 'g.proj')
-        
-        ret = self._runCommand(RunCommand, prog = 'g.proj',
-                               read = True, flags = 'p')
-        
+        env = os.environ.copy()
+        if self.gisrc:
+            env['GISRC'] = self.gisrc
+        ret = RunCommand(prog='g.proj', read=True, flags='p', env=env)
+
         if not ret:
             return projinfo
         
@@ -485,9 +456,10 @@
     def GetWindow(self):
         """!Read WIND file and set up self.wind dictionary"""
         # FIXME: duplicated region WIND == g.region (at least some values)
-        filename = os.path.join (self.env['GISDBASE'],
-                                 self.env['LOCATION_NAME'],
-                                 self.env['MAPSET'],
+        env = grass.gisenv()
+        filename = os.path.join (env['GISDBASE'],
+                                 env['LOCATION_NAME'],
+                                 env['MAPSET'],
                                  "WIND")
         try:
             windfile = open (filename, "r")
@@ -629,15 +601,10 @@
         @see GetCurrentRegion()
         """
         region = {}
-        
-        tmpreg = os.getenv("GRASS_REGION")
-        if tmpreg:
-            del os.environ["GRASS_REGION"]
-        
-        # use external gisrc if defined
-        gisrc_orig = os.getenv("GISRC")
+
+        env = os.environ.copy()
         if self.gisrc:
-            os.environ["GISRC"] = self.gisrc
+            env['GISRC'] = self.gisrc
         
         # do not update & shell style output
         cmd = {}
@@ -676,6 +643,7 @@
         ret, reg, msg = RunCommand('g.region',
                                    read = True,
                                    getErrorMsg = True,
+                                   env=env,
                                    **cmd)
         
         if ret != 0:
@@ -701,15 +669,7 @@
                 region[key] = float(val)
             except ValueError:
                 region[key] = val
-        
-        # back to original gisrc
-        if self.gisrc:
-            os.environ["GISRC"] = gisrc_orig
-        
-        # restore region
-        if tmpreg:
-            os.environ["GRASS_REGION"] = tmpreg
-        
+
         Debug.msg (3, "Map.GetRegion(): %s" % region)
         
         if update:
@@ -887,7 +847,7 @@
         
         return selected
 
-    def _renderLayers(self, force = False, overlaysOnly = False):
+    def _renderLayers(self, env, force = False, overlaysOnly = False):
         """!Render all map layers into files
 
         @param force True to force rendering
@@ -916,6 +876,7 @@
             
             # render
             if force or layer.forceRender:
+                layer.SetEnvironment(env)
                 if not layer.Render():
                     continue
 
@@ -938,13 +899,13 @@
 
         return maps, masks, opacities
         
-    def GetMapsMasksAndOpacities(self, force, windres):
+    def GetMapsMasksAndOpacities(self, force, windres, env):
         """!
         Used by Render function.
         
         @return maps, masks, opacities
         """
-        return self._renderLayers(force)
+        return self._renderLayers(force=force, env=env)
     
     def Render(self, force = False, windres = False):
         """!Creates final image composite
@@ -958,22 +919,21 @@
         @return name of file with rendered image or None
         """
         wx.BeginBusyCursor()
+        env = os.environ.copy()
+        env.update(self.default_env)
         # use external gisrc if defined
-        gisrc_orig = os.getenv("GISRC")
         if self.gisrc:
-            os.environ["GISRC"] = self.gisrc
-        
-        tmp_region = os.getenv("GRASS_REGION")
-        os.environ["GRASS_REGION"] = self.SetRegion(windres)
-        os.environ["GRASS_WIDTH"]  = str(self.width)
-        os.environ["GRASS_HEIGHT"] = str(self.height)
+            env['GISRC'] = self.gisrc
+        env['GRASS_REGION'] = self.SetRegion(windres)
+        env['GRASS_WIDTH'] = str(self.width)
+        env['GRASS_HEIGHT'] = str(self.height)
         driver = UserSettings.Get(group = 'display', key = 'driver', subkey = 'type')
         if driver == 'png':
-            os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
+            env['GRASS_RENDER_IMMEDIATE'] = 'png'
         else:
-            os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"
+            env['GRASS_RENDER_IMMEDIATE'] = 'cairo'
         
-        maps, masks, opacities = self.GetMapsMasksAndOpacities(force, windres)
+        maps, masks, opacities = self.GetMapsMasksAndOpacities(force, windres, env)
         
         # ugly hack for MSYS
         if sys.platform != 'win32':
@@ -1003,7 +963,8 @@
                                   bgcolor = bgcolor,
                                   width = self.width,
                                   height = self.height,
-                                  output = self.mapfile)
+                                  output = self.mapfile,
+                                  env=env)
             
             if ret != 0:
                 print >> sys.stderr, _("ERROR: Rendering failed. Details: %s") % msg
@@ -1011,17 +972,7 @@
                 return None
         
         Debug.msg (3, "Map.Render() force=%s file=%s" % (force, self.mapfile))
-        
-        # back to original region
-        if tmp_region:
-            os.environ["GRASS_REGION"] = tmp_region
-        else:
-            del os.environ["GRASS_REGION"]
-        
-        # back to original gisrc
-        if self.gisrc:
-            os.environ["GISRC"] = gisrc_orig
-        
+
         wx.EndBusyCursor()
         if not maps:
             return None

Modified: grass/branches/releasebranch_7_0/gui/wxpython/core/ws.py
===================================================================
--- grass/branches/releasebranch_7_0/gui/wxpython/core/ws.py	2014-07-23 11:49:24 UTC (rev 61369)
+++ grass/branches/releasebranch_7_0/gui/wxpython/core/ws.py	2014-07-23 11:50:19 UTC (rev 61370)
@@ -16,8 +16,8 @@
 
 @author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
 """
-import os
 import sys
+import copy
 
 import wx
 from wx.lib.newevent import NewEvent
@@ -76,7 +76,7 @@
     def __del__(self):
         grass.try_remove(self.tempMap)
 
-    def Render(self, cmd):
+    def Render(self, cmd, env):
         """!If it is needed, download missing WMS data.
 
         @todo lmgr deletes mapfile and maskfile when order of layers
@@ -85,10 +85,11 @@
         if not haveGdal:
             return
 
-        self.dstSize['cols'] = int(os.environ["GRASS_WIDTH"])
-        self.dstSize['rows'] = int(os.environ["GRASS_HEIGHT"])
+        env = copy.copy(env)
+        self.dstSize['cols'] = int(env["GRASS_WIDTH"])
+        self.dstSize['rows'] = int(env["GRASS_HEIGHT"])
 
-        region = self._getRegionDict()
+        region = self._getRegionDict(env)
         self._fitAspect(region, self.dstSize)
 
         self.updateMap = True
@@ -127,23 +128,12 @@
 
             if Debug.GetLevel() < 3:
                 cmdList.append('--quiet')
-            
-            tempPngfile = None
-            if "GRASS_PNGFILE" in os.environ:  
-                tempPngfile = os.environ["GRASS_PNGFILE"]
-            os.environ["GRASS_PNGFILE"] = self.tempMap
 
-            tempRegion = os.environ["GRASS_REGION"]
-            os.environ["GRASS_REGION"] = self._createRegionStr(region)
+            env["GRASS_PNGFILE"] = self.tempMap
+            env["GRASS_REGION"] = self._createRegionStr(region)
 
-            self.thread.RunCmd(cmdList, env = os.environ.copy(), stderr = self.cmdStdErr)
+            self.thread.RunCmd(cmdList, env=env, stderr=self.cmdStdErr)
 
-            os.environ.pop("GRASS_PNGFILE")
-            if tempPngfile:
-                os.environ["GRASS_PNGFILE"] = tempPngfile
-
-            os.environ["GRASS_REGION"] = tempRegion
-
     def OnCmdOutput(self, event):
         """!Print cmd output according to debug level.
         """
@@ -181,11 +171,11 @@
 
         self.dataFetched.emit()
 
-    def _getRegionDict(self):
+    def _getRegionDict(self, env):
         """!Parse string from GRASS_REGION env variable into dict.
         """
         region = {}
-        parsedRegion = os.environ["GRASS_REGION"].split(';')
+        parsedRegion = env["GRASS_REGION"].split(';')
         for r in parsedRegion:
             r = r.split(':')
             r[0] = r[0].strip()



More information about the grass-commit mailing list