GRASS Programmer's Manual  6.5.svn(2014)-r66266
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
settings.py
Go to the documentation of this file.
1 """!
2 @package core.settings
3 
4 @brief Default GUI settings
5 
6 List of classes:
7  - settings::Settings
8 
9 Usage:
10 @code
11 from core.settings import UserSettings
12 @endcode
13 
14 (C) 2007-2011 by the GRASS Development Team
15 This program is free software under the GNU General Public License
16 (>=v2). Read the file COPYING that comes with GRASS for details.
17 
18 @author Martin Landa <landa.martin gmail.com>
19 @author Luca Delucchi <lucadeluge gmail.com> (language choice)
20 """
21 
22 import os
23 import sys
24 import copy
25 import types
26 import locale
27 
28 from core import globalvar
29 from core.gcmd import GException, GError
30 from core.utils import GetSettingsPath, PathJoin
31 
32 class Settings:
33  """!Generic class where to store settings"""
34  def __init__(self):
35  # settings file
36  self.filePath = os.path.join(GetSettingsPath(), 'wx')
37 
38  # key/value separator
39  self.sep = ';'
40 
41  # define default settings
42  self._defaultSettings() # -> self.defaultSettings
43 
44  # read settings from the file
45  self.userSettings = copy.deepcopy(self.defaultSettings)
46  try:
47  self.ReadSettingsFile()
48  except GException, e:
49  print >> sys.stderr, e.value
50 
51  # define internal settings
52  self._internalSettings() # -> self.internalSettings
53 
54  def _generateLocale(self):
55  """!Generate locales
56  """
57  import os
58 
59  try:
60  self.locs = os.listdir(os.path.join(os.environ['GISBASE'], 'locale'))
61  self.locs.append('en') # GRASS doesn't ship EN po files
62  self.locs.sort()
63  # Add a default choice to not override system locale
64  self.locs.insert(0, 'system')
65  except:
66  # No NLS
67  self.locs = ['system']
68 
69  return 'system'
70 
71  def _defaultSettings(self):
72  """!Define default settings
73  """
74  try:
75  projFile = PathJoin(os.environ["GRASS_PROJSHARE"], 'epsg')
76  except KeyError:
77  projFile = ''
78 
79  self.defaultSettings = {
80  #
81  # general
82  #
83  'general': {
84  # use default window layout (layer manager, displays, ...)
85  'defWindowPos' : {
86  'enabled' : True,
87  'dim' : '0,0,%d,%d,%d,0,%d,%d' % \
88  (globalvar.GM_WINDOW_SIZE[0],
89  globalvar.GM_WINDOW_SIZE[1],
90  globalvar.GM_WINDOW_SIZE[0],
91  globalvar.MAP_WINDOW_SIZE[0],
92  globalvar.MAP_WINDOW_SIZE[1])
93  },
94  # workspace
95  'workspace' : {
96  'posDisplay' : {
97  'enabled' : False
98  },
99  'posManager' : {
100  'enabled' : False
101  },
102  },
103  },
104  'manager' : {
105  # show opacity level widget
106  'changeOpacityLevel' : {
107  'enabled' : False
108  },
109  # ask when removing layer from layer tree
110  'askOnRemoveLayer' : {
111  'enabled' : True
112  },
113  # ask when quiting wxGUI or closing display
114  'askOnQuit' : {
115  'enabled' : True
116  },
117  # hide tabs
118  'hideTabs' : {
119  'search' : False,
120  'pyshell' : False,
121  },
122  'copySelectedTextToClipboard' : {
123  'enabled' : False
124  },
125  },
126  #
127  # appearance
128  #
129  'appearance': {
130  'outputfont' : {
131  'type' : 'Courier New',
132  'size': '10',
133  },
134  # expand/collapse element list
135  'elementListExpand' : {
136  'selection' : 0
137  },
138  'menustyle' : {
139  'selection' : 1
140  },
141  'gSelectPopupHeight' : {
142  'value' : 200
143  },
144  'iconTheme' : {
145  'type' : 'grass2'
146  }, # grass2, grass, silk
147  },
148  #
149  # language
150  #
151  'language': {
152  'locale': {
153  'lc_all' : self._generateLocale(),
154  }
155  },
156  #
157  # display
158  #
159  'display': {
160  'font' : {
161  'type' : '',
162  'encoding': 'ISO-8859-1',
163  },
164  'driver': {
165  'type': 'default'
166  },
167  'alignExtent' : {
168  'enabled' : True
169  },
170  'compResolution' : {
171  'enabled' : False
172  },
173  'autoRendering': {
174  'enabled' : True
175  },
176  'autoZooming' : {
177  'enabled' : False
178  },
179  'statusbarMode': {
180  'selection' : 0
181  },
182  'bgcolor': {
183  'color' : (255, 255, 255, 255),
184  },
185  'mouseWheelZoom' : {
186  'selection' : 1,
187  },
188  'scrollDirection' : {
189  'selection' : 0,
190  },
191  'nvizDepthBuffer' : {
192  'value' : '16',
193  },
194  },
195  #
196  # projection
197  #
198  'projection' : {
199  'statusbar' : {
200  'proj4' : '',
201  'epsg' : '',
202  'projFile' : projFile,
203  },
204  'format' : {
205  'll' : 'DMS',
206  'precision' : 2,
207  },
208  },
209  #
210  # Attribute Table Manager
211  #
212  'atm' : {
213  'highlight' : {
214  'color' : (255, 255, 0, 255),
215  'width' : 2
216  },
217  'leftDbClick' : {
218  'selection' : 1 # draw selected
219  },
220  'askOnDeleteRec' : {
221  'enabled' : True
222  },
223  'keycolumn' : {
224  'value' : 'cat'
225  },
226  'encoding' : {
227  'value' : '',
228  }
229  },
230  #
231  # Command
232  #
233  'cmd': {
234  'overwrite' : {
235  'enabled' : False
236  },
237  'closeDlg' : {
238  'enabled' : False
239  },
240  'verbosity' : {
241  'selection' : 'grassenv'
242  },
243  # d.rast
244  'rasterOverlay' : {
245  'enabled' : True
246  },
247  'rasterColorTable' : {
248  'enabled' : False,
249  'selection' : 'rainbow',
250  },
251  # d.vect
252  'showType': {
253  'point' : {
254  'enabled' : True
255  },
256  'line' : {
257  'enabled' : True
258  },
259  'centroid' : {
260  'enabled' : True
261  },
262  'boundary' : {
263  'enabled' : True
264  },
265  'area' : {
266  'enabled' : True
267  },
268  'face' : {
269  'enabled' : True
270  },
271  },
272  'addNewLayer' : {
273  'enabled' : True,
274  },
275  'interactiveInput' : {
276  'enabled' : True,
277  },
278  },
279  #
280  # vdigit
281  #
282  'vdigit' : {
283  # symbology
284  'symbol' : {
285  'newSegment' : {
286  'enabled' : None,
287  'color' : (255, 0, 0, 255)
288  }, # red
289  'newLine' : {
290  'enabled' : None,
291  'color' : (0, 86, 45, 255)
292  }, # dark green
293  'highlight' : {
294  'enabled' : None,
295  'color' : (255, 255, 0, 255)
296  }, # yellow
297  'highlightDupl' : {
298  'enabled' : None,
299  'color' : (255, 72, 0, 255)
300  }, # red
301  'point' : {
302  'enabled' : True,
303  'color' : (0, 0, 0, 255)
304  }, # black
305  'line' : {
306  'enabled' : True,
307  'color' : (0, 0, 0, 255)
308  }, # black
309  'boundaryNo' : {
310  'enabled' : True,
311  'color' : (126, 126, 126, 255)
312  }, # grey
313  'boundaryOne' : {
314  'enabled' : True,
315  'color' : (0, 255, 0, 255)
316  }, # green
317  'boundaryTwo' : {
318  'enabled' : True,
319  'color' : (255, 135, 0, 255)
320  }, # orange
321  'centroidIn' : {
322  'enabled' : True,
323  'color' : (0, 0, 255, 255)
324  }, # blue
325  'centroidOut' : {
326  'enabled' : True,
327  'color' : (165, 42, 42, 255)
328  }, # brown
329  'centroidDup' : {
330  'enabled' : True,
331  'color' : (156, 62, 206, 255)
332  }, # violet
333  'nodeOne' : {
334  'enabled' : True,
335  'color' : (255, 0, 0, 255)
336  }, # red
337  'nodeTwo' : {
338  'enabled' : True,
339  'color' : (0, 86, 45, 255)
340  }, # dark green
341  'vertex' : {
342  'enabled' : False,
343  'color' : (255, 20, 147, 255)
344  }, # deep pink
345  'area' : {
346  'enabled' : True,
347  'color' : (217, 255, 217, 255)
348  }, # green
349  'direction' : {
350  'enabled' : False,
351  'color' : (255, 0, 0, 255)
352  }, # red
353  },
354  # display
355  'lineWidth' : {
356  'value' : 2,
357  'units' : 'screen pixels'
358  },
359  # snapping
360  'snapping' : {
361  'value' : 10,
362  'units' : 'screen pixels'
363  },
364  'snapToVertex' : {
365  'enabled' : False
366  },
367  # digitize new record
368  'addRecord' : {
369  'enabled' : True
370  },
371  'layer' :{
372  'value' : 1
373  },
374  'category' : {
375  'value' : 1
376  },
377  'categoryMode' : {
378  'selection' : 0
379  },
380  # delete existing feature(s)
381  'delRecord' : {
382  'enabled' : True
383  },
384  # query tool
385  'query' : {
386  'selection' : 0,
387  'box' : True
388  },
389  'queryLength' : {
390  'than-selection' : 0,
391  'thresh' : 0
392  },
393  'queryDangle' : {
394  'than-selection' : 0,
395  'thresh' : 0
396  },
397  # select feature (point, line, centroid, boundary)
398  'selectType': {
399  'point' : {
400  'enabled' : True
401  },
402  'line' : {
403  'enabled' : True
404  },
405  'centroid' : {
406  'enabled' : True
407  },
408  'boundary' : {
409  'enabled' : True
410  },
411  },
412  'selectThresh' : {
413  'value' : 10,
414  'units' : 'screen pixels'
415  },
416  'checkForDupl' : {
417  'enabled' : False
418  },
419  'selectInside' : {
420  'enabled' : False
421  },
422  # exit
423  'saveOnExit' : {
424  'enabled' : False,
425  },
426  # break lines on intersection
427  'breakLines' : {
428  'enabled' : False,
429  },
430  },
431  'profile': {
432  'raster' : {
433  'pcolor' : (0, 0, 255, 255), # profile line color
434  'pwidth' : 1, # profile line width
435  'pstyle' : 'solid', # profile line pen style
436  },
437  'font' : {
438  'titleSize' : 12,
439  'axisSize' : 11,
440  'legendSize' : 10,
441  },
442  'marker' : {
443  'color' : (0, 0, 0, 255),
444  'fill' : 'transparent',
445  'size' : 2,
446  'type' : 'triangle',
447  'legend' : _('Segment break'),
448  },
449  'grid' : {
450  'color' : (200, 200, 200, 255),
451  'enabled' : True,
452  },
453  'x-axis' : {
454  'type' : 'auto', # axis format
455  'min' : 0, # axis min for custom axis range
456  'max': 0, # axis max for custom axis range
457  'log' : False,
458  },
459  'y-axis' : {
460  'type' : 'auto', # axis format
461  'min' : 0, # axis min for custom axis range
462  'max': 0, # axis max for custom axis range
463  'log' : False,
464  },
465  'legend' : {
466  'enabled' : True
467  },
468  },
469  'gcpman' : {
470  'rms' : {
471  'highestonly' : True,
472  'sdfactor' : 1,
473  },
474  'symbol' : {
475  'color' : (0, 0, 255, 255),
476  'hcolor' : (255, 0, 0, 255),
477  'scolor' : (0, 255, 0, 255),
478  'ucolor' : (255, 165, 0, 255),
479  'unused' : True,
480  'size' : 8,
481  'width' : 2,
482  },
483  },
484  'nviz' : {
485  'view' : {
486  'persp' : {
487  'value' : 20,
488  'step' : 2,
489  },
490  'position' : {
491  'x' : 0.84,
492  'y' : 0.16,
493  },
494  'twist' : {
495  'value' : 0,
496  },
497  'z-exag' : {
498  'min' : 0,
499  'max' : 10,
500  'value': 1,
501  },
502  'background' : {
503  'color' : (255, 255, 255, 255), # white
504  },
505  },
506  'fly' : {
507  'exag' : {
508  'move' : 5,
509  'turn' : 5,
510  }
511  },
512  'animation' : {
513  'fps' : 24,
514  'prefix' : _("animation")
515  },
516  'surface' : {
517  'shine': {
518  'map' : False,
519  'value' : 60.0,
520  },
521  'color' : {
522  'map' : True,
523  'value' : (100, 100, 100, 255), # constant: grey
524  },
525  'draw' : {
526  'wire-color' : (136, 136, 136, 255),
527  'mode' : 1, # fine
528  'style' : 1, # surface
529  'shading' : 1, # gouraud
530  'res-fine' : 6,
531  'res-coarse' : 9,
532  },
533  'position' : {
534  'x' : 0,
535  'y' : 0,
536  'z' : 0,
537  },
538  },
539  'constant' : {
540  'color' : (100, 100, 100, 255),
541  'value' : 0.0,
542  'transp' : 0,
543  'resolution': 6
544  },
545  'vector' : {
546  'lines' : {
547  'show' : False,
548  'width' : 2,
549  'color' : (0, 0, 255, 255), # blue
550  'flat' : False,
551  'height' : 0,
552  },
553  'points' : {
554  'show' : False,
555  'size' : 100,
556  'width' : 2,
557  'marker' : 2,
558  'color' : (0, 0, 255, 255), # blue
559  'height' : 0,
560  }
561  },
562  'volume' : {
563  'color' : {
564  'map' : True,
565  'value' : (100, 100, 100, 255), # constant: grey
566  },
567  'draw' : {
568  'mode' : 0, # isosurfaces
569  'shading' : 1, # gouraud
570  'resolution' : 3, # polygon resolution
571  },
572  'shine': {
573  'map' : False,
574  'value' : 60,
575  },
576  'topo': {
577  'map' : None,
578  'value' : 0.0
579  },
580  'transp': {
581  'map' : None,
582  'value': 0
583  },
584  'mask': {
585  'map' : None,
586  'value': ''
587  },
588  'slice_position': {
589  'x1' : 0,
590  'x2' : 1,
591  'y1' : 0,
592  'y2' : 1,
593  'z1' : 0,
594  'z2' : 1,
595  'axis' : 0,
596  }
597  },
598  'cplane' : {
599  'shading': 4,
600  'rotation':{
601  'rot': 180,
602  'tilt': 0
603  },
604  'position':{
605  'x' : 0,
606  'y' : 0,
607  'z' : 0
608  }
609  },
610  'light' : {
611  'position' : {
612  'x' : 0.68,
613  'y' : -0.68,
614  'z' : 80,
615  },
616  'bright' : 80,
617  'color' : (255, 255, 255, 255), # white
618  'ambient' : 20,
619  },
620  'fringe' : {
621  'elev' : 55,
622  'color' : (128, 128, 128, 255), # grey
623  },
624  'arrow': {
625  'color': (0, 0, 0),
626  },
627  'scalebar': {
628  'color': (0, 0, 0),
629  }
630  },
631  'modeler' : {
632  'disabled': {
633  'color': (211, 211, 211, 255), # light grey
634  },
635  'action' : {
636  'color' : {
637  'valid' : (180, 234, 154, 255), # light green
638  'invalid' : (255, 255, 255, 255), # white
639  'running' : (255, 0, 0, 255), # red
640  },
641  'size' : {
642  'width' : 125,
643  'height' : 50,
644  },
645  'width': {
646  'parameterized' : 2,
647  'default' : 1,
648  },
649  },
650  'data' : {
651  'color': {
652  'raster' : (215, 215, 248, 255), # light blue
653  'raster3d' : (215, 248, 215, 255), # light green
654  'vector' : (248, 215, 215, 255), # light red
655  },
656  'size' : {
657  'width' : 175,
658  'height' : 50,
659  },
660  },
661  'loop' : {
662  'color' : {
663  'valid' : (234, 226, 154, 255), # light yellow
664  },
665  'size' : {
666  'width' : 175,
667  'height' : 40,
668  },
669  },
670  'if-else' : {
671  'size' : {
672  'width' : 150,
673  'height' : 40,
674  },
675  },
676  },
677  }
678 
679  # quick fix, http://trac.osgeo.org/grass/ticket/1233
680  # TODO
681  if sys.platform == 'darwin':
682  self.defaultSettings['general']['defWindowPos']['enabled'] = False
683 
684  def _internalSettings(self):
685  """!Define internal settings (based on user settings)
686  """
688  for group in self.userSettings.keys():
689  self.internalSettings[group] = {}
690  for key in self.userSettings[group].keys():
691  self.internalSettings[group][key] = {}
692 
693  # self.internalSettings['general']["mapsetPath"]['value'] = self.GetMapsetPath()
694  self.internalSettings['appearance']['elementListExpand']['choices'] = \
695  (_("Collapse all except PERMANENT and current"),
696  _("Collapse all except PERMANENT"),
697  _("Collapse all except current"),
698  _("Collapse all"),
699  _("Expand all"))
700 
701  self.internalSettings['language']['locale']['choices'] = tuple(self.locs)
702  self.internalSettings['atm']['leftDbClick']['choices'] = (_('Edit selected record'),
703  _('Display selected'))
704 
705  self.internalSettings['cmd']['verbosity']['choices'] = ('grassenv',
706  'verbose',
707  'quiet')
708 
709  self.internalSettings['appearance']['iconTheme']['choices'] = ('grass',
710  'grass2',
711  'silk')
712  self.internalSettings['appearance']['menustyle']['choices'] = \
713  (_("Classic (labels only)"),
714  _("Combined (labels and module names)"),
715  _("Professional (module names only)"))
716  self.internalSettings['appearance']['gSelectPopupHeight']['min'] = 50
717  # there is also maxHeight given to TreeCtrlComboPopup.GetAdjustedSize
718  self.internalSettings['appearance']['gSelectPopupHeight']['max'] = 1000
719 
720  self.internalSettings['display']['driver']['choices'] = ['default']
721  self.internalSettings['display']['statusbarMode']['choices'] = None # set during MapFrame init
722  self.internalSettings['display']['mouseWheelZoom']['choices'] = (_('Zoom and recenter'),
723  _('Zoom to mouse cursor'),
724  _('Nothing'))
725  self.internalSettings['display']['scrollDirection']['choices'] = (_('Scroll forward to zoom in'),
726  _('Scroll back to zoom in'))
727 
728  self.internalSettings['nviz']['view'] = {}
729  self.internalSettings['nviz']['view']['twist'] = {}
730  self.internalSettings['nviz']['view']['twist']['min'] = -180
731  self.internalSettings['nviz']['view']['twist']['max'] = 180
732  self.internalSettings['nviz']['view']['persp'] = {}
733  self.internalSettings['nviz']['view']['persp']['min'] = 1
734  self.internalSettings['nviz']['view']['persp']['max'] = 100
735  self.internalSettings['nviz']['view']['height'] = {}
736  self.internalSettings['nviz']['view']['height']['value'] = -1
737  self.internalSettings['nviz']['view']['z-exag'] = {}
738  self.internalSettings['nviz']['view']['z-exag']['llRatio'] = 1
739  self.internalSettings['nviz']['view']['rotation'] = None
740  self.internalSettings['nviz']['view']['focus'] = {}
741  self.internalSettings['nviz']['view']['focus']['x'] = -1
742  self.internalSettings['nviz']['view']['focus']['y'] = -1
743  self.internalSettings['nviz']['view']['focus']['z'] = -1
744  self.internalSettings['nviz']['view']['dir'] = {}
745  self.internalSettings['nviz']['view']['dir']['x'] = -1
746  self.internalSettings['nviz']['view']['dir']['y'] = -1
747  self.internalSettings['nviz']['view']['dir']['z'] = -1
748  self.internalSettings['nviz']['view']['dir']['use'] = False
749 
750  for decor in ('arrow', 'scalebar'):
751  self.internalSettings['nviz'][decor] = {}
752  self.internalSettings['nviz'][decor]['position'] = {}
753  self.internalSettings['nviz'][decor]['position']['x'] = 0
754  self.internalSettings['nviz'][decor]['position']['y'] = 0
755  self.internalSettings['nviz'][decor]['size'] = 100
756  self.internalSettings['nviz']['vector'] = {}
757  self.internalSettings['nviz']['vector']['points'] = {}
758  self.internalSettings['nviz']['vector']['points']['marker'] = ("x",
759  _("box"),
760  _("sphere"),
761  _("cube"),
762  _("diamond"),
763  _("aster"),
764  _("gyro"),
765  _("histogram"))
766  self.internalSettings['vdigit']['bgmap'] = {}
767  self.internalSettings['vdigit']['bgmap']['value'] = ''
768 
769  def ReadSettingsFile(self, settings = None):
770  """!Reads settings file (mapset, location, gisdbase)"""
771  if settings is None:
772  settings = self.userSettings
773 
774  self._readFile(self.filePath, settings)
775 
776  # set environment variables
777  font = self.Get(group = 'display', key = 'font', subkey = 'type')
778  enc = self.Get(group = 'display', key = 'font', subkey = 'encoding')
779  if font:
780  os.environ["GRASS_FONT"] = font
781  if enc:
782  os.environ["GRASS_ENCODING"] = enc
783 
784  def _readFile(self, filename, settings = None):
785  """!Read settings from file to dict
786 
787  @param filename settings file path
788  @param settings dict where to store settings (None for self.userSettings)
789  """
790  if settings is None:
791  settings = self.userSettings
792 
793  if not os.path.exists(filename):
794  # try alternative path
795  filename = os.path.join(os.path.expanduser("~"), '.grasswx6')
796  if not os.path.exists(filename):
797  return
798 
799  try:
800  fd = open(filename, "r")
801  except IOError:
802  sys.stderr.write(_("Unable to read settings file <%s>\n") % filename)
803  return
804 
805  try:
806  line = ''
807  for line in fd.readlines():
808  line = line.rstrip('%s' % os.linesep)
809  group, key = line.split(self.sep)[0:2]
810  kv = line.split(self.sep)[2:]
811  subkeyMaster = None
812  if len(kv) % 2 != 0: # multiple (e.g. nviz)
813  subkeyMaster = kv[0]
814  del kv[0]
815  idx = 0
816  while idx < len(kv):
817  if subkeyMaster:
818  subkey = [subkeyMaster, kv[idx]]
819  else:
820  subkey = kv[idx]
821  value = kv[idx+1]
822  value = self._parseValue(value, read = True)
823  self.Append(settings, group, key, subkey, value)
824  idx += 2
825  except ValueError, e:
826  print >> sys.stderr, _("Error: Reading settings from file <%(file)s> failed.\n"
827  "\t\tDetails: %(detail)s\n"
828  "\t\tLine: '%(line)s'\n") % { 'file' : filename,
829  'detail' : e,
830  'line' : line }
831  fd.close()
832 
833  fd.close()
834 
835  def SaveToFile(self, settings = None):
836  """!Save settings to the file"""
837  if settings is None:
838  settings = self.userSettings
839 
840  dirPath = GetSettingsPath()
841  if not os.path.exists(dirPath):
842  try:
843  os.mkdir(dirPath)
844  except:
845  GError(_('Unable to create settings directory'))
846  return
847 
848  try:
849  file = open(self.filePath, "w")
850  for group in settings.keys():
851  for key in settings[group].keys():
852  subkeys = settings[group][key].keys()
853  file.write('%s%s%s%s' % (group, self.sep, key, self.sep))
854  for idx in range(len(subkeys)):
855  value = settings[group][key][subkeys[idx]]
856  if type(value) == types.DictType:
857  if idx > 0:
858  file.write('%s%s%s%s%s' % (os.linesep, group, self.sep, key, self.sep))
859  file.write('%s%s' % (subkeys[idx], self.sep))
860  kvalues = settings[group][key][subkeys[idx]].keys()
861  srange = range(len(kvalues))
862  for sidx in srange:
863  svalue = self._parseValue(settings[group][key][subkeys[idx]][kvalues[sidx]])
864  file.write('%s%s%s' % (kvalues[sidx], self.sep,
865  svalue))
866  if sidx < len(kvalues) - 1:
867  file.write('%s' % self.sep)
868  else:
869  if idx > 0 and \
870  type(settings[group][key][subkeys[idx - 1]]) == types.DictType:
871  file.write('%s%s%s%s%s' % (os.linesep, group, self.sep, key, self.sep))
872  value = self._parseValue(settings[group][key][subkeys[idx]])
873  file.write('%s%s%s' % (subkeys[idx], self.sep, value))
874  if idx < len(subkeys) - 1 and \
875  type(settings[group][key][subkeys[idx + 1]]) != types.DictType:
876  file.write('%s' % self.sep)
877  file.write(os.linesep)
878  except IOError, e:
879  raise GException(e)
880  except StandardError, e:
881  raise GException(_('Writing settings to file <%(file)s> failed.'
882  '\n\nDetails: %(detail)s') % { 'file' : self.filePath,
883  'detail' : e })
884 
885  file.close()
886 
887  def _parseValue(self, value, read = False):
888  """!Parse value to be store in settings file"""
889  if read: # -> read settings (cast values)
890  if value == 'True':
891  value = True
892  elif value == 'False':
893  value = False
894  elif value == 'None':
895  value = None
896  elif ':' in value: # -> color
897  try:
898  value = tuple(map(int, value.split(':')))
899  except ValueError: # -> string
900  pass
901  else:
902  try:
903  value = int(value)
904  except ValueError:
905  try:
906  value = float(value)
907  except ValueError:
908  pass
909  else: # -> write settings
910  if type(value) == type(()): # -> color
911  value = str(value[0]) + ':' +\
912  str(value[1]) + ':' + \
913  str(value[2])
914 
915  return value
916 
917  def Get(self, group, key = None, subkey = None, internal = False):
918  """!Get value by key/subkey
919 
920  Raise KeyError if key is not found
921 
922  @param group settings group
923  @param key (value, None)
924  @param subkey (value, list or None)
925  @param internal use internal settings instead
926 
927  @return value
928  """
929  if internal is True:
930  settings = self.internalSettings
931  else:
932  settings = self.userSettings
933 
934  try:
935  if subkey is None:
936  if key is None:
937  return settings[group]
938  else:
939  return settings[group][key]
940  else:
941  if type(subkey) == type(tuple()) or \
942  type(subkey) == type(list()):
943  return settings[group][key][subkey[0]][subkey[1]]
944  else:
945  return settings[group][key][subkey]
946 
947  except KeyError:
948  print >> sys.stderr, "Settings: unable to get value '%s:%s:%s'\n" % \
949  (group, key, subkey)
950 
951  def Set(self, group, value, key = None, subkey = None, internal = False):
952  """!Set value of key/subkey
953 
954  Raise KeyError if group/key is not found
955 
956  @param group settings group
957  @param key key (value, None)
958  @param subkey subkey (value, list or None)
959  @param value value
960  @param internal use internal settings instead
961  """
962  if internal is True:
963  settings = self.internalSettings
964  else:
965  settings = self.userSettings
966 
967  try:
968  if subkey is None:
969  if key is None:
970  settings[group] = value
971  else:
972  settings[group][key] = value
973  else:
974  if type(subkey) == type(tuple()) or \
975  type(subkey) == type(list()):
976  settings[group][key][subkey[0]][subkey[1]] = value
977  else:
978  settings[group][key][subkey] = value
979  except KeyError:
980  raise GException("%s '%s:%s:%s'" % (_("Unable to set "), group, key, subkey))
981 
982  def Append(self, dict, group, key, subkey, value):
983  """!Set value of key/subkey
984 
985  Create group/key/subkey if not exists
986 
987  @param dict settings dictionary to use
988  @param group settings group
989  @param key key
990  @param subkey subkey (value or list)
991  @param value value
992  """
993  if group not in dict:
994  dict[group] = {}
995 
996  if key not in dict[group]:
997  dict[group][key] = {}
998 
999  if type(subkey) == types.ListType:
1000  # TODO: len(subkey) > 2
1001  if subkey[0] not in dict[group][key]:
1002  dict[group][key][subkey[0]] = {}
1003  try:
1004  dict[group][key][subkey[0]][subkey[1]] = value
1005  except TypeError:
1006  print >> sys.stderr, _("Unable to parse settings '%s'") % value + \
1007  ' (' + group + ':' + key + ':' + subkey[0] + ':' + subkey[1] + ')'
1008  else:
1009  try:
1010  dict[group][key][subkey] = value
1011  except TypeError:
1012  print >> sys.stderr, _("Unable to parse settings '%s'") % value + \
1013  ' (' + group + ':' + key + ':' + subkey + ')'
1014 
1016  """!Get default user settings"""
1017  return self.defaultSettings
1018 
1019  def Reset(self, key = None):
1020  """!Reset to default settings
1021 
1022  @key key in settings dict (None for all keys)
1023  """
1024  if not key:
1025  self.userSettings = copy.deepcopy(self.defaultSettings)
1026  else:
1027  self.userSettings[key] = copy.deepcopy(self.defaultSettings[key])
1028 
1029 UserSettings = Settings()
def Set
Set value of key/subkey.
Definition: settings.py:951
def ReadSettingsFile
Reads settings file (mapset, location, gisdbase)
Definition: settings.py:769
def Get
Get value by key/subkey.
Definition: settings.py:917
wxGUI command interface
def GetSettingsPath
Get full path to the settings directory.
Definition: core/utils.py:807
def Append
Set value of key/subkey.
Definition: settings.py:982
def _parseValue
Parse value to be store in settings file.
Definition: settings.py:887
def Reset
Reset to default settings.
Definition: settings.py:1019
def _internalSettings
Define internal settings (based on user settings)
Definition: settings.py:684
def _readFile
Read settings from file to dict.
Definition: settings.py:784
Generic class where to store settings.
Definition: settings.py:32
Misc utilities for wxGUI.
def GetDefaultSettings
Get default user settings.
Definition: settings.py:1015
def PathJoin
Check path created by os.path.join.
Definition: core/utils.py:551
def _defaultSettings
Define default settings.
Definition: settings.py:71
def SaveToFile
Save settings to the file.
Definition: settings.py:835
tuple range
Definition: tools.py:1406
def _generateLocale
Generate locales.
Definition: settings.py:54