GRASS Programmer's Manual  6.4.4(2014)-r
globalvar.py
Go to the documentation of this file.
1 """!
2 @package core.globalvar
3 
4 @brief Global variables used by wxGUI
5 
6 (C) 2007-2012 by the GRASS Development Team
7 
8 This program is free software under the GNU General Public License
9 (>=v2). Read the file COPYING that comes with GRASS for details.
10 
11 @author Martin Landa <landa.martin gmail.com>
12 """
13 
14 import os
15 import sys
16 import locale
17 
18 if not os.getenv("GISBASE"):
19  sys.exit("GRASS is not running. Exiting...")
20 
21 # path to python scripts
22 ETCDIR = os.path.join(os.getenv("GISBASE"), "etc")
23 ETCICONDIR = os.path.join(os.getenv("GISBASE"), "etc", "gui", "icons")
24 ETCWXDIR = os.path.join(ETCDIR, "wxpython")
25 ETCIMGDIR = os.path.join(ETCDIR, "gui", "images")
26 ETCSYMBOLDIR = os.path.join(ETCDIR, "gui", "images", "symbols")
27 
28 from core.debug import Debug
29 
30 sys.path.append(os.path.join(ETCDIR, "python"))
31 import grass.script as grass
32 
33 def CheckWxVersion(version = [2, 8, 11, 0]):
34  """!Check wx version"""
35  ver = wx.__version__
36  if map(int, ver.split('.')) < version:
37  return False
38 
39  return True
40 
41 def CheckForWx():
42  """!Try to import wx module and check its version"""
43  if 'wx' in sys.modules.keys():
44  return
45 
46  minVersion = [2, 8, 1, 1]
47 
48  try:
49  try:
50  import wxversion
51  except ImportError, e:
52  raise ImportError(e)
53  # wxversion.select(str(minVersion[0]) + '.' + str(minVersion[1]))
54  wxversion.ensureMinimal(str(minVersion[0]) + '.' + str(minVersion[1]))
55  import wx
56  version = wx.__version__
57 
58  if map(int, version.split('.')) < minVersion:
59  raise ValueError('Your wxPython version is %s.%s.%s.%s' % tuple(version.split('.')))
60 
61  except ImportError, e:
62  print >> sys.stderr, 'ERROR: wxGUI requires wxPython. %s' % str(e)
63  sys.exit(1)
64  except (ValueError, wxversion.VersionError), e:
65  print >> sys.stderr, 'ERROR: wxGUI requires wxPython >= %d.%d.%d.%d. ' % tuple(minVersion) + \
66  '%s.' % (str(e))
67  sys.exit(1)
68  except locale.Error, e:
69  print >> sys.stderr, "Unable to set locale:", e
70  os.environ['LC_ALL'] = ''
71 
72 if not os.getenv("GRASS_WXBUNDLED"):
73  CheckForWx()
74 import wx
75 import wx.lib.flatnotebook as FN
76 
77 """
78 Query layer (generated for example by selecting item in the Attribute Table Manager)
79 Deleted automatically on re-render action
80 """
81 # temporal query layer (removed on re-render action)
82 QUERYLAYER = 'qlayer'
83 
84 """!Style definition for FlatNotebook pages"""
85 FNPageStyle = FN.FNB_VC8 | \
86  FN.FNB_BACKGROUND_GRADIENT | \
87  FN.FNB_NODRAG | \
88  FN.FNB_TABS_BORDER_SIMPLE
89 
90 FNPageDStyle = FN.FNB_FANCY_TABS | \
91  FN.FNB_BOTTOM | \
92  FN.FNB_NO_NAV_BUTTONS | \
93  FN.FNB_NO_X_BUTTON
94 
95 FNPageColor = wx.Colour(125,200,175)
96 
97 """!Dialog widget dimension"""
98 DIALOG_SPIN_SIZE = (150, -1)
99 DIALOG_COMBOBOX_SIZE = (300, -1)
100 DIALOG_GSELECT_SIZE = (400, -1)
101 DIALOG_TEXTCTRL_SIZE = (400, -1)
102 DIALOG_LAYER_SIZE = (100, -1)
103 DIALOG_COLOR_SIZE = (30, 30)
104 
105 MAP_WINDOW_SIZE = (800, 600)
106 GM_WINDOW_SIZE = (500, 600)
107 
108 if sys.platform == 'win32':
109  BIN_EXT = '.exe'
110  SCT_EXT = '.bat'
111 else:
112  BIN_EXT = SCT_EXT = ''
113 
115  """!Create list of available GRASS commands to use when parsing
116  string from the command line
117 
118  @return list of commands (set) and directory of scripts (collected
119  by extension - MS Windows only)
120  """
121  gisbase = os.environ['GISBASE']
122  cmd = list()
123  if sys.platform == 'win32':
124  scripts = { SCT_EXT : list() }
125  else:
126  scripts = {}
127 
128  # scan bin/
129  if os.path.exists(os.path.join(gisbase, 'bin')):
130  for fname in os.listdir(os.path.join(gisbase, 'bin')):
131  if scripts: # win32
132  name, ext = os.path.splitext(fname)
133  if ext != '.manifest':
134  cmd.append(name)
135  if ext in scripts.keys():
136  scripts[ext].append(name)
137  else:
138  cmd.append(fname)
139 
140  # scan scripts/ (not on MS Windows)
141  if not scripts and os.path.exists(os.path.join(gisbase, 'scripts')):
142  for fname in os.listdir(os.path.join(gisbase, 'scripts')):
143  cmd.append(fname)
144 
145  # scan gui/scripts/
146  if os.path.exists(os.path.join(gisbase, 'etc', 'gui', 'scripts')):
147  os.environ["PATH"] = os.getenv("PATH") + os.pathsep + os.path.join(gisbase, 'etc', 'gui', 'scripts')
148  os.environ["PATH"] = os.getenv("PATH") + os.pathsep + os.path.join(gisbase, 'etc', 'wxpython', 'scripts')
149 
150  pattern = "_wrapper"
151  for script in os.listdir(os.path.join(gisbase, 'etc', 'gui', 'scripts')):
152  if script[-len(pattern):] != pattern: # ignore wrappers
153  cmd.append(script)
154 
155  return set(cmd), scripts
156 
157 def UpdateGRASSAddOnCommands(eList = None):
158  """!Update list of available GRASS AddOns commands to use when
159  parsing string from the command line
160 
161  @param eList list of AddOns commands to remove
162  """
163  global grassCmd, grassScripts
164 
165  # scan addons (path)
166  if not os.getenv('GRASS_ADDON_PATH'):
167  return
168 
169  # remove commands first
170  if eList:
171  for ext in eList:
172  if ext in grassCmd:
173  grassCmd.remove(ext)
174  Debug.msg(1, "Number of removed AddOn commands: %d", len(eList))
175 
176  nCmd = 0
177  for path in os.getenv('GRASS_ADDON_PATH').split(os.pathsep):
178  if not os.path.exists(path) or not os.path.isdir(path):
179  continue
180  for fname in os.listdir(path):
181  if fname in ['docs', 'modules.xml']:
182  continue
183  if grassScripts: # win32
184  name, ext = os.path.splitext(fname)
185  if ext not in [BIN_EXT, SCT_EXT]:
186  continue
187  if name not in grassCmd:
188  grassCmd.add(name)
189  Debug.msg(3, "AddOn commands: %s", name)
190  nCmd += 1
191  if ext == SCT_EXT and \
192  ext in grassScripts.keys() and \
193  name not in grassScripts[ext]:
194  grassScripts[ext].append(name)
195  else:
196  if fname not in grassCmd:
197  grassCmd.add(fname)
198  Debug.msg(3, "AddOn commands: %s", fname)
199  nCmd += 1
200 
201  Debug.msg(1, "Number of new AddOn commands: %d", nCmd)
202 
204  import locale
205 
206  language = os.getenv('LANG')
207  if not language:
208  return
209 
210  language = language.split('.')[0] # Split off ignored .encoding part if present
211  orig_language = language
212  try:
213  locale.setlocale(locale.LC_ALL, language)
214  except locale.Error, e:
215  if sys.platform != 'win32': # Don't try on Windows, it will probably not work
216  # sys.stderr.write("Failed to set LC_ALL to %s (%s)\n" % (language, e))
217  try:
218  # Locale lang.encoding might be missing. Let's try
219  # UTF-8 encoding before giving up as on Linux systems
220  # lang.UTF-8 locales are more common than legacy
221  # ISO-8859 ones.
222  language = locale.normalize('%s.UTF-8' % (language))
223  locale.setlocale(locale.LC_ALL, language)
224  except locale.Error, e:
225  # If we got so far, provided locale is not supported
226  # on this system
227  sys.stderr.write("Failed to set LC_ALL to %s (%s)\n" % (language, e))
228  ### locale.getdefaultlocale() is probably related to gettext?
229  # try:
230  # default_locale = locale.getdefaultlocale()
231  # except:
232  # default_locale = None
233  # if default_locale and default_locale[0]:
234  # language = default_locale[0]
235  # else:
236  language = 'C'
237 
238  # Set up environment for subprocesses
239  for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE', 'LC_MONETARY', 'LC_PAPER',
240  'LC_NAME', 'LC_ADDRESS', 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
241  os.environ[lc] = language
242 
243  Debug.msg(1, "Language setttings: (WX) %s / (GRASS) %s", language, orig_language)
244 
245  # Some code in GRASS might not like other decimal separators than .
246  # Other potential sources for problems are: LC_TIME LC_CTYPE
247  locale.setlocale(locale.LC_NUMERIC, 'C')
248  os.environ['LC_NUMERIC'] = 'C'
249  if os.getenv('LC_ALL'):
250  del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
251 
252  # Even if setting locale has failed, let's set LANG in a hope,
253  # that UI will use it GRASS texts will be in selected language,
254  # system messages (i.e. OK, Cancel etc.) - in system default
255  # language
256  os.environ['LANGUAGE'] = orig_language
257  os.environ['LANG'] = orig_language
258 
259 """@brief Collected GRASS-relared binaries/scripts"""
260 grassCmd, grassScripts = GetGRASSCommands()
261 Debug.msg(1, "Number of GRASS commands: %d", len(grassCmd))
263 
264 """@Toolbar icon size"""
265 toolbarSize = (24, 24)
266 
267 """@Is g.mlist available?"""
268 if 'g.mlist' in grassCmd:
269  have_mlist = True
270 else:
271  have_mlist = False
272 
273 """@Check version of wxPython, use agwStyle for 2.8.11+"""
274 hasAgw = CheckWxVersion()
275 
276 SetLanguage()
def CheckForWx()
Try to import wx module and check its version.
Definition: globalvar.py:41
wxGUI debugging
def split(s)
Platform spefic shlex.split.
Definition: core/utils.py:37
def CheckWxVersion(version=[2)
Check wx version.
Definition: globalvar.py:33
def GetGRASSCommands()
Create list of available GRASS commands to use when parsing string from the command line...
Definition: globalvar.py:114
def UpdateGRASSAddOnCommands
Update list of available GRASS AddOns commands to use when parsing string from the command line...
Definition: globalvar.py:157
string set
def SetLanguage()
Definition: globalvar.py:203