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